diff --git a/Data/modules/automated-evocations/packs/macros/000467.log b/Data/modules/automated-evocations/packs/macros/000471.log similarity index 100% rename from Data/modules/automated-evocations/packs/macros/000467.log rename to Data/modules/automated-evocations/packs/macros/000471.log diff --git a/Data/modules/automated-evocations/packs/macros/CURRENT b/Data/modules/automated-evocations/packs/macros/CURRENT index 98d8b496..65eef602 100644 --- a/Data/modules/automated-evocations/packs/macros/CURRENT +++ b/Data/modules/automated-evocations/packs/macros/CURRENT @@ -1 +1 @@ -MANIFEST-000466 +MANIFEST-000470 diff --git a/Data/modules/automated-evocations/packs/macros/LOG b/Data/modules/automated-evocations/packs/macros/LOG index c2aaab40..4429a5d7 100644 --- a/Data/modules/automated-evocations/packs/macros/LOG +++ b/Data/modules/automated-evocations/packs/macros/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:11.017296 ffff87fff0a0 Recovering log #464 -2023/10/20-07:55:11.021890 ffff87fff0a0 Delete type=0 #464 -2023/10/20-07:55:11.021910 ffff87fff0a0 Delete type=3 #462 +2023/10/23-05:12:18.627717 ffff877ef0a0 Recovering log #468 +2023/10/23-05:12:18.636023 ffff877ef0a0 Delete type=0 #468 +2023/10/23-05:12:18.636044 ffff877ef0a0 Delete type=3 #466 diff --git a/Data/modules/automated-evocations/packs/macros/LOG.old b/Data/modules/automated-evocations/packs/macros/LOG.old index 4b7c56ea..21c4dec3 100644 --- a/Data/modules/automated-evocations/packs/macros/LOG.old +++ b/Data/modules/automated-evocations/packs/macros/LOG.old @@ -1,8 +1,8 @@ -2023/10/20-07:41:11.883918 ffff867cf0a0 Recovering log #460 -2023/10/20-07:41:11.888949 ffff867cf0a0 Delete type=3 #458 -2023/10/20-07:41:11.888971 ffff867cf0a0 Delete type=0 #460 -2023/10/20-07:49:07.625833 ffff85fbf0a0 Level-0 table #465: started -2023/10/20-07:49:07.625858 ffff85fbf0a0 Level-0 table #465: 0 bytes OK -2023/10/20-07:49:07.627689 ffff85fbf0a0 Delete type=0 #463 -2023/10/20-07:49:07.631365 ffff85fbf0a0 Manual compaction at level-0 from '!macros!DFIqi3kVXrYZ8S7y' @ 72057594037927935 : 1 .. '!macros!z5CFHKH4XzXITTGU' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.633130 ffff85fbf0a0 Manual compaction at level-1 from '!macros!DFIqi3kVXrYZ8S7y' @ 72057594037927935 : 1 .. '!macros!z5CFHKH4XzXITTGU' @ 0 : 0; will stop at (end) +2023/10/20-07:55:11.017296 ffff87fff0a0 Recovering log #464 +2023/10/20-07:55:11.021890 ffff87fff0a0 Delete type=0 #464 +2023/10/20-07:55:11.021910 ffff87fff0a0 Delete type=3 #462 +2023/10/23-05:11:51.655803 ffff85fbf0a0 Level-0 table #469: started +2023/10/23-05:11:51.655819 ffff85fbf0a0 Level-0 table #469: 0 bytes OK +2023/10/23-05:11:51.657559 ffff85fbf0a0 Delete type=0 #467 +2023/10/23-05:11:51.659781 ffff85fbf0a0 Manual compaction at level-0 from '!macros!DFIqi3kVXrYZ8S7y' @ 72057594037927935 : 1 .. '!macros!z5CFHKH4XzXITTGU' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.663827 ffff85fbf0a0 Manual compaction at level-1 from '!macros!DFIqi3kVXrYZ8S7y' @ 72057594037927935 : 1 .. '!macros!z5CFHKH4XzXITTGU' @ 0 : 0; will stop at (end) diff --git a/Data/modules/automated-evocations/packs/macros/MANIFEST-000466 b/Data/modules/automated-evocations/packs/macros/MANIFEST-000470 similarity index 65% rename from Data/modules/automated-evocations/packs/macros/MANIFEST-000466 rename to Data/modules/automated-evocations/packs/macros/MANIFEST-000470 index 08b7b6ed..1820adef 100644 Binary files a/Data/modules/automated-evocations/packs/macros/MANIFEST-000466 and b/Data/modules/automated-evocations/packs/macros/MANIFEST-000470 differ diff --git a/Data/modules/bossbar/packs/macros/000023.log b/Data/modules/bossbar/packs/macros/000027.log similarity index 100% rename from Data/modules/bossbar/packs/macros/000023.log rename to Data/modules/bossbar/packs/macros/000027.log diff --git a/Data/modules/bossbar/packs/macros/CURRENT b/Data/modules/bossbar/packs/macros/CURRENT index 5af92b2b..8b152150 100644 --- a/Data/modules/bossbar/packs/macros/CURRENT +++ b/Data/modules/bossbar/packs/macros/CURRENT @@ -1 +1 @@ -MANIFEST-000022 +MANIFEST-000026 diff --git a/Data/modules/bossbar/packs/macros/LOG b/Data/modules/bossbar/packs/macros/LOG index 35d408f9..5a52530a 100644 --- a/Data/modules/bossbar/packs/macros/LOG +++ b/Data/modules/bossbar/packs/macros/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:11.023015 ffff86fdf0a0 Recovering log #20 -2023/10/20-07:55:11.027896 ffff86fdf0a0 Delete type=0 #20 -2023/10/20-07:55:11.027916 ffff86fdf0a0 Delete type=3 #18 +2023/10/23-05:12:18.637198 ffff87fff0a0 Recovering log #24 +2023/10/23-05:12:18.642198 ffff87fff0a0 Delete type=3 #22 +2023/10/23-05:12:18.642221 ffff87fff0a0 Delete type=0 #24 diff --git a/Data/modules/bossbar/packs/macros/LOG.old b/Data/modules/bossbar/packs/macros/LOG.old index 4371b56a..8f8b4709 100644 --- a/Data/modules/bossbar/packs/macros/LOG.old +++ b/Data/modules/bossbar/packs/macros/LOG.old @@ -1,8 +1,8 @@ -2023/10/20-07:41:11.890071 ffff87fff0a0 Recovering log #16 -2023/10/20-07:41:11.895193 ffff87fff0a0 Delete type=3 #14 -2023/10/20-07:41:11.895215 ffff87fff0a0 Delete type=0 #16 -2023/10/20-07:49:07.627724 ffff85fbf0a0 Level-0 table #21: started -2023/10/20-07:49:07.627738 ffff85fbf0a0 Level-0 table #21: 0 bytes OK -2023/10/20-07:49:07.629410 ffff85fbf0a0 Delete type=0 #19 -2023/10/20-07:49:07.631378 ffff85fbf0a0 Manual compaction at level-0 from '!macros!LD5Wc6K0vLQw0att' @ 72057594037927935 : 1 .. '!macros!iWwnlmoMWqNGJ54U' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.633245 ffff85fbf0a0 Manual compaction at level-1 from '!macros!LD5Wc6K0vLQw0att' @ 72057594037927935 : 1 .. '!macros!iWwnlmoMWqNGJ54U' @ 0 : 0; will stop at (end) +2023/10/20-07:55:11.023015 ffff86fdf0a0 Recovering log #20 +2023/10/20-07:55:11.027896 ffff86fdf0a0 Delete type=0 #20 +2023/10/20-07:55:11.027916 ffff86fdf0a0 Delete type=3 #18 +2023/10/23-05:11:51.657720 ffff85fbf0a0 Level-0 table #25: started +2023/10/23-05:11:51.657744 ffff85fbf0a0 Level-0 table #25: 0 bytes OK +2023/10/23-05:11:51.659570 ffff85fbf0a0 Delete type=0 #23 +2023/10/23-05:11:51.661826 ffff85fbf0a0 Manual compaction at level-0 from '!macros!LD5Wc6K0vLQw0att' @ 72057594037927935 : 1 .. '!macros!iWwnlmoMWqNGJ54U' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.663971 ffff85fbf0a0 Manual compaction at level-1 from '!macros!LD5Wc6K0vLQw0att' @ 72057594037927935 : 1 .. '!macros!iWwnlmoMWqNGJ54U' @ 0 : 0; will stop at (end) diff --git a/Data/modules/bossbar/packs/macros/MANIFEST-000022 b/Data/modules/bossbar/packs/macros/MANIFEST-000026 similarity index 52% rename from Data/modules/bossbar/packs/macros/MANIFEST-000022 rename to Data/modules/bossbar/packs/macros/MANIFEST-000026 index fdfd7f67..2603c9a7 100644 Binary files a/Data/modules/bossbar/packs/macros/MANIFEST-000022 and b/Data/modules/bossbar/packs/macros/MANIFEST-000026 differ diff --git a/Data/modules/levels/packs/levels-samples/000965.log b/Data/modules/levels/packs/levels-samples/000969.log similarity index 100% rename from Data/modules/levels/packs/levels-samples/000965.log rename to Data/modules/levels/packs/levels-samples/000969.log diff --git a/Data/modules/levels/packs/levels-samples/CURRENT b/Data/modules/levels/packs/levels-samples/CURRENT index 6169e016..0a8f1fe1 100644 --- a/Data/modules/levels/packs/levels-samples/CURRENT +++ b/Data/modules/levels/packs/levels-samples/CURRENT @@ -1 +1 @@ -MANIFEST-000964 +MANIFEST-000968 diff --git a/Data/modules/levels/packs/levels-samples/LOG b/Data/modules/levels/packs/levels-samples/LOG index cf37fe01..645255a4 100644 --- a/Data/modules/levels/packs/levels-samples/LOG +++ b/Data/modules/levels/packs/levels-samples/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:11.035627 ffff86fdf0a0 Recovering log #962 -2023/10/20-07:55:11.040517 ffff86fdf0a0 Delete type=3 #960 -2023/10/20-07:55:11.040539 ffff86fdf0a0 Delete type=0 #962 +2023/10/23-05:12:18.649746 ffff87fff0a0 Recovering log #966 +2023/10/23-05:12:18.655169 ffff87fff0a0 Delete type=0 #966 +2023/10/23-05:12:18.655188 ffff87fff0a0 Delete type=3 #964 diff --git a/Data/modules/levels/packs/levels-samples/LOG.old b/Data/modules/levels/packs/levels-samples/LOG.old index 2ca416e8..9b5cf9c4 100644 --- a/Data/modules/levels/packs/levels-samples/LOG.old +++ b/Data/modules/levels/packs/levels-samples/LOG.old @@ -1,8 +1,8 @@ -2023/10/20-07:41:11.902849 ffff87fff0a0 Recovering log #958 -2023/10/20-07:41:11.907588 ffff87fff0a0 Delete type=0 #958 -2023/10/20-07:41:11.907607 ffff87fff0a0 Delete type=3 #956 -2023/10/20-07:49:07.631389 ffff85fbf0a0 Level-0 table #963: started -2023/10/20-07:49:07.631403 ffff85fbf0a0 Level-0 table #963: 0 bytes OK -2023/10/20-07:49:07.633079 ffff85fbf0a0 Delete type=0 #961 -2023/10/20-07:49:07.633332 ffff85fbf0a0 Manual compaction at level-0 from '!scenes!fT64AORvwMUdHzwr' @ 72057594037927935 : 1 .. '!scenes.walls!w5eztsez7EhiFrmE.zlashxFbpTyjyOHo' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.636870 ffff85fbf0a0 Manual compaction at level-1 from '!scenes!fT64AORvwMUdHzwr' @ 72057594037927935 : 1 .. '!scenes.walls!w5eztsez7EhiFrmE.zlashxFbpTyjyOHo' @ 0 : 0; will stop at (end) +2023/10/20-07:55:11.035627 ffff86fdf0a0 Recovering log #962 +2023/10/20-07:55:11.040517 ffff86fdf0a0 Delete type=3 #960 +2023/10/20-07:55:11.040539 ffff86fdf0a0 Delete type=0 #962 +2023/10/23-05:11:51.661839 ffff85fbf0a0 Level-0 table #967: started +2023/10/23-05:11:51.661852 ffff85fbf0a0 Level-0 table #967: 0 bytes OK +2023/10/23-05:11:51.663788 ffff85fbf0a0 Delete type=0 #965 +2023/10/23-05:11:51.664057 ffff85fbf0a0 Manual compaction at level-0 from '!scenes!fT64AORvwMUdHzwr' @ 72057594037927935 : 1 .. '!scenes.walls!w5eztsez7EhiFrmE.zlashxFbpTyjyOHo' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.668488 ffff85fbf0a0 Manual compaction at level-1 from '!scenes!fT64AORvwMUdHzwr' @ 72057594037927935 : 1 .. '!scenes.walls!w5eztsez7EhiFrmE.zlashxFbpTyjyOHo' @ 0 : 0; will stop at (end) diff --git a/Data/modules/levels/packs/levels-samples/MANIFEST-000964 b/Data/modules/levels/packs/levels-samples/MANIFEST-000968 similarity index 86% rename from Data/modules/levels/packs/levels-samples/MANIFEST-000964 rename to Data/modules/levels/packs/levels-samples/MANIFEST-000968 index 44b9d6bb..524e9c49 100644 Binary files a/Data/modules/levels/packs/levels-samples/MANIFEST-000964 and b/Data/modules/levels/packs/levels-samples/MANIFEST-000968 differ diff --git a/Data/modules/levels/packs/macros/000965.log b/Data/modules/levels/packs/macros/000969.log similarity index 100% rename from Data/modules/levels/packs/macros/000965.log rename to Data/modules/levels/packs/macros/000969.log diff --git a/Data/modules/levels/packs/macros/CURRENT b/Data/modules/levels/packs/macros/CURRENT index 6169e016..0a8f1fe1 100644 --- a/Data/modules/levels/packs/macros/CURRENT +++ b/Data/modules/levels/packs/macros/CURRENT @@ -1 +1 @@ -MANIFEST-000964 +MANIFEST-000968 diff --git a/Data/modules/levels/packs/macros/LOG b/Data/modules/levels/packs/macros/LOG index bbee4580..a2721805 100644 --- a/Data/modules/levels/packs/macros/LOG +++ b/Data/modules/levels/packs/macros/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:11.029068 ffff87fff0a0 Recovering log #962 -2023/10/20-07:55:11.034068 ffff87fff0a0 Delete type=3 #960 -2023/10/20-07:55:11.034090 ffff87fff0a0 Delete type=0 #962 +2023/10/23-05:12:18.643342 ffff877ef0a0 Recovering log #966 +2023/10/23-05:12:18.648199 ffff877ef0a0 Delete type=0 #966 +2023/10/23-05:12:18.648219 ffff877ef0a0 Delete type=3 #964 diff --git a/Data/modules/levels/packs/macros/LOG.old b/Data/modules/levels/packs/macros/LOG.old index 36f8e389..1badc184 100644 --- a/Data/modules/levels/packs/macros/LOG.old +++ b/Data/modules/levels/packs/macros/LOG.old @@ -1,8 +1,8 @@ -2023/10/20-07:41:11.896350 ffff867cf0a0 Recovering log #958 -2023/10/20-07:41:11.901305 ffff867cf0a0 Delete type=0 #958 -2023/10/20-07:41:11.901323 ffff867cf0a0 Delete type=3 #956 -2023/10/20-07:49:07.629563 ffff85fbf0a0 Level-0 table #963: started -2023/10/20-07:49:07.629584 ffff85fbf0a0 Level-0 table #963: 0 bytes OK -2023/10/20-07:49:07.631327 ffff85fbf0a0 Delete type=0 #961 -2023/10/20-07:49:07.633118 ffff85fbf0a0 Manual compaction at level-0 from '!macros!2LfY4Ky5rRDkK7h8' @ 72057594037927935 : 1 .. '!macros!yx7Eb76rfzjh0LEO' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.633348 ffff85fbf0a0 Manual compaction at level-1 from '!macros!2LfY4Ky5rRDkK7h8' @ 72057594037927935 : 1 .. '!macros!yx7Eb76rfzjh0LEO' @ 0 : 0; will stop at (end) +2023/10/20-07:55:11.029068 ffff87fff0a0 Recovering log #962 +2023/10/20-07:55:11.034068 ffff87fff0a0 Delete type=3 #960 +2023/10/20-07:55:11.034090 ffff87fff0a0 Delete type=0 #962 +2023/10/23-05:11:51.659810 ffff85fbf0a0 Level-0 table #967: started +2023/10/23-05:11:51.659829 ffff85fbf0a0 Level-0 table #967: 0 bytes OK +2023/10/23-05:11:51.661788 ffff85fbf0a0 Delete type=0 #965 +2023/10/23-05:11:51.663952 ffff85fbf0a0 Manual compaction at level-0 from '!macros!2LfY4Ky5rRDkK7h8' @ 72057594037927935 : 1 .. '!macros!yx7Eb76rfzjh0LEO' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.666374 ffff85fbf0a0 Manual compaction at level-1 from '!macros!2LfY4Ky5rRDkK7h8' @ 72057594037927935 : 1 .. '!macros!yx7Eb76rfzjh0LEO' @ 0 : 0; will stop at (end) diff --git a/Data/modules/levels/packs/macros/MANIFEST-000964 b/Data/modules/levels/packs/macros/MANIFEST-000968 similarity index 52% rename from Data/modules/levels/packs/macros/MANIFEST-000964 rename to Data/modules/levels/packs/macros/MANIFEST-000968 index 3c29af27..e76c076a 100644 Binary files a/Data/modules/levels/packs/macros/MANIFEST-000964 and b/Data/modules/levels/packs/macros/MANIFEST-000968 differ diff --git a/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/000210.log b/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/000214.log similarity index 100% rename from Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/000210.log rename to Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/000214.log diff --git a/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/CURRENT b/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/CURRENT index 52262f04..51af8957 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/CURRENT +++ b/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/CURRENT @@ -1 +1 @@ -MANIFEST-000209 +MANIFEST-000213 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/LOG b/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/LOG index 76278066..48828e96 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/LOG +++ b/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:11.058378 ffff877ef0a0 Recovering log #207 -2023/10/20-07:55:11.063161 ffff877ef0a0 Delete type=3 #205 -2023/10/20-07:55:11.063184 ffff877ef0a0 Delete type=0 #207 +2023/10/23-05:12:18.677757 ffff86fdf0a0 Recovering log #211 +2023/10/23-05:12:18.683119 ffff86fdf0a0 Delete type=0 #211 +2023/10/23-05:12:18.683139 ffff86fdf0a0 Delete type=3 #209 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/LOG.old b/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/LOG.old index f8a8976a..3de6cdcb 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/LOG.old +++ b/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/LOG.old @@ -1,7 +1,7 @@ -2023/10/20-07:41:11.926296 ffff877ef0a0 Recovering log #203 -2023/10/20-07:41:11.931494 ffff877ef0a0 Delete type=3 #201 -2023/10/20-07:41:11.931538 ffff877ef0a0 Delete type=0 #203 -2023/10/20-07:49:07.636980 ffff85fbf0a0 Level-0 table #208: started -2023/10/20-07:49:07.637000 ffff85fbf0a0 Level-0 table #208: 0 bytes OK -2023/10/20-07:49:07.638905 ffff85fbf0a0 Delete type=0 #206 -2023/10/20-07:49:07.640897 ffff85fbf0a0 Manual compaction at level-0 from '!items!0WtqP7Wei3AxHh5M' @ 72057594037927935 : 1 .. '!items!zSlsnbvsGKdCTzL1' @ 0 : 0; will stop at (end) +2023/10/20-07:55:11.058378 ffff877ef0a0 Recovering log #207 +2023/10/20-07:55:11.063161 ffff877ef0a0 Delete type=3 #205 +2023/10/20-07:55:11.063184 ffff877ef0a0 Delete type=0 #207 +2023/10/23-05:11:51.668688 ffff85fbf0a0 Level-0 table #212: started +2023/10/23-05:11:51.668707 ffff85fbf0a0 Level-0 table #212: 0 bytes OK +2023/10/23-05:11:51.670818 ffff85fbf0a0 Delete type=0 #210 +2023/10/23-05:11:51.674988 ffff85fbf0a0 Manual compaction at level-0 from '!items!0WtqP7Wei3AxHh5M' @ 72057594037927935 : 1 .. '!items!zSlsnbvsGKdCTzL1' @ 0 : 0; will stop at (end) diff --git a/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/MANIFEST-000209 b/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/MANIFEST-000213 similarity index 81% rename from Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/MANIFEST-000209 rename to Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/MANIFEST-000213 index a1da5bb6..3c19d66e 100644 Binary files a/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/MANIFEST-000209 and b/Data/modules/pf2e-animal-companions/packs/ac-advanced-maneuvers/MANIFEST-000213 differ diff --git a/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/000212.log b/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/000216.log similarity index 100% rename from Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/000212.log rename to Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/000216.log diff --git a/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/CURRENT b/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/CURRENT index 12fd2820..68076bd4 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/CURRENT +++ b/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/CURRENT @@ -1 +1 @@ -MANIFEST-000211 +MANIFEST-000215 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/LOG b/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/LOG index 3c30d393..5bb22ad5 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/LOG +++ b/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:11.044977 ffff877ef0a0 Recovering log #209 -2023/10/20-07:55:11.049730 ffff877ef0a0 Delete type=3 #207 -2023/10/20-07:55:11.049753 ffff877ef0a0 Delete type=0 #209 +2023/10/23-05:12:18.659451 ffff86fdf0a0 Recovering log #213 +2023/10/23-05:12:18.664573 ffff86fdf0a0 Delete type=0 #213 +2023/10/23-05:12:18.664592 ffff86fdf0a0 Delete type=3 #211 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/LOG.old b/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/LOG.old index a20d2546..9448c909 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/LOG.old +++ b/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/LOG.old @@ -1,7 +1,7 @@ -2023/10/20-07:41:11.911901 ffff877ef0a0 Recovering log #205 -2023/10/20-07:41:11.917093 ffff877ef0a0 Delete type=3 #203 -2023/10/20-07:41:11.917115 ffff877ef0a0 Delete type=0 #205 -2023/10/20-07:49:07.633430 ffff85fbf0a0 Level-0 table #210: started -2023/10/20-07:49:07.633449 ffff85fbf0a0 Level-0 table #210: 0 bytes OK -2023/10/20-07:49:07.635180 ffff85fbf0a0 Delete type=0 #208 -2023/10/20-07:49:07.638943 ffff85fbf0a0 Manual compaction at level-0 from '!items!0BVoHy7R86KJoani' @ 72057594037927935 : 1 .. '!items!yukG72FSivsrqVoG' @ 0 : 0; will stop at (end) +2023/10/20-07:55:11.044977 ffff877ef0a0 Recovering log #209 +2023/10/20-07:55:11.049730 ffff877ef0a0 Delete type=3 #207 +2023/10/20-07:55:11.049753 ffff877ef0a0 Delete type=0 #209 +2023/10/23-05:11:51.664073 ffff85fbf0a0 Level-0 table #214: started +2023/10/23-05:11:51.664088 ffff85fbf0a0 Level-0 table #214: 0 bytes OK +2023/10/23-05:11:51.666336 ffff85fbf0a0 Delete type=0 #212 +2023/10/23-05:11:51.668601 ffff85fbf0a0 Manual compaction at level-0 from '!items!0BVoHy7R86KJoani' @ 72057594037927935 : 1 .. '!items!yukG72FSivsrqVoG' @ 0 : 0; will stop at (end) diff --git a/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/MANIFEST-000211 b/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/MANIFEST-000215 similarity index 81% rename from Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/MANIFEST-000211 rename to Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/MANIFEST-000215 index aafc0fa3..d80692d4 100644 Binary files a/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/MANIFEST-000211 and b/Data/modules/pf2e-animal-companions/packs/ac-ancestries-and-class/MANIFEST-000215 differ diff --git a/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/000207.log b/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/000211.log similarity index 100% rename from Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/000207.log rename to Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/000211.log diff --git a/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/CURRENT b/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/CURRENT index b04a015d..af31d429 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/CURRENT +++ b/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/CURRENT @@ -1 +1 @@ -MANIFEST-000206 +MANIFEST-000210 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/LOG b/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/LOG index 53f990d8..e89b3b34 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/LOG +++ b/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:11.097635 ffff867cf0a0 Recovering log #204 -2023/10/20-07:55:11.102669 ffff867cf0a0 Delete type=0 #204 -2023/10/20-07:55:11.102689 ffff867cf0a0 Delete type=3 #202 +2023/10/23-05:12:18.712482 ffff867cf0a0 Recovering log #208 +2023/10/23-05:12:18.717589 ffff867cf0a0 Delete type=3 #206 +2023/10/23-05:12:18.717613 ffff867cf0a0 Delete type=0 #208 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/LOG.old b/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/LOG.old index 436c4dad..97509209 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/LOG.old +++ b/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/LOG.old @@ -1,7 +1,7 @@ -2023/10/20-07:41:11.963847 ffff86fdf0a0 Recovering log #200 -2023/10/20-07:41:11.969701 ffff86fdf0a0 Delete type=3 #198 -2023/10/20-07:41:11.969725 ffff86fdf0a0 Delete type=0 #200 -2023/10/20-07:49:07.646695 ffff85fbf0a0 Level-0 table #205: started -2023/10/20-07:49:07.646712 ffff85fbf0a0 Level-0 table #205: 0 bytes OK -2023/10/20-07:49:07.648413 ffff85fbf0a0 Delete type=0 #203 -2023/10/20-07:49:07.652079 ffff85fbf0a0 Manual compaction at level-0 from '!items!1mE83uSucJZS4FB9' @ 72057594037927935 : 1 .. '!items!zo6B3JGQIt99K1HF' @ 0 : 0; will stop at (end) +2023/10/20-07:55:11.097635 ffff867cf0a0 Recovering log #204 +2023/10/20-07:55:11.102669 ffff867cf0a0 Delete type=0 #204 +2023/10/20-07:55:11.102689 ffff867cf0a0 Delete type=3 #202 +2023/10/23-05:11:51.679758 ffff85fbf0a0 Level-0 table #209: started +2023/10/23-05:11:51.679779 ffff85fbf0a0 Level-0 table #209: 0 bytes OK +2023/10/23-05:11:51.681727 ffff85fbf0a0 Delete type=0 #207 +2023/10/23-05:11:51.685639 ffff85fbf0a0 Manual compaction at level-0 from '!items!1mE83uSucJZS4FB9' @ 72057594037927935 : 1 .. '!items!zo6B3JGQIt99K1HF' @ 0 : 0; will stop at (end) diff --git a/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/MANIFEST-000206 b/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/MANIFEST-000210 similarity index 82% rename from Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/MANIFEST-000206 rename to Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/MANIFEST-000210 index dc23ec31..db1889df 100644 Binary files a/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/MANIFEST-000206 and b/Data/modules/pf2e-animal-companions/packs/ac-construct-breakthroughs/MANIFEST-000210 differ diff --git a/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/000207.log b/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/000211.log similarity index 100% rename from Data/modules/pf2e-animal-companions/packs/ac-construct-companions/000207.log rename to Data/modules/pf2e-animal-companions/packs/ac-construct-companions/000211.log diff --git a/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/CURRENT b/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/CURRENT index b04a015d..af31d429 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/CURRENT +++ b/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/CURRENT @@ -1 +1 @@ -MANIFEST-000206 +MANIFEST-000210 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/LOG b/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/LOG index 15a4e82a..65d7d230 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/LOG +++ b/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:11.085765 ffff877ef0a0 Recovering log #204 -2023/10/20-07:55:11.090514 ffff877ef0a0 Delete type=0 #204 -2023/10/20-07:55:11.090534 ffff877ef0a0 Delete type=3 #202 +2023/10/23-05:12:18.705730 ffff86fdf0a0 Recovering log #208 +2023/10/23-05:12:18.710937 ffff86fdf0a0 Delete type=3 #206 +2023/10/23-05:12:18.710959 ffff86fdf0a0 Delete type=0 #208 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/LOG.old b/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/LOG.old index 0333d598..bcc2ad14 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/LOG.old +++ b/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/LOG.old @@ -1,7 +1,7 @@ -2023/10/20-07:41:11.956676 ffff877ef0a0 Recovering log #200 -2023/10/20-07:41:11.962262 ffff877ef0a0 Delete type=3 #198 -2023/10/20-07:41:11.962284 ffff877ef0a0 Delete type=0 #200 -2023/10/20-07:49:07.644615 ffff85fbf0a0 Level-0 table #205: started -2023/10/20-07:49:07.644636 ffff85fbf0a0 Level-0 table #205: 0 bytes OK -2023/10/20-07:49:07.646463 ffff85fbf0a0 Delete type=0 #203 -2023/10/20-07:49:07.648451 ffff85fbf0a0 Manual compaction at level-0 from '!items!5v2Kj6Jh2YYGaSQq' @ 72057594037927935 : 1 .. '!items!mjDtydpNNfI9SuFq' @ 0 : 0; will stop at (end) +2023/10/20-07:55:11.085765 ffff877ef0a0 Recovering log #204 +2023/10/20-07:55:11.090514 ffff877ef0a0 Delete type=0 #204 +2023/10/20-07:55:11.090534 ffff877ef0a0 Delete type=3 #202 +2023/10/23-05:11:51.677476 ffff85fbf0a0 Level-0 table #209: started +2023/10/23-05:11:51.677494 ffff85fbf0a0 Level-0 table #209: 0 bytes OK +2023/10/23-05:11:51.679602 ffff85fbf0a0 Delete type=0 #207 +2023/10/23-05:11:51.683581 ffff85fbf0a0 Manual compaction at level-0 from '!items!5v2Kj6Jh2YYGaSQq' @ 72057594037927935 : 1 .. '!items!mjDtydpNNfI9SuFq' @ 0 : 0; will stop at (end) diff --git a/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/MANIFEST-000206 b/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/MANIFEST-000210 similarity index 82% rename from Data/modules/pf2e-animal-companions/packs/ac-construct-companions/MANIFEST-000206 rename to Data/modules/pf2e-animal-companions/packs/ac-construct-companions/MANIFEST-000210 index b5edeb7d..baca917a 100644 Binary files a/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/MANIFEST-000206 and b/Data/modules/pf2e-animal-companions/packs/ac-construct-companions/MANIFEST-000210 differ diff --git a/Data/modules/pf2e-animal-companions/packs/ac-eidolons/000209.log b/Data/modules/pf2e-animal-companions/packs/ac-eidolons/000213.log similarity index 100% rename from Data/modules/pf2e-animal-companions/packs/ac-eidolons/000209.log rename to Data/modules/pf2e-animal-companions/packs/ac-eidolons/000213.log diff --git a/Data/modules/pf2e-animal-companions/packs/ac-eidolons/CURRENT b/Data/modules/pf2e-animal-companions/packs/ac-eidolons/CURRENT index 704e06e0..7d5a51c6 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-eidolons/CURRENT +++ b/Data/modules/pf2e-animal-companions/packs/ac-eidolons/CURRENT @@ -1 +1 @@ -MANIFEST-000208 +MANIFEST-000212 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-eidolons/LOG b/Data/modules/pf2e-animal-companions/packs/ac-eidolons/LOG index a4763629..d30f1129 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-eidolons/LOG +++ b/Data/modules/pf2e-animal-companions/packs/ac-eidolons/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:11.104393 ffff877ef0a0 Recovering log #206 -2023/10/20-07:55:11.109460 ffff877ef0a0 Delete type=3 #204 -2023/10/20-07:55:11.109483 ffff877ef0a0 Delete type=0 #206 +2023/10/23-05:12:18.719203 ffff86fdf0a0 Recovering log #210 +2023/10/23-05:12:18.724705 ffff86fdf0a0 Delete type=3 #208 +2023/10/23-05:12:18.724728 ffff86fdf0a0 Delete type=0 #210 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-eidolons/LOG.old b/Data/modules/pf2e-animal-companions/packs/ac-eidolons/LOG.old index 43163d16..c355ff6a 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-eidolons/LOG.old +++ b/Data/modules/pf2e-animal-companions/packs/ac-eidolons/LOG.old @@ -1,7 +1,7 @@ -2023/10/20-07:41:11.971282 ffff877ef0a0 Recovering log #202 -2023/10/20-07:41:11.976940 ffff877ef0a0 Delete type=0 #202 -2023/10/20-07:41:11.976960 ffff877ef0a0 Delete type=3 #200 -2023/10/20-07:49:07.648574 ffff85fbf0a0 Level-0 table #207: started -2023/10/20-07:49:07.648595 ffff85fbf0a0 Level-0 table #207: 0 bytes OK -2023/10/20-07:49:07.650256 ffff85fbf0a0 Delete type=0 #205 -2023/10/20-07:49:07.658873 ffff85fbf0a0 Manual compaction at level-0 from '!items!1YJoaMhZPvLGvj1J' @ 72057594037927935 : 1 .. '!items!zjIVbS6nGX6BS2UD' @ 0 : 0; will stop at (end) +2023/10/20-07:55:11.104393 ffff877ef0a0 Recovering log #206 +2023/10/20-07:55:11.109460 ffff877ef0a0 Delete type=3 #204 +2023/10/20-07:55:11.109483 ffff877ef0a0 Delete type=0 #206 +2023/10/23-05:11:51.681764 ffff85fbf0a0 Level-0 table #211: started +2023/10/23-05:11:51.681781 ffff85fbf0a0 Level-0 table #211: 0 bytes OK +2023/10/23-05:11:51.683542 ffff85fbf0a0 Delete type=0 #209 +2023/10/23-05:11:51.685759 ffff85fbf0a0 Manual compaction at level-0 from '!items!1YJoaMhZPvLGvj1J' @ 72057594037927935 : 1 .. '!items!zjIVbS6nGX6BS2UD' @ 0 : 0; will stop at (end) diff --git a/Data/modules/pf2e-animal-companions/packs/ac-eidolons/MANIFEST-000208 b/Data/modules/pf2e-animal-companions/packs/ac-eidolons/MANIFEST-000212 similarity index 81% rename from Data/modules/pf2e-animal-companions/packs/ac-eidolons/MANIFEST-000208 rename to Data/modules/pf2e-animal-companions/packs/ac-eidolons/MANIFEST-000212 index 2608cb04..27cc6567 100644 Binary files a/Data/modules/pf2e-animal-companions/packs/ac-eidolons/MANIFEST-000208 and b/Data/modules/pf2e-animal-companions/packs/ac-eidolons/MANIFEST-000212 differ diff --git a/Data/modules/pf2e-animal-companions/packs/ac-features/000212.log b/Data/modules/pf2e-animal-companions/packs/ac-equipment/000212.log similarity index 100% rename from Data/modules/pf2e-animal-companions/packs/ac-features/000212.log rename to Data/modules/pf2e-animal-companions/packs/ac-equipment/000212.log diff --git a/Data/modules/pf2e-animal-companions/packs/ac-equipment/CURRENT b/Data/modules/pf2e-animal-companions/packs/ac-equipment/CURRENT index c692fd19..12fd2820 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-equipment/CURRENT +++ b/Data/modules/pf2e-animal-companions/packs/ac-equipment/CURRENT @@ -1 +1 @@ -MANIFEST-000207 +MANIFEST-000211 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-equipment/LOG b/Data/modules/pf2e-animal-companions/packs/ac-equipment/LOG index 5566b318..c07f8845 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-equipment/LOG +++ b/Data/modules/pf2e-animal-companions/packs/ac-equipment/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:11.064982 ffff867cf0a0 Recovering log #205 -2023/10/20-07:55:11.069869 ffff867cf0a0 Delete type=3 #203 -2023/10/20-07:55:11.069892 ffff867cf0a0 Delete type=0 #205 +2023/10/23-05:12:18.684964 ffff867cf0a0 Recovering log #209 +2023/10/23-05:12:18.690072 ffff867cf0a0 Delete type=3 #207 +2023/10/23-05:12:18.690096 ffff867cf0a0 Delete type=0 #209 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-equipment/LOG.old b/Data/modules/pf2e-animal-companions/packs/ac-equipment/LOG.old index 8ae633c2..504de7a1 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-equipment/LOG.old +++ b/Data/modules/pf2e-animal-companions/packs/ac-equipment/LOG.old @@ -1,7 +1,7 @@ -2023/10/20-07:41:11.933334 ffff86fdf0a0 Recovering log #201 -2023/10/20-07:41:11.938665 ffff86fdf0a0 Delete type=0 #201 -2023/10/20-07:41:11.938683 ffff86fdf0a0 Delete type=3 #199 -2023/10/20-07:49:07.639138 ffff85fbf0a0 Level-0 table #206: started -2023/10/20-07:49:07.639155 ffff85fbf0a0 Level-0 table #206: 0 bytes OK -2023/10/20-07:49:07.640859 ffff85fbf0a0 Delete type=0 #204 -2023/10/20-07:49:07.644506 ffff85fbf0a0 Manual compaction at level-0 from '!items!2SeEnERJqaECplam' @ 72057594037927935 : 1 .. '!items!suEEtFqaGpPG2OHt' @ 0 : 0; will stop at (end) +2023/10/20-07:55:11.064982 ffff867cf0a0 Recovering log #205 +2023/10/20-07:55:11.069869 ffff867cf0a0 Delete type=3 #203 +2023/10/20-07:55:11.069892 ffff867cf0a0 Delete type=0 #205 +2023/10/23-05:11:51.670977 ffff85fbf0a0 Level-0 table #210: started +2023/10/23-05:11:51.670998 ffff85fbf0a0 Level-0 table #210: 0 bytes OK +2023/10/23-05:11:51.672983 ffff85fbf0a0 Delete type=0 #208 +2023/10/23-05:11:51.677276 ffff85fbf0a0 Manual compaction at level-0 from '!items!2SeEnERJqaECplam' @ 72057594037927935 : 1 .. '!items!suEEtFqaGpPG2OHt' @ 0 : 0; will stop at (end) diff --git a/Data/modules/pf2e-animal-companions/packs/ac-equipment/MANIFEST-000207 b/Data/modules/pf2e-animal-companions/packs/ac-equipment/MANIFEST-000211 similarity index 82% rename from Data/modules/pf2e-animal-companions/packs/ac-equipment/MANIFEST-000207 rename to Data/modules/pf2e-animal-companions/packs/ac-equipment/MANIFEST-000211 index ecb98516..08282a59 100644 Binary files a/Data/modules/pf2e-animal-companions/packs/ac-equipment/MANIFEST-000207 and b/Data/modules/pf2e-animal-companions/packs/ac-equipment/MANIFEST-000211 differ diff --git a/Data/modules/pf2e-animal-companions/packs/ac-equipment/000208.log b/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/000211.log similarity index 100% rename from Data/modules/pf2e-animal-companions/packs/ac-equipment/000208.log rename to Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/000211.log diff --git a/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/CURRENT b/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/CURRENT index b04a015d..af31d429 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/CURRENT +++ b/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/CURRENT @@ -1 +1 @@ -MANIFEST-000206 +MANIFEST-000210 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/LOG b/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/LOG index 287d7532..c7bae8d4 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/LOG +++ b/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:11.111542 ffff867cf0a0 Recovering log #204 -2023/10/20-07:55:11.116717 ffff867cf0a0 Delete type=0 #204 -2023/10/20-07:55:11.116738 ffff867cf0a0 Delete type=3 #202 +2023/10/23-05:12:18.726338 ffff867cf0a0 Recovering log #208 +2023/10/23-05:12:18.731969 ffff867cf0a0 Delete type=3 #206 +2023/10/23-05:12:18.731992 ffff867cf0a0 Delete type=0 #208 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/LOG.old b/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/LOG.old index 5781267a..f230d2c7 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/LOG.old +++ b/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/LOG.old @@ -1,7 +1,7 @@ -2023/10/20-07:41:11.978556 ffff86fdf0a0 Recovering log #200 -2023/10/20-07:41:11.983776 ffff86fdf0a0 Delete type=3 #198 -2023/10/20-07:41:11.983800 ffff86fdf0a0 Delete type=0 #200 -2023/10/20-07:49:07.650292 ffff85fbf0a0 Level-0 table #205: started -2023/10/20-07:49:07.650305 ffff85fbf0a0 Level-0 table #205: 0 bytes OK -2023/10/20-07:49:07.652041 ffff85fbf0a0 Delete type=0 #203 -2023/10/20-07:49:07.658887 ffff85fbf0a0 Manual compaction at level-0 from '!items!00eOhkScQi1K5GZk' @ 72057594037927935 : 1 .. '!items!yCSsQaTFINIbr9Gh' @ 0 : 0; will stop at (end) +2023/10/20-07:55:11.111542 ffff867cf0a0 Recovering log #204 +2023/10/20-07:55:11.116717 ffff867cf0a0 Delete type=0 #204 +2023/10/20-07:55:11.116738 ffff867cf0a0 Delete type=3 #202 +2023/10/23-05:11:51.683698 ffff85fbf0a0 Level-0 table #209: started +2023/10/23-05:11:51.683719 ffff85fbf0a0 Level-0 table #209: 0 bytes OK +2023/10/23-05:11:51.685601 ffff85fbf0a0 Delete type=0 #207 +2023/10/23-05:11:51.692996 ffff85fbf0a0 Manual compaction at level-0 from '!items!00eOhkScQi1K5GZk' @ 72057594037927935 : 1 .. '!items!yCSsQaTFINIbr9Gh' @ 0 : 0; will stop at (end) diff --git a/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/MANIFEST-000206 b/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/MANIFEST-000210 similarity index 81% rename from Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/MANIFEST-000206 rename to Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/MANIFEST-000210 index 91f3e59d..a853ad15 100644 Binary files a/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/MANIFEST-000206 and b/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/MANIFEST-000210 differ diff --git a/Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/000207.log b/Data/modules/pf2e-animal-companions/packs/ac-feats/000213.log similarity index 100% rename from Data/modules/pf2e-animal-companions/packs/ac-evolution-feats/000207.log rename to Data/modules/pf2e-animal-companions/packs/ac-feats/000213.log diff --git a/Data/modules/pf2e-animal-companions/packs/ac-feats/CURRENT b/Data/modules/pf2e-animal-companions/packs/ac-feats/CURRENT index 704e06e0..7d5a51c6 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-feats/CURRENT +++ b/Data/modules/pf2e-animal-companions/packs/ac-feats/CURRENT @@ -1 +1 @@ -MANIFEST-000208 +MANIFEST-000212 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-feats/LOG b/Data/modules/pf2e-animal-companions/packs/ac-feats/LOG index a99a3219..2efd5d27 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-feats/LOG +++ b/Data/modules/pf2e-animal-companions/packs/ac-feats/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:11.051785 ffff867cf0a0 Recovering log #206 -2023/10/20-07:55:11.056653 ffff867cf0a0 Delete type=3 #204 -2023/10/20-07:55:11.056675 ffff867cf0a0 Delete type=0 #206 +2023/10/23-05:12:18.670958 ffff867cf0a0 Recovering log #210 +2023/10/23-05:12:18.676015 ffff867cf0a0 Delete type=3 #208 +2023/10/23-05:12:18.676040 ffff867cf0a0 Delete type=0 #210 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-feats/LOG.old b/Data/modules/pf2e-animal-companions/packs/ac-feats/LOG.old index cfd2867f..dbcd34cb 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-feats/LOG.old +++ b/Data/modules/pf2e-animal-companions/packs/ac-feats/LOG.old @@ -1,7 +1,7 @@ -2023/10/20-07:41:11.919110 ffff86fdf0a0 Recovering log #202 -2023/10/20-07:41:11.924598 ffff86fdf0a0 Delete type=0 #202 -2023/10/20-07:41:11.924618 ffff86fdf0a0 Delete type=3 #200 -2023/10/20-07:49:07.635217 ffff85fbf0a0 Level-0 table #207: started -2023/10/20-07:49:07.635231 ffff85fbf0a0 Level-0 table #207: 0 bytes OK -2023/10/20-07:49:07.636833 ffff85fbf0a0 Delete type=0 #205 -2023/10/20-07:49:07.639052 ffff85fbf0a0 Manual compaction at level-0 from '!items!4gNZCu2ncgu98A0H' @ 72057594037927935 : 1 .. '!items!wZXL6VgEK88BCF0C' @ 0 : 0; will stop at (end) +2023/10/20-07:55:11.051785 ffff867cf0a0 Recovering log #206 +2023/10/20-07:55:11.056653 ffff867cf0a0 Delete type=3 #204 +2023/10/20-07:55:11.056675 ffff867cf0a0 Delete type=0 #206 +2023/10/23-05:11:51.666493 ffff85fbf0a0 Level-0 table #211: started +2023/10/23-05:11:51.666513 ffff85fbf0a0 Level-0 table #211: 0 bytes OK +2023/10/23-05:11:51.668449 ffff85fbf0a0 Delete type=0 #209 +2023/10/23-05:11:51.670857 ffff85fbf0a0 Manual compaction at level-0 from '!items!4gNZCu2ncgu98A0H' @ 72057594037927935 : 1 .. '!items!wZXL6VgEK88BCF0C' @ 0 : 0; will stop at (end) diff --git a/Data/modules/pf2e-animal-companions/packs/ac-feats/MANIFEST-000208 b/Data/modules/pf2e-animal-companions/packs/ac-feats/MANIFEST-000212 similarity index 81% rename from Data/modules/pf2e-animal-companions/packs/ac-feats/MANIFEST-000208 rename to Data/modules/pf2e-animal-companions/packs/ac-feats/MANIFEST-000212 index e87e8256..8e90eca8 100644 Binary files a/Data/modules/pf2e-animal-companions/packs/ac-feats/MANIFEST-000208 and b/Data/modules/pf2e-animal-companions/packs/ac-feats/MANIFEST-000212 differ diff --git a/Data/modules/pf2e-animal-companions/packs/ac-feats/000209.log b/Data/modules/pf2e-animal-companions/packs/ac-features/000216.log similarity index 100% rename from Data/modules/pf2e-animal-companions/packs/ac-feats/000209.log rename to Data/modules/pf2e-animal-companions/packs/ac-features/000216.log diff --git a/Data/modules/pf2e-animal-companions/packs/ac-features/CURRENT b/Data/modules/pf2e-animal-companions/packs/ac-features/CURRENT index 12fd2820..68076bd4 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-features/CURRENT +++ b/Data/modules/pf2e-animal-companions/packs/ac-features/CURRENT @@ -1 +1 @@ -MANIFEST-000211 +MANIFEST-000215 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-features/LOG b/Data/modules/pf2e-animal-companions/packs/ac-features/LOG index 95e1bbd5..eb289904 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-features/LOG +++ b/Data/modules/pf2e-animal-companions/packs/ac-features/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:11.071381 ffff877ef0a0 Recovering log #209 -2023/10/20-07:55:11.076235 ffff877ef0a0 Delete type=3 #207 -2023/10/20-07:55:11.076257 ffff877ef0a0 Delete type=0 #209 +2023/10/23-05:12:18.691598 ffff86fdf0a0 Recovering log #213 +2023/10/23-05:12:18.696647 ffff86fdf0a0 Delete type=0 #213 +2023/10/23-05:12:18.696667 ffff86fdf0a0 Delete type=3 #211 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-features/LOG.old b/Data/modules/pf2e-animal-companions/packs/ac-features/LOG.old index 2793d475..53bada0a 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-features/LOG.old +++ b/Data/modules/pf2e-animal-companions/packs/ac-features/LOG.old @@ -1,7 +1,7 @@ -2023/10/20-07:41:11.940216 ffff877ef0a0 Recovering log #205 -2023/10/20-07:41:11.945224 ffff877ef0a0 Delete type=3 #203 -2023/10/20-07:41:11.945247 ffff877ef0a0 Delete type=0 #205 -2023/10/20-07:49:07.641018 ffff85fbf0a0 Level-0 table #210: started -2023/10/20-07:49:07.641042 ffff85fbf0a0 Level-0 table #210: 0 bytes OK -2023/10/20-07:49:07.642797 ffff85fbf0a0 Delete type=0 #208 -2023/10/20-07:49:07.646500 ffff85fbf0a0 Manual compaction at level-0 from '!items!0i2ZSrRpjKG0KV4U' @ 72057594037927935 : 1 .. '!items!zF6bLjVwj7Njkqan' @ 0 : 0; will stop at (end) +2023/10/20-07:55:11.071381 ffff877ef0a0 Recovering log #209 +2023/10/20-07:55:11.076235 ffff877ef0a0 Delete type=3 #207 +2023/10/20-07:55:11.076257 ffff877ef0a0 Delete type=0 #209 +2023/10/23-05:11:51.673019 ffff85fbf0a0 Level-0 table #214: started +2023/10/23-05:11:51.673035 ffff85fbf0a0 Level-0 table #214: 0 bytes OK +2023/10/23-05:11:51.674950 ffff85fbf0a0 Delete type=0 #212 +2023/10/23-05:11:51.677388 ffff85fbf0a0 Manual compaction at level-0 from '!items!0i2ZSrRpjKG0KV4U' @ 72057594037927935 : 1 .. '!items!zF6bLjVwj7Njkqan' @ 0 : 0; will stop at (end) diff --git a/Data/modules/pf2e-animal-companions/packs/ac-features/MANIFEST-000211 b/Data/modules/pf2e-animal-companions/packs/ac-features/MANIFEST-000215 similarity index 80% rename from Data/modules/pf2e-animal-companions/packs/ac-features/MANIFEST-000211 rename to Data/modules/pf2e-animal-companions/packs/ac-features/MANIFEST-000215 index cf2128bd..471d2067 100644 Binary files a/Data/modules/pf2e-animal-companions/packs/ac-features/MANIFEST-000211 and b/Data/modules/pf2e-animal-companions/packs/ac-features/MANIFEST-000215 differ diff --git a/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/000210.log b/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/000214.log similarity index 100% rename from Data/modules/pf2e-animal-companions/packs/ac-support-benefits/000210.log rename to Data/modules/pf2e-animal-companions/packs/ac-support-benefits/000214.log diff --git a/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/CURRENT b/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/CURRENT index 52262f04..51af8957 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/CURRENT +++ b/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/CURRENT @@ -1 +1 @@ -MANIFEST-000209 +MANIFEST-000213 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/LOG b/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/LOG index 8e866ac1..0a7d87c6 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/LOG +++ b/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:11.078354 ffff867cf0a0 Recovering log #207 -2023/10/20-07:55:11.083248 ffff867cf0a0 Delete type=3 #205 -2023/10/20-07:55:11.083270 ffff867cf0a0 Delete type=0 #207 +2023/10/23-05:12:18.698781 ffff867cf0a0 Recovering log #211 +2023/10/23-05:12:18.703939 ffff867cf0a0 Delete type=0 #211 +2023/10/23-05:12:18.703959 ffff867cf0a0 Delete type=3 #209 diff --git a/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/LOG.old b/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/LOG.old index dfdca09e..8dd87e97 100644 --- a/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/LOG.old +++ b/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/LOG.old @@ -1,7 +1,7 @@ -2023/10/20-07:41:11.947332 ffff86fdf0a0 Recovering log #203 -2023/10/20-07:41:11.952612 ffff86fdf0a0 Delete type=3 #201 -2023/10/20-07:41:11.952634 ffff86fdf0a0 Delete type=0 #203 -2023/10/20-07:49:07.642835 ffff85fbf0a0 Level-0 table #208: started -2023/10/20-07:49:07.642850 ffff85fbf0a0 Level-0 table #208: 0 bytes OK -2023/10/20-07:49:07.644469 ffff85fbf0a0 Delete type=0 #206 -2023/10/20-07:49:07.646612 ffff85fbf0a0 Manual compaction at level-0 from '!items!2Jaz98WiQMNnqKCD' @ 72057594037927935 : 1 .. '!items!zE01vpjowhoKygig' @ 0 : 0; will stop at (end) +2023/10/20-07:55:11.078354 ffff867cf0a0 Recovering log #207 +2023/10/20-07:55:11.083248 ffff867cf0a0 Delete type=3 #205 +2023/10/20-07:55:11.083270 ffff867cf0a0 Delete type=0 #207 +2023/10/23-05:11:51.675097 ffff85fbf0a0 Level-0 table #212: started +2023/10/23-05:11:51.675117 ffff85fbf0a0 Level-0 table #212: 0 bytes OK +2023/10/23-05:11:51.677238 ffff85fbf0a0 Delete type=0 #210 +2023/10/23-05:11:51.679641 ffff85fbf0a0 Manual compaction at level-0 from '!items!2Jaz98WiQMNnqKCD' @ 72057594037927935 : 1 .. '!items!zE01vpjowhoKygig' @ 0 : 0; will stop at (end) diff --git a/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/MANIFEST-000209 b/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/MANIFEST-000213 similarity index 81% rename from Data/modules/pf2e-animal-companions/packs/ac-support-benefits/MANIFEST-000209 rename to Data/modules/pf2e-animal-companions/packs/ac-support-benefits/MANIFEST-000213 index c759c188..8cc015e2 100644 Binary files a/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/MANIFEST-000209 and b/Data/modules/pf2e-animal-companions/packs/ac-support-benefits/MANIFEST-000213 differ diff --git a/Data/modules/wall-height/packs/macros/001037.log b/Data/modules/wall-height/packs/macros/001041.log similarity index 100% rename from Data/modules/wall-height/packs/macros/001037.log rename to Data/modules/wall-height/packs/macros/001041.log diff --git a/Data/modules/wall-height/packs/macros/CURRENT b/Data/modules/wall-height/packs/macros/CURRENT index 2a2a31fb..dd123db1 100644 --- a/Data/modules/wall-height/packs/macros/CURRENT +++ b/Data/modules/wall-height/packs/macros/CURRENT @@ -1 +1 @@ -MANIFEST-001036 +MANIFEST-001040 diff --git a/Data/modules/wall-height/packs/macros/LOG b/Data/modules/wall-height/packs/macros/LOG index d38be4b1..01f364ad 100644 --- a/Data/modules/wall-height/packs/macros/LOG +++ b/Data/modules/wall-height/packs/macros/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:11.118478 ffff877ef0a0 Recovering log #1034 -2023/10/20-07:55:11.123398 ffff877ef0a0 Delete type=3 #1032 -2023/10/20-07:55:11.123422 ffff877ef0a0 Delete type=0 #1034 +2023/10/23-05:12:18.733634 ffff86fdf0a0 Recovering log #1038 +2023/10/23-05:12:18.739053 ffff86fdf0a0 Delete type=0 #1038 +2023/10/23-05:12:18.739072 ffff86fdf0a0 Delete type=3 #1036 diff --git a/Data/modules/wall-height/packs/macros/LOG.old b/Data/modules/wall-height/packs/macros/LOG.old index 875d2e52..fd673a05 100644 --- a/Data/modules/wall-height/packs/macros/LOG.old +++ b/Data/modules/wall-height/packs/macros/LOG.old @@ -1,7 +1,7 @@ -2023/10/20-07:41:11.985428 ffff877ef0a0 Recovering log #1030 -2023/10/20-07:41:11.990474 ffff877ef0a0 Delete type=0 #1030 -2023/10/20-07:41:11.990494 ffff877ef0a0 Delete type=3 #1028 -2023/10/20-07:49:07.656961 ffff85fbf0a0 Level-0 table #1035: started -2023/10/20-07:49:07.656991 ffff85fbf0a0 Level-0 table #1035: 0 bytes OK -2023/10/20-07:49:07.658834 ffff85fbf0a0 Delete type=0 #1033 -2023/10/20-07:49:07.658898 ffff85fbf0a0 Manual compaction at level-0 from 'undefined' @ 72057594037927935 : 1 .. 'undefined' @ 0 : 0; will stop at (end) +2023/10/20-07:55:11.118478 ffff877ef0a0 Recovering log #1034 +2023/10/20-07:55:11.123398 ffff877ef0a0 Delete type=3 #1032 +2023/10/20-07:55:11.123422 ffff877ef0a0 Delete type=0 #1034 +2023/10/23-05:11:51.689038 ffff85fbf0a0 Level-0 table #1039: started +2023/10/23-05:11:51.689068 ffff85fbf0a0 Level-0 table #1039: 0 bytes OK +2023/10/23-05:11:51.692955 ffff85fbf0a0 Delete type=0 #1037 +2023/10/23-05:11:51.700309 ffff85fbf0a0 Manual compaction at level-0 from 'undefined' @ 72057594037927935 : 1 .. 'undefined' @ 0 : 0; will stop at (end) diff --git a/Data/modules/wall-height/packs/macros/MANIFEST-001036 b/Data/modules/wall-height/packs/macros/MANIFEST-001036 deleted file mode 100644 index ff88774e..00000000 Binary files a/Data/modules/wall-height/packs/macros/MANIFEST-001036 and /dev/null differ diff --git a/Data/modules/wall-height/packs/macros/MANIFEST-001040 b/Data/modules/wall-height/packs/macros/MANIFEST-001040 new file mode 100644 index 00000000..9fe15206 Binary files /dev/null and b/Data/modules/wall-height/packs/macros/MANIFEST-001040 differ diff --git a/Data/systems/pf2e/CHANGELOG.md b/Data/systems/pf2e/CHANGELOG.md index 07657a67..e465ec7e 100644 --- a/Data/systems/pf2e/CHANGELOG.md +++ b/Data/systems/pf2e/CHANGELOG.md @@ -1,3 +1,43 @@ +## 5.7.3 + +### System Improvements + +- (stwlam) Add round-end expiry option for effects +- (stwlam) Add search input on spell preparation dialog +- (stwlam) Include `@target` as resolvable in strike, spell, and blast damage rolls + +### Bugfixes + +- (Cerapter) Fix ancestry featgroup not being able to filter for homebrew ancestries +- (Cerapter) Include custom IWR definitions in weaknesses and immunities +- (stwlam) Prevent error from being thrown in some circumstances when damage dice doubling is enabled +- (stwlam) Fix issue causing some oracular curse effects to not automatically adjust condition values +- (stwlam) Fix issue causing thief rogues to roll unarmed strike damage with no attribute modifier +- (Supe) Prevent party-actor data preparation failure when familiar data preparation fails + +### Data Updates + +- (Cora) Make minor Kingmaker data entry tweaks and fixes +- (CrackJackFlood) Add inert effects for Rage of Elements stances +- (CrackJackFlood) Brush up effects for scouting +- (Dire Weasel) Add automation for NPC Expanded Splash and update bomb Strikes +- (Dire Weasel) Add custom resistance for Maliadi's Collar of Fire +- (Dire Weasel) Add effect for Vitrifying Blast and Warding Statuette +- (Dire Weasel) Add infused alchemical items to Blue Viper's (Level 20) inventory, infused trait to several NPC items +- (Dire Weasel) Add otherTags to Rune Patron and Way of the Spellshot +- (Dire Weasel) Brush up automation for some skeleton bestiary abilities and Vewslog's Deadeye +- (Dire Weasel) Refresh copies of NPC bomb strikes +- (Jesse) Add size increase for heightened Righteous Might spell effect +- (jfn4th) Fix rarely occuring aberrant rendering of actions on PC sheet +- (stwlam) Add alternate crit spec effect to Lavasoul feat's Magma Spike +- (stwlam) Expire Devise a Stratagem effect at end of current round +- (stwlam) Improve automation of Fearsome Brute feat +- (Tikael) Add missing spells to FotRP actor +- (Tikael) Automate Kineticist critical junctions +- (Tikael) Automate Buckler Expertise feat +- (Tikael) Fix DC of inline save in Mountain Quake +- (TiloBuechsenschuss) Fix strike names for Vegetable Lamb and spell variants for Falling Stars + ## 5.7.2 ### System Improvements diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/acid-flask.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/acid-flask.webp index 88ddf8ec..7b677fa7 100644 --- a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/acid-flask.webp +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/acid-flask.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:280b30af6ab01130c0e3f88b6703c6d2ba0ba35a190d4deba9da2aff90fb9be5 -size 1066 +oid sha256:0f1164e0aacce79fb802869edcaf08b3ec915685266dc6c654b8b4836caaf1c3 +size 2152 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/bottled-lightning.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/bottled-lightning.webp index 5783adfc..49af6db7 100644 --- a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/bottled-lightning.webp +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/bottled-lightning.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f3e78372ed083cccf2ca51950e44f2238d5ff43783e46409c33517ba9fb56120 -size 834 +oid sha256:35c6254594d9aafc582aeb995a65e779dde9b4a633e0dfdade29f56cc790953d +size 2408 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/bottled-sunlight.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/bottled-sunlight.webp index 89bd4ebf..03e6b878 100644 --- a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/bottled-sunlight.webp +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/bottled-sunlight.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b7b0473b973e24f0d99dfa2f7d03a195b679f408d1d2d13e9533fb7bc3185ab2 -size 1862 +oid sha256:8d05d25ebea68493e2537f0b405b8a419a00c101c31d7426d3bde30b7a394a7e +size 1984 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/dread-ampoule.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/dread-ampoule.webp index c4e5173f..37b6bd16 100644 --- a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/dread-ampoule.webp +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-bombs/dread-ampoule.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f36a2da917bf9925acc4718cc2c4681c9c1e943d3d0fd082beef9955f4cdbbd7 -size 884 +oid sha256:caeb948ae624487508a663f96d456815abd9c17357bf3f70e1dba0c9a5ef7503 +size 1518 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-elixirs/bombers-eye-elixir.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-elixirs/bombers-eye-elixir.webp index 00949778..5cd2290a 100644 --- a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-elixirs/bombers-eye-elixir.webp +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-elixirs/bombers-eye-elixir.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b728e63929cedc2956aaafc15ca661ceb420cf356001ad2c371b4e731e74ad31 -size 928 +oid sha256:75b1b2d5bd783a0afe716b9a3865075f2947d3285696ad4645ec35092e7c8510 +size 1736 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-elixirs/drakeheart-mutagen.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-elixirs/drakeheart-mutagen.webp index b84da8b2..1e1d90eb 100644 --- a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-elixirs/drakeheart-mutagen.webp +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-elixirs/drakeheart-mutagen.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d4c36a5b79cd2914d14f04298cb268192d7c6d0a217300be791429317f03c337 -size 842 +oid sha256:1394f261116e2702c8de0efd261e691d4756583b350ee59e016aef90214b49da +size 2128 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-elixirs/egg-cream-fizz.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-elixirs/egg-cream-fizz.webp new file mode 100644 index 00000000..7104e73a --- /dev/null +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-elixirs/egg-cream-fizz.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:153c51e55a8ee6ea7f07d6334ffce8125c0e84cb069b46e9cb394ea8f518224b +size 2004 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-elixirs/prey-mutagen.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-elixirs/prey-mutagen.webp new file mode 100644 index 00000000..38175625 --- /dev/null +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-elixirs/prey-mutagen.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:508c23f97deec986867559b0e4a5957cde367ef82de19adb631902cf3f4b09a3 +size 1574 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-poisons/mustard-powder.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-poisons/mustard-powder.webp new file mode 100644 index 00000000..f2497c61 --- /dev/null +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-poisons/mustard-powder.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30c4a2437c7a982031b59d0d5576a06f01d0c7a123bab69d4aae37170939a6a7 +size 1976 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-poisons/slumber-wine.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-poisons/slumber-wine.webp index f0f2817c..ca4afc86 100644 --- a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-poisons/slumber-wine.webp +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-poisons/slumber-wine.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1119ea91dc2bc6fc9a9e42f425c9ced8367803f560dfad35ed366e16b8e1eced -size 544 +oid sha256:3177d5f62961e6c9c0fe0c78f29161cc174a821c03502c2d068250ca494a92b5 +size 1998 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/blue.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/blue.webp new file mode 100644 index 00000000..75ee7dd6 --- /dev/null +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/blue.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3747fe4e6d7878b6b98d80620571f905a678f0c4069fd0c4e8523a6b87bbcd88 +size 1776 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/green.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/green.webp new file mode 100644 index 00000000..f7dd89d6 --- /dev/null +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/green.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8e0e062fd660647c773ac030d4b5977214d4623cd47b28e9248b0811389a5775 +size 1788 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/indigo.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/indigo.webp new file mode 100644 index 00000000..70d6d52f --- /dev/null +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/indigo.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d3f7c4988d360ea9157df6855481ebe39f83e0630a382d34a3127738a73cbb2b +size 1698 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/orange.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/orange.webp new file mode 100644 index 00000000..5a7550f4 --- /dev/null +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/orange.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9107758e034f2f9b58775770360c0eff7ae8c6dc32262df87a960a7f6620dff9 +size 1776 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/red.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/red.webp new file mode 100644 index 00000000..c2fa3d2f --- /dev/null +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/red.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7219ee2220d3aba3176645c0312aa75d4c06e7053f64f20737d3eb7c252423b9 +size 1682 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/violet.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/violet.webp new file mode 100644 index 00000000..a7440534 --- /dev/null +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/violet.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f51b1c064fa4f0aa2a5e90d657e56e602b7467c546dd48143e8915b0ac41f349 +size 1758 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/yellow.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/yellow.webp new file mode 100644 index 00000000..b37a07e8 --- /dev/null +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/colorful-coating/yellow.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2eec1682dd2c200e359da4466e07c2814ab35b7d081df3295c572ef7a08c3c8 +size 1810 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/ghost-ampoule.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/ghost-ampoule.webp new file mode 100644 index 00000000..92c2a5dd --- /dev/null +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/alchemical-tools/ghost-ampoule.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b5283b7c0753300d6f9c84d9e204e3d04a40102fba56e4f9ae488fec80d9a53 +size 1786 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/food/auric-noodles.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/food/auric-noodles.webp new file mode 100644 index 00000000..b0b51ad8 --- /dev/null +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/food/auric-noodles.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dde5c1b7102fa4799e3ff3b8af70a2822fe9fa958e0597c8294041f1e58ea22a +size 2292 diff --git a/Data/systems/pf2e/icons/equipment/alchemical-items/food/moon-radish-soup.webp b/Data/systems/pf2e/icons/equipment/alchemical-items/food/moon-radish-soup.webp new file mode 100644 index 00000000..8acd7993 --- /dev/null +++ b/Data/systems/pf2e/icons/equipment/alchemical-items/food/moon-radish-soup.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:41bbad102c3375e359d755a4ac8f115d5931927860a635ebac9a2945306c7ca9 +size 2162 diff --git a/Data/systems/pf2e/icons/equipment/armor/chainmail.webp b/Data/systems/pf2e/icons/equipment/armor/chainmail.webp index ef805fd8..c2937042 100644 --- a/Data/systems/pf2e/icons/equipment/armor/chainmail.webp +++ b/Data/systems/pf2e/icons/equipment/armor/chainmail.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:bc1168ea33cccf933beaa70da057ba9a033ff5c640d8337d07fb2a3bcb354bef -size 1194 +oid sha256:1ea34b04b94835993adbf67c0e5191a8b2cafa504cb9bf7bde5db2e75ae6cbf3 +size 2428 diff --git a/Data/systems/pf2e/icons/equipment/armor/chainshirt.webp b/Data/systems/pf2e/icons/equipment/armor/chainshirt.webp index e132463c..1a1b2ef4 100644 --- a/Data/systems/pf2e/icons/equipment/armor/chainshirt.webp +++ b/Data/systems/pf2e/icons/equipment/armor/chainshirt.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:90ed3d69f0af71818b5db4b23b045122ce651e0756c8a9619a963f279be1bd49 -size 1230 +oid sha256:73b7b48fd51421c49b343f9c1b8f2af5a54f6c8c7ad71345f5d29e234e53f30a +size 2232 diff --git a/Data/systems/pf2e/icons/equipment/weapons/double-barreled-pistol.webp b/Data/systems/pf2e/icons/equipment/weapons/double-barreled-pistol.webp index 5641752b..2b242111 100644 --- a/Data/systems/pf2e/icons/equipment/weapons/double-barreled-pistol.webp +++ b/Data/systems/pf2e/icons/equipment/weapons/double-barreled-pistol.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6562589754fc547771ba2f6460bb261a747f692e9931213c7a77db721324db8a -size 13784 +oid sha256:b1872718b8a773a023b2a4e848d3228b78585460c541287d2ce23eecf38325a0 +size 1874 diff --git a/Data/systems/pf2e/icons/equipment/weapons/forked-bipod.webp b/Data/systems/pf2e/icons/equipment/weapons/forked-bipod.webp index ca409cd3..06f1264e 100644 --- a/Data/systems/pf2e/icons/equipment/weapons/forked-bipod.webp +++ b/Data/systems/pf2e/icons/equipment/weapons/forked-bipod.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:264eac8373dd60715aed188ae2e4d7a41c54104dc300aad4587489c360aa815c -size 10538 +oid sha256:f8f59a60e4fe82092ee1b4e0b23b0f233e184695698493f277b736bff4162caf +size 1056 diff --git a/Data/systems/pf2e/icons/equipment/weapons/mithral-tree.webp b/Data/systems/pf2e/icons/equipment/weapons/mithral-tree.webp index 5e0923da..c05e7494 100644 --- a/Data/systems/pf2e/icons/equipment/weapons/mithral-tree.webp +++ b/Data/systems/pf2e/icons/equipment/weapons/mithral-tree.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:79e4d1bf085e11b0751bb9ba486f91287807d6647a751ae2a3523339ba7adc9b -size 13606 +oid sha256:c08a937282b697208282c32e8e4a46ab30e0f4e27da5f417ac9e6748c9bef00c +size 1724 diff --git a/Data/systems/pf2e/icons/equipment/weapons/pepperbox.webp b/Data/systems/pf2e/icons/equipment/weapons/pepperbox.webp index 808da47a..cd8d082f 100644 --- a/Data/systems/pf2e/icons/equipment/weapons/pepperbox.webp +++ b/Data/systems/pf2e/icons/equipment/weapons/pepperbox.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a66a990591fa859fbdd0ed95307187fdf6cbe427af17c55c41e2991a07bf66f4 -size 13664 +oid sha256:61609dd3784e8dac4ffcc44b022e97c7fc6a951e9b415d62d6ed6271a92953ff +size 1686 diff --git a/Data/systems/pf2e/icons/equipment/weapons/shears.webp b/Data/systems/pf2e/icons/equipment/weapons/shears.webp index ff2a9965..b5ece688 100644 --- a/Data/systems/pf2e/icons/equipment/weapons/shears.webp +++ b/Data/systems/pf2e/icons/equipment/weapons/shears.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:5d60d49adf5980646305344cbf9c9e7e77762e00860ffd66b653c415c25a0da7 -size 834 +oid sha256:fe2eed166d12f97aa9d5e906582308e190f8176cae5c152e92b5445345bb695c +size 1692 diff --git a/Data/systems/pf2e/icons/equipment/weapons/slide-pistol.webp b/Data/systems/pf2e/icons/equipment/weapons/slide-pistol.webp index 62ea4c7b..a52c4759 100644 --- a/Data/systems/pf2e/icons/equipment/weapons/slide-pistol.webp +++ b/Data/systems/pf2e/icons/equipment/weapons/slide-pistol.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9adbbb364fb5dc71e41c749b1322cc182c92d383bc4e60f996d45dcf90227b4d -size 14454 +oid sha256:242b25fdc9cff49761f1f5a1a8c8fdfba8ebcc0024b2c8f74a834ecd20342f96 +size 2086 diff --git a/Data/systems/pf2e/icons/spells/bountiful-oasis.webp b/Data/systems/pf2e/icons/spells/bountiful-oasis.webp new file mode 100644 index 00000000..d6f4a44e --- /dev/null +++ b/Data/systems/pf2e/icons/spells/bountiful-oasis.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:add6a1c0a4308365a6e3406648d2022de5b12a9a03543b222c323f80f5f8e635 +size 1520 diff --git a/Data/systems/pf2e/icons/spells/burrow-ward.webp b/Data/systems/pf2e/icons/spells/burrow-ward.webp new file mode 100644 index 00000000..eb9b2e3b --- /dev/null +++ b/Data/systems/pf2e/icons/spells/burrow-ward.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:493b4ae6d9bb9e4fada0da3e9a5e3440fcfac208354700e2d42ce8f9f44dc38a +size 2290 diff --git a/Data/systems/pf2e/icons/spells/cloud-dragons-cloak.webp b/Data/systems/pf2e/icons/spells/cloud-dragons-cloak.webp new file mode 100644 index 00000000..5d45eaca --- /dev/null +++ b/Data/systems/pf2e/icons/spells/cloud-dragons-cloak.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edb478b0892698bdcd2f0cacbb7605fbbde72a4729828d27420710bb26d1dafa +size 1662 diff --git a/Data/systems/pf2e/icons/spells/coral-scourge.webp b/Data/systems/pf2e/icons/spells/coral-scourge.webp new file mode 100644 index 00000000..64823b27 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/coral-scourge.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3df1bff7ddfaa3e3e91e6306f26b316c98b7344d54fb4948b322f077df6f7ab +size 2224 diff --git a/Data/systems/pf2e/icons/spells/deep-breath.webp b/Data/systems/pf2e/icons/spells/deep-breath.webp new file mode 100644 index 00000000..bf4ef7f4 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/deep-breath.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3fc172ec7d584e926ac49b96f4030ec54bb79f7e9ab3f50240982678bced0fb1 +size 2464 diff --git a/Data/systems/pf2e/icons/spells/dive-and-breach.webp b/Data/systems/pf2e/icons/spells/dive-and-breach.webp new file mode 100644 index 00000000..9f8d09a1 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/dive-and-breach.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ce13e7a33aa8bd7330982640419d4d48995e13729f4e3d268808f7c198ad35db +size 2230 diff --git a/Data/systems/pf2e/icons/spells/draw-moisture.webp b/Data/systems/pf2e/icons/spells/draw-moisture.webp new file mode 100644 index 00000000..9fd9acc0 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/draw-moisture.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88dc2a0be019795244d7ca34e5a466c3041e7cd9ed1d8beca35832e8dd7bced8 +size 2310 diff --git a/Data/systems/pf2e/icons/spells/eat-fire.webp b/Data/systems/pf2e/icons/spells/eat-fire.webp new file mode 100644 index 00000000..1ddda8d2 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/eat-fire.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5885c182a9166f278911b0da2a940d45467bdbbe0b3b2f8e49a8aef0ff2d1f3a +size 1718 diff --git a/Data/systems/pf2e/icons/spells/elemental-breath.webp b/Data/systems/pf2e/icons/spells/elemental-breath.webp new file mode 100644 index 00000000..3498729b --- /dev/null +++ b/Data/systems/pf2e/icons/spells/elemental-breath.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb70a2def576972eb4689134303a9199f6b6c06d53c4d56b998140379125ba9f +size 1814 diff --git a/Data/systems/pf2e/icons/spells/elemental-counter.webp b/Data/systems/pf2e/icons/spells/elemental-counter.webp new file mode 100644 index 00000000..147dcb67 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/elemental-counter.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:46aa9a7c925a3b5aa079eb42e306f7084a9092bb3146f7dade8ddbeaab7b7934 +size 1500 diff --git a/Data/systems/pf2e/icons/spells/elemental-servitor.webp b/Data/systems/pf2e/icons/spells/elemental-servitor.webp new file mode 100644 index 00000000..c48c53ed --- /dev/null +++ b/Data/systems/pf2e/icons/spells/elemental-servitor.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e5745c58be4b607be86ea3e2d4cc525122ff25aa5f56c44c9d5c9d398f8c836 +size 2220 diff --git a/Data/systems/pf2e/icons/spells/exploding-earth.webp b/Data/systems/pf2e/icons/spells/exploding-earth.webp new file mode 100644 index 00000000..83c396ca --- /dev/null +++ b/Data/systems/pf2e/icons/spells/exploding-earth.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9fb4f05d79272640c3988e26558fa088e72640efd922b59d489575459e5a32f2 +size 1276 diff --git a/Data/systems/pf2e/icons/spells/falsify-heat.webp b/Data/systems/pf2e/icons/spells/falsify-heat.webp new file mode 100644 index 00000000..02c4e095 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/falsify-heat.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d9ad121c1f6731b0b0d3b755a0c1985e4840381980f583415e4c2e8f111cd1c +size 2628 diff --git a/Data/systems/pf2e/icons/spells/field-of-razors.webp b/Data/systems/pf2e/icons/spells/field-of-razors.webp new file mode 100644 index 00000000..5f5ea1fd --- /dev/null +++ b/Data/systems/pf2e/icons/spells/field-of-razors.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6bdd288294d2ccbbabb35c0f6d0d723364901ce4e792666a9e08208199e9c365 +size 2268 diff --git a/Data/systems/pf2e/icons/spells/fireproof.webp b/Data/systems/pf2e/icons/spells/fireproof.webp new file mode 100644 index 00000000..4ce39ea9 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/fireproof.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:37228c60ef794799ed407e9e8f2563855f49d1b397a3223c41e08a4b8e02e588 +size 1676 diff --git a/Data/systems/pf2e/icons/spells/fires-pathway.webp b/Data/systems/pf2e/icons/spells/fires-pathway.webp new file mode 100644 index 00000000..ce0600c9 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/fires-pathway.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a344c6a29494723c15cf4f828211bef57d48cfc2c65660a3d8b211dd386d6416 +size 1494 diff --git a/Data/systems/pf2e/icons/spells/flames-of-ego.webp b/Data/systems/pf2e/icons/spells/flames-of-ego.webp new file mode 100644 index 00000000..82c07901 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/flames-of-ego.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f0dfeee50bcd284630f1c2da099f9d0bf23034e3b41981349e8d7f8957976fe +size 2070 diff --git a/Data/systems/pf2e/icons/spells/fold-metal.webp b/Data/systems/pf2e/icons/spells/fold-metal.webp new file mode 100644 index 00000000..6356c816 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/fold-metal.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f114f7e512c232297f059e83101159d21778d6d37c91a16c4b88bbace40e77a8 +size 1126 diff --git a/Data/systems/pf2e/icons/spells/freezing-rain.webp b/Data/systems/pf2e/icons/spells/freezing-rain.webp new file mode 100644 index 00000000..4da2300c --- /dev/null +++ b/Data/systems/pf2e/icons/spells/freezing-rain.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d795d37a1ac951f7506368d9ddf401a30cff0a23a5bec3393459c8c3e609b982 +size 1762 diff --git a/Data/systems/pf2e/icons/spells/frost-pillar.webp b/Data/systems/pf2e/icons/spells/frost-pillar.webp new file mode 100644 index 00000000..b9116c3b --- /dev/null +++ b/Data/systems/pf2e/icons/spells/frost-pillar.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69143cc96481e560c603b3a4d489726cd144c0b3ff4430eeb4a519012785f356 +size 1576 diff --git a/Data/systems/pf2e/icons/spells/glass-form.webp b/Data/systems/pf2e/icons/spells/glass-form.webp new file mode 100644 index 00000000..f30026b1 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/glass-form.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e9395f52deac0607550be93eeb31ad97680f97529a5740301f42081f656caf61 +size 1322 diff --git a/Data/systems/pf2e/icons/spells/grasp-of-the-deep.webp b/Data/systems/pf2e/icons/spells/grasp-of-the-deep.webp new file mode 100644 index 00000000..004cad5b --- /dev/null +++ b/Data/systems/pf2e/icons/spells/grasp-of-the-deep.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6729e8a1bb22e4bbd37dd127247b7eb05195f548855fabeee6fc3d5a6d047b41 +size 1718 diff --git a/Data/systems/pf2e/icons/spells/grasping-earth.webp b/Data/systems/pf2e/icons/spells/grasping-earth.webp new file mode 100644 index 00000000..0173734e --- /dev/null +++ b/Data/systems/pf2e/icons/spells/grasping-earth.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e50349c888e947287bab098588ea82a3420f588e9485fd969c5be4dd37fe37a5 +size 1750 diff --git a/Data/systems/pf2e/icons/spells/heaving-earth.webp b/Data/systems/pf2e/icons/spells/heaving-earth.webp new file mode 100644 index 00000000..3bc41805 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/heaving-earth.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43374f76a96957fc56136e1f3e93ac6168e288f3d874e9af3cdc7d6f0e17b617 +size 1568 diff --git a/Data/systems/pf2e/icons/spells/helpful-wood-spirits.webp b/Data/systems/pf2e/icons/spells/helpful-wood-spirits.webp new file mode 100644 index 00000000..83660d52 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/helpful-wood-spirits.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43b1695b8fa5c5b9890a6c26a9cd0fcbb6bf52c4255d2733990efa37f5a7da31 +size 2102 diff --git a/Data/systems/pf2e/icons/spells/hungry-depths.webp b/Data/systems/pf2e/icons/spells/hungry-depths.webp new file mode 100644 index 00000000..f55aa519 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/hungry-depths.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c621778c2c19573dcf4973e0ed8479ce4e0a54c1d2eafc6e1c9c52d751aae141 +size 1804 diff --git a/Data/systems/pf2e/icons/spells/interposing-earth.webp b/Data/systems/pf2e/icons/spells/interposing-earth.webp new file mode 100644 index 00000000..9ac1f127 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/interposing-earth.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bda761d61d5ae277e01cc083dfd66e3b4e21cdd6a686e15a2aecd52205b6b040 +size 1740 diff --git a/Data/systems/pf2e/icons/spells/life-draining-roots.webp b/Data/systems/pf2e/icons/spells/life-draining-roots.webp new file mode 100644 index 00000000..14b2344d --- /dev/null +++ b/Data/systems/pf2e/icons/spells/life-draining-roots.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:366a9ca11a572e2943cfba5dd42961026f6d03618c451e4cccb87b21df0155c7 +size 1758 diff --git a/Data/systems/pf2e/icons/spells/lignify.webp b/Data/systems/pf2e/icons/spells/lignify.webp new file mode 100644 index 00000000..5e794f62 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/lignify.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:97b4c6123af11ae65459bb023631aeb4f33b73ecdcb8b02b0f63be401d6b25b4 +size 1314 diff --git a/Data/systems/pf2e/icons/spells/magic-weapon.webp b/Data/systems/pf2e/icons/spells/magic-weapon.webp index 49a454cb..a70f66ac 100644 --- a/Data/systems/pf2e/icons/spells/magic-weapon.webp +++ b/Data/systems/pf2e/icons/spells/magic-weapon.webp @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b6d80280da8fdeff8d877de3a1307776603f249649ffac0cef4f3d0da0364508 -size 1138 +oid sha256:4fdb7d5384cf8055a92d8067a2b0f4c840c484c56e4e857441ee3c27ac422b5d +size 2146 diff --git a/Data/systems/pf2e/icons/spells/magnetic-domination.webp b/Data/systems/pf2e/icons/spells/magnetic-domination.webp new file mode 100644 index 00000000..f32cec41 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/magnetic-domination.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:28cbc876ecc3fc49610c2aaf8cad7136d9b66d57164c647d71826e08ce916653 +size 2120 diff --git a/Data/systems/pf2e/icons/spells/mantle-of-the-melting-heart.webp b/Data/systems/pf2e/icons/spells/mantle-of-the-melting-heart.webp new file mode 100644 index 00000000..1e06dced --- /dev/null +++ b/Data/systems/pf2e/icons/spells/mantle-of-the-melting-heart.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:228aa2b825d31d519eab395ae9cba793fecd1863da35015076f76f4b2bad7afc +size 2348 diff --git a/Data/systems/pf2e/icons/spells/mantle-of-the-unwavering-heart.webp b/Data/systems/pf2e/icons/spells/mantle-of-the-unwavering-heart.webp new file mode 100644 index 00000000..b91b390c --- /dev/null +++ b/Data/systems/pf2e/icons/spells/mantle-of-the-unwavering-heart.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:961a5f260cdab42eaa5ec4d0f4ccaa56b25dbe0070eca0a29cf24069556355d1 +size 1798 diff --git a/Data/systems/pf2e/icons/spells/mercurial-stride.webp b/Data/systems/pf2e/icons/spells/mercurial-stride.webp new file mode 100644 index 00000000..cb468ba8 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/mercurial-stride.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ba7acec5e5bdb09cec698e96fcce4304f045b3300722eeccc7950a6b51e29444 +size 1816 diff --git a/Data/systems/pf2e/icons/spells/noxious-metals.webp b/Data/systems/pf2e/icons/spells/noxious-metals.webp new file mode 100644 index 00000000..9fe55d6d --- /dev/null +++ b/Data/systems/pf2e/icons/spells/noxious-metals.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f3ce89b5c53055391b59721b813cb2df19a7b3f5ced5f9fa6a24c5f7f1a90247 +size 2116 diff --git a/Data/systems/pf2e/icons/spells/pave-ground.webp b/Data/systems/pf2e/icons/spells/pave-ground.webp new file mode 100644 index 00000000..571f590e --- /dev/null +++ b/Data/systems/pf2e/icons/spells/pave-ground.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2724b474ff5b6b281f085aab030110e622baacc3dc1755b40bf3e04dbbd19cdb +size 1766 diff --git a/Data/systems/pf2e/icons/spells/phantom-orchestra.webp b/Data/systems/pf2e/icons/spells/phantom-orchestra.webp new file mode 100644 index 00000000..74573b5c --- /dev/null +++ b/Data/systems/pf2e/icons/spells/phantom-orchestra.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0834f7cccd427bbdbd629c8552a69c5597130fc36da6998bf5375077c2f38113 +size 1074 diff --git a/Data/systems/pf2e/icons/spells/pollen-pods.webp b/Data/systems/pf2e/icons/spells/pollen-pods.webp new file mode 100644 index 00000000..6f20e73b --- /dev/null +++ b/Data/systems/pf2e/icons/spells/pollen-pods.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a199bc6f785ebd352e11d18d7c22576aacd0972d681c1b5d6ab7f5eaad7bbaf +size 1022 diff --git a/Data/systems/pf2e/icons/spells/pressure-zone.webp b/Data/systems/pf2e/icons/spells/pressure-zone.webp new file mode 100644 index 00000000..3b34386e --- /dev/null +++ b/Data/systems/pf2e/icons/spells/pressure-zone.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ebb5546dbc4eb5c2cfc5c5d1bab613876fd7ac252e7fe36d9748086b258f489c +size 1210 diff --git a/Data/systems/pf2e/icons/spells/rainbow-fumarole.webp b/Data/systems/pf2e/icons/spells/rainbow-fumarole.webp new file mode 100644 index 00000000..6eb5bc79 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/rainbow-fumarole.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a78aa939affc48f47372c4a62b35d8681ccc61c7c1f23ea598ddf5f61581008 +size 950 diff --git a/Data/systems/pf2e/icons/spells/rigid-form.webp b/Data/systems/pf2e/icons/spells/rigid-form.webp new file mode 100644 index 00000000..6fcbf8bc --- /dev/null +++ b/Data/systems/pf2e/icons/spells/rigid-form.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:886bb1f89b0dc9db6b3585f64f844f409cbaf5ce7f99d11ab6eb7632edaf27fc +size 1972 diff --git a/Data/systems/pf2e/icons/spells/shielded-arm.webp b/Data/systems/pf2e/icons/spells/shielded-arm.webp new file mode 100644 index 00000000..08e00ab4 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/shielded-arm.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1262517e3e60cf04e5f92b9e7b6a032fa5579096f97f1ab8f6603b978afbf021 +size 2276 diff --git a/Data/systems/pf2e/icons/spells/shock-to-the-system.webp b/Data/systems/pf2e/icons/spells/shock-to-the-system.webp new file mode 100644 index 00000000..074cd3c3 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/shock-to-the-system.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73e0c8bab70d9f442a8a9af4d1d637f2df0219c17268eecce165157789b5edc9 +size 2662 diff --git a/Data/systems/pf2e/icons/spells/signal-skyrocket.webp b/Data/systems/pf2e/icons/spells/signal-skyrocket.webp new file mode 100644 index 00000000..018d0e6e --- /dev/null +++ b/Data/systems/pf2e/icons/spells/signal-skyrocket.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ed8d2637f6958a1cbe3065401222ca9a6006449c80188a99d826a21e5f2c65b +size 2420 diff --git a/Data/systems/pf2e/icons/spells/sky-sign.webp b/Data/systems/pf2e/icons/spells/sky-sign.webp new file mode 100644 index 00000000..e45bfde6 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/sky-sign.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eace5a92747244141cc77f988a7d7b5b720f7ad826daf5df87e3499640f13a82 +size 1004 diff --git a/Data/systems/pf2e/icons/spells/stifling-stillness.webp b/Data/systems/pf2e/icons/spells/stifling-stillness.webp new file mode 100644 index 00000000..3b709a22 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/stifling-stillness.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef5b9ef2f406db26cbca1c8148df0004a8a140d4b83ae82a7bdb1f252b94651c +size 1550 diff --git a/Data/systems/pf2e/icons/spells/summon-elemental-herald.webp b/Data/systems/pf2e/icons/spells/summon-elemental-herald.webp new file mode 100644 index 00000000..5cbb693d --- /dev/null +++ b/Data/systems/pf2e/icons/spells/summon-elemental-herald.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad6f59f6e2a28a4913cb1be2ddbd1d5b61f10018c8c96a104e6d3c27baa72d88 +size 2608 diff --git a/Data/systems/pf2e/icons/spells/timber.webp b/Data/systems/pf2e/icons/spells/timber.webp new file mode 100644 index 00000000..36fa3226 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/timber.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01d28be2574eb558a77b9e9dd73d98709c888282ce0e8e4e78457698c9071fae +size 1620 diff --git a/Data/systems/pf2e/icons/spells/tremor-signs.webp b/Data/systems/pf2e/icons/spells/tremor-signs.webp new file mode 100644 index 00000000..bb94e94f --- /dev/null +++ b/Data/systems/pf2e/icons/spells/tremor-signs.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8053aa8617e01494d8cab7cf51f8adf9fc5459579e1d3be6be77aa02bf312d2 +size 2526 diff --git a/Data/systems/pf2e/icons/spells/vacuum.webp b/Data/systems/pf2e/icons/spells/vacuum.webp new file mode 100644 index 00000000..da4f963f --- /dev/null +++ b/Data/systems/pf2e/icons/spells/vacuum.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ccd826090a79622d79e8ce52849d9962b18c6d8d7e50a15871e4281d8fe2a2f3 +size 1632 diff --git a/Data/systems/pf2e/icons/spells/wall-of-shrubs.webp b/Data/systems/pf2e/icons/spells/wall-of-shrubs.webp new file mode 100644 index 00000000..68862c57 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/wall-of-shrubs.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:961f8e89b1bd05f1781bb4f84294b3c9ce355ee45cbc613a7649e7476a4f0422 +size 2820 diff --git a/Data/systems/pf2e/icons/spells/waterproof.webp b/Data/systems/pf2e/icons/spells/waterproof.webp new file mode 100644 index 00000000..95bc9b21 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/waterproof.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b19c83012f856c10502879a1c434330bc017616ddb6ad643e71af8dadaebba92 +size 2350 diff --git a/Data/systems/pf2e/icons/spells/wood-walk.webp b/Data/systems/pf2e/icons/spells/wood-walk.webp new file mode 100644 index 00000000..5cc60591 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/wood-walk.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25869c43a3efade356ba506887f3a637e89379f509126c53394e8d0455bfe113 +size 1960 diff --git a/Data/systems/pf2e/icons/spells/wooden-double.webp b/Data/systems/pf2e/icons/spells/wooden-double.webp new file mode 100644 index 00000000..efd01132 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/wooden-double.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8029336e6ca27ce1bb5636c39624978756c9a6c1805ece68715f2c17739b9419 +size 1994 diff --git a/Data/systems/pf2e/icons/spells/ymeris-mark.webp b/Data/systems/pf2e/icons/spells/ymeris-mark.webp new file mode 100644 index 00000000..9818cfaa --- /dev/null +++ b/Data/systems/pf2e/icons/spells/ymeris-mark.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fdd79bf8a2751660e6fd25208c3dce8a874f6f415a1f78caa29db06050100d28 +size 1972 diff --git a/Data/systems/pf2e/icons/spells/zephyr-slip.webp b/Data/systems/pf2e/icons/spells/zephyr-slip.webp new file mode 100644 index 00000000..faa244a5 --- /dev/null +++ b/Data/systems/pf2e/icons/spells/zephyr-slip.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:41cbd3d36d631f4db919ac91b7fb4b62dde06ddbe8830457bcdbbd1f40b61a09 +size 1900 diff --git a/Data/systems/pf2e/icons/unarmed-attacks/magma-spike.webp b/Data/systems/pf2e/icons/unarmed-attacks/magma-spike.webp new file mode 100644 index 00000000..064bdd10 --- /dev/null +++ b/Data/systems/pf2e/icons/unarmed-attacks/magma-spike.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82dc5d6c0184ec11482b08ce0818c02693321b16720e91ad0540f8e4530cec7f +size 1676 diff --git a/Data/systems/pf2e/lang/en.json b/Data/systems/pf2e/lang/en.json index e5b3bac5..a2efaee9 100644 --- a/Data/systems/pf2e/lang/en.json +++ b/Data/systems/pf2e/lang/en.json @@ -252,6 +252,7 @@ "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": { @@ -1963,10 +1964,12 @@ "Hint": "Almost all deities have a single favored weapon, but a few have both a favored weapon and unarmed attack.", "Label": "Favored Weapon(s)" }, - "FollowerAlignments": "Follower Alignments" + "FollowerAlignments": "Follower Alignments", + "Spellcasting": "Spellcasting" }, "Effect": { "Expiry": { + "EndOfRound": "End of Round", "EndOfTurn": "End of Turn", "ExpiresOn": "Expires On", "StartOfTurn": "Start of Turn" @@ -2163,6 +2166,7 @@ "Clear": "Clear Placed Templates", "Place": "Place {size}-{unit} {shape}" }, + "Rank": "Rank", "Variants": { "DeleteDialogText": "Are you sure you want to delete '{variantName}'?", "DeleteDialogTitle": "Delete Spell Variant", @@ -2444,7 +2448,8 @@ "Off": "OFF", "On": "ON" }, - "Plural": "Macros" + "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!", @@ -5738,19 +5743,19 @@ "GiveMessage": "{giver} gives {quantity} × {item} to {recipient}.", "GiveSubtitle": "Give item", "HiddenWhenEmpty": { - "Hint": "Hide this actor's token(s) when its inventory is empty", - "Label": "Hidden when empty" + "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} × {item} off {corpse}.", - "LootNPCsLabel": "Loot selected tokens", + "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.", + "MerchantDescription": "Allows players to purchase items directly from the sheet", "MerchantLabel": "Merchant", "MoveLoot": "Move Items", "MoveLootMessage": "How many items do you wish to move?", diff --git a/Data/systems/pf2e/lang/re-en.json b/Data/systems/pf2e/lang/re-en.json index 6710c5bc..0367dc4a 100644 --- a/Data/systems/pf2e/lang/re-en.json +++ b/Data/systems/pf2e/lang/re-en.json @@ -567,7 +567,9 @@ "MagicalSilver": "magical silver", "MagicalSilverWeapons": "magical silver weapons", "MagicalWeaponsBrightLight": "magical weapons shedding bright light", - "NonWeapons": "non-weapons" + "NonWeapons": "non-weapons", + "PhysicalRangedAttacks": "physical ranged attacks", + "RangedWeaponAttacks": "ranged weapon attacks" } }, "Mutagens": { @@ -2207,6 +2209,15 @@ "Kineticist": { "GateAttenuator": "Gate Attenuator", "Impulse": { + "CriticalBlast": { + "Air": "Push the target up to 10 feet.", + "Earth": "If the target is on the ground, it's knocked @UUID[Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60]{Prone}; if it isn't on the ground, it descends up to 20 feet (you choose the distance).", + "Fire": "The target takes 1d6 persistent fire damage. You gain an item bonus to this persistent damage equal to your item bonus to impulse attack rolls, such as from a gate attenuator.", + "Label": "Critical Blast", + "Metal": "The target takes 1d6 persistent bleed damage; if the creature has the metal trait or is made of metal, it instead takes @Damage[1d6[persistent,untyped]] damage with no type from rust. You gain an item bonus to this persistent damage equal to your item bonus to impulse attack rolls, such as from a gate attenuator.", + "Water": "The blast deals 2 splash damage per damage die of the blast, with the same damage type.", + "Wood": "If the target of the critical hit is adjacent to a surface, roots entangle it. The target is @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{Immobilized} and must spend an Interact action to attempt a @Check[type:athletics|dc:10] check to pull itself free. The target doesn't become stuck if it is incorporeal, is liquid, or could otherwise escape without effort." + }, "ElementalBlast": { "Label": { "Air": "Elemental Blast (Air)", diff --git a/Data/systems/pf2e/packs/abomination-vaults-bestiary/000009.ldb b/Data/systems/pf2e/packs/abomination-vaults-bestiary/000005.ldb similarity index 97% rename from Data/systems/pf2e/packs/abomination-vaults-bestiary/000009.ldb rename to Data/systems/pf2e/packs/abomination-vaults-bestiary/000005.ldb index 89d177d9..4c1a53cb 100644 Binary files a/Data/systems/pf2e/packs/abomination-vaults-bestiary/000009.ldb and b/Data/systems/pf2e/packs/abomination-vaults-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/abomination-vaults-bestiary/000015.log b/Data/systems/pf2e/packs/abomination-vaults-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/abomination-vaults-bestiary/000015.log rename to Data/systems/pf2e/packs/abomination-vaults-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/abomination-vaults-bestiary/CURRENT b/Data/systems/pf2e/packs/abomination-vaults-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/abomination-vaults-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/abomination-vaults-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/abomination-vaults-bestiary/LOG b/Data/systems/pf2e/packs/abomination-vaults-bestiary/LOG index f25d4e0e..9e9ee7cb 100644 --- a/Data/systems/pf2e/packs/abomination-vaults-bestiary/LOG +++ b/Data/systems/pf2e/packs/abomination-vaults-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:09.775602 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:09.780700 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:09.780720 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:16.180050 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:16.185298 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:16.202851 ffff87fff0a0 Level-0 table #5: 1387633 bytes OK +2023/10/23-05:12:16.207585 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:16.208074 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/abomination-vaults-bestiary/LOG.old b/Data/systems/pf2e/packs/abomination-vaults-bestiary/LOG.old index b8bbbdc0..bd9f71c6 100644 --- a/Data/systems/pf2e/packs/abomination-vaults-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/abomination-vaults-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.617313 ffff877ef0a0 Recovering log #7 -2023/10/20-07:41:10.622714 ffff877ef0a0 Delete type=3 #4 -2023/10/20-07:41:10.622738 ffff877ef0a0 Delete type=0 #7 -2023/10/20-07:49:07.467340 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.467358 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.468982 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.473231 ffff85fbf0a0 Manual compaction at level-0 from '!actors!00s3MhFQ4yOp2rTf' @ 72057594037927935 : 1 .. '!actors.items!zsgW8hHm3JfZUgwF.zNFSrrQNB1kgV8Go' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.526917 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/abomination-vaults-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/abomination-vaults-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..2bb5c48f Binary files /dev/null and b/Data/systems/pf2e/packs/abomination-vaults-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/abomination-vaults-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/abomination-vaults-bestiary/MANIFEST-000014 deleted file mode 100644 index 7cabbcce..00000000 Binary files a/Data/systems/pf2e/packs/abomination-vaults-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/action-macros/000009.ldb b/Data/systems/pf2e/packs/action-macros/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/action-macros/000009.ldb rename to Data/systems/pf2e/packs/action-macros/000005.ldb diff --git a/Data/systems/pf2e/packs/action-macros/000015.log b/Data/systems/pf2e/packs/action-macros/000006.log similarity index 100% rename from Data/systems/pf2e/packs/action-macros/000015.log rename to Data/systems/pf2e/packs/action-macros/000006.log diff --git a/Data/systems/pf2e/packs/action-macros/CURRENT b/Data/systems/pf2e/packs/action-macros/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/action-macros/CURRENT +++ b/Data/systems/pf2e/packs/action-macros/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/action-macros/LOG b/Data/systems/pf2e/packs/action-macros/LOG index 62f0e9b8..adea8ba2 100644 --- a/Data/systems/pf2e/packs/action-macros/LOG +++ b/Data/systems/pf2e/packs/action-macros/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.970917 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.975732 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.975751 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:18.568109 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:18.568175 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:18.570280 ffff877ef0a0 Level-0 table #5: 7022 bytes OK +2023/10/23-05:12:18.575078 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:18.575103 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/action-macros/LOG.old b/Data/systems/pf2e/packs/action-macros/LOG.old index 681764c4..3c605f0f 100644 --- a/Data/systems/pf2e/packs/action-macros/LOG.old +++ b/Data/systems/pf2e/packs/action-macros/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.840620 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.847310 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.847334 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.614140 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.614162 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.615962 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.618319 ffff85fbf0a0 Manual compaction at level-0 from '!macros!1AIo5UcVbCmvpRL3' @ 72057594037927935 : 1 .. '!macros!zn0HadZeoKDALxRu' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.527398 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/action-macros/MANIFEST-000004 b/Data/systems/pf2e/packs/action-macros/MANIFEST-000004 new file mode 100644 index 00000000..8eee8ee5 Binary files /dev/null and b/Data/systems/pf2e/packs/action-macros/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/action-macros/MANIFEST-000014 b/Data/systems/pf2e/packs/action-macros/MANIFEST-000014 deleted file mode 100644 index 2425c7a0..00000000 Binary files a/Data/systems/pf2e/packs/action-macros/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/actions/000009.ldb b/Data/systems/pf2e/packs/actions/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/actions/000009.ldb rename to Data/systems/pf2e/packs/actions/000005.ldb diff --git a/Data/systems/pf2e/packs/actions/000015.log b/Data/systems/pf2e/packs/actions/000006.log similarity index 100% rename from Data/systems/pf2e/packs/actions/000015.log rename to Data/systems/pf2e/packs/actions/000006.log diff --git a/Data/systems/pf2e/packs/actions/CURRENT b/Data/systems/pf2e/packs/actions/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/actions/CURRENT +++ b/Data/systems/pf2e/packs/actions/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/actions/LOG b/Data/systems/pf2e/packs/actions/LOG index d02a9934..cb1f2721 100644 --- a/Data/systems/pf2e/packs/actions/LOG +++ b/Data/systems/pf2e/packs/actions/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.644525 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.649734 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.649754 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:17.908408 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:17.909312 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:17.914373 ffff86fdf0a0 Level-0 table #5: 276012 bytes OK +2023/10/23-05:12:17.918875 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:17.918987 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/actions/LOG.old b/Data/systems/pf2e/packs/actions/LOG.old index 295705d3..8e661d80 100644 --- a/Data/systems/pf2e/packs/actions/LOG.old +++ b/Data/systems/pf2e/packs/actions/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.530943 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.535742 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.535763 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.561084 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.561105 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.563041 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.566758 ffff85fbf0a0 Manual compaction at level-0 from '!items!00LNVSCbwJ8pszwE' @ 72057594037927935 : 1 .. '!items!yzNJgwzV9XqEhKc6' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.526703 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/actions/MANIFEST-000004 b/Data/systems/pf2e/packs/actions/MANIFEST-000004 new file mode 100644 index 00000000..79231762 Binary files /dev/null and b/Data/systems/pf2e/packs/actions/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/actions/MANIFEST-000014 b/Data/systems/pf2e/packs/actions/MANIFEST-000014 deleted file mode 100644 index 237d412c..00000000 Binary files a/Data/systems/pf2e/packs/actions/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/adventure-specific-actions/000009.ldb b/Data/systems/pf2e/packs/adventure-specific-actions/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/adventure-specific-actions/000009.ldb rename to Data/systems/pf2e/packs/adventure-specific-actions/000005.ldb diff --git a/Data/systems/pf2e/packs/adventure-specific-actions/000015.log b/Data/systems/pf2e/packs/adventure-specific-actions/000006.log similarity index 100% rename from Data/systems/pf2e/packs/adventure-specific-actions/000015.log rename to Data/systems/pf2e/packs/adventure-specific-actions/000006.log diff --git a/Data/systems/pf2e/packs/adventure-specific-actions/CURRENT b/Data/systems/pf2e/packs/adventure-specific-actions/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/adventure-specific-actions/CURRENT +++ b/Data/systems/pf2e/packs/adventure-specific-actions/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/adventure-specific-actions/LOG b/Data/systems/pf2e/packs/adventure-specific-actions/LOG index 564a97ee..eed7b004 100644 --- a/Data/systems/pf2e/packs/adventure-specific-actions/LOG +++ b/Data/systems/pf2e/packs/adventure-specific-actions/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:11.003368 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:11.008160 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:11.008179 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:18.605722 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:18.606071 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:18.609602 ffff877ef0a0 Level-0 table #5: 113628 bytes OK +2023/10/23-05:12:18.614608 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:18.614665 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/adventure-specific-actions/LOG.old b/Data/systems/pf2e/packs/adventure-specific-actions/LOG.old index 0b8ca05b..1b9367eb 100644 --- a/Data/systems/pf2e/packs/adventure-specific-actions/LOG.old +++ b/Data/systems/pf2e/packs/adventure-specific-actions/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.869587 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.874835 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.874856 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.622077 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.622097 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.623764 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.625708 ffff85fbf0a0 Manual compaction at level-0 from '!items!0HbksdcT2zNV5CUt' @ 72057594037927935 : 1 .. '!items!zIwbbth7qyKraiWV' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.527388 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/adventure-specific-actions/MANIFEST-000004 b/Data/systems/pf2e/packs/adventure-specific-actions/MANIFEST-000004 new file mode 100644 index 00000000..bf3d9b12 Binary files /dev/null and b/Data/systems/pf2e/packs/adventure-specific-actions/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/adventure-specific-actions/MANIFEST-000014 b/Data/systems/pf2e/packs/adventure-specific-actions/MANIFEST-000014 deleted file mode 100644 index 8b46475a..00000000 Binary files a/Data/systems/pf2e/packs/adventure-specific-actions/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/age-of-ashes-bestiary/000009.ldb b/Data/systems/pf2e/packs/age-of-ashes-bestiary/000005.ldb similarity index 95% rename from Data/systems/pf2e/packs/age-of-ashes-bestiary/000009.ldb rename to Data/systems/pf2e/packs/age-of-ashes-bestiary/000005.ldb index 903149c4..607e5f1a 100644 Binary files a/Data/systems/pf2e/packs/age-of-ashes-bestiary/000009.ldb and b/Data/systems/pf2e/packs/age-of-ashes-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/age-of-ashes-bestiary/000015.log b/Data/systems/pf2e/packs/age-of-ashes-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/age-of-ashes-bestiary/000015.log rename to Data/systems/pf2e/packs/age-of-ashes-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/age-of-ashes-bestiary/CURRENT b/Data/systems/pf2e/packs/age-of-ashes-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/age-of-ashes-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/age-of-ashes-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/age-of-ashes-bestiary/LOG b/Data/systems/pf2e/packs/age-of-ashes-bestiary/LOG index 97a0dd3a..86861467 100644 --- a/Data/systems/pf2e/packs/age-of-ashes-bestiary/LOG +++ b/Data/systems/pf2e/packs/age-of-ashes-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:09.813963 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:09.819387 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:09.819409 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:16.245119 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:16.250889 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:16.274738 ffff877ef0a0 Level-0 table #5: 1594481 bytes OK +2023/10/23-05:12:16.279601 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:16.280149 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/age-of-ashes-bestiary/LOG.old b/Data/systems/pf2e/packs/age-of-ashes-bestiary/LOG.old index 81fd8182..1236c24c 100644 --- a/Data/systems/pf2e/packs/age-of-ashes-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/age-of-ashes-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.669177 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:10.674731 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:10.674759 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.473359 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.473381 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.475386 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.477860 ffff85fbf0a0 Manual compaction at level-0 from '!actors!080v247YtmFRxT3l' @ 72057594037927935 : 1 .. '!actors.items!zdJHl3xMY7n2Lwlf.zVCalXk0BtUnOMfM' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.529648 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/age-of-ashes-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/age-of-ashes-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..7abc3f73 Binary files /dev/null and b/Data/systems/pf2e/packs/age-of-ashes-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/age-of-ashes-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/age-of-ashes-bestiary/MANIFEST-000014 deleted file mode 100644 index ab005af5..00000000 Binary files a/Data/systems/pf2e/packs/age-of-ashes-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/000009.ldb b/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/000005.ldb similarity index 89% rename from Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/000009.ldb rename to Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/000005.ldb index ee01e573..44736f4b 100644 Binary files a/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/000009.ldb and b/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/000015.log b/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/000015.log rename to Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/CURRENT b/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/LOG b/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/LOG index 3a2effb9..6601f795 100644 --- a/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/LOG +++ b/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:09.841348 ffff867cf0a0 Recovering log #12 -2023/10/20-07:55:09.846356 ffff867cf0a0 Delete type=0 #12 -2023/10/20-07:55:09.846378 ffff867cf0a0 Delete type=3 #10 +2023/10/23-05:12:16.297304 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:16.304050 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:16.329495 ffff86fdf0a0 Level-0 table #5: 1905989 bytes OK +2023/10/23-05:12:16.334637 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:16.335281 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/LOG.old b/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/LOG.old index 57abb9b8..a83f90bd 100644 --- a/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.695642 ffff86fdf0a0 Recovering log #7 -2023/10/20-07:41:10.700740 ffff86fdf0a0 Delete type=3 #4 -2023/10/20-07:41:10.700767 ffff86fdf0a0 Delete type=0 #7 -2023/10/20-07:49:07.475811 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.475834 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.477820 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.481537 ffff85fbf0a0 Manual compaction at level-0 from '!actors!07AGJt4ZRjwH85Xp' @ 72057594037927935 : 1 .. '!actors.items!zrh3MrS68H2gPlVs.zMxrSkK2U9CDEp0u' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.531805 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..30c16e52 Binary files /dev/null and b/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/MANIFEST-000014 deleted file mode 100644 index 17a7d447..00000000 Binary files a/Data/systems/pf2e/packs/agents-of-edgewatch-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/ancestries/000009.ldb b/Data/systems/pf2e/packs/ancestries/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/ancestries/000009.ldb rename to Data/systems/pf2e/packs/ancestries/000005.ldb diff --git a/Data/systems/pf2e/packs/ancestries/000015.log b/Data/systems/pf2e/packs/ancestries/000006.log similarity index 100% rename from Data/systems/pf2e/packs/ancestries/000015.log rename to Data/systems/pf2e/packs/ancestries/000006.log diff --git a/Data/systems/pf2e/packs/ancestries/CURRENT b/Data/systems/pf2e/packs/ancestries/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/ancestries/CURRENT +++ b/Data/systems/pf2e/packs/ancestries/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/ancestries/LOG b/Data/systems/pf2e/packs/ancestries/LOG index 2e292acb..f96d9250 100644 --- a/Data/systems/pf2e/packs/ancestries/LOG +++ b/Data/systems/pf2e/packs/ancestries/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.653359 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.658401 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.658422 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:17.929146 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:17.929266 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:17.931528 ffff877ef0a0 Level-0 table #5: 28101 bytes OK +2023/10/23-05:12:17.936390 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:17.936424 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/ancestries/LOG.old b/Data/systems/pf2e/packs/ancestries/LOG.old index 4782ad83..040de3e5 100644 --- a/Data/systems/pf2e/packs/ancestries/LOG.old +++ b/Data/systems/pf2e/packs/ancestries/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.539085 ffff877ef0a0 Recovering log #7 -2023/10/20-07:41:11.543745 ffff877ef0a0 Delete type=3 #4 -2023/10/20-07:41:11.543768 ffff877ef0a0 Delete type=0 #7 -2023/10/20-07:49:07.563199 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.563219 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.564958 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.568727 ffff85fbf0a0 Manual compaction at level-0 from '!items!18xDKYPDBLEv2myX' @ 72057594037927935 : 1 .. '!items!yFoojz6q3ZjvceFw' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.529730 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/ancestries/MANIFEST-000004 b/Data/systems/pf2e/packs/ancestries/MANIFEST-000004 new file mode 100644 index 00000000..ced2ea8e Binary files /dev/null and b/Data/systems/pf2e/packs/ancestries/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/ancestries/MANIFEST-000014 b/Data/systems/pf2e/packs/ancestries/MANIFEST-000014 deleted file mode 100644 index 8d5bbae4..00000000 Binary files a/Data/systems/pf2e/packs/ancestries/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/ancestryfeatures/000009.ldb b/Data/systems/pf2e/packs/ancestryfeatures/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/ancestryfeatures/000009.ldb rename to Data/systems/pf2e/packs/ancestryfeatures/000005.ldb diff --git a/Data/systems/pf2e/packs/ancestryfeatures/000015.log b/Data/systems/pf2e/packs/ancestryfeatures/000006.log similarity index 100% rename from Data/systems/pf2e/packs/ancestryfeatures/000015.log rename to Data/systems/pf2e/packs/ancestryfeatures/000006.log diff --git a/Data/systems/pf2e/packs/ancestryfeatures/CURRENT b/Data/systems/pf2e/packs/ancestryfeatures/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/ancestryfeatures/CURRENT +++ b/Data/systems/pf2e/packs/ancestryfeatures/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/ancestryfeatures/LOG b/Data/systems/pf2e/packs/ancestryfeatures/LOG index 39ef5576..97eb9a52 100644 --- a/Data/systems/pf2e/packs/ancestryfeatures/LOG +++ b/Data/systems/pf2e/packs/ancestryfeatures/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.660428 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.665591 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.665610 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:17.938350 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:17.938454 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:17.941029 ffff86fdf0a0 Level-0 table #5: 23680 bytes OK +2023/10/23-05:12:17.946626 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:17.946659 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/ancestryfeatures/LOG.old b/Data/systems/pf2e/packs/ancestryfeatures/LOG.old index 3ec95648..67c8e503 100644 --- a/Data/systems/pf2e/packs/ancestryfeatures/LOG.old +++ b/Data/systems/pf2e/packs/ancestryfeatures/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.545524 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.550162 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.550184 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.564995 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.565010 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.566721 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.568881 ffff85fbf0a0 Manual compaction at level-0 from '!items!8sxtjVsk9HBY5yAv' @ 72057594037927935 : 1 .. '!items!y1EmCv2cEb5hXBwx' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.530243 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/ancestryfeatures/MANIFEST-000004 b/Data/systems/pf2e/packs/ancestryfeatures/MANIFEST-000004 new file mode 100644 index 00000000..c3109b3e Binary files /dev/null and b/Data/systems/pf2e/packs/ancestryfeatures/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/ancestryfeatures/MANIFEST-000014 b/Data/systems/pf2e/packs/ancestryfeatures/MANIFEST-000014 deleted file mode 100644 index 3a02c467..00000000 Binary files a/Data/systems/pf2e/packs/ancestryfeatures/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/backgrounds/000009.ldb b/Data/systems/pf2e/packs/backgrounds/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/backgrounds/000009.ldb rename to Data/systems/pf2e/packs/backgrounds/000005.ldb diff --git a/Data/systems/pf2e/packs/backgrounds/000015.log b/Data/systems/pf2e/packs/backgrounds/000006.log similarity index 100% rename from Data/systems/pf2e/packs/backgrounds/000015.log rename to Data/systems/pf2e/packs/backgrounds/000006.log diff --git a/Data/systems/pf2e/packs/backgrounds/CURRENT b/Data/systems/pf2e/packs/backgrounds/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/backgrounds/CURRENT +++ b/Data/systems/pf2e/packs/backgrounds/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/backgrounds/LOG b/Data/systems/pf2e/packs/backgrounds/LOG index 0e996a42..8d38d84d 100644 --- a/Data/systems/pf2e/packs/backgrounds/LOG +++ b/Data/systems/pf2e/packs/backgrounds/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.667357 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.672917 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.672936 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:17.948605 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:17.949766 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:17.958359 ffff877ef0a0 Level-0 table #5: 370183 bytes OK +2023/10/23-05:12:17.963285 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:17.963428 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/backgrounds/LOG.old b/Data/systems/pf2e/packs/backgrounds/LOG.old index 8c6f33c2..bf479c6a 100644 --- a/Data/systems/pf2e/packs/backgrounds/LOG.old +++ b/Data/systems/pf2e/packs/backgrounds/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.551937 ffff877ef0a0 Recovering log #7 -2023/10/20-07:41:11.556820 ffff877ef0a0 Delete type=3 #4 -2023/10/20-07:41:11.556844 ffff877ef0a0 Delete type=0 #7 -2023/10/20-07:49:07.566874 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.566897 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.568689 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.570900 ffff85fbf0a0 Manual compaction at level-0 from '!items!0FgYkkKv9u8zxWiO' @ 72057594037927935 : 1 .. '!items!zwjoAOGkT44MmDKT' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.533383 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/backgrounds/MANIFEST-000004 b/Data/systems/pf2e/packs/backgrounds/MANIFEST-000004 new file mode 100644 index 00000000..74d52b73 Binary files /dev/null and b/Data/systems/pf2e/packs/backgrounds/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/backgrounds/MANIFEST-000014 b/Data/systems/pf2e/packs/backgrounds/MANIFEST-000014 deleted file mode 100644 index 30dd6307..00000000 Binary files a/Data/systems/pf2e/packs/backgrounds/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/000009.ldb b/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/bestiary-ability-glossary-srd/000009.ldb rename to Data/systems/pf2e/packs/bestiary-ability-glossary-srd/000005.ldb diff --git a/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/000015.log b/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/000006.log similarity index 100% rename from Data/systems/pf2e/packs/bestiary-ability-glossary-srd/000015.log rename to Data/systems/pf2e/packs/bestiary-ability-glossary-srd/000006.log diff --git a/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/CURRENT b/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/CURRENT +++ b/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/LOG b/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/LOG index 63274cb7..c48b66d5 100644 --- a/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/LOG +++ b/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.985594 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.990289 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.990308 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:18.583790 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:18.583875 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:18.586142 ffff877ef0a0 Level-0 table #5: 11536 bytes OK +2023/10/23-05:12:18.590870 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:18.590899 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/LOG.old b/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/LOG.old index a22fe52e..f3de4c9c 100644 --- a/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/LOG.old +++ b/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.854832 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.859862 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.859884 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.618438 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.618459 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.620171 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.623802 ffff85fbf0a0 Manual compaction at level-0 from '!items!0B39GdScyZMPWalX' @ 72057594037927935 : 1 .. '!items!zU3Ovaet4xQ5Gmvy' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.532807 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/MANIFEST-000004 b/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/MANIFEST-000004 new file mode 100644 index 00000000..00760aec Binary files /dev/null and b/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/MANIFEST-000014 b/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/MANIFEST-000014 deleted file mode 100644 index f0c6f6e3..00000000 Binary files a/Data/systems/pf2e/packs/bestiary-ability-glossary-srd/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/bestiary-effects/000009.ldb b/Data/systems/pf2e/packs/bestiary-effects/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/bestiary-effects/000009.ldb rename to Data/systems/pf2e/packs/bestiary-effects/000005.ldb diff --git a/Data/systems/pf2e/packs/bestiary-effects/000015.log b/Data/systems/pf2e/packs/bestiary-effects/000006.log similarity index 100% rename from Data/systems/pf2e/packs/bestiary-effects/000015.log rename to Data/systems/pf2e/packs/bestiary-effects/000006.log diff --git a/Data/systems/pf2e/packs/bestiary-effects/CURRENT b/Data/systems/pf2e/packs/bestiary-effects/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/bestiary-effects/CURRENT +++ b/Data/systems/pf2e/packs/bestiary-effects/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/bestiary-effects/LOG b/Data/systems/pf2e/packs/bestiary-effects/LOG index d5ad5a1c..eebaee9d 100644 --- a/Data/systems/pf2e/packs/bestiary-effects/LOG +++ b/Data/systems/pf2e/packs/bestiary-effects/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.765991 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.770954 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.770973 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:18.148726 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:18.149287 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:18.153039 ffff877ef0a0 Level-0 table #5: 130289 bytes OK +2023/10/23-05:12:18.157589 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:18.157658 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/bestiary-effects/LOG.old b/Data/systems/pf2e/packs/bestiary-effects/LOG.old index 0f4d5e2f..587e5f91 100644 --- a/Data/systems/pf2e/packs/bestiary-effects/LOG.old +++ b/Data/systems/pf2e/packs/bestiary-effects/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.650838 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.655825 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.655848 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.580872 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.580887 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.582700 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.584917 ffff85fbf0a0 Manual compaction at level-0 from '!items!0ifqiVhhKULXJyf9' @ 72057594037927935 : 1 .. '!items!zzdOof9hHUf9s13H' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.533911 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/bestiary-effects/MANIFEST-000004 b/Data/systems/pf2e/packs/bestiary-effects/MANIFEST-000004 new file mode 100644 index 00000000..e084172e Binary files /dev/null and b/Data/systems/pf2e/packs/bestiary-effects/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/bestiary-effects/MANIFEST-000014 b/Data/systems/pf2e/packs/bestiary-effects/MANIFEST-000014 deleted file mode 100644 index e33dc809..00000000 Binary files a/Data/systems/pf2e/packs/bestiary-effects/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/bestiary-family-ability-glossary/000009.ldb b/Data/systems/pf2e/packs/bestiary-family-ability-glossary/000005.ldb similarity index 97% rename from Data/systems/pf2e/packs/bestiary-family-ability-glossary/000009.ldb rename to Data/systems/pf2e/packs/bestiary-family-ability-glossary/000005.ldb index 47a99df3..8f9988a8 100644 Binary files a/Data/systems/pf2e/packs/bestiary-family-ability-glossary/000009.ldb and b/Data/systems/pf2e/packs/bestiary-family-ability-glossary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/bestiary-family-ability-glossary/000015.log b/Data/systems/pf2e/packs/bestiary-family-ability-glossary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/bestiary-family-ability-glossary/000015.log rename to Data/systems/pf2e/packs/bestiary-family-ability-glossary/000006.log diff --git a/Data/systems/pf2e/packs/bestiary-family-ability-glossary/CURRENT b/Data/systems/pf2e/packs/bestiary-family-ability-glossary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/bestiary-family-ability-glossary/CURRENT +++ b/Data/systems/pf2e/packs/bestiary-family-ability-glossary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/bestiary-family-ability-glossary/LOG b/Data/systems/pf2e/packs/bestiary-family-ability-glossary/LOG index 22b10202..0161dee0 100644 --- a/Data/systems/pf2e/packs/bestiary-family-ability-glossary/LOG +++ b/Data/systems/pf2e/packs/bestiary-family-ability-glossary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.995833 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:11.000525 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:11.000544 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:18.592493 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:18.593176 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:18.597590 ffff87fff0a0 Level-0 table #5: 188002 bytes OK +2023/10/23-05:12:18.602887 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:18.602974 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/bestiary-family-ability-glossary/LOG.old b/Data/systems/pf2e/packs/bestiary-family-ability-glossary/LOG.old index fb74f842..756889d5 100644 --- a/Data/systems/pf2e/packs/bestiary-family-ability-glossary/LOG.old +++ b/Data/systems/pf2e/packs/bestiary-family-ability-glossary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.861603 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.866768 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.866790 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.620208 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.620222 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.621926 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.623920 ffff85fbf0a0 Manual compaction at level-0 from '!items!03knx0BWuYBNciXI' @ 72057594037927935 : 1 .. '!items!zwgUxJBNFqWOuaBX' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.565702 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/bestiary-family-ability-glossary/MANIFEST-000004 b/Data/systems/pf2e/packs/bestiary-family-ability-glossary/MANIFEST-000004 new file mode 100644 index 00000000..a90218ac Binary files /dev/null and b/Data/systems/pf2e/packs/bestiary-family-ability-glossary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/bestiary-family-ability-glossary/MANIFEST-000014 b/Data/systems/pf2e/packs/bestiary-family-ability-glossary/MANIFEST-000014 deleted file mode 100644 index 0a9f76cc..00000000 Binary files a/Data/systems/pf2e/packs/bestiary-family-ability-glossary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/blog-bestiary/000009.ldb b/Data/systems/pf2e/packs/blog-bestiary/000005.ldb similarity index 94% rename from Data/systems/pf2e/packs/blog-bestiary/000009.ldb rename to Data/systems/pf2e/packs/blog-bestiary/000005.ldb index 99c572aa..5f28e567 100644 Binary files a/Data/systems/pf2e/packs/blog-bestiary/000009.ldb and b/Data/systems/pf2e/packs/blog-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/blog-bestiary/000015.log b/Data/systems/pf2e/packs/blog-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/blog-bestiary/000015.log rename to Data/systems/pf2e/packs/blog-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/blog-bestiary/CURRENT b/Data/systems/pf2e/packs/blog-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/blog-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/blog-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/blog-bestiary/LOG b/Data/systems/pf2e/packs/blog-bestiary/LOG index 94957195..009f1928 100644 --- a/Data/systems/pf2e/packs/blog-bestiary/LOG +++ b/Data/systems/pf2e/packs/blog-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:09.905024 ffff867cf0a0 Recovering log #12 -2023/10/20-07:55:09.910136 ffff867cf0a0 Delete type=0 #12 -2023/10/20-07:55:09.910156 ffff867cf0a0 Delete type=3 #10 +2023/10/23-05:12:16.452731 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:16.453591 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:16.458583 ffff86fdf0a0 Level-0 table #5: 221955 bytes OK +2023/10/23-05:12:16.463475 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:16.463582 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/blog-bestiary/LOG.old b/Data/systems/pf2e/packs/blog-bestiary/LOG.old index 1e9f4eb1..314608b6 100644 --- a/Data/systems/pf2e/packs/blog-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/blog-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.759613 ffff86fdf0a0 Recovering log #7 -2023/10/20-07:41:10.764684 ffff86fdf0a0 Delete type=3 #4 -2023/10/20-07:41:10.764709 ffff86fdf0a0 Delete type=0 #7 -2023/10/20-07:49:07.481660 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.481682 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.483632 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.485948 ffff85fbf0a0 Manual compaction at level-0 from '!actors!4BzHtRTPQ5mZj9Mr' @ 72057594037927935 : 1 .. '!actors.items!z3u0OykjFKz9KJjk.rS4SIziM9TmwCXD7' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.564320 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/blog-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/blog-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..1c23dd13 Binary files /dev/null and b/Data/systems/pf2e/packs/blog-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/blog-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/blog-bestiary/MANIFEST-000014 deleted file mode 100644 index f8ca5d93..00000000 Binary files a/Data/systems/pf2e/packs/blog-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/blood-lords-bestiary/000009.ldb b/Data/systems/pf2e/packs/blood-lords-bestiary/000005.ldb similarity index 98% rename from Data/systems/pf2e/packs/blood-lords-bestiary/000009.ldb rename to Data/systems/pf2e/packs/blood-lords-bestiary/000005.ldb index 3d35a727..af3dfce6 100644 Binary files a/Data/systems/pf2e/packs/blood-lords-bestiary/000009.ldb and b/Data/systems/pf2e/packs/blood-lords-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/blood-lords-bestiary/000015.log b/Data/systems/pf2e/packs/blood-lords-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/blood-lords-bestiary/000015.log rename to Data/systems/pf2e/packs/blood-lords-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/blood-lords-bestiary/CURRENT b/Data/systems/pf2e/packs/blood-lords-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/blood-lords-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/blood-lords-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/blood-lords-bestiary/LOG b/Data/systems/pf2e/packs/blood-lords-bestiary/LOG index a4df8a8c..2b4ea079 100644 --- a/Data/systems/pf2e/packs/blood-lords-bestiary/LOG +++ b/Data/systems/pf2e/packs/blood-lords-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:09.881516 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:09.886245 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:09.886266 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:16.391312 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:16.398452 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:16.426394 ffff877ef0a0 Level-0 table #5: 2088469 bytes OK +2023/10/23-05:12:16.431334 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:16.431971 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/blood-lords-bestiary/LOG.old b/Data/systems/pf2e/packs/blood-lords-bestiary/LOG.old index f18b209e..8b69f523 100644 --- a/Data/systems/pf2e/packs/blood-lords-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/blood-lords-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.735285 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:10.740123 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:10.740146 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.479741 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.479756 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.481498 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.483796 ffff85fbf0a0 Manual compaction at level-0 from '!actors!07DkxPmw2du1xu16' @ 72057594037927935 : 1 .. '!actors.items!zw1uj88nmUrCf7iS.yw7bRJOAMVdTnVkG' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.566684 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/blood-lords-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/blood-lords-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..9ea41a7e Binary files /dev/null and b/Data/systems/pf2e/packs/blood-lords-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/blood-lords-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/blood-lords-bestiary/MANIFEST-000014 deleted file mode 100644 index 71045535..00000000 Binary files a/Data/systems/pf2e/packs/blood-lords-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/book-of-the-dead-bestiary/000009.ldb b/Data/systems/pf2e/packs/book-of-the-dead-bestiary/000005.ldb similarity index 95% rename from Data/systems/pf2e/packs/book-of-the-dead-bestiary/000009.ldb rename to Data/systems/pf2e/packs/book-of-the-dead-bestiary/000005.ldb index 808f065a..2c986e08 100644 Binary files a/Data/systems/pf2e/packs/book-of-the-dead-bestiary/000009.ldb and b/Data/systems/pf2e/packs/book-of-the-dead-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/book-of-the-dead-bestiary/000015.log b/Data/systems/pf2e/packs/book-of-the-dead-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/book-of-the-dead-bestiary/000015.log rename to Data/systems/pf2e/packs/book-of-the-dead-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/book-of-the-dead-bestiary/CURRENT b/Data/systems/pf2e/packs/book-of-the-dead-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/book-of-the-dead-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/book-of-the-dead-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/book-of-the-dead-bestiary/LOG b/Data/systems/pf2e/packs/book-of-the-dead-bestiary/LOG index 16dd67bf..2a7a28d6 100644 --- a/Data/systems/pf2e/packs/book-of-the-dead-bestiary/LOG +++ b/Data/systems/pf2e/packs/book-of-the-dead-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:09.865144 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:09.870607 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:09.870628 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:16.355499 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:16.359063 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:16.372565 ffff87fff0a0 Level-0 table #5: 1025867 bytes OK +2023/10/23-05:12:16.377917 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:16.378250 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/book-of-the-dead-bestiary/LOG.old b/Data/systems/pf2e/packs/book-of-the-dead-bestiary/LOG.old index 3d4f9597..55296493 100644 --- a/Data/systems/pf2e/packs/book-of-the-dead-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/book-of-the-dead-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.719885 ffff877ef0a0 Recovering log #7 -2023/10/20-07:41:10.725013 ffff877ef0a0 Delete type=3 #4 -2023/10/20-07:41:10.725037 ffff877ef0a0 Delete type=0 #7 -2023/10/20-07:49:07.477983 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.478003 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.479704 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.483670 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0PrrwvV1936eSCQy' @ 72057594037927935 : 1 .. '!actors.items!zqftTUpxqkdLx2IY.t4dd2bxdturlg45u' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.568358 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/book-of-the-dead-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/book-of-the-dead-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..8749b91f Binary files /dev/null and b/Data/systems/pf2e/packs/book-of-the-dead-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/book-of-the-dead-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/book-of-the-dead-bestiary/MANIFEST-000014 deleted file mode 100644 index f1602a7b..00000000 Binary files a/Data/systems/pf2e/packs/book-of-the-dead-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/boons-and-curses/000009.ldb b/Data/systems/pf2e/packs/boons-and-curses/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/boons-and-curses/000009.ldb rename to Data/systems/pf2e/packs/boons-and-curses/000005.ldb diff --git a/Data/systems/pf2e/packs/boons-and-curses/000015.log b/Data/systems/pf2e/packs/boons-and-curses/000006.log similarity index 100% rename from Data/systems/pf2e/packs/boons-and-curses/000015.log rename to Data/systems/pf2e/packs/boons-and-curses/000006.log diff --git a/Data/systems/pf2e/packs/boons-and-curses/CURRENT b/Data/systems/pf2e/packs/boons-and-curses/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/boons-and-curses/CURRENT +++ b/Data/systems/pf2e/packs/boons-and-curses/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/boons-and-curses/LOG b/Data/systems/pf2e/packs/boons-and-curses/LOG index 5843a86b..c6af7046 100644 --- a/Data/systems/pf2e/packs/boons-and-curses/LOG +++ b/Data/systems/pf2e/packs/boons-and-curses/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.773788 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.778681 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.778700 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:18.160492 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:18.160955 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:18.164310 ffff86fdf0a0 Level-0 table #5: 110817 bytes OK +2023/10/23-05:12:18.168646 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:18.168708 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/boons-and-curses/LOG.old b/Data/systems/pf2e/packs/boons-and-curses/LOG.old index 58b7582f..4441cf61 100644 --- a/Data/systems/pf2e/packs/boons-and-curses/LOG.old +++ b/Data/systems/pf2e/packs/boons-and-curses/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.661063 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.666019 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.666043 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.582860 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.582883 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.584725 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.587063 ffff85fbf0a0 Manual compaction at level-0 from '!items!02FtcdSA8tjFNmvD' @ 72057594037927935 : 1 .. '!items!zu2yJaXxOus4tNqd' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.568667 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/boons-and-curses/MANIFEST-000004 b/Data/systems/pf2e/packs/boons-and-curses/MANIFEST-000004 new file mode 100644 index 00000000..b80b5952 Binary files /dev/null and b/Data/systems/pf2e/packs/boons-and-curses/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/boons-and-curses/MANIFEST-000014 b/Data/systems/pf2e/packs/boons-and-curses/MANIFEST-000014 deleted file mode 100644 index de0627dc..00000000 Binary files a/Data/systems/pf2e/packs/boons-and-curses/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/campaign-effects/000009.ldb b/Data/systems/pf2e/packs/campaign-effects/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/campaign-effects/000009.ldb rename to Data/systems/pf2e/packs/campaign-effects/000005.ldb diff --git a/Data/systems/pf2e/packs/campaign-effects/000015.log b/Data/systems/pf2e/packs/campaign-effects/000006.log similarity index 100% rename from Data/systems/pf2e/packs/campaign-effects/000015.log rename to Data/systems/pf2e/packs/campaign-effects/000006.log diff --git a/Data/systems/pf2e/packs/campaign-effects/CURRENT b/Data/systems/pf2e/packs/campaign-effects/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/campaign-effects/CURRENT +++ b/Data/systems/pf2e/packs/campaign-effects/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/campaign-effects/LOG b/Data/systems/pf2e/packs/campaign-effects/LOG index d7bb8acf..cc1bd2b2 100644 --- a/Data/systems/pf2e/packs/campaign-effects/LOG +++ b/Data/systems/pf2e/packs/campaign-effects/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.787818 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.792857 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.792876 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:18.179768 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:18.179855 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:18.182067 ffff86fdf0a0 Level-0 table #5: 20207 bytes OK +2023/10/23-05:12:18.186241 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:18.186274 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/campaign-effects/LOG.old b/Data/systems/pf2e/packs/campaign-effects/LOG.old index a9deaef1..c21c92d0 100644 --- a/Data/systems/pf2e/packs/campaign-effects/LOG.old +++ b/Data/systems/pf2e/packs/campaign-effects/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.675266 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.679931 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.679953 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.587179 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.587200 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.589169 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.592977 ffff85fbf0a0 Manual compaction at level-0 from '!items!1iIObOrXUGA3RwQ9' @ 72057594037927935 : 1 .. '!items!yJWWTfZkAF4raa4R' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.591426 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/campaign-effects/MANIFEST-000004 b/Data/systems/pf2e/packs/campaign-effects/MANIFEST-000004 new file mode 100644 index 00000000..082737fc Binary files /dev/null and b/Data/systems/pf2e/packs/campaign-effects/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/campaign-effects/MANIFEST-000014 b/Data/systems/pf2e/packs/campaign-effects/MANIFEST-000014 deleted file mode 100644 index 11c35f52..00000000 Binary files a/Data/systems/pf2e/packs/campaign-effects/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/classes/000009.ldb b/Data/systems/pf2e/packs/classes/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/classes/000009.ldb rename to Data/systems/pf2e/packs/classes/000005.ldb diff --git a/Data/systems/pf2e/packs/classes/000015.log b/Data/systems/pf2e/packs/classes/000006.log similarity index 100% rename from Data/systems/pf2e/packs/classes/000015.log rename to Data/systems/pf2e/packs/classes/000006.log diff --git a/Data/systems/pf2e/packs/classes/CURRENT b/Data/systems/pf2e/packs/classes/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/classes/CURRENT +++ b/Data/systems/pf2e/packs/classes/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/classes/LOG b/Data/systems/pf2e/packs/classes/LOG index 9891ed79..b78ce1bb 100644 --- a/Data/systems/pf2e/packs/classes/LOG +++ b/Data/systems/pf2e/packs/classes/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.676511 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.681619 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.681638 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:17.967974 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:17.968173 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:17.970927 ffff86fdf0a0 Level-0 table #5: 61863 bytes OK +2023/10/23-05:12:17.975372 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:17.975414 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/classes/LOG.old b/Data/systems/pf2e/packs/classes/LOG.old index 5ed4c08e..cb5936b0 100644 --- a/Data/systems/pf2e/packs/classes/LOG.old +++ b/Data/systems/pf2e/packs/classes/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.560373 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.565471 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.565493 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.568972 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.568992 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.570862 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.574615 ffff85fbf0a0 Manual compaction at level-0 from '!items!15Yc1r6s9CEhSTMe' @ 72057594037927935 : 1 .. '!items!x8iwnpdLbfcoZkHA' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.571536 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/classes/MANIFEST-000004 b/Data/systems/pf2e/packs/classes/MANIFEST-000004 new file mode 100644 index 00000000..ca697d53 Binary files /dev/null and b/Data/systems/pf2e/packs/classes/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/classes/MANIFEST-000014 b/Data/systems/pf2e/packs/classes/MANIFEST-000014 deleted file mode 100644 index 6669bb38..00000000 Binary files a/Data/systems/pf2e/packs/classes/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/classfeatures/000009.ldb b/Data/systems/pf2e/packs/classfeatures/000005.ldb similarity index 98% rename from Data/systems/pf2e/packs/classfeatures/000009.ldb rename to Data/systems/pf2e/packs/classfeatures/000005.ldb index 2760d2b0..a97c8476 100644 Binary files a/Data/systems/pf2e/packs/classfeatures/000009.ldb and b/Data/systems/pf2e/packs/classfeatures/000005.ldb differ diff --git a/Data/systems/pf2e/packs/classfeatures/000015.log b/Data/systems/pf2e/packs/classfeatures/000006.log similarity index 100% rename from Data/systems/pf2e/packs/classfeatures/000015.log rename to Data/systems/pf2e/packs/classfeatures/000006.log diff --git a/Data/systems/pf2e/packs/classfeatures/CURRENT b/Data/systems/pf2e/packs/classfeatures/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/classfeatures/CURRENT +++ b/Data/systems/pf2e/packs/classfeatures/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/classfeatures/LOG b/Data/systems/pf2e/packs/classfeatures/LOG index 5606ac0c..34faf1b8 100644 --- a/Data/systems/pf2e/packs/classfeatures/LOG +++ b/Data/systems/pf2e/packs/classfeatures/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.689243 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.694203 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.694224 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:17.977279 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:17.979045 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:17.987359 ffff877ef0a0 Level-0 table #5: 548690 bytes OK +2023/10/23-05:12:17.992144 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:17.992345 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/classfeatures/LOG.old b/Data/systems/pf2e/packs/classfeatures/LOG.old index 95b587d5..984df50a 100644 --- a/Data/systems/pf2e/packs/classfeatures/LOG.old +++ b/Data/systems/pf2e/packs/classfeatures/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.573145 ffff877ef0a0 Recovering log #7 -2023/10/20-07:41:11.578164 ffff877ef0a0 Delete type=3 #4 -2023/10/20-07:41:11.578186 ffff877ef0a0 Delete type=0 #7 -2023/10/20-07:49:07.571022 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.571043 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.572905 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.576628 ffff85fbf0a0 Manual compaction at level-0 from '!items!09iL38CZZEa0q0Mt' @ 72057594037927935 : 1 .. '!items!zy0toWeGIeQstbT4' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.591615 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/classfeatures/MANIFEST-000004 b/Data/systems/pf2e/packs/classfeatures/MANIFEST-000004 new file mode 100644 index 00000000..613c0198 Binary files /dev/null and b/Data/systems/pf2e/packs/classfeatures/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/classfeatures/MANIFEST-000014 b/Data/systems/pf2e/packs/classfeatures/MANIFEST-000014 deleted file mode 100644 index 5c5c5877..00000000 Binary files a/Data/systems/pf2e/packs/classfeatures/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/conditions/000009.ldb b/Data/systems/pf2e/packs/conditions/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/conditions/000009.ldb rename to Data/systems/pf2e/packs/conditions/000005.ldb diff --git a/Data/systems/pf2e/packs/conditions/000015.log b/Data/systems/pf2e/packs/conditions/000006.log similarity index 100% rename from Data/systems/pf2e/packs/conditions/000015.log rename to Data/systems/pf2e/packs/conditions/000006.log diff --git a/Data/systems/pf2e/packs/conditions/CURRENT b/Data/systems/pf2e/packs/conditions/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/conditions/CURRENT +++ b/Data/systems/pf2e/packs/conditions/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/conditions/LOG b/Data/systems/pf2e/packs/conditions/LOG index e31e339d..19651f18 100644 --- a/Data/systems/pf2e/packs/conditions/LOG +++ b/Data/systems/pf2e/packs/conditions/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.781259 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.785960 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.785978 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:18.171228 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:18.171343 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:18.173652 ffff877ef0a0 Level-0 table #5: 26788 bytes OK +2023/10/23-05:12:18.178009 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:18.178042 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/conditions/LOG.old b/Data/systems/pf2e/packs/conditions/LOG.old index d026d09c..b6f15089 100644 --- a/Data/systems/pf2e/packs/conditions/LOG.old +++ b/Data/systems/pf2e/packs/conditions/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.668529 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.673514 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.673536 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.585005 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.585023 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.587024 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.591053 ffff85fbf0a0 Manual compaction at level-0 from '!items!1wQY3JYyhMYeeV2G' @ 72057594037927935 : 1 .. '!items!zJxUflt9np0q4yML' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.590283 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/conditions/MANIFEST-000004 b/Data/systems/pf2e/packs/conditions/MANIFEST-000004 new file mode 100644 index 00000000..fbf3e784 Binary files /dev/null and b/Data/systems/pf2e/packs/conditions/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/conditions/MANIFEST-000014 b/Data/systems/pf2e/packs/conditions/MANIFEST-000014 deleted file mode 100644 index 9b539c02..00000000 Binary files a/Data/systems/pf2e/packs/conditions/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/criticaldeck/000009.ldb b/Data/systems/pf2e/packs/criticaldeck/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/criticaldeck/000009.ldb rename to Data/systems/pf2e/packs/criticaldeck/000005.ldb diff --git a/Data/systems/pf2e/packs/criticaldeck/000015.log b/Data/systems/pf2e/packs/criticaldeck/000006.log similarity index 100% rename from Data/systems/pf2e/packs/criticaldeck/000015.log rename to Data/systems/pf2e/packs/criticaldeck/000006.log diff --git a/Data/systems/pf2e/packs/criticaldeck/CURRENT b/Data/systems/pf2e/packs/criticaldeck/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/criticaldeck/CURRENT +++ b/Data/systems/pf2e/packs/criticaldeck/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/criticaldeck/LOG b/Data/systems/pf2e/packs/criticaldeck/LOG index c5d0b76e..99d97c7f 100644 --- a/Data/systems/pf2e/packs/criticaldeck/LOG +++ b/Data/systems/pf2e/packs/criticaldeck/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.943523 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.948744 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.948765 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:18.515276 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:18.515543 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:18.518226 ffff877ef0a0 Level-0 table #5: 59661 bytes OK +2023/10/23-05:12:18.522548 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:18.522593 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/criticaldeck/LOG.old b/Data/systems/pf2e/packs/criticaldeck/LOG.old index 0e80387a..f6515131 100644 --- a/Data/systems/pf2e/packs/criticaldeck/LOG.old +++ b/Data/systems/pf2e/packs/criticaldeck/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.811661 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.817058 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.817080 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.608429 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.608450 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.610163 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.614022 ffff85fbf0a0 Manual compaction at level-0 from '!journal!0BESWYMP9vEbG3cr' @ 72057594037927935 : 1 .. '!journal.pages!yBE9e9l5KW7SdHZH.AHnMn8nDzBU8XiDZ' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.593081 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/criticaldeck/MANIFEST-000004 b/Data/systems/pf2e/packs/criticaldeck/MANIFEST-000004 new file mode 100644 index 00000000..19f6150d Binary files /dev/null and b/Data/systems/pf2e/packs/criticaldeck/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/criticaldeck/MANIFEST-000014 b/Data/systems/pf2e/packs/criticaldeck/MANIFEST-000014 deleted file mode 100644 index 12e6bc0f..00000000 Binary files a/Data/systems/pf2e/packs/criticaldeck/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/000009.ldb b/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/000009.ldb rename to Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/000005.ldb diff --git a/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/000015.log b/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/000015.log rename to Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/CURRENT b/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/LOG b/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/LOG index b622aaa9..ac62d951 100644 --- a/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/LOG +++ b/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.557687 ffff867cf0a0 Recovering log #12 -2023/10/20-07:55:10.563928 ffff867cf0a0 Delete type=0 #12 -2023/10/20-07:55:10.563950 ffff867cf0a0 Delete type=3 #10 +2023/10/23-05:12:17.775800 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:17.776709 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:17.781975 ffff877ef0a0 Level-0 table #5: 261283 bytes OK +2023/10/23-05:12:17.786690 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:17.786826 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/LOG.old b/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/LOG.old index 58792e6a..7a26f61b 100644 --- a/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.474384 ffff86fdf0a0 Recovering log #7 -2023/10/20-07:41:11.479848 ffff86fdf0a0 Delete type=3 #4 -2023/10/20-07:41:11.479872 ffff86fdf0a0 Delete type=0 #7 -2023/10/20-07:49:07.553193 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.553212 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.555083 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.558905 ffff85fbf0a0 Manual compaction at level-0 from '!actors!02EH7sCwxaLi28Rw' @ 72057594037927935 : 1 .. '!actors.items!zxUgsY4fqAoweoEp.wzN8J4osvRa61D9u' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.594411 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..c67764ad Binary files /dev/null and b/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/MANIFEST-000014 deleted file mode 100644 index ee879f53..00000000 Binary files a/Data/systems/pf2e/packs/crown-of-the-kobold-king-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/deities/000009.ldb b/Data/systems/pf2e/packs/deities/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/deities/000009.ldb rename to Data/systems/pf2e/packs/deities/000005.ldb diff --git a/Data/systems/pf2e/packs/deities/000015.log b/Data/systems/pf2e/packs/deities/000006.log similarity index 100% rename from Data/systems/pf2e/packs/deities/000015.log rename to Data/systems/pf2e/packs/deities/000006.log diff --git a/Data/systems/pf2e/packs/deities/CURRENT b/Data/systems/pf2e/packs/deities/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/deities/CURRENT +++ b/Data/systems/pf2e/packs/deities/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/deities/LOG b/Data/systems/pf2e/packs/deities/LOG index a3802d61..7d98cc88 100644 --- a/Data/systems/pf2e/packs/deities/LOG +++ b/Data/systems/pf2e/packs/deities/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.885804 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.891440 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.891461 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:18.390209 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:18.391163 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:18.397723 ffff877ef0a0 Level-0 table #5: 361655 bytes OK +2023/10/23-05:12:18.402442 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:18.402580 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/deities/LOG.old b/Data/systems/pf2e/packs/deities/LOG.old index 1dc407a1..c4b68f6b 100644 --- a/Data/systems/pf2e/packs/deities/LOG.old +++ b/Data/systems/pf2e/packs/deities/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.755076 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.760027 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.760050 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.600890 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.600908 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.602589 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.606318 ffff85fbf0a0 Manual compaction at level-0 from '!items!0BH54ZVR8NcrGlMu' @ 72057594037927935 : 1 .. '!items!zzhYFcShT9JoE2Mp' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.594593 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/deities/MANIFEST-000004 b/Data/systems/pf2e/packs/deities/MANIFEST-000004 new file mode 100644 index 00000000..014352aa Binary files /dev/null and b/Data/systems/pf2e/packs/deities/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/deities/MANIFEST-000014 b/Data/systems/pf2e/packs/deities/MANIFEST-000014 deleted file mode 100644 index 0393d4bc..00000000 Binary files a/Data/systems/pf2e/packs/deities/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/equipment-effects/000009.ldb b/Data/systems/pf2e/packs/equipment-effects/000005.ldb similarity index 68% rename from Data/systems/pf2e/packs/equipment-effects/000009.ldb rename to Data/systems/pf2e/packs/equipment-effects/000005.ldb index c6d0e6ab..3311ab77 100644 Binary files a/Data/systems/pf2e/packs/equipment-effects/000009.ldb and b/Data/systems/pf2e/packs/equipment-effects/000005.ldb differ diff --git a/Data/systems/pf2e/packs/equipment-effects/000015.log b/Data/systems/pf2e/packs/equipment-effects/000006.log similarity index 100% rename from Data/systems/pf2e/packs/equipment-effects/000015.log rename to Data/systems/pf2e/packs/equipment-effects/000006.log diff --git a/Data/systems/pf2e/packs/equipment-effects/CURRENT b/Data/systems/pf2e/packs/equipment-effects/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/equipment-effects/CURRENT +++ b/Data/systems/pf2e/packs/equipment-effects/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/equipment-effects/LOG b/Data/systems/pf2e/packs/equipment-effects/LOG index 16832d18..b615d835 100644 --- a/Data/systems/pf2e/packs/equipment-effects/LOG +++ b/Data/systems/pf2e/packs/equipment-effects/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.802279 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.807702 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.807721 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:18.187912 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:18.189010 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:18.194225 ffff877ef0a0 Level-0 table #5: 269317 bytes OK +2023/10/23-05:12:18.198673 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:18.198826 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/equipment-effects/LOG.old b/Data/systems/pf2e/packs/equipment-effects/LOG.old index 962e7113..864fb0c5 100644 --- a/Data/systems/pf2e/packs/equipment-effects/LOG.old +++ b/Data/systems/pf2e/packs/equipment-effects/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.681653 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.686379 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.686401 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.589207 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.589220 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.591017 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.593090 ffff85fbf0a0 Manual compaction at level-0 from '!items!02LNcIl70TTy9XS1' @ 72057594037927935 : 1 .. '!items!ztxW3lBPRcesF7wK' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.596539 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/equipment-effects/MANIFEST-000004 b/Data/systems/pf2e/packs/equipment-effects/MANIFEST-000004 new file mode 100644 index 00000000..e3b81e3a Binary files /dev/null and b/Data/systems/pf2e/packs/equipment-effects/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/equipment-effects/MANIFEST-000014 b/Data/systems/pf2e/packs/equipment-effects/MANIFEST-000014 deleted file mode 100644 index afc793d1..00000000 Binary files a/Data/systems/pf2e/packs/equipment-effects/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/equipment/000005.ldb b/Data/systems/pf2e/packs/equipment/000005.ldb new file mode 100644 index 00000000..b7765ae1 Binary files /dev/null and b/Data/systems/pf2e/packs/equipment/000005.ldb differ diff --git a/Data/systems/pf2e/packs/equipment/000017.log b/Data/systems/pf2e/packs/equipment/000006.log similarity index 100% rename from Data/systems/pf2e/packs/equipment/000017.log rename to Data/systems/pf2e/packs/equipment/000006.log diff --git a/Data/systems/pf2e/packs/equipment/000009.ldb b/Data/systems/pf2e/packs/equipment/000009.ldb deleted file mode 100644 index 0a3328eb..00000000 Binary files a/Data/systems/pf2e/packs/equipment/000009.ldb and /dev/null differ diff --git a/Data/systems/pf2e/packs/equipment/000010.ldb b/Data/systems/pf2e/packs/equipment/000010.ldb deleted file mode 100644 index 1c332348..00000000 Binary files a/Data/systems/pf2e/packs/equipment/000010.ldb and /dev/null differ diff --git a/Data/systems/pf2e/packs/equipment/000011.ldb b/Data/systems/pf2e/packs/equipment/000011.ldb deleted file mode 100644 index 9fb90dac..00000000 Binary files a/Data/systems/pf2e/packs/equipment/000011.ldb and /dev/null differ diff --git a/Data/systems/pf2e/packs/equipment/CURRENT b/Data/systems/pf2e/packs/equipment/CURRENT index 32108be6..cacca757 100644 --- a/Data/systems/pf2e/packs/equipment/CURRENT +++ b/Data/systems/pf2e/packs/equipment/CURRENT @@ -1 +1 @@ -MANIFEST-000016 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/equipment/LOG b/Data/systems/pf2e/packs/equipment/LOG index e424ad41..de13e228 100644 --- a/Data/systems/pf2e/packs/equipment/LOG +++ b/Data/systems/pf2e/packs/equipment/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.851749 ffff86fdf0a0 Recovering log #14 -2023/10/20-07:55:10.857112 ffff86fdf0a0 Delete type=0 #14 -2023/10/20-07:55:10.857131 ffff86fdf0a0 Delete type=3 #12 +2023/10/23-05:12:18.265008 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:18.281652 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:18.352015 ffff86fdf0a0 Level-0 table #5: 4822636 bytes OK +2023/10/23-05:12:18.357882 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:18.359850 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/equipment/LOG.old b/Data/systems/pf2e/packs/equipment/LOG.old index 67eb18e2..5681ea2e 100644 --- a/Data/systems/pf2e/packs/equipment/LOG.old +++ b/Data/systems/pf2e/packs/equipment/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.722422 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.727273 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.727296 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.598865 ffff85fbf0a0 Level-0 table #15: started -2023/10/20-07:49:07.598888 ffff85fbf0a0 Level-0 table #15: 0 bytes OK -2023/10/20-07:49:07.600611 ffff85fbf0a0 Delete type=0 #13 -2023/10/20-07:49:07.602626 ffff85fbf0a0 Manual compaction at level-0 from '!items!00gDg8WcPv3TKC9N' @ 72057594037927935 : 1 .. '!items!zzLGE9zmSu3yMEOq' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.594724 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/equipment/MANIFEST-000004 b/Data/systems/pf2e/packs/equipment/MANIFEST-000004 new file mode 100644 index 00000000..fbb0ac16 Binary files /dev/null and b/Data/systems/pf2e/packs/equipment/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/equipment/MANIFEST-000016 b/Data/systems/pf2e/packs/equipment/MANIFEST-000016 deleted file mode 100644 index d7e476dd..00000000 Binary files a/Data/systems/pf2e/packs/equipment/MANIFEST-000016 and /dev/null differ diff --git a/Data/systems/pf2e/packs/extinction-curse-bestiary/000009.ldb b/Data/systems/pf2e/packs/extinction-curse-bestiary/000005.ldb similarity index 96% rename from Data/systems/pf2e/packs/extinction-curse-bestiary/000009.ldb rename to Data/systems/pf2e/packs/extinction-curse-bestiary/000005.ldb index bb04f453..a0cfdafb 100644 Binary files a/Data/systems/pf2e/packs/extinction-curse-bestiary/000009.ldb and b/Data/systems/pf2e/packs/extinction-curse-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/extinction-curse-bestiary/000015.log b/Data/systems/pf2e/packs/extinction-curse-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/extinction-curse-bestiary/000015.log rename to Data/systems/pf2e/packs/extinction-curse-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/extinction-curse-bestiary/CURRENT b/Data/systems/pf2e/packs/extinction-curse-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/extinction-curse-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/extinction-curse-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/extinction-curse-bestiary/LOG b/Data/systems/pf2e/packs/extinction-curse-bestiary/LOG index b0847712..2dba1676 100644 --- a/Data/systems/pf2e/packs/extinction-curse-bestiary/LOG +++ b/Data/systems/pf2e/packs/extinction-curse-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:09.914338 ffff867cf0a0 Recovering log #12 -2023/10/20-07:55:09.919331 ffff867cf0a0 Delete type=0 #12 -2023/10/20-07:55:09.919352 ffff867cf0a0 Delete type=3 #10 +2023/10/23-05:12:16.467911 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:16.474456 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:16.498399 ffff877ef0a0 Level-0 table #5: 1837588 bytes OK +2023/10/23-05:12:16.503025 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:16.503683 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/extinction-curse-bestiary/LOG.old b/Data/systems/pf2e/packs/extinction-curse-bestiary/LOG.old index 9584f7bb..6effdac1 100644 --- a/Data/systems/pf2e/packs/extinction-curse-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/extinction-curse-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.769238 ffff86fdf0a0 Recovering log #7 -2023/10/20-07:41:10.774325 ffff86fdf0a0 Delete type=3 #4 -2023/10/20-07:41:10.774350 ffff86fdf0a0 Delete type=0 #7 -2023/10/20-07:49:07.483892 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.483914 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.485908 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.489584 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0VzVpqN3Yp0IY3C1' @ 72057594037927935 : 1 .. '!actors.items!zPXXUNE3m9VdrF9z.vGPRZAcP9sO1oSWb' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.597494 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/extinction-curse-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/extinction-curse-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..d3e9dfdf Binary files /dev/null and b/Data/systems/pf2e/packs/extinction-curse-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/extinction-curse-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/extinction-curse-bestiary/MANIFEST-000014 deleted file mode 100644 index d8cfce55..00000000 Binary files a/Data/systems/pf2e/packs/extinction-curse-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/fall-of-plaguestone/000009.ldb b/Data/systems/pf2e/packs/fall-of-plaguestone/000005.ldb similarity index 71% rename from Data/systems/pf2e/packs/fall-of-plaguestone/000009.ldb rename to Data/systems/pf2e/packs/fall-of-plaguestone/000005.ldb index 955fecd0..46e96e78 100644 Binary files a/Data/systems/pf2e/packs/fall-of-plaguestone/000009.ldb and b/Data/systems/pf2e/packs/fall-of-plaguestone/000005.ldb differ diff --git a/Data/systems/pf2e/packs/fall-of-plaguestone/000015.log b/Data/systems/pf2e/packs/fall-of-plaguestone/000006.log similarity index 100% rename from Data/systems/pf2e/packs/fall-of-plaguestone/000015.log rename to Data/systems/pf2e/packs/fall-of-plaguestone/000006.log diff --git a/Data/systems/pf2e/packs/fall-of-plaguestone/CURRENT b/Data/systems/pf2e/packs/fall-of-plaguestone/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/fall-of-plaguestone/CURRENT +++ b/Data/systems/pf2e/packs/fall-of-plaguestone/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/fall-of-plaguestone/LOG b/Data/systems/pf2e/packs/fall-of-plaguestone/LOG index c8b4aba8..75868466 100644 --- a/Data/systems/pf2e/packs/fall-of-plaguestone/LOG +++ b/Data/systems/pf2e/packs/fall-of-plaguestone/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:09.936639 ffff877ef0a0 Recovering log #12 -2023/10/20-07:55:09.941998 ffff877ef0a0 Delete type=0 #12 -2023/10/20-07:55:09.942019 ffff877ef0a0 Delete type=3 #10 +2023/10/23-05:12:16.525236 ffff867cf0a0 Recovering log #3 +2023/10/23-05:12:16.525676 ffff867cf0a0 Level-0 table #5: started +2023/10/23-05:12:16.529281 ffff867cf0a0 Level-0 table #5: 109654 bytes OK +2023/10/23-05:12:16.533525 ffff867cf0a0 Delete type=0 #3 +2023/10/23-05:12:16.533589 ffff867cf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/fall-of-plaguestone/LOG.old b/Data/systems/pf2e/packs/fall-of-plaguestone/LOG.old index 41924960..3d9366a6 100644 --- a/Data/systems/pf2e/packs/fall-of-plaguestone/LOG.old +++ b/Data/systems/pf2e/packs/fall-of-plaguestone/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.792599 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:10.797544 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:10.797568 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.486073 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.486095 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.487879 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.491474 ffff85fbf0a0 Manual compaction at level-0 from '!actors!1Nr9cgWHMn8KtiXe' @ 72057594037927935 : 1 .. '!actors.items!yFfT9yPbUzldlhxN.xiU6BoUEXG3kg8X3' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.597412 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/fall-of-plaguestone/MANIFEST-000004 b/Data/systems/pf2e/packs/fall-of-plaguestone/MANIFEST-000004 new file mode 100644 index 00000000..a4273685 Binary files /dev/null and b/Data/systems/pf2e/packs/fall-of-plaguestone/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/fall-of-plaguestone/MANIFEST-000014 b/Data/systems/pf2e/packs/fall-of-plaguestone/MANIFEST-000014 deleted file mode 100644 index ed1f7311..00000000 Binary files a/Data/systems/pf2e/packs/fall-of-plaguestone/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/familiar-abilities/000009.ldb b/Data/systems/pf2e/packs/familiar-abilities/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/familiar-abilities/000009.ldb rename to Data/systems/pf2e/packs/familiar-abilities/000005.ldb diff --git a/Data/systems/pf2e/packs/familiar-abilities/000015.log b/Data/systems/pf2e/packs/familiar-abilities/000006.log similarity index 100% rename from Data/systems/pf2e/packs/familiar-abilities/000015.log rename to Data/systems/pf2e/packs/familiar-abilities/000006.log diff --git a/Data/systems/pf2e/packs/familiar-abilities/CURRENT b/Data/systems/pf2e/packs/familiar-abilities/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/familiar-abilities/CURRENT +++ b/Data/systems/pf2e/packs/familiar-abilities/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/familiar-abilities/LOG b/Data/systems/pf2e/packs/familiar-abilities/LOG index ce6b7983..2c0b50c3 100644 --- a/Data/systems/pf2e/packs/familiar-abilities/LOG +++ b/Data/systems/pf2e/packs/familiar-abilities/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.699191 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.704678 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.704699 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:18.000463 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:18.000613 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:18.002981 ffff86fdf0a0 Level-0 table #5: 29776 bytes OK +2023/10/23-05:12:18.007693 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:18.007733 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/familiar-abilities/LOG.old b/Data/systems/pf2e/packs/familiar-abilities/LOG.old index 52d7af2b..3563df08 100644 --- a/Data/systems/pf2e/packs/familiar-abilities/LOG.old +++ b/Data/systems/pf2e/packs/familiar-abilities/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.583066 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.588550 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.588573 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.572943 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.572957 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.574578 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.576749 ffff85fbf0a0 Manual compaction at level-0 from '!items!0Xrkk46IM43iI1Fv' @ 72057594037927935 : 1 .. '!items!zyMRLQnFCQVpltiR' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.597661 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/familiar-abilities/MANIFEST-000004 b/Data/systems/pf2e/packs/familiar-abilities/MANIFEST-000004 new file mode 100644 index 00000000..b7e759d3 Binary files /dev/null and b/Data/systems/pf2e/packs/familiar-abilities/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/familiar-abilities/MANIFEST-000014 b/Data/systems/pf2e/packs/familiar-abilities/MANIFEST-000014 deleted file mode 100644 index 6607de63..00000000 Binary files a/Data/systems/pf2e/packs/familiar-abilities/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/feat-effects/000009.ldb b/Data/systems/pf2e/packs/feat-effects/000005.ldb similarity index 53% rename from Data/systems/pf2e/packs/feat-effects/000009.ldb rename to Data/systems/pf2e/packs/feat-effects/000005.ldb index 463fc1a8..0d163111 100644 Binary files a/Data/systems/pf2e/packs/feat-effects/000009.ldb and b/Data/systems/pf2e/packs/feat-effects/000005.ldb differ diff --git a/Data/systems/pf2e/packs/feat-effects/000015.log b/Data/systems/pf2e/packs/feat-effects/000006.log similarity index 100% rename from Data/systems/pf2e/packs/feat-effects/000015.log rename to Data/systems/pf2e/packs/feat-effects/000006.log diff --git a/Data/systems/pf2e/packs/feat-effects/CURRENT b/Data/systems/pf2e/packs/feat-effects/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/feat-effects/CURRENT +++ b/Data/systems/pf2e/packs/feat-effects/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/feat-effects/LOG b/Data/systems/pf2e/packs/feat-effects/LOG index d912fa72..6e918d8d 100644 --- a/Data/systems/pf2e/packs/feat-effects/LOG +++ b/Data/systems/pf2e/packs/feat-effects/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.821244 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.827175 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.827194 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:18.218132 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:18.219062 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:18.225034 ffff877ef0a0 Level-0 table #5: 271193 bytes OK +2023/10/23-05:12:18.229958 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:18.230069 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/feat-effects/LOG.old b/Data/systems/pf2e/packs/feat-effects/LOG.old index 1705b4df..07d3c191 100644 --- a/Data/systems/pf2e/packs/feat-effects/LOG.old +++ b/Data/systems/pf2e/packs/feat-effects/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.698511 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.703265 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.703288 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.593177 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.593195 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.594994 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.598746 ffff85fbf0a0 Manual compaction at level-0 from '!items!09oP0FBBAhXOS4JW' @ 72057594037927935 : 1 .. '!items!zzC2qZwEKf4Ja3xD' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.600341 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/feat-effects/MANIFEST-000004 b/Data/systems/pf2e/packs/feat-effects/MANIFEST-000004 new file mode 100644 index 00000000..390cb8bd Binary files /dev/null and b/Data/systems/pf2e/packs/feat-effects/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/feat-effects/MANIFEST-000014 b/Data/systems/pf2e/packs/feat-effects/MANIFEST-000014 deleted file mode 100644 index a21c22a9..00000000 Binary files a/Data/systems/pf2e/packs/feat-effects/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/feats/000009.ldb b/Data/systems/pf2e/packs/feats/000005.ldb similarity index 72% rename from Data/systems/pf2e/packs/feats/000009.ldb rename to Data/systems/pf2e/packs/feats/000005.ldb index eaa30ede..3987072c 100644 Binary files a/Data/systems/pf2e/packs/feats/000009.ldb and b/Data/systems/pf2e/packs/feats/000005.ldb differ diff --git a/Data/systems/pf2e/packs/feats/000016.log b/Data/systems/pf2e/packs/feats/000006.log similarity index 100% rename from Data/systems/pf2e/packs/feats/000016.log rename to Data/systems/pf2e/packs/feats/000006.log diff --git a/Data/systems/pf2e/packs/feats/000010.ldb b/Data/systems/pf2e/packs/feats/000010.ldb deleted file mode 100644 index aaa397fe..00000000 Binary files a/Data/systems/pf2e/packs/feats/000010.ldb and /dev/null differ diff --git a/Data/systems/pf2e/packs/feats/CURRENT b/Data/systems/pf2e/packs/feats/CURRENT index 42c62b67..cacca757 100644 --- a/Data/systems/pf2e/packs/feats/CURRENT +++ b/Data/systems/pf2e/packs/feats/CURRENT @@ -1 +1 @@ -MANIFEST-000015 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/feats/LOG b/Data/systems/pf2e/packs/feats/LOG index 32ea710c..bdeebceb 100644 --- a/Data/systems/pf2e/packs/feats/LOG +++ b/Data/systems/pf2e/packs/feats/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.706738 ffff87fff0a0 Recovering log #13 -2023/10/20-07:55:10.711900 ffff87fff0a0 Delete type=0 #13 -2023/10/20-07:55:10.711920 ffff87fff0a0 Delete type=3 #11 +2023/10/23-05:12:18.009750 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:18.019638 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:18.062283 ffff877ef0a0 Level-0 table #5: 2834112 bytes OK +2023/10/23-05:12:18.067236 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:18.068161 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/feats/LOG.old b/Data/systems/pf2e/packs/feats/LOG.old index 465e1b13..3b137b8c 100644 --- a/Data/systems/pf2e/packs/feats/LOG.old +++ b/Data/systems/pf2e/packs/feats/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.593316 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.598664 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.598687 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.574732 ffff85fbf0a0 Level-0 table #14: started -2023/10/20-07:49:07.574753 ffff85fbf0a0 Level-0 table #14: 0 bytes OK -2023/10/20-07:49:07.576589 ffff85fbf0a0 Delete type=0 #12 -2023/10/20-07:49:07.578950 ffff85fbf0a0 Manual compaction at level-0 from '!items!00OnDt8UEMwfoYWH' @ 72057594037927935 : 1 .. '!items!zzMugLCUkQQPa2qT' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.600675 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/feats/MANIFEST-000004 b/Data/systems/pf2e/packs/feats/MANIFEST-000004 new file mode 100644 index 00000000..43257b3f Binary files /dev/null and b/Data/systems/pf2e/packs/feats/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/feats/MANIFEST-000015 b/Data/systems/pf2e/packs/feats/MANIFEST-000015 deleted file mode 100644 index 178864af..00000000 Binary files a/Data/systems/pf2e/packs/feats/MANIFEST-000015 and /dev/null differ diff --git a/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/000009.ldb b/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/000005.ldb similarity index 80% rename from Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/000009.ldb rename to Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/000005.ldb index d8b7ce28..6638b395 100644 Binary files a/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/000009.ldb and b/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/000015.log b/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/000015.log rename to Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/CURRENT b/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/LOG b/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/LOG index 3cc855e9..2b94088c 100644 --- a/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/LOG +++ b/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:09.945135 ffff867cf0a0 Recovering log #12 -2023/10/20-07:55:09.949913 ffff867cf0a0 Delete type=0 #12 -2023/10/20-07:55:09.949933 ffff867cf0a0 Delete type=3 #10 +2023/10/23-05:12:16.536756 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:16.543073 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:16.566300 ffff877ef0a0 Level-0 table #5: 1768356 bytes OK +2023/10/23-05:12:16.571964 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:16.572535 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/LOG.old b/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/LOG.old index af68a758..c42c16e4 100644 --- a/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.800866 ffff86fdf0a0 Recovering log #7 -2023/10/20-07:41:10.805686 ffff86fdf0a0 Delete type=3 #4 -2023/10/20-07:41:10.805709 ffff86fdf0a0 Delete type=0 #7 -2023/10/20-07:49:07.487915 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.487929 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.489547 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.491623 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0N4ugHFs5GYllcMA' @ 72057594037927935 : 1 .. '!actors.items!zpXQHbe037haBVmD.vHgfbthW5N53w1vA' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.601622 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..56115e16 Binary files /dev/null and b/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/MANIFEST-000014 deleted file mode 100644 index 4915f93d..00000000 Binary files a/Data/systems/pf2e/packs/fists-of-the-ruby-phoenix-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/gatewalkers-bestiary/000009.ldb b/Data/systems/pf2e/packs/gatewalkers-bestiary/000005.ldb similarity index 97% rename from Data/systems/pf2e/packs/gatewalkers-bestiary/000009.ldb rename to Data/systems/pf2e/packs/gatewalkers-bestiary/000005.ldb index 3227b0e8..acbc8a66 100644 Binary files a/Data/systems/pf2e/packs/gatewalkers-bestiary/000009.ldb and b/Data/systems/pf2e/packs/gatewalkers-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/gatewalkers-bestiary/000015.log b/Data/systems/pf2e/packs/gatewalkers-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/gatewalkers-bestiary/000015.log rename to Data/systems/pf2e/packs/gatewalkers-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/gatewalkers-bestiary/CURRENT b/Data/systems/pf2e/packs/gatewalkers-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/gatewalkers-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/gatewalkers-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/gatewalkers-bestiary/LOG b/Data/systems/pf2e/packs/gatewalkers-bestiary/LOG index 01e7dd25..ef6397f9 100644 --- a/Data/systems/pf2e/packs/gatewalkers-bestiary/LOG +++ b/Data/systems/pf2e/packs/gatewalkers-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:09.974424 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:09.979241 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:09.979260 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:16.602497 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:16.604522 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:16.613538 ffff87fff0a0 Level-0 table #5: 603814 bytes OK +2023/10/23-05:12:16.618136 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:16.618346 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/gatewalkers-bestiary/LOG.old b/Data/systems/pf2e/packs/gatewalkers-bestiary/LOG.old index 97506f4d..f7145278 100644 --- a/Data/systems/pf2e/packs/gatewalkers-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/gatewalkers-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.829042 ffff877ef0a0 Recovering log #7 -2023/10/20-07:41:10.833629 ffff877ef0a0 Delete type=3 #4 -2023/10/20-07:41:10.833651 ffff877ef0a0 Delete type=0 #7 -2023/10/20-07:49:07.491723 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.491742 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.493741 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.497403 ffff85fbf0a0 Manual compaction at level-0 from '!actors!16Ru7zfHAHD544xO' @ 72057594037927935 : 1 .. '!actors.items!z4QsiqC9EDD7UV1s.Jfzeyl6xxHUOt1Qa' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.601589 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/gatewalkers-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/gatewalkers-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..e0c31698 Binary files /dev/null and b/Data/systems/pf2e/packs/gatewalkers-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/gatewalkers-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/gatewalkers-bestiary/MANIFEST-000014 deleted file mode 100644 index fc0803a9..00000000 Binary files a/Data/systems/pf2e/packs/gatewalkers-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/gmg-srd/000009.ldb b/Data/systems/pf2e/packs/gmg-srd/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/gmg-srd/000009.ldb rename to Data/systems/pf2e/packs/gmg-srd/000005.ldb diff --git a/Data/systems/pf2e/packs/gmg-srd/000015.log b/Data/systems/pf2e/packs/gmg-srd/000006.log similarity index 100% rename from Data/systems/pf2e/packs/gmg-srd/000015.log rename to Data/systems/pf2e/packs/gmg-srd/000006.log diff --git a/Data/systems/pf2e/packs/gmg-srd/CURRENT b/Data/systems/pf2e/packs/gmg-srd/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/gmg-srd/CURRENT +++ b/Data/systems/pf2e/packs/gmg-srd/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/gmg-srd/LOG b/Data/systems/pf2e/packs/gmg-srd/LOG index 0894ebdf..7fba4997 100644 --- a/Data/systems/pf2e/packs/gmg-srd/LOG +++ b/Data/systems/pf2e/packs/gmg-srd/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.963871 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.968994 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.969013 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:18.558816 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:18.558923 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:18.561492 ffff87fff0a0 Level-0 table #5: 24058 bytes OK +2023/10/23-05:12:18.566203 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:18.566233 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/gmg-srd/LOG.old b/Data/systems/pf2e/packs/gmg-srd/LOG.old index e8728e5a..19cb6f6c 100644 --- a/Data/systems/pf2e/packs/gmg-srd/LOG.old +++ b/Data/systems/pf2e/packs/gmg-srd/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.832529 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.838741 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.838763 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.612211 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.612225 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.613983 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.616117 ffff85fbf0a0 Manual compaction at level-0 from '!journal!2cyhXgGkmoFe3Phw' @ 72057594037927935 : 1 .. '!journal!ziWhyyygUG3Lemdu' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.608346 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/gmg-srd/MANIFEST-000004 b/Data/systems/pf2e/packs/gmg-srd/MANIFEST-000004 new file mode 100644 index 00000000..7c9180cc Binary files /dev/null and b/Data/systems/pf2e/packs/gmg-srd/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/gmg-srd/MANIFEST-000014 b/Data/systems/pf2e/packs/gmg-srd/MANIFEST-000014 deleted file mode 100644 index a124511e..00000000 Binary files a/Data/systems/pf2e/packs/gmg-srd/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/hazards/000009.ldb b/Data/systems/pf2e/packs/hazards/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/hazards/000009.ldb rename to Data/systems/pf2e/packs/hazards/000005.ldb diff --git a/Data/systems/pf2e/packs/hazards/000015.log b/Data/systems/pf2e/packs/hazards/000006.log similarity index 100% rename from Data/systems/pf2e/packs/hazards/000015.log rename to Data/systems/pf2e/packs/hazards/000006.log diff --git a/Data/systems/pf2e/packs/hazards/CURRENT b/Data/systems/pf2e/packs/hazards/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/hazards/CURRENT +++ b/Data/systems/pf2e/packs/hazards/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/hazards/LOG b/Data/systems/pf2e/packs/hazards/LOG index b3170e87..d7f755af 100644 --- a/Data/systems/pf2e/packs/hazards/LOG +++ b/Data/systems/pf2e/packs/hazards/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:09.965998 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:09.970829 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:09.970848 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:16.590808 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:16.591091 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:16.594673 ffff86fdf0a0 Level-0 table #5: 78951 bytes OK +2023/10/23-05:12:16.599697 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:16.599750 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/hazards/LOG.old b/Data/systems/pf2e/packs/hazards/LOG.old index 59809c9a..e60fbc31 100644 --- a/Data/systems/pf2e/packs/hazards/LOG.old +++ b/Data/systems/pf2e/packs/hazards/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.821416 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:10.826183 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:10.826205 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.489704 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.489725 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.491436 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.493780 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0dg9YrjsDi6Ap3jF' @ 72057594037927935 : 1 .. '!actors.items!yM4G2LvMwvkIRx0G.K7Ya0U5jerfvH0vw' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.667305 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/hazards/MANIFEST-000004 b/Data/systems/pf2e/packs/hazards/MANIFEST-000004 new file mode 100644 index 00000000..4b422892 Binary files /dev/null and b/Data/systems/pf2e/packs/hazards/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/hazards/MANIFEST-000014 b/Data/systems/pf2e/packs/hazards/MANIFEST-000014 deleted file mode 100644 index 4a133a27..00000000 Binary files a/Data/systems/pf2e/packs/hazards/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/heritages/000009.ldb b/Data/systems/pf2e/packs/heritages/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/heritages/000009.ldb rename to Data/systems/pf2e/packs/heritages/000005.ldb diff --git a/Data/systems/pf2e/packs/heritages/000015.log b/Data/systems/pf2e/packs/heritages/000006.log similarity index 100% rename from Data/systems/pf2e/packs/heritages/000015.log rename to Data/systems/pf2e/packs/heritages/000006.log diff --git a/Data/systems/pf2e/packs/heritages/CURRENT b/Data/systems/pf2e/packs/heritages/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/heritages/CURRENT +++ b/Data/systems/pf2e/packs/heritages/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/heritages/LOG b/Data/systems/pf2e/packs/heritages/LOG index ae6408b5..13f20696 100644 --- a/Data/systems/pf2e/packs/heritages/LOG +++ b/Data/systems/pf2e/packs/heritages/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.741034 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.746580 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.746602 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:18.090857 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:18.091348 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:18.095257 ffff877ef0a0 Level-0 table #5: 141010 bytes OK +2023/10/23-05:12:18.099914 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:18.099986 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/heritages/LOG.old b/Data/systems/pf2e/packs/heritages/LOG.old index cfddeb2f..5cc833d0 100644 --- a/Data/systems/pf2e/packs/heritages/LOG.old +++ b/Data/systems/pf2e/packs/heritages/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.626794 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.632117 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.632140 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.576880 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.576900 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.578912 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.582738 ffff85fbf0a0 Manual compaction at level-0 from '!items!0Iv6LfT3UEt8taj5' @ 72057594037927935 : 1 .. '!items!zcO93E8gAW1tDYKk' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.668053 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/heritages/MANIFEST-000004 b/Data/systems/pf2e/packs/heritages/MANIFEST-000004 new file mode 100644 index 00000000..b2aa2322 Binary files /dev/null and b/Data/systems/pf2e/packs/heritages/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/heritages/MANIFEST-000014 b/Data/systems/pf2e/packs/heritages/MANIFEST-000014 deleted file mode 100644 index 667908d3..00000000 Binary files a/Data/systems/pf2e/packs/heritages/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/highhelm-bestiary/000009.ldb b/Data/systems/pf2e/packs/highhelm-bestiary/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/highhelm-bestiary/000009.ldb rename to Data/systems/pf2e/packs/highhelm-bestiary/000005.ldb diff --git a/Data/systems/pf2e/packs/highhelm-bestiary/000015.log b/Data/systems/pf2e/packs/highhelm-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/highhelm-bestiary/000015.log rename to Data/systems/pf2e/packs/highhelm-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/highhelm-bestiary/CURRENT b/Data/systems/pf2e/packs/highhelm-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/highhelm-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/highhelm-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/highhelm-bestiary/LOG b/Data/systems/pf2e/packs/highhelm-bestiary/LOG index 6f66d48d..43bae02a 100644 --- a/Data/systems/pf2e/packs/highhelm-bestiary/LOG +++ b/Data/systems/pf2e/packs/highhelm-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.003368 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.009509 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.009528 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:16.660702 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:16.660904 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:16.663622 ffff87fff0a0 Level-0 table #5: 41036 bytes OK +2023/10/23-05:12:16.668018 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:16.668055 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/highhelm-bestiary/LOG.old b/Data/systems/pf2e/packs/highhelm-bestiary/LOG.old index 6b73d581..622082cc 100644 --- a/Data/systems/pf2e/packs/highhelm-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/highhelm-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.857775 ffff877ef0a0 Recovering log #7 -2023/10/20-07:41:10.862420 ffff877ef0a0 Delete type=3 #4 -2023/10/20-07:41:10.862442 ffff877ef0a0 Delete type=0 #7 -2023/10/20-07:49:07.497522 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.497544 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.499265 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.501423 ffff85fbf0a0 Manual compaction at level-0 from '!actors!6X4zL4GSS9aUcP9f' @ 72057594037927935 : 1 .. '!actors.items!fQvTnIpC2Wq1U32z.z8uIV3qPaxm6Ytug' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.668165 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/highhelm-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/highhelm-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..fa26d322 Binary files /dev/null and b/Data/systems/pf2e/packs/highhelm-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/highhelm-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/highhelm-bestiary/MANIFEST-000014 deleted file mode 100644 index 082e37a8..00000000 Binary files a/Data/systems/pf2e/packs/highhelm-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/iconics/000009.ldb b/Data/systems/pf2e/packs/iconics/000005.ldb similarity index 97% rename from Data/systems/pf2e/packs/iconics/000009.ldb rename to Data/systems/pf2e/packs/iconics/000005.ldb index 2c69eb77..dd5a324f 100644 Binary files a/Data/systems/pf2e/packs/iconics/000009.ldb and b/Data/systems/pf2e/packs/iconics/000005.ldb differ diff --git a/Data/systems/pf2e/packs/iconics/000015.log b/Data/systems/pf2e/packs/iconics/000006.log similarity index 100% rename from Data/systems/pf2e/packs/iconics/000015.log rename to Data/systems/pf2e/packs/iconics/000006.log diff --git a/Data/systems/pf2e/packs/iconics/CURRENT b/Data/systems/pf2e/packs/iconics/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/iconics/CURRENT +++ b/Data/systems/pf2e/packs/iconics/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/iconics/LOG b/Data/systems/pf2e/packs/iconics/LOG index 268c4d39..ebf992be 100644 --- a/Data/systems/pf2e/packs/iconics/LOG +++ b/Data/systems/pf2e/packs/iconics/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.894965 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.900249 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.900270 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:18.407398 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:18.412621 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:18.433131 ffff86fdf0a0 Level-0 table #5: 1604618 bytes OK +2023/10/23-05:12:18.437916 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:18.438459 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/iconics/LOG.old b/Data/systems/pf2e/packs/iconics/LOG.old index 93db2561..c30c0ed1 100644 --- a/Data/systems/pf2e/packs/iconics/LOG.old +++ b/Data/systems/pf2e/packs/iconics/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.763457 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.768721 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.768743 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.602739 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.602761 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.604519 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.608231 ffff85fbf0a0 Manual compaction at level-0 from '!actors!27kg8dCRYM3bsqND' @ 72057594037927935 : 1 .. '!actors.items!zLOVCrRwZhL46vLI.zzJLHah9rHpVpFEQ' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.669392 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/iconics/MANIFEST-000004 b/Data/systems/pf2e/packs/iconics/MANIFEST-000004 new file mode 100644 index 00000000..67ffc095 Binary files /dev/null and b/Data/systems/pf2e/packs/iconics/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/iconics/MANIFEST-000014 b/Data/systems/pf2e/packs/iconics/MANIFEST-000014 deleted file mode 100644 index 4b037ac3..00000000 Binary files a/Data/systems/pf2e/packs/iconics/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/impossible-lands-bestiary/000009.ldb b/Data/systems/pf2e/packs/impossible-lands-bestiary/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/impossible-lands-bestiary/000009.ldb rename to Data/systems/pf2e/packs/impossible-lands-bestiary/000005.ldb diff --git a/Data/systems/pf2e/packs/impossible-lands-bestiary/000015.log b/Data/systems/pf2e/packs/impossible-lands-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/impossible-lands-bestiary/000015.log rename to Data/systems/pf2e/packs/impossible-lands-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/impossible-lands-bestiary/CURRENT b/Data/systems/pf2e/packs/impossible-lands-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/impossible-lands-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/impossible-lands-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/impossible-lands-bestiary/LOG b/Data/systems/pf2e/packs/impossible-lands-bestiary/LOG index a2e1b13f..19f314f6 100644 --- a/Data/systems/pf2e/packs/impossible-lands-bestiary/LOG +++ b/Data/systems/pf2e/packs/impossible-lands-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:09.985983 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:09.990933 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:09.990953 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:16.628299 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:16.628694 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:16.632229 ffff86fdf0a0 Level-0 table #5: 118203 bytes OK +2023/10/23-05:12:16.636968 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:16.637026 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/impossible-lands-bestiary/LOG.old b/Data/systems/pf2e/packs/impossible-lands-bestiary/LOG.old index 15353f78..8a0861cf 100644 --- a/Data/systems/pf2e/packs/impossible-lands-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/impossible-lands-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.840597 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:10.845099 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:10.845122 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.493905 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.493926 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.495649 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.499304 ffff85fbf0a0 Manual compaction at level-0 from '!actors!1MxubcO4SB8PwmKT' @ 72057594037927935 : 1 .. '!actors.items!xl2UxOFVSDGqaVS5.t8ySn9dzFCtVzTO9' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.672366 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/impossible-lands-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/impossible-lands-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..ef95a1da Binary files /dev/null and b/Data/systems/pf2e/packs/impossible-lands-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/impossible-lands-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/impossible-lands-bestiary/MANIFEST-000014 deleted file mode 100644 index c9b65f82..00000000 Binary files a/Data/systems/pf2e/packs/impossible-lands-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/journals/000009.ldb b/Data/systems/pf2e/packs/journals/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/journals/000009.ldb rename to Data/systems/pf2e/packs/journals/000005.ldb diff --git a/Data/systems/pf2e/packs/journals/000015.log b/Data/systems/pf2e/packs/journals/000006.log similarity index 100% rename from Data/systems/pf2e/packs/journals/000015.log rename to Data/systems/pf2e/packs/journals/000006.log diff --git a/Data/systems/pf2e/packs/journals/CURRENT b/Data/systems/pf2e/packs/journals/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/journals/CURRENT +++ b/Data/systems/pf2e/packs/journals/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/journals/LOG b/Data/systems/pf2e/packs/journals/LOG index 0cdc8d29..faa2366f 100644 --- a/Data/systems/pf2e/packs/journals/LOG +++ b/Data/systems/pf2e/packs/journals/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.951382 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.956240 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.956260 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:18.524812 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:18.528207 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:18.543724 ffff86fdf0a0 Level-0 table #5: 1244760 bytes OK +2023/10/23-05:12:18.548666 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:18.549103 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/journals/LOG.old b/Data/systems/pf2e/packs/journals/LOG.old index 225fbfeb..9b7f3279 100644 --- a/Data/systems/pf2e/packs/journals/LOG.old +++ b/Data/systems/pf2e/packs/journals/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.819491 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.825152 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.825175 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.610317 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.610338 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.612175 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.616001 ffff85fbf0a0 Manual compaction at level-0 from '!journal!45SK8rdbbxvEHfMn' @ 72057594037927935 : 1 .. '!journal.pages!xtrW5GEtPPuXR6k2.oAfVg9t7GGTW7R1H' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.670839 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/journals/MANIFEST-000004 b/Data/systems/pf2e/packs/journals/MANIFEST-000004 new file mode 100644 index 00000000..711f46a3 Binary files /dev/null and b/Data/systems/pf2e/packs/journals/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/journals/MANIFEST-000014 b/Data/systems/pf2e/packs/journals/MANIFEST-000014 deleted file mode 100644 index 080ba5af..00000000 Binary files a/Data/systems/pf2e/packs/journals/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/kingmaker-bestiary/000009.ldb b/Data/systems/pf2e/packs/kingmaker-bestiary/000005.ldb similarity index 51% rename from Data/systems/pf2e/packs/kingmaker-bestiary/000009.ldb rename to Data/systems/pf2e/packs/kingmaker-bestiary/000005.ldb index b06b2795..13894b65 100644 Binary files a/Data/systems/pf2e/packs/kingmaker-bestiary/000009.ldb and b/Data/systems/pf2e/packs/kingmaker-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/kingmaker-bestiary/000016.log b/Data/systems/pf2e/packs/kingmaker-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/kingmaker-bestiary/000016.log rename to Data/systems/pf2e/packs/kingmaker-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/kingmaker-bestiary/000010.ldb b/Data/systems/pf2e/packs/kingmaker-bestiary/000010.ldb deleted file mode 100644 index 0e3f8b2e..00000000 Binary files a/Data/systems/pf2e/packs/kingmaker-bestiary/000010.ldb and /dev/null differ diff --git a/Data/systems/pf2e/packs/kingmaker-bestiary/CURRENT b/Data/systems/pf2e/packs/kingmaker-bestiary/CURRENT index 42c62b67..cacca757 100644 --- a/Data/systems/pf2e/packs/kingmaker-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/kingmaker-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000015 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/kingmaker-bestiary/LOG b/Data/systems/pf2e/packs/kingmaker-bestiary/LOG index b97f0bd4..2121072e 100644 --- a/Data/systems/pf2e/packs/kingmaker-bestiary/LOG +++ b/Data/systems/pf2e/packs/kingmaker-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.088828 ffff877ef0a0 Recovering log #13 -2023/10/20-07:55:10.093723 ffff877ef0a0 Delete type=0 #13 -2023/10/20-07:55:10.093743 ffff877ef0a0 Delete type=3 #11 +2023/10/23-05:12:16.809436 ffff867cf0a0 Recovering log #3 +2023/10/23-05:12:16.821406 ffff867cf0a0 Level-0 table #5: started +2023/10/23-05:12:16.869990 ffff867cf0a0 Level-0 table #5: 3403687 bytes OK +2023/10/23-05:12:16.876298 ffff867cf0a0 Delete type=0 #3 +2023/10/23-05:12:16.877467 ffff867cf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/kingmaker-bestiary/LOG.old b/Data/systems/pf2e/packs/kingmaker-bestiary/LOG.old index 39ee731f..eb240e64 100644 --- a/Data/systems/pf2e/packs/kingmaker-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/kingmaker-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.944172 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:10.948929 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:10.948952 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.512885 ffff85fbf0a0 Level-0 table #14: started -2023/10/20-07:49:07.512906 ffff85fbf0a0 Level-0 table #14: 0 bytes OK -2023/10/20-07:49:07.514544 ffff85fbf0a0 Delete type=0 #12 -2023/10/20-07:49:07.516934 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0EO5vP2gCliAxLrF' @ 72057594037927935 : 1 .. '!actors.items!zvhw5Qx6gU7e39he.zQB4cIjvZCjdjzgJ' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.671878 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/kingmaker-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/kingmaker-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..d9a67b7a Binary files /dev/null and b/Data/systems/pf2e/packs/kingmaker-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/kingmaker-bestiary/MANIFEST-000015 b/Data/systems/pf2e/packs/kingmaker-bestiary/MANIFEST-000015 deleted file mode 100644 index 0eb070be..00000000 Binary files a/Data/systems/pf2e/packs/kingmaker-bestiary/MANIFEST-000015 and /dev/null differ diff --git a/Data/systems/pf2e/packs/kingmaker-features/000009.ldb b/Data/systems/pf2e/packs/kingmaker-features/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/kingmaker-features/000009.ldb rename to Data/systems/pf2e/packs/kingmaker-features/000005.ldb diff --git a/Data/systems/pf2e/packs/kingmaker-features/000015.log b/Data/systems/pf2e/packs/kingmaker-features/000006.log similarity index 100% rename from Data/systems/pf2e/packs/kingmaker-features/000015.log rename to Data/systems/pf2e/packs/kingmaker-features/000006.log diff --git a/Data/systems/pf2e/packs/kingmaker-features/CURRENT b/Data/systems/pf2e/packs/kingmaker-features/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/kingmaker-features/CURRENT +++ b/Data/systems/pf2e/packs/kingmaker-features/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/kingmaker-features/LOG b/Data/systems/pf2e/packs/kingmaker-features/LOG index 7e4ea370..3d1e0c7f 100644 --- a/Data/systems/pf2e/packs/kingmaker-features/LOG +++ b/Data/systems/pf2e/packs/kingmaker-features/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:11.010418 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:11.015114 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:11.015134 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:18.616816 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:18.617143 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:18.620659 ffff87fff0a0 Level-0 table #5: 100391 bytes OK +2023/10/23-05:12:18.625550 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:18.625615 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/kingmaker-features/LOG.old b/Data/systems/pf2e/packs/kingmaker-features/LOG.old index 26a6a656..8096f3af 100644 --- a/Data/systems/pf2e/packs/kingmaker-features/LOG.old +++ b/Data/systems/pf2e/packs/kingmaker-features/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.877136 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.881792 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.881814 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.624007 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.624025 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.625670 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.629447 ffff85fbf0a0 Manual compaction at level-0 from '!folders!DVa3GkbBsLwGp2In' @ 72057594037927935 : 1 .. '!items!ysKkyZp02RMujObE' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.673609 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/kingmaker-features/MANIFEST-000004 b/Data/systems/pf2e/packs/kingmaker-features/MANIFEST-000004 new file mode 100644 index 00000000..1ddd8f3e Binary files /dev/null and b/Data/systems/pf2e/packs/kingmaker-features/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/kingmaker-features/MANIFEST-000014 b/Data/systems/pf2e/packs/kingmaker-features/MANIFEST-000014 deleted file mode 100644 index 0aab367c..00000000 Binary files a/Data/systems/pf2e/packs/kingmaker-features/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/macros/000009.ldb b/Data/systems/pf2e/packs/macros/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/macros/000009.ldb rename to Data/systems/pf2e/packs/macros/000005.ldb diff --git a/Data/systems/pf2e/packs/macros/000015.log b/Data/systems/pf2e/packs/macros/000006.log similarity index 100% rename from Data/systems/pf2e/packs/macros/000015.log rename to Data/systems/pf2e/packs/macros/000006.log diff --git a/Data/systems/pf2e/packs/macros/CURRENT b/Data/systems/pf2e/packs/macros/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/macros/CURRENT +++ b/Data/systems/pf2e/packs/macros/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/macros/LOG b/Data/systems/pf2e/packs/macros/LOG index e74391ea..0b119c1d 100644 --- a/Data/systems/pf2e/packs/macros/LOG +++ b/Data/systems/pf2e/packs/macros/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.977055 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.982030 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.982049 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:18.576300 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:18.576329 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:18.578198 ffff87fff0a0 Level-0 table #5: 1742 bytes OK +2023/10/23-05:12:18.582613 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:18.582632 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/macros/LOG.old b/Data/systems/pf2e/packs/macros/LOG.old index fcab9341..81b09afa 100644 --- a/Data/systems/pf2e/packs/macros/LOG.old +++ b/Data/systems/pf2e/packs/macros/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.848597 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.853640 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.853662 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.616205 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.616222 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.618280 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.621964 ffff85fbf0a0 Manual compaction at level-0 from '!macros!084MOWWSEVNwpHVG' @ 72057594037927935 : 1 .. '!macros!yBuEphSaJJ7V9Yw3' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.694167 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/macros/MANIFEST-000004 b/Data/systems/pf2e/packs/macros/MANIFEST-000004 new file mode 100644 index 00000000..6d7b2516 Binary files /dev/null and b/Data/systems/pf2e/packs/macros/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/macros/MANIFEST-000014 b/Data/systems/pf2e/packs/macros/MANIFEST-000014 deleted file mode 100644 index 99ebb1c5..00000000 Binary files a/Data/systems/pf2e/packs/macros/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/malevolence-bestiary/000009.ldb b/Data/systems/pf2e/packs/malevolence-bestiary/000005.ldb similarity index 98% rename from Data/systems/pf2e/packs/malevolence-bestiary/000009.ldb rename to Data/systems/pf2e/packs/malevolence-bestiary/000005.ldb index ce5ec3b1..0cc27d59 100644 Binary files a/Data/systems/pf2e/packs/malevolence-bestiary/000009.ldb and b/Data/systems/pf2e/packs/malevolence-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/malevolence-bestiary/000015.log b/Data/systems/pf2e/packs/malevolence-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/malevolence-bestiary/000015.log rename to Data/systems/pf2e/packs/malevolence-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/malevolence-bestiary/CURRENT b/Data/systems/pf2e/packs/malevolence-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/malevolence-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/malevolence-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/malevolence-bestiary/LOG b/Data/systems/pf2e/packs/malevolence-bestiary/LOG index f5344aa7..e4150c97 100644 --- a/Data/systems/pf2e/packs/malevolence-bestiary/LOG +++ b/Data/systems/pf2e/packs/malevolence-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.030766 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.035602 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.035621 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:16.702291 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:16.702736 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:16.706289 ffff86fdf0a0 Level-0 table #5: 125242 bytes OK +2023/10/23-05:12:16.710898 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:16.710964 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/malevolence-bestiary/LOG.old b/Data/systems/pf2e/packs/malevolence-bestiary/LOG.old index 812aba91..a935fc0a 100644 --- a/Data/systems/pf2e/packs/malevolence-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/malevolence-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.886267 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:10.891126 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:10.891150 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.503406 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.503421 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.505012 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.507155 ffff85fbf0a0 Manual compaction at level-0 from '!actors!1XrwqxEW8rUr8238' @ 72057594037927935 : 1 .. '!actors.items!x0RGlIHXDN9y0D08.w9dbnWlDHHH9m9cM' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.694756 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/malevolence-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/malevolence-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..11055fe5 Binary files /dev/null and b/Data/systems/pf2e/packs/malevolence-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/malevolence-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/malevolence-bestiary/MANIFEST-000014 deleted file mode 100644 index ea7f3d87..00000000 Binary files a/Data/systems/pf2e/packs/malevolence-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/menace-under-otari-bestiary/000009.ldb b/Data/systems/pf2e/packs/menace-under-otari-bestiary/000005.ldb similarity index 99% rename from Data/systems/pf2e/packs/menace-under-otari-bestiary/000009.ldb rename to Data/systems/pf2e/packs/menace-under-otari-bestiary/000005.ldb index b2972844..b289a33c 100644 Binary files a/Data/systems/pf2e/packs/menace-under-otari-bestiary/000009.ldb and b/Data/systems/pf2e/packs/menace-under-otari-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/menace-under-otari-bestiary/000015.log b/Data/systems/pf2e/packs/menace-under-otari-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/menace-under-otari-bestiary/000015.log rename to Data/systems/pf2e/packs/menace-under-otari-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/menace-under-otari-bestiary/CURRENT b/Data/systems/pf2e/packs/menace-under-otari-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/menace-under-otari-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/menace-under-otari-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/menace-under-otari-bestiary/LOG b/Data/systems/pf2e/packs/menace-under-otari-bestiary/LOG index 62c0528b..465e35bb 100644 --- a/Data/systems/pf2e/packs/menace-under-otari-bestiary/LOG +++ b/Data/systems/pf2e/packs/menace-under-otari-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.038714 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.043848 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.043868 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:16.713918 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:16.715112 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:16.721422 ffff87fff0a0 Level-0 table #5: 311367 bytes OK +2023/10/23-05:12:16.725935 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:16.726063 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/menace-under-otari-bestiary/LOG.old b/Data/systems/pf2e/packs/menace-under-otari-bestiary/LOG.old index f51d6daa..ac74bd9e 100644 --- a/Data/systems/pf2e/packs/menace-under-otari-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/menace-under-otari-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.894711 ffff877ef0a0 Recovering log #7 -2023/10/20-07:41:10.899738 ffff877ef0a0 Delete type=3 #4 -2023/10/20-07:41:10.899762 ffff877ef0a0 Delete type=0 #7 -2023/10/20-07:49:07.505169 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.505189 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.506997 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.509109 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0oWKApY5FR8IO7GG' @ 72057594037927935 : 1 .. '!actors.items!xKYIN88ULPFgSZmw.ufap97U4FyUOrJZF' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.696145 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/menace-under-otari-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/menace-under-otari-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..6d31878c Binary files /dev/null and b/Data/systems/pf2e/packs/menace-under-otari-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/menace-under-otari-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/menace-under-otari-bestiary/MANIFEST-000014 deleted file mode 100644 index 9f38f9dd..00000000 Binary files a/Data/systems/pf2e/packs/menace-under-otari-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/monsters-of-myth-bestiary/000009.ldb b/Data/systems/pf2e/packs/monsters-of-myth-bestiary/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/monsters-of-myth-bestiary/000009.ldb rename to Data/systems/pf2e/packs/monsters-of-myth-bestiary/000005.ldb diff --git a/Data/systems/pf2e/packs/monsters-of-myth-bestiary/000015.log b/Data/systems/pf2e/packs/monsters-of-myth-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/monsters-of-myth-bestiary/000015.log rename to Data/systems/pf2e/packs/monsters-of-myth-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/monsters-of-myth-bestiary/CURRENT b/Data/systems/pf2e/packs/monsters-of-myth-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/monsters-of-myth-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/monsters-of-myth-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/monsters-of-myth-bestiary/LOG b/Data/systems/pf2e/packs/monsters-of-myth-bestiary/LOG index 73802b15..b8ec7cdd 100644 --- a/Data/systems/pf2e/packs/monsters-of-myth-bestiary/LOG +++ b/Data/systems/pf2e/packs/monsters-of-myth-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.011974 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.016963 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.016982 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:16.670462 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:16.672273 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:16.680439 ffff86fdf0a0 Level-0 table #5: 514513 bytes OK +2023/10/23-05:12:16.684701 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:16.684934 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/monsters-of-myth-bestiary/LOG.old b/Data/systems/pf2e/packs/monsters-of-myth-bestiary/LOG.old index d3cb6f6d..006e49ed 100644 --- a/Data/systems/pf2e/packs/monsters-of-myth-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/monsters-of-myth-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.864744 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:10.869819 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:10.869842 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.499523 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.499573 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.501384 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.505050 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0ypo8Vt3B6p9DqAt' @ 72057594037927935 : 1 .. '!actors.items!zE2ykzHZKNS3Rnc3.tyvo7ikid2evukk0' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.696779 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/monsters-of-myth-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/monsters-of-myth-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..9591fcaf Binary files /dev/null and b/Data/systems/pf2e/packs/monsters-of-myth-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/monsters-of-myth-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/monsters-of-myth-bestiary/MANIFEST-000014 deleted file mode 100644 index d6db3079..00000000 Binary files a/Data/systems/pf2e/packs/monsters-of-myth-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/mwangi-expanse-bestiary/000009.ldb b/Data/systems/pf2e/packs/mwangi-expanse-bestiary/000005.ldb similarity index 97% rename from Data/systems/pf2e/packs/mwangi-expanse-bestiary/000009.ldb rename to Data/systems/pf2e/packs/mwangi-expanse-bestiary/000005.ldb index 2e5f6428..02701c30 100644 Binary files a/Data/systems/pf2e/packs/mwangi-expanse-bestiary/000009.ldb and b/Data/systems/pf2e/packs/mwangi-expanse-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/mwangi-expanse-bestiary/000015.log b/Data/systems/pf2e/packs/mwangi-expanse-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/mwangi-expanse-bestiary/000015.log rename to Data/systems/pf2e/packs/mwangi-expanse-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/mwangi-expanse-bestiary/CURRENT b/Data/systems/pf2e/packs/mwangi-expanse-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/mwangi-expanse-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/mwangi-expanse-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/mwangi-expanse-bestiary/LOG b/Data/systems/pf2e/packs/mwangi-expanse-bestiary/LOG index ed9b1ffd..075dcbd6 100644 --- a/Data/systems/pf2e/packs/mwangi-expanse-bestiary/LOG +++ b/Data/systems/pf2e/packs/mwangi-expanse-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:09.993899 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:09.998935 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:09.998955 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:16.639957 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:16.640652 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:16.645158 ffff87fff0a0 Level-0 table #5: 201554 bytes OK +2023/10/23-05:12:16.649683 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:16.649777 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/mwangi-expanse-bestiary/LOG.old b/Data/systems/pf2e/packs/mwangi-expanse-bestiary/LOG.old index fe3f25f5..3b2f138b 100644 --- a/Data/systems/pf2e/packs/mwangi-expanse-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/mwangi-expanse-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.848225 ffff877ef0a0 Recovering log #7 -2023/10/20-07:41:10.852940 ffff877ef0a0 Delete type=3 #4 -2023/10/20-07:41:10.852962 ffff877ef0a0 Delete type=0 #7 -2023/10/20-07:49:07.495686 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.495700 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.497365 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.499426 ffff85fbf0a0 Manual compaction at level-0 from '!actors!8K5v5q9Y01hcSNug' @ 72057594037927935 : 1 .. '!actors.items!x2udXsqiLZachJHY.zltKri0RdONGiYzp' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.697548 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/mwangi-expanse-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/mwangi-expanse-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..1c2bc9eb Binary files /dev/null and b/Data/systems/pf2e/packs/mwangi-expanse-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/mwangi-expanse-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/mwangi-expanse-bestiary/MANIFEST-000014 deleted file mode 100644 index c2149430..00000000 Binary files a/Data/systems/pf2e/packs/mwangi-expanse-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/000009.ldb b/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/000005.ldb similarity index 98% rename from Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/000009.ldb rename to Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/000005.ldb index 0941ac51..a84f1eba 100644 Binary files a/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/000009.ldb and b/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/000015.log b/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/000015.log rename to Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/CURRENT b/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/LOG b/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/LOG index 87cf6fdf..557a938f 100644 --- a/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/LOG +++ b/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.514888 ffff867cf0a0 Recovering log #12 -2023/10/20-07:55:10.521801 ffff867cf0a0 Delete type=0 #12 -2023/10/20-07:55:10.521826 ffff867cf0a0 Delete type=3 #10 +2023/10/23-05:12:17.760680 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:17.761533 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:17.766430 ffff86fdf0a0 Level-0 table #5: 242185 bytes OK +2023/10/23-05:12:17.771609 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:17.771716 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/LOG.old b/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/LOG.old index 1e04a23e..a90f4c20 100644 --- a/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.462851 ffff86fdf0a0 Recovering log #7 -2023/10/20-07:41:11.468350 ffff86fdf0a0 Delete type=3 #4 -2023/10/20-07:41:11.468374 ffff86fdf0a0 Delete type=0 #7 -2023/10/20-07:49:07.551236 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.551258 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.552938 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.555121 ffff85fbf0a0 Manual compaction at level-0 from '!actors!7jALXqInrmh428DW' @ 72057594037927935 : 1 .. '!actors.items!w7Y6zn3wRabuOdNv.vPiD83jHe3pfnCGb' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.697716 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..8e8537ac Binary files /dev/null and b/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/MANIFEST-000014 deleted file mode 100644 index b65e1afc..00000000 Binary files a/Data/systems/pf2e/packs/night-of-the-gray-death-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/npc-gallery/000009.ldb b/Data/systems/pf2e/packs/npc-gallery/000005.ldb similarity index 93% rename from Data/systems/pf2e/packs/npc-gallery/000009.ldb rename to Data/systems/pf2e/packs/npc-gallery/000005.ldb index b949163c..88b5ac68 100644 Binary files a/Data/systems/pf2e/packs/npc-gallery/000009.ldb and b/Data/systems/pf2e/packs/npc-gallery/000005.ldb differ diff --git a/Data/systems/pf2e/packs/npc-gallery/000015.log b/Data/systems/pf2e/packs/npc-gallery/000006.log similarity index 100% rename from Data/systems/pf2e/packs/npc-gallery/000015.log rename to Data/systems/pf2e/packs/npc-gallery/000006.log diff --git a/Data/systems/pf2e/packs/npc-gallery/CURRENT b/Data/systems/pf2e/packs/npc-gallery/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/npc-gallery/CURRENT +++ b/Data/systems/pf2e/packs/npc-gallery/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/npc-gallery/LOG b/Data/systems/pf2e/packs/npc-gallery/LOG index 374bfd14..41e6e253 100644 --- a/Data/systems/pf2e/packs/npc-gallery/LOG +++ b/Data/systems/pf2e/packs/npc-gallery/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.048964 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.054091 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.054110 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:16.731781 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:16.735622 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:16.749920 ffff877ef0a0 Level-0 table #5: 1113942 bytes OK +2023/10/23-05:12:16.754987 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:16.755412 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/npc-gallery/LOG.old b/Data/systems/pf2e/packs/npc-gallery/LOG.old index e2ce1335..fa3bf57c 100644 --- a/Data/systems/pf2e/packs/npc-gallery/LOG.old +++ b/Data/systems/pf2e/packs/npc-gallery/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.904988 ffff877ef0a0 Recovering log #7 -2023/10/20-07:41:10.909520 ffff877ef0a0 Delete type=3 #4 -2023/10/20-07:41:10.909543 ffff877ef0a0 Delete type=0 #7 -2023/10/20-07:49:07.507251 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.507270 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.509070 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.512737 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0Ex7rBuiJVu2NwCz' @ 72057594037927935 : 1 .. '!actors.items!zQfufnnLCTzQ165S.xBb6evQkhB3uYAvn' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.701142 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/npc-gallery/MANIFEST-000004 b/Data/systems/pf2e/packs/npc-gallery/MANIFEST-000004 new file mode 100644 index 00000000..ae0e4e2f Binary files /dev/null and b/Data/systems/pf2e/packs/npc-gallery/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/npc-gallery/MANIFEST-000014 b/Data/systems/pf2e/packs/npc-gallery/MANIFEST-000014 deleted file mode 100644 index b8d8de3d..00000000 Binary files a/Data/systems/pf2e/packs/npc-gallery/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/one-shot-bestiary/000009.ldb b/Data/systems/pf2e/packs/one-shot-bestiary/000005.ldb similarity index 98% rename from Data/systems/pf2e/packs/one-shot-bestiary/000009.ldb rename to Data/systems/pf2e/packs/one-shot-bestiary/000005.ldb index b5e2fc0a..bf41b4db 100644 Binary files a/Data/systems/pf2e/packs/one-shot-bestiary/000009.ldb and b/Data/systems/pf2e/packs/one-shot-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/one-shot-bestiary/000015.log b/Data/systems/pf2e/packs/one-shot-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/one-shot-bestiary/000015.log rename to Data/systems/pf2e/packs/one-shot-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/one-shot-bestiary/CURRENT b/Data/systems/pf2e/packs/one-shot-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/one-shot-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/one-shot-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/one-shot-bestiary/LOG b/Data/systems/pf2e/packs/one-shot-bestiary/LOG index 97cec806..1418ee91 100644 --- a/Data/systems/pf2e/packs/one-shot-bestiary/LOG +++ b/Data/systems/pf2e/packs/one-shot-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.066491 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.071473 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.071492 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:16.768519 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:16.769230 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:16.773822 ffff877ef0a0 Level-0 table #5: 195214 bytes OK +2023/10/23-05:12:16.778325 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:16.778410 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/one-shot-bestiary/LOG.old b/Data/systems/pf2e/packs/one-shot-bestiary/LOG.old index 74d60c33..3a63ebb8 100644 --- a/Data/systems/pf2e/packs/one-shot-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/one-shot-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.921319 ffff877ef0a0 Recovering log #7 -2023/10/20-07:41:10.926268 ffff877ef0a0 Delete type=3 #4 -2023/10/20-07:41:10.926292 ffff877ef0a0 Delete type=0 #7 -2023/10/20-07:49:07.509233 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.509255 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.511025 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.514582 ffff85fbf0a0 Manual compaction at level-0 from '!actors!305dxeny5G1sVvwe' @ 72057594037927935 : 1 .. '!actors.items!ws7D95828SXNi4Vp.zJLNk0x1jVbbA5Nc' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.699580 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/one-shot-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/one-shot-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..acaa53ee Binary files /dev/null and b/Data/systems/pf2e/packs/one-shot-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/one-shot-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/one-shot-bestiary/MANIFEST-000014 deleted file mode 100644 index f97cc72a..00000000 Binary files a/Data/systems/pf2e/packs/one-shot-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/other-effects/000009.ldb b/Data/systems/pf2e/packs/other-effects/000005.ldb similarity index 82% rename from Data/systems/pf2e/packs/other-effects/000009.ldb rename to Data/systems/pf2e/packs/other-effects/000005.ldb index 0b2b0515..835aa7b7 100644 Binary files a/Data/systems/pf2e/packs/other-effects/000009.ldb and b/Data/systems/pf2e/packs/other-effects/000005.ldb differ diff --git a/Data/systems/pf2e/packs/other-effects/000015.log b/Data/systems/pf2e/packs/other-effects/000006.log similarity index 100% rename from Data/systems/pf2e/packs/other-effects/000015.log rename to Data/systems/pf2e/packs/other-effects/000006.log diff --git a/Data/systems/pf2e/packs/other-effects/CURRENT b/Data/systems/pf2e/packs/other-effects/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/other-effects/CURRENT +++ b/Data/systems/pf2e/packs/other-effects/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/other-effects/LOG b/Data/systems/pf2e/packs/other-effects/LOG index 6d4325bd..a2d141f7 100644 --- a/Data/systems/pf2e/packs/other-effects/LOG +++ b/Data/systems/pf2e/packs/other-effects/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.813665 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.819427 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.819446 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:18.202853 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:18.202949 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:18.205487 ffff86fdf0a0 Level-0 table #5: 17150 bytes OK +2023/10/23-05:12:18.210148 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:18.210177 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/other-effects/LOG.old b/Data/systems/pf2e/packs/other-effects/LOG.old index faa4d448..4a3fff5f 100644 --- a/Data/systems/pf2e/packs/other-effects/LOG.old +++ b/Data/systems/pf2e/packs/other-effects/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.689974 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.695003 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.695025 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.591174 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.591196 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.592939 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.595032 ffff85fbf0a0 Manual compaction at level-0 from '!items!0r8MznJe5UugViee' @ 72057594037927935 : 1 .. '!items!zDV1wo2ytNTbyTB0' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.701305 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/other-effects/MANIFEST-000004 b/Data/systems/pf2e/packs/other-effects/MANIFEST-000004 new file mode 100644 index 00000000..971d5890 Binary files /dev/null and b/Data/systems/pf2e/packs/other-effects/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/other-effects/MANIFEST-000014 b/Data/systems/pf2e/packs/other-effects/MANIFEST-000014 deleted file mode 100644 index 62ee96d4..00000000 Binary files a/Data/systems/pf2e/packs/other-effects/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/000009.ldb b/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/000005.ldb similarity index 95% rename from Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/000009.ldb rename to Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/000005.ldb index 0f55aa7f..06f53db1 100644 Binary files a/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/000009.ldb and b/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/000015.log b/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/000015.log rename to Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/CURRENT b/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/LOG b/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/LOG index f43b9de0..c858b1b9 100644 --- a/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/LOG +++ b/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.075073 ffff877ef0a0 Recovering log #12 -2023/10/20-07:55:10.080448 ffff877ef0a0 Delete type=0 #12 -2023/10/20-07:55:10.080467 ffff877ef0a0 Delete type=3 #10 +2023/10/23-05:12:16.782177 ffff867cf0a0 Recovering log #3 +2023/10/23-05:12:16.784616 ffff867cf0a0 Level-0 table #5: started +2023/10/23-05:12:16.794369 ffff867cf0a0 Level-0 table #5: 666663 bytes OK +2023/10/23-05:12:16.799130 ffff867cf0a0 Delete type=0 #3 +2023/10/23-05:12:16.799377 ffff867cf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/LOG.old b/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/LOG.old index c03fb178..cef031ec 100644 --- a/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.931491 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:10.936306 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:10.936330 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.511063 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.511077 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.512700 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.514706 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0hy54Fyobwdb7AGN' @ 72057594037927935 : 1 .. '!actors.items!zUHMrJZKcKIv6IpM.xTbmqvj8q9NXpTNJ' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.700974 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..075b9c1a Binary files /dev/null and b/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/MANIFEST-000014 deleted file mode 100644 index 48322b9d..00000000 Binary files a/Data/systems/pf2e/packs/outlaws-of-alkenstar-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/paizo-pregens/000009.ldb b/Data/systems/pf2e/packs/paizo-pregens/000005.ldb similarity index 99% rename from Data/systems/pf2e/packs/paizo-pregens/000009.ldb rename to Data/systems/pf2e/packs/paizo-pregens/000005.ldb index 9fbd83fc..51905422 100644 Binary files a/Data/systems/pf2e/packs/paizo-pregens/000009.ldb and b/Data/systems/pf2e/packs/paizo-pregens/000005.ldb differ diff --git a/Data/systems/pf2e/packs/paizo-pregens/000015.log b/Data/systems/pf2e/packs/paizo-pregens/000006.log similarity index 100% rename from Data/systems/pf2e/packs/paizo-pregens/000015.log rename to Data/systems/pf2e/packs/paizo-pregens/000006.log diff --git a/Data/systems/pf2e/packs/paizo-pregens/CURRENT b/Data/systems/pf2e/packs/paizo-pregens/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/paizo-pregens/CURRENT +++ b/Data/systems/pf2e/packs/paizo-pregens/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/paizo-pregens/LOG b/Data/systems/pf2e/packs/paizo-pregens/LOG index 5934422d..d38083a5 100644 --- a/Data/systems/pf2e/packs/paizo-pregens/LOG +++ b/Data/systems/pf2e/packs/paizo-pregens/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.913170 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.918944 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.918965 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:18.453095 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:18.458453 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:18.479485 ffff86fdf0a0 Level-0 table #5: 1678573 bytes OK +2023/10/23-05:12:18.484218 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:18.484860 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/paizo-pregens/LOG.old b/Data/systems/pf2e/packs/paizo-pregens/LOG.old index 9f8bbcbb..474cb1b1 100644 --- a/Data/systems/pf2e/packs/paizo-pregens/LOG.old +++ b/Data/systems/pf2e/packs/paizo-pregens/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.780926 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.786201 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.786224 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.604555 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.604569 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.606281 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.608345 ffff85fbf0a0 Manual compaction at level-0 from '!actors!1NE3CrEExL2QZvEk' @ 72057594037927935 : 1 .. '!actors.items!zo0OV4kxZ4LntHkU.ybnmmMexX81A8eJZ' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.702556 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/paizo-pregens/MANIFEST-000004 b/Data/systems/pf2e/packs/paizo-pregens/MANIFEST-000004 new file mode 100644 index 00000000..c933759d Binary files /dev/null and b/Data/systems/pf2e/packs/paizo-pregens/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/paizo-pregens/MANIFEST-000014 b/Data/systems/pf2e/packs/paizo-pregens/MANIFEST-000014 deleted file mode 100644 index db38ecd6..00000000 Binary files a/Data/systems/pf2e/packs/paizo-pregens/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-2/000009.ldb b/Data/systems/pf2e/packs/pathfinder-bestiary-2/000005.ldb similarity index 57% rename from Data/systems/pf2e/packs/pathfinder-bestiary-2/000009.ldb rename to Data/systems/pf2e/packs/pathfinder-bestiary-2/000005.ldb index 3fb884b1..435b30c7 100644 Binary files a/Data/systems/pf2e/packs/pathfinder-bestiary-2/000009.ldb and b/Data/systems/pf2e/packs/pathfinder-bestiary-2/000005.ldb differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-2/000016.log b/Data/systems/pf2e/packs/pathfinder-bestiary-2/000006.log similarity index 100% rename from Data/systems/pf2e/packs/pathfinder-bestiary-2/000016.log rename to Data/systems/pf2e/packs/pathfinder-bestiary-2/000006.log diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-2/000010.ldb b/Data/systems/pf2e/packs/pathfinder-bestiary-2/000010.ldb deleted file mode 100644 index d3e5776d..00000000 Binary files a/Data/systems/pf2e/packs/pathfinder-bestiary-2/000010.ldb and /dev/null differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-2/CURRENT b/Data/systems/pf2e/packs/pathfinder-bestiary-2/CURRENT index 42c62b67..cacca757 100644 --- a/Data/systems/pf2e/packs/pathfinder-bestiary-2/CURRENT +++ b/Data/systems/pf2e/packs/pathfinder-bestiary-2/CURRENT @@ -1 +1 @@ -MANIFEST-000015 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-2/LOG b/Data/systems/pf2e/packs/pathfinder-bestiary-2/LOG index 2e9cb0e3..85d880fc 100644 --- a/Data/systems/pf2e/packs/pathfinder-bestiary-2/LOG +++ b/Data/systems/pf2e/packs/pathfinder-bestiary-2/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.171980 ffff867cf0a0 Recovering log #13 -2023/10/20-07:55:10.177430 ffff867cf0a0 Delete type=0 #13 -2023/10/20-07:55:10.177451 ffff867cf0a0 Delete type=3 #11 +2023/10/23-05:12:17.063370 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:17.076708 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:17.130299 ffff87fff0a0 Level-0 table #5: 3711251 bytes OK +2023/10/23-05:12:17.135911 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:17.137734 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-2/LOG.old b/Data/systems/pf2e/packs/pathfinder-bestiary-2/LOG.old index 62769d06..f2136eb6 100644 --- a/Data/systems/pf2e/packs/pathfinder-bestiary-2/LOG.old +++ b/Data/systems/pf2e/packs/pathfinder-bestiary-2/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.028012 ffff86fdf0a0 Recovering log #7 -2023/10/20-07:41:11.033437 ffff86fdf0a0 Delete type=3 #4 -2023/10/20-07:41:11.033461 ffff86fdf0a0 Delete type=0 #7 -2023/10/20-07:49:07.517052 ffff85fbf0a0 Level-0 table #14: started -2023/10/20-07:49:07.517074 ffff85fbf0a0 Level-0 table #14: 0 bytes OK -2023/10/20-07:49:07.518907 ffff85fbf0a0 Delete type=0 #12 -2023/10/20-07:49:07.522620 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0rhltfBkQtYkCwXd' @ 72057594037927935 : 1 .. '!actors.items!zzu3q9m4kJzgnNfl.yoc8sNwSb16TykKF' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.706398 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-2/MANIFEST-000004 b/Data/systems/pf2e/packs/pathfinder-bestiary-2/MANIFEST-000004 new file mode 100644 index 00000000..5cd74466 Binary files /dev/null and b/Data/systems/pf2e/packs/pathfinder-bestiary-2/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-2/MANIFEST-000015 b/Data/systems/pf2e/packs/pathfinder-bestiary-2/MANIFEST-000015 deleted file mode 100644 index a55c1770..00000000 Binary files a/Data/systems/pf2e/packs/pathfinder-bestiary-2/MANIFEST-000015 and /dev/null differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-3/000005.ldb b/Data/systems/pf2e/packs/pathfinder-bestiary-3/000005.ldb new file mode 100644 index 00000000..00d52a4c Binary files /dev/null and b/Data/systems/pf2e/packs/pathfinder-bestiary-3/000005.ldb differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-3/000017.log b/Data/systems/pf2e/packs/pathfinder-bestiary-3/000006.log similarity index 100% rename from Data/systems/pf2e/packs/pathfinder-bestiary-3/000017.log rename to Data/systems/pf2e/packs/pathfinder-bestiary-3/000006.log diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-3/000009.ldb b/Data/systems/pf2e/packs/pathfinder-bestiary-3/000009.ldb deleted file mode 100644 index 05d420ce..00000000 Binary files a/Data/systems/pf2e/packs/pathfinder-bestiary-3/000009.ldb and /dev/null differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-3/000010.ldb b/Data/systems/pf2e/packs/pathfinder-bestiary-3/000010.ldb deleted file mode 100644 index fb8febf1..00000000 Binary files a/Data/systems/pf2e/packs/pathfinder-bestiary-3/000010.ldb and /dev/null differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-3/000011.ldb b/Data/systems/pf2e/packs/pathfinder-bestiary-3/000011.ldb deleted file mode 100644 index 0815e20c..00000000 Binary files a/Data/systems/pf2e/packs/pathfinder-bestiary-3/000011.ldb and /dev/null differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-3/CURRENT b/Data/systems/pf2e/packs/pathfinder-bestiary-3/CURRENT index 32108be6..cacca757 100644 --- a/Data/systems/pf2e/packs/pathfinder-bestiary-3/CURRENT +++ b/Data/systems/pf2e/packs/pathfinder-bestiary-3/CURRENT @@ -1 +1 @@ -MANIFEST-000016 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-3/LOG b/Data/systems/pf2e/packs/pathfinder-bestiary-3/LOG index 0dc4b6a6..7c721d78 100644 --- a/Data/systems/pf2e/packs/pathfinder-bestiary-3/LOG +++ b/Data/systems/pf2e/packs/pathfinder-bestiary-3/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.210582 ffff86fdf0a0 Recovering log #14 -2023/10/20-07:55:10.216478 ffff86fdf0a0 Delete type=0 #14 -2023/10/20-07:55:10.216499 ffff86fdf0a0 Delete type=3 #12 +2023/10/23-05:12:17.171993 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:17.187123 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:17.252362 ffff86fdf0a0 Level-0 table #5: 4378205 bytes OK +2023/10/23-05:12:17.258128 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:17.259505 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-3/LOG.old b/Data/systems/pf2e/packs/pathfinder-bestiary-3/LOG.old index 2e3dd0ff..74ebecb6 100644 --- a/Data/systems/pf2e/packs/pathfinder-bestiary-3/LOG.old +++ b/Data/systems/pf2e/packs/pathfinder-bestiary-3/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.066899 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.071811 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.071837 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.518945 ffff85fbf0a0 Level-0 table #15: started -2023/10/20-07:49:07.518959 ffff85fbf0a0 Level-0 table #15: 0 bytes OK -2023/10/20-07:49:07.520595 ffff85fbf0a0 Delete type=0 #13 -2023/10/20-07:49:07.522740 ffff85fbf0a0 Manual compaction at level-0 from '!actors!01alXdlOUvAC6woS' @ 72057594037927935 : 1 .. '!actors.items!zdJgaVe6VRSfEE1n.ztbAEwewoiM3nyRj' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.704366 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-3/MANIFEST-000004 b/Data/systems/pf2e/packs/pathfinder-bestiary-3/MANIFEST-000004 new file mode 100644 index 00000000..87400a38 Binary files /dev/null and b/Data/systems/pf2e/packs/pathfinder-bestiary-3/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary-3/MANIFEST-000016 b/Data/systems/pf2e/packs/pathfinder-bestiary-3/MANIFEST-000016 deleted file mode 100644 index b2c0a47d..00000000 Binary files a/Data/systems/pf2e/packs/pathfinder-bestiary-3/MANIFEST-000016 and /dev/null differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary/000005.ldb b/Data/systems/pf2e/packs/pathfinder-bestiary/000005.ldb new file mode 100644 index 00000000..0eee7afe Binary files /dev/null and b/Data/systems/pf2e/packs/pathfinder-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary/000017.log b/Data/systems/pf2e/packs/pathfinder-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/pathfinder-bestiary/000017.log rename to Data/systems/pf2e/packs/pathfinder-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary/000009.ldb b/Data/systems/pf2e/packs/pathfinder-bestiary/000009.ldb deleted file mode 100644 index 3c65e1e8..00000000 Binary files a/Data/systems/pf2e/packs/pathfinder-bestiary/000009.ldb and /dev/null differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary/000010.ldb b/Data/systems/pf2e/packs/pathfinder-bestiary/000010.ldb deleted file mode 100644 index 2766f1fb..00000000 Binary files a/Data/systems/pf2e/packs/pathfinder-bestiary/000010.ldb and /dev/null differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary/000011.ldb b/Data/systems/pf2e/packs/pathfinder-bestiary/000011.ldb deleted file mode 100644 index 2265869a..00000000 Binary files a/Data/systems/pf2e/packs/pathfinder-bestiary/000011.ldb and /dev/null differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary/CURRENT b/Data/systems/pf2e/packs/pathfinder-bestiary/CURRENT index 32108be6..cacca757 100644 --- a/Data/systems/pf2e/packs/pathfinder-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/pathfinder-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000016 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary/LOG b/Data/systems/pf2e/packs/pathfinder-bestiary/LOG index 899acd0a..2e04bcb5 100644 --- a/Data/systems/pf2e/packs/pathfinder-bestiary/LOG +++ b/Data/systems/pf2e/packs/pathfinder-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.121541 ffff877ef0a0 Recovering log #14 -2023/10/20-07:55:10.126840 ffff877ef0a0 Delete type=0 #14 -2023/10/20-07:55:10.126861 ffff877ef0a0 Delete type=3 #12 +2023/10/23-05:12:16.906987 ffff867cf0a0 Recovering log #3 +2023/10/23-05:12:16.927100 ffff867cf0a0 Level-0 table #5: started +2023/10/23-05:12:17.004953 ffff867cf0a0 Level-0 table #5: 5306423 bytes OK +2023/10/23-05:12:17.011235 ffff867cf0a0 Delete type=0 #3 +2023/10/23-05:12:17.013382 ffff867cf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary/LOG.old b/Data/systems/pf2e/packs/pathfinder-bestiary/LOG.old index 837547f3..730d744a 100644 --- a/Data/systems/pf2e/packs/pathfinder-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/pathfinder-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.976973 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:10.982225 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:10.982250 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.514801 ffff85fbf0a0 Level-0 table #15: started -2023/10/20-07:49:07.514823 ffff85fbf0a0 Level-0 table #15: 0 bytes OK -2023/10/20-07:49:07.516895 ffff85fbf0a0 Delete type=0 #13 -2023/10/20-07:49:07.520633 ffff85fbf0a0 Manual compaction at level-0 from '!actors!024PqcF8yMRBrPuq' @ 72057594037927935 : 1 .. '!actors.items!zq18QX6CBJNeUIgG.yTXiHzmRavI1BmKJ' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.704548 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/pathfinder-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..82d1bcd8 Binary files /dev/null and b/Data/systems/pf2e/packs/pathfinder-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/pathfinder-bestiary/MANIFEST-000016 b/Data/systems/pf2e/packs/pathfinder-bestiary/MANIFEST-000016 deleted file mode 100644 index a71f443e..00000000 Binary files a/Data/systems/pf2e/packs/pathfinder-bestiary/MANIFEST-000016 and /dev/null differ diff --git a/Data/systems/pf2e/packs/pathfinder-dark-archive/000009.ldb b/Data/systems/pf2e/packs/pathfinder-dark-archive/000005.ldb similarity index 90% rename from Data/systems/pf2e/packs/pathfinder-dark-archive/000009.ldb rename to Data/systems/pf2e/packs/pathfinder-dark-archive/000005.ldb index 2f8e8a9f..fa640966 100644 Binary files a/Data/systems/pf2e/packs/pathfinder-dark-archive/000009.ldb and b/Data/systems/pf2e/packs/pathfinder-dark-archive/000005.ldb differ diff --git a/Data/systems/pf2e/packs/pathfinder-dark-archive/000015.log b/Data/systems/pf2e/packs/pathfinder-dark-archive/000006.log similarity index 100% rename from Data/systems/pf2e/packs/pathfinder-dark-archive/000015.log rename to Data/systems/pf2e/packs/pathfinder-dark-archive/000006.log diff --git a/Data/systems/pf2e/packs/pathfinder-dark-archive/CURRENT b/Data/systems/pf2e/packs/pathfinder-dark-archive/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/pathfinder-dark-archive/CURRENT +++ b/Data/systems/pf2e/packs/pathfinder-dark-archive/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/pathfinder-dark-archive/LOG b/Data/systems/pf2e/packs/pathfinder-dark-archive/LOG index 12f16965..0d97ce44 100644 --- a/Data/systems/pf2e/packs/pathfinder-dark-archive/LOG +++ b/Data/systems/pf2e/packs/pathfinder-dark-archive/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.253255 ffff877ef0a0 Recovering log #12 -2023/10/20-07:55:10.259009 ffff877ef0a0 Delete type=0 #12 -2023/10/20-07:55:10.259030 ffff877ef0a0 Delete type=3 #10 +2023/10/23-05:12:17.297304 ffff867cf0a0 Recovering log #3 +2023/10/23-05:12:17.297665 ffff867cf0a0 Level-0 table #5: started +2023/10/23-05:12:17.301075 ffff867cf0a0 Level-0 table #5: 94483 bytes OK +2023/10/23-05:12:17.306227 ffff867cf0a0 Delete type=0 #3 +2023/10/23-05:12:17.306282 ffff867cf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/pathfinder-dark-archive/LOG.old b/Data/systems/pf2e/packs/pathfinder-dark-archive/LOG.old index 14760425..98e4fcc7 100644 --- a/Data/systems/pf2e/packs/pathfinder-dark-archive/LOG.old +++ b/Data/systems/pf2e/packs/pathfinder-dark-archive/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.219402 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.224767 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.224823 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.520757 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.520813 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.522580 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.524638 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0AdtolhMWrPlzVZY' @ 72057594037927935 : 1 .. '!actors.items!wmKvVsfc6Hg1Bj8I.vt810lsvoNHLaCNF' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.705269 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/pathfinder-dark-archive/MANIFEST-000004 b/Data/systems/pf2e/packs/pathfinder-dark-archive/MANIFEST-000004 new file mode 100644 index 00000000..5bd84dbb Binary files /dev/null and b/Data/systems/pf2e/packs/pathfinder-dark-archive/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/pathfinder-dark-archive/MANIFEST-000014 b/Data/systems/pf2e/packs/pathfinder-dark-archive/MANIFEST-000014 deleted file mode 100644 index 0e9208b9..00000000 Binary files a/Data/systems/pf2e/packs/pathfinder-dark-archive/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/pathfinder-society-boons/000009.ldb b/Data/systems/pf2e/packs/pathfinder-society-boons/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/pathfinder-society-boons/000009.ldb rename to Data/systems/pf2e/packs/pathfinder-society-boons/000005.ldb diff --git a/Data/systems/pf2e/packs/pathfinder-society-boons/000015.log b/Data/systems/pf2e/packs/pathfinder-society-boons/000006.log similarity index 100% rename from Data/systems/pf2e/packs/pathfinder-society-boons/000015.log rename to Data/systems/pf2e/packs/pathfinder-society-boons/000006.log diff --git a/Data/systems/pf2e/packs/pathfinder-society-boons/CURRENT b/Data/systems/pf2e/packs/pathfinder-society-boons/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/pathfinder-society-boons/CURRENT +++ b/Data/systems/pf2e/packs/pathfinder-society-boons/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/pathfinder-society-boons/LOG b/Data/systems/pf2e/packs/pathfinder-society-boons/LOG index 6ae83412..9ec6cef6 100644 --- a/Data/systems/pf2e/packs/pathfinder-society-boons/LOG +++ b/Data/systems/pf2e/packs/pathfinder-society-boons/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.830436 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.835967 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.835985 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:18.234387 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:18.234703 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:18.238041 ffff86fdf0a0 Level-0 table #5: 82652 bytes OK +2023/10/23-05:12:18.243077 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:18.243135 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/pathfinder-society-boons/LOG.old b/Data/systems/pf2e/packs/pathfinder-society-boons/LOG.old index 33900b07..d7800daf 100644 --- a/Data/systems/pf2e/packs/pathfinder-society-boons/LOG.old +++ b/Data/systems/pf2e/packs/pathfinder-society-boons/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.706574 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.711282 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.711305 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.595148 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.595168 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.596894 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.600648 ffff85fbf0a0 Manual compaction at level-0 from '!items!0CqkYRFUlb0tB9li' @ 72057594037927935 : 1 .. '!items!ybrynsFe4a0jJcgz' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.708250 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/pathfinder-society-boons/MANIFEST-000004 b/Data/systems/pf2e/packs/pathfinder-society-boons/MANIFEST-000004 new file mode 100644 index 00000000..cad1a445 Binary files /dev/null and b/Data/systems/pf2e/packs/pathfinder-society-boons/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/pathfinder-society-boons/MANIFEST-000014 b/Data/systems/pf2e/packs/pathfinder-society-boons/MANIFEST-000014 deleted file mode 100644 index 34fe0355..00000000 Binary files a/Data/systems/pf2e/packs/pathfinder-society-boons/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/pfs-introductions-bestiary/000009.ldb b/Data/systems/pf2e/packs/pfs-introductions-bestiary/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/pfs-introductions-bestiary/000009.ldb rename to Data/systems/pf2e/packs/pfs-introductions-bestiary/000005.ldb diff --git a/Data/systems/pf2e/packs/pfs-introductions-bestiary/000015.log b/Data/systems/pf2e/packs/pfs-introductions-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/pfs-introductions-bestiary/000015.log rename to Data/systems/pf2e/packs/pfs-introductions-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/pfs-introductions-bestiary/CURRENT b/Data/systems/pf2e/packs/pfs-introductions-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/pfs-introductions-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/pfs-introductions-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/pfs-introductions-bestiary/LOG b/Data/systems/pf2e/packs/pfs-introductions-bestiary/LOG index 19bd9e0f..b569d12e 100644 --- a/Data/systems/pf2e/packs/pfs-introductions-bestiary/LOG +++ b/Data/systems/pf2e/packs/pfs-introductions-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.269969 ffff867cf0a0 Recovering log #12 -2023/10/20-07:55:10.275448 ffff867cf0a0 Delete type=0 #12 -2023/10/20-07:55:10.275467 ffff867cf0a0 Delete type=3 #10 +2023/10/23-05:12:17.309170 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:17.309317 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:17.312081 ffff87fff0a0 Level-0 table #5: 36057 bytes OK +2023/10/23-05:12:17.316821 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:17.316858 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/pfs-introductions-bestiary/LOG.old b/Data/systems/pf2e/packs/pfs-introductions-bestiary/LOG.old index e69b88b4..e53394c4 100644 --- a/Data/systems/pf2e/packs/pfs-introductions-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/pfs-introductions-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.229638 ffff86fdf0a0 Recovering log #7 -2023/10/20-07:41:11.234476 ffff86fdf0a0 Delete type=3 #4 -2023/10/20-07:41:11.234499 ffff86fdf0a0 Delete type=0 #7 -2023/10/20-07:49:07.522838 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.522856 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.524599 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.528330 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0B7h7yvceKuI2SFJ' @ 72057594037927935 : 1 .. '!actors.items!uNUQujgmyavb52Xa.krjZ9lqVkGcDTbNl' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.707800 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/pfs-introductions-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/pfs-introductions-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..049aa4f4 Binary files /dev/null and b/Data/systems/pf2e/packs/pfs-introductions-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/pfs-introductions-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/pfs-introductions-bestiary/MANIFEST-000014 deleted file mode 100644 index a366dba7..00000000 Binary files a/Data/systems/pf2e/packs/pfs-introductions-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/pfs-season-1-bestiary/000009.ldb b/Data/systems/pf2e/packs/pfs-season-1-bestiary/000005.ldb similarity index 94% rename from Data/systems/pf2e/packs/pfs-season-1-bestiary/000009.ldb rename to Data/systems/pf2e/packs/pfs-season-1-bestiary/000005.ldb index 67ed1360..ad6bdc7e 100644 Binary files a/Data/systems/pf2e/packs/pfs-season-1-bestiary/000009.ldb and b/Data/systems/pf2e/packs/pfs-season-1-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/pfs-season-1-bestiary/000015.log b/Data/systems/pf2e/packs/pfs-season-1-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/pfs-season-1-bestiary/000015.log rename to Data/systems/pf2e/packs/pfs-season-1-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/pfs-season-1-bestiary/CURRENT b/Data/systems/pf2e/packs/pfs-season-1-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/pfs-season-1-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/pfs-season-1-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/pfs-season-1-bestiary/LOG b/Data/systems/pf2e/packs/pfs-season-1-bestiary/LOG index 9a1f6462..ec36a920 100644 --- a/Data/systems/pf2e/packs/pfs-season-1-bestiary/LOG +++ b/Data/systems/pf2e/packs/pfs-season-1-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.277870 ffff877ef0a0 Recovering log #12 -2023/10/20-07:55:10.283334 ffff877ef0a0 Delete type=0 #12 -2023/10/20-07:55:10.283353 ffff877ef0a0 Delete type=3 #10 +2023/10/23-05:12:17.319139 ffff867cf0a0 Recovering log #3 +2023/10/23-05:12:17.326875 ffff867cf0a0 Level-0 table #5: started +2023/10/23-05:12:17.356183 ffff867cf0a0 Level-0 table #5: 2065521 bytes OK +2023/10/23-05:12:17.361231 ffff867cf0a0 Delete type=0 #3 +2023/10/23-05:12:17.361976 ffff867cf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/pfs-season-1-bestiary/LOG.old b/Data/systems/pf2e/packs/pfs-season-1-bestiary/LOG.old index ba5ae030..ea0e8210 100644 --- a/Data/systems/pf2e/packs/pfs-season-1-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/pfs-season-1-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.236980 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.242085 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.242109 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.524758 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.524812 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.526561 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.530380 ffff85fbf0a0 Manual compaction at level-0 from '!actors!02MIBcyPwCEmh8lA' @ 72057594037927935 : 1 .. '!actors.items!zveTUg1NtYmTwlFn.xmfwRP62FdWdbVsu' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.708039 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/pfs-season-1-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/pfs-season-1-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..0a61a680 Binary files /dev/null and b/Data/systems/pf2e/packs/pfs-season-1-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/pfs-season-1-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/pfs-season-1-bestiary/MANIFEST-000014 deleted file mode 100644 index 44d7609e..00000000 Binary files a/Data/systems/pf2e/packs/pfs-season-1-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/pfs-season-2-bestiary/000009.ldb b/Data/systems/pf2e/packs/pfs-season-2-bestiary/000005.ldb similarity index 97% rename from Data/systems/pf2e/packs/pfs-season-2-bestiary/000009.ldb rename to Data/systems/pf2e/packs/pfs-season-2-bestiary/000005.ldb index 425e2b6a..dabeae6a 100644 Binary files a/Data/systems/pf2e/packs/pfs-season-2-bestiary/000009.ldb and b/Data/systems/pf2e/packs/pfs-season-2-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/pfs-season-2-bestiary/000015.log b/Data/systems/pf2e/packs/pfs-season-2-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/pfs-season-2-bestiary/000015.log rename to Data/systems/pf2e/packs/pfs-season-2-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/pfs-season-2-bestiary/CURRENT b/Data/systems/pf2e/packs/pfs-season-2-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/pfs-season-2-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/pfs-season-2-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/pfs-season-2-bestiary/LOG b/Data/systems/pf2e/packs/pfs-season-2-bestiary/LOG index 7bba3640..933fbc31 100644 --- a/Data/systems/pf2e/packs/pfs-season-2-bestiary/LOG +++ b/Data/systems/pf2e/packs/pfs-season-2-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.302697 ffff867cf0a0 Recovering log #12 -2023/10/20-07:55:10.308525 ffff867cf0a0 Delete type=0 #12 -2023/10/20-07:55:10.308545 ffff867cf0a0 Delete type=3 #10 +2023/10/23-05:12:17.386012 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:17.391681 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:17.412232 ffff87fff0a0 Level-0 table #5: 1539382 bytes OK +2023/10/23-05:12:17.416924 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:17.417428 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/pfs-season-2-bestiary/LOG.old b/Data/systems/pf2e/packs/pfs-season-2-bestiary/LOG.old index fb4ed55a..b60d7ee4 100644 --- a/Data/systems/pf2e/packs/pfs-season-2-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/pfs-season-2-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.261545 ffff86fdf0a0 Recovering log #7 -2023/10/20-07:41:11.266500 ffff86fdf0a0 Delete type=3 #4 -2023/10/20-07:41:11.266524 ffff86fdf0a0 Delete type=0 #7 -2023/10/20-07:49:07.526599 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.526614 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.528292 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.530504 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0ATZwmS2yxbheza4' @ 72057594037927935 : 1 .. '!actors.items!zpIVn1k5nsR0sMZ8.myrVlXNqGxkZox9I' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.711253 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/pfs-season-2-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/pfs-season-2-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..970dda97 Binary files /dev/null and b/Data/systems/pf2e/packs/pfs-season-2-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/pfs-season-2-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/pfs-season-2-bestiary/MANIFEST-000014 deleted file mode 100644 index c513ba52..00000000 Binary files a/Data/systems/pf2e/packs/pfs-season-2-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/pfs-season-3-bestiary/000009.ldb b/Data/systems/pf2e/packs/pfs-season-3-bestiary/000005.ldb similarity index 97% rename from Data/systems/pf2e/packs/pfs-season-3-bestiary/000009.ldb rename to Data/systems/pf2e/packs/pfs-season-3-bestiary/000005.ldb index f91cb9ae..139733cd 100644 Binary files a/Data/systems/pf2e/packs/pfs-season-3-bestiary/000009.ldb and b/Data/systems/pf2e/packs/pfs-season-3-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/pfs-season-3-bestiary/000015.log b/Data/systems/pf2e/packs/pfs-season-3-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/pfs-season-3-bestiary/000015.log rename to Data/systems/pf2e/packs/pfs-season-3-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/pfs-season-3-bestiary/CURRENT b/Data/systems/pf2e/packs/pfs-season-3-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/pfs-season-3-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/pfs-season-3-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/pfs-season-3-bestiary/LOG b/Data/systems/pf2e/packs/pfs-season-3-bestiary/LOG index 112d37a5..9eb38754 100644 --- a/Data/systems/pf2e/packs/pfs-season-3-bestiary/LOG +++ b/Data/systems/pf2e/packs/pfs-season-3-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.324719 ffff877ef0a0 Recovering log #12 -2023/10/20-07:55:10.330350 ffff877ef0a0 Delete type=0 #12 -2023/10/20-07:55:10.330370 ffff877ef0a0 Delete type=3 #10 +2023/10/23-05:12:17.435043 ffff867cf0a0 Recovering log #3 +2023/10/23-05:12:17.441463 ffff867cf0a0 Level-0 table #5: started +2023/10/23-05:12:17.465526 ffff867cf0a0 Level-0 table #5: 1726659 bytes OK +2023/10/23-05:12:17.470178 ffff867cf0a0 Delete type=0 #3 +2023/10/23-05:12:17.470752 ffff867cf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/pfs-season-3-bestiary/LOG.old b/Data/systems/pf2e/packs/pfs-season-3-bestiary/LOG.old index 73338dc1..c36e2781 100644 --- a/Data/systems/pf2e/packs/pfs-season-3-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/pfs-season-3-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.282353 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.287687 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.287711 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.528448 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.528471 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.530341 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.532418 ffff85fbf0a0 Manual compaction at level-0 from '!actors!06XCiuS7ZDEM5Xpf' @ 72057594037927935 : 1 .. '!actors.items!zzbBBSmjvCzJ6lyt.ygcqxglhl1ki3ua7' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.710842 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/pfs-season-3-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/pfs-season-3-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..3d563fc2 Binary files /dev/null and b/Data/systems/pf2e/packs/pfs-season-3-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/pfs-season-3-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/pfs-season-3-bestiary/MANIFEST-000014 deleted file mode 100644 index 81910646..00000000 Binary files a/Data/systems/pf2e/packs/pfs-season-3-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/pfs-season-4-bestiary/000009.ldb b/Data/systems/pf2e/packs/pfs-season-4-bestiary/000005.ldb similarity index 98% rename from Data/systems/pf2e/packs/pfs-season-4-bestiary/000009.ldb rename to Data/systems/pf2e/packs/pfs-season-4-bestiary/000005.ldb index afd2d8c0..34d26b13 100644 Binary files a/Data/systems/pf2e/packs/pfs-season-4-bestiary/000009.ldb and b/Data/systems/pf2e/packs/pfs-season-4-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/pfs-season-4-bestiary/000015.log b/Data/systems/pf2e/packs/pfs-season-4-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/pfs-season-4-bestiary/000015.log rename to Data/systems/pf2e/packs/pfs-season-4-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/pfs-season-4-bestiary/CURRENT b/Data/systems/pf2e/packs/pfs-season-4-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/pfs-season-4-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/pfs-season-4-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/pfs-season-4-bestiary/LOG b/Data/systems/pf2e/packs/pfs-season-4-bestiary/LOG index de2661b6..7e2a871f 100644 --- a/Data/systems/pf2e/packs/pfs-season-4-bestiary/LOG +++ b/Data/systems/pf2e/packs/pfs-season-4-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.349447 ffff867cf0a0 Recovering log #12 -2023/10/20-07:55:10.354702 ffff867cf0a0 Delete type=0 #12 -2023/10/20-07:55:10.354722 ffff867cf0a0 Delete type=3 #10 +2023/10/23-05:12:17.489267 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:17.495594 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:17.520541 ffff87fff0a0 Level-0 table #5: 1824190 bytes OK +2023/10/23-05:12:17.525591 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:17.526180 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/pfs-season-4-bestiary/LOG.old b/Data/systems/pf2e/packs/pfs-season-4-bestiary/LOG.old index e396a61d..a3a44706 100644 --- a/Data/systems/pf2e/packs/pfs-season-4-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/pfs-season-4-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.304598 ffff86fdf0a0 Recovering log #7 -2023/10/20-07:41:11.310077 ffff86fdf0a0 Delete type=3 #4 -2023/10/20-07:41:11.310101 ffff86fdf0a0 Delete type=0 #7 -2023/10/20-07:49:07.530595 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.530614 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.532379 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.536030 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0x30gt2GzALItGAh' @ 72057594037927935 : 1 .. '!actors.items!zmOYvFVhxA6zDEBg.eKNIz9F33vxP8JS5' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.712836 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/pfs-season-4-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/pfs-season-4-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..f3810a00 Binary files /dev/null and b/Data/systems/pf2e/packs/pfs-season-4-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/pfs-season-4-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/pfs-season-4-bestiary/MANIFEST-000014 deleted file mode 100644 index 5e799a52..00000000 Binary files a/Data/systems/pf2e/packs/pfs-season-4-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/pfs-season-5-bestiary/000009.ldb b/Data/systems/pf2e/packs/pfs-season-5-bestiary/000005.ldb similarity index 74% rename from Data/systems/pf2e/packs/pfs-season-5-bestiary/000009.ldb rename to Data/systems/pf2e/packs/pfs-season-5-bestiary/000005.ldb index 78032d2f..19acaefb 100644 Binary files a/Data/systems/pf2e/packs/pfs-season-5-bestiary/000009.ldb and b/Data/systems/pf2e/packs/pfs-season-5-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/pfs-season-5-bestiary/000015.log b/Data/systems/pf2e/packs/pfs-season-5-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/pfs-season-5-bestiary/000015.log rename to Data/systems/pf2e/packs/pfs-season-5-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/pfs-season-5-bestiary/CURRENT b/Data/systems/pf2e/packs/pfs-season-5-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/pfs-season-5-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/pfs-season-5-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/pfs-season-5-bestiary/LOG b/Data/systems/pf2e/packs/pfs-season-5-bestiary/LOG index 99a3e05e..5ce19c0b 100644 --- a/Data/systems/pf2e/packs/pfs-season-5-bestiary/LOG +++ b/Data/systems/pf2e/packs/pfs-season-5-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.371893 ffff877ef0a0 Recovering log #12 -2023/10/20-07:55:10.376815 ffff877ef0a0 Delete type=0 #12 -2023/10/20-07:55:10.376835 ffff877ef0a0 Delete type=3 #10 +2023/10/23-05:12:17.544747 ffff867cf0a0 Recovering log #3 +2023/10/23-05:12:17.545886 ffff867cf0a0 Level-0 table #5: started +2023/10/23-05:12:17.551771 ffff867cf0a0 Level-0 table #5: 298466 bytes OK +2023/10/23-05:12:17.557604 ffff867cf0a0 Delete type=0 #3 +2023/10/23-05:12:17.557729 ffff867cf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/pfs-season-5-bestiary/LOG.old b/Data/systems/pf2e/packs/pfs-season-5-bestiary/LOG.old index 2999c601..77b5d69b 100644 --- a/Data/systems/pf2e/packs/pfs-season-5-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/pfs-season-5-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.328432 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.333953 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.333978 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.532538 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.532561 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.534392 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.537873 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0dfF8IyWHPop4IR6' @ 72057594037927935 : 1 .. '!actors.items!ytb75tCpHFXxryFZ.guZzNdz6Rwxovmsa' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.711689 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/pfs-season-5-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/pfs-season-5-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..d1e5d42e Binary files /dev/null and b/Data/systems/pf2e/packs/pfs-season-5-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/pfs-season-5-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/pfs-season-5-bestiary/MANIFEST-000014 deleted file mode 100644 index b9a1b991..00000000 Binary files a/Data/systems/pf2e/packs/pfs-season-5-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/000009.ldb b/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/000005.ldb similarity index 96% rename from Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/000009.ldb rename to Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/000005.ldb index 83d8c7de..8d614712 100644 Binary files a/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/000009.ldb and b/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/000015.log b/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/000015.log rename to Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/CURRENT b/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/LOG b/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/LOG index 33e25cd2..12471f1e 100644 --- a/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/LOG +++ b/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.381447 ffff877ef0a0 Recovering log #12 -2023/10/20-07:55:10.386718 ffff877ef0a0 Delete type=0 #12 -2023/10/20-07:55:10.386736 ffff877ef0a0 Delete type=3 #10 +2023/10/23-05:12:17.563697 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:17.565953 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:17.575103 ffff877ef0a0 Level-0 table #5: 625808 bytes OK +2023/10/23-05:12:17.579501 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:17.579718 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/LOG.old b/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/LOG.old index 61b6340c..6d988ddf 100644 --- a/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.341077 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.345974 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.345998 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.534429 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.534443 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.535992 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.538001 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0GArHVfN0VxejVZp' @ 72057594037927935 : 1 .. '!actors.items!zXTacktEPpjUlYr3.z62u9f54lyh5rr58' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.714257 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..6b4ee245 Binary files /dev/null and b/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/MANIFEST-000014 deleted file mode 100644 index adc7e0c9..00000000 Binary files a/Data/systems/pf2e/packs/quest-for-the-frozen-flame-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/rage-of-elements-bestiary/000009.ldb b/Data/systems/pf2e/packs/rage-of-elements-bestiary/000005.ldb similarity index 89% rename from Data/systems/pf2e/packs/rage-of-elements-bestiary/000009.ldb rename to Data/systems/pf2e/packs/rage-of-elements-bestiary/000005.ldb index aac615f4..c827718b 100644 Binary files a/Data/systems/pf2e/packs/rage-of-elements-bestiary/000009.ldb and b/Data/systems/pf2e/packs/rage-of-elements-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/rage-of-elements-bestiary/000015.log b/Data/systems/pf2e/packs/rage-of-elements-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/rage-of-elements-bestiary/000015.log rename to Data/systems/pf2e/packs/rage-of-elements-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/rage-of-elements-bestiary/CURRENT b/Data/systems/pf2e/packs/rage-of-elements-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/rage-of-elements-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/rage-of-elements-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/rage-of-elements-bestiary/LOG b/Data/systems/pf2e/packs/rage-of-elements-bestiary/LOG index 0b434ef4..c72a3593 100644 --- a/Data/systems/pf2e/packs/rage-of-elements-bestiary/LOG +++ b/Data/systems/pf2e/packs/rage-of-elements-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.619772 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.625421 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.625441 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:17.860435 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:17.863052 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:17.881699 ffff877ef0a0 Level-0 table #5: 751790 bytes OK +2023/10/23-05:12:17.886479 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:17.886741 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/rage-of-elements-bestiary/LOG.old b/Data/systems/pf2e/packs/rage-of-elements-bestiary/LOG.old index 12f83155..29098a06 100644 --- a/Data/systems/pf2e/packs/rage-of-elements-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/rage-of-elements-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.503841 ffff877ef0a0 Recovering log #7 -2023/10/20-07:41:11.509117 ffff877ef0a0 Delete type=3 #4 -2023/10/20-07:41:11.509140 ffff877ef0a0 Delete type=0 #7 -2023/10/20-07:49:07.557247 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.557261 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.558868 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.560994 ffff85fbf0a0 Manual compaction at level-0 from '!actors!1cpG2DuXPXq3DMBx' @ 72057594037927935 : 1 .. '!actors.items!zBUFjuz3dR8bacee.odu8Xo2gEpO7H1fa' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.715814 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/rage-of-elements-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/rage-of-elements-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..90218e58 Binary files /dev/null and b/Data/systems/pf2e/packs/rage-of-elements-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/rage-of-elements-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/rage-of-elements-bestiary/MANIFEST-000014 deleted file mode 100644 index efb30f25..00000000 Binary files a/Data/systems/pf2e/packs/rage-of-elements-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/rollable-tables/000009.ldb b/Data/systems/pf2e/packs/rollable-tables/000005.ldb similarity index 95% rename from Data/systems/pf2e/packs/rollable-tables/000009.ldb rename to Data/systems/pf2e/packs/rollable-tables/000005.ldb index edfcf496..1db5d5f2 100644 Binary files a/Data/systems/pf2e/packs/rollable-tables/000009.ldb and b/Data/systems/pf2e/packs/rollable-tables/000005.ldb differ diff --git a/Data/systems/pf2e/packs/rollable-tables/000015.log b/Data/systems/pf2e/packs/rollable-tables/000006.log similarity index 100% rename from Data/systems/pf2e/packs/rollable-tables/000015.log rename to Data/systems/pf2e/packs/rollable-tables/000006.log diff --git a/Data/systems/pf2e/packs/rollable-tables/CURRENT b/Data/systems/pf2e/packs/rollable-tables/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/rollable-tables/CURRENT +++ b/Data/systems/pf2e/packs/rollable-tables/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/rollable-tables/LOG b/Data/systems/pf2e/packs/rollable-tables/LOG index 1238be9d..d1954ca8 100644 --- a/Data/systems/pf2e/packs/rollable-tables/LOG +++ b/Data/systems/pf2e/packs/rollable-tables/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.931710 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.937171 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.937194 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:18.499285 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:18.500456 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:18.504907 ffff86fdf0a0 Level-0 table #5: 191129 bytes OK +2023/10/23-05:12:18.509321 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:18.509422 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/rollable-tables/LOG.old b/Data/systems/pf2e/packs/rollable-tables/LOG.old index bdc128a7..bd0b51a2 100644 --- a/Data/systems/pf2e/packs/rollable-tables/LOG.old +++ b/Data/systems/pf2e/packs/rollable-tables/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.798536 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.803930 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.803953 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.606440 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.606462 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.608193 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.610202 ffff85fbf0a0 Manual compaction at level-0 from '!tables!0JtfURwAEbgfkhss' @ 72057594037927935 : 1 .. '!tables.results!zyXbnTnUGs7tWR5j.zAJ8MNJRO5e7p5zw' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.715338 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/rollable-tables/MANIFEST-000004 b/Data/systems/pf2e/packs/rollable-tables/MANIFEST-000004 new file mode 100644 index 00000000..6f5fb5b6 Binary files /dev/null and b/Data/systems/pf2e/packs/rollable-tables/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/rollable-tables/MANIFEST-000014 b/Data/systems/pf2e/packs/rollable-tables/MANIFEST-000014 deleted file mode 100644 index 917a8a4e..00000000 Binary files a/Data/systems/pf2e/packs/rollable-tables/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/rusthenge-bestiary/000009.ldb b/Data/systems/pf2e/packs/rusthenge-bestiary/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/rusthenge-bestiary/000009.ldb rename to Data/systems/pf2e/packs/rusthenge-bestiary/000005.ldb diff --git a/Data/systems/pf2e/packs/rusthenge-bestiary/000015.log b/Data/systems/pf2e/packs/rusthenge-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/rusthenge-bestiary/000015.log rename to Data/systems/pf2e/packs/rusthenge-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/rusthenge-bestiary/CURRENT b/Data/systems/pf2e/packs/rusthenge-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/rusthenge-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/rusthenge-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/rusthenge-bestiary/LOG b/Data/systems/pf2e/packs/rusthenge-bestiary/LOG index c463104c..41cc239e 100644 --- a/Data/systems/pf2e/packs/rusthenge-bestiary/LOG +++ b/Data/systems/pf2e/packs/rusthenge-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.393857 ffff877ef0a0 Recovering log #12 -2023/10/20-07:55:10.398969 ffff877ef0a0 Delete type=0 #12 -2023/10/20-07:55:10.398988 ffff877ef0a0 Delete type=3 #10 +2023/10/23-05:12:17.589100 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:17.589825 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:17.594505 ffff877ef0a0 Level-0 table #5: 224323 bytes OK +2023/10/23-05:12:17.598830 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:17.598932 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/rusthenge-bestiary/LOG.old b/Data/systems/pf2e/packs/rusthenge-bestiary/LOG.old index 69a22e8e..97e8ac27 100644 --- a/Data/systems/pf2e/packs/rusthenge-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/rusthenge-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.361460 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.367275 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.367299 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.536148 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.536170 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.537834 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.539938 ffff85fbf0a0 Manual compaction at level-0 from '!actors!1oVJFDY5BJQxO3k9' @ 72057594037927935 : 1 .. '!actors.items!yscVNbJvyotk9NLG.xdQJFj57QglkQXeG' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.717132 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/rusthenge-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/rusthenge-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..94f18925 Binary files /dev/null and b/Data/systems/pf2e/packs/rusthenge-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/rusthenge-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/rusthenge-bestiary/MANIFEST-000014 deleted file mode 100644 index c72180e9..00000000 Binary files a/Data/systems/pf2e/packs/rusthenge-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/season-of-ghosts-bestiary/000009.ldb b/Data/systems/pf2e/packs/season-of-ghosts-bestiary/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/season-of-ghosts-bestiary/000009.ldb rename to Data/systems/pf2e/packs/season-of-ghosts-bestiary/000005.ldb diff --git a/Data/systems/pf2e/packs/season-of-ghosts-bestiary/000015.log b/Data/systems/pf2e/packs/season-of-ghosts-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/season-of-ghosts-bestiary/000015.log rename to Data/systems/pf2e/packs/season-of-ghosts-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/season-of-ghosts-bestiary/CURRENT b/Data/systems/pf2e/packs/season-of-ghosts-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/season-of-ghosts-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/season-of-ghosts-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/season-of-ghosts-bestiary/LOG b/Data/systems/pf2e/packs/season-of-ghosts-bestiary/LOG index 46ceeb42..600a075f 100644 --- a/Data/systems/pf2e/packs/season-of-ghosts-bestiary/LOG +++ b/Data/systems/pf2e/packs/season-of-ghosts-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.402525 ffff867cf0a0 Recovering log #12 -2023/10/20-07:55:10.407326 ffff867cf0a0 Delete type=0 #12 -2023/10/20-07:55:10.407345 ffff867cf0a0 Delete type=3 #10 +2023/10/23-05:12:17.602562 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:17.603201 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:17.607307 ffff87fff0a0 Level-0 table #5: 177598 bytes OK +2023/10/23-05:12:17.611685 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:17.611771 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/season-of-ghosts-bestiary/LOG.old b/Data/systems/pf2e/packs/season-of-ghosts-bestiary/LOG.old index fa92c9e9..2fcf00bf 100644 --- a/Data/systems/pf2e/packs/season-of-ghosts-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/season-of-ghosts-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.371625 ffff86fdf0a0 Recovering log #7 -2023/10/20-07:41:11.376269 ffff86fdf0a0 Delete type=3 #4 -2023/10/20-07:41:11.376291 ffff86fdf0a0 Delete type=0 #7 -2023/10/20-07:49:07.538094 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.538114 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.539900 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.543491 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0QfL4oXQrDfhfZDs' @ 72057594037927935 : 1 .. '!actors.items!zhw2TOrXkWyvle5S.vkCzRuNyjRncoZGw' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.717719 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/season-of-ghosts-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/season-of-ghosts-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..3180936c Binary files /dev/null and b/Data/systems/pf2e/packs/season-of-ghosts-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/season-of-ghosts-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/season-of-ghosts-bestiary/MANIFEST-000014 deleted file mode 100644 index bc53cef8..00000000 Binary files a/Data/systems/pf2e/packs/season-of-ghosts-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/000009.ldb b/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/shadows-at-sundown-bestiary/000009.ldb rename to Data/systems/pf2e/packs/shadows-at-sundown-bestiary/000005.ldb diff --git a/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/000015.log b/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/shadows-at-sundown-bestiary/000015.log rename to Data/systems/pf2e/packs/shadows-at-sundown-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/CURRENT b/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/LOG b/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/LOG index 6c446acc..ed03434f 100644 --- a/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/LOG +++ b/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.410596 ffff877ef0a0 Recovering log #12 -2023/10/20-07:55:10.415660 ffff877ef0a0 Delete type=0 #12 -2023/10/20-07:55:10.415679 ffff877ef0a0 Delete type=3 #10 +2023/10/23-05:12:17.615257 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:17.616119 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:17.621568 ffff877ef0a0 Level-0 table #5: 286499 bytes OK +2023/10/23-05:12:17.626031 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:17.626157 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/LOG.old b/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/LOG.old index f146175a..3de2130d 100644 --- a/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.379856 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.384942 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.384965 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.540061 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.540083 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.541781 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.545491 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0jAkZcP5559iO0wo' @ 72057594037927935 : 1 .. '!actors.items!z03ztiH8vBDRQTuw.SoUjhknpCUBSa9Yd' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.718878 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..70bfb81f Binary files /dev/null and b/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/MANIFEST-000014 deleted file mode 100644 index a4ee4679..00000000 Binary files a/Data/systems/pf2e/packs/shadows-at-sundown-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/000009.ldb b/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/000005.ldb similarity index 98% rename from Data/systems/pf2e/packs/sky-kings-tomb-bestiary/000009.ldb rename to Data/systems/pf2e/packs/sky-kings-tomb-bestiary/000005.ldb index fb2fa800..a8de52cb 100644 Binary files a/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/000009.ldb and b/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/000015.log b/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/sky-kings-tomb-bestiary/000015.log rename to Data/systems/pf2e/packs/sky-kings-tomb-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/CURRENT b/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/LOG b/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/LOG index 3788d90c..5f142cfd 100644 --- a/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/LOG +++ b/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.419531 ffff877ef0a0 Recovering log #12 -2023/10/20-07:55:10.424577 ffff877ef0a0 Delete type=0 #12 -2023/10/20-07:55:10.424597 ffff877ef0a0 Delete type=3 #10 +2023/10/23-05:12:17.630572 ffff867cf0a0 Recovering log #3 +2023/10/23-05:12:17.633705 ffff867cf0a0 Level-0 table #5: started +2023/10/23-05:12:17.646090 ffff867cf0a0 Level-0 table #5: 919923 bytes OK +2023/10/23-05:12:17.650587 ffff867cf0a0 Delete type=0 #3 +2023/10/23-05:12:17.650919 ffff867cf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/LOG.old b/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/LOG.old index 10b3d075..eeecc3a4 100644 --- a/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.389122 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.395655 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.395678 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.541820 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.541835 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.543453 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.545615 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0IzwmjL0OIfDqInF' @ 72057594037927935 : 1 .. '!actors.items!zWtfGN6uugDaRtcS.tOCS9mkYR5K1LuOZ' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.720023 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..27d956f4 Binary files /dev/null and b/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/MANIFEST-000014 deleted file mode 100644 index 9c2f5e2f..00000000 Binary files a/Data/systems/pf2e/packs/sky-kings-tomb-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/spell-effects/000009.ldb b/Data/systems/pf2e/packs/spell-effects/000005.ldb similarity index 95% rename from Data/systems/pf2e/packs/spell-effects/000009.ldb rename to Data/systems/pf2e/packs/spell-effects/000005.ldb index 304ee5db..ce48fa6d 100644 Binary files a/Data/systems/pf2e/packs/spell-effects/000009.ldb and b/Data/systems/pf2e/packs/spell-effects/000005.ldb differ diff --git a/Data/systems/pf2e/packs/spell-effects/000015.log b/Data/systems/pf2e/packs/spell-effects/000006.log similarity index 100% rename from Data/systems/pf2e/packs/spell-effects/000015.log rename to Data/systems/pf2e/packs/spell-effects/000006.log diff --git a/Data/systems/pf2e/packs/spell-effects/CURRENT b/Data/systems/pf2e/packs/spell-effects/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/spell-effects/CURRENT +++ b/Data/systems/pf2e/packs/spell-effects/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/spell-effects/LOG b/Data/systems/pf2e/packs/spell-effects/LOG index f52c64bf..91938d87 100644 --- a/Data/systems/pf2e/packs/spell-effects/LOG +++ b/Data/systems/pf2e/packs/spell-effects/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.838101 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.843263 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.843283 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:18.245544 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:18.246858 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:18.253775 ffff877ef0a0 Level-0 table #5: 415661 bytes OK +2023/10/23-05:12:18.258456 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:18.258618 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/spell-effects/LOG.old b/Data/systems/pf2e/packs/spell-effects/LOG.old index e73bc231..29edab63 100644 --- a/Data/systems/pf2e/packs/spell-effects/LOG.old +++ b/Data/systems/pf2e/packs/spell-effects/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.713730 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.718542 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.718564 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.596930 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.596946 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.598709 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.600763 ffff85fbf0a0 Manual compaction at level-0 from '!items!06zdFoxzuTpPPGyJ' @ 72057594037927935 : 1 .. '!items!zpxIwEjnLUSO1B4z' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.719502 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/spell-effects/MANIFEST-000004 b/Data/systems/pf2e/packs/spell-effects/MANIFEST-000004 new file mode 100644 index 00000000..828773f7 Binary files /dev/null and b/Data/systems/pf2e/packs/spell-effects/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/spell-effects/MANIFEST-000014 b/Data/systems/pf2e/packs/spell-effects/MANIFEST-000014 deleted file mode 100644 index 49f1f5b3..00000000 Binary files a/Data/systems/pf2e/packs/spell-effects/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/spells/000009.ldb b/Data/systems/pf2e/packs/spells/000005.ldb similarity index 90% rename from Data/systems/pf2e/packs/spells/000009.ldb rename to Data/systems/pf2e/packs/spells/000005.ldb index deeda869..202b32b4 100644 Binary files a/Data/systems/pf2e/packs/spells/000009.ldb and b/Data/systems/pf2e/packs/spells/000005.ldb differ diff --git a/Data/systems/pf2e/packs/spells/000015.log b/Data/systems/pf2e/packs/spells/000006.log similarity index 100% rename from Data/systems/pf2e/packs/spells/000015.log rename to Data/systems/pf2e/packs/spells/000006.log diff --git a/Data/systems/pf2e/packs/spells/CURRENT b/Data/systems/pf2e/packs/spells/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/spells/CURRENT +++ b/Data/systems/pf2e/packs/spells/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/spells/LOG b/Data/systems/pf2e/packs/spells/LOG index f1e5d470..a3e74b4a 100644 --- a/Data/systems/pf2e/packs/spells/LOG +++ b/Data/systems/pf2e/packs/spells/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.749463 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:55:10.754851 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:55:10.754870 ffff86fdf0a0 Delete type=3 #10 +2023/10/23-05:12:18.102696 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:18.107969 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:18.129978 ffff86fdf0a0 Level-0 table #5: 1655214 bytes OK +2023/10/23-05:12:18.135040 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:18.135608 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/spells/LOG.old b/Data/systems/pf2e/packs/spells/LOG.old index f6b2901a..0e3f5df8 100644 --- a/Data/systems/pf2e/packs/spells/LOG.old +++ b/Data/systems/pf2e/packs/spells/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.634942 ffff87fff0a0 Recovering log #7 -2023/10/20-07:41:11.639829 ffff87fff0a0 Delete type=3 #4 -2023/10/20-07:41:11.639854 ffff87fff0a0 Delete type=0 #7 -2023/10/20-07:49:07.579070 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.579092 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.580835 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.584762 ffff85fbf0a0 Manual compaction at level-0 from '!items!02J0rDTk37KN2sjt' @ 72057594037927935 : 1 .. '!items!zvvHOQV78WKUB33l' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.720123 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/spells/MANIFEST-000004 b/Data/systems/pf2e/packs/spells/MANIFEST-000004 new file mode 100644 index 00000000..e0983128 Binary files /dev/null and b/Data/systems/pf2e/packs/spells/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/spells/MANIFEST-000014 b/Data/systems/pf2e/packs/spells/MANIFEST-000014 deleted file mode 100644 index 94801169..00000000 Binary files a/Data/systems/pf2e/packs/spells/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/stolen-fate-bestiary/000009.ldb b/Data/systems/pf2e/packs/stolen-fate-bestiary/000005.ldb similarity index 99% rename from Data/systems/pf2e/packs/stolen-fate-bestiary/000009.ldb rename to Data/systems/pf2e/packs/stolen-fate-bestiary/000005.ldb index fe5e8c87..9e9abf2d 100644 Binary files a/Data/systems/pf2e/packs/stolen-fate-bestiary/000009.ldb and b/Data/systems/pf2e/packs/stolen-fate-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/stolen-fate-bestiary/000015.log b/Data/systems/pf2e/packs/stolen-fate-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/stolen-fate-bestiary/000015.log rename to Data/systems/pf2e/packs/stolen-fate-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/stolen-fate-bestiary/CURRENT b/Data/systems/pf2e/packs/stolen-fate-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/stolen-fate-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/stolen-fate-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/stolen-fate-bestiary/LOG b/Data/systems/pf2e/packs/stolen-fate-bestiary/LOG index 882d872a..a04b1ac7 100644 --- a/Data/systems/pf2e/packs/stolen-fate-bestiary/LOG +++ b/Data/systems/pf2e/packs/stolen-fate-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.599385 ffff867cf0a0 Recovering log #12 -2023/10/20-07:55:10.605141 ffff867cf0a0 Delete type=0 #12 -2023/10/20-07:55:10.605163 ffff867cf0a0 Delete type=3 #10 +2023/10/23-05:12:17.791246 ffff867cf0a0 Recovering log #3 +2023/10/23-05:12:17.797256 ffff867cf0a0 Level-0 table #5: started +2023/10/23-05:12:17.821601 ffff867cf0a0 Level-0 table #5: 1747468 bytes OK +2023/10/23-05:12:17.826456 ffff867cf0a0 Delete type=0 #3 +2023/10/23-05:12:17.827051 ffff867cf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/stolen-fate-bestiary/LOG.old b/Data/systems/pf2e/packs/stolen-fate-bestiary/LOG.old index d018cebc..029ed38d 100644 --- a/Data/systems/pf2e/packs/stolen-fate-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/stolen-fate-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.483962 ffff86fdf0a0 Recovering log #7 -2023/10/20-07:41:11.489285 ffff86fdf0a0 Delete type=3 #4 -2023/10/20-07:41:11.489307 ffff86fdf0a0 Delete type=0 #7 -2023/10/20-07:49:07.555237 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.555259 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.557210 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.560871 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0C9muUhjn4vAL5UW' @ 72057594037927935 : 1 .. '!actors.items!zw2JQhb4cHkDk2zb.zu5kwhnrxafjmru7' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.722346 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/stolen-fate-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/stolen-fate-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..e0a77bff Binary files /dev/null and b/Data/systems/pf2e/packs/stolen-fate-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/stolen-fate-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/stolen-fate-bestiary/MANIFEST-000014 deleted file mode 100644 index ea4af398..00000000 Binary files a/Data/systems/pf2e/packs/stolen-fate-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/strength-of-thousands-bestiary/000009.ldb b/Data/systems/pf2e/packs/strength-of-thousands-bestiary/000005.ldb similarity index 95% rename from Data/systems/pf2e/packs/strength-of-thousands-bestiary/000009.ldb rename to Data/systems/pf2e/packs/strength-of-thousands-bestiary/000005.ldb index a699db53..20ae5144 100644 Binary files a/Data/systems/pf2e/packs/strength-of-thousands-bestiary/000009.ldb and b/Data/systems/pf2e/packs/strength-of-thousands-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/strength-of-thousands-bestiary/000015.log b/Data/systems/pf2e/packs/strength-of-thousands-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/strength-of-thousands-bestiary/000015.log rename to Data/systems/pf2e/packs/strength-of-thousands-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/strength-of-thousands-bestiary/CURRENT b/Data/systems/pf2e/packs/strength-of-thousands-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/strength-of-thousands-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/strength-of-thousands-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/strength-of-thousands-bestiary/LOG b/Data/systems/pf2e/packs/strength-of-thousands-bestiary/LOG index b9dc9a5e..edad7faf 100644 --- a/Data/systems/pf2e/packs/strength-of-thousands-bestiary/LOG +++ b/Data/systems/pf2e/packs/strength-of-thousands-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.434511 ffff867cf0a0 Recovering log #12 -2023/10/20-07:55:10.439315 ffff867cf0a0 Delete type=0 #12 -2023/10/20-07:55:10.439334 ffff867cf0a0 Delete type=3 #10 +2023/10/23-05:12:17.662307 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:17.668990 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:17.695279 ffff86fdf0a0 Level-0 table #5: 1879496 bytes OK +2023/10/23-05:12:17.700011 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:17.700655 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/strength-of-thousands-bestiary/LOG.old b/Data/systems/pf2e/packs/strength-of-thousands-bestiary/LOG.old index dc939ea9..e0048789 100644 --- a/Data/systems/pf2e/packs/strength-of-thousands-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/strength-of-thousands-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.405179 ffff86fdf0a0 Recovering log #7 -2023/10/20-07:41:11.410521 ffff86fdf0a0 Delete type=3 #4 -2023/10/20-07:41:11.410545 ffff86fdf0a0 Delete type=0 #7 -2023/10/20-07:49:07.543632 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.543655 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.545452 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.547518 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0Gnj7jlSf4WLY0lA' @ 72057594037927935 : 1 .. '!actors.items!zy69GWkQ4xS5y5O3.y4pG7XtJaPtJBo6e' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.722041 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/strength-of-thousands-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/strength-of-thousands-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..e46f2680 Binary files /dev/null and b/Data/systems/pf2e/packs/strength-of-thousands-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/strength-of-thousands-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/strength-of-thousands-bestiary/MANIFEST-000014 deleted file mode 100644 index 1ec9b36c..00000000 Binary files a/Data/systems/pf2e/packs/strength-of-thousands-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/000009.ldb b/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/000005.ldb similarity index 98% rename from Data/systems/pf2e/packs/the-enmity-cycle-bestiary/000009.ldb rename to Data/systems/pf2e/packs/the-enmity-cycle-bestiary/000005.ldb index bbb7ae72..a62edfac 100644 Binary files a/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/000009.ldb and b/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/000015.log b/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/the-enmity-cycle-bestiary/000015.log rename to Data/systems/pf2e/packs/the-enmity-cycle-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/CURRENT b/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/LOG b/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/LOG index 4fe98000..89d1d2eb 100644 --- a/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/LOG +++ b/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.455634 ffff877ef0a0 Recovering log #12 -2023/10/20-07:55:10.460693 ffff877ef0a0 Delete type=0 #12 -2023/10/20-07:55:10.460714 ffff877ef0a0 Delete type=3 #10 +2023/10/23-05:12:17.719366 ffff867cf0a0 Recovering log #3 +2023/10/23-05:12:17.719904 ffff867cf0a0 Level-0 table #5: started +2023/10/23-05:12:17.723756 ffff867cf0a0 Level-0 table #5: 145155 bytes OK +2023/10/23-05:12:17.728550 ffff867cf0a0 Delete type=0 #3 +2023/10/23-05:12:17.728628 ffff867cf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/LOG.old b/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/LOG.old index 3186be00..ca3b74e6 100644 --- a/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.428133 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.433732 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.433756 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.545706 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.545726 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.547479 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.551118 ffff85fbf0a0 Manual compaction at level-0 from '!actors!257nqvaDItlttlG2' @ 72057594037927935 : 1 .. '!actors.items!xwEcqgkn9Fvrhpv7.y5AkKYpA3zYTkHI4' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.723733 7fdbd3fff640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..2ce0ea6a Binary files /dev/null and b/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/MANIFEST-000014 deleted file mode 100644 index f56edf44..00000000 Binary files a/Data/systems/pf2e/packs/the-enmity-cycle-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/the-slithering-bestiary/000009.ldb b/Data/systems/pf2e/packs/the-slithering-bestiary/000005.ldb similarity index 97% rename from Data/systems/pf2e/packs/the-slithering-bestiary/000009.ldb rename to Data/systems/pf2e/packs/the-slithering-bestiary/000005.ldb index 25d1dfaa..0e486e05 100644 Binary files a/Data/systems/pf2e/packs/the-slithering-bestiary/000009.ldb and b/Data/systems/pf2e/packs/the-slithering-bestiary/000005.ldb differ diff --git a/Data/systems/pf2e/packs/the-slithering-bestiary/000015.log b/Data/systems/pf2e/packs/the-slithering-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/the-slithering-bestiary/000015.log rename to Data/systems/pf2e/packs/the-slithering-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/the-slithering-bestiary/CURRENT b/Data/systems/pf2e/packs/the-slithering-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/the-slithering-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/the-slithering-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/the-slithering-bestiary/LOG b/Data/systems/pf2e/packs/the-slithering-bestiary/LOG index b23f37e9..8bd4d15b 100644 --- a/Data/systems/pf2e/packs/the-slithering-bestiary/LOG +++ b/Data/systems/pf2e/packs/the-slithering-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.464036 ffff867cf0a0 Recovering log #12 -2023/10/20-07:55:10.469231 ffff867cf0a0 Delete type=0 #12 -2023/10/20-07:55:10.469250 ffff867cf0a0 Delete type=3 #10 +2023/10/23-05:12:17.734100 ffff86fdf0a0 Recovering log #3 +2023/10/23-05:12:17.734643 ffff86fdf0a0 Level-0 table #5: started +2023/10/23-05:12:17.738987 ffff86fdf0a0 Level-0 table #5: 152030 bytes OK +2023/10/23-05:12:17.744123 ffff86fdf0a0 Delete type=0 #3 +2023/10/23-05:12:17.744207 ffff86fdf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/the-slithering-bestiary/LOG.old b/Data/systems/pf2e/packs/the-slithering-bestiary/LOG.old index c9b35157..eaa4e7a0 100644 --- a/Data/systems/pf2e/packs/the-slithering-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/the-slithering-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.437206 ffff86fdf0a0 Recovering log #7 -2023/10/20-07:41:11.442792 ffff86fdf0a0 Delete type=3 #4 -2023/10/20-07:41:11.442816 ffff86fdf0a0 Delete type=0 #7 -2023/10/20-07:49:07.547656 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.547677 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.549436 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.552976 ffff85fbf0a0 Manual compaction at level-0 from '!actors!6U8P0ITf4gkJfeKD' @ 72057594037927935 : 1 .. '!actors.items!wgeuaYe2fbGNg42z.z7ibYqOwng8NoutT' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.722448 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/the-slithering-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/the-slithering-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..9a3c95a4 Binary files /dev/null and b/Data/systems/pf2e/packs/the-slithering-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/the-slithering-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/the-slithering-bestiary/MANIFEST-000014 deleted file mode 100644 index 465c7d88..00000000 Binary files a/Data/systems/pf2e/packs/the-slithering-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/travel-guide-bestiary/000009.ldb b/Data/systems/pf2e/packs/travel-guide-bestiary/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/travel-guide-bestiary/000009.ldb rename to Data/systems/pf2e/packs/travel-guide-bestiary/000005.ldb diff --git a/Data/systems/pf2e/packs/travel-guide-bestiary/000015.log b/Data/systems/pf2e/packs/travel-guide-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/travel-guide-bestiary/000015.log rename to Data/systems/pf2e/packs/travel-guide-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/travel-guide-bestiary/CURRENT b/Data/systems/pf2e/packs/travel-guide-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/travel-guide-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/travel-guide-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/travel-guide-bestiary/LOG b/Data/systems/pf2e/packs/travel-guide-bestiary/LOG index 25fca066..d64c091b 100644 --- a/Data/systems/pf2e/packs/travel-guide-bestiary/LOG +++ b/Data/systems/pf2e/packs/travel-guide-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.023185 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.028399 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.028431 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:16.693294 ffff87fff0a0 Recovering log #3 +2023/10/23-05:12:16.693394 ffff87fff0a0 Level-0 table #5: started +2023/10/23-05:12:16.695568 ffff87fff0a0 Level-0 table #5: 17054 bytes OK +2023/10/23-05:12:16.700079 ffff87fff0a0 Delete type=0 #3 +2023/10/23-05:12:16.700110 ffff87fff0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/travel-guide-bestiary/LOG.old b/Data/systems/pf2e/packs/travel-guide-bestiary/LOG.old index 3b7fe6f2..069f66b5 100644 --- a/Data/systems/pf2e/packs/travel-guide-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/travel-guide-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:10.876478 ffff877ef0a0 Recovering log #7 -2023/10/20-07:41:10.881434 ffff877ef0a0 Delete type=3 #4 -2023/10/20-07:41:10.881461 ffff877ef0a0 Delete type=0 #7 -2023/10/20-07:49:07.501549 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.501572 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.503369 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.507035 ffff85fbf0a0 Manual compaction at level-0 from '!actors!FMGyuNpkxMRR1Jrw' @ 72057594037927935 : 1 .. '!actors.items!yRhCsQsoz1Uqvkmk.yLnwKltbJHYpn8qC' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.726232 7fdbe1ffd640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/travel-guide-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/travel-guide-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..140584bc Binary files /dev/null and b/Data/systems/pf2e/packs/travel-guide-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/travel-guide-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/travel-guide-bestiary/MANIFEST-000014 deleted file mode 100644 index 2894564b..00000000 Binary files a/Data/systems/pf2e/packs/travel-guide-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/troubles-in-otari-bestiary/000009.ldb b/Data/systems/pf2e/packs/troubles-in-otari-bestiary/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/troubles-in-otari-bestiary/000009.ldb rename to Data/systems/pf2e/packs/troubles-in-otari-bestiary/000005.ldb diff --git a/Data/systems/pf2e/packs/troubles-in-otari-bestiary/000015.log b/Data/systems/pf2e/packs/troubles-in-otari-bestiary/000006.log similarity index 100% rename from Data/systems/pf2e/packs/troubles-in-otari-bestiary/000015.log rename to Data/systems/pf2e/packs/troubles-in-otari-bestiary/000006.log diff --git a/Data/systems/pf2e/packs/troubles-in-otari-bestiary/CURRENT b/Data/systems/pf2e/packs/troubles-in-otari-bestiary/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/troubles-in-otari-bestiary/CURRENT +++ b/Data/systems/pf2e/packs/troubles-in-otari-bestiary/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/troubles-in-otari-bestiary/LOG b/Data/systems/pf2e/packs/troubles-in-otari-bestiary/LOG index 91d0a1a1..ca861488 100644 --- a/Data/systems/pf2e/packs/troubles-in-otari-bestiary/LOG +++ b/Data/systems/pf2e/packs/troubles-in-otari-bestiary/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.472370 ffff877ef0a0 Recovering log #12 -2023/10/20-07:55:10.477367 ffff877ef0a0 Delete type=0 #12 -2023/10/20-07:55:10.477386 ffff877ef0a0 Delete type=3 #10 +2023/10/23-05:12:17.748594 ffff867cf0a0 Recovering log #3 +2023/10/23-05:12:17.749060 ffff867cf0a0 Level-0 table #5: started +2023/10/23-05:12:17.752737 ffff867cf0a0 Level-0 table #5: 120871 bytes OK +2023/10/23-05:12:17.757531 ffff867cf0a0 Delete type=0 #3 +2023/10/23-05:12:17.757595 ffff867cf0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/troubles-in-otari-bestiary/LOG.old b/Data/systems/pf2e/packs/troubles-in-otari-bestiary/LOG.old index c8173eeb..fb4bcff5 100644 --- a/Data/systems/pf2e/packs/troubles-in-otari-bestiary/LOG.old +++ b/Data/systems/pf2e/packs/troubles-in-otari-bestiary/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.454181 ffff867cf0a0 Recovering log #7 -2023/10/20-07:41:11.459664 ffff867cf0a0 Delete type=3 #4 -2023/10/20-07:41:11.459687 ffff867cf0a0 Delete type=0 #7 -2023/10/20-07:49:07.549472 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.549486 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.551080 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.553100 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0Fvulq5Zv4BQPvYV' @ 72057594037927935 : 1 .. '!actors.items!vg6fEjWSj4jilXRn.dwvQyKJ9gUWC4S3f' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.725682 7fdbd2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/troubles-in-otari-bestiary/MANIFEST-000004 b/Data/systems/pf2e/packs/troubles-in-otari-bestiary/MANIFEST-000004 new file mode 100644 index 00000000..8f3c1621 Binary files /dev/null and b/Data/systems/pf2e/packs/troubles-in-otari-bestiary/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/troubles-in-otari-bestiary/MANIFEST-000014 b/Data/systems/pf2e/packs/troubles-in-otari-bestiary/MANIFEST-000014 deleted file mode 100644 index 5b14cb36..00000000 Binary files a/Data/systems/pf2e/packs/troubles-in-otari-bestiary/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/packs/vehicles/000009.ldb b/Data/systems/pf2e/packs/vehicles/000005.ldb similarity index 100% rename from Data/systems/pf2e/packs/vehicles/000009.ldb rename to Data/systems/pf2e/packs/vehicles/000005.ldb diff --git a/Data/systems/pf2e/packs/vehicles/000015.log b/Data/systems/pf2e/packs/vehicles/000006.log similarity index 100% rename from Data/systems/pf2e/packs/vehicles/000015.log rename to Data/systems/pf2e/packs/vehicles/000006.log diff --git a/Data/systems/pf2e/packs/vehicles/CURRENT b/Data/systems/pf2e/packs/vehicles/CURRENT index 23b73d91..cacca757 100644 --- a/Data/systems/pf2e/packs/vehicles/CURRENT +++ b/Data/systems/pf2e/packs/vehicles/CURRENT @@ -1 +1 @@ -MANIFEST-000014 +MANIFEST-000004 diff --git a/Data/systems/pf2e/packs/vehicles/LOG b/Data/systems/pf2e/packs/vehicles/LOG index b598fe39..529162bd 100644 --- a/Data/systems/pf2e/packs/vehicles/LOG +++ b/Data/systems/pf2e/packs/vehicles/LOG @@ -1,3 +1,5 @@ -2023/10/20-07:55:10.633327 ffff87fff0a0 Recovering log #12 -2023/10/20-07:55:10.639027 ffff87fff0a0 Delete type=0 #12 -2023/10/20-07:55:10.639048 ffff87fff0a0 Delete type=3 #10 +2023/10/23-05:12:17.898152 ffff877ef0a0 Recovering log #3 +2023/10/23-05:12:17.898411 ffff877ef0a0 Level-0 table #5: started +2023/10/23-05:12:17.901380 ffff877ef0a0 Level-0 table #5: 68529 bytes OK +2023/10/23-05:12:17.905797 ffff877ef0a0 Delete type=0 #3 +2023/10/23-05:12:17.905846 ffff877ef0a0 Delete type=3 #2 diff --git a/Data/systems/pf2e/packs/vehicles/LOG.old b/Data/systems/pf2e/packs/vehicles/LOG.old index aa6e8ff0..0ab5d216 100644 --- a/Data/systems/pf2e/packs/vehicles/LOG.old +++ b/Data/systems/pf2e/packs/vehicles/LOG.old @@ -1,7 +1 @@ -2023/10/20-07:41:11.523289 ffff877ef0a0 Recovering log #7 -2023/10/20-07:41:11.528425 ffff877ef0a0 Delete type=3 #4 -2023/10/20-07:41:11.528449 ffff877ef0a0 Delete type=0 #7 -2023/10/20-07:49:07.559023 ffff85fbf0a0 Level-0 table #13: started -2023/10/20-07:49:07.559046 ffff85fbf0a0 Level-0 table #13: 0 bytes OK -2023/10/20-07:49:07.560833 ffff85fbf0a0 Delete type=0 #11 -2023/10/20-07:49:07.563079 ffff85fbf0a0 Manual compaction at level-0 from '!actors!0H2BbJCAKauXYKE6' @ 72057594037927935 : 1 .. '!actors.items!yukamyipO8x9VuZa.uIzebnQMmGWvKMo5' @ 0 : 0; will stop at (end) +2023/10/21-22:35:17.728173 7fdbe2ffe640 Delete type=3 #1 diff --git a/Data/systems/pf2e/packs/vehicles/MANIFEST-000004 b/Data/systems/pf2e/packs/vehicles/MANIFEST-000004 new file mode 100644 index 00000000..25cc7a32 Binary files /dev/null and b/Data/systems/pf2e/packs/vehicles/MANIFEST-000004 differ diff --git a/Data/systems/pf2e/packs/vehicles/MANIFEST-000014 b/Data/systems/pf2e/packs/vehicles/MANIFEST-000014 deleted file mode 100644 index 246e9e21..00000000 Binary files a/Data/systems/pf2e/packs/vehicles/MANIFEST-000014 and /dev/null differ diff --git a/Data/systems/pf2e/pf2e.mjs b/Data/systems/pf2e/pf2e.mjs index 208a2d6e..0402cd7a 100644 --- a/Data/systems/pf2e/pf2e.mjs +++ b/Data/systems/pf2e/pf2e.mjs @@ -1,4 +1,4 @@ -var __defProp=Object.defineProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __defProp2=Object.defineProperty,__getProtoOf=Object.getPrototypeOf,__reflectGet=Reflect.get,__defNormalProp=__name((obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,"__defNormalProp"),__name2=__name((target,value)=>__defProp2(target,"name",{value,configurable:!0}),"__name"),__publicField=__name((obj,key,value)=>(__defNormalProp(obj,typeof key!="symbol"?key+"":key,value),value),"__publicField"),__accessCheck=__name((obj,member,msg)=>{if(!member.has(obj))throw TypeError("Cannot "+msg)},"__accessCheck"),__privateGet=__name((obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),"__privateGet"),__privateAdd=__name((obj,member,value)=>{if(member.has(obj))throw TypeError("Cannot add the same private member more than once");member instanceof WeakSet?member.add(obj):member.set(obj,value)},"__privateAdd"),__privateSet=__name((obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),"__privateSet"),__privateMethod=__name((obj,member,method)=>(__accessCheck(obj,member,"access private method"),method),"__privateMethod"),__superGet=__name((cls,obj,key)=>__reflectGet(__getProtoOf(cls),key,obj),"__superGet"),_updateMigrationRecord,updateMigrationRecord_fn,_migrateDocuments,migrateDocuments_fn,_migrateItem,migrateItem_fn,_migrateActor,migrateActor_fn,_migrateWorldJournalEntry,migrateWorldJournalEntry_fn,_migrateWorldMacro,migrateWorldMacro_fn,_migrateWorldTable,migrateWorldTable_fn,_migrateSceneToken,migrateSceneToken_fn,_migrateUser,migrateUser_fn,_data,_diehardPromise,_featSlugs,_featsPromise,_IMAGE_PATHS,_regexp,_renameToWebP,renameToWebP_fn,_isABCK,isABCK_fn,_BASE_ARMORS,_MAGIC_ARMOR_TO_BASE,_BASE_WEAPONS,_isTrue,isTrue_fn,_testBinaryOp,testBinaryOp_fn,_testCompound,testCompound_fn,_binaryOperators,_imageOverrides,_sizeOverrides,_isTokenImageFlag,isTokenImageFlag_fn,_isTokenSizeFlag,isTokenSizeFlag_fn,_needsRuleElement,needsRuleElement_fn,_increasesByOne,_isClassFeature,isClassFeature_fn,_pathsToRemove,_isRemovableAE,isRemovableAE_fn,_isRemoveableChange,isRemoveableChange_fn,_fixClassKeyAbilities,fixClassKeyAbilities_fn,_isTokenSizeRE,isTokenSizeRE_fn,_isActorSizeAELike,isActorSizeAELike_fn,_isBracketedValue,isBracketedValue_fn,_setAncestryVision,setAncestryVision_fn,_resolveBracketedValue,resolveBracketedValue_fn,_coerceNumber,coerceNumber_fn,_traitsDictionary,traitsDictionary_get,_handleModeAffectingTrait,handleModeAffectingTrait_fn,_getDegreeAdjustment,getDegreeAdjustment_fn,_adjustDegreeOfSuccess,adjustDegreeOfSuccess_fn,_adjustDegreeByDieValue,adjustDegreeByDieValue_fn,_calculateDegreeOfSuccess,calculateDegreeOfSuccess_fn,_SKILL_LONG_FORM_PATH,_rewriteSkillLongFormPath,rewriteSkillLongFormPath_fn,_pathIsValid,pathIsValid_fn,_logChange,logChange_fn,_processEffects,processEffects_fn,_processAppearanceData,processAppearanceData_fn,_createMovementType,createMovementType_fn,_customLabel,_weapon,_resolveOptions,resolveOptions_fn,_actions,_lores,_prepareProficiencyRanks,prepareProficiencyRanks_fn,_prepareDCAdjustments,prepareDCAdjustments_fn,_generatePrompt,generatePrompt_fn,_htmlQueryTags,htmlQueryTags_fn,_formatLoreType,formatLoreType_fn,_formatActionType,formatActionType_fn,_getDC,getDC_fn,_constructCheck,constructCheck_fn,_renderFormula,renderFormula_fn,_prepareDamageTypes,prepareDamageTypes_fn,_getInputElements,getInputElements_fn,_disableScale,disableScale_fn,_reestablishPrototype,reestablishPrototype_fn,_disableVisionInputs,disableVisionInputs_fn,_drawBorder,drawBorder_fn,_drawTexture,drawTexture_fn,_drawLabel,drawLabel_fn,_showBordersHighlights,showBordersHighlights_get,_moveTime,_wheelListenerOptions,_onPreviewMouseMove,_onPreviewLeftClick,_onPreviewRightClick,_onPreviewMouseWheel,_squares,_prepareDerivedPerception,prepareDerivedPerception_fn,_getChoices,getChoices_fn,_filterTimeout,_getUpdateData,getUpdateData_fn,_search,search_fn,_onFilterResults,onFilterResults_fn,_updateIWR,updateIWR_fn,_sortableOnMoveData,_activateInventoryDragDrop,activateInventoryDragDrop_fn,_sortableOnMove,sortableOnMove_fn,_sortableOnEnd,sortableOnEnd_fn,_onClickDeleteItem,onClickDeleteItem_fn,_onClickBrowseEquipment,onClickBrowseEquipment_fn,_onClickCreateItem,onClickCreateItem_fn,_onClickSellAllTreasure,onClickSellAllTreasure_fn,_resolve,_originallyEnabled,_getModifierIcon,getModifierIcon_fn,_getTypeLabel,getTypeLabel_fn,_applyStackingRules,applyStackingRules_fn,_localize,localize_fn,_createTemplate,createTemplate_fn,_parseInlineParams,parseInlineParams_fn,_createCheck,createCheck_fn,_createSingleCheck,createSingleCheck_fn,_createDamageRoll,createDamageRoll_fn,_createActionOptions,createActionOptions_fn,_originallyEnabled2,_resolveSubstitutions,resolveSubstitutions_fn,_createTagFlavor,createTagFlavor_fn,_createResultFlavor,createResultFlavor_fn,_resolveCheckDC,resolveCheckDC_fn,_item,_resolve2,_action,_canSetAttribute,canSetAttribute_fn,_onConfigureActor,onConfigureActor_fn,_onToggleSignatureSpell,onToggleSignatureSpell_fn,_onClickBrowseActions,onClickBrowseActions_fn,_onClickBrowseSpellCompendia,onClickBrowseSpellCompendia_fn,_abpEnabled,_createButtons,createButtons_fn,_calculateAncestryBoosts,calculateAncestryBoosts_fn,_calculateBackgroundBoosts,calculateBackgroundBoosts_fn,_calculateLeveledBoosts,calculateLeveledBoosts_fn,_getBoostFlawLabels,getBoostFlawLabels_fn,_updateRE,updateRE_fn,_blastConfigSchema,_blastInfusionSchema,_prepareBlastConfigs,prepareBlastConfigs_fn,_prepareBlastInfusion,prepareBlastInfusion_fn,_getBlastConfig,getBlastConfig_fn,_createModifiedItem,createModifiedItem_fn,_strengthModToDamage,strengthModToDamage_fn,_knownFormulas,_formulaQuantities,_prepareAbilities,prepareAbilities_fn,_prepareCraftingEntries,prepareCraftingEntries_fn,_getBlastData,getBlastData_fn,_activateBlastListeners,activateBlastListeners_fn,_onClickBrowseFeats,onClickBrowseFeats_fn,_onChangeAdjustStat,onChangeAdjustStat_fn,_onChangeAdjustItemStat,onChangeAdjustItemStat_fn,_onClickAdjustItemStat,onClickAdjustItemStat_fn,_getFeatSlotData,getFeatSlotData_fn,_sortFormulas,sortFormulas_fn,_strikeItemId,_strikeSlug,_strike,_elementTrait,_blasts,_getReach,getReach_fn,_isValid,isValid_fn,_constructWeapon,constructWeapon_fn,_defaultIcons,_setRollOptions,setRollOptions_fn,_prepareAC,prepareAC_fn,_prepareSenses,prepareSenses_fn,_prepareSize,prepareSize_fn,_prepareSpeeds,prepareSpeeds_fn,_prepareSkills,prepareSkills_fn,_prepareStrikes,prepareStrikes_fn,_prepareIWR,prepareIWR_fn,_suppressModifiers,suppressModifiers_fn,_filterModifier,filterModifier_fn,_suppressNotes,suppressNotes_fn,_resolveStrikeQueries,resolveStrikeQueries_fn,_resolve3,_setDefaultFlag,setDefaultFlag_fn,_choicesFromArray,choicesFromArray_fn,_choicesFromPath,choicesFromPath_fn,_choicesFromOwnedItems,choicesFromOwnedItems_fn,_choicesFromAttacks,choicesFromAttacks_fn,_getPreselection,getPreselection_fn,_setRollOption,setRollOption_fn,_getEffect,getEffect_fn,_isValidOverride,isValidOverride_fn,_resolvedBracketsIsValid,resolvedBracketsIsValid_fn,_validateForItem,_adjustCreatureShieldData,adjustCreatureShieldData_fn,_getNewInterval,getNewInterval_fn,_createDeferredEffect,createDeferredEffect_fn,_getOnDeleteActions,getOnDeleteActions_fn,_applyChoiceSelections,applyChoiceSelections_fn,_setGrantFlags,setGrantFlags_fn,_runGrantedItemPreCreates,runGrantedItemPreCreates_fn,_createInMemoryCondition,createInMemoryCondition_fn,_trackItem,trackItem_fn,_resolveOption,resolveOption_fn,_setFlag,setFlag_fn,_setRollOption2,setRollOption_fn2,_effect,_srcIsValid,srcIsValid_fn,_target,_resolve4,_cancelHandler,cancelHandler_fn,_checkRuleSource,checkRuleSource_fn,_activeTab,_getFormHelpers,getFormHelpers_fn,_effectsMap,_addEffect,addEffect_fn,_updateEffectsMap,updateEffectsMap_fn,_deleteEffect,deleteEffect_fn,_selectedRuleElementType,_editingRuleElementIndex,_rulesLastScrollTop,_ruleElementForms,_createRuleElementForms,createRuleElementForms_fn,_initialRefresh,_damageManager,_processDeletions,processDeletions_fn,_refreshSettings,refreshSettings_fn,_registerModuleTags,registerModuleTags_fn,_getConfigRecord,getConfigRecord_fn,_updateConfigRecords,updateConfigRecords_fn,_isFlatModifier,isFlatModifier_fn,_toRuleElement,toRuleElement_fn,_rationsSourceId,_rationsPromise,_isOldRations,isOldRations_fn,_getRationRefs,getRationRefs_fn,_migrateClass,migrateClass_fn,_migrateFeature,migrateFeature_fn,_isClassFeature2,isClassFeature_fn2,_isClassFeature3,isClassFeature_fn3,_isHeritageFeature,isHeritageFeature_fn,_officialAncestries,_heritagesWithoutAncestryInName,_ancestrySlugs,_heritageFromFeat,heritageFromFeat_fn,_explorersClothingVariants,_pathPattern,_hasWellFormedFeatType,hasWellFormedFeatType_fn,_needsTrait,needsTrait_fn,_hasBrokenThreshold,hasBrokenThreshold_fn,_shadowPromise,_cascadePromise,_isEffectTargetRE,isEffectTargetRE_fn,_toChoiceSet,toChoiceSet_fn,_loadedSpells,_isChoiceSetWithSelection,isChoiceSetWithSelection_fn,_newRules,newRules_fn,_toSkip,_hasThrownTrait,hasThrownTrait_fn,_cleanText,cleanText_fn,_updateEffect,updateEffect_fn,_updateFeat,updateFeat_fn,_vivaciousRules,vivaciousRules_get,_auraOfLife,_enlightenedPresence,_eternalBlessing,_marshalsAura,_findDamageDiceRE,findDamageDiceRE_fn,_isClassFeature4,isClassFeature_fn4,_athleticStrategist,athleticStrategist_get,_deviseAStratagem,deviseAStratagem_get,_ruffianPredicate,ruffianPredicate_get,_sneakAttackPredicate,sneakAttackPredicate_get,_updateSpeed,updateSpeed_fn,_suppressNoCrowbar,suppressNoCrowbar_get,_convertToUUIDs,convertToUUIDs_fn,_getRules,getRules_fn,_preciseStrikeRules,preciseStrikeRules_get,_finishingPrecisionRules,finishingPrecisionRules_get,_otherClassDCs,_isClassFeature5,isClassFeature_fn5,_critSpec,critSpec_get,_hands,hands_get,_convertLegacyData,convertLegacyData_fn,_isOldRawPredicate,isOldRawPredicate_fn,_isArrayChoiceSet,isArrayChoiceSet_fn,_isObjectChoiceSet,isObjectChoiceSet_fn,_shapeFeats,_flatFootedToggle,flatFootedToggle_get,_isFlatFootedToggle,isFlatFootedToggle_fn,_convertToEntry,convertToEntry_fn,_modifyFlag,modifyFlag_fn,_oldIdsPattern,_colorDarkvision,colorDarkvision_get,_AREA_TYPES,_isAreaType,isAreaType_fn,_hasDetails,hasDetails_fn,_pattern,_damageTypeLabelPattern,_updateDamageFormula,updateDamageFormula_fn,_automatonEnhancements,automatonEnhancements_get,_conditionPattern,_pattern2,_updateDamageFormula2,updateDamageFormula_fn2,_getWR,getWR_fn,_oldENmappings,_parseExceptions,parseExceptions_fn,_normalizeType,normalizeType_fn,_updateWeaponMaterialData,updateWeaponMaterialData_fn,_updateChoiceSet,updateChoiceSet_fn,_bomberSetFlags,bomberSetFlags_get,_chirurgeonSetFlags,chirurgeonSetFlags_get,_mutagenistSetFlags,mutagenistSetFlags_get,_toxicologistSetFlags,toxicologistSetFlags_get,_needsRE,needsRE_fn,_splashPattern1,_splashPattern2,_damagePatternSingle,_damagePatternPair,_cleanFormula,cleanFormula_fn,_buildSplashFormula,buildSplashFormula_fn,_buildDamageFormula,buildDamageFormula_fn,_updateDamageFormula3,updateDamageFormula_fn3,_rename,rename_fn,_removeLinks,removeLinks_fn,_cloisteredClericSetFlags,cloisteredClericSetFlags_get,_warpriestSetFlags,warpriestSetFlags_get,_updateCategoryData,updateCategoryData_fn,_rename2,rename_fn2,_wrapPredicate,wrapPredicate_fn,_replaceUUID,replaceUUID_fn,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn,_updateUUIDs,updateUUIDs_fn,_idMap,_oldToNew,_oldNamePattern,_newName,_imgPattern,_aToAnUUIDPatern,_replace,replace_fn,_OLD_TO_NEW_LANGUAGES,_testHasOption,testHasOption_fn,_hasOldMaterialData,hasOldMaterialData_fn,_resilientRuneValues,_replaceStrings,replaceStrings_fn,_mightyBulwarkRules,mightyBulwarkRules_get,_defensePathPattern,_mvSchema,mvSchema_fn,_setPublicationData,setPublicationData_fn,_list,_finalizeDamage,finalizeDamage_fn,_excludeDamage,excludeDamage_fn,_strengthModToDamage2,strengthModToDamage_fn2,_check,_dc,_determineLabel,determineLabel_fn,_createBonusesAndPenalties,createBonusesAndPenalties_fn,_createShieldBonus,createShieldBonus_fn,_baseMax,_currentFilter,_lastClick,_onClickButton,onClickButton_fn,_rollActorSaves,rollActorSaves_fn,_onHoverIn,onHoverIn_fn,_onHoverOut,onHoverOut_fn,_initialized,_value,_actorStrength,actorStrength_get,_flattenNonStowing,flattenNonStowing_fn,_localize2,_initialize,initialize_fn,_handleTrickItem,handleTrickItem_fn,_assertEntryIsDocument,assertEntryIsDocument_fn,_getRitualData,getRitualData_fn,_idMap2,_slugMap,_templatePaths,_getActor,getActor_fn,_getSource,getSource_fn,_getTarget,getTarget_fn,_tokenName,tokenName_fn,_sendMessage,sendMessage_fn,_messageFlavor,messageFlavor_fn,_findBestLocation,findBestLocation_fn,_getChildSlots,getChildSlots_fn,_editingSettlements,_prepareSettlement,prepareSettlement_fn,_activateSettlementEvents,activateSettlementEvents_fn,_getFeatSlotData2,getFeatSlotData_fn2,_prepareAbilityBuilder,prepareAbilityBuilder_fn,_originalValue,_slider,_noRefreshHook,_hasRollOptionData,hasRollOptionData_fn,_createItemMacro,createItemMacro_fn,_createRollOptionToggleMacro,createRollOptionToggleMacro_fn,_draggingParty,_onDragHighlightFolderLike,onDragHighlightFolderLike_fn,_appendBrowseButton,appendBrowseButton_fn,_appendBrowseButton2,appendBrowseButton_fn2,_messageFromEvent,messageFromEvent_fn,_onClickDamageButton,onClickDamageButton_fn,_onClickRevertDamage,onClickRevertDamage_fn,_onClickShieldBlock,onClickShieldBlock_fn,_onClickSender,onClickSender_fn,_dragPreview,dragPreview_get,_onToggleTarget,onToggleTarget_fn,_onDropCombatant,onDropCombatant_fn,_setModuleArt,setModuleArt_fn,_getSources,getSources_fn,_createFilteredIndex,createFilteredIndex_fn,_loadSources,loadSources_fn,_getSourceFromDocument,getSourceFromDocument_fn,_domParser,_getRollTableResults,getRollTableResults_fn,_localizeCoins,_creatureTraits,_resetInitializedTabs,resetInitializedTabs_fn,_renderResultList,renderResultList_fn,_activateResultListeners,activateResultListeners_fn,_takePhysicalItem,takePhysicalItem_fn,_buyPhysicalItem,buyPhysicalItem_fn,_getPhysicalItem,getPhysicalItem_fn,_resetFilters,resetFilters_fn,_clearScrollLimit,clearScrollLimit_fn,_getRemainingDurationLabel,getRemainingDurationLabel_fn,_getEnrichedDescriptions,getEnrichedDescriptions_fn,_lastCombatantToken,_ICON_THEME_DIRS,_conditionSummaries,_activateListeners,activateListeners_fn,_updateStatusIcons,updateStatusIcons_fn,_showStatusLabel,showStatusLabel_fn,_setStatusValue,setStatusValue_fn,_toggleStatus,toggleStatus_fn,_createChatMessage,createChatMessage_fn,_action2,_cost,_description,_slug,_traits,_variants,_action3,_effect2,_action4,_difficultyClass,_modifiers,_notes,_rollOptions,_statistic,_insert,insert_fn,_removeExpired,removeExpired_fn,_getArtMap,getArtMap_fn,_isModuleArt,isModuleArt_fn,_retrieve,retrieve_fn,_deposit,deposit_fn,_getDepositSpaces,getDepositSpaces_fn,_prepareActions,prepareActions_fn,_prepareSaves,prepareSaves_fn,_distributeCoins,distributeCoins_fn,_lootNPCs,lootNPCs_fn,_identificationData,_padAttempts,padAttempts_fn,_prepareAbilities2,prepareAbilities_fn2,_prepareAlignment,prepareAlignment_fn,_prepareSkills2,prepareSkills_fn2,_prepareSaves2,prepareSaves_fn2,_onClickRollable,onClickRollable_fn,_rollAbility,rollAbility_fn,_prepareActions2,prepareActions_fn2,_onChangeSpellcastingEntry,onChangeSpellcastingEntry_fn,_prepareMembers,prepareMembers_fn,_prepareOverviewSummary,prepareOverviewSummary_fn,_getActorsThatUnderstand,getActorsThatUnderstand_fn,_renderRegions,renderRegions_fn,_isValidDrop,isValidDrop_fn,_formatSpellComponents,formatSpellComponents_fn,_prepareHeighteningLevels,prepareHeighteningLevels_fn,_activateRBVListeners,activateRBVListeners_fn;import{i as isNil,T as Tagify,p as pick$1,m as mapToObj,a as mapValues$1,o as omit,b as isObject$1,c as compact,k as keys,u as uniq,d as isEmpty,g as groupBy$1,e as equals,s as sortBy$1,S as Sortable,f as uniqBy,h as difference,D as Duration,j as meanBy,E as EditorView,l as basicSetup,n as json,q as linter,r as keymap,t as indentWithTab,v as autocompletion,w as syntaxTree,x as jsonParseLinter,y as fromPairs,z as maxBy,A as sumBy,B as pipe,C as filter,F as map,I as Interval,G as DateTime,H as noUiSlider,P as PipsMode,J as findLast,M as MiniSearch,K as omitBy}from"./vendor.mjs";const BabeleReady={listen(){Hooks.once("babele.ready",()=>{game.pf2e.ConditionManager.initialize(!0)})}},CanvasInit={listen:()=>{Hooks.on("canvasInit",async canvas2=>{SquareGrid.prototype.measureDistances=__name2(__name(function(segments,options={}){if(!options.gridSpaces)return BaseGrid.prototype.measureDistances.call(this,segments,options);let nDiagonal=0;const d=canvas2.dimensions;return segments.map(s=>{const r=s.ray,nx=Math.abs(Math.ceil(r.dx/d.size)),ny=Math.abs(Math.ceil(r.dy/d.size)),nd=Math.min(nx,ny),ns=Math.abs(ny-nx);nDiagonal+=nd;const nd10=Math.floor(nDiagonal/2)-Math.floor((nDiagonal-nd)/2);return(nd10*2+(nd-nd10)+ns)*canvas2.dimensions.distance})},"measureDistances"),"measureDistances")})}},_BaseStatistic=class{static{__name(this,"_BaseStatistic")}actor;slug;label;data;domains;modifiers;constructor(actor,data){this.actor=actor,this.slug=data.slug,this.label=game.i18n.localize(data.label).trim(),this.data={...data},this.domains=[...data.domains??=[]];const modifiers=[data.modifiers??[],extractModifiers(this.actor.synthetics,this.domains)].flat();if(this.modifiers=new StatisticModifier("",modifiers).modifiers.map(m=>m.clone()),this.domains.length>0){const options=this.createRollOptions();for(const modifier of this.modifiers)modifier.test(options)}}createRollOptions(domains=this.domains){return new Set(this.actor.getRollOptions(domains))}};__name2(_BaseStatistic,"BaseStatistic");let BaseStatistic=_BaseStatistic;const _MigrationRunnerBase=class{static{__name(this,"_MigrationRunnerBase")}constructor(migrations=[]){__privateAdd(this,_updateMigrationRecord),__publicField(this,"migrations"),this.migrations=migrations.sort((a,b)=>a.version-b.version)}needsMigration(currentVersion){return currentVersion0&&__privateMethod(this,_updateMigrationRecord,updateMigrationRecord_fn).call(this,current.system._migration,migrations.slice(-1)[0]),current}async getUpdatedTable(tableSource,migrations){const current=deepClone(tableSource);for(const migration of migrations)try{await migration.updateTable?.(current)}catch(err){console.error(err)}return current}async getUpdatedMacro(macroSource,migrations){const current=deepClone(macroSource);for(const migration of migrations)try{await migration.updateMacro?.(current)}catch(err){console.error(err)}return current}async getUpdatedJournalEntry(source,migrations){const clone=deepClone(source);for(const migration of migrations)try{await migration.updateJournalEntry?.(clone)}catch(err){console.error(err)}return clone}async getUpdatedToken(token,migrations){const current=token.toObject();for(const migration of migrations)await migration.updateToken?.(current,token.actor,token.scene);return current}async getUpdatedUser(userData,migrations){const current=deepClone(userData);for(const migration of migrations)try{await migration.updateUser?.(current)}catch(err){console.error(err)}return current}};_updateMigrationRecord=new WeakSet,updateMigrationRecord_fn=__name2(function(migrations,latestMigration){if(!("game"in globalThis&&latestMigration))return;const fromVersion=typeof migrations.version=="number"?migrations.version:null;migrations.version=latestMigration.version,migrations.previous={schema:fromVersion,foundry:game.version,system:game.system.version}},"#updateMigrationRecord"),__name2(_MigrationRunnerBase,"MigrationRunnerBase"),__publicField(_MigrationRunnerBase,"LATEST_SCHEMA_VERSION",.878),__publicField(_MigrationRunnerBase,"MINIMUM_SAFE_VERSION",.618),__publicField(_MigrationRunnerBase,"RECOMMENDED_SAFE_VERSION",.634),__publicField(_MigrationRunnerBase,"FOUNDRY_SCHEMA_VERSIONS",{.8:.634,9:.7,10:.781,11:.841});let MigrationRunnerBase=_MigrationRunnerBase;const _Progress=class{static{__name(this,"_Progress")}value=0;max;label;constructor({max,label}){this.label=label??"",this.max=max}advance({by=1,label=this.label}={}){if(this.value===this.max)return;this.value+=Math.abs(by);const pct=Math.floor(this.value/this.max*100);SceneNavigation.displayProgressBar({label,pct})}close({label=""}={}){SceneNavigation.displayProgressBar({label,pct:100})}};__name2(_Progress,"Progress");let Progress=_Progress;const _MigrationRunner=class _MigrationRunner2 extends MigrationRunnerBase{static{__name(this,"_MigrationRunner")}constructor(){super(...arguments),__privateAdd(this,_migrateDocuments),__privateAdd(this,_migrateItem),__privateAdd(this,_migrateActor),__privateAdd(this,_migrateWorldJournalEntry),__privateAdd(this,_migrateWorldMacro),__privateAdd(this,_migrateWorldTable),__privateAdd(this,_migrateSceneToken),__privateAdd(this,_migrateUser)}needsMigration(){return super.needsMigration(game.settings.get("pf2e","worldSchemaVersion"))}static async ensureSchemaVersion(document2,migrations){if(migrations.length===0)return;const currentVersion=this.LATEST_SCHEMA_VERSION;if((Number(document2.schemaVersion)||0){try{return"items"in source?await runner.getUpdatedActor(source,runner.migrations):await runner.getUpdatedItem(source,runner.migrations)}catch{return null}})();updated&&document2.updateSource(updated)}if(document2.updateSource({"system._migration.version":currentVersion}),"items"in document2&&"token"in document2)for(const item of document2.items)item.schemaVersion||item.updateSource({"system._migration.version":currentVersion})}async runCompendiumMigration(compendium){const pack=compendium.metadata.id;ui.notifications.info(game.i18n.format("PF2E.Migrations.Starting",{version:game.system.version}));const documents=await compendium.getDocuments();await compendium.documentClass.updateDocuments(documents,{diff:!1,recursive:!1,pack}),ui.notifications.info(game.i18n.format("PF2E.Migrations.Finished",{version:game.system.version}))}async runMigrations(migrations){if(migrations.length===0)return;const progress=new Progress({label:game.i18n.localize("PF2E.Migrations.Running"),max:Math.floor(game.actors.size+game.items.size+game.scenes.map(s=>s.tokens.contents).flat().filter(t=>t.actor?.isToken).length)});await __privateMethod(this,_migrateDocuments,migrateDocuments_fn).call(this,game.actors,migrations,progress),await __privateMethod(this,_migrateDocuments,migrateDocuments_fn).call(this,game.items,migrations,progress);for(const entry of game.journal)await __privateMethod(this,_migrateWorldJournalEntry,migrateWorldJournalEntry_fn).call(this,entry,migrations);const promises=[];for(const macro of game.macros)promises.push(__privateMethod(this,_migrateWorldMacro,migrateWorldMacro_fn).call(this,macro,migrations));for(const table of game.tables)promises.push(__privateMethod(this,_migrateWorldTable,migrateWorldTable_fn).call(this,table,migrations));for(const user of game.users)promises.push(__privateMethod(this,_migrateUser,migrateUser_fn).call(this,user,migrations));for(const migration of migrations)migration.migrate&&promises.push(migration.migrate());await Promise.allSettled(promises);for(const scene of game.scenes)for(const token of scene.tokens){const{actor}=token;if(!actor||!!!await __privateMethod(this,_migrateSceneToken,migrateSceneToken_fn).call(this,token,migrations))continue;const deltaSource=token.delta?._source,hasMigratableData=!!deltaSource&&!!deltaSource.flags?.pf2e||((deltaSource??{}).items??[]).length>0||Object.keys(deltaSource?.system??{}).length>0;if(actor.isToken){if(hasMigratableData){const updated=await __privateMethod(this,_migrateActor,migrateActor_fn).call(this,migrations,actor);if(updated)try{await actor.update(updated,{noHook:!0})}catch(error){console.warn(error)}}progress.advance()}}progress.valueschemaVersion.current0&&await this.runMigrations(migrationPhase);await game.settings.set("pf2e","worldSchemaVersion",schemaVersion.latest)}};_migrateDocuments=new WeakSet,migrateDocuments_fn=__name2(async function(collection,migrations,progress){const DocumentClass=collection.documentClass,pack="metadata"in collection?collection.metadata.id:null,updateGroup=[];for(const document2 of collection.contents.sort(a=>a.type==="familiar"?1:-1)){if(updateGroup.length===50)try{await DocumentClass.updateDocuments(updateGroup,{noHook:!0,pack}),progress?.advance({by:updateGroup.length})}catch(error){console.warn(error)}finally{updateGroup.length=0}const updated="items"in document2?await __privateMethod(this,_migrateActor,migrateActor_fn).call(this,migrations,document2,{pack}):await __privateMethod(this,_migrateItem,migrateItem_fn).call(this,migrations,document2);updated&&updateGroup.push(updated)}if(updateGroup.length>0)try{await DocumentClass.updateDocuments(updateGroup,{noHook:!0,pack}),progress?.advance({by:updateGroup.length})}catch(error){console.warn(error)}},"#migrateDocuments"),_migrateItem=new WeakSet,migrateItem_fn=__name2(async function(migrations,item){const baseItem=item.toObject();try{return this.getUpdatedItem(baseItem,migrations)}catch(error){return error instanceof Error&&console.error(`Error thrown while migrating ${item.uuid}: ${error.message}`),null}},"#migrateItem"),_migrateActor=new WeakSet,migrateActor_fn=__name2(async function(migrations,actor,options={}){const{pack}=options,baseActor=actor.toObject(),updatedActor=await(()=>{try{return this.getUpdatedActor(baseActor,migrations)}catch(error){return error instanceof Error&&console.error(`Error thrown while migrating ${actor.uuid}: ${error.message}`),null}})();if(!updatedActor)return null;actor.effects.size>0&&actor.deleteEmbeddedDocuments("ActiveEffect",[],{deleteAll:!0});const baseItems=[...baseActor.items],updatedItems=[...updatedActor.items],itemDiff=this.diffCollection(baseItems,updatedItems),finalDeleted=itemDiff.deleted.filter(id=>actor.items.has(id));if(finalDeleted.length>0)try{await actor.deleteEmbeddedDocuments("Item",finalDeleted,{noHook:!0,pack})}catch(error){console.warn(error)}const finalUpdated=itemDiff.updated.filter(i=>actor.items.has(i._id));return updatedActor.items=[...itemDiff.inserted,...finalUpdated],updatedActor},"#migrateActor"),_migrateWorldJournalEntry=new WeakSet,migrateWorldJournalEntry_fn=__name2(async function(journalEntry,migrations){if(migrations.some(migration=>!!migration.updateJournalEntry))try{const updated=await this.getUpdatedJournalEntry(journalEntry.toObject(),migrations),changes=diffObject(journalEntry.toObject(),updated);Object.keys(changes).length>0&&await journalEntry.update(changes,{noHook:!0})}catch(error){console.warn(error)}},"#migrateWorldJournalEntry"),_migrateWorldMacro=new WeakSet,migrateWorldMacro_fn=__name2(async function(macro,migrations){if(migrations.some(migration=>!!migration.updateMacro))try{const updatedMacro=await this.getUpdatedMacro(macro.toObject(),migrations),changes=diffObject(macro.toObject(),updatedMacro);Object.keys(changes).length>0&&await macro.update(changes,{noHook:!0})}catch(error){console.warn(error)}},"#migrateWorldMacro"),_migrateWorldTable=new WeakSet,migrateWorldTable_fn=__name2(async function(table,migrations){if(migrations.some(migration=>!!migration.updateTable))try{const updatedMacro=await this.getUpdatedTable(table.toObject(),migrations),changes=diffObject(table.toObject(),updatedMacro);Object.keys(changes).length>0&&table.update(changes,{noHook:!0})}catch(error){console.warn(error)}},"#migrateWorldTable"),_migrateSceneToken=new WeakSet,migrateSceneToken_fn=__name2(async function(token,migrations){if(!migrations.some(migration=>!!migration.updateToken))return token.toObject();try{const updatedToken=await this.getUpdatedToken(token,migrations),changes=diffObject(token.toObject(),updatedToken);if(Object.keys(changes).length>0)try{await token.update(changes,{noHook:!0})}catch(error){console.warn(error)}return updatedToken}catch(error){return console.error(error),null}},"#migrateSceneToken"),_migrateUser=new WeakSet,migrateUser_fn=__name2(async function(user,migrations){if(migrations.some(migration=>!!migration.updateUser))try{const baseUser=user.toObject(),updatedUser=await this.getUpdatedUser(baseUser,migrations),changes=diffObject(user.toObject(),updatedUser);Object.keys(changes).length>0&&await user.update(changes,{noHook:!0})}catch(error){console.error(error)}},"#migrateUser"),__name2(_MigrationRunner,"MigrationRunner");let MigrationRunner=_MigrationRunner;const _MigrationBase=class{static{__name(this,"_MigrationBase")}version=this.constructor.version;requiresFlush=!1};__name2(_MigrationBase,"MigrationBase"),__publicField(_MigrationBase,"version");let MigrationBase=_MigrationBase;const _Migration600Reach=class extends MigrationBase{static{__name(this,"_Migration600Reach")}async updateItem(item){item.type==="ancestry"&&(item.system.reach=5)}};__name2(_Migration600Reach,"Migration600Reach"),__publicField(_Migration600Reach,"version",.6);let Migration600Reach=_Migration600Reach;function createHTMLElement(nodeName,{classes=[],dataset={},children=[],innerHTML}={}){const element=document.createElement(nodeName);classes.length>0&&element.classList.add(...classes);for(const[key,value]of Object.entries(dataset).filter(([,v])=>!isNil(v)))element.dataset[key]=String(value);if(innerHTML)element.innerHTML=innerHTML;else for(const child of children){const childElement=child instanceof HTMLElement?child:new Text(child);element.appendChild(childElement)}return element}__name(createHTMLElement,"createHTMLElement"),__name2(createHTMLElement,"createHTMLElement");function htmlQuery(parent,selectors){return parent instanceof Element||parent instanceof Document?parent.querySelector(selectors):null}__name(htmlQuery,"htmlQuery"),__name2(htmlQuery,"htmlQuery");function htmlQueryAll(parent,selectors){return parent instanceof Element||parent instanceof Document?Array.from(parent.querySelectorAll(selectors)):[]}__name(htmlQueryAll,"htmlQueryAll"),__name2(htmlQueryAll,"htmlQueryAll");function htmlClosest(child,selectors){return child instanceof Element?child.closest(selectors):null}__name(htmlClosest,"htmlClosest"),__name2(htmlClosest,"htmlClosest");function groupBy(array,criterion){const result=new Map;for(const elem of array){const key=criterion(elem),group=result.get(key);group?group.push(elem):result.set(key,[elem])}return result}__name(groupBy,"groupBy"),__name2(groupBy,"groupBy");function sortBy(mapping){return(a,b)=>{const value1=mapping(a),value2=mapping(b);return value1(result[key]=mapping(value,key),result),{})}__name(mapValues,"mapValues"),__name2(mapValues,"mapValues");function isBlank(text){return text==null||text.trim()===""}__name(isBlank,"isBlank"),__name2(isBlank,"isBlank");function addSign(number){return number<0?`${number}`:`+${number}`}__name(addSign,"addSign"),__name2(addSign,"addSign");function sum(values){return values.reduce((a,b)=>a+b,0)}__name(sum,"sum"),__name2(sum,"sum");function zip(a,b,zipFunction){return a.length>b.length?b.map((elem,index)=>zipFunction(a[index],elem)):a.map((elem,index)=>zipFunction(elem,b[index]))}__name(zip,"zip"),__name2(zip,"zip");function applyNTimes(func,times,start){let result=start;for(let i=0;i(key in obj&&(result[key]=obj[key]),result),{})}__name(pick,"pick"),__name2(pick,"pick");let intlNumberFormat;function signedInteger(value,{emptyStringZero=!1}={}){return value===0&&emptyStringZero?"":(intlNumberFormat??=new Intl.NumberFormat(game.i18n.lang,{maximumFractionDigits:0,signDisplay:"always"})).format(value)}__name(signedInteger,"signedInteger"),__name2(signedInteger,"signedInteger");const wordCharacter=String.raw`[\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Join_Control}]`,nonWordCharacter=String.raw`[^\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Join_Control}]`,nonWordCharacterRE=new RegExp(nonWordCharacter,"gu"),wordBoundary=String.raw`(?:${wordCharacter})(?=${nonWordCharacter})|(?:${nonWordCharacter})(?=${wordCharacter})`,nonWordBoundary=String.raw`(?:${wordCharacter})(?=${wordCharacter})`,lowerCaseLetter=String.raw`\p{Lowercase_Letter}`,upperCaseLetter=String.raw`\p{Uppercase_Letter}`,lowerCaseThenUpperCaseRE=new RegExp(`(${lowerCaseLetter})(${upperCaseLetter}${nonWordBoundary})`,"gu"),nonWordCharacterHyphenOrSpaceRE=/[^-\p{White_Space}\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Join_Control}]/gu,upperOrWordBoundariedLowerRE=new RegExp(`${upperCaseLetter}|(?:${wordBoundary})${lowerCaseLetter}`,"gu");function sluggify(text,{camel=null}={}){if(typeof text!="string")return console.warn("Non-string argument passed to `sluggify`"),"";if(text==="-")return text;switch(camel){case null:return text.replace(lowerCaseThenUpperCaseRE,"$1-$2").toLowerCase().replace(/['’]/g,"").replace(nonWordCharacterRE," ").trim().replace(/[-\s]+/g,"-");case"bactrian":{const dromedary=sluggify(text,{camel:"dromedary"});return dromedary.charAt(0).toUpperCase()+dromedary.slice(1)}case"dromedary":return text.replace(nonWordCharacterHyphenOrSpaceRE,"").replace(/[-_]+/g," ").replace(upperOrWordBoundariedLowerRE,(part,index)=>index===0?part.toLowerCase():part.toUpperCase()).replace(/\s+/g,"");default:throw ErrorPF2e("I don't think that's a real camel.")}}__name(sluggify,"sluggify"),__name2(sluggify,"sluggify");function parseHTML(unparsed){const fragment=document.createElement("template");fragment.innerHTML=unparsed;const element=fragment.content.firstElementChild;if(!(element instanceof HTMLElement))throw ErrorPF2e("Unexpected error parsing HTML");return element}__name(parseHTML,"parseHTML"),__name2(parseHTML,"parseHTML");function getActionTypeLabel(type,cost){switch(type){case"action":return cost===1?"PF2E.Item.Action.Type.Single":"PF2E.Item.Action.Type.Activity";case"free":return"PF2E.Item.Action.Type.Free";case"reaction":return"PF2E.Item.Action.Type.Reaction";default:return null}}__name(getActionTypeLabel,"getActionTypeLabel"),__name2(getActionTypeLabel,"getActionTypeLabel");const actionImgMap={0:"systems/pf2e/icons/actions/FreeAction.webp",free:"systems/pf2e/icons/actions/FreeAction.webp",1:"systems/pf2e/icons/actions/OneAction.webp",2:"systems/pf2e/icons/actions/TwoActions.webp",3:"systems/pf2e/icons/actions/ThreeActions.webp","1 or 2":"systems/pf2e/icons/actions/OneTwoActions.webp","1 to 3":"systems/pf2e/icons/actions/OneThreeActions.webp","2 or 3":"systems/pf2e/icons/actions/TwoThreeActions.webp",reaction:"systems/pf2e/icons/actions/Reaction.webp",passive:"systems/pf2e/icons/actions/Passive.webp"};function getActionIcon(action2,fallback="systems/pf2e/icons/actions/Empty.webp"){if(action2===null)return actionImgMap.passive;const value=typeof action2!="object"?action2:action2.type==="action"?action2.value:action2.type,sanitized=String(value??"").toLowerCase().trim();return actionImgMap[sanitized]??fallback}__name(getActionIcon,"getActionIcon"),__name2(getActionIcon,"getActionIcon");const actionGlyphMap={0:"F",free:"F",1:"A",2:"D",3:"T","1 or 2":"A/D","1 to 3":"A - T","2 or 3":"D/T",reaction:"R"};function getActionGlyph(action2){if(!action2&&action2!==0)return"";const value=typeof action2!="object"?action2:action2.type==="action"?action2.value:action2.type,sanitized=String(value??"").toLowerCase().trim();return actionGlyphMap[sanitized]??""}__name(getActionGlyph,"getActionGlyph"),__name2(getActionGlyph,"getActionGlyph");function ErrorPF2e(message){return Error(`PF2e System | ${message}`)}__name(ErrorPF2e,"ErrorPF2e"),__name2(ErrorPF2e,"ErrorPF2e");function ordinal(value){const pluralRules=new Intl.PluralRules(game.i18n.lang,{type:"ordinal"}),suffix=game.i18n.localize(`PF2E.OrdinalSuffixes.${pluralRules.select(value)}`);return game.i18n.format("PF2E.OrdinalNumber",{value,suffix})}__name(ordinal,"ordinal"),__name2(ordinal,"ordinal");function localizeList(items,{conjunction="or"}={}){items=[...items].sort((a,b)=>a.localeCompare(b,game.i18n.lang));const parts=conjunction==="or"?"PF2E.ListPartsOr":"PF2E.ListPartsAnd";if(items.length===0)return"";if(items.length===1)return items[0];if(items.length===2)return game.i18n.format(`${parts}.two`,{first:items[0],second:items[1]});let result=game.i18n.format(`${parts}.start`,{first:items[0],second:"{second}"});for(let i=1;i<=items.length-2;i++)if(i===items.length-2){const end=game.i18n.format(`${parts}.end`,{first:items[i],second:items[items.length-1]});result=result.replace("{second}",end)}else{const newSegment=game.i18n.format(`${parts}.middle`,{first:items[i],second:"{second}"});result=result.replace("{second}",newSegment)}return result}__name(localizeList,"localizeList"),__name2(localizeList,"localizeList");function fontAwesomeIcon(glyph,{style="solid",fixedWidth=!1}={}){const styleClass=`fa-${style}`,glyphClass=glyph.startsWith("fa-")?glyph:`fa-${glyph}`,icon=document.createElement("i");return icon.classList.add(styleClass,glyphClass),fixedWidth&&icon.classList.add("fa-fw"),icon}__name(fontAwesomeIcon,"fontAwesomeIcon"),__name2(fontAwesomeIcon,"fontAwesomeIcon");function isObject(value){return typeof value=="object"&&value!==null}__name(isObject,"isObject"),__name2(isObject,"isObject");function sortLabeledRecord(record){return Object.entries(record).sort((a,b)=>a[1].label.localeCompare(b[1].label,game.i18n.lang)).reduce((copy,[key,value])=>mergeObject(copy,{[key]:value}),{})}__name(sortLabeledRecord,"sortLabeledRecord"),__name2(sortLabeledRecord,"sortLabeledRecord");function sortStringRecord(record){return Object.fromEntries(Object.entries(record).map(entry=>(entry[1]=game.i18n.localize(entry[1]),entry)).sort((a,b)=>a[1].localeCompare(b[1],game.i18n.lang)))}__name(sortStringRecord,"sortStringRecord"),__name2(sortStringRecord,"sortStringRecord");function recursiveReplaceString(source,replace){const clone=Array.isArray(source)||isObject(source)?deepClone(source):source;if(typeof clone=="string")return replace(clone);if(Array.isArray(clone))return clone.map(e=>recursiveReplaceString(e,replace));if(isObject(clone))for(const key of Object.keys(clone))clone[key]=recursiveReplaceString(clone[key],replace);return clone}__name(recursiveReplaceString,"recursiveReplaceString"),__name2(recursiveReplaceString,"recursiveReplaceString");function localizer(prefix){return(...[suffix,formatArgs])=>formatArgs?game.i18n.format(`${prefix}.${suffix}`,formatArgs):game.i18n.localize(`${prefix}.${suffix}`)}__name(localizer,"localizer"),__name2(localizer,"localizer");function configFromLocalization(localization,prefix){return Object.entries(localization).reduce((result,[key,value])=>(result[key]=typeof value=="string"?`${prefix}.${key}`:configFromLocalization(value,`${prefix}.${key}`),result),{})}__name(configFromLocalization,"configFromLocalization"),__name2(configFromLocalization,"configFromLocalization");function isImageFilePath(path){return typeof path=="string"&&Object.keys(CONST.IMAGE_FILE_EXTENSIONS).some(e=>path.endsWith(`.${e}`))}__name(isImageFilePath,"isImageFilePath"),__name2(isImageFilePath,"isImageFilePath");function isVideoFilePath(path){return typeof path=="string"&&Object.keys(CONST.VIDEO_FILE_EXTENSIONS).some(e=>path.endsWith(`.${e}`))}__name(isVideoFilePath,"isVideoFilePath"),__name2(isVideoFilePath,"isVideoFilePath");function isImageOrVideoPath(path){return isImageFilePath(path)||isVideoFilePath(path)}__name(isImageOrVideoPath,"isImageOrVideoPath"),__name2(isImageOrVideoPath,"isImageOrVideoPath");const SORTABLE_DEFAULTS={animation:200,direction:"vertical",dragClass:"drag-preview",dragoverBubble:!0,easing:"cubic-bezier(1, 0, 0, 1)",ghostClass:"drag-gap",scroll:!0,scrollSensitivity:30,scrollSpeed:15};function traitSlugToObject(trait,dictionary){const traitObject={name:trait,label:game.i18n.localize(dictionary[trait]??trait)};return objectHasKey(CONFIG.PF2E.traitsDescriptions,trait)&&(traitObject.description=CONFIG.PF2E.traitsDescriptions[trait]),traitObject}__name(traitSlugToObject,"traitSlugToObject"),__name2(traitSlugToObject,"traitSlugToObject");function transformWhitelist(whitelist){return Array.isArray(whitelist)?whitelist:Object.entries(whitelist).map(([key,locPath])=>({id:key,value:game.i18n.localize(typeof locPath=="string"?locPath:locPath.label)})).sort((a,b)=>a.value.localeCompare(b.value,game.i18n.lang))}__name(transformWhitelist,"transformWhitelist"),__name2(transformWhitelist,"transformWhitelist");function tagify$1(input,{whitelist,maxTags,enforceWhitelist=!0}={}){if(input?.hasAttribute("name")&&input.dataset.dtype!=="JSON")throw ErrorPF2e("Usable only on input elements with JSON data-dtype");if(!input)return null;const whitelistTransformed=whitelist?transformWhitelist(whitelist):[],maxItems=whitelist?Object.keys(whitelistTransformed).length:void 0,tagify2=new Tagify(input,{enforceWhitelist:!!whitelist&&enforceWhitelist,keepInvalidTags:!1,skipInvalid:!!whitelist,maxTags:maxTags??maxItems,dropdown:{enabled:0,maxItems,searchKeys:["id","value"]},whitelist:whitelistTransformed});return input.name&&(tagify2.DOM.scope.dataset.name=input.name),tagify2.DOM.input.blur(),tagify2}__name(tagify$1,"tagify$1"),__name2(tagify$1,"tagify$1");const _DelegatedCollection=class{static{__name(this,"_DelegatedCollection")}constructor(entries=[]){__privateAdd(this,_data,void 0),__privateSet(this,_data,new Collection(entries))}[Symbol.iterator](){return __privateGet(this,_data).values()}get size(){return __privateGet(this,_data).size}get contents(){return __privateGet(this,_data).contents}get(key,options){return __privateGet(this,_data).get(key,options)}set(key,value){return __privateGet(this,_data).set(key,value),this}has(key){return __privateGet(this,_data).has(key)}find(predicate){return __privateGet(this,_data).find(predicate)}some(predicate){return __privateGet(this,_data).some(predicate)}filter(predicate){return __privateGet(this,_data).filter(predicate)}map(callback){return __privateGet(this,_data).map(callback)}delete(key){return __privateGet(this,_data).delete(key)}clear(){__privateGet(this,_data).clear()}};_data=new WeakMap,__name2(_DelegatedCollection,"DelegatedCollection");let DelegatedCollection=_DelegatedCollection;const _Migration601SplitEffectCompendia=class _Migration601SplitEffectCompendia2 extends MigrationBase{static{__name(this,"_Migration601SplitEffectCompendia")}async updateItem(item){typeof item.system.description.value=="string"&&(item.system.description.value=item.system.description.value.replace(/(@Compendium\[pf2e\.)(spell-effects)(\.)([a-zA-Z0-9]{16})(\]{.*?})/g,(_full,first,_replace2,dot,itemId,rest)=>{const packName=objectHasKey(_Migration601SplitEffectCompendia2.effectLocations,itemId)?_Migration601SplitEffectCompendia2.effectLocations[itemId]:"??";return first+packName+dot+itemId+rest})),typeof item.flags.core?.sourceId=="string"&&(item.flags.core.sourceId=item.flags.core.sourceId.replace(/(Compendium\.pf2e\.)(spell-effects)(\.)([a-zA-Z0-9]{16})/g,(_full,first,_replace2,dot,itemId)=>{const packName=objectHasKey(_Migration601SplitEffectCompendia2.effectLocations,itemId)?_Migration601SplitEffectCompendia2.effectLocations[itemId]:"??";return first+packName+dot+itemId}))}async migrate(){for(const macro of game.macros)macro._source.command=macro._source.command.replace(/(Compendium\.pf2e\.)(spell-effects)(\.)([a-zA-Z0-9]{16})/g,(_full,first,_replace2,dot,itemId)=>{const packName=objectHasKey(_Migration601SplitEffectCompendia2.effectLocations,itemId)?_Migration601SplitEffectCompendia2.effectLocations[itemId]:"??";return first+packName+dot+itemId})}};__name2(_Migration601SplitEffectCompendia,"Migration601SplitEffectCompendia"),__publicField(_Migration601SplitEffectCompendia,"version",.601),__publicField(_Migration601SplitEffectCompendia,"effectLocations",{QuZ5frBMJF3gi7RY:"consumable-effects","7z1iY4AaNEAIKuAU":"consumable-effects","1mKjaWC65KWPuFR4":"consumable-effects",mi4Md1fB2XThCand:"consumable-effects",R106i7WCXvHLGMTu:"consumable-effects",kkDbalYEavzRpYlp:"consumable-effects",qVKrrKpTghgMIuGH:"consumable-effects",HeRHBo2NaKy5IxhU:"consumable-effects",tTBJ33UGtzXjWOJp:"consumable-effects",xVAdPzFaSvJXPMKv:"consumable-effects",fYjvLx9DHIdCHdDx:"consumable-effects",kwD0wuW5Ndkc9YXB:"consumable-effects",fIpzDpuwLdIS4tW5:"consumable-effects","1ouUo8lLK6H79Rqh":"consumable-effects",xFQRiVU6h8EA6Lw9:"consumable-effects",MI5OCkF9IXmD2lPF:"consumable-effects",S4MZzALqFoXJsr6o:"consumable-effects",wFF0SZs1Hcf87Kk1:"consumable-effects","2C1HuKDQDGFZuv7l":"consumable-effects",q1EhQ716bPSgJVnC:"consumable-effects",eh7EqmDBDW30ShCu:"consumable-effects",wTZnKkT0K4Tdy8mD:"consumable-effects",Cxa7MdgMCUoMqbKm:"consumable-effects",PeuUz7JaabCgl6Yh:"consumable-effects",lNWACCNe9RYgaFxb:"consumable-effects",j9zVZwRBVAcnpEkE:"consumable-effects",qit1mLbJUyRTYcPU:"consumable-effects",jaBMZKdoywOTrQvP:"consumable-effects",RT1BxXrbbGgk40Ti:"consumable-effects",ztxW3lBPRcesF7wK:"consumable-effects","7vCenP9j6FuHRv5C":"consumable-effects","7UL8belWmo7U5YGM":"consumable-effects",bcxVvIbuZWOvsKcA:"consumable-effects","4tepFOJLhZSelPoa":"consumable-effects",qwoLV4awdezlEJ60:"consumable-effects",GBBjw61g4ekJymT0:"consumable-effects",vFOr2JAJxiVvvn2E:"consumable-effects",BV8RPntjc9FUzD3g:"consumable-effects",kgotU0sFmtAHYySB:"consumable-effects",VCypzSu659eC6jNi:"consumable-effects",wyLEew86nhNUXASu:"consumable-effects",Wa4317cqU4lJ8vAQ:"consumable-effects",Z9oPh462q82IYIZ6:"consumable-effects",EpB7yJPEuG6ez4z3:"consumable-effects",PpLxndUSgzgs6dd0:"consumable-effects",lPRuIRbu0rHBkoKY:"consumable-effects",Yxssrnh9UZJAM0V7:"consumable-effects","9MeHc072G4L8AJkp":"consumable-effects",xLilBqqf34ZJYO9i:"consumable-effects","1l139A2Qik4lBHKO":"consumable-effects","2PNo8u4wxSbz5WEs":"consumable-effects",fUrZ4xcMJz0CfTyG:"consumable-effects","6A8jsLR7upLGuRiv":"consumable-effects",Zdh2uO1vVYJmaqld:"consumable-effects",Mf9EBLhYmZerf0nS:"consumable-effects",ModBoFdCi7YQU4gP:"consumable-effects",W3xQBLj5hLOtb6Tj:"consumable-effects","2Bds6d4UGQZqYSZM":"consumable-effects","6PNLBIdlqqWNCFMy":"consumable-effects","988f6NpOo4YzFzIr":"consumable-effects",VPtsrpbP0AE642al:"consumable-effects",MCny5ohCGf09a7Wl:"consumable-effects",RRusoN3HEGnDO1Dg:"consumable-effects",thOpQunbQr77XWdF:"consumable-effects","9keegq0GdS1eSrNr":"consumable-effects",jw6Tr9FbErjLAFLQ:"consumable-effects","5xgapIXn5DwbXHKh":"consumable-effects",t7VUJHSUT6bkVUjg:"consumable-effects",yrbz0rZzp8aZEqbv:"consumable-effects","16tOZk4qy329s2aK":"consumable-effects",zd85Ny1RS46OL0TD:"consumable-effects",oAewXfq9c0ecaSfw:"consumable-effects",dpIrjd1UPY7EnWUD:"consumable-effects","9FfFhu2kl2wMTsiI":"consumable-effects",v5Ht1V4MZvRKRBjL:"consumable-effects",TkRuKKYyPHTGPfgf:"consumable-effects",XrlChFETfe8avLsX:"consumable-effects",qzRcSQ0HTTp58hV2:"consumable-effects",TsWUTODTVi487SEz:"consumable-effects","5Gof60StUppR2Xn9":"consumable-effects",mG6S6zm6hxaF7Tla:"consumable-effects",zlSNbMDIlTOpcO8R:"consumable-effects",b9DTIJyBT8kvIBpj:"consumable-effects",PEPOd38VfVzQMKG5:"consumable-effects","1xHHvQlW4pRR89qj":"consumable-effects",AMhUb42NAJ1aisZp:"consumable-effects",kwOtHtmlH69ctK0O:"consumable-effects",VrYfR2WuyA15zFhq:"consumable-effects",OAN5Fj21PJPhIqRU:"consumable-effects",e6dXfbKzv5sNr1zh:"consumable-effects",Hnt3Trd7TiFICB06:"consumable-effects",p2aGtovaY1feytws:"equipment-effects",yvabfuAO74pvH8hh:"equipment-effects",etJW0w4CiSFgMrWP:"equipment-effects",vOU4Yv2MyAfYBbmF:"equipment-effects",FbFl95WRpzrrijh3:"equipment-effects",iK6JeCsZwm5Vakks:"equipment-effects",P7Y7pO2ulZ5wBgxU:"equipment-effects",cg5qyeMJUh6b4fta:"equipment-effects",fbSFwwp60AuDDKpK:"equipment-effects","88kqcDmsoAEddzUt":"equipment-effects",lLP56tbG689TNKW5:"equipment-effects",PeiuJ951kkBPTCSM:"equipment-effects",G0lG7IIZnCZtYi6v:"equipment-effects",gDefAEEMXVVZgqXH:"equipment-effects",uXEp1rPU5fY4OiBf:"equipment-effects",Uadsb25G18pKdZ2e:"equipment-effects",viCX9fZzTWGuoO85:"equipment-effects",eeGWTG9ZAha4IIOY:"equipment-effects",ioGzmVSmMGXWWBYb:"equipment-effects",pAMyEbJzWBoYoGhs:"equipment-effects","7dLsA9PAb5ij7Bc6":"equipment-effects",NE7Fm5YnUhD4ySX3:"equipment-effects","8ersuvNJXX00XaIQ":"equipment-effects",EpNflrkmWzQ0lEb4:"equipment-effects",iEkH8BKLMUa2wxLX:"equipment-effects",bP40jr6wE6MCsRvY:"equipment-effects",eSIYyxi6uTKiP6W5:"equipment-effects",E4B02mJmNexQLa8F:"equipment-effects","3O5lvuX4VHqtpCkU":"equipment-effects",ah41XCrV4LFsVyzl:"equipment-effects",W3BCLbX6j1IqL0uB:"equipment-effects",zqKzWGLODgIvtiKf:"equipment-effects",lBMhT2W2raYMa8JS:"equipment-effects","5uK3fmGlfJrbWQz4":"equipment-effects",i0tm2ZHekp7rGGR3:"equipment-effects",Zb8RYgmzCI6fQE0o:"equipment-effects",QapoFh0tbUgMwSIB:"equipment-effects",UlalLihKzDxcOdXL:"equipment-effects",lO95TwgihBdTilAB:"equipment-effects","9PASRixhNM0ogqmG":"equipment-effects","7MgpgF8tOXOiDEwv":"equipment-effects","1S51uIRb9bnZtpFU":"equipment-effects","1nCwQErK6hpkNvfw":"feat-effects","5IGz4iheaiUWm5KR":"feat-effects",uFYvW3kFP9iyNfVX:"feat-effects",CgxYa0lrLUjS2ZhI:"feat-effects",nwkYZs6YwXYAJ4ps:"feat-effects",qUowHpn79Dpt1hVn:"feat-effects",RozqjLocahvQWERr:"feat-effects",tPKXLtDJ3bzJcXlv:"feat-effects",gYpy9XBPScIlY93p:"feat-effects",Im5JBInybWFbHEYS:"feat-effects",BCyGDKcplkJiSAKJ:"feat-effects",PMHwCrnh9W4sMu5b:"feat-effects",pf9yvKNg6jZLrE30:"feat-effects",eeAlh6edygcZIz9c:"feat-effects",b2kWJuCPj1rDMdwz:"feat-effects",UQ7vZgmfK0VSFS8A:"feature-effects",s1tulrmW6teTFjVd:"feature-effects",aKRo5TIhUtu0kyEr:"feature-effects",yfbP64r4a9e5oyli:"feature-effects",n1vhmOd7aNiuR3nk:"feature-effects",FNTTeJHiK6iOjrSq:"feature-effects","3gGBZHcUFsHLJeQH":"feature-effects",rJpkKaPRGaH0pLse:"feature-effects","9AUcoY48H5LrVZiF":"feature-effects",KVbS7AbhQdeuA0J6:"feature-effects","6fb15XuSV4TNuVAT":"feature-effects",vguxP8ukwVTWWWaA:"feature-effects",SVGW8CLKwixFlnTv:"feature-effects",ruRAfGJnik7lRavk:"feature-effects",uBJsxCzNhje8m8jj:"feature-effects","7BFd8A9HFrmg6vwL":"feature-effects",z3uyCMBddrPK5umr:"feature-effects",Nv70aqcQgCBpDYp8:"feature-effects",OqH6IaeOwRWkGPrk:"feature-effects",Lb4q2bBAgxamtix5:"feature-effects",Gqy7K6FnbLtwGpud:"spell-effects","41WThj17MZBXTO2X":"spell-effects",sPCWrhUHqlbGhYSD:"spell-effects","3qHKBDF7lrHw8jFK":"spell-effects",l9HRQggofFGIxEse:"spell-effects",beReeFroAx24hj83:"spell-effects",qkwb5DD3zmKwvbk0:"spell-effects",GnWkI3T3LYRlm3X8:"spell-effects",dWbg2gACxMkSnZag:"spell-effects",Jemq5UknGdMO7b73:"spell-effects",LXf1Cqi1zyo4DaLv:"spell-effects"});let Migration601SplitEffectCompendia=_Migration601SplitEffectCompendia;const _Migration602UpdateDiehardFeat=class extends MigrationBase{static{__name(this,"_Migration602UpdateDiehardFeat")}constructor(){super(),__publicField(this,"requiresFlush",!0),__privateAdd(this,_diehardPromise,void 0),__privateSet(this,_diehardPromise,fromUuid("Compendium.pf2e.feats-srd.I0BhPWqYf1bbzEYg"))}async updateActor(source){const diehard=source.items.find(itemData=>itemData.system.slug==="diehard"&&itemData.type==="feat");if(source.type==="character"&&diehard!==void 0&&"dying"in source.system.attributes&&isObject(source.system.attributes.dying)){source.system.attributes.dying.max=4;const diehardIndex=source.items.indexOf(diehard),newDiehard=await __privateGet(this,_diehardPromise);if(!(newDiehard instanceof FeatPF2e))throw Error("PF2E System | Expected item not found in Compendium");source.items.splice(diehardIndex,1,newDiehard.toObject())}}};_diehardPromise=new WeakMap,__name2(_Migration602UpdateDiehardFeat,"Migration602UpdateDiehardFeat"),__publicField(_Migration602UpdateDiehardFeat,"version",.602);let Migration602UpdateDiehardFeat=_Migration602UpdateDiehardFeat;const _Migration603ResetQuickRollDefault=class extends MigrationBase{static{__name(this,"_Migration603ResetQuickRollDefault")}async updateUser(userData){const flags=userData.flags;isObject(flags.PF2e)&&isObject(flags.PF2e.settings)&&typeof flags.PF2e.settings.quickD20roll=="boolean"&&(flags.PF2e.settings.quickD20roll=!1)}};__name2(_Migration603ResetQuickRollDefault,"Migration603ResetQuickRollDefault"),__publicField(_Migration603ResetQuickRollDefault,"version",.603);let Migration603ResetQuickRollDefault=_Migration603ResetQuickRollDefault;const _Migration604FixClassItem=class extends MigrationBase{static{__name(this,"_Migration604FixClassItem")}async updateItem(item){item.type==="class"&&(Array.isArray(item.system.ancestryFeatLevels)&&(item.system.ancestryFeatLevels={value:item.system.ancestryFeatLevels}),Array.isArray(item.system.classFeatLevels)&&(item.system.classFeatLevels={value:item.system.classFeatLevels}),Array.isArray(item.system.skillFeatLevels)&&(item.system.skillFeatLevels={value:item.system.skillFeatLevels}),Array.isArray(item.system.generalFeatLevels)&&(item.system.generalFeatLevels={value:item.system.generalFeatLevels}),Array.isArray(item.system.skillIncreaseLevels)&&(item.system.skillIncreaseLevels={value:item.system.skillIncreaseLevels}),Array.isArray(item.system.abilityBoostLevels)&&(item.system.abilityBoostLevels={value:item.system.abilityBoostLevels}))}};__name2(_Migration604FixClassItem,"Migration604FixClassItem"),__publicField(_Migration604FixClassItem,"version",.604);let Migration604FixClassItem=_Migration604FixClassItem;const PHYSICAL_ITEM_TYPES=new Set(["armor","backpack","book","consumable","equipment","treasure","weapon"]),BULK_VALUES=["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","L"],PRECIOUS_MATERIAL_TYPES=new Set(["abysium","adamantine","cold-iron","darkwood","djezet","dragonhide","grisantian-pelt","inubrix","keep-stone","mithral","noqual","orichalcum","peachwood","siccatite","silver","sisterstone","sisterstone-dusk","sisterstone-scarlet","sovereign-steel","warpglass"]),PRECIOUS_MATERIAL_GRADES=new Set(["low","standard","high"]),DENOMINATIONS=["pp","gp","sp","cp"];function isItemSystemData(data){return isObject(data)&&isObject(data.description)&&typeof data.description.value=="string"&&Array.isArray(data.rules)&&(data.slug===null||typeof data.slug=="string")}__name(isItemSystemData,"isItemSystemData"),__name2(isItemSystemData,"isItemSystemData");function isPhysicalData(source){return setHasElement(PHYSICAL_ITEM_TYPES,source.type)}__name(isPhysicalData,"isPhysicalData"),__name2(isPhysicalData,"isPhysicalData");function hasInvestedProperty(source){return isPhysicalData(source)&&"invested"in source.system.equipped}__name(hasInvestedProperty,"hasInvestedProperty"),__name2(hasInvestedProperty,"hasInvestedProperty");const _Migration605CatchUpToTemplateJSON=class extends MigrationBase{static{__name(this,"_Migration605CatchUpToTemplateJSON")}addEffects(entityData){Array.isArray(entityData.effects)||(entityData.effects=[])}async updateActor(actorData){if(this.addEffects(actorData),actorData.type==="character"||actorData.type==="npc"){if("max"in actorData.system.attributes.hp&&typeof actorData.system.attributes.hp.max=="string"){const newMax=parseInt(actorData.system.attributes.hp.max,10);Number.isInteger(newMax)&&(actorData.system.attributes.hp.max=newMax)}if(typeof actorData.system.attributes.hp.value=="string"){const newValue=parseInt(actorData.system.attributes.hp.value,10);Number.isInteger(newValue)&&(actorData.system.attributes.hp.value=newValue)}if(typeof actorData.system.details.level.value=="string"){const newLevel=parseInt(actorData.system.details.level.value,10);Number.isInteger(newLevel)&&(actorData.system.details.level.value=newLevel)}"tempmax"in actorData.system.attributes.hp&&delete actorData.system.attributes.hp.tempmax,"special"in actorData.system.attributes.speed&&delete actorData.system.attributes.speed.special}}async updateItem(itemData,actorData){this.addEffects(itemData),!itemData.system.slug&&actorData&&(itemData.system.slug=null),Array.isArray(itemData.system.rules)||(itemData.system.rules=[]);const traits=itemData.system.traits;if(traits&&!traits.custom&&(traits.custom=""),traits&&!traits.rarity&&(traits.rarity={value:"common"}),isPhysicalData(itemData)&&!itemData.system.identification){const withoutIdentifyData=itemData.system;withoutIdentifyData.identification.status="identified"}itemData.type==="spell"&&!itemData.system.hasCounteractCheck&&(itemData.system.hasCounteractCheck={value:!1}),itemData.type==="lore"&&"featType"in itemData.system&&delete itemData.system.featType,itemData.type==="action"&&"skill_requirements"in itemData.system&&delete itemData.system.skill_requirements,itemData.type==="action"&&"skill_requirement"in itemData.system&&itemData.system.skill_requirement}};__name2(_Migration605CatchUpToTemplateJSON,"Migration605CatchUpToTemplateJSON"),__publicField(_Migration605CatchUpToTemplateJSON,"version",.605);let Migration605CatchUpToTemplateJSON=_Migration605CatchUpToTemplateJSON;const _Migration606SignatureSpells=class extends MigrationBase{static{__name(this,"_Migration606SignatureSpells")}async updateItem(item){if(item.type==="spellcastingEntry"){const data=item.system;data.signatureSpells||(data.signatureSpells={value:[]})}}};__name2(_Migration606SignatureSpells,"Migration606SignatureSpells"),__publicField(_Migration606SignatureSpells,"version",.606);let Migration606SignatureSpells=_Migration606SignatureSpells;const _Migration607MeleeItemDamageRolls=class extends MigrationBase{static{__name(this,"_Migration607MeleeItemDamageRolls")}async updateItem(itemData){if(itemData.type==="melee"&&Array.isArray(itemData.system.damageRolls)){const damageRolls={};itemData.system.damageRolls.forEach(roll=>{const key=randomID(20);damageRolls[key]=roll}),itemData.system.damageRolls=damageRolls}}};__name2(_Migration607MeleeItemDamageRolls,"Migration607MeleeItemDamageRolls"),__publicField(_Migration607MeleeItemDamageRolls,"version",.607);let Migration607MeleeItemDamageRolls=_Migration607MeleeItemDamageRolls;const _Migration608DeletePersistedKits=class extends MigrationBase{static{__name(this,"_Migration608DeletePersistedKits")}async updateItem(itemData,actorData){if(actorData&&itemData.type==="kit"){const index=actorData.items.indexOf(itemData);actorData.items.splice(index,1)}}};__name2(_Migration608DeletePersistedKits,"Migration608DeletePersistedKits"),__publicField(_Migration608DeletePersistedKits,"version",.608);let Migration608DeletePersistedKits=_Migration608DeletePersistedKits;const _Migration609LootActorTraits=class extends MigrationBase{static{__name(this,"_Migration609LootActorTraits")}async updateActor(source){if(source.type==="loot"&&source.system.traits&&"traits"in source.system.traits){const systemData=source.system;systemData.traits||(systemData.traits={rarity:{value:"common"},size:{value:"med"},traits:{value:[]},di:{value:[]},dr:[],dv:[],ci:[]})}}};__name2(_Migration609LootActorTraits,"Migration609LootActorTraits"),__publicField(_Migration609LootActorTraits,"version",.609);let Migration609LootActorTraits=_Migration609LootActorTraits;const _Migration610SetHeritageFeatType=class extends MigrationBase{static{__name(this,"_Migration610SetHeritageFeatType")}async updateItem(source){const itemTraits=source.system.traits?.value;if(source.type==="feat"&&itemTraits?.includes("heritage")){const{system}=source,featType="featType"in system&&isObject(system.featType)&&"value"in system.featType&&typeof system.featType.value=="string"?system.featType:{value:""};featType.value="heritage";const index=itemTraits.indexOf("heritage");itemTraits.splice(index,1)}}};__name2(_Migration610SetHeritageFeatType,"Migration610SetHeritageFeatType"),__publicField(_Migration610SetHeritageFeatType,"version",.61);let Migration610SetHeritageFeatType=_Migration610SetHeritageFeatType;const _Migration611UpdateToughnessMountainsStoutness=class extends MigrationBase{static{__name(this,"_Migration611UpdateToughnessMountainsStoutness")}constructor(){super(),__publicField(this,"requiresFlush",!0),__privateAdd(this,_featSlugs,["mountains-stoutness","mountain-s-stoutness","toughness"]),__privateAdd(this,_featsPromise,void 0),__privateSet(this,_featsPromise,game.packs.get("pf2e.feats-srd").getDocuments())}async updateActor(actorData){if(actorData.type!=="character")return;const oldFeatsData=actorData.items.filter(itemData=>__privateGet(this,_featSlugs).includes(itemData.system.slug??"")&&itemData.type==="feat");for(const oldFeatData of oldFeatsData){oldFeatData.system.slug==="mountain-s-stoutness"&&(oldFeatData.system.slug="mountains-stoutness");const newFeat=oldFeatData.system.slug==="toughness"?(await __privateGet(this,_featsPromise)).find(feat=>feat.slug==="toughness"):(await __privateGet(this,_featsPromise)).find(feat=>feat.slug==="mountains-stoutness");if(!(newFeat instanceof FeatPF2e))throw ErrorPF2e("Expected item not found in Compendium");newFeat._source.system.location=oldFeatData.system.location;const oldFeatIndex=actorData.items.indexOf(oldFeatData);actorData.items.splice(oldFeatIndex,1,newFeat.toObject())}}};_featSlugs=new WeakMap,_featsPromise=new WeakMap,__name2(_Migration611UpdateToughnessMountainsStoutness,"Migration611UpdateToughnessMountainsStoutness"),__publicField(_Migration611UpdateToughnessMountainsStoutness,"version",.611);let Migration611UpdateToughnessMountainsStoutness=_Migration611UpdateToughnessMountainsStoutness;const _Migration612NormalizeRarities=class extends MigrationBase{static{__name(this,"_Migration612NormalizeRarities")}async updateActor(source){const traitsRaw=source.system.traits;if(source.type==="familiar"||!traitsRaw)return;const traitsAndOtherMiscellany=traitsRaw;"rarity"in traitsAndOtherMiscellany||(traitsAndOtherMiscellany.rarity={value:"common"});const rarities=["common","uncommon","rare","unique"];for(const rarity of rarities){const{traits}=traitsAndOtherMiscellany;if(traits?.value.includes(rarity)){const index=traits.value.indexOf(rarity);traits.value.splice(index,1),traitsAndOtherMiscellany.rarity={value:rarity}}}}};__name2(_Migration612NormalizeRarities,"Migration612NormalizeRarities"),__publicField(_Migration612NormalizeRarities,"version",.612);let Migration612NormalizeRarities=_Migration612NormalizeRarities;const _Migration613RemoveAmmoCharges=class extends MigrationBase{static{__name(this,"_Migration613RemoveAmmoCharges")}async updateItem(itemData){itemData.type==="consumable"&&itemData.system.consumableType.value==="ammo"&&(itemData.system.charges.value=0,itemData.system.charges.max=0)}};__name2(_Migration613RemoveAmmoCharges,"Migration613RemoveAmmoCharges"),__publicField(_Migration613RemoveAmmoCharges,"version",.613);let Migration613RemoveAmmoCharges=_Migration613RemoveAmmoCharges;const _Migration614NumifyMeleeBonuses=class extends MigrationBase{static{__name(this,"_Migration614NumifyMeleeBonuses")}async updateItem(itemData){itemData.type==="melee"&&(itemData.system.bonus={value:Number(itemData.system.bonus.value)})}};__name2(_Migration614NumifyMeleeBonuses,"Migration614NumifyMeleeBonuses"),__publicField(_Migration614NumifyMeleeBonuses,"version",.614);let Migration614NumifyMeleeBonuses=_Migration614NumifyMeleeBonuses;const _Migration615RemoveInstinctTrait=class extends MigrationBase{static{__name(this,"_Migration615RemoveInstinctTrait")}async updateItem(itemData){const traits=itemData.system.traits;traits&&(typeof traits.value=="string"?traits.value=[]:traits.value=traits.value?.filter(trait=>trait!=="instinct"))}};__name2(_Migration615RemoveInstinctTrait,"Migration615RemoveInstinctTrait"),__publicField(_Migration615RemoveInstinctTrait,"version",.615);let Migration615RemoveInstinctTrait=_Migration615RemoveInstinctTrait;const _Migration616MigrateFeatPrerequisites=class extends MigrationBase{static{__name(this,"_Migration616MigrateFeatPrerequisites")}async updateItem(source){if(source.type==="feat"){const update=[],prerequisites=source.system.prerequisites;if(prerequisites.value){if(typeof prerequisites.value=="string")update.push({value:prerequisites.value});else if(Array.isArray(prerequisites.value))for(const p of prerequisites.value)p&&update.push({value:isObject(p)&&typeof p.value=="string"?p.value:String(p)})}else if(Array.isArray(prerequisites))for(const p of prerequisites)p&&update.push({value:p?.value?p.value:p});source.system.prerequisites={value:update}}}};__name2(_Migration616MigrateFeatPrerequisites,"Migration616MigrateFeatPrerequisites"),__publicField(_Migration616MigrateFeatPrerequisites,"version",.616);let Migration616MigrateFeatPrerequisites=_Migration616MigrateFeatPrerequisites;const _Migration617FixUserFlags=class extends MigrationBase{static{__name(this,"_Migration617FixUserFlags")}async updateUser(source){const flags=source.flags,settings=flags.PF2e?.settings;if(isObject(settings)&&typeof settings.color=="string"){const uiTheme=settings.color??"blue",showRollDialogs=!settings.quickD20roll;flags.pf2e??={},flags.pf2e.settings={uiTheme,showEffectPanel:flags.pf2e?.showEffectPanel??!0,showRollDialogs},delete flags.PF2e,flags["-=PF2e"]=null}}};__name2(_Migration617FixUserFlags,"Migration617FixUserFlags"),__publicField(_Migration617FixUserFlags,"version",.617);let Migration617FixUserFlags=_Migration617FixUserFlags;const _Migration618MigrateItemImagePaths=class extends MigrationBase{static{__name(this,"_Migration618MigrateItemImagePaths")}constructor(){super(...arguments),__privateAdd(this,_IMAGE_PATHS,{"systems/pf2e/icons/equipment/weapons/blowgun.png":"systems/pf2e/icons/equipment/weapons/blowgun.jpg","systems/pf2e/icons/equipment/weapons/trident.png":"systems/pf2e/icons/equipment/weapons/trident.jpg","systems/pf2e/icons/equipment/weapons/longsword.png":"systems/pf2e/icons/equipment/weapons/longsword.jpg","systems/pf2e/icons/equipment/weapons/composite-longbow.png":"systems/pf2e/icons/equipment/weapons/composite-longbow.jpg","systems/pf2e/icons/equipment/weapons/composite-shortbow.png":"systems/pf2e/icons/equipment/weapons/composite-shortbow.jpg","systems/pf2e/icons/equipment/weapons/dagger.png":"systems/pf2e/icons/equipment/weapons/dagger.jpg","systems/pf2e/icons/equipment/weapons/katar.png":"systems/pf2e/icons/equipment/weapons/katar.jpg","systems/pf2e/icons/equipment/weapons/kukri.png":"systems/pf2e/icons/equipment/weapons/kukri.jpg","systems/pf2e/icons/equipment/weapons/shortbow.png":"systems/pf2e/icons/equipment/weapons/shortbow.jpg","systems/pf2e/icons/equipment/weapons/scimitar.png":"systems/pf2e/icons/equipment/weapons/scimitar.jpg","systems/pf2e/icons/equipment/weapons/hatchet.png":"systems/pf2e/icons/equipment/weapons/hatchet.jpg","systems/pf2e/icons/equipment/weapons/halfling-sling-staff.png":"systems/pf2e/icons/equipment/weapons/halfling-sling-staff.jpg","systems/pf2e/icons/equipment/weapons/halberd.png":"systems/pf2e/icons/equipment/weapons/halberd.jpg","systems/pf2e/icons/equipment/weapons/shield-spikes.png":"systems/pf2e/icons/equipment/weapons/shield-spikes.jpg","systems/pf2e/icons/equipment/weapons/light-mace.jpg":"systems/pf2e/icons/equipment/weapons/light-mace.jpg","systems/pf2e/icons/equipment/weapons/morningstar.png":"systems/pf2e/icons/equipment/weapons/morningstar.jpg","systems/pf2e/icons/equipment/weapons/sling.png":"systems/pf2e/icons/equipment/weapons/sling.jpg","systems/pf2e/icons/equipment/weapons/main-gauche.png":"systems/pf2e/icons/equipment/weapons/main-gauche.jpg","systems/pf2e/icons/equipment/weapons/bastard-sword.png":"systems/pf2e/icons/equipment/weapons/bastard-sword.jpg","systems/pf2e/icons/equipment/weapons/spear.png":"systems/pf2e/icons/equipment/weapons/spear.jpg","systems/pf2e/icons/equipment/weapons/staff.png":"systems/pf2e/icons/equipment/weapons/staff.jpg","systems/pf2e/icons/equipment/weapons/katana.png":"systems/pf2e/icons/equipment/weapons/katana.jpg","systems/pf2e/icons/equipment/weapons/elven-curve-blade.png":"systems/pf2e/icons/equipment/weapons/elven-curve-blade.jpg","systems/pf2e/icons/equipment/weapons/bo-staff.png":"systems/pf2e/icons/equipment/weapons/bo-staff.jpg","systems/pf2e/icons/equipment/weapons/clan-dagger.png":"systems/pf2e/icons/equipment/weapons/clan-dagger.jpg","systems/pf2e/icons/equipment/weapons/dogslicer.png":"systems/pf2e/icons/equipment/weapons/dogslicer.jpg","systems/pf2e/icons/equipment/weapons/falchion.png":"systems/pf2e/icons/equipment/weapons/falchion.jpg","systems/pf2e/icons/equipment/weapons/fist.png":"systems/pf2e/icons/equipment/weapons/fist.jpg","systems/pf2e/icons/equipment/weapons/gauntlet.png":"systems/pf2e/icons/equipment/weapons/gauntlet.jpg","systems/pf2e/icons/equipment/weapons/gnome-hooked-hammer.png":"systems/pf2e/icons/equipment/weapons/gnome-hooked-hammer.jpg","systems/pf2e/icons/equipment/weapons/greatpick.png":"systems/pf2e/icons/equipment/weapons/greatpick.jpg","systems/pf2e/icons/equipment/weapons/guisarme.png":"systems/pf2e/icons/equipment/weapons/guisarme.jpg","systems/pf2e/icons/equipment/weapons/horsechopper.png":"systems/pf2e/icons/equipment/weapons/horsechopper.jpg","systems/pf2e/icons/equipment/weapons/lance.png":"systems/pf2e/icons/equipment/weapons/lance.jpg","systems/pf2e/icons/equipment/weapons/maul.png":"systems/pf2e/icons/equipment/weapons/maul.jpg","systems/pf2e/icons/equipment/weapons/pick.png":"systems/pf2e/icons/equipment/weapons/pick.jpg","systems/pf2e/icons/equipment/weapons/ranseur.png":"systems/pf2e/icons/equipment/weapons/ranseur.jpg","systems/pf2e/icons/equipment/weapons/sai.png":"systems/pf2e/icons/equipment/weapons/sai.jpg","systems/pf2e/icons/equipment/weapons/sawtooth-saber.png":"systems/pf2e/icons/equipment/weapons/sawtooth-saber.jpg","systems/pf2e/icons/equipment/weapons/shield-bash.png":"systems/pf2e/icons/equipment/weapons/shield-bash.jpg","systems/pf2e/icons/equipment/weapons/shield-boss.png":"systems/pf2e/icons/equipment/weapons/shield-boss.jpg","systems/pf2e/icons/equipment/weapons/shuriken.png":"systems/pf2e/icons/equipment/weapons/shuriken.jpg","systems/pf2e/icons/equipment/weapons/spiked-gauntlet.png":"systems/pf2e/icons/equipment/weapons/spiked-gauntlet.jpg","systems/pf2e/icons/equipment/weapons/broom.png":"systems/pf2e/icons/equipment/held-items/broom-of-flying.jpg","systems/pf2e/icons/equipment/weapons/cutlass.png":"systems/pf2e/icons/equipment/weapons/scimitar.jpg","systems/pf2e/icons/equipment/weapons/scalpel.png":"systems/pf2e/icons/equipment/weapons/war-razor.jpg","systems/pf2e/icons/equipment/weapons/cane.png":"systems/pf2e/icons/equipment/weapons/cane.jpg"})}async updateItem(itemData){itemData.img=__privateGet(this,_IMAGE_PATHS)[itemData.img]??itemData.img}};_IMAGE_PATHS=new WeakMap,__name2(_Migration618MigrateItemImagePaths,"Migration618MigrateItemImagePaths"),__publicField(_Migration618MigrateItemImagePaths,"version",.618);let Migration618MigrateItemImagePaths=_Migration618MigrateItemImagePaths;const LEGIT_TRADITIONS=["arcane","divine","occult","primal","focus","ritual","halcyon",""];function makeLowercase(value){return value.toLowerCase()}__name(makeLowercase,"makeLowercase"),__name2(makeLowercase,"makeLowercase");const _Migration619TraditionLowercaseAndRemoveWandScroll=class extends MigrationBase{static{__name(this,"_Migration619TraditionLowercaseAndRemoveWandScroll")}async updateItem(item,actorData){if(!actorData||item.type!=="spellcastingEntry")return;const tradition=item.system.tradition;if(tradition.value=makeLowercase(tradition.value),tupleHasValue(LEGIT_TRADITIONS,item.system.tradition.value))return;const highestTradition=actorData.items.filter(itemData=>itemData.type==="spellcastingEntry").reduce((prev,current)=>{if(tupleHasValue(LEGIT_TRADITIONS,current.system.tradition.value)){const value=current.system.spelldc.value??0;if(value>prev.value)return{name:current.system.tradition.value,value}}return prev},{name:"arcane",value:0});tradition.value=highestTradition.name}};__name2(_Migration619TraditionLowercaseAndRemoveWandScroll,"Migration619TraditionLowercaseAndRemoveWandScroll"),__publicField(_Migration619TraditionLowercaseAndRemoveWandScroll,"version",.619);let Migration619TraditionLowercaseAndRemoveWandScroll=_Migration619TraditionLowercaseAndRemoveWandScroll;const _Migration620RenameToWebp=class extends MigrationBase{static{__name(this,"_Migration620RenameToWebp")}constructor(){super(...arguments),__privateAdd(this,_renameToWebP),__privateAdd(this,_isABCK),__privateAdd(this,_regexp,/(\/?systems\/pf2e\/[^"]+)\.(?:jpg|png)\b/)}async updateActor(source){source.img=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,source.img),typeof source.prototypeToken?.texture.src=="string"&&(source.prototypeToken.texture.src=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,source.prototypeToken.texture.src));for(const effect of source.effects??[])effect.icon=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,effect.icon);if(source.type==="character"){const details=source.system.details;details.deity&&(details.deity.image=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,details.deity.image))}}async updateItem(itemData){itemData.img=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,itemData.img);for(const effect of itemData.effects??[])effect.icon=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,effect.icon);if(__privateMethod(this,_isABCK,isABCK_fn).call(this,itemData)){const embedData=itemData.system.items,embeds=Object.values(embedData).filter(maybeEmbed=>!!maybeEmbed);for(const embed of embeds)if(embed.img=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,embed.img),"items"in embed&&embed.items){const deepEmbeds=Object.values(embed.items).filter(maybeDeepEmbed=>!!maybeDeepEmbed);for(const deepEmbed of deepEmbeds)deepEmbed.img=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,deepEmbed.img)}}}async updateMacro(macroData){macroData.img=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,macroData.img)}async updateTable(tableData){tableData.img=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,tableData.img);for(const result of tableData.results)result.img=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,result.img)}async updateToken(tokenData){tokenData.texture.src=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,tokenData.texture.src),tokenData.effects=tokenData.effects.filter(texture=>!__privateGet(this,_regexp).test(texture))}async updateUser(source){source.avatar=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,source.avatar)}};_regexp=new WeakMap,_renameToWebP=new WeakSet,renameToWebP_fn=__name2(function(imgPath){return typeof imgPath=="string"&&__privateGet(this,_regexp).test(imgPath)?imgPath.replace(__privateGet(this,_regexp),"$1.webp"):imgPath?.replace("icons/svg/mystery-man.svg","systems/pf2e/icons/default-icons/mystery-man.svg")},"#renameToWebP"),_isABCK=new WeakSet,isABCK_fn=__name2(function(itemData){return["ancestry","background","class","kit"].includes(itemData.type)},"#isABCK"),__name2(_Migration620RenameToWebp,"Migration620RenameToWebp"),__publicField(_Migration620RenameToWebp,"version",.62);let Migration620RenameToWebp=_Migration620RenameToWebp;const MAGIC_SCHOOLS=new Set(["abjuration","conjuration","divination","enchantment","evocation","illusion","necromancy","transmutation"]),MAGIC_TRADITIONS=new Set(["arcane","divine","occult","primal"]),_Migration621RemoveConfigSpellSchools=class extends MigrationBase{static{__name(this,"_Migration621RemoveConfigSpellSchools")}KEY_MAP={abj:"abjuration",con:"conjuration",div:"divination",enc:"enchantment",evo:"evocation",ill:"illusion",nec:"necromancy",trs:"transmutation"};reassignSchool(abbreviation){return objectHasKey(this.KEY_MAP,abbreviation)?this.KEY_MAP[abbreviation]:setHasElement(MAGIC_SCHOOLS,abbreviation)?abbreviation:this.KEY_MAP.evo}async updateItem(itemData){if(itemData.type==="spell"){const school=itemData.system.school??{value:"evocation"};school.value=this.reassignSchool(school.value)}}};__name2(_Migration621RemoveConfigSpellSchools,"Migration621RemoveConfigSpellSchools"),__publicField(_Migration621RemoveConfigSpellSchools,"version",.621);let Migration621RemoveConfigSpellSchools=_Migration621RemoveConfigSpellSchools;const _Migration623NumifyPotencyRunes=class extends MigrationBase{static{__name(this,"_Migration623NumifyPotencyRunes")}async updateItem(itemData){if(!(itemData.type==="weapon"||itemData.type==="armor"))return;const potencyRune=itemData.system.potencyRune;potencyRune?potencyRune.value=Number(itemData.system.potencyRune.value)||null:itemData.system.potencyRune={value:null}}};__name2(_Migration623NumifyPotencyRunes,"Migration623NumifyPotencyRunes"),__publicField(_Migration623NumifyPotencyRunes,"version",.623);let Migration623NumifyPotencyRunes=_Migration623NumifyPotencyRunes;const _Migration624RemoveTokenEffectIconFlags=class extends MigrationBase{static{__name(this,"_Migration624RemoveTokenEffectIconFlags")}async updateActor(actorData){const flags=actorData.flags;flags.pf2e?.token?.effects&&(delete flags.pf2e.token.effects,"game"in globalThis&&(flags.pf2e.token["-=effects"]=null))}async updateToken(tokenData){const flags=tokenData.delta?.flags??{};flags.pf2e?.token?.effects&&(delete flags.pf2e.token.effects,"game"in globalThis&&(flags.pf2e.token["-=effects"]=null))}};__name2(_Migration624RemoveTokenEffectIconFlags,"Migration624RemoveTokenEffectIconFlags"),__publicField(_Migration624RemoveTokenEffectIconFlags,"version",.624);let Migration624RemoveTokenEffectIconFlags=_Migration624RemoveTokenEffectIconFlags;const _Migration625EnsurePresenceOfSaves=class extends MigrationBase{static{__name(this,"_Migration625EnsurePresenceOfSaves")}async updateActor(actorData){if(actorData.type!=="npc")return;const saves=actorData.system.saves;for(const key of["fortitude","reflex","will"])saves[key]??={value:0,saveDetail:""},typeof saves[key].value!="number"&&(saves[key].value=Number(saves[key].value)||0),typeof saves[key].saveDetail!="string"&&(saves[key].saveDetail="")}};__name2(_Migration625EnsurePresenceOfSaves,"Migration625EnsurePresenceOfSaves"),__publicField(_Migration625EnsurePresenceOfSaves,"version",.625);let Migration625EnsurePresenceOfSaves=_Migration625EnsurePresenceOfSaves;const _Migration626UpdateSpellCategory=class extends MigrationBase{static{__name(this,"_Migration626UpdateSpellCategory")}async updateItem(source){if(source.type!=="spell")return;const systemData=source.system,traditions=systemData.traditions,isFocus=traditions.value.includes("focus"),isRitual=traditions.value.includes("ritual");if(typeof traditions.value=="string"&&(traditions.value=[]),systemData.spellCategorie||systemData.spellCategory){const currentCategory=systemData.spellCategorie?.value??systemData.spellCategory?.value??"";source.system.category={value:isFocus?"focus":isRitual?"ritual":currentCategory===""?"spell":currentCategory},delete systemData.spellCategorie,delete systemData.spellCategory,"game"in globalThis&&(systemData["-=spellCategorie"]=null,systemData["-=spellCategory"]=null)}["focus","ritual"].includes(source.system.spellType.value)&&(source.system.spellType.value="utility"),traditions.value=traditions.value.filter(tradition=>!["focus","ritual"].includes(tradition))}};__name2(_Migration626UpdateSpellCategory,"Migration626UpdateSpellCategory"),__publicField(_Migration626UpdateSpellCategory,"version",.626);let Migration626UpdateSpellCategory=_Migration626UpdateSpellCategory;const _Migration627LowerCaseSpellSaves=class extends MigrationBase{static{__name(this,"_Migration627LowerCaseSpellSaves")}async updateItem(itemData){if(itemData.type!=="spell")return;const saveType=itemData.system.save.value?.toLowerCase()??"";tupleHasValue(["fortitude","reflex","will"],saveType)?itemData.system.save.value=saveType:itemData.system.save.value=""}};__name2(_Migration627LowerCaseSpellSaves,"Migration627LowerCaseSpellSaves"),__publicField(_Migration627LowerCaseSpellSaves,"version",.627);let Migration627LowerCaseSpellSaves=_Migration627LowerCaseSpellSaves;const _Migration629SetBaseItems=class extends MigrationBase{static{__name(this,"_Migration629SetBaseItems")}constructor(){super(...arguments),__privateAdd(this,_BASE_ARMORS,["explorers-clothing","padded-armor","leather-armor","studded-leather-armor","chain-shirt","hide-armor","scale-mail","chain-mail","breastplate","splint-mail","half-plate","full-plate","hellknight-plate"]),__privateAdd(this,_MAGIC_ARMOR_TO_BASE,{"breastplate-of-command-greater":"breastplate","breastplate-of-command":"breastplate","celestial-armor":"chain-mail","demon-armor":"full-plate",dragonplate:"full-plate","electric-eelskin":"leather-armor","forgotten-shell":"full-plate","ghoul-hide":"hide-armor","glorious-plate":"full-plate","impenetrable-scale":"scale-mail","jerkin-of-liberation":"studded-leather-armor","mail-of-luck":"splint-mail","moonlit-chain":"chain-shirt","noxious-jerkin":"padded-armor","numerian-steel-breastplate":"breastplate","plate-armor-of-the-deep":"full-plate","rhino-hide":"hide-armor","spangled-riders-suit":"studded-leather-armor","victory-plate":"full-plate"}),__privateAdd(this,_BASE_WEAPONS,["adze","aklys","alchemical-bomb","alchemical-crossbow","aldori-dueling-sword","arrows","bastard-sword","battle-axe","battle-lute","bladed-diabolo","bladed-hoop","bladed-scarf","blowgun-darts","blowgun","bo-staff","boarding-axe","boarding-pike","bola","bolts","buugeng","clan-dagger","claw","claw-blade","club","combat-grapnel","composite-longbow","composite-shortbow","crossbow","dagger","daikyu","dart","dogslicer","dwarven-war-axe","elven-curve-blade","exquisite-sword-cane-sheath","exquisite-sword-cane","falchion","fangwire","fauchard","fighting-fan","filchers-fork","fire-poi","fist","flail","gaff","gauntlet","gill-hook","glaive","gnome-flickmace","gnome-hooked-hammer","greataxe","greatclub","greatpick","greatsword","guisarme","halberd","halfling-sling-staff","hand-adze","hand-crossbow","hatchet","heavy-crossbow","horsechopper","javelin","jaws","juggling-club","kama","katana","katar","khakkhara","khopesh","kukri","lance","light-hammer","light-mace","light-pick","longbow","longspear","longsword","mace","machete","main-gauche","mambele","maul","meteor-hammer","monkeys-fist","morningstar","naginata","nightstick","nine-ring-sword","nunchaku","ogre-hook","orc-knuckle-dagger","orc-necksplitter","pick","poi","polytool","ranseur","rapier","rhoka-sword","rungu","sai","sap","sawtooth-saber","scimitar","scorpion-whip","scourge","scythe","shears","shield-bash","shield-boss","shield-spikes","shortbow","shortsword","shuriken","sickle","sling-bullets","sling","spear","spiked-chain","spiked-gauntlet","staff","starknife","stiletto-pen","sword-cane","tamchal-chakram","taw-launcher","tekko-kagi","temple-sword","tengu-gale-blade","throwing-knife","thunder-sling","tricky-pick","trident","urumi","wakizashi","war-flail","war-razor","warhammer","whip-claw","whip","wish-blade","wish-knife","wooden-taws"])}async updateItem(itemData){if(!isPhysicalData(itemData))return;const systemData=itemData.system;!systemData.slug||itemData.type!=="armor"&&itemData.type!=="weapon"||(itemData.type==="armor"?((systemData.slug==="hide"||sluggify(itemData.name)==="hide")&&(systemData.slug="hide-armor"),__privateGet(this,_BASE_ARMORS).includes(systemData.slug??"")?systemData.baseItem=systemData.slug:systemData.slug in __privateGet(this,_MAGIC_ARMOR_TO_BASE)&&(systemData.baseItem=__privateGet(this,_MAGIC_ARMOR_TO_BASE)[systemData.slug])):itemData.type==="weapon"&&(__privateGet(this,_BASE_WEAPONS).includes(systemData.slug)&&(systemData.baseItem=systemData.slug),systemData.slug==="cinderclaw-gauntlet"&&(systemData.baseItem="spiked-gauntlet")))}};_BASE_ARMORS=new WeakMap,_MAGIC_ARMOR_TO_BASE=new WeakMap,_BASE_WEAPONS=new WeakMap,__name2(_Migration629SetBaseItems,"Migration629SetBaseItems"),__publicField(_Migration629SetBaseItems,"version",.629);let Migration629SetBaseItems=_Migration629SetBaseItems;const _Migration630FixTalismanSpelling=class extends MigrationBase{static{__name(this,"_Migration630FixTalismanSpelling")}async updateItem(itemData){if(itemData.type==="consumable"){const consumableType=itemData.system.consumableType;consumableType.value==="talasman"&&(consumableType.value="talisman")}}};__name2(_Migration630FixTalismanSpelling,"Migration630FixTalismanSpelling"),__publicField(_Migration630FixTalismanSpelling,"version",.63);let Migration630FixTalismanSpelling=_Migration630FixTalismanSpelling;const _Migration631FixSenseRuleElementSelector=class extends MigrationBase{static{__name(this,"_Migration631FixSenseRuleElementSelector")}SENSE_SELECTOR_CONVERSION={lowlightvision:"lowLightVision",Tremorsense:"tremorsense"};async updateItem(source){const rules=source.system.rules;for(const rule of rules)rule.key==="PF2E.RuleElement.Sense"&&typeof rule.selector=="string"&&(rule.selector=this.SENSE_SELECTOR_CONVERSION[rule.selector]??rule.selector)}};__name2(_Migration631FixSenseRuleElementSelector,"Migration631FixSenseRuleElementSelector"),__publicField(_Migration631FixSenseRuleElementSelector,"version",.631);let Migration631FixSenseRuleElementSelector=_Migration631FixSenseRuleElementSelector;const _Migration632DeleteOrphanedSpells=class extends MigrationBase{static{__name(this,"_Migration632DeleteOrphanedSpells")}requiresFlush=!0;async updateActor(actorData){const spells=actorData.items.filter(itemData=>itemData.type==="spell"),entries=actorData.items.filter(itemData=>itemData.type==="spellcastingEntry"),orphans=spells.filter(spellData=>!entries.some(entryData=>entryData._id===spellData.system.location.value));actorData.items=actorData.items.filter(itemData=>!orphans.some(orphan=>orphan._id===itemData._id))}};__name2(_Migration632DeleteOrphanedSpells,"Migration632DeleteOrphanedSpells"),__publicField(_Migration632DeleteOrphanedSpells,"version",.632);let Migration632DeleteOrphanedSpells=_Migration632DeleteOrphanedSpells;const _Migration633DeleteUnidentifiedTraits=class extends MigrationBase{static{__name(this,"_Migration633DeleteUnidentifiedTraits")}async updateItem(itemData){if(itemData.type==="melee"){const systemData=itemData.system;systemData.identification&&("game"in globalThis?itemData["system.-=identification"]=null:delete systemData.identification)}if(!isPhysicalData(itemData))return;const unidentifiedDataData=itemData.system.identification?.unidentified?.data;unidentifiedDataData?.traits&&("game"in globalThis?itemData["system.identification.unidentified.data.-=traits"]=null:delete unidentifiedDataData.traits)}};__name2(_Migration633DeleteUnidentifiedTraits,"Migration633DeleteUnidentifiedTraits"),__publicField(_Migration633DeleteUnidentifiedTraits,"version",.633);let Migration633DeleteUnidentifiedTraits=_Migration633DeleteUnidentifiedTraits;const _Migration634PurgeMartialItems=class extends MigrationBase{static{__name(this,"_Migration634PurgeMartialItems")}async updateActor(actorData){const martialIds=actorData.items.filter(itemData=>itemData.type==="martial").map(itemData=>itemData._id),martialItemWeapons=actorData.items.filter(itemData=>{if(itemData.type!=="weapon")return!1;const systemData=itemData.system;return martialIds.includes(systemData.weaponType?.value??"")});for(const weaponData of martialItemWeapons)weaponData.data.category="simple";actorData.items=actorData.items.filter(itemData=>itemData.type!=="martial")}};__name2(_Migration634PurgeMartialItems,"Migration634PurgeMartialItems"),__publicField(_Migration634PurgeMartialItems,"version",.634);let Migration634PurgeMartialItems=_Migration634PurgeMartialItems;const _Migration635NumifyACAndQuantity=class extends MigrationBase{static{__name(this,"_Migration635NumifyACAndQuantity")}async updateActor(actorData){(actorData.type==="hazard"||actorData.type==="npc"||actorData.type==="vehicle")&&(actorData.system.attributes.ac.value=Number(actorData.system.attributes.ac.value))}async updateItem(itemData){if(isPhysicalData(itemData)){const quantity=itemData.system.quantity||{value:0};quantity instanceof Object&&(quantity.value=Number(quantity.value))}}};__name2(_Migration635NumifyACAndQuantity,"Migration635NumifyACAndQuantity"),__publicField(_Migration635NumifyACAndQuantity,"version",.635);let Migration635NumifyACAndQuantity=_Migration635NumifyACAndQuantity;const _Migration636NumifyArmorData=class extends MigrationBase{static{__name(this,"_Migration636NumifyArmorData")}async updateItem(source){if(source.type!=="armor")return;const systemData=source.system;isObject(systemData.armor)&&(systemData.armor.value=Number(systemData.armor.value)||0),isObject(systemData.check)&&(systemData.check.value=Number(systemData.check.value)||0),isObject(systemData.dex)&&(systemData.dex.value=Number(systemData.dex.value)||0),isObject(systemData.strength)&&(systemData.strength.value=Number(systemData.strength.value)||0),isObject(systemData.speed)&&typeof systemData.speed.value=="string"&&(systemData.speed.value=parseInt(systemData.speed.value,10)||0)}};__name2(_Migration636NumifyArmorData,"Migration636NumifyArmorData"),__publicField(_Migration636NumifyArmorData,"version",.636);let Migration636NumifyArmorData=_Migration636NumifyArmorData;const meleeKeys=new Set(["description","source","traits","rules","slug","weaponType","attack","damageRolls","bonus","attackEffects"]),_Migration637CleanMeleeItems=class extends MigrationBase{static{__name(this,"_Migration637CleanMeleeItems")}async updateItem(itemData){if(itemData.type!=="melee")return;const systemData=itemData.system;for(const key of Object.keys(systemData))meleeKeys.has(key)||delete systemData[key]}};__name2(_Migration637CleanMeleeItems,"Migration637CleanMeleeItems");let Migration637CleanMeleeItems=_Migration637CleanMeleeItems;const validComponents=["material","somatic","verbal"],_Migration638SpellComponents=class extends MigrationBase{static{__name(this,"_Migration638SpellComponents")}async updateItem(itemData){if(itemData.type!=="spell")return;const components=itemData.system.components,oldComponents=new Set(components.value?.split(",").map(v=>v.trim().toLowerCase()));for(const component of validComponents)components[component]=components[component]||oldComponents.has(component);delete components.value,"game"in globalThis&&(components["-=value"]=null)}};__name2(_Migration638SpellComponents,"Migration638SpellComponents"),__publicField(_Migration638SpellComponents,"version",.638);let Migration638SpellComponents=_Migration638SpellComponents;const SIZES=["tiny","sm","med","lg","huge","grg"],SIZE_SLUGS=["tiny","small","medium","large","huge","gargantuan"],RARITIES=["common","uncommon","rare","unique"];function goesToEleven(value){return value>=0&&value<=11}__name(goesToEleven,"goesToEleven"),__name2(goesToEleven,"goesToEleven");const PROFICIENCY_RANKS=["untrained","trained","expert","master","legendary"],STACK_DEFINITIONS={bolts:{size:10,lightBulk:1},arrows:{size:10,lightBulk:1},slingBullets:{size:10,lightBulk:1},blowgunDarts:{size:10,lightBulk:1},woodenTaws:{size:10,lightBulk:1},rounds5:{size:5,lightBulk:1},rounds10:{size:10,lightBulk:1},rations:{size:7,lightBulk:1},sacks:{size:5,lightBulk:1},coins:{size:1e3,lightBulk:10},gems:{size:2e3,lightBulk:10}},_Bulk=class _Bulk2{static{__name(this,"_Bulk")}normal;light;constructor({normal=0,light=0}={}){this.normal=normal+Math.floor(light/10),this.light=light%10}get isNegligible(){return this.normal===0&&this.light===0}get isLight(){return this.toLightBulk()<10&&!this.isNegligible}toLightBulk(){return this.normal*10+this.light}plus(bulk){return new _Bulk2({normal:this.normal+bulk.normal,light:this.light+bulk.light})}minus(bulk){const[thisBulk,otherBulk]=this._toSingleNumber(bulk),result=thisBulk-otherBulk;return result<0?new _Bulk2:new _Bulk2({normal:Math.floor(result/10),light:result%10})}_toSingleNumber(bulk){return[this.normal*10+this.light,bulk.normal*10+bulk.light]}times(factor){const normal=this.normal*factor,lightCarryOver=normal<1&&normal>0?1:0,light=Math.floor(this.light*factor)+lightCarryOver;return new _Bulk2({normal:Math.floor(normal),light})}isSmallerThan(bulk){const[thisBulk,otherBulk]=this._toSingleNumber(bulk);return thisBulkotherBulk}isEqualTo(bulk){return this.normal===bulk.normal&&this.light===bulk.light}isPositive(){return this.normal>0||this.light>0}toString(){const{light,normal}=this;return normal===0&&light===0?game.i18n.localize("PF2E.Item.Physical.Bulk.Negligible"):normal>0&&light===0?normal.toString():light===1&&normal===0?game.i18n.localize("PF2E.Item.Physical.Bulk.Light"):light>0&&normal===0?game.i18n.format("PF2E.Item.Physical.Bulk.NLight",{light}):game.i18n.format("PF2E.Item.Physical.Bulk.WithLight",{bulk:normal,light})}double(){return this.isNegligible?new _Bulk2({light:1}):this.isLight?this.times(10):this.times(2)}halve(){return this.isNegligible?new _Bulk2:this.isLight?new _Bulk2:this.normal===1?new _Bulk2({light:1}):this.times(.5)}convertToSize(itemSize,actorSize){const sizes=Array.from(SIZES).filter(size=>size!=="sm"),itemSizeIndex=sizes.indexOf(itemSize==="sm"?"med":itemSize),actorSizeIndex=sizes.indexOf(actorSize==="sm"?"med":actorSize);return itemSizeIndex===actorSizeIndex?this:itemSizeIndex>actorSizeIndex?applyNTimes(bulk=>bulk.double(),itemSizeIndex-actorSizeIndex,this):applyNTimes(bulk=>bulk.halve(),actorSizeIndex-itemSizeIndex,this)}};__name2(_Bulk,"Bulk");let Bulk=_Bulk;const lightBulkRegex=/^(\d*)l$/i,complexBulkRegex=/^(\d+);\s*(\d*)l$/i;function weightToBulk(weight){if(typeof weight!="string"&&typeof weight!="number")return null;const trimmed=String(weight).trim();if(/^\d+$/.test(trimmed))return new Bulk({normal:parseInt(trimmed,10)});const lightMatch=trimmed.match(lightBulkRegex);if(lightMatch)return new Bulk({light:parseInt(lightMatch[1]||"1",10)});const complexMatch=trimmed.match(complexBulkRegex);if(complexMatch){const[,normal,light]=complexMatch;return new Bulk({normal:Number(normal)||0,light:Number(light||1)||0})}return null}__name(weightToBulk,"weightToBulk"),__name2(weightToBulk,"weightToBulk");const _CoinsPF2e=class _CoinsPF2e2{static{__name(this,"_CoinsPF2e")}constructor(data){data??={};for(const denomination of DENOMINATIONS)this[denomination]=Math.max(Math.floor(Math.abs(data[denomination]??0)),0)}get copperValue(){const{cp,sp,gp,pp}=this;return cp+sp*10+gp*100+pp*1e3}get goldValue(){return this.copperValue/100}add(coins){const other=new _CoinsPF2e2(coins);return new _CoinsPF2e2({pp:this.pp+other.pp,gp:this.gp+other.gp,sp:this.sp+other.sp,cp:this.cp+other.cp})}scale(factor){const result=new _CoinsPF2e2(this);if(result.pp*=factor,result.gp*=factor,result.sp*=factor,result.cp*=factor,factor%1!==0){result.gp+=result.pp%1*10,result.sp+=result.gp%1*10,result.cp+=result.sp%1*10;for(const denomination of DENOMINATIONS)result[denomination]=Math.floor(Number(result[denomination].toFixed(1)))}return result}adjustForSize(size){const basePrice=new _CoinsPF2e2(this);switch(size){case"lg":return basePrice.scale(2);case"huge":return basePrice.scale(4);case"grg":return basePrice.scale(8);default:return basePrice}}toObject(){return DENOMINATIONS.reduce((result,denomination)=>this[denomination]!==0?{...result,[denomination]:this[denomination]}:result,{})}static fromString(coinString,quantity=1){return[...String(coinString).trim().replace(/,/g,"").matchAll(/(\d+)\s*([pgsc]p)/g)].map(match=>{const[value,denomination]=match.slice(1,3),computedValue=(Number(value)||0)*quantity;return{[denomination]:computedValue}}).reduce((first,second)=>first.add(second),new _CoinsPF2e2)}static fromPrice(price,factor){const per=Math.max(1,price.per??1);return new _CoinsPF2e2(price.value).scale(factor/per)}toString(){if(DENOMINATIONS.every(denomination=>!this[denomination]))return"0 gp";const DENOMINATIONS_REVERSED=[...DENOMINATIONS].reverse(),parts=[];for(const denomation of DENOMINATIONS_REVERSED)this[denomation]&&parts.push(`${this[denomation]} ${denomation}`);return parts.join(", ")}};__name2(_CoinsPF2e,"CoinsPF2e");let CoinsPF2e=_CoinsPF2e;const coinCompendiumIds={pp:"JuNPeK5Qm1w6wpb4",gp:"B6B7tBWJSqOBz5zz",sp:"5Ew82vBF9YfaiY9f",cp:"lzJ8AVhRcbFul5fh"};function getMaterialValuationData(item){const valuationData=item.isOfType("weapon")?WEAPON_MATERIAL_VALUATION_DATA:item.isOfType("armor")&&!item.isShield?ARMOR_MATERIAL_VALUATION_DATA:null;if(!valuationData)return null;const{material}=item;return!material.type||!material.grade?null:valuationData[material.type]?.[material.grade]??null}__name(getMaterialValuationData,"getMaterialValuationData"),__name2(getMaterialValuationData,"getMaterialValuationData");const WEAPON_MATERIAL_VALUATION_DATA={"":{low:null,standard:null,high:null},abysium:{low:null,standard:{level:12,price:2e3,rarity:"rare"},high:{level:18,price:24e3,rarity:"rare"}},adamantine:{low:null,standard:{level:11,price:1400,rarity:"uncommon"},high:{level:17,price:13500,rarity:"uncommon"}},"cold-iron":{low:{level:2,price:40,rarity:"common"},standard:{level:10,price:880,rarity:"common"},high:{level:16,price:9e3,rarity:"common"}},darkwood:{low:null,standard:{level:11,price:1400,rarity:"uncommon"},high:{level:17,price:13500,rarity:"uncommon"}},djezet:{low:null,standard:{level:12,price:1800,rarity:"rare"},high:{level:18,price:22e3,rarity:"rare"}},inubrix:{low:null,standard:{level:11,price:1400,rarity:"rare"},high:{level:17,price:13500,rarity:"rare"}},"keep-stone":{low:null,standard:null,high:{level:18,price:22500,rarity:"rare"}},mithral:{low:null,standard:{level:11,price:1400,rarity:"uncommon"},high:{level:17,price:13500,rarity:"uncommon"}},noqual:{low:null,standard:{level:12,price:1600,rarity:"rare"},high:{level:18,price:24e3,rarity:"rare"}},peachwood:{low:null,standard:{level:12,price:2e3,rarity:"uncommon"},high:{level:18,price:19e3,rarity:"uncommon"}},orichalcum:{low:null,standard:null,high:{level:18,price:22500,rarity:"rare"}},siccatite:{low:null,standard:{level:11,price:1400,rarity:"rare"},high:{level:17,price:15e3,rarity:"rare"}},silver:{low:{level:2,price:40,rarity:"common"},standard:{level:10,price:880,rarity:"common"},high:{level:16,price:9e3,rarity:"common"}},"sisterstone-dusk":{low:{level:3,price:70,rarity:"rare"},standard:{level:11,price:1200,rarity:"rare"},high:{level:19,price:32e3,rarity:"rare"}},"sisterstone-scarlet":{low:{level:3,price:70,rarity:"rare"},standard:{level:11,price:1200,rarity:"rare"},high:{level:19,price:32e3,rarity:"rare"}},"sovereign-steel":{low:null,standard:{level:12,price:1600,rarity:"rare"},high:{level:19,price:32e3,rarity:"rare"}},warpglass:{low:null,standard:null,high:{level:17,price:14e3,rarity:"rare"}}},ARMOR_MATERIAL_VALUATION_DATA={"":{low:null,standard:null,high:null},abysium:{low:null,standard:{level:12,price:2e3,rarity:"rare"},high:{level:19,price:4e4,rarity:"rare"}},adamantine:{low:null,standard:{level:11,price:1600,rarity:"uncommon"},high:{level:19,price:32e3,rarity:"uncommon"}},"cold-iron":{low:{level:5,price:140,rarity:"common"},standard:{level:11,price:1200,rarity:"common"},high:{level:18,price:2e4,rarity:"common"}},darkwood:{low:null,standard:{level:12,price:1600,rarity:"uncommon"},high:{level:19,price:32e3,rarity:"uncommon"}},djezet:{low:null,standard:{level:12,price:1800,rarity:"rare"},high:{level:19,price:35e3,rarity:"rare"}},dragonhide:{low:null,standard:{level:12,price:1600,rarity:"uncommon"},high:{level:19,price:32e3,rarity:"uncommon"}},"grisantian-pelt":{low:null,standard:{level:12,price:1800,rarity:"rare"},high:{level:19,price:33e3,rarity:"rare"}},inubrix:{low:null,standard:{level:11,price:1200,rarity:"rare"},high:{level:18,price:18e3,rarity:"rare"}},"keep-stone":{low:null,standard:null,high:{level:20,price:56e3,rarity:"rare"}},mithral:{low:null,standard:{level:12,price:1600,rarity:"uncommon"},high:{level:19,price:32e3,rarity:"uncommon"}},noqual:{low:null,standard:{level:12,price:1600,rarity:"rare"},high:{level:19,price:32e3,rarity:"rare"}},peachwood:{low:null,standard:null,high:null},orichalcum:{low:null,standard:null,high:{level:20,price:55e3,rarity:"rare"}},siccatite:{low:null,standard:{level:12,price:1600,rarity:"rare"},high:{level:19,price:32e3,rarity:"rare"}},silver:{low:{level:5,price:140,rarity:"common"},standard:{level:11,price:1200,rarity:"common"},high:{level:18,price:2e4,rarity:"common"}},"sisterstone-dusk":{low:{level:5,price:140,rarity:"rare"},standard:{level:10,price:1e3,rarity:"rare"},high:{level:18,price:19500,rarity:"rare"}},"sisterstone-scarlet":{low:{level:5,price:140,rarity:"rare"},standard:{level:10,price:1e3,rarity:"rare"},high:{level:18,price:19500,rarity:"rare"}},"sovereign-steel":{low:null,standard:{level:13,price:2400,rarity:"rare"},high:{level:20,price:5e4,rarity:"rare"}},warpglass:{low:null,standard:null,high:null}},_PredicatePF2e=class _PredicatePF2e2 extends Array{static{__name(this,"_PredicatePF2e")}constructor(...statements){super(...Array.isArray(statements[0])?statements[0]:statements),__privateAdd(this,_isTrue),__privateAdd(this,_testBinaryOp),__privateAdd(this,_testCompound),__publicField(this,"isValid"),this.isValid=_PredicatePF2e2.isValid(this)}static isValid(statements){return this.isArray(statements)}static isArray(statements){return super.isArray(statements)&&statements.every(s=>StatementValidator.isStatement(s))}static test(predicate=[],options){return predicate instanceof _PredicatePF2e2?predicate.test(options):new _PredicatePF2e2(...predicate).test(options)}test(options){if(this.length===0)return!0;if(!this.isValid)return console.warn("PF2e System | The provided predicate set is malformed."),!1;const domain=options instanceof Set?options:new Set(options);return this.every(s=>__privateMethod(this,_isTrue,isTrue_fn).call(this,s,domain))}toObject(){return deepClone([...this])}clone(){return new _PredicatePF2e2(this.toObject())}};_isTrue=new WeakSet,isTrue_fn=__name2(function(statement,domain){return typeof statement=="string"&&domain.has(statement)||StatementValidator.isBinaryOp(statement)&&__privateMethod(this,_testBinaryOp,testBinaryOp_fn).call(this,statement,domain)||StatementValidator.isCompound(statement)&&__privateMethod(this,_testCompound,testCompound_fn).call(this,statement,domain)},"#isTrue"),_testBinaryOp=new WeakSet,testBinaryOp_fn=__name2(function(statement,domain){if("eq"in statement)return domain.has(`${statement.eq[0]}:${statement.eq[1]}`);{const operator=Object.keys(statement)[0],[left,right]=Object.values(statement)[0],domainArray=Array.from(domain),getValues=__name2(operand=>{const maybeNumber=Number(operand);if(!Number.isNaN(maybeNumber))return[maybeNumber];const pattern=new RegExp(String.raw`^${operand}:([^:]+)$`),values=domainArray.map(s=>Number(pattern.exec(s)?.[1]||NaN)).filter(v=>!Number.isNaN(v));return values.length>0?values:[NaN]},"getValues"),leftValues=getValues(left),rightValues=getValues(right);switch(operator){case"gt":return leftValues.some(l=>rightValues.every(r=>l>r));case"gte":return leftValues.some(l=>rightValues.every(r=>l>=r));case"lt":return leftValues.some(l=>rightValues.every(r=>lrightValues.every(r=>l<=r));default:return console.warn("PF2e System | Malformed binary operation encountered"),!1}}},"#testBinaryOp"),_testCompound=new WeakSet,testCompound_fn=__name2(function(statement,domain){return"and"in statement&&statement.and.every(subProp=>__privateMethod(this,_isTrue,isTrue_fn).call(this,subProp,domain))||"nand"in statement&&!statement.nand.every(subProp=>__privateMethod(this,_isTrue,isTrue_fn).call(this,subProp,domain))||"or"in statement&&statement.or.some(subProp=>__privateMethod(this,_isTrue,isTrue_fn).call(this,subProp,domain))||"xor"in statement&&statement.xor.filter(subProp=>__privateMethod(this,_isTrue,isTrue_fn).call(this,subProp,domain)).length===1||"nor"in statement&&!statement.nor.some(subProp=>__privateMethod(this,_isTrue,isTrue_fn).call(this,subProp,domain))||"not"in statement&&!__privateMethod(this,_isTrue,isTrue_fn).call(this,statement.not,domain)||"if"in statement&&!(__privateMethod(this,_isTrue,isTrue_fn).call(this,statement.if,domain)&&!__privateMethod(this,_isTrue,isTrue_fn).call(this,statement.then,domain))},"#testCompound"),__name2(_PredicatePF2e,"PredicatePF2e");let PredicatePF2e=_PredicatePF2e;const _StatementValidator=class{static{__name(this,"_StatementValidator")}static isStatement(statement){return statement instanceof Object?this.isCompound(statement)||this.isBinaryOp(statement):typeof statement=="string"?this.isAtomic(statement):!1}static isAtomic(statement){return typeof statement=="string"&&statement.length>0||this.isBinaryOp(statement)}static isBinaryOp(statement){if(!isObject(statement))return!1;const entries=Object.entries(statement);if(entries.length>1)return!1;const[operator,operands]=entries[0];return __privateGet(this,_binaryOperators).has(operator)&&Array.isArray(operands)&&operands.length===2&&typeof operands[0]=="string"&&["string","number"].includes(typeof operands[1])}static isCompound(statement){return isObject(statement)&&(this.isAnd(statement)||this.isOr(statement)||this.isNand(statement)||this.isXor(statement)||this.isNor(statement)||this.isNot(statement)||this.isIf(statement))}static isAnd(statement){return Object.keys(statement).length===1&&Array.isArray(statement.and)&&statement.and.every(subProp=>this.isStatement(subProp))}static isNand(statement){return Object.keys(statement).length===1&&Array.isArray(statement.nand)&&statement.nand.every(subProp=>this.isStatement(subProp))}static isOr(statement){return Object.keys(statement).length===1&&Array.isArray(statement.or)&&statement.or.every(subProp=>this.isStatement(subProp))}static isXor(statement){return Object.keys(statement).length===1&&Array.isArray(statement.xor)&&statement.xor.every(subProp=>this.isStatement(subProp))}static isNor(statement){return Object.keys(statement).length===1&&Array.isArray(statement.nor)&&statement.nor.every(subProp=>this.isStatement(subProp))}static isNot(statement){return Object.keys(statement).length===1&&!!statement.not&&this.isStatement(statement.not)}static isIf(statement){return Object.keys(statement).length===2&&this.isStatement(statement.if)&&this.isStatement(statement.then)}};_binaryOperators=new WeakMap,__name2(_StatementValidator,"StatementValidator"),__privateAdd(_StatementValidator,_binaryOperators,new Set(["eq","gt","gte","lt","lte"]));let StatementValidator=_StatementValidator;const _AutomaticBonusProgression=class{static{__name(this,"_AutomaticBonusProgression")}static isEnabled(actor){if(actor&&!actor.flags?.pf2e)return!1;const settingEnabled=game.settings.get("pf2e","automaticBonusVariant")!=="noABP",abpDisabledForActor=!!actor?.flags.pf2e.disableABP;return settingEnabled&&!abpDisabledForActor}static getStrikingDice(level){return level<4?0:level<12?1:level<19?2:3}static concatModifiers(actor){if(!this.isEnabled(actor))return;const{level,synthetics}=actor,values=this.abpValues(level),ac=values.ac,perception=values.perception,save=values.save,setting=game.settings.get("pf2e","automaticBonusVariant");if(save>0&&(synthetics.modifiers["saving-throw"]??=[]).push(()=>new ModifierPF2e({slug:"save-potency",label:"PF2E.AutomaticBonusProgression.savePotency",modifier:save,type:"potency"})),ac>0&&(synthetics.modifiers.ac??=[]).push(()=>new ModifierPF2e({slug:"defense-potency",label:"PF2E.AutomaticBonusProgression.defensePotency",modifier:ac,type:"potency"})),perception>0&&(synthetics.modifiers.perception??=[]).push(()=>new ModifierPF2e({slug:"perception-potency",label:"PF2E.AutomaticBonusProgression.perceptionPotency",modifier:perception,type:"potency"})),setting==="ABPRulesAsWritten"){const attack=this.abpValues(level).attack;attack>0&&(synthetics.modifiers["strike-attack-roll"]??=[]).push(()=>new ModifierPF2e({slug:"attack-potency",label:"PF2E.AutomaticBonusProgression.attackPotency",modifier:attack,type:"potency"}))}if(setting==="ABPFundamentalPotency"){const attack=this.abpValues(level).attack;if(attack>0){const potency={label:game.i18n.localize("PF2E.AutomaticBonusProgression.attackPotency"),type:"potency",bonus:attack,predicate:new PredicatePF2e};(synthetics.weaponPotency["strike-attack-roll"]??=[]).push(potency)}}}static cleanupRunes(item){if(!this.isEnabled(item.actor))return;item.system.potencyRune.value=null;const otherFundamental=item.isOfType("weapon")?item.system.strikingRune:item.system.resiliencyRune;if(otherFundamental.value=null,game.settings.get("pf2e","automaticBonusVariant")==="ABPRulesAsWritten"){const propertyRunes=[1,2,3,4].map(n=>item.system[`propertyRune${n}`]);for(const rune of propertyRunes)rune.value=null}}static suppressRuleElement(rule,value){return this.isEnabled(rule.actor)&&rule.type==="item"&&value>=0&&rule.fromEquipment}static getAttackPotency(level){return level<2?0:level<10?1:level<16?2:3}static abpValues(level){const attack=this.getAttackPotency(level);let ac,perception,save;return level>=5&&level<11?ac=1:level>=11&&level<18?ac=2:level>=18?ac=3:ac=0,level>=7&&level<13?perception=1:level>=13&&level<19?perception=2:level>=19?perception=3:perception=0,level>=8&&level<14?save=1:level>=14&&level<20?save=2:level>=20?save=3:save=0,{attack,ac,perception,save}}};__name2(_AutomaticBonusProgression,"AutomaticBonusProgression");let AutomaticBonusProgression=_AutomaticBonusProgression;function getPropertySlots(item){const fromMaterial=item.system.material.type==="orichalcum"?1:0,fromPotency=AutomaticBonusProgression.isEnabled(item.actor)?AutomaticBonusProgression.getAttackPotency(!item.actor||item.actor.isOfType("loot")?20:item.actor.level):item.system.runes.potency;return fromMaterial+fromPotency}__name(getPropertySlots,"getPropertySlots"),__name2(getPropertySlots,"getPropertySlots");function prunePropertyRunes(runes,validTypes){const runeSet=new Set(runes);return Array.from(runeSet).filter(r=>!!r&&r in validTypes&&!runeSet.has(`greater${r.titleCase()}`)&&!runeSet.has(`major${r.replace(/^greater/,"").titleCase()}`)&&!runeSet.has(`true${r.replace(/^greater|^major/,"").titleCase()}`))}__name(prunePropertyRunes,"prunePropertyRunes"),__name2(prunePropertyRunes,"prunePropertyRunes");function getRuneValuationData(item){if(!item.isOfType("armor","weapon")||item.isOfType("armor")&&item.isShield)return[];const itemRunes=item.system.runes,data=item.isOfType("armor")?{runes:RUNE_DATA.armor,secondaryFundamental:"resilient"}:{runes:RUNE_DATA.weapon,secondaryFundamental:"striking"};return[data.runes.potency[item.system.runes.potency],data.runes[data.secondaryFundamental][itemRunes[data.secondaryFundamental]??""],...item.system.runes.property.map(p=>data.runes.property[p])].filter(d=>!!d)}__name(getRuneValuationData,"getRuneValuationData"),__name2(getRuneValuationData,"getRuneValuationData");const strikingRuneValues=new Map([["striking",1],["greaterStriking",2],["majorStriking",3]]);function getStrikingDice(itemData){return strikingRuneValues.get(itemData.strikingRune.value)??0}__name(getStrikingDice,"getStrikingDice"),__name2(getStrikingDice,"getStrikingDice");const resilientRuneValues=new Map([[null,0],["resilient",1],["greaterResilient",2],["majorResilient",3]]);function getResilientBonus(itemData){return resilientRuneValues.get(itemData.resiliencyRune.value)??0}__name(getResilientBonus,"getResilientBonus"),__name2(getResilientBonus,"getResilientBonus");function getPropertyRuneDice(runes,options){return runes.flatMap(rune=>{const runeData=WEAPON_PROPERTY_RUNES[rune];return deepClone(runeData.damage?.dice??[]).map(data=>{const dice=new DamageDicePF2e({selector:"strike-damage",slug:rune,label:RUNE_DATA.weapon.property[rune]?.name,diceNumber:data.diceNumber??1,dieSize:data.dieSize??"d6",damageType:data.damageType,category:data.category??null,predicate:data.predicate,critical:data.critical??null});return dice.test(options),dice})})}__name(getPropertyRuneDice,"getPropertyRuneDice"),__name2(getPropertyRuneDice,"getPropertyRuneDice");function getPropertyRuneStrikeAdjustments(runes){return runes.flatMap(r=>RUNE_DATA.weapon.property[r].strikeAdjustments??[])}__name(getPropertyRuneStrikeAdjustments,"getPropertyRuneStrikeAdjustments"),__name2(getPropertyRuneStrikeAdjustments,"getPropertyRuneStrikeAdjustments");function getPropertyRuneModifierAdjustments(runes){return runes.flatMap(r=>RUNE_DATA.weapon.property[r].damage?.adjustments??[])}__name(getPropertyRuneModifierAdjustments,"getPropertyRuneModifierAdjustments"),__name2(getPropertyRuneModifierAdjustments,"getPropertyRuneModifierAdjustments");const FUNDAMENTAL_ARMOR_RUNE_DATA={potency:{0:null,1:{name:"PF2E.ArmorPotencyRune1",value:1,level:5,price:160,rarity:"common",traits:["abjuration"]},2:{name:"PF2E.ArmorPotencyRune2",value:2,level:11,price:1060,rarity:"common",traits:["abjuration"]},3:{name:"PF2E.ArmorPotencyRune3",value:3,level:18,price:20560,rarity:"common",traits:["abjuration"]},4:{name:"PF2E.ArmorPotencyRune4",value:4,level:18,price:20560,rarity:"common",traits:["abjuration"]}},resilient:{0:null,1:{name:"PF2E.ArmorResilientRune",level:8,price:340,rarity:"common",slug:"resilient",traits:["abjuration"]},2:{name:"PF2E.ArmorGreaterResilientRune",level:14,price:3440,rarity:"common",slug:"greaterResilient",traits:["abjuration"]},3:{name:"PF2E.ArmorMajorResilientRune",level:20,price:49440,rarity:"common",slug:"majorResilient",traits:["abjuration"]}}},FUNDAMENTAL_WEAPON_RUNE_DATA={potency:{0:null,1:{name:"PF2E.WeaponPotencyRune1",value:1,level:2,price:35,rarity:"common",traits:["evocation"]},2:{name:"PF2E.WeaponPotencyRune2",value:2,level:10,price:935,rarity:"common",traits:["evocation"]},3:{name:"PF2E.WeaponPotencyRune3",value:3,level:16,price:8935,rarity:"common",traits:["evocation"]},4:{name:"PF2E.WeaponPotencyRune4",value:4,level:16,price:8935,rarity:"common",traits:["evocation"]}},striking:{0:null,1:{name:"PF2E.Item.Weapon.Rune.Striking.Striking",level:4,price:65,rarity:"common",slug:"striking",traits:["evocation"]},2:{name:"PF2E.Item.Weapon.Rune.Striking.Greater",level:12,price:1065,rarity:"common",slug:"greaterStriking",traits:["evocation"]},3:{name:"PF2E.Item.Weapon.Rune.Striking.Major",level:19,price:31065,rarity:"common",slug:"majorStriking",traits:["evocation"]}}},ARMOR_PROPERTY_RUNES={acidResistant:{name:"PF2E.ArmorPropertyRuneAcidResistant",level:8,price:420,rarity:"common",slug:"acidResistant",traits:["abjuration","magical"]},advancing:{name:"PF2E.ArmorPropertyRuneAdvancing",level:9,price:625,rarity:"common",slug:"advancing",traits:["magical","necromancy"]},aimAiding:{name:"PF2E.ArmorPropertyRuneAimAiding",level:6,price:225,rarity:"common",slug:"aimAiding",traits:["magical","transmutation"]},antimagic:{name:"PF2E.ArmorPropertyRuneAntimagic",level:15,price:6500,rarity:"uncommon",slug:"antimagic",traits:["abjuration","magical"]},assisting:{name:"PF2E.ArmorPropertyRuneAssisting",level:5,price:125,rarity:"common",slug:"assisting",traits:["magical","transmutation"]},bitter:{name:"PF2E.ArmorPropertyRuneBitter",level:9,price:135,rarity:"uncommon",slug:"bitter",traits:["magical","poison","transmutation"]},coldResistant:{name:"PF2E.ArmorPropertyRuneColdResistant",level:8,price:420,rarity:"common",slug:"coldResistant",traits:["abjuration","magical"]},deathless:{name:"PF2E.ArmorPropertyRuneDeathless",level:7,price:330,rarity:"uncommon",slug:"deathless",traits:["healing","magical","necromancy"]},electricityResistant:{name:"PF2E.ArmorPropertyRuneElectricityResistant",level:8,price:420,rarity:"common",slug:"electricityResistant",traits:["abjuration","magical"]},energyAdaptive:{name:"PF2E.ArmorPropertyRuneEnergyAdaptive",level:6,price:225,rarity:"common",slug:"energyAdaptive",traits:["magical","transmutation"]},ethereal:{name:"PF2E.ArmorPropertyRuneEthereal",level:17,price:13500,rarity:"common",slug:"ethereal",traits:["conjuration","magical"]},fireResistant:{name:"PF2E.ArmorPropertyRuneFireResistant",level:8,price:420,rarity:"common",slug:"fireResistant",traits:["abjuration","magical"]},fortification:{name:"PF2E.ArmorPropertyRuneFortification",level:12,price:2e3,rarity:"common",slug:"fortification",traits:["abjuration","magical"]},glamered:{name:"PF2E.ArmorPropertyRuneGlamered",level:5,price:140,rarity:"common",slug:"glamered",traits:["illusion","magical"]},gliding:{name:"PF2E.ArmorPropertyRuneGliding",level:8,price:450,rarity:"common",slug:"gliding",traits:["magical","transmutation"]},greaterAcidResistant:{name:"PF2E.ArmorPropertyRuneGreaterAcidResistant",level:12,price:1650,rarity:"common",slug:"greaterAcidResistant",traits:["abjuration","magical"]},greaterAdvancing:{name:"PF2E.ArmorPropertyRuneGreaterAdvancing",level:16,price:8e3,rarity:"common",slug:"greaterAdvancing",traits:["magical","necromancy"]},greaterColdResistant:{name:"PF2E.ArmorPropertyRuneGreaterColdResistant",level:12,price:1650,rarity:"common",slug:"greaterColdResistant",traits:["abjuration","magical"]},greaterDread:{name:"PF2E.ArmorPropertyRuneGreaterDread",level:18,price:21e3,rarity:"uncommon",slug:"greaterDread",traits:["emotion","enchantment","fear","magical","mental","visual"]},greaterElectricityResistant:{name:"PF2E.ArmorPropertyRuneGreaterElectricityResistant",level:12,price:1650,rarity:"common",slug:"greaterElectricityResistant",traits:["abjuration","magical"]},greaterFireResistant:{name:"PF2E.ArmorPropertyRuneGreaterFireResistant",level:12,price:1650,rarity:"common",slug:"greaterFireResistant",traits:["abjuration","magical"]},greaterFortification:{name:"PF2E.ArmorPropertyRuneGreaterFortification",level:19,price:24e3,rarity:"common",slug:"greaterFortification",traits:["abjuration","magical"]},greaterInvisibility:{name:"PF2E.ArmorPropertyRuneGreaterInvisibility",level:10,price:1e3,rarity:"common",slug:"greaterInvisibility",traits:["illusion","magical"]},greaterReady:{name:"PF2E.ArmorPropertyRuneGreaterReady",level:11,price:1200,rarity:"common",slug:"greaterReady",traits:["evocation","magical"]},greaterShadow:{name:"PF2E.ArmorPropertyRuneGreaterShadow",level:9,price:650,rarity:"common",slug:"greaterShadow",traits:["magical","transmutation"]},greaterSlick:{name:"PF2E.ArmorPropertyRuneGreaterSlick",level:8,price:450,rarity:"common",slug:"greaterSlick",traits:["magical","transmutation"]},greaterStanching:{name:"PF2E.ArmorPropertyRuneGreaterStanching",level:9,price:600,rarity:"uncommon",slug:"greaterStanching",traits:["magical","necromancy"]},greaterQuenching:{name:"PF2E.ArmorPropertyRuneGreaterQuenching",level:10,price:1e3,rarity:"common",slug:"greaterQuenching",traits:["abjuration","magical"]},greaterSwallowSpike:{name:"PF2E.ArmorPropertyRuneGreaterSwallowSpike",level:12,price:1750,rarity:"common",slug:"greaterSwallowSpike",traits:["magical","transmutation"]},greaterWinged:{name:"PF2E.ArmorPropertyRuneGreaterWinged",level:19,price:35e3,rarity:"common",slug:"greaterWinged",traits:["magical","transmutation"]},immovable:{name:"PF2E.ArmorPropertyRuneImmovable",level:12,price:1800,rarity:"uncommon",slug:"immovable",traits:["magical","transmutation"]},implacable:{name:"PF2E.ArmorPropertyRuneImplacable",level:11,price:1200,rarity:"uncommon",slug:"implacable",traits:["magical","transmutation"]},invisibility:{name:"PF2E.ArmorPropertyRuneInvisibility",level:8,price:500,rarity:"common",slug:"invisibility",traits:["illusion","magical"]},lesserDread:{name:"PF2E.ArmorPropertyRuneLesserDread",level:6,price:225,rarity:"uncommon",slug:"lesserDread",traits:["emotion","enchantment","fear","magical","mental","visual"]},magnetizing:{name:"PF2E.ArmorPropertyRuneMagnetizing",level:10,price:900,rarity:"common",slug:"magnetizing",traits:["evocation","magical"]},majorQuenching:{name:"PF2E.ArmorPropertyRuneMajorQuenching",level:14,price:4500,rarity:"common",slug:"majorQuenching",traits:["abjuration","magical"]},majorShadow:{name:"PF2E.ArmorPropertyRuneMajorShadow",level:17,price:14e3,rarity:"common",slug:"majorShadow",traits:["magical","transmutation"]},majorSlick:{name:"PF2E.ArmorPropertyRuneMajorSlick",level:16,price:9e3,rarity:"common",slug:"majorSlick",traits:["magical","transmutation"]},majorStanching:{name:"PF2E.ArmorPropertyRuneMajorStanching",level:13,price:2500,rarity:"uncommon",slug:"majorStanching",traits:["magical","necromancy"]},majorSwallowSpike:{name:"PF2E.ArmorPropertyRuneMajorSwallowSpike",level:16,price:19250,rarity:"common",slug:"majorSwallowSpike",traits:["magical","transmutation"]},malleable:{name:"PF2E.ArmorPropertyRuneMalleable",level:9,price:650,rarity:"common",slug:"malleable",traits:["magical","metal"]},misleading:{name:"PF2E.ArmorPropertyRuneMisleading",level:16,price:8e3,rarity:"common",slug:"misleading",traits:["illusion","magical"]},moderateDread:{name:"PF2E.ArmorPropertyRuneModerateDread",level:12,price:1800,rarity:"uncommon",slug:"moderateDread",traits:["emotion","enchantment","fear","magical","mental","visual"]},portable:{name:"PF2E.ArmorPropertyRunePortable",level:9,price:660,rarity:"common",slug:"portable",traits:["magical","transmutation"]},quenching:{name:"PF2E.ArmorPropertyRuneQuenching",level:6,price:250,rarity:"common",slug:"quenching",traits:["abjuration","magical"]},ready:{name:"PF2E.ArmorPropertyRuneReady",level:6,price:200,rarity:"common",slug:"ready",traits:["evocation","magical"]},rockBraced:{name:"PF2E.ArmorPropertyRuneRockBraced",level:13,price:3e3,rarity:"rare",slug:"rockBraced",traits:["abjuration","dwarf","magical","saggorak"]},shadow:{name:"PF2E.ArmorPropertyRuneShadow",level:5,price:55,rarity:"common",slug:"shadow",traits:["magical","transmutation"]},sinisterKnight:{name:"PF2E.ArmorPropertyRuneSinisterKnight",level:8,price:500,rarity:"uncommon",slug:"sinisterKnight",traits:["abjuration","illusion","magical"]},slick:{name:"PF2E.ArmorPropertyRuneSlick",level:5,price:45,rarity:"common",slug:"slick",traits:["magical","transmutation"]},soaring:{name:"PF2E.ArmorPropertyRuneSoaring",level:14,price:3750,rarity:"common",slug:"soaring",traits:["abjuration","magical"]},stanching:{name:"PF2E.ArmorPropertyRuneStanching",level:5,price:130,rarity:"uncommon",slug:"stanching",traits:["magical","necromancy"]},swallowSpike:{name:"PF2E.ArmorPropertyRuneSwallowSpike",level:6,price:200,rarity:"common",slug:"swallowSpike",traits:["magical","transmutation"]},trueQuenching:{name:"PF2E.ArmorPropertyRuneTrueQuenching",level:18,price:24e3,rarity:"common",slug:"trueQuenching",traits:["abjuration","magical"]},trueStanching:{name:"PF2E.ArmorPropertyRuneTrueStanching",level:17,price:12500,rarity:"uncommon",slug:"trueStanching",traits:["magical","necromancy"]},winged:{name:"PF2E.ArmorPropertyRuneWinged",level:13,price:2500,rarity:"common",slug:"winged",traits:["magical","transmutation"]}},WEAPON_PROPERTY_RUNES={anarchic:{damage:{dice:[{damageType:"chaotic",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.anarchic.Name",text:"PF2E.WeaponPropertyRune.anarchic.Note.criticalSuccess"}]},level:11,name:"PF2E.WeaponPropertyRune.anarchic.Name",price:1400,rarity:"common",slug:"anarchic",traits:["chaotic","evocation","magical"]},ancestralEchoing:{level:15,name:"PF2E.WeaponPropertyRune.ancestralEchoing.Name",price:9500,rarity:"rare",slug:"ancestralEchoing",traits:["dwarf","evocation","magical","saggorak"]},anchoring:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.anchoring.Name",text:"PF2E.WeaponPropertyRune.anchoring.Note.criticalSuccess"}]},level:10,name:"PF2E.WeaponPropertyRune.anchoring.Name",price:900,rarity:"uncommon",slug:"anchoring",traits:["abjuration","magical"]},ashen:{damage:{dice:[{damageType:"fire",category:"persistent",diceNumber:1,dieSize:"d4"}],notes:[{outcome:["success"],title:"PF2E.WeaponPropertyRune.ashen.Name",text:"PF2E.WeaponPropertyRune.ashen.Note.success"}]},level:9,name:"PF2E.WeaponPropertyRune.ashen.Name",price:700,rarity:"common",slug:"ashen",traits:["enchantment","magical"]},authorized:{level:3,name:"PF2E.WeaponPropertyRune.authorized.Name",price:50,rarity:"common",slug:"authorized",traits:["abjuration","magical"]},axiomatic:{damage:{dice:[{damageType:"lawful",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.axiomatic.Name",text:"PF2E.WeaponPropertyRune.axiomatic.Note.criticalSuccess"}]},level:11,name:"PF2E.WeaponPropertyRune.axiomatic.Name",price:1400,rarity:"common",slug:"axiomatic",traits:["evocation","lawful","magical"]},bane:{level:4,name:"PF2E.WeaponPropertyRune.bane.Name",price:100,rarity:"uncommon",slug:"bane",traits:["divination","magical"]},bloodbane:{level:8,name:"PF2E.WeaponPropertyRune.bloodbane.Name",price:475,rarity:"uncommon",slug:"bloodbane",traits:["dwarf","evocation","magical"]},bloodthirsty:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.bloodbane.Name",text:"PF2E.WeaponPropertyRune.bloodthirsty.Note.criticalSuccess"}]},level:16,name:"PF2E.WeaponPropertyRune.bloodthirsty.Name",price:8500,rarity:"uncommon",slug:"bloodthirsty",traits:["magical","necromancy"]},brilliant:{damage:{dice:[{damageType:"fire",diceNumber:1,dieSize:"d4"},{damageType:"good",diceNumber:1,dieSize:"d4",predicate:[{or:["target:trait:fiend",{not:"target"}]}]},{damageType:"vitality",diceNumber:1,dieSize:"d4"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.brilliant.Name",text:"PF2E.WeaponPropertyRune.brilliant.Note.criticalSuccess"}]},level:12,name:"PF2E.WeaponPropertyRune.brilliant.Name",price:2e3,rarity:"common",slug:"brilliant",traits:["evocation","magical"]},called:{level:7,name:"PF2E.WeaponPropertyRune.called.Name",price:350,rarity:"common",slug:"called",traits:["conjuration","magical"]},coating:{level:9,name:"PF2E.WeaponPropertyRune.coating.Name",price:700,rarity:"common",slug:"coating",traits:["conjuration","extradimensional","magical"]},conducting:{level:7,name:"PF2E.WeaponPropertyRune.conducting.Name",price:300,rarity:"common",slug:"conducting",traits:["evocation","magical"]},corrosive:{damage:{dice:[{damageType:"acid",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.corrosive.Name",text:"PF2E.WeaponPropertyRune.corrosive.Note.criticalSuccess"}]},level:8,name:"PF2E.WeaponPropertyRune.corrosive.Name",price:500,rarity:"common",slug:"corrosive",traits:["acid","conjuration","magical"]},crushing:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.crushing.Name",text:"PF2E.WeaponPropertyRune.crushing.Note.criticalSuccess"}]},level:3,name:"PF2E.WeaponPropertyRune.crushing.Name",price:50,rarity:"uncommon",slug:"crushing",traits:["magical","necromancy"]},cunning:{level:5,name:"PF2E.WeaponPropertyRune.cunning.Name",price:140,rarity:"common",slug:"cunning",traits:["divination","magical"]},dancing:{level:13,name:"PF2E.WeaponPropertyRune.dancing.Name",price:2700,rarity:"uncommon",slug:"dancing",traits:["evocation","magical"]},deathdrinking:{damage:{dice:[{slug:"deathdrinking-negative",damageType:"void",diceNumber:1,dieSize:"d6",critical:!0,predicate:["target:mode:living",{not:"target:negative-healing"}]},{slug:"deathdrinking-positive",damageType:"vitality",diceNumber:1,dieSize:"d6",critical:!0,predicate:["target:negative-healing"]}]},level:7,name:"PF2E.WeaponPropertyRune.deathdrinking.Name",price:360,rarity:"rare",slug:"deathdrinking",traits:["magical","necromancy"]},demolishing:{damage:{dice:[{damageType:"force",category:"persistent",diceNumber:1,dieSize:"d6",predicate:["target:trait:construct"]}]},level:6,name:"PF2E.WeaponPropertyRune.demolishing.Name",price:225,rarity:"rare",slug:"demolishing",traits:["evocation","magical"]},disrupting:{damage:{dice:[{damageType:"vitality",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.disrupting.Name",text:"PF2E.WeaponPropertyRune.disrupting.Note.criticalSuccess"}]},level:5,name:"PF2E.WeaponPropertyRune.disrupting.Name",price:150,rarity:"common",slug:"disrupting",traits:["magical","necromancy"]},earthbinding:{level:5,name:"PF2E.WeaponPropertyRune.earthbinding.Name",price:125,rarity:"common",slug:"earthbinding",traits:["magical","transmutation"]},energizing:{level:6,name:"PF2E.WeaponPropertyRune.energizing.Name",price:250,rarity:"uncommon",slug:"energizing",traits:["abjuration","magical"]},extending:{level:7,name:"PF2E.WeaponPropertyRune.extending.Name",price:700,rarity:"common",slug:"extending",traits:["magical","transmutation"]},fanged:{level:2,name:"PF2E.WeaponPropertyRune.fanged.Name",price:30,rarity:"uncommon",slug:"fanged",traits:["magical","transmutation"]},fearsome:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.fearsome.Name",text:"PF2E.WeaponPropertyRune.fearsome.Note.criticalSuccess"}]},level:5,name:"PF2E.WeaponPropertyRune.fearsome.Name",price:160,rarity:"common",slug:"fearsome",traits:["emotion","enchantment","fear","magical","mental"]},flaming:{damage:{dice:[{damageType:"fire",diceNumber:1,dieSize:"d6"},{damageType:"fire",category:"persistent",diceNumber:1,dieSize:"d10",critical:!0}]},level:8,name:"PF2E.WeaponPropertyRune.flaming.Name",price:500,rarity:"common",slug:"flaming",traits:["conjuration","fire","magical"]},flurrying:{level:7,name:"PF2E.WeaponPropertyRune.flurrying.Name",price:360,rarity:"common",slug:"flurrying",traits:["evocation","magical"]},frost:{damage:{dice:[{damageType:"cold",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.frost.Name",text:"PF2E.WeaponPropertyRune.frost.Note.criticalSuccess"}]},level:8,name:"PF2E.WeaponPropertyRune.frost.Name",price:500,rarity:"common",slug:"frost",traits:["cold","conjuration","magical"]},ghostTouch:{damage:{notes:[{predicate:[{or:["target:trait:incorporeal",{not:"target"}]}],title:"PF2E.WeaponPropertyRune.ghostTouch.Name",text:"PF2E.WeaponPropertyRune.ghostTouch.Note"}]},level:4,name:"PF2E.WeaponPropertyRune.ghostTouch.Name",price:75,rarity:"common",slug:"ghostTouch",traits:["magical","transmutation"]},giantKilling:{damage:{dice:[{slug:"giantKilling",damageType:"mental",diceNumber:1,dieSize:"d6",predicate:["target:trait:giant"]}],notes:[{outcome:["criticalSuccess"],predicate:["target:trait:giant"],title:"PF2E.WeaponPropertyRune.giantKilling.Name",text:"PF2E.WeaponPropertyRune.giantKilling.Note.criticalSuccess"}]},level:8,name:"PF2E.WeaponPropertyRune.giantKilling.Name",price:450,rarity:"rare",slug:"giantKilling",traits:["magical","necromancy"]},greaterAnchoring:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterAnchoring.Name",text:"PF2E.WeaponPropertyRune.greaterAnchoring.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterAnchoring.Name",text:"PF2E.WeaponPropertyRune.greaterAnchoring.Note.success"}]},level:18,name:"PF2E.WeaponPropertyRune.greaterAnchoring.Name",price:22e3,rarity:"uncommon",slug:"greaterAnchoring",traits:["abjuration","magical"]},greaterAshen:{damage:{dice:[{damageType:"fire",category:"persistent",diceNumber:1,dieSize:"d8"}],notes:[{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterAshen.Name",text:"PF2E.WeaponPropertyRune.greaterAshen.Note.success"}]},level:16,name:"PF2E.WeaponPropertyRune.greaterAshen.Name",price:9e3,rarity:"common",slug:"greaterAshen",traits:["enchantment","magical"]},greaterBloodbane:{level:13,name:"PF2E.WeaponPropertyRune.greaterBloodbane.Name",price:2800,rarity:"uncommon",slug:"greaterBloodbane",traits:["dwarf","evocation","magical"]},greaterBrilliant:{damage:{dice:[{damageType:"fire",diceNumber:1,dieSize:"d4"},{damageType:"good",diceNumber:1,dieSize:"d4",predicate:[{or:["target:trait:fiend",{not:"target"}]}]},{damageType:"vitality",diceNumber:1,dieSize:"d4"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterBrilliant.Name",text:"PF2E.WeaponPropertyRune.greaterBrilliant.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterBrilliant.Name",text:"PF2E.WeaponPropertyRune.greaterBrilliant.Note.success"}],ignoredResistances:[{type:"fire",max:null},{type:"good",max:null},{type:"vitality",max:null}]},level:18,name:"PF2E.WeaponPropertyRune.greaterBrilliant.Name",price:24e3,rarity:"common",slug:"greaterBrilliant",traits:["evocation","magical"]},greaterCorrosive:{damage:{dice:[{damageType:"acid",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterCorrosive.Name",text:"PF2E.WeaponPropertyRune.greaterCorrosive.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterCorrosive.Name",text:"PF2E.WeaponPropertyRune.greaterCorrosive.Note.success"}]},level:15,name:"PF2E.WeaponPropertyRune.greaterCorrosive.Name",price:6500,rarity:"common",slug:"greaterCorrosive",traits:["acid","conjuration","magical"]},greaterCrushing:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterCrushing.Name",text:"PF2E.WeaponPropertyRune.greaterCrushing.Note.criticalSuccess"}]},level:9,name:"PF2E.WeaponPropertyRune.greaterCrushing.Name",price:650,rarity:"uncommon",slug:"greaterCrushing",traits:["magical","necromancy"]},greaterDisrupting:{damage:{dice:[{damageType:"vitality",diceNumber:2,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterDisrupting.Name",text:"PF2E.WeaponPropertyRune.greaterDisrupting.Note.criticalSuccess"}]},level:14,name:"PF2E.WeaponPropertyRune.greaterDisrupting.Name",price:4300,rarity:"uncommon",slug:"greaterDisrupting",traits:["magical","necromancy"]},greaterExtending:{level:13,name:"PF2E.WeaponPropertyRune.greaterExtending.Name",price:3e3,rarity:"common",slug:"greaterExtending",traits:["magical","transmutation"]},greaterFanged:{level:8,name:"PF2E.WeaponPropertyRune.greaterFanged.Name",price:425,rarity:"uncommon",slug:"greaterFanged",traits:["magical","transmutation"]},greaterFearsome:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterFearsome.Name",text:"PF2E.WeaponPropertyRune.greaterFearsome.Note.criticalSuccess"}]},level:12,name:"PF2E.WeaponPropertyRune.greaterFearsome.Name",price:2e3,rarity:"common",slug:"greaterFearsome",traits:["emotion","enchantment","fear","magical","mental"]},greaterFlaming:{damage:{dice:[{damageType:"fire",diceNumber:1,dieSize:"d6"},{damageType:"fire",category:"persistent",diceNumber:2,dieSize:"d10",critical:!0}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterFlaming.Name",text:"PF2E.WeaponPropertyRune.greaterFlaming.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterFlaming.Name",text:"PF2E.WeaponPropertyRune.greaterFlaming.Note.success"}],ignoredResistances:[{type:"fire",max:null}]},level:15,name:"PF2E.WeaponPropertyRune.greaterFlaming.Name",price:6500,rarity:"common",slug:"greaterFlaming",traits:["conjuration","fire","magical"]},greaterFrost:{damage:{dice:[{damageType:"cold",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterFrost.Name",text:"PF2E.WeaponPropertyRune.greaterFrost.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterFrost.Name",text:"PF2E.WeaponPropertyRune.greaterFrost.Note.success"}],ignoredResistances:[{type:"cold",max:null}]},level:15,name:"PF2E.WeaponPropertyRune.greaterFrost.Name",price:6500,rarity:"common",slug:"greaterFrost",traits:["cold","conjuration","magical"]},greaterGiantKilling:{damage:{dice:[{slug:"greaterGiantKilling",damageType:"mental",diceNumber:2,dieSize:"d6",predicate:["target:trait:giant"]}],ignoredResistances:[{type:"mental",max:null}],notes:[{outcome:["criticalSuccess"],predicate:["target:trait:giant"],title:"PF2E.WeaponPropertyRune.greaterGiantKilling.Name",text:"PF2E.WeaponPropertyRune.greaterGiantKilling.Note.criticalSuccess"}]},level:15,name:"PF2E.WeaponPropertyRune.greaterGiantKilling.Name",price:6e3,rarity:"rare",slug:"greaterGiantKilling",traits:["magical","necromancy"]},greaterHauling:{level:11,name:"PF2E.WeaponPropertyRune.greaterHauling.Name",price:1300,rarity:"uncommon",slug:"greaterHauling",traits:["evocation","magical"]},greaterImpactful:{damage:{dice:[{damageType:"force",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterImpactful.Name",text:"PF2E.WeaponPropertyRune.greaterImpactful.Note.criticalSuccess"}]},level:17,name:"PF2E.WeaponPropertyRune.greaterImpactful.Name",price:15e3,rarity:"common",slug:"greaterImpactful",traits:["evocation","force","magical"]},greaterRooting:{level:11,name:"PF2E.WeaponPropertyRune.greaterRooting.Name",price:1400,rarity:"common",slug:"greaterRooting",traits:["plant","magical","wood"],damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterRooting.Name",text:"PF2E.WeaponPropertyRune.greaterRooting.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterRooting.Name",text:"PF2E.WeaponPropertyRune.greaterRooting.Note.success"}]}},greaterShock:{damage:{dice:[{damageType:"electricity",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterShock.Name",text:"PF2E.WeaponPropertyRune.greaterShock.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterShock.Name",text:"PF2E.WeaponPropertyRune.greaterShock.Note.success"}],ignoredResistances:[{type:"electricity",max:null}]},level:15,name:"PF2E.WeaponPropertyRune.greaterShock.Name",price:6500,rarity:"common",slug:"greaterShock",traits:["electricity","evocation","magical"]},greaterThundering:{damage:{dice:[{damageType:"sonic",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterThundering.Name",text:"PF2E.WeaponPropertyRune.greaterThundering.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterThundering.Name",text:"PF2E.WeaponPropertyRune.greaterThundering.Note.success"}],ignoredResistances:[{type:"sonic",max:null}]},level:15,name:"PF2E.WeaponPropertyRune.greaterThundering.Name",price:6500,rarity:"common",slug:"greaterThundering",traits:["evocation","magical","sonic"]},grievous:{damage:{dice:[{damageType:"bleed",diceNumber:1,dieSize:"d6",critical:!0,predicate:["critical-specialization","item:group:dart"]}],notes:[{outcome:["criticalSuccess"],predicate:["item:group:axe"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Axe"},{outcome:["criticalSuccess"],predicate:["item:group:brawling"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Brawling"},{outcome:["criticalSuccess"],predicate:["item:group:club"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Club"},{outcome:["criticalSuccess"],predicate:["item:group:flail"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Flail"},{outcome:["criticalSuccess"],predicate:["item:group:hammer"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Hammer"},{outcome:["criticalSuccess"],predicate:["item:group:knife"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Knife"},{outcome:["criticalSuccess"],predicate:["item:group:polearm"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Polearm"},{outcome:["criticalSuccess"],predicate:["item:group:shield"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Shield"},{outcome:["criticalSuccess"],predicate:["item:group:sling"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Sling"},{outcome:["criticalSuccess"],predicate:["item:group:spear"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Spear"},{outcome:["criticalSuccess"],predicate:["item:group:sword"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Sword"}],adjustments:[{slug:"critical-specialization",test:options=>new PredicatePF2e("item:group:pick").test(options),getNewValue:current=>current*2}]},level:9,name:"PF2E.WeaponPropertyRune.grievous.Name",price:700,rarity:"common",slug:"grievous",traits:["enchantment","magical"]},hauling:{level:6,name:"PF2E.WeaponPropertyRune.hauling.Name",price:225,rarity:"uncommon",slug:"hauling",traits:["evocation","magical"]},holy:{damage:{dice:[{damageType:"good",diceNumber:1,dieSize:"d6"}]},level:11,name:"PF2E.WeaponPropertyRune.holy.Name",price:1400,rarity:"common",slug:"holy",traits:["evocation","good","magical"]},hopeful:{attack:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.hopeful.Name",text:"PF2E.WeaponPropertyRune.hopeful.Note.criticalSuccess"}]},level:11,name:"PF2E.WeaponPropertyRune.hopeful.Name",price:1200,rarity:"uncommon",slug:"hopeful",traits:["enchantment","magical"]},hooked:{level:5,name:"PF2E.WeaponPropertyRune.hooked.Name",price:140,rarity:"rare",slug:"hooked",traits:["conjuration","magical"],strikeAdjustments:[{adjustWeapon:weapon=>{weapon.system.traits.value.includes("trip")||weapon.system.traits.value.push("trip")}}]},impactful:{damage:{dice:[{damageType:"force",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.impactful.Name",text:"PF2E.WeaponPropertyRune.impactful.Note.criticalSuccess"}]},level:10,name:"PF2E.WeaponPropertyRune.impactful.Name",price:1e3,rarity:"common",slug:"impactful",traits:["evocation","force","magical"]},impossible:{level:20,name:"PF2E.WeaponPropertyRune.impossible.Name",price:7e4,rarity:"common",slug:"impossible",traits:["conjuration","magical"],strikeAdjustments:[{adjustWeapon:weapon=>{if(weapon.isOfType("weapon")&&weapon.system.range&&weapon._source.system.range){const sourceRange=weapon._source.system.range,preparedRange=weapon.system.range;weapon.system.range=sourceRange*2+Math.abs(preparedRange-sourceRange)}}}]},keen:{attack:{notes:[{outcome:["success"],title:"PF2E.WeaponPropertyRune.keen.Name",text:"PF2E.WeaponPropertyRune.keen.Note"}]},level:13,name:"PF2E.WeaponPropertyRune.keen.Name",price:3e3,rarity:"uncommon",slug:"keen",traits:["magical","transmutation"]},kinWarding:{level:3,name:"PF2E.WeaponPropertyRune.kinWarding.Name",price:52,rarity:"uncommon",slug:"kinWarding",traits:["abjuration","dwarf","magical"]},majorFanged:{level:15,name:"PF2E.WeaponPropertyRune.majorFanged.Name",price:6e3,rarity:"uncommon",slug:"majorFanged",traits:["magical","transmutation"]},majorRooting:{level:15,name:"PF2E.WeaponPropertyRune.majorRooting.Name",price:6500,rarity:"common",slug:"majorRooting",traits:["plant","magical","wood"],damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.majorRooting.Name",text:"PF2E.WeaponPropertyRune.majorRooting.Note.criticalSuccess"}]}},merciful:{strikeAdjustments:[{adjustWeapon:weapon=>{weapon.system.traits.value.includes("nonlethal")||weapon.system.traits.value.push("nonlethal")}}],level:4,name:"PF2E.WeaponPropertyRune.merciful.Name",price:70,rarity:"common",slug:"merciful",traits:["abjuration","magical","mental"]},pacifying:{level:5,name:"PF2E.WeaponPropertyRune.pacifying.Name",price:150,rarity:"uncommon",slug:"pacifying",traits:["enchantment","magical"]},returning:{attack:{notes:[{title:"PF2E.WeaponPropertyRune.returning.Name",text:"PF2E.WeaponPropertyRune.returning.Note"}]},level:3,name:"PF2E.WeaponPropertyRune.returning.Name",price:55,rarity:"common",slug:"returning",traits:["evocation","magical"]},rooting:{level:7,name:"PF2E.WeaponPropertyRune.rooting.Name",price:360,rarity:"common",slug:"rooting",traits:["plant","magical","wood"],damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.rooting.Name",text:"PF2E.WeaponPropertyRune.rooting.Note.criticalSuccess"}]}},serrating:{damage:{dice:[{damageType:"slashing",diceNumber:1,dieSize:"d4"}]},level:10,name:"PF2E.WeaponPropertyRune.serrating.Name",price:1e3,rarity:"uncommon",slug:"serrating",traits:["evocation","magical"]},shifting:{level:6,name:"PF2E.WeaponPropertyRune.shifting.Name",price:225,rarity:"common",slug:"shifting",traits:["magical","transmutation"]},shock:{damage:{dice:[{damageType:"electricity",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.shock.Name",text:"PF2E.WeaponPropertyRune.shock.Note.criticalSuccess"}]},level:8,name:"PF2E.WeaponPropertyRune.shock.Name",price:500,rarity:"common",slug:"shock",traits:["electricity","conjuration","magical"]},speed:{level:16,name:"PF2E.WeaponPropertyRune.speed.Name",price:1e4,rarity:"rare",slug:"speed",traits:["magical","transmutation"]},spellStoring:{level:13,name:"PF2E.WeaponPropertyRune.spellStoring.Name",price:2700,rarity:"uncommon",slug:"spellStoring",traits:["abjuration","magical"]},swarming:{level:9,name:"PF2E.WeaponPropertyRune.swarming.Name",price:700,rarity:"common",slug:"swarming",traits:["conjuration","magical"]},thundering:{damage:{dice:[{damageType:"sonic",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.thundering.Name",text:"PF2E.WeaponPropertyRune.thundering.Note.criticalSuccess"}]},level:8,name:"PF2E.WeaponPropertyRune.thundering.Name",price:500,rarity:"common",slug:"thundering",traits:["evocation","magical","sonic"]},trueRooting:{level:19,name:"PF2E.WeaponPropertyRune.trueRooting.Name",price:4e4,rarity:"common",slug:"trueRooting",traits:["plant","magical","wood"],damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.trueRooting.Name",text:"PF2E.WeaponPropertyRune.trueRooting.Note.criticalSuccess"}]}},underwater:{level:3,name:"PF2E.WeaponPropertyRune.underwater.Name",price:50,rarity:"common",slug:"underwater",traits:["magical","water"]},unholy:{damage:{dice:[{damageType:"evil",diceNumber:1,dieSize:"d6"}]},level:11,name:"PF2E.WeaponPropertyRune.unholy.Name",price:1400,rarity:"common",slug:"unholy",traits:["evil","evocation","magical"]},vorpal:{level:17,name:"PF2E.WeaponPropertyRune.vorpal.Name",price:15e3,rarity:"rare",slug:"vorpal",traits:["evocation","magical"]},wounding:{damage:{dice:[{damageType:"bleed",diceNumber:1,dieSize:"d6"}]},level:7,name:"PF2E.WeaponPropertyRune.wounding.Name",price:340,rarity:"common",slug:"wounding",traits:["magical","necromancy"]}},RUNE_DATA={armor:{...FUNDAMENTAL_ARMOR_RUNE_DATA,property:ARMOR_PROPERTY_RUNES},weapon:{...FUNDAMENTAL_WEAPON_RUNE_DATA,property:WEAPON_PROPERTY_RUNES}};function computePrice(item){const basePrice=item.price.value;if(item.isOfType("treasure"))return basePrice;const materialPrice=getMaterialValuationData(item)?.price??0,heldOrStowedBulk=new Bulk({light:item.system.bulk.heldOrStowed}),bulk=Math.max(Math.ceil(heldOrStowedBulk.normal),1),materialValue=materialPrice+bulk*materialPrice/10,runesData=getRuneValuationData(item),runeValue=item.isSpecific?0:runesData.reduce((sum2,rune)=>sum2+rune.price,0),afterMaterialAndRunes=runeValue?new CoinsPF2e({gp:runeValue+materialValue}):basePrice.add({gp:materialValue}),higher=afterMaterialAndRunes.copperValue>basePrice.copperValue?afterMaterialAndRunes:basePrice,afterShoddy=item.isShoddy?higher.scale(.5):higher;return item.isMagical?afterShoddy:afterShoddy.adjustForSize(item.size)}__name(computePrice,"computePrice"),__name2(computePrice,"computePrice");function computeLevelRarityPrice(item){const materialData=getMaterialValuationData(item),price=computePrice(item);if(!(item.isMagical||materialData)||item.isSpecific||item.isOfType("armor")&&item.isShield)return{...pick$1(item,["level","rarity"]),price};const runesData=getRuneValuationData(item),level=runesData.map(runeData=>runeData.level).concat(materialData?.level??0).reduce((highest,level2)=>level2>highest?level2:highest,item.level),rarityOrder={common:0,uncommon:1,rare:2,unique:3},baseRarity=item.rarity,rarity=runesData.map(runeData=>runeData.rarity).concat(materialData?.rarity??"common").reduce((highest,rarity2)=>rarityOrder[rarity2]>rarityOrder[highest]?rarity2:highest,baseRarity);return{level,rarity,price}}__name(computeLevelRarityPrice,"computeLevelRarityPrice"),__name2(computeLevelRarityPrice,"computeLevelRarityPrice");function generateItemName(item){if(!item.isOfType("armor","weapon")||item.isOfType("armor")&&item.isShield)return item.name;const[baseItemDictionary,propertyDictionary,fundamentalTwoDictionary]=item.isOfType("armor")?[CONFIG.PF2E.baseArmorTypes,RUNE_DATA.armor.property,RUNE_DATA.armor.resilient]:[CONFIG.PF2E.baseWeaponTypes,RUNE_DATA.weapon.property,RUNE_DATA.weapon.striking],storedName=item._source.name,baseType=item.baseType??"";if(!baseType||!(baseType in baseItemDictionary)||item.isSpecific||storedName!==game.i18n.localize(baseItemDictionary[baseType]??""))return item.name;const{material}=item,{runes}=item.system,potencyRune=runes.potency,fundamental2="resilient"in runes?runes.resilient:runes.striking,params={base:baseType?game.i18n.localize(baseItemDictionary[baseType]??""):item.name,material:material.type&&game.i18n.localize(CONFIG.PF2E.preciousMaterials[material.type]),potency:potencyRune,fundamental2:game.i18n.localize(fundamentalTwoDictionary[fundamental2]?.name??"")||null,property1:game.i18n.localize(propertyDictionary[runes.property[0]]?.name??"")||null,property2:game.i18n.localize(propertyDictionary[runes.property[1]]?.name??"")||null,property3:game.i18n.localize(propertyDictionary[runes.property[2]]?.name??"")||null,property4:game.i18n.localize(propertyDictionary[runes.property[3]]?.name??"")||null},formatString=(()=>{const potency=params.potency&&"Potency",fundamental22=params.fundamental2&&"Fundamental2",properties=params.property4?"FourProperties":params.property3?"ThreeProperties":params.property2?"TwoProperties":params.property1?"OneProperty":null,material2=params.material&&"Material",key=[potency,fundamental22,properties,material2].filter(keyPart=>!!keyPart).join("")||null;return key&&game.i18n.localize(key)})();return formatString?game.i18n.format(`PF2E.Item.Physical.GeneratedName.${formatString}`,params):item.name}__name(generateItemName,"generateItemName"),__name2(generateItemName,"generateItemName");function organizeBulkData(item){const stackData=STACK_DEFINITIONS[item.system.stackGroup??""]??null,per=stackData?.size??1,heldOrStowed=stackData?.lightBulk??weightToBulk(item.system.weight.value)?.toLightBulk()??0,worn=item.system.equippedBulk.value?weightToBulk(item.system.equippedBulk.value)?.toLightBulk()??0:heldOrStowed,value=item.isOfType("armor","equipment","backpack")&&item.isEquipped?worn:heldOrStowed;return{heldOrStowed,worn,value,per}}__name(organizeBulkData,"organizeBulkData"),__name2(organizeBulkData,"organizeBulkData");const _Migration639NormalizeLevelAndPrice=class extends MigrationBase{static{__name(this,"_Migration639NormalizeLevelAndPrice")}coinSlugs=new Set(["platinum-pieces","gold-pieces","silver-pieces","copper-pieces"]);async updateItem(source){if(source.system.level&&(source.system.level.value=Number(source.system.level.value)||0),!isPhysicalData(source)||this.coinSlugs.has(source.system.slug??""))return;const system=source.system,price=system.price;if(!(typeof price.value!="string"&&isObject(price.value)))if(price.value?price.value=price.value.trim():price.value="0 gp",/^[0-9]+$/.test(price.value))price.value=`${price.value} gp`;else{const quantity=system.quantity,priceValue=price.value;CoinsPF2e.fromString(priceValue,quantity).copperValue&&(price.value="0 gp")}}};__name2(_Migration639NormalizeLevelAndPrice,"Migration639NormalizeLevelAndPrice"),__publicField(_Migration639NormalizeLevelAndPrice,"version",.639);let Migration639NormalizeLevelAndPrice=_Migration639NormalizeLevelAndPrice;const _Migration640CantripsAreNotZeroLevel=class extends MigrationBase{static{__name(this,"_Migration640CantripsAreNotZeroLevel")}async updateItem(itemData){if(itemData.type!=="spell")return;const level=itemData.system.level;level.value===0&&(level.value=1,itemData.system.traits.value.includes("cantrip")||itemData.system.traits.value.push("cantrip"))}};__name2(_Migration640CantripsAreNotZeroLevel,"Migration640CantripsAreNotZeroLevel"),__publicField(_Migration640CantripsAreNotZeroLevel,"version",.64);let Migration640CantripsAreNotZeroLevel=_Migration640CantripsAreNotZeroLevel;const _Migration641SovereignSteelValue=class extends MigrationBase{static{__name(this,"_Migration641SovereignSteelValue")}async updateItem(source){if(source.type!=="weapon")return;const material=source.system.preciousMaterial??{};material.value?.toLowerCase()==="sovereign steel"&&(material.value="sovereignSteel")}};__name2(_Migration641SovereignSteelValue,"Migration641SovereignSteelValue"),__publicField(_Migration641SovereignSteelValue,"version",.641);let Migration641SovereignSteelValue=_Migration641SovereignSteelValue;const _Migration642TrackSchemaVersion=class extends MigrationBase{static{__name(this,"_Migration642TrackSchemaVersion")}async updateActor(actorSource){actorSource.system.schema??={version:null,lastMigration:null}}async updateItem(itemSource){itemSource.system.schema??={version:null,lastMigration:null}}};__name2(_Migration642TrackSchemaVersion,"Migration642TrackSchemaVersion"),__publicField(_Migration642TrackSchemaVersion,"version",.642);let Migration642TrackSchemaVersion=_Migration642TrackSchemaVersion;const _Migration643HazardLevel=class extends MigrationBase{static{__name(this,"_Migration643HazardLevel")}async updateActor(actorSource){if(actorSource.type!=="hazard")return;const hazardDetails=actorSource.system.details;if(typeof hazardDetails.level=="number"){const level=hazardDetails.level;hazardDetails.level={value:level}}}};__name2(_Migration643HazardLevel,"Migration643HazardLevel"),__publicField(_Migration643HazardLevel,"version",.643);let Migration643HazardLevel=_Migration643HazardLevel;const defaultTraditionByClass$1={wizard:"arcane",cleric:"divine",druid:"primal",bard:"occult",ranger:"primal",champion:"divine",monk:"divine"},_Migration644SpellcastingCategory=class extends MigrationBase{static{__name(this,"_Migration644SpellcastingCategory")}async updateItem(item,actor){if(!actor||item.type!=="spellcastingEntry")return;const spellcasting=item.system;if(spellcasting.tradition.value==="ritual")spellcasting.prepared.value="ritual",spellcasting.tradition.value="";else if(spellcasting.tradition.value==="focus"){spellcasting.prepared.value="focus";const possibleMatch=actor.items.find(testItem=>{if(testItem.type!=="spellcastingEntry")return!1;const testSpellcasting=testItem.system;return tupleHasValue(["prepared","spontaneous"],testSpellcasting.prepared.value)&&testSpellcasting.tradition.value!=="focus"&&(actor.type==="character"?testSpellcasting.proficiency.value===spellcasting.proficiency.value:testSpellcasting.spelldc.value===spellcasting.spelldc.value)&&(testSpellcasting.ability.value||"int")===(spellcasting.ability.value||"int")});if(possibleMatch)spellcasting.tradition.value=possibleMatch.system.tradition.value;else{const classItem=actor.items.find(testItem=>testItem.type==="class"),className=classItem?.system.slug||sluggify(classItem?.name??"");spellcasting.tradition.value=defaultTraditionByClass$1[className]??"arcane"}}}};__name2(_Migration644SpellcastingCategory,"Migration644SpellcastingCategory"),__publicField(_Migration644SpellcastingCategory,"version",.644);let Migration644SpellcastingCategory=_Migration644SpellcastingCategory;const _Migration645TokenImageSize=class extends MigrationBase{static{__name(this,"_Migration645TokenImageSize")}constructor(){super(...arguments),__privateAdd(this,_isTokenImageFlag),__privateAdd(this,_isTokenSizeFlag),__privateAdd(this,_imageOverrides,new Map),__privateAdd(this,_sizeOverrides,new Map)}async updateActor(actorSource){const flags=actorSource.flags,originalImg=flags.pf2e?.token?.img;__privateMethod(this,_isTokenImageFlag,isTokenImageFlag_fn).call(this,originalImg)&&__privateGet(this,_imageOverrides).set(actorSource._id,originalImg);const originalSize=flags.pf2e?.token?.size;__privateMethod(this,_isTokenSizeFlag,isTokenSizeFlag_fn).call(this,originalSize)&&__privateGet(this,_sizeOverrides).set(actorSource._id,originalSize),typeof flags.pf2e?.token=="object"&&("game"in globalThis&&(flags.pf2e["-=token"]=null),delete flags.pf2e.token)}async updateToken(tokenSource,actor){tokenSource.texture.src=__privateGet(this,_imageOverrides).get(actor?.id??"")??tokenSource.texture.src;const sizeOverride=__privateGet(this,_sizeOverrides).get(actor?.id??"");tokenSource.height=sizeOverride?.height??tokenSource.height,tokenSource.width=sizeOverride?.width??tokenSource.width}};_imageOverrides=new WeakMap,_sizeOverrides=new WeakMap,_isTokenImageFlag=new WeakSet,isTokenImageFlag_fn=__name2(function(flag){return typeof flag=="string"},"#isTokenImageFlag"),_isTokenSizeFlag=new WeakSet,isTokenSizeFlag_fn=__name2(function(flag){return flag instanceof Object&&"height"in flag&&typeof flag.height=="number"&&"width"in flag&&typeof flag.width=="number"},"#isTokenSizeFlag"),__name2(_Migration645TokenImageSize,"Migration645TokenImageSize"),__publicField(_Migration645TokenImageSize,"version",.645);let Migration645TokenImageSize=_Migration645TokenImageSize;const _Migration646UpdateInlineLinks=class extends MigrationBase{static{__name(this,"_Migration646UpdateInlineLinks")}updateCheckAttributes(markup=""){return markup.replace(/\bdata-pf2-([a-z]+)-check="\w*"/g,'data-pf2-check="$1"').replace(/\bdata-pf2-(?:saving-throw|skill-check)\b/g,"data-pf2-check")}async updateActor(actorData){if(actorData.type==="hazard"){const hazardDetails=actorData.system.details;hazardDetails.disable=this.updateCheckAttributes(hazardDetails.disable??"")}}async updateItem(itemData){const description=itemData.system.description;description.value=this.updateCheckAttributes(description.value??"")}};__name2(_Migration646UpdateInlineLinks,"Migration646UpdateInlineLinks"),__publicField(_Migration646UpdateInlineLinks,"version",.646);let Migration646UpdateInlineLinks=_Migration646UpdateInlineLinks;const _Migration647FixPCSenses=class extends MigrationBase{static{__name(this,"_Migration647FixPCSenses")}async updateActor(actorData){if(actorData.type!=="character")return;const notTraits=actorData.system.traits;Array.isArray(notTraits.senses)?notTraits.senses=notTraits.senses.filter(sense=>!!sense):notTraits.senses=[]}};__name2(_Migration647FixPCSenses,"Migration647FixPCSenses"),__publicField(_Migration647FixPCSenses,"version",.647);let Migration647FixPCSenses=_Migration647FixPCSenses;const _Migration648RemoveInvestedProperty=class extends MigrationBase{static{__name(this,"_Migration648RemoveInvestedProperty")}async updateItem(itemSource){if(!(itemSource.type==="treasure"||itemSource.type==="consumable"))return;const systemData=itemSource.system;delete systemData.invested,"game"in globalThis&&(systemData["-=invested"]=null)}};__name2(_Migration648RemoveInvestedProperty,"Migration648RemoveInvestedProperty"),__publicField(_Migration648RemoveInvestedProperty,"version",.648);let Migration648RemoveInvestedProperty=_Migration648RemoveInvestedProperty;function isCreatureSource(source){return["character","npc"].includes(source.type)}__name(isCreatureSource,"isCreatureSource"),__name2(isCreatureSource,"isCreatureSource");const _Migration649FocusToActor=class extends MigrationBase{static{__name(this,"_Migration649FocusToActor")}async updateActor(actorData){if(!isCreatureSource(actorData))return;const systemData=actorData.system;systemData.resources||(systemData.resources={});const spellLists=actorData.items.filter(i=>i.type==="spellcastingEntry").sort((a,b)=>(a.sort||0)-(b.sort||0)).map(i=>i.system).filter(i=>i.prepared.value==="focus"&&i.focus).sort((a,b)=>(b.focus?.pool||0)-(a.focus?.pool||0));if(spellLists.length===0)return;const focusOld=spellLists[0].focus,resources=actorData.system.resources;resources.focus={value:focusOld?.points??0,max:focusOld?.pool??1}}async updateItem(itemData){if(itemData.type!=="spellcastingEntry")return;const data=itemData.system;delete data.focus,"game"in globalThis&&(data["-=focus"]=null)}};__name2(_Migration649FocusToActor,"Migration649FocusToActor"),__publicField(_Migration649FocusToActor,"version",.649);let Migration649FocusToActor=_Migration649FocusToActor;const _Migration650StringifyWeaponProperties=class extends MigrationBase{static{__name(this,"_Migration650StringifyWeaponProperties")}async updateItem(itemData){if(itemData.type!=="weapon")return;const systemData=itemData.system;systemData.weaponType&&(systemData.weaponType.value||="simple");const range=systemData.range??={value:"melee"};range instanceof Object&&typeof range.value=="string"&&(range.value=range.value.trim()||"melee",range.value==="reach"&&(range.value="melee"))}};__name2(_Migration650StringifyWeaponProperties,"Migration650StringifyWeaponProperties"),__publicField(_Migration650StringifyWeaponProperties,"version",.65);let Migration650StringifyWeaponProperties=_Migration650StringifyWeaponProperties;const _Migration651EphemeralFocusPool=class extends MigrationBase{static{__name(this,"_Migration651EphemeralFocusPool")}constructor(){super(...arguments),__privateAdd(this,_needsRuleElement),__privateAdd(this,_isClassFeature),__privateAdd(this,_increasesByOne,new Set(["abundant-step","achaekeks-grip","advanced-bloodline","advanced-deitys-domain","advanced-domain","advanced-revelation","advanced-school-spell","advanced-seeker-of-truths","animal-feature","arcane-school-spell","apex-companion","basic-lesson","beastmasters-trance","blessed-sacrifice","cackle","champions-sacrifice","clinging-shadows-initiate","counter-perform","debilitating-dichotomy","domain-acumen","domain-fluency","empty-body","enlarge-companion","ephemeral-tracking","familiar-form","fatal-aria","gaze-of-veracity","greater-bloodline","greater-lesson","greater-revelation","heal-animal","healing-touch","hunters-luck","hunters-vision","impaling-briars","inspire-heroics","invoke-disaster","invoke-the-crimson-oath","ki-blast","ki-form","ki-rush","ki-strike","leaf-order","light-of-revelation","lingering-composition","litany-against-sloth","litany-against-wrath","litany-of-depravity","litany-of-righteousness","litany-of-self-interest","loremasters-etude","magic-hide","major-lesson","mantis-form","medusas-wrath","order-spell","perfect-ki-adept","perfect-strike","quivering-palm","rangers-bramble","shadow-magic","shadows-web","shall-not-falter-shall-not-rout","snare-hopping","song-of-the-fallen","soothing-ballad","soothing-mist","speaking-sky","spellmasters-ward","steal-the-sky","storm-order","sun-blade","suns-fury","terrain-transposition","transcribe-moment","universal-versatility","vision-of-weakness","wholeness-of-body","wild-winds-initiate","wind-caller","wind-jump","wronged-monks-wrath"]))}async updateActor(source){if(source.type!=="character")return;const systemData=source.system;systemData.resources??={};const resources=systemData.resources;typeof resources.focus?.max=="number"&&"game"in globalThis?resources.focus["-=max"]=null:delete resources.focus?.max}async updateItem(source){if(source.type!=="feat")return;const systemData=source.system,rule=(()=>{const slug=systemData.slug??sluggify(source.name);return slug==="revelation-spells"?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"upgrade",value:2,priority:10}:slug==="major-curse"?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"upgrade",value:3}:["composition-spells","devotion-spells","druidic-order","hexes"].includes(slug)||/^(?:arcane-school|bloodline)-/.test(slug)&&__privateMethod(this,_isClassFeature,isClassFeature_fn).call(this,source)?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"upgrade",value:1,priority:10}:__privateGet(this,_increasesByOne).has(slug)||slug.startsWith("first-revelation-")?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"add",value:1}:null})();rule&&__privateMethod(this,_needsRuleElement,needsRuleElement_fn).call(this,source.system.rules)&&systemData.rules.push(rule)}};_needsRuleElement=new WeakSet,needsRuleElement_fn=__name2(function(rules){return!rules.some(rule=>rule.key==="ActiveEffectLike"&&rule.path==="system.resources.focus.max")},"#needsRuleElement"),_increasesByOne=new WeakMap,_isClassFeature=new WeakSet,isClassFeature_fn=__name2(function(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"},"#isClassFeature"),__name2(_Migration651EphemeralFocusPool,"Migration651EphemeralFocusPool"),__publicField(_Migration651EphemeralFocusPool,"version",.651);let Migration651EphemeralFocusPool=_Migration651EphemeralFocusPool;const defaultTraditionByClass={wizard:"arcane",druid:"primal",ranger:"primal"},_Migration652KillHalcyonTradition=class extends MigrationBase{static{__name(this,"_Migration652KillHalcyonTradition")}async updateItem(itemData,actor){if(itemData.type!=="spellcastingEntry")return;const tradition=itemData.system.tradition;if(tradition.value==="halcyon"){const classItem=actor?.items.find(testItem=>testItem.type==="class"),className=classItem?.system.slug||sluggify(classItem?.name??"");tradition.value=defaultTraditionByClass[className]??"arcane"}}};__name2(_Migration652KillHalcyonTradition,"Migration652KillHalcyonTradition"),__publicField(_Migration652KillHalcyonTradition,"version",.652);let Migration652KillHalcyonTradition=_Migration652KillHalcyonTradition;const _Migration653AEstoREs=class extends MigrationBase{static{__name(this,"_Migration653AEstoREs")}constructor(){super(...arguments),__privateAdd(this,_isRemovableAE),__privateAdd(this,_isRemoveableChange),__privateAdd(this,_fixClassKeyAbilities),__privateAdd(this,_pathsToRemove,new Set([...["unarmored","light","medium","heavy"].map(category=>`system.martial.${category}.rank`),...["unarmed","simple","martial","advanced"].map(category=>`system.martial.${category}.rank`),...["fortitude","reflex","will"].map(save=>`system.saves.${save}.rank`),"system.details.keyability.value","system.attributes.perception.rank","system.attributes.classDC.rank"]))}async updateActor(actorSource){if(actorSource.type!=="character")return;const systemData=actorSource.system;systemData.martial={},actorSource.effects=actorSource.effects.filter(effect=>{const origin=effect.origin??"",itemId=/\bItem\.([A-Za-z0-9]{16})$/.exec(origin)?.[1],itemSource=actorSource.items.find(maybeSource=>maybeSource._id===itemId);return itemSource&&!(["class","effect","feat"].includes(itemSource.type)&&__privateMethod(this,_isRemovableAE,isRemovableAE_fn).call(this,effect))})}async updateItem(itemSource){if(!(itemSource.type==="class"||itemSource.type==="effect"||itemSource.type==="feat"))return;itemSource.type==="class"&&__privateMethod(this,_fixClassKeyAbilities,fixClassKeyAbilities_fn).call(this,itemSource);const modes2={1:"multiply",2:"add",3:"downgrade",4:"upgrade",5:"override"};for(const effect of[...itemSource.effects]){itemSource.type==="class"&&(effect.changes=effect.changes.filter(change=>!__privateGet(this,_pathsToRemove).has(change.key)));const toAELikes=effect.changes.filter(__privateMethod(this,_isRemoveableChange,isRemoveableChange_fn)),rules=itemSource.system.rules;for(const change of toAELikes){if(change.mode===0)continue;const newRule={key:"ActiveEffectLike",path:change.key,mode:modes2[change.mode],value:Number.isNaN(Number(change.value))?change.value:Number(change.value),priority:change.priority??50};rules.push(newRule)}effect.changes=effect.changes.filter(change=>!__privateMethod(this,_isRemoveableChange,isRemoveableChange_fn).call(this,change))}itemSource.effects=itemSource.effects.filter(effect=>!__privateMethod(this,_isRemovableAE,isRemovableAE_fn).call(this,effect))}};_pathsToRemove=new WeakMap,_isRemovableAE=new WeakSet,isRemovableAE_fn=__name2(function(effect){return effect.changes.every(__privateMethod(this,_isRemoveableChange,isRemoveableChange_fn))},"#isRemovableAE"),_isRemoveableChange=new WeakSet,isRemoveableChange_fn=__name2(function(change){return change.mode!==0&&Number.isInteger(Number(change.value))||change.mode===5&&!change.value.startsWith("{")},"#isRemoveableChange"),_fixClassKeyAbilities=new WeakSet,fixClassKeyAbilities_fn=__name2(function(classSource){const keyAbility=classSource.system.keyAbility;keyAbility.value=keyAbility.value.map(value=>typeof value=="string"?value:value.value)},"#fixClassKeyAbilities"),__name2(_Migration653AEstoREs,"Migration653AEstoREs"),__publicField(_Migration653AEstoREs,"version",.653);let Migration653AEstoREs=_Migration653AEstoREs;const _Migration654ActionTypeAndCount=class extends MigrationBase{static{__name(this,"_Migration654ActionTypeAndCount")}async updateItem(item){if(item.type!=="feat"&&item.type!=="action")return;const systemData=item.system;systemData.actions.value=Math.min(3,Math.max(Number(systemData.actions.value),0))||null}};__name2(_Migration654ActionTypeAndCount,"Migration654ActionTypeAndCount"),__publicField(_Migration654ActionTypeAndCount,"version",.654);let Migration654ActionTypeAndCount=_Migration654ActionTypeAndCount;const _Migration655CreatureTokenSizes=class extends MigrationBase{static{__name(this,"_Migration655CreatureTokenSizes")}constructor(){super(...arguments),__privateAdd(this,_isTokenSizeRE),__privateAdd(this,_isActorSizeAELike),__privateAdd(this,_isBracketedValue),__publicField(this,"dimensionToSize",{.5:"tiny",2:"lg",3:"huge",4:"grg"})}async updateItem(itemSource){itemSource.system.rules??=[];const rules=itemSource.system.rules,actorSizeAELike=rules.find(__privateMethod(this,_isActorSizeAELike,isActorSizeAELike_fn)),tokenSizeRE=rules.find(__privateMethod(this,_isTokenSizeRE,isTokenSizeRE_fn));if(actorSizeAELike)actorSizeAELike.key="CreatureSize",delete actorSizeAELike.path,delete actorSizeAELike.mode;else if(tokenSizeRE&&["number","string","object"].includes(typeof tokenSizeRE.value))if(tokenSizeRE.key="CreatureSize",__privateMethod(this,_isBracketedValue,isBracketedValue_fn).call(this,tokenSizeRE.value))for(const bracket of tokenSizeRE.value.brackets)typeof bracket.value=="number"&&(bracket.value=this.dimensionToSize[bracket.value]??"med");else typeof tokenSizeRE.value=="number"&&(tokenSizeRE.value=this.dimensionToSize[tokenSizeRE.value]??"med");tokenSizeRE&&tokenSizeRE.key!=="CreatureSize"&&itemSource.system.rules.splice(itemSource.system.rules.indexOf(tokenSizeRE),1)}};_isTokenSizeRE=new WeakSet,isTokenSizeRE_fn=__name2(function(rule){return typeof rule.key=="string"&&rule.key.endsWith("TokenSize")},"#isTokenSizeRE"),_isActorSizeAELike=new WeakSet,isActorSizeAELike_fn=__name2(function(rule){return typeof rule.key=="string"&&rule.key.endsWith("ActiveEffectLike")&&rule.path==="system.traits.size.value"},"#isActorSizeAELike"),_isBracketedValue=new WeakSet,isBracketedValue_fn=__name2(function(value){return isObject(value)&&Array.isArray(value.brackets)},"#isBracketedValue"),__name2(_Migration655CreatureTokenSizes,"Migration655CreatureTokenSizes"),__publicField(_Migration655CreatureTokenSizes,"version",.655);let Migration655CreatureTokenSizes=_Migration655CreatureTokenSizes;const _Migration656OtherFocusPoolSources=class extends MigrationBase{static{__name(this,"_Migration656OtherFocusPoolSources")}needsRuleElement(rules){return!rules.some(rule=>rule.key==="ActiveEffectLike"&&rule.path==="system.resources.focus.max")}increasesByOne=new Set(["additional-shadow-magic","basic-bloodline-spell","blessed-one-dedication","breath-of-the-dragon","crystal-ward-spells","domain-initiate","expanded-domain-initiate","gravity-weapon","heal-companion","leaf-order","shadow-illusion","storm-order","wings-of-the-dragon"]);async updateItem(itemSource){if(itemSource.type!=="feat")return;const systemData=itemSource.system,rule=(()=>{const slug=systemData.slug??sluggify(itemSource.name);return slug==="druidic-order"?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"upgrade",value:1,priority:10}:this.increasesByOne.has(slug)?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"add",value:1}:null})();rule&&this.needsRuleElement(itemSource.system.rules)&&systemData.rules.push(rule)}};__name2(_Migration656OtherFocusPoolSources,"Migration656OtherFocusPoolSources"),__publicField(_Migration656OtherFocusPoolSources,"version",.656);let Migration656OtherFocusPoolSources=_Migration656OtherFocusPoolSources;const _Migration657RemoveSetProperty=class extends MigrationBase{static{__name(this,"_Migration657RemoveSetProperty")}async updateActor(actorSource){const systemFlags=actorSource.flags.pf2e??{};delete systemFlags["set-property"],"game"in globalThis&&"set-property"in systemFlags&&(systemFlags["-=set-property"]=null)}async updateItem(itemSource){itemSource.system.rules??=[];const rules=itemSource.system.rules,setPropertyRules=itemSource.system.rules.filter(rule=>typeof rule.key=="string"&&["SetProperty","PF2E.RuleElement.SetProperty"].includes(rule.key)&&typeof rule.property=="string"&&typeof rule.on=="object"&&rule.on!==null&&"added"in rule.on),aeLikes=setPropertyRules.map(setProperty2=>({key:"ActiveEffectLike",mode:"override",path:setProperty2.property.replace(/^flags\.2e/,"flags.pf2e"),value:setProperty2.on.added,priority:10}));for(const setPropertyRule of setPropertyRules){const index=rules.indexOf(setPropertyRule);rules.splice(index,1,aeLikes.shift())}itemSource.system.rules=itemSource.system.rules.filter(rule=>rule&&typeof rule.key=="string"&&!rule.key.trim().endsWith("SetProperty"))}};__name2(_Migration657RemoveSetProperty,"Migration657RemoveSetProperty"),__publicField(_Migration657RemoveSetProperty,"version",.657);let Migration657RemoveSetProperty=_Migration657RemoveSetProperty;const _Migration658MonkUnarmoredProficiency=class extends MigrationBase{static{__name(this,"_Migration658MonkUnarmoredProficiency")}async updateItem(itemSource){const slug=itemSource.system.slug??sluggify(itemSource.name);itemSource.type==="class"&&slug==="monk"&&itemSource.system.defenses.unarmored!==2&&(itemSource.system.defenses.unarmored=2)}};__name2(_Migration658MonkUnarmoredProficiency,"Migration658MonkUnarmoredProficiency"),__publicField(_Migration658MonkUnarmoredProficiency,"version",.658);let Migration658MonkUnarmoredProficiency=_Migration658MonkUnarmoredProficiency;const formulaHasValue=__name2(value=>!!value&&value!=="0","formulaHasValue"),modes=["level1","level2","level3","level4"],_Migration659MultipleDamageRows=class extends MigrationBase{static{__name(this,"_Migration659MultipleDamageRows")}async updateItem(source){if(source.type!=="spell")return;const data=source.system;if(data.scaling instanceof Object&&(typeof data.scaling.mode=="string"&&tupleHasValue(modes,data.scaling.mode)&&(data.scaling.interval=modes.indexOf(data.scaling.mode)+1),typeof data.scaling.formula=="string"&&formulaHasValue(data.scaling.formula)&&!data.scaling.damage&&(data.scaling.damage={0:data.scaling.formula}),!data.scaling.interval||!data.scaling.damage?"game"in globalThis?data["-=scaling"]=null:delete data.scaling:"game"in globalThis?(data.scaling["-=mode"]=null,data.scaling["-=formula"]=null):(delete data.scaling.mode,delete data.scaling.formula)),typeof data.damage.value=="string"){if(formulaHasValue(data.damage.value)||data.damage.applyMod){const value=data.damage.value;data.damage.value={0:{value,applyMod:data.damage.applyMod||void 0,type:{value:data.damageType?.value||"untyped",categories:[]}}}}else data.damage.value={};"game"in globalThis?data.damage["-=applyMod"]=null:delete data.damage.applyMod}"damageType"in data&&("game"in globalThis?data["-=damageType"]=null:data.damageType=void 0)}};__name2(_Migration659MultipleDamageRows,"Migration659MultipleDamageRows"),__publicField(_Migration659MultipleDamageRows,"version",.659);let Migration659MultipleDamageRows=_Migration659MultipleDamageRows;const _Migration660DerivedSpellTraits=class extends MigrationBase{static{__name(this,"_Migration660DerivedSpellTraits")}derivedTraits=[...MAGIC_SCHOOLS,...MAGIC_TRADITIONS];async updateItem(itemSource){if(itemSource.type==="spell"){const traits=itemSource.system.traits;traits.value=traits.value.filter(trait=>!this.derivedTraits.includes(trait))}}};__name2(_Migration660DerivedSpellTraits,"Migration660DerivedSpellTraits"),__publicField(_Migration660DerivedSpellTraits,"version",.66);let Migration660DerivedSpellTraits=_Migration660DerivedSpellTraits;const _Migration661NumifyVehicleDimensions=class extends MigrationBase{static{__name(this,"_Migration661NumifyVehicleDimensions")}async updateActor(actorSource){if(actorSource.type==="vehicle"){const{space}=actorSource.system.details;space.long=Number(space.long)||2,space.wide=Number(space.wide)||2,space.high=Number(space.high)||1}}};__name2(_Migration661NumifyVehicleDimensions,"Migration661NumifyVehicleDimensions"),__publicField(_Migration661NumifyVehicleDimensions,"version",.661);let Migration661NumifyVehicleDimensions=_Migration661NumifyVehicleDimensions;const _Migration662LinkToActorSizeDefaults=class extends MigrationBase{static{__name(this,"_Migration662LinkToActorSizeDefaults")}async updateActor(actorSource){const linkToActorSize=!["hazard","loot"].includes(actorSource.type);actorSource.prototypeToken.flags??={pf2e:{linkToActorSize}},actorSource.prototypeToken.flags.pf2e??={linkToActorSize},actorSource.prototypeToken.flags.pf2e.linkToActorSize??=linkToActorSize}async updateToken(tokenSource,actor){const linkToActorSize=!["hazard","loot"].includes(actor.type);tokenSource.flags.pf2e??={linkToActorSize},tokenSource.flags.pf2e.linkToActorSize??=linkToActorSize}};__name2(_Migration662LinkToActorSizeDefaults,"Migration662LinkToActorSizeDefaults"),__publicField(_Migration662LinkToActorSizeDefaults,"version",.662);let Migration662LinkToActorSizeDefaults=_Migration662LinkToActorSizeDefaults;function createBasicDamage(value,applyMod,damageType){return{0:{applyMod,type:{categories:[],value:damageType},value}}}__name(createBasicDamage,"createBasicDamage"),__name2(createBasicDamage,"createBasicDamage");function createBasicScaling(interval,scaling){return{interval,damage:{0:scaling}}}__name(createBasicScaling,"createBasicScaling"),__name2(createBasicScaling,"createBasicScaling");const _Migration663FixSpellDamage=class extends MigrationBase{static{__name(this,"_Migration663FixSpellDamage")}async updateItem(source){if(source.type!=="spell"||Object.keys(source.system.damage?.value??{}).length>0)return;const itemName=source.system.slug??sluggify(source.name),systemData=source.system;switch(itemName){case"animated-assault":systemData.damage.value=createBasicDamage("2d10",!1,"bludgeoning"),systemData.scaling=createBasicScaling(2,"2d10");break;case"daze":systemData.damage.value=createBasicDamage("0",!0,"mental"),systemData.scaling=createBasicScaling(2,"1d6");break;case"personal-blizzard":systemData.damage.value={0:{applyMod:!1,type:{value:"cold",categories:[]},value:"1d6"},1:{applyMod:!1,type:{value:"cold",subtype:"persistent",categories:[]},value:"1d6"}},systemData.scaling={interval:1,damage:{0:"1",1:"1"}};break;case"power-word-kill":systemData.damage.value=createBasicDamage("50",!1,"untyped");break}}};__name2(_Migration663FixSpellDamage,"Migration663FixSpellDamage"),__publicField(_Migration663FixSpellDamage,"version",.663);let Migration663FixSpellDamage=_Migration663FixSpellDamage;const _Migration664DeleteCUBConditions=class extends MigrationBase{static{__name(this,"_Migration664DeleteCUBConditions")}async updateActor(actorSource){const cubConditions=actorSource.items.filter(item=>item.type==="condition"&&!item.system.references?.overriddenBy);for(const condition of cubConditions)actorSource.items.findSplice(item=>item===condition)}};__name2(_Migration664DeleteCUBConditions,"Migration664DeleteCUBConditions"),__publicField(_Migration664DeleteCUBConditions,"version",.664);let Migration664DeleteCUBConditions=_Migration664DeleteCUBConditions;const _Migration665HandwrapsCorrections=class extends MigrationBase{static{__name(this,"_Migration665HandwrapsCorrections")}async updateItem(itemSource){const slug=itemSource.system.slug??sluggify(itemSource.name);if(itemSource.type==="weapon"&&slug==="handwraps-of-mighty-blows"){const usage=itemSource.system.usage;usage.value="worn-gloves"}const dirPath="systems/pf2e/icons/equipment/worn-items/other-worn-items";itemSource.img===`${dirPath}/handwraps-of-nighty-blows.webp`&&(itemSource.img=`${dirPath}/handwraps-of-mighty-blows.webp`)}};__name2(_Migration665HandwrapsCorrections,"Migration665HandwrapsCorrections"),__publicField(_Migration665HandwrapsCorrections,"version",.665);let Migration665HandwrapsCorrections=_Migration665HandwrapsCorrections;const _Migration666UsageAndStowingContainers=class extends MigrationBase{static{__name(this,"_Migration666UsageAndStowingContainers")}backpacks=new Set(["backpack","knapsack-of-halflingkind","knapsack-of-halflingkind-greater","sturdy-satchel","vaultbreaker-harness","voyagers-pack"]);wornGarment=new Set(["sleeves-of-storage","sleeves-of-storage-greater"]);wornGloves=new Set(["gloves-of-storing"]);heldInTwoHands=new Set(["bag-of-devouring-type-i","bag-of-devouring-type-ii","bag-of-devouring-type-iii","bag-of-holding-type-i","bag-of-holding-type-ii","bag-of-holding-type-iii","bag-of-holding-type-iv","bag-of-weasels","chest","sealing-chest-greater","sealing-chest-lesser","sealing-chest-moderate"]);stowingContainers=new Set([...this.backpacks,...this.heldInTwoHands,...this.wornGarment,...this.wornGloves,"extradimensional-stash"]);async updateItem(itemSource){if(!itemSource.system.traits)return;const traits=itemSource.system.traits;if(typeof traits.usage?.value=="string"){const traitUsage=traits.usage.value,isPhysical=isPhysicalData(itemSource),keepUsage=isPhysical&&(traitUsage!=="held-in-one-hand"||itemSource.system.usage.value==="");isPhysical&&keepUsage&&(itemSource.system.usage.value=traits.usage.value),"game"in globalThis?traits["-=usage"]=null:delete traits.usage}if(itemSource.type!=="backpack")return;const slug=itemSource.system.slug??sluggify(itemSource.name);this.backpacks.has(slug)?itemSource.system.usage.value="wornbackpack":this.heldInTwoHands.has(slug)?itemSource.system.usage.value="held-in-two-hands":this.wornGarment.has(slug)?itemSource.system.usage.value="worngarment":this.wornGloves.has(slug)?itemSource.system.usage.value="worngloves":itemSource.system.usage.value="worn",itemSource.system.stowing=this.stowingContainers.has(slug)}};__name2(_Migration666UsageAndStowingContainers,"Migration666UsageAndStowingContainers"),__publicField(_Migration666UsageAndStowingContainers,"version",.666);let Migration666UsageAndStowingContainers=_Migration666UsageAndStowingContainers;const _Migration667HPSubProperties=class extends MigrationBase{static{__name(this,"_Migration667HPSubProperties")}addRecoveryMultiplier(itemSource,slug){if(!["dream-may","fast-recovery"].includes(slug))return;const rules=itemSource.system.rules;if(!rules.some(rule=>"path"in rule&&rule.path==="system.attributes.hp.recoveryMultiplier")){const element={key:"ActiveEffectLike",mode:"add",path:"system.attributes.hp.recoveryMultiplier",value:1};rules.push(element)}}addNegativeHealing(itemSource,slug){if(!["dhampir","negative-healing"].includes(slug))return;const rules=itemSource.system.rules;if(!rules.some(rule=>"path"in rule&&rule.path==="system.attributes.hp.negativeHealing")){const element={key:"ActiveEffectLike",mode:"override",path:"system.attributes.hp.negativeHealing",value:!0};rules.push(element)}}async updateItem(itemSource){if(itemSource.type!=="feat"&&itemSource.type!=="action")return;const slug=itemSource.system.slug??sluggify(itemSource.name);this.addRecoveryMultiplier(itemSource,slug),this.addNegativeHealing(itemSource,slug)}};__name2(_Migration667HPSubProperties,"Migration667HPSubProperties"),__publicField(_Migration667HPSubProperties,"version",.667);let Migration667HPSubProperties=_Migration667HPSubProperties;const _Migration668ArmorSpeedPenalty=class extends MigrationBase{static{__name(this,"_Migration668ArmorSpeedPenalty")}async updateItem(itemSource){const slug=itemSource.system.slug??sluggify(itemSource.name);if(itemSource.type==="armor"){const rules=itemSource.system.rules??=[],rule=rules.find(r=>typeof r.key=="string"&&r.key.endsWith("FlatModifier")&&r.selector==="speed"&&typeof r.value=="object"&&JSON.stringify(r.predicate??null)===JSON.stringify({not:["unburdened-iron"]}));rule&&rules.splice(rules.indexOf(rule),1)}else if(itemSource.type==="feat"){if(slug==="unburdened-iron"){const rule={key:"RollOption",domain:"speed",option:"armor:ignore-speed-penalty"};itemSource.system.rules=[rule]}else if(slug==="armored-stealth"){const rule={key:"RollOption",domain:"stealth",option:"armor:ignore-noisy-penalty"};itemSource.system.rules=[rule]}}}};__name2(_Migration668ArmorSpeedPenalty,"Migration668ArmorSpeedPenalty"),__publicField(_Migration668ArmorSpeedPenalty,"version",.668);let Migration668ArmorSpeedPenalty=_Migration668ArmorSpeedPenalty;const _Migration669NPCAttackEffects=class extends MigrationBase{static{__name(this,"_Migration669NPCAttackEffects")}async updateItem(item,actor){!actor||item.type!=="melee"||(item.system.attackEffects??={value:[]},Array.isArray(item.system.attackEffects.value)&&item.system.attackEffects.value.forEach((entry,index,arr)=>{arr[index]=sluggify(entry)}))}};__name2(_Migration669NPCAttackEffects,"Migration669NPCAttackEffects"),__publicField(_Migration669NPCAttackEffects,"version",.669);let Migration669NPCAttackEffects=_Migration669NPCAttackEffects;const _Migration670AncestryVision=class extends MigrationBase{static{__name(this,"_Migration670AncestryVision")}constructor(){super(...arguments),__privateAdd(this,_setAncestryVision),__publicField(this,"DARKVISION_ID","HHVQDp61ehcpdiU8"),__publicField(this,"LOWLIGHTVISION_ID","DRtaqOHXTRtGRIUT")}async updateActor(source){if(source.type!=="character")return;const ancestry=source.items.find(item=>item.type==="ancestry");if(ancestry){__privateMethod(this,_setAncestryVision,setAncestryVision_fn).call(this,ancestry);for(const vision of["darkvision","low-light-vision"]){const index=source.items.findIndex(item=>item.type==="feat"&&(item.system.slug??sluggify(item.name))===vision);index!==-1&&source.items.splice(index,1)}}}async updateItem(source,actor){source.type==="ancestry"&&!actor&&__privateMethod(this,_setAncestryVision,setAncestryVision_fn).call(this,source)}};_setAncestryVision=new WeakSet,setAncestryVision_fn=__name2(function(ancestry){const features=ancestry.system.items;for(const[key,value]of Object.entries(features))value?.id===this.LOWLIGHTVISION_ID?("game"in globalThis?features[`-=${key}`]=null:delete features[key],ancestry.system.vision=ancestry.system.vision==="darkvision"?"darkvision":"lowLightVision"):value?.id===this.DARKVISION_ID&&("game"in globalThis?features[`-=${key}`]=null:delete features[key],ancestry.system.vision="darkvision");ancestry.system.vision??="normal"},"#setAncestryVision"),__name2(_Migration670AncestryVision,"Migration670AncestryVision"),__publicField(_Migration670AncestryVision,"version",.67);let Migration670AncestryVision=_Migration670AncestryVision;const _Migration670NoCustomTrait=class extends MigrationBase{static{__name(this,"_Migration670NoCustomTrait")}async updateItem(itemSource){const traits=itemSource.system.traits;traits&&(Array.isArray(traits.value)?traits.value=traits.value.filter(trait=>trait&&trait!=="custom"):traits.value=[])}};__name2(_Migration670NoCustomTrait,"Migration670NoCustomTrait"),__publicField(_Migration670NoCustomTrait,"version",.67);let Migration670NoCustomTrait=_Migration670NoCustomTrait;const _Migration671NoPCItemsOnNonPCs=class extends MigrationBase{static{__name(this,"_Migration671NoPCItemsOnNonPCs")}async updateActor(actorSource){if(actorSource.type==="character")return;const pcOnlyTypes=["ancestry","background","class","feat"],forbiddenItems=actorSource.items.filter(item=>pcOnlyTypes.includes(item.type));for(const forbiddenItem of forbiddenItems){const index=actorSource.items.findIndex(item=>item===forbiddenItem);index!==-1&&actorSource.items.splice(index,1)}}};__name2(_Migration671NoPCItemsOnNonPCs,"Migration671NoPCItemsOnNonPCs"),__publicField(_Migration671NoPCItemsOnNonPCs,"version",.671);let Migration671NoPCItemsOnNonPCs=_Migration671NoPCItemsOnNonPCs;const PHYSICAL_DAMAGE_TYPES=["bludgeoning","piercing","slashing","bleed"],LIFE_ENERGY_DAMAGE_TYPES=["vitality","void"],ENERGY_DAMAGE_TYPES=["acid","cold","electricity","fire","sonic","force",...LIFE_ENERGY_DAMAGE_TYPES],ALIGNMENT_DAMAGE_TYPES=["chaotic","lawful","good","evil"],DAMAGE_CATEGORIES_UNIQUE=new Set(["persistent","precision","splash"]),MATERIAL_DAMAGE_EFFECTS=new Set(["adamantine","cold-iron","darkwood","mithral","orichalcum","silver","sisterstone-dusk","sisterstone-scarlet","warpglass"]);[...DAMAGE_CATEGORIES_UNIQUE,...MATERIAL_DAMAGE_EFFECTS];const DAMAGE_DIE_FACES_TUPLE=["d4","d6","d8","d10","d12"],DAMAGE_DIE_FACES=new Set(DAMAGE_DIE_FACES_TUPLE),DAMAGE_TYPES=new Set([...PHYSICAL_DAMAGE_TYPES,...ENERGY_DAMAGE_TYPES,...ALIGNMENT_DAMAGE_TYPES,"mental","poison","spirit","untyped"]),BASE_DAMAGE_TYPES_TO_CATEGORIES={bludgeoning:"physical",piercing:"physical",slashing:"physical",bleed:"physical",acid:"energy",cold:"energy",electricity:"energy",fire:"energy",sonic:"energy",vitality:"energy",void:"energy",force:"energy",chaotic:"alignment",evil:"alignment",good:"alignment",lawful:"alignment",mental:null,poison:null,spirit:null,untyped:null},DAMAGE_TYPE_ICONS={bleed:"droplet",acid:"vial",bludgeoning:"hammer",chaotic:"face-zany",cold:"snowflake",electricity:"bolt",evil:"face-angry-horns",fire:"fire",force:"sparkles",good:"face-smile-halo",lawful:"scale-balanced",mental:"brain",piercing:"bow-arrow",poison:"spider",slashing:"axe",sonic:"waveform-lines",spirit:"ghost",vitality:"sun",void:"skull",untyped:null},PERSISTENT_DAMAGE_IMAGES={acid:"icons/magic/acid/dissolve-arm-flesh.webp",bludgeoning:"systems/pf2e/icons/equipment/weapons/bola.webp",chaotic:"systems/pf2e/icons/spells/dinosaur-form.webp",cold:"icons/magic/water/ice-snowman.webp",electricity:"systems/pf2e/icons/spells/chain-lightning.webp",evil:"icons/magic/unholy/strike-body-explode-disintegrate.webp",fire:"icons/magic/fire/flame-burning-creature-skeleton.webp",force:"systems/pf2e/icons/spells/magic-missile.webp",good:"systems/pf2e/icons/damage/persistent/good.webp",lawful:"systems/pf2e/icons/equipment/adventuring-gear/merchant-scale.webp",mental:"systems/pf2e/icons/spells/modify-memory.webp",piercing:"systems/pf2e/icons/equipment/weapons/throwing-knife.webp",poison:"systems/pf2e/icons/spells/acidic-burst.webp",slashing:"systems/pf2e/icons/equipment/weapons/scimitar.webp",sonic:"systems/pf2e/icons/spells/cry-of-destruction.webp",spirit:"icons/magic/unholy/hand-claw-fire-blue.webp",vitality:"systems/pf2e/icons/spells/moment-of-renewal.webp",void:"systems/pf2e/icons/spells/grim-tendrils.webp"},CRITICAL_INCLUSION={DOUBLE_ON_CRIT:null,CRITICAL_ONLY:!0,DONT_DOUBLE_ON_CRIT:!1},_MystifiedTraits=class{static{__name(this,"_MystifiedTraits")}static compile(){this.mystifiedTraits=new Set(["artifact","extradimensional","invested","shadow",...Object.keys(CONFIG.PF2E.consumableTraits).filter(t=>!["consumable","nonlethal"].includes(t))].sort())}static has(trait){return this.mystifiedTraits.has(trait)}};__name2(_MystifiedTraits,"MystifiedTraits"),__publicField(_MystifiedTraits,"mystifiedTraits",new Set);let MystifiedTraits=_MystifiedTraits;const ITEM_CARRY_TYPES=new Set(["held","worn","stowed","dropped"]),RANGE_TRAITS=["range-5","range-10","range-15","range-20","range-25","range-30","range-40","range-50","range-60","range-70","range-80","range-90","range-100","range-110","range-120","range-140","range-150","range-160","range-170","range-180","range-190","range-200","range-210","range-220","range-230","range-240","range-250","range-260","range-270","range-280","range-290","range-300","range-310","range-320","range-500","range-increment-5","range-increment-10","range-increment-15","range-increment-20","range-increment-25","range-increment-30","range-increment-40","range-increment-50","range-increment-60","range-increment-70","range-increment-75","range-increment-80","range-increment-90","range-increment-100","range-increment-110","range-increment-120","range-increment-130","range-increment-140","range-increment-150","range-increment-160","range-increment-170","range-increment-180","range-increment-190","range-increment-200","range-increment-210","range-increment-220","range-increment-230","range-increment-240","range-increment-250","range-increment-260","range-increment-270","range-increment-280","range-increment-290","range-increment-300","range-increment-310","range-increment-320"],ancestryTraits={"half-elf":"PF2E.TraitHalfElf","half-orc":"PF2E.TraitHalfOrc",aasimar:"PF2E.TraitAasimar",aberration:"PF2E.TraitAberration",anadi:"PF2E.TraitAnadi",android:"PF2E.TraitAndroid",aphorite:"PF2E.TraitAphorite",ardande:"PF2E.TraitArdande",automaton:"PF2E.TraitAutomaton",azarketi:"PF2E.TraitAzarketi",beastkin:"PF2E.TraitBeastkin",catfolk:"PF2E.TraitCatfolk",changeling:"PF2E.TraitChangeling",conrasu:"PF2E.TraitConrasu",dhampir:"PF2E.TraitDhampir",duskwalker:"PF2E.TraitDuskwalker",dwarf:"PF2E.TraitDwarf",elf:"PF2E.TraitElf",fetchling:"PF2E.TraitFetchling",fleshwarp:"PF2E.TraitFleshwarp",ganzi:"PF2E.TraitGanzi",geniekin:"PF2E.TraitGeniekin",ghoran:"PF2E.TraitGhoran",gnoll:"PF2E.TraitGnoll",gnome:"PF2E.TraitGnome",goblin:"PF2E.TraitGoblin",goloma:"PF2E.TraitGoloma",grippli:"PF2E.TraitGrippli",halfling:"PF2E.TraitHalfling",hobgoblin:"PF2E.TraitHobgoblin",human:"PF2E.TraitHuman",ifrit:"PF2E.TraitIfrit",kashrishi:"PF2E.TraitKashrishi",kitsune:"PF2E.TraitKitsune",kobold:"PF2E.TraitKobold",leshy:"PF2E.TraitLeshy",lizardfolk:"PF2E.TraitLizardfolk",nagaji:"PF2E.TraitNagaji",orc:"PF2E.TraitOrc",oread:"PF2E.TraitOread",poppet:"PF2E.TraitPoppet",ratfolk:"PF2E.TraitRatfolk",reflection:"PF2E.TraitReflection",shisk:"PF2E.TraitShisk",shoony:"PF2E.TraitShoony",skeleton:"PF2E.TraitSkeleton",sprite:"PF2E.TraitSprite",strix:"PF2E.TraitStrix",suli:"PF2E.TraitSuli",sylph:"PF2E.TraitSylph",talos:"PF2E.TraitTalos",tengu:"PF2E.TraitTengu",tiefling:"PF2E.TraitTiefling",undine:"PF2E.TraitUndine",vanara:"PF2E.TraitVanara",vishkanya:"PF2E.TraitVishkanya"},ancestryItemTraits={...ancestryTraits,aeon:"PF2E.TraitAeon",amphibious:"PF2E.TraitAmphibious",automaton:"PF2E.TraitAutomaton",construct:"PF2E.TraitConstruct",fey:"PF2E.TraitFey",fungus:"PF2E.TraitFungus",humanoid:"PF2E.TraitHumanoid",plant:"PF2E.TraitPlant",undead:"PF2E.TraitUndead"},elementTraits={air:"PF2E.TraitAir",earth:"PF2E.TraitEarth",fire:"PF2E.TraitFire",metal:"PF2E.TraitMetal",water:"PF2E.TraitWater",wood:"PF2E.TraitWood"},energyDamageTypes={acid:"PF2E.TraitAcid",cold:"PF2E.TraitCold",electricity:"PF2E.TraitElectricity",fire:"PF2E.TraitFire",force:"PF2E.TraitForce",sonic:"PF2E.TraitSonic",vitality:"PF2E.TraitVitality",void:"PF2E.TraitVoid"},magicTraditions={arcane:"PF2E.TraitArcane",divine:"PF2E.TraitDivine",occult:"PF2E.TraitOccult",primal:"PF2E.TraitPrimal"},creatureTraits={...ancestryItemTraits,...elementTraits,...energyDamageTypes,...magicTraditions,aberration:"PF2E.TraitAberration",aeon:"PF2E.TraitAeon",aesir:"PF2E.TraitAesir",agathion:"PF2E.TraitAgathion",alchemical:"PF2E.TraitAlchemical",angel:"PF2E.TraitAngel",animal:"PF2E.TraitAnimal",anugobu:"PF2E.TraitAnugobu",aquatic:"PF2E.TraitAquatic",archon:"PF2E.TraitArchon",astral:"PF2E.TraitAstral",asura:"PF2E.TraitAsura",azata:"PF2E.TraitAzata",beast:"PF2E.TraitBeast",boggard:"PF2E.TraitBoggard",caligni:"PF2E.TraitCaligni",celestial:"PF2E.TraitCelestial","charau-ka":"PF2E.TraitCharauKa",clockwork:"PF2E.TraitClockwork",construct:"PF2E.TraitConstruct",couatl:"PF2E.TraitCouatl",daemon:"PF2E.TraitDaemon",darvakka:"PF2E.TraitDarvakka",demon:"PF2E.TraitDemon",dero:"PF2E.TraitDero",devil:"PF2E.TraitDevil",dinosaur:"PF2E.TraitDinosaur",div:"PF2E.TraitDiv",dragon:"PF2E.TraitDragon",dream:"PF2E.TraitDream",drow:"PF2E.TraitDrow",duergar:"PF2E.TraitDuergar",duskwalker:"PF2E.TraitDuskwalker",eidolon:"PF2E.TraitEidolon",elemental:"PF2E.TraitElemental",ethereal:"PF2E.TraitEthereal",evocation:"PF2E.TraitEvocation",fiend:"PF2E.TraitFiend",formian:"PF2E.TraitFormian",fungus:"PF2E.TraitFungus",genie:"PF2E.TraitGenie",ghoran:"PF2E.TraitGhoran",ghost:"PF2E.TraitGhost",ghoul:"PF2E.TraitGhoul",ghul:"PF2E.TraitGhul",giant:"PF2E.TraitGiant",golem:"PF2E.TraitGolem",gremlin:"PF2E.TraitGremlin",grioth:"PF2E.TraitGrioth",grippli:"PF2E.TraitGrippli",hag:"PF2E.TraitHag",hantu:"PF2E.TraitHantu",herald:"PF2E.TraitHerald",hryngar:"PF2E.TraitHryngar",humanoid:"PF2E.TraitHumanoid",ifrit:"PF2E.TraitIfrit",ikeshti:"PF2E.TraitIkeshti",illusion:"PF2E.TraitIllusion",incorporeal:"PF2E.TraitIncorporeal",inevitable:"PF2E.TraitInevitable",kami:"PF2E.TraitKami",kovintus:"PF2E.TraitKovintus",light:"PF2E.TraitLight",lilu:"PF2E.TraitLilu",locathah:"PF2E.TraitLocathah",mental:"PF2E.TraitMental",merfolk:"PF2E.TraitMerfolk",mindless:"PF2E.TraitMindless",minion:"PF2E.TraitMinion",monitor:"PF2E.TraitMonitor",morlock:"PF2E.TraitMorlock",mortic:"PF2E.TraitMortic",mummy:"PF2E.TraitMummy",munavri:"PF2E.TraitMunavri",mutant:"PF2E.TraitMutant",nagaji:"PF2E.TraitNagaji",necromancy:"PF2E.TraitNecromancy",nymph:"PF2E.TraitNymph",oni:"PF2E.TraitOni",ooze:"PF2E.TraitOoze",orc:"PF2E.TraitOrc",oread:"PF2E.TraitOread",paaridar:"PF2E.TraitPaaridar",petitioner:"PF2E.TraitPetitioner",phantom:"PF2E.TraitPhantom",poison:"PF2E.TraitPoison",protean:"PF2E.TraitProtean",psychopomp:"PF2E.TraitPsychopomp",qlippoth:"PF2E.TraitQlippoth",rakshasa:"PF2E.TraitRakshasa",reflection:"PF2E.TraitReflection",sahkil:"PF2E.TraitSahkil",samsaran:"PF2E.TraitSamsaran","sea-devil":"PF2E.TraitSeaDevil",serpentfolk:"PF2E.TraitSerpentfolk",seugathi:"PF2E.TraitSeugathi",shabti:"PF2E.TraitShabti",shadow:"PF2E.TraitShadow",shobhad:"PF2E.TraitShobhad",siktempora:"PF2E.TraitSiktempora",skeleton:"PF2E.TraitSkeleton",skelm:"PF2E.TraitSkelm",skulk:"PF2E.TraitSkulk",soulbound:"PF2E.TraitSoulbound",spirit:"PF2E.TraitSpirit",sporeborn:"PF2E.TraitSporeborn",spriggan:"PF2E.TraitSpriggan",stheno:"PF2E.TraitStheno",summoned:"PF2E.TraitSummoned",swarm:"PF2E.TraitSwarm",sylph:"PF2E.TraitSylph",tane:"PF2E.TraitTane",tanggal:"PF2E.TraitTanggal",tengu:"PF2E.TraitTengu",time:"PF2E.TraitTime",titan:"PF2E.TraitTitan",troll:"PF2E.TraitTroll",troop:"PF2E.TraitTroop",undead:"PF2E.TraitUndead",undine:"PF2E.TraitUndine",urdefhan:"PF2E.TraitUrdefhan",vampire:"PF2E.TraitVampire",vanara:"PF2E.TraitVanara",velstrac:"PF2E.TraitVelstrac",vishkanya:"PF2E.TraitVishkanya",wayang:"PF2E.TraitWayang",werecreature:"PF2E.TraitWerecreature",wight:"PF2E.TraitWight","wild-hunt":"PF2E.TraitWildHunt",wraith:"PF2E.TraitWraith",wyrwood:"PF2E.TraitWyrwood",xulgath:"PF2E.TraitXulgath",zombie:"PF2E.TraitZombie"},backgroundTraits={"pervasive-magic":"PF2E.TraitPervasiveMagic"},classTraits={alchemist:"PF2E.TraitAlchemist",barbarian:"PF2E.TraitBarbarian",bard:"PF2E.TraitBard",champion:"PF2E.TraitChampion",cleric:"PF2E.TraitCleric",druid:"PF2E.TraitDruid",fighter:"PF2E.TraitFighter",gunslinger:"PF2E.TraitGunslinger",inventor:"PF2E.TraitInventor",investigator:"PF2E.TraitInvestigator",kineticist:"PF2E.TraitKineticist",magus:"PF2E.TraitMagus",monk:"PF2E.TraitMonk",oracle:"PF2E.TraitOracle",psychic:"PF2E.TraitPsychic",ranger:"PF2E.TraitRanger",rogue:"PF2E.TraitRogue",sorcerer:"PF2E.TraitSorcerer",summoner:"PF2E.TraitSummoner",swashbuckler:"PF2E.TraitSwashbuckler",thaumaturge:"PF2E.TraitThaumaturge",witch:"PF2E.TraitWitch",wizard:"PF2E.TraitWizard"},spellOtherTraits={amp:"PF2E.TraitAmp",attack:"PF2E.TraitAttack",auditory:"PF2E.TraitAuditory",aura:"PF2E.TraitAura",beast:"PF2E.TraitBeast",cantrip:"PF2E.TraitCantrip",composition:"PF2E.TraitComposition",concentrate:"PF2E.TraitConcentrate",consecration:"PF2E.TraitConsecration",contingency:"PF2E.TraitContingency",curse:"PF2E.TraitCurse",cursebound:"PF2E.TraitCursebound",darkness:"PF2E.TraitDarkness",death:"PF2E.TraitDeath",detection:"PF2E.TraitDetection",disease:"PF2E.TraitDisease",dream:"PF2E.TraitDream",eidolon:"PF2E.TraitEidolon",emotion:"PF2E.TraitEmotion",extradimensional:"PF2E.TraitExtradimensional",fear:"PF2E.TraitFear",fortune:"PF2E.TraitFortune",fungus:"PF2E.TraitFungus",healing:"PF2E.TraitHealing",hex:"PF2E.TraitHex",incapacitation:"PF2E.TraitIncapacitation",incarnate:"PF2E.TraitIncarnate",incorporeal:"PF2E.TraitIncorporeal",inhaled:"PF2E.TraitInhaled",light:"PF2E.TraitLight",linguistic:"PF2E.TraitLinguistic",litany:"PF2E.TraitLitany",metamagic:"PF2E.TraitMetamagic",mindless:"PF2E.TraitMindless",misfortune:"PF2E.TraitMisfortune",morph:"PF2E.TraitMorph",move:"PF2E.TraitMove",nonlethal:"PF2E.TraitNonlethal",olfactory:"PF2E.TraitOlfactory",plant:"PF2E.TraitPlant",poison:"PF2E.TraitPoison",polymorph:"PF2E.TraitPolymorph",possession:"PF2E.TraitPossession",prediction:"PF2E.TraitPrediction",psyche:"PF2E.TraitPsyche",revelation:"PF2E.TraitRevelation",scrying:"PF2E.TraitScrying",shadow:"PF2E.TraitShadow",sleep:"PF2E.TraitSleep",stance:"PF2E.TraitStance",summoned:"PF2E.TraitSummoned",teleportation:"PF2E.TraitTeleportation","true-name":"PF2E.TraitTrueName",visual:"PF2E.TraitVisual"},alignmentTraits={chaotic:"PF2E.TraitChaotic",evil:"PF2E.TraitEvil",good:"PF2E.TraitGood",lawful:"PF2E.TraitLawful"},damageTraits={...alignmentTraits,...elementTraits,...energyDamageTypes,light:"PF2E.TraitLight",magical:"PF2E.TraitMagical",mental:"PF2E.TraitMental",nonlethal:"PF2E.TraitNonlethal",plant:"PF2E.TraitPlant",radiation:"PF2E.TraitRadiation",vitality:"PF2E.TraitVitality",void:"PF2E.TraitVoid"},magicSchools={abjuration:"PF2E.TraitAbjuration",conjuration:"PF2E.TraitConjuration",divination:"PF2E.TraitDivination",enchantment:"PF2E.TraitEnchantment",evocation:"PF2E.TraitEvocation",illusion:"PF2E.TraitIllusion",necromancy:"PF2E.TraitNecromancy",transmutation:"PF2E.TraitTransmutation"},spellTraits={...alignmentTraits,...classTraits,...damageTraits,...elementTraits,...magicSchools,...magicTraditions,...spellOtherTraits},weaponTraits={...alignmentTraits,...ancestryTraits,...elementTraits,...energyDamageTypes,...magicSchools,...magicTraditions,adjusted:"PF2E.TraitAdjusted",alchemical:"PF2E.TraitAlchemical",agile:"PF2E.TraitAgile",apex:"PF2E.TraitApex",artifact:"PF2E.TraitArtifact",attached:"PF2E.TraitAttached","attached-to-shield":"PF2E.TraitAttachedToShield","attached-to-crossbow-or-firearm":"PF2E.TraitAttachedToCrossbowOrFirearm",auditory:"PF2E.TraitAuditory",backstabber:"PF2E.TraitBackstabber",backswing:"PF2E.TraitBackswing",bomb:"PF2E.TraitBomb",brace:"PF2E.TraitBrace",brutal:"PF2E.TraitBrutal","capacity-2":"PF2E.TraitCapacity2","capacity-3":"PF2E.TraitCapacity3","capacity-4":"PF2E.TraitCapacity4","capacity-5":"PF2E.TraitCapacity5",climbing:"PF2E.TraitClimbing",clockwork:"PF2E.TraitClockwork",cobbled:"PF2E.TraitCobbled",combination:"PF2E.TraitCombination",concealable:"PF2E.TraitConcealable",concussive:"PF2E.TraitConcussive",consumable:"PF2E.TraitConsumable","critical-fusion":"PF2E.TraitCriticalFusion",cursed:"PF2E.TraitCursed","deadly-d4":"PF2E.TraitDeadlyD4","deadly-d6":"PF2E.TraitDeadlyD6","deadly-d8":"PF2E.TraitDeadlyD8","deadly-d10":"PF2E.TraitDeadlyD10","deadly-d12":"PF2E.TraitDeadlyD12",death:"PF2E.TraitDeath",disarm:"PF2E.TraitDisarm",disease:"PF2E.TraitDisease","double-barrel":"PF2E.TraitDoubleBarrel",emotion:"PF2E.TraitEmotion",extradimensional:"PF2E.TraitExtradimensional","fatal-aim-d10":"PF2E.TraitFatalAimD10","fatal-aim-d12":"PF2E.TraitFatalAimD12","fatal-d8":"PF2E.TraitFatalD8","fatal-d10":"PF2E.TraitFatalD10","fatal-d12":"PF2E.TraitFatalD12",fear:"PF2E.TraitFear",finesse:"PF2E.TraitFinesse",forceful:"PF2E.TraitForceful",fortune:"PF2E.TraitFortune","free-hand":"PF2E.TraitFreeHand",fungus:"PF2E.TraitFungus",grapple:"PF2E.TraitGrapple",hampering:"PF2E.TraitHampering",healing:"PF2E.TraitHealing",infused:"PF2E.TraitInfused",inhaled:"PF2E.TraitInhaled",injection:"PF2E.TraitInjection",intelligent:"PF2E.TraitIntelligent",invested:"PF2E.TraitInvested","jousting-d6":"PF2E.TraitJoustingD6",kickback:"PF2E.TraitKickback",light:"PF2E.TraitLight",magical:"PF2E.TraitMagical",mental:"PF2E.TraitMental",modular:"PF2E.TraitModular",monk:"PF2E.TraitMonk",nonlethal:"PF2E.TraitNonlethal",olfactory:"PF2E.TraitOlfactory",parry:"PF2E.TraitParry",plant:"PF2E.TraitPlant",poison:"PF2E.TraitPoison",propulsive:"PF2E.TraitPropulsive","ranged-trip":"PF2E.TraitRangedTrip",razing:"PF2E.TraitRazing",reach:"PF2E.TraitReach",recovery:"PF2E.TraitRecovery",relic:"PF2E.TraitRelic",repeating:"PF2E.TraitRepeating",resonant:"PF2E.TraitResonant",saggorak:"PF2E.TraitSaggorak","scatter-5":"PF2E.TraitScatter5","scatter-10":"PF2E.TraitScatter10","scatter-15":"PF2E.TraitScatter15","scatter-20":"PF2E.TraitScatter20",scrying:"PF2E.TraitScrying",shadow:"PF2E.TraitShadow",shove:"PF2E.TraitShove",splash:"PF2E.TraitSplash",staff:"PF2E.TraitStaff",sweep:"PF2E.TraitSweep",tech:"PF2E.TraitTech",teleportation:"PF2E.TraitTeleportation",tethered:"PF2E.TraitTethered",thrown:"PF2E.TraitThrown","thrown-10":"PF2E.TraitThrown10","thrown-15":"PF2E.TraitThrown15","thrown-20":"PF2E.TraitThrown20","thrown-30":"PF2E.TraitThrown30","thrown-40":"PF2E.TraitThrown40","thrown-60":"PF2E.TraitThrown60","thrown-80":"PF2E.TraitThrown80","thrown-100":"PF2E.TraitThrown100","thrown-200":"PF2E.TraitThrown200",training:"PF2E.TraitTraining",trip:"PF2E.TraitTrip",twin:"PF2E.TraitTwin","two-hand-d6":"PF2E.TraitTwoHandD6","two-hand-d8":"PF2E.TraitTwoHandD8","two-hand-d10":"PF2E.TraitTwoHandD10","two-hand-d12":"PF2E.TraitTwoHandD12",unarmed:"PF2E.TraitUnarmed",vehicular:"PF2E.TraitVehicular","versatile-acid":"PF2E.TraitVersatileAcid","versatile-b":"PF2E.TraitVersatileB","versatile-chaotic":"PF2E.TraitVersatileChaotic","versatile-cold":"PF2E.TraitVersatileCold","versatile-electricity":"PF2E.TraitVersatileElectricity","versatile-evil":"PF2E.TraitVersatileEvil","versatile-fire":"PF2E.TraitVersatileFire","versatile-force":"PF2E.TraitVersatileForce","versatile-good":"PF2E.TraitVersatileGood","versatile-lawful":"PF2E.TraitVersatileLawful","versatile-p":"PF2E.TraitVersatileP","versatile-poison":"PF2E.TraitVersatilePoison","versatile-s":"PF2E.TraitVersatileS","versatile-sonic":"PF2E.TraitVersatileSonic","versatile-vitality":"PF2E.TraitVersatileVitality","versatile-void":"PF2E.TraitVersatileVoid","volley-20":"PF2E.TraitVolley20","volley-30":"PF2E.TraitVolley30","volley-50":"PF2E.TraitVolley50"},preciousMaterials={abysium:"PF2E.PreciousMaterialAbysium",adamantine:"PF2E.PreciousMaterialAdamantine","cold-iron":"PF2E.PreciousMaterialColdIron",darkwood:"PF2E.PreciousMaterialDarkwood",djezet:"PF2E.PreciousMaterialDjezet",dragonhide:"PF2E.PreciousMaterialDragonhide","grisantian-pelt":"PF2E.PreciousMaterialGrisantianPelt",inubrix:"PF2E.PreciousMaterialInubrix","keep-stone":"PF2E.PreciousMaterialKeepStone",mithral:"PF2E.PreciousMaterialMithral",noqual:"PF2E.PreciousMaterialNoqual",orichalcum:"PF2E.PreciousMaterialOrichalcum",peachwood:"PF2E.PreciousMaterialPeachwood",siccatite:"PF2E.PreciousMaterialSiccatite",silver:"PF2E.PreciousMaterialSilver",sisterstone:"PF2E.PreciousMaterialSisterstone","sisterstone-dusk":"PF2E.PreciousMaterialSisterstoneDusk","sisterstone-scarlet":"PF2E.PreciousMaterialSisterstoneScarlet","sovereign-steel":"PF2E.PreciousMaterialSovereignSteel",warpglass:"PF2E.PreciousMaterialWarpglass"},otherArmorTags={shoddy:"PF2E.Item.Physical.OtherTag.Shoddy"},otherConsumableTags={herbal:"PF2E.Item.Physical.OtherTag.Herbal"},otherWeaponTags={crossbow:"PF2E.Weapon.Base.crossbow",improvised:"PF2E.Item.Physical.OtherTag.Improvised",shoddy:"PF2E.Item.Physical.OtherTag.Shoddy"},rangeTraits=mapToObj(RANGE_TRAITS,trait=>[trait,`PF2E.Trait${sluggify(trait,{camel:"bactrian"})}`]),npcAttackTraits={...weaponTraits,...preciousMaterials,...rangeTraits,curse:"PF2E.TraitCurse","deadly-2d8":"PF2E.TraitDeadly2D8","deadly-3d8":"PF2E.TraitDeadly3D8","deadly-4d8":"PF2E.TraitDeadly4D8","deadly-2d10":"PF2E.TraitDeadly2D10","deadly-3d10":"PF2E.TraitDeadly3D10","deadly-4d10":"PF2E.TraitDeadly4D10","deadly-2d12":"PF2E.TraitDeadly2D12","deadly-3d12":"PF2E.TraitDeadly3D12","deadly-4d12":"PF2E.TraitDeadly4D12",incorporeal:"PF2E.TraitIncorporeal",radiation:"PF2E.TraitRadiation","reach-0":"PF2E.TraitReach0","reach-10":"PF2E.TraitReach10","reach-15":"PF2E.TraitReach15","reach-20":"PF2E.TraitReach20","reach-25":"PF2E.TraitReach25","reach-30":"PF2E.TraitReach30","reach-40":"PF2E.TraitReach40","reach-50":"PF2E.TraitReach50","reach-60":"PF2E.TraitReach60","reach-100":"PF2E.TraitReach100","reach-120":"PF2E.TraitReach120","reach-200":"PF2E.TraitReach200","reach-1000":"PF2E.TraitReach1000","reload-0":"PF2E.TraitReload0","reload-1":"PF2E.TraitReload1","reload-2":"PF2E.TraitReload2","reload-1-min":"PF2E.TraitReload1Min"},featTraits={...ancestryTraits,...classTraits,...damageTraits,...magicSchools,...magicTraditions,...spellTraits,additive1:"PF2E.TraitAdditive1",additive2:"PF2E.TraitAdditive2",additive3:"PF2E.TraitAdditive3",aftermath:"PF2E.TraitAftermath",alchemical:"PF2E.TraitAlchemical",archetype:"PF2E.TraitArchetype",artifact:"PF2E.TraitArtifact",auditory:"PF2E.TraitAuditory",aura:"PF2E.TraitAura",circus:"PF2E.TraitCircus",class:"PF2E.Class",composite:"PF2E.TraitComposite",concentrate:"PF2E.TraitConcentrate",dedication:"PF2E.TraitDedication",detection:"PF2E.TraitDetection",deviant:"PF2E.TraitDeviant",downtime:"PF2E.TraitDowntime",emotion:"PF2E.TraitEmotion",evolution:"PF2E.TraitEvolution",esoterica:"PF2E.TraitEsoterica",exploration:"PF2E.TraitExploration",fear:"PF2E.TraitFear",finisher:"PF2E.TraitFinisher",flourish:"PF2E.TraitFlourish",fortune:"PF2E.TraitFortune",general:"PF2E.TraitGeneral",impulse:"PF2E.TraitImpulse",infusion:"PF2E.TraitInfusion",injury:"PF2E.TraitInjury",lineage:"PF2E.TraitLineage",manipulate:"PF2E.TraitManipulate",metamagic:"PF2E.TraitMetamagic",mindshift:"PF2E.TraitMindshift",modification:"PF2E.TraitModification",move:"PF2E.TraitMove",multiclass:"PF2E.TraitMulticlass",oath:"PF2E.TraitOath",olfactory:"PF2E.TraitOlfactory",open:"PF2E.TraitOpen",overflow:"PF2E.TraitOverflow","pervasive-magic":"PF2E.TraitPervasiveMagic",poison:"PF2E.TraitPoison",press:"PF2E.TraitPress",rage:"PF2E.TraitRage",reckless:"PF2E.TraitReckless",reflection:"PF2E.TraitReflection",secret:"PF2E.TraitSecret",skill:"PF2E.TraitSkill",social:"PF2E.TraitSocial",spellshot:"PF2E.TraitSpellshot",stamina:"PF2E.TraitStamina",stance:"PF2E.TraitStance",tandem:"PF2E.TraitTandem",time:"PF2E.TraitTime","true-name":"PF2E.TraitTrueName",unstable:"PF2E.TraitUnstable",vigilante:"PF2E.TraitVigilante",virulent:"PF2E.TraitVirulent",vitality:"PF2E.TraitVitality",void:"PF2E.TraitVoid"},consumableTraits={...damageTraits,...elementTraits,...magicSchools,...magicTraditions,additive1:"PF2E.TraitAdditive1",additive2:"PF2E.TraitAdditive2",additive3:"PF2E.TraitAdditive3",alchemical:"PF2E.TraitAlchemical",attack:"PF2E.TraitAttack",auditory:"PF2E.TraitAuditory",aura:"PF2E.TraitAura","bottled-breath":"PF2E.TraitBottledBreath",catalyst:"PF2E.TraitCatalyst",clockwork:"PF2E.TraitClockwork",consumable:"PF2E.TraitConsumable",contact:"PF2E.TraitContact",curse:"PF2E.TraitCurse",cursed:"PF2E.TraitCursed",drug:"PF2E.TraitDrug",elixir:"PF2E.TraitElixir",emotion:"PF2E.TraitEmotion",expandable:"PF2E.TraitExpandable",fear:"PF2E.TraitFear",fey:"PF2E.TraitFey",fortune:"PF2E.TraitFortune",fulu:"PF2E.TraitFulu",gadget:"PF2E.TraitGadget",healing:"PF2E.TraitHealing",incapacitation:"PF2E.TraitIncapacitation",infused:"PF2E.TraitInfused",ingested:"PF2E.TraitIngested",inhaled:"PF2E.TraitInhaled",injury:"PF2E.TraitInjury",kobold:"PF2E.TraitKobold",light:"PF2E.TraitLight",linguistic:"PF2E.TraitLinguistic",lozenge:"PF2E.TraitLozenge",magical:"PF2E.TraitMagical",mechanical:"PF2E.TraitMechanical",misfortune:"PF2E.TraitMisfortune",missive:"PF2E.TraitMissive",morph:"PF2E.TraitMorph",mutagen:"PF2E.TraitMutagen",oil:"PF2E.TraitOil",olfactory:"PF2E.TraitOlfactory",poison:"PF2E.TraitPoison",polymorph:"PF2E.TraitPolymorph",possession:"PF2E.TraitPossession",potion:"PF2E.TraitPotion",precious:"PF2E.TraitPrecious",processed:"PF2E.TraitProcessed",scroll:"PF2E.TraitScroll",scrying:"PF2E.TraitScrying",sleep:"PF2E.TraitSleep",snare:"PF2E.TraitSnare",spellgun:"PF2E.TraitSpellgun",splash:"PF2E.TraitSplash",structure:"PF2E.TraitStructure",talisman:"PF2E.TraitTalisman",teleportation:"PF2E.TraitTeleportation",trap:"PF2E.TraitTrap",virulent:"PF2E.TraitVirulent",visual:"PF2E.TraitVisual",wand:"PF2E.TraitWand"},actionTraits={...featTraits,...consumableTraits,...spellTraits,...pick$1(weaponTraits,["agile","propulsive","backswing","forceful","reach","sweep","thrown","volley-20","volley-30","volley-50"]),summon:"PF2E.TraitSummon"},hazardTraits={...damageTraits,...magicSchools,...magicTraditions,aberration:"PF2E.TraitAberration",alchemical:"PF2E.TraitAlchemical",animal:"PF2E.TraitAnimal",aquatic:"PF2E.TraitAquatic",auditory:"PF2E.TraitAuditory",beast:"PF2E.TraitBeast",clockwork:"PF2E.TraitClockwork",consumable:"PF2E.TraitConsumable",curse:"PF2E.TraitCurse",environmental:"PF2E.TraitEnvironmental",fungus:"PF2E.TraitFungus",haunt:"PF2E.TraitHaunt",inhaled:"PF2E.TraitInhaled",kaiju:"PF2E.TraitKaiju",magical:"PF2E.TraitMagical",mechanical:"PF2E.TraitMechanical",poison:"PF2E.TraitPoison",polymorph:"PF2E.TraitPolymorph",shadow:"PF2E.TraitShadow",steam:"PF2E.TraitSteam",summoned:"PF2E.TraitSummoned",technological:"PF2E.TraitTechnological",teleportation:"PF2E.TraitTeleportation",trap:"PF2E.TraitTrap",virulent:"PF2E.TraitVirulent",visual:"PF2E.TraitVisual"},vehicleTraits={...magicSchools,artifact:"PF2E.TraitArtifact",clockwork:"PF2E.TraitClockwork",magical:"PF2E.TraitMagical",teleportation:"PF2E.TraitTeleportation"},equipmentTraits={...alignmentTraits,...ancestryTraits,...elementTraits,...energyDamageTypes,...magicSchools,...magicTraditions,additive0:"PF2E.TraitAdditive0",additive1:"PF2E.TraitAdditive1",adjusted:"PF2E.TraitAdjusted",adjustment:"PF2E.TraitAdjustment",alchemical:"PF2E.TraitAlchemical",apex:"PF2E.TraitApex",artifact:"PF2E.TraitArtifact",auditory:"PF2E.TraitAuditory",aura:"PF2E.TraitAura",barding:"PF2E.TraitBarding",censer:"PF2E.TraitCenser",clockwork:"PF2E.TraitClockwork",coda:"PF2E.TraitCoda",companion:"PF2E.TraitCompanion",contract:"PF2E.TraitContract",consecration:"PF2E.TraitConsecration",cursed:"PF2E.TraitCursed",darkness:"PF2E.TraitDarkness",death:"PF2E.TraitDeath",detection:"PF2E.TraitDetection",eidolon:"PF2E.TraitEidolon",emotion:"PF2E.TraitEmotion",expandable:"PF2E.TraitExpandable",extradimensional:"PF2E.TraitExtradimensional",fear:"PF2E.TraitFear",figurehead:"PF2E.TraitFigurehead",focused:"PF2E.TraitFocused",fortune:"PF2E.TraitFortune",fulu:"PF2E.TraitFulu",gadget:"PF2E.TraitGadget",grimoire:"PF2E.TraitGrimoire","harrow-court":"PF2E.TraitHarrowCourt",healing:"PF2E.TraitHealing",incapacitation:"PF2E.TraitIncapacitation",incorporeal:"PF2E.TraitIncorporeal",infused:"PF2E.TraitInfused",intelligent:"PF2E.TraitIntelligent",invested:"PF2E.TraitInvested",light:"PF2E.TraitLight",magical:"PF2E.TraitMagical",mechanical:"PF2E.TraitMechanical",mental:"PF2E.TraitMental",misfortune:"PF2E.TraitMisfortune",morph:"PF2E.TraitMorph",mounted:"PF2E.TraitMounted",nonlethal:"PF2E.TraitNonlethal",plant:"PF2E.TraitPlant",poison:"PF2E.TraitPoison",polymorph:"PF2E.TraitPolymorph",portable:"PF2E.TraitPortable",precious:"PF2E.TraitPrecious",prediction:"PF2E.TraitPrediction",relic:"PF2E.TraitRelic",revelation:"PF2E.TraitRevelation",saggorak:"PF2E.TraitSaggorak",scrying:"PF2E.TraitScrying",shadow:"PF2E.TraitShadow",sleep:"PF2E.TraitSleep",spellgun:"PF2E.TraitSpellgun",spellheart:"PF2E.TraitSpellheart",staff:"PF2E.TraitStaff",steam:"PF2E.TraitSteam",structure:"PF2E.TraitStructure",tattoo:"PF2E.TraitTattoo",teleportation:"PF2E.TraitTeleportation",visual:"PF2E.TraitVisual",wand:"PF2E.TraitWand"},shieldTraits={"deflecting-bludgeoning":"PF2E.TraitDeflectingBludgeoning","deflecting-physical-ranged":"PF2E.TraitDeflectingPhysicalRanged","deflecting-piercing":"PF2E.TraitDeflectingPiercing","deflecting-slashing":"PF2E.TraitDeflectingSlashing",foldaway:"PF2E.TraitFoldaway",harnessed:"PF2E.TraitHarnessed","hefty-14":"PF2E.TraitHefty14",inscribed:"PF2E.TraitInscribed","integrated-1d6-b":"PF2E.TraitIntegrated1d6B","integrated-1d6-p":"PF2E.TraitIntegrated1d6P","integrated-1d6-s":"PF2E.TraitIntegrated1d6S","integrated-1d6-s-versatile-p":"PF2E.TraitIntegrated1d6SVersatileP","launching-dart":"PF2E.TraitLaunching","shield-throw-20":"PF2E.TraitShieldThrow20","shield-throw-30":"PF2E.TraitShieldThrow30"},armorTraits={...alignmentTraits,...elementTraits,...magicSchools,...magicTraditions,...shieldTraits,adjusted:"PF2E.TraitAdjusted",alchemical:"PF2E.TraitAlchemical",apex:"PF2E.TraitApex",aquadynamic:"PF2E.TraitAquadynamic",artifact:"PF2E.TraitArtifact",auditory:"PF2E.TraitAuditory",aura:"PF2E.TraitAura",barding:"PF2E.TraitBarding",bulwark:"PF2E.TraitBulwark",clockwork:"PF2E.TraitClockwork",comfort:"PF2E.TraitComfort",companion:"PF2E.TraitCompanion",cursed:"PF2E.TraitCursed","entrench-melee":"PF2E.TraitEntrenchMelee","entrench-ranged":"PF2E.TraitEntrenchRanged",extradimensional:"PF2E.TraitExtradimensional",focused:"PF2E.TraitFocused",force:"PF2E.TraitForce",flexible:"PF2E.TraitFlexible",healing:"PF2E.TraitHealing",hindering:"PF2E.TraitHindering",inscribed:"PF2E.TraitInscribed",intelligent:"PF2E.TraitIntelligent",invested:"PF2E.TraitInvested",laminar:"PF2E.TraitLaminar",light:"PF2E.TraitLight",magical:"PF2E.TraitMagical",noisy:"PF2E.TraitNoisy",plant:"PF2E.TraitPlant",ponderous:"PF2E.TraitPonderous"},rangeDescriptions=mapToObj(RANGE_TRAITS,trait=>[trait,"PF2E.TraitDescriptionRange"]),preciousMaterialDescriptions={abysium:"PF2E.PreciousMaterialAbysiumDescription",adamantine:"PF2E.PreciousMaterialAdamantineDescription","cold-iron":"PF2E.PreciousMaterialColdIronDescription",darkwood:"PF2E.PreciousMaterialDarkwoodDescription",djezet:"PF2E.PreciousMaterialDjezetDescription",dragonhide:"PF2E.PreciousMaterialDragonhideDescription","grisantian-pelt":"PF2E.PreciousMaterialGrisantianPeltDescription",inubrix:"PF2E.PreciousMaterialInubrixDescription",mithral:"PF2E.PreciousMaterialMithralDescription",noqual:"PF2E.PreciousMaterialNoqualDescription",orichalcum:"PF2E.PreciousMaterialOrichalcumDescription",siccatite:"PF2E.PreciousMaterialSiccatiteDescription",silver:"PF2E.PreciousMaterialSilverDescription",sisterstone:"PF2E.PreciousMaterialSisterstoneDescription","sisterstone-dusk":"PF2E.PreciousMaterialSisterstoneDescription","sisterstone-scarlet":"PF2E.PreciousMaterialSisterstoneDescription","sovereign-steel":"PF2E.PreciousMaterialSovereignSteelDescription",warpglass:"PF2E.PreciousMaterialWarpglassDescription"},traitDescriptions={aasimar:"PF2E.TraitDescriptionAasimar",aberration:"PF2E.TraitDescriptionAberration",abjuration:"PF2E.TraitDescriptionAbjuration",acid:"PF2E.TraitDescriptionAcid",additive0:"PF2E.TraitDescriptionAdditive",additive1:"PF2E.TraitDescriptionAdditive",additive2:"PF2E.TraitDescriptionAdditive",additive3:"PF2E.TraitDescriptionAdditive",adjusted:"PF2E.TraitDescriptionAdjusted",adjustment:"PF2E.TraitDescriptionAdjustment",aeon:"PF2E.TraitDescriptionAeon",aesir:"PF2E.TraitDescriptionAesir",aftermath:"PF2E.TraitDescriptionAftermath",agathion:"PF2E.TraitDescriptionAgathion",agile:"PF2E.TraitDescriptionAgile",air:"PF2E.TraitDescriptionAir",alchemical:"PF2E.TraitDescriptionAlchemical",alchemist:"PF2E.TraitDescriptionAlchemist",amphibious:"PF2E.TraitDescriptionAmphibious",anadi:"PF2E.TraitDescriptionAnadi",android:"PF2E.TraitDescriptionAndroid",apex:"PF2E.TraitDescriptionApex",aphorite:"PF2E.TraitDescriptionAphorite",aquadynamic:"PF2E.TraitDescriptionAquadynamic",arcane:"PF2E.TraitDescriptionArcane",archetype:"PF2E.TraitDescriptionArchetype",ardande:"PF2E.TraitDescriptionArdande",artifact:"PF2E.TraitDescriptionArtifact",attached:"PF2E.TraitDescriptionAttached","attached-to-crossbow-or-firearm":"PF2E.TraitDescriptionAttached","attached-to-shield":"PF2E.TraitDescriptionAttached",attack:"PF2E.TraitDescriptionAttack",auditory:"PF2E.TraitDescriptionAuditory",aura:"PF2E.TraitDescriptionAura",automaton:"PF2E.TraitDescriptionAutomaton",azarketi:"PF2E.TraitDescriptionAzarketi",backstabber:"PF2E.TraitDescriptionBackstabber",backswing:"PF2E.TraitDescriptionBackswing",barbarian:"PF2E.TraitDescriptionBarbarian",bard:"PF2E.TraitDescriptionBard",beastkin:"PF2E.TraitDescriptionBeastkin",bomb:"PF2E.TraitDescriptionBomb","bottled-breath":"PF2E.TraitDescriptionBottledBreath",brace:"PF2E.TraitDescriptionBrace",brutal:"PF2E.TraitDescriptionBrutal",bulwark:"PF2E.TraitDescriptionBulwark",cantrip:"PF2E.TraitDescriptionCantrip","capacity-2":"PF2E.TraitDescriptionCapacity","capacity-3":"PF2E.TraitDescriptionCapacity","capacity-4":"PF2E.TraitDescriptionCapacity","capacity-5":"PF2E.TraitDescriptionCapacity",catalyst:"PF2E.TraitDescriptionCatalyst",catfolk:"PF2E.TraitDescriptionCatfolk",censer:"PF2E.TraitDescriptionCenser",champion:"PF2E.TraitDescriptionChampion",changeling:"PF2E.TraitDescriptionChangeling",chaotic:"PF2E.TraitDescriptionChaotic",class:"PF2E.TraitDescriptionClass",cleric:"PF2E.TraitDescriptionCleric",climbing:"PF2E.TraitDescriptionClimbing",clockwork:"PF2E.TraitDescriptionClockwork",cobbled:"PF2E.TraitDescriptionCobbled",coda:"PF2E.TraitDescriptionCoda",cold:"PF2E.TraitDescriptionCold",combination:"PF2E.TraitDescriptionCombination",comfort:"PF2E.TraitDescriptionComfort",common:"PF2E.TraitDescriptionCommon",companion:"PF2E.TraitDescriptionCompanion",complex:"PF2E.TraitDescriptionComplex",composite:"PF2E.TraitDescriptionComposite",composition:"PF2E.TraitDescriptionComposition",concealable:"PF2E.TraitDescriptionConcealable",concentrate:"PF2E.TraitDescriptionConcentrate",concussive:"PF2E.TraitDescriptionConcussive",conjuration:"PF2E.TraitDescriptionConjuration",conrasu:"PF2E.TraitDescriptionConrasu",consecration:"PF2E.TraitDescriptionConsecration",consumable:"PF2E.TraitDescriptionConsumable",contact:"PF2E.TraitDescriptionContact",contingency:"PF2E.TraitDescriptionContingency",contract:"PF2E.TraitDescriptionContract","critical-fusion":"PF2E.TraitDescriptionCriticalFusion",curse:"PF2E.TraitDescriptionCurse",cursebound:"PF2E.TraitDescriptionCursebound",cursed:"PF2E.TraitDescriptionCursed",darkness:"PF2E.TraitDescriptionDarkness",darvakka:"PF2E.TraitDescriptionDarvakka","deadly-2d10":"PF2E.TraitDescriptionDeadly","deadly-2d12":"PF2E.TraitDescriptionDeadly","deadly-2d8":"PF2E.TraitDescriptionDeadly","deadly-3d10":"PF2E.TraitDescriptionDeadly","deadly-3d12":"PF2E.TraitDescriptionDeadly","deadly-3d8":"PF2E.TraitDescriptionDeadly","deadly-4d10":"PF2E.TraitDescriptionDeadly","deadly-4d12":"PF2E.TraitDescriptionDeadly","deadly-4d8":"PF2E.TraitDescriptionDeadly","deadly-d10":"PF2E.TraitDescriptionDeadly","deadly-d12":"PF2E.TraitDescriptionDeadly","deadly-d6":"PF2E.TraitDescriptionDeadly","deadly-d8":"PF2E.TraitDescriptionDeadly","deadly-d4":"PF2E.TraitDescriptionDeadly",death:"PF2E.TraitDescriptionDeath","deflecting-bludgeoning":"PF2E.TraitDescriptionDeflecting","deflecting-physical-ranged":"PF2E.TraitDescriptionDeflecting","deflecting-slashing":"PF2E.TraitDescriptionDeflecting",dedication:"PF2E.TraitDescriptionDedication",detection:"PF2E.TraitDescriptionDetection",deviant:"PF2E.TraitDescriptionDeviant",dhampir:"PF2E.TraitDescriptionDhampir",disarm:"PF2E.TraitDescriptionDisarm",disease:"PF2E.TraitDescriptionDisease",divination:"PF2E.TraitDescriptionDivination",divine:"PF2E.TraitDescriptionDivine","double-barrel":"PF2E.TraitDescriptionDoubleBarrel",downtime:"PF2E.TraitDescriptionDowntime",drug:"PF2E.TraitDescriptionDrug",druid:"PF2E.TraitDescriptionDruid",duskwalker:"PF2E.TraitDescriptionDuskwalker",dwarf:"PF2E.TraitDescriptionDwarf",earth:"PF2E.TraitDescriptionEarth",eidolon:"PF2E.TraitDescriptionEidolon",electricity:"PF2E.TraitDescriptionElectricity",elf:"PF2E.TraitDescriptionElf",elixir:"PF2E.TraitDescriptionElixir",emotion:"PF2E.TraitDescriptionEmotion",enchantment:"PF2E.TraitDescriptionEnchantment","entrench-melee":"PF2E.TraitDescriptionEntrench","entrench-ranged":"PF2E.TraitDescriptionEntrench",environment:"PF2E.TraitDescriptionEnvironment",esoterica:"PF2E.TraitDescriptionEsoterica",evil:"PF2E.TraitDescriptionEvil",evocation:"PF2E.TraitDescriptionEvocation",evolution:"PF2E.TraitDescriptionEvolution",expandable:"PF2E.TraitDescriptionExpandable",exploration:"PF2E.TraitDescriptionExploration",extradimensional:"PF2E.TraitDescriptionExtradimensional","fatal-aim-d10":"PF2E.TraitDescriptionFatalAim","fatal-aim-d12":"PF2E.TraitDescriptionFatalAim","fatal-d10":"PF2E.TraitDescriptionFatal","fatal-d12":"PF2E.TraitDescriptionFatal","fatal-d8":"PF2E.TraitDescriptionFatal",fear:"PF2E.TraitDescriptionFear",fetchling:"PF2E.TraitDescriptionFetchling",fey:"PF2E.TraitDescriptionFey",fighter:"PF2E.TraitDescriptionFighter",figurehead:"PF2E.TraitDescriptionFigurehead",finesse:"PF2E.TraitDescriptionFinesse",finisher:"PF2E.TraitDescriptionFinisher",fire:"PF2E.TraitDescriptionFire",fleshwarp:"PF2E.TraitDescriptionFleshwarp",flexible:"PF2E.TraitDescriptionFlexible",flourish:"PF2E.TraitDescriptionFlourish",focused:"PF2E.TraitDescriptionFocused",foldaway:"PF2E.TraitDescriptionFoldaway",force:"PF2E.TraitDescriptionForce",forceful:"PF2E.TraitDescriptionForceful",fortune:"PF2E.TraitDescriptionFortune","free-hand":"PF2E.TraitDescriptionFreeHand",fulu:"PF2E.TraitDescriptionFulu",fungus:"PF2E.TraitDescriptionFungus",gadget:"PF2E.TraitDescriptionGadget",ganzi:"PF2E.TraitDescriptionGanzi",general:"PF2E.TraitDescriptionGeneral",genie:"PF2E.TraitDescriptionGenie",geniekin:"PF2E.TraitDescriptionGeniekin",ghoran:"PF2E.TraitDescriptionGhoran",ghul:"PF2E.TraitDescriptionGhul",gnoll:"PF2E.TraitDescriptionGnoll",gnome:"PF2E.TraitDescriptionGnome",goblin:"PF2E.TraitDescriptionGoblin",goloma:"PF2E.TraitDescriptionGoloma",good:"PF2E.TraitDescriptionGood",grapple:"PF2E.TraitDescriptionGrapple",grimoire:"PF2E.TraitDescriptionGrimoire",grippli:"PF2E.TraitDescriptionGrippli",gunslinger:"PF2E.TraitDescriptionGunslinger",halfling:"PF2E.TraitDescriptionHalfling","half-elf":"PF2E.TraitDescriptionHalfElf","half-orc":"PF2E.TraitDescriptionHalfOrc","jousting-d6":"PF2E.TraitDescriptionJousting",hampering:"PF2E.TraitDescriptionHampering",harnessed:"PF2E.TraitDescriptionHarnessed",haunt:"PF2E.TraitDescriptionHaunt",healing:"PF2E.TraitDescriptionHealing","hefty-14":"PF2E.TraitDescriptionHefty",hex:"PF2E.TraitDescriptionHex",hindering:"PF2E.TraitDescriptionHindering",hobgoblin:"PF2E.TraitDescriptionHobgoblin",human:"PF2E.TraitDescriptionHuman",humanoid:"PF2E.TraitDescriptionHumanoid",ifrit:"PF2E.TraitDescriptionIfrit",illusion:"PF2E.TraitDescriptionIllusion",impulse:"PF2E.TraitDescriptionImpulse",incapacitation:"PF2E.TraitDescriptionIncapacitation",incarnate:"PF2E.TraitDescriptionIncarnate",incorporeal:"PF2E.TraitDescriptionIncorporeal",infused:"PF2E.TraitDescriptionInfused",infusion:"PF2E.TraitDescriptionInfusion",ingested:"PF2E.TraitDescriptionIngested",inhaled:"PF2E.TraitDescriptionInhaled",injection:"PF2E.TraitDescriptionInjection",injury:"PF2E.TraitDescriptionInjury",inscribed:"PF2E.TraitDescriptionInscribed","integrated-1d6-b":"PF2E.TraitDescriptionIntegrated","integrated-1d6-p":"PF2E.TraitDescriptionIntegrated","integrated-1d6-s":"PF2E.TraitDescriptionIntegrated","integrated-1d6-s-versatile-p":"PF2E.TraitDescriptionIntegrated",intelligent:"PF2E.TraitDescriptionIntelligent",inventor:"PF2E.TraitDescriptionInventor",invested:"PF2E.TraitDescriptionInvested",investigator:"PF2E.TraitDescriptionInvestigator",kashrishi:"PF2E.TraitDescriptionKashrishi","keep-stone":"PF2E.PreciousMaterialKeepStoneDescription",kickback:"PF2E.TraitDescriptionKickback",kineticist:"PF2E.TraitDescriptionKineticist",kitsune:"PF2E.TraitDescriptionKitsune",kobold:"PF2E.TraitDescriptionKobold",laminar:"PF2E.TraitDescriptionLaminar","launching-dart":"PF2E.TraitDescriptionLaunching",lawful:"PF2E.TraitDescriptionLawful",leshy:"PF2E.TraitDescriptionLeshy",light:"PF2E.TraitDescriptionLight",linguistic:"PF2E.TraitDescriptionLinguistic",litany:"PF2E.TraitDescriptionLitany",lizardfolk:"PF2E.TraitDescriptionLizardfolk",lozenge:"PF2E.TraitDescriptionLozenge",magical:"PF2E.TraitDescriptionMagical",magus:"PF2E.TraitDescriptionMagus",manipulate:"PF2E.TraitDescriptionManipulate",mechanical:"PF2E.TraitDescriptionMechanical",mental:"PF2E.TraitDescriptionMental",metal:"PF2E.TraitDescriptionMetal",metamagic:"PF2E.TraitDescriptionMetamagic",mindless:"PF2E.TraitDescriptionMindless",mindshift:"PF2E.TraitDescriptionMindshift",minion:"PF2E.TraitDescriptionMinion",misfortune:"PF2E.TraitDescriptionMisfortune",missive:"PF2E.TraitDescriptionMissive",modification:"PF2E.TraitDescriptionModification",modular:"PF2E.TraitDescriptionModular",monk:"PF2E.TraitDescriptionMonk",morph:"PF2E.TraitDescriptionMorph",mounted:"PF2E.TraitDescriptionMounted",move:"PF2E.TraitDescriptionMove",multiclass:"PF2E.TraitDescriptionMulticlass",mutagen:"PF2E.TraitDescriptionMutagen",nagaji:"PF2E.TraitDescriptionNagaji",necromancy:"PF2E.TraitDescriptionNecromancy",noisy:"PF2E.TraitDescriptionNoisy",nonlethal:"PF2E.TraitDescriptionNonlethal",oath:"PF2E.TraitDescriptionOath",occult:"PF2E.TraitDescriptionOccult",oil:"PF2E.TraitDescriptionOil",olfactory:"PF2E.TraitDescriptionOlfactory",open:"PF2E.TraitDescriptionOpen",oracle:"PF2E.TraitDescriptionOracle",orc:"PF2E.TraitDescriptionOrc",oread:"PF2E.TraitDescriptionOread",overflow:"PF2E.TraitDescriptionOverflow",parry:"PF2E.TraitDescriptionParry",peachwood:"PF2E.PreciousMaterialPeachwoodDescription",plant:"PF2E.TraitDescriptionPlant",poison:"PF2E.TraitDescriptionPoison",polymorph:"PF2E.TraitDescriptionPolymorph",ponderous:"PF2E.TraitDescriptionPonderous",poppet:"PF2E.TraitDescriptionPoppet",portable:"PF2E.TraitDescriptionPortable",possession:"PF2E.TraitDescriptionPossession",potion:"PF2E.TraitDescriptionPotion",precious:"PF2E.TraitDescriptionPrecious",prediction:"PF2E.TraitDescriptionPrediction",press:"PF2E.TraitDescriptionPress",primal:"PF2E.TraitDescriptionPrimal",propulsive:"PF2E.TraitDescriptionPropulsive",psyche:"PF2E.TraitDescriptionPsyche",psychic:"PF2E.TraitDescriptionPsychic",radiation:"PF2E.TraitDescriptionRadiation",rage:"PF2E.TraitDescriptionRage",ranger:"PF2E.TraitDescriptionRanger",...rangeDescriptions,"ranged-trip":"PF2E.TraitDescriptionRangedTrip",rare:"PF2E.TraitDescriptionRare",ratfolk:"PF2E.TraitDescriptionRatfolk",razing:"PF2E.TraitDescriptionRazing",reach:"PF2E.TraitDescriptionReach","reach-0":"PF2E.TraitDescriptionReach","reach-10":"PF2E.TraitDescriptionReach","reach-100":"PF2E.TraitDescriptionReach","reach-120":"PF2E.TraitDescriptionReach","reach-1000":"PF2E.TraitDescriptionReach","reach-15":"PF2E.TraitDescriptionReach","reach-20":"PF2E.TraitDescriptionReach","reach-200":"PF2E.TraitDescriptionReach","reach-25":"PF2E.TraitDescriptionReach","reach-30":"PF2E.TraitDescriptionReach","reach-40":"PF2E.TraitDescriptionReach","reach-50":"PF2E.TraitDescriptionReach","reach-60":"PF2E.TraitDescriptionReach",recovery:"PF2E.TraitDescriptionRecovery",reflection:"PF2E.TraitDescriptionReflection",relic:"PF2E.TraitDescriptionRelic",reload:"PF2E.TraitDescriptionReload","reload-0":"PF2E.TraitDescriptionReload","reload-1":"PF2E.TraitDescriptionReload","reload-1-min":"PF2E.TraitDescriptionReload","reload-2":"PF2E.TraitDescriptionReload",repeating:"PF2E.TraitDescriptionRepeating",resonant:"PF2E.TraitDescriptionResonant",revelation:"PF2E.TraitDescriptionRevelation",rogue:"PF2E.TraitDescriptionRogue",saggorak:"PF2E.TraitDescriptionSaggorak","scatter-10":"PF2E.TraitDescriptionScatter","scatter-15":"PF2E.TraitDescriptionScatter","scatter-20":"PF2E.TraitDescriptionScatter","scatter-5":"PF2E.TraitDescriptionScatter",scroll:"PF2E.TraitDescriptionScroll",scrying:"PF2E.TraitDescriptionScrying",secret:"PF2E.TraitDescriptionSecret",shadow:"PF2E.TraitDescriptionShadow","shield-throw-20":"PF2E.TraitDescriptionShieldThrow","shield-throw-30":"PF2E.TraitDescriptionShieldThrow",shisk:"PF2E.TraitDescriptionShisk",shoony:"PF2E.TraitDescriptionShoony",shove:"PF2E.TraitDescriptionShove",skeleton:"PF2E.TraitDescriptionSkeleton",skill:"PF2E.TraitDescriptionSkill",sleep:"PF2E.TraitDescriptionSleep",snare:"PF2E.TraitDescriptionSnare",social:"PF2E.TraitDescriptionSocial",sonic:"PF2E.TraitDescriptionSonic",sorcerer:"PF2E.TraitDescriptionSorcerer",spellgun:"PF2E.TraitDescriptionSpellgun",spellheart:"PF2E.TraitDescriptionSpellheart",spellshot:"PF2E.TraitNoDescription",splash:"PF2E.TraitDescriptionSplash","splash-10":"PF2E.TraitDescriptionSplash10",sprite:"PF2E.TraitDescriptionSprite",staff:"PF2E.TraitDescriptionStaff",stance:"PF2E.TraitDescriptionStance",steam:"PF2E.TraitDescriptionSteam",strix:"PF2E.TraitDescriptionStrix",structure:"PF2E.TraitDescriptionStructure",suli:"PF2E.TraitDescriptionSuli",summon:"PF2E.TraitDescriptionSummon",summoned:"PF2E.TraitDescriptionSummoned",summoner:"PF2E.TraitDescriptionSummoner",swashbuckler:"PF2E.TraitDescriptionSwashbuckler",sweep:"PF2E.TraitDescriptionSweep",sylph:"PF2E.TraitDescriptionSylph",talisman:"PF2E.TraitDescriptionTalisman",talos:"PF2E.TraitDescriptionTalos",tandem:"PF2E.TraitDescriptionTandem",tattoo:"PF2E.TraitDescriptionTattoo",tech:"PF2E.TraitDescriptionTech",telepathy:"PF2E.TraitDescriptionTelepathy",teleportation:"PF2E.TraitDescriptionTeleportation",tengu:"PF2E.TraitDescriptionTengu",tethered:"PF2E.TraitDescriptionTethered",thaumaturge:"PF2E.TraitDescriptionThaumaturge",thrown:"PF2E.TraitDescriptionThrown","thrown-10":"PF2E.TraitDescriptionThrown","thrown-100":"PF2E.TraitDescriptionThrown","thrown-15":"PF2E.TraitDescriptionThrown","thrown-20":"PF2E.TraitDescriptionThrown","thrown-200":"PF2E.TraitDescriptionThrown","thrown-25":"PF2E.TraitDescriptionThrown","thrown-30":"PF2E.TraitDescriptionThrown","thrown-40":"PF2E.TraitDescriptionThrown","thrown-50":"PF2E.TraitDescriptionThrown","thrown-60":"PF2E.TraitDescriptionThrown","thrown-80":"PF2E.TraitDescriptionThrown",tiefling:"PF2E.TraitDescriptionTiefling",time:"PF2E.TraitDescriptionTime",training:"PF2E.TraitDescriptionTraining",transmutation:"PF2E.TraitDescriptionTransmutation",trap:"PF2E.TraitDescriptionTrap",trip:"PF2E.TraitDescriptionTrip","true-name":"PF2E.TraitDescriptionTrueName",twin:"PF2E.TraitDescriptionTwin","two-hand-d10":"PF2E.TraitDescriptionTwoHand","two-hand-d12":"PF2E.TraitDescriptionTwoHand","two-hand-d6":"PF2E.TraitDescriptionTwoHand","two-hand-d8":"PF2E.TraitDescriptionTwoHand",unarmed:"PF2E.TraitDescriptionUnarmed",uncommon:"PF2E.TraitDescriptionUncommon",undine:"PF2E.TraitDescriptionUndine",unique:"PF2E.TraitDescriptionUnique",unstable:"PF2E.TraitDescriptionUnstable",vanara:"PF2E.TraitDescriptionVanara",vishkanya:"PF2E.TraitDescriptionVishkanya",vehicular:"PF2E.TraitDescriptionVehicular","versatile-acid":"PF2E.TraitDescriptionVersatile","versatile-b":"PF2E.TraitDescriptionVersatile","versatile-chaotic":"PF2E.TraitDescriptionVersatile","versatile-cold":"PF2E.TraitDescriptionVersatile","versatile-electricity":"PF2E.TraitDescriptionVersatile","versatile-evil":"PF2E.TraitDescriptionVersatile","versatile-fire":"PF2E.TraitDescriptionVersatile","versatile-force":"PF2E.TraitDescriptionVersatile","versatile-good":"PF2E.TraitDescriptionVersatile","versatile-lawful":"PF2E.TraitDescriptionVersatile","versatile-p":"PF2E.TraitDescriptionVersatile","versatile-poison":"PF2E.TraitDescriptionVersatile","versatile-s":"PF2E.TraitDescriptionVersatile","versatile-sonic":"PF2E.TraitDescriptionVersatile","versatile-vitality":"PF2E.TraitDescriptionVersatile","versatile-void":"PF2E.TraitDescriptionVersatile",virulent:"PF2E.TraitDescriptionVirulent",visual:"PF2E.TraitDescriptionVisual",vitality:"PF2E.TraitDescriptionVitality",void:"PF2E.TraitDescriptionVoid","volley-20":"PF2E.TraitDescriptionVolley","volley-30":"PF2E.TraitDescriptionVolley","volley-50":"PF2E.TraitDescriptionVolley",wand:"PF2E.TraitDescriptionWand",water:"PF2E.TraitDescriptionWater",witch:"PF2E.TraitDescriptionWitch",wizard:"PF2E.TraitDescriptionWizard",wood:"PF2E.TraitDescriptionWood",...preciousMaterialDescriptions},kingmakerTraits={...actionTraits,army:"PF2E.Kingmaker.Trait.army",cavalry:"PF2E.Kingmaker.Trait.cavalry",civic:"PF2E.Kingmaker.Trait.civic",commerce:"PF2E.Kingmaker.Trait.commerce",infantry:"PF2E.Kingmaker.Trait.infantry",kingdom:"PF2E.Kingmaker.Trait.kingdom",leadership:"PF2E.Kingmaker.Trait.leadership",maneuver:"PF2E.Kingmaker.Trait.maneuver",morale:"PF2E.Kingmaker.Trait.morale",region:"PF2E.Kingmaker.Trait.region",siege:"PF2E.Kingmaker.Trait.siege",skirmisher:"PF2E.Kingmaker.Trait.skirmisher",upkeep:"PF2E.Kingmaker.Trait.upkeep"},damageCategoriesUnique={persistent:"PF2E.ConditionTypePersistentShort",precision:"PF2E.Damage.Precision",splash:"PF2E.TraitSplash"},materialDamageEffects=pick$1(preciousMaterials,["abysium","adamantine","cold-iron","darkwood","djezet","inubrix","keep-stone","mithral","noqual","orichalcum","peachwood","siccatite","silver","sisterstone-dusk","sisterstone-scarlet","sovereign-steel","warpglass"]),damageCategories={...damageCategoriesUnique,...materialDamageEffects,alignment:"PF2E.Alignment",energy:"PF2E.TraitEnergy",physical:"PF2E.TraitPhysical"},physicalDamageTypes={bleed:"PF2E.TraitBleed",bludgeoning:"PF2E.TraitBludgeoning",piercing:"PF2E.TraitPiercing",slashing:"PF2E.TraitSlashing"},damageTypes={...alignmentTraits,...energyDamageTypes,...physicalDamageTypes,mental:"PF2E.TraitMental",poison:"PF2E.TraitPoison",spirit:"PF2E.TraitSpirit",untyped:"PF2E.TraitUntyped"},damageRollFlavors=[...DAMAGE_TYPES].reduce((result,key)=>(result[key]=`PF2E.Damage.RollFlavor.${key}`,result),{}),materialIWR=mapValues$1(omit(materialDamageEffects,["keep-stone","peachwood","sisterstone-dusk","sisterstone-scarlet","sovereign-steel","warpglass"]),(_v,k)=>`PF2E.Damage.IWR.Type.${k}`),immunityTypes={...materialIWR,acid:"PF2E.Damage.RollFlavor.acid",air:"PF2E.Damage.RollFlavor.air","area-damage":"PF2E.Damage.IWR.Type.area-damage",auditory:"PF2E.Damage.IWR.Type.auditory",bleed:"PF2E.Damage.RollFlavor.bleed",blinded:"PF2E.Damage.IWR.Type.blinded",bludgeoning:"PF2E.Damage.RollFlavor.bludgeoning",chaotic:"PF2E.Damage.RollFlavor.chaotic",clumsy:"PF2E.Damage.IWR.Type.clumsy",cold:"PF2E.Damage.RollFlavor.cold",confused:"PF2E.Damage.IWR.Type.confused",conjuration:"PF2E.Damage.IWR.Type.conjuration",controlled:"PF2E.Damage.IWR.Type.controlled","critical-hits":"PF2E.Damage.IWR.Type.critical-hits",curse:"PF2E.Damage.IWR.Type.curse",custom:"",darkwood:"PF2E.Damage.IWR.Type.darkwood",dazzled:"PF2E.Damage.IWR.Type.dazzled",deafened:"PF2E.Damage.IWR.Type.deafened","death-effects":"PF2E.Damage.IWR.Type.death-effects",disease:"PF2E.Damage.IWR.Type.disease",doomed:"PF2E.Damage.IWR.Type.doomed",drained:"PF2E.Damage.IWR.Type.drained",earth:"PF2E.Damage.RollFlavor.earth",electricity:"PF2E.Damage.RollFlavor.electricity",emotion:"PF2E.Damage.IWR.Type.emotion",enchantment:"PF2E.Damage.IWR.Type.enchantment",energy:"PF2E.Damage.IWR.Type.energy",enfeebled:"PF2E.Damage.IWR.Type.enfeebled",evil:"PF2E.Damage.RollFlavor.evil",evocation:"PF2E.Damage.IWR.Type.evocation",fascinated:"PF2E.Damage.IWR.Type.fascinated",fatigued:"PF2E.Damage.IWR.Type.fatigued","fear-effects":"PF2E.Damage.IWR.Type.fear-effects",fire:"PF2E.Damage.RollFlavor.fire",fleeing:"PF2E.Damage.IWR.Type.fleeing",force:"PF2E.Damage.RollFlavor.force",frightened:"PF2E.Damage.IWR.Type.frightened",good:"PF2E.Damage.RollFlavor.good",grabbed:"PF2E.Damage.IWR.Type.grabbed",healing:"PF2E.Damage.IWR.Type.healing",illusion:"PF2E.Damage.IWR.Type.illusion",immobilized:"PF2E.Damage.IWR.Type.immobilized",inhaled:"PF2E.Damage.IWR.Type.inhaled",lawful:"PF2E.Damage.RollFlavor.lawful",light:"PF2E.Damage.IWR.Type.light",magic:"PF2E.Damage.IWR.Type.magic",mental:"PF2E.Damage.RollFlavor.mental",metal:"PF2E.Damage.IWR.Type.metal","misfortune-effects":"PF2E.Damage.IWR.Type.misfortune-effects",necromancy:"PF2E.Damage.IWR.Type.necromancy","non-magical":"PF2E.Damage.IWR.Type.non-magical","nonlethal-attacks":"PF2E.Damage.IWR.Type.nonlethal-attacks","object-immunities":"PF2E.Damage.IWR.Type.object-immunities","off-guard":"PF2E.Damage.IWR.Type.off-guard",olfactory:"PF2E.Damage.IWR.Type.olfactory",paralyzed:"PF2E.Damage.IWR.Type.paralyzed","persistent-damage":"PF2E.Damage.IWR.Type.persistent-damage",petrified:"PF2E.Damage.IWR.Type.petrified",physical:"PF2E.Damage.IWR.Type.physical",piercing:"PF2E.Damage.RollFlavor.piercing",plant:"PF2E.Damage.IWR.Type.plant",poison:"PF2E.Damage.RollFlavor.poison",polymorph:"PF2E.Damage.IWR.Type.polymorph",possession:"PF2E.Damage.IWR.Type.possession",precision:"PF2E.Damage.RollFlavor.precision",prone:"PF2E.Damage.IWR.Type.prone",radiation:"PF2E.Damage.IWR.Type.radiation",restrained:"PF2E.Damage.IWR.Type.restrained","salt-water":"PF2E.Damage.IWR.Type.salt-water",scrying:"PF2E.Damage.IWR.Type.scrying",sickened:"PF2E.Damage.IWR.Type.sickened",slashing:"PF2E.Damage.RollFlavor.slashing",sleep:"PF2E.Damage.IWR.Type.sleep",slowed:"PF2E.Damage.IWR.Type.slowed",sonic:"PF2E.Damage.RollFlavor.sonic","spell-deflection":"PF2E.Damage.IWR.Type.spell-deflection",spirit:"PF2E.Damage.RollFlavor.spirit",stunned:"PF2E.Damage.IWR.Type.stunned",stupefied:"PF2E.Damage.IWR.Type.stupefied","swarm-attacks":"PF2E.Damage.IWR.Type.swarm-attacks","swarm-mind":"PF2E.Damage.IWR.Type.swarm-mind",transmutation:"PF2E.Damage.IWR.Type.transmutation",trip:"PF2E.Damage.IWR.Type.trip","unarmed-attacks":"PF2E.Damage.IWR.Type.unarmed-attacks",unconscious:"PF2E.Damage.IWR.Type.unconscious",visual:"PF2E.Damage.IWR.Type.visual",vitality:"PF2E.Damage.RollFlavor.vitality",void:"PF2E.Damage.RollFlavor.void",water:"PF2E.Damage.IWR.Type.water",wood:"PF2E.Damage.IWR.Type.wood",wounded:"PF2E.Damage.IWR.Type.wounded"},weaknessTypes={...materialIWR,acid:"PF2E.Damage.RollFlavor.acid",air:"PF2E.Damage.RollFlavor.air","area-damage":"PF2E.Damage.IWR.Type.area-damage","arrow-vulnerability":"PF2E.Damage.IWR.Type.arrow-vulnerability","axe-vulnerability":"PF2E.Damage.IWR.Type.axe-vulnerability",bleed:"PF2E.Damage.RollFlavor.bleed",bludgeoning:"PF2E.Damage.RollFlavor.bludgeoning",chaotic:"PF2E.Damage.RollFlavor.chaotic",cold:"PF2E.Damage.RollFlavor.cold","critical-hits":"PF2E.Damage.IWR.Type.critical-hits",custom:"",earth:"PF2E.Damage.RollFlavor.earth",electricity:"PF2E.Damage.RollFlavor.electricity",emotion:"PF2E.Damage.IWR.Type.emotion",energy:"PF2E.Damage.IWR.Type.energy",evil:"PF2E.Damage.RollFlavor.evil",fire:"PF2E.Damage.RollFlavor.fire",force:"PF2E.Damage.RollFlavor.force","ghost-touch":"PF2E.Damage.IWR.Type.ghost-touch",glass:"PF2E.Damage.IWR.Type.glass",good:"PF2E.Damage.RollFlavor.good",lawful:"PF2E.Damage.RollFlavor.lawful",light:"PF2E.Damage.IWR.Type.light",magical:"PF2E.Damage.IWR.Type.magical",mental:"PF2E.Damage.RollFlavor.mental",metal:"PF2E.Damage.RollFlavor.metal","non-magical":"PF2E.Damage.IWR.Type.non-magical","nonlethal-attacks":"PF2E.Damage.IWR.Type.nonlethal-attacks",physical:"PF2E.Damage.IWR.Type.physical",piercing:"PF2E.Damage.RollFlavor.piercing",plant:"PF2E.Damage.IWR.Type.plant",poison:"PF2E.Damage.RollFlavor.poison",precision:"PF2E.Damage.RollFlavor.precision",radiation:"PF2E.Damage.IWR.Type.radiation",salt:"PF2E.Damage.IWR.Type.salt","salt-water":"PF2E.Damage.IWR.Type.salt-water",slashing:"PF2E.Damage.RollFlavor.slashing",sonic:"PF2E.Damage.RollFlavor.sonic",spells:"PF2E.Damage.IWR.Type.spells",spirit:"PF2E.Damage.RollFlavor.spirit","splash-damage":"PF2E.Damage.IWR.Type.splash-damage","unarmed-attacks":"PF2E.Damage.IWR.Type.unarmed-attacks","vampire-weaknesses":"PF2E.Damage.IWR.Type.vampire-weaknesses",vitality:"PF2E.Damage.RollFlavor.vitality",void:"PF2E.Damage.RollFlavor.void",vorpal:"PF2E.Damage.IWR.Type.vorpal","vorpal-fear":"PF2E.Damage.IWR.Type.vorpal-fear","vulnerable-to-sunlight":"PF2E.Damage.IWR.Type.vulnerable-to-sunlight",water:"PF2E.Damage.IWR.Type.water",weapons:"PF2E.Damage.IWR.Type.weapons","weapons-shedding-bright-light":"PF2E.Damage.IWR.Type.weapons-shedding-bright-light",wood:"PF2E.Damage.IWR.Type.wood"},resistanceTypes={...materialIWR,acid:"PF2E.Damage.RollFlavor.acid",air:"PF2E.Damage.RollFlavor.air","all-damage":"PF2E.Damage.IWR.Type.all-damage","area-damage":"PF2E.Damage.IWR.Type.area-damage",bleed:"PF2E.Damage.RollFlavor.bleed",bludgeoning:"PF2E.Damage.RollFlavor.bludgeoning",chaotic:"PF2E.Damage.RollFlavor.chaotic",cold:"PF2E.Damage.RollFlavor.cold","critical-hits":"PF2E.Damage.IWR.Type.critical-hits",custom:"","damage-from-spells":"PF2E.Damage.IWR.Type.damage-from-spells",earth:"PF2E.Damage.RollFlavor.earth",electricity:"PF2E.Damage.RollFlavor.electricity",energy:"PF2E.Damage.IWR.Type.energy",evil:"PF2E.Damage.RollFlavor.evil",fire:"PF2E.Damage.RollFlavor.fire",force:"PF2E.Damage.RollFlavor.force","ghost-touch":"PF2E.Damage.IWR.Type.ghost-touch",good:"PF2E.Damage.RollFlavor.good",lawful:"PF2E.Damage.RollFlavor.lawful",light:"PF2E.Damage.IWR.Type.light",magical:"PF2E.Damage.IWR.Type.magical",mental:"PF2E.Damage.RollFlavor.mental",metal:"PF2E.Damage.RollFlavor.metal","non-magical":"PF2E.Damage.IWR.Type.non-magical",nonlethal:"PF2E.Damage.IWR.Type.nonlethal","nonlethal-attacks":"PF2E.Damage.IWR.Type.nonlethal-attacks",physical:"PF2E.Damage.IWR.Type.physical",piercing:"PF2E.Damage.RollFlavor.piercing",plant:"PF2E.Damage.IWR.Type.plant",poison:"PF2E.Damage.RollFlavor.poison",precision:"PF2E.Damage.RollFlavor.precision","protean-anatomy":"PF2E.Damage.IWR.Type.protean-anatomy",radiation:"PF2E.Damage.IWR.Type.radiation",salt:"PF2E.Damage.IWR.Type.salt","salt-water":"PF2E.Damage.IWR.Type.salt-water",slashing:"PF2E.Damage.RollFlavor.slashing",sonic:"PF2E.Damage.RollFlavor.sonic",spells:"PF2E.Damage.IWR.Type.spells",spirit:"PF2E.Damage.RollFlavor.spirit","unarmed-attacks":"PF2E.Damage.IWR.Type.unarmed-attacks",vitality:"PF2E.Damage.RollFlavor.vitality",void:"PF2E.Damage.RollFlavor.void",vorpal:"PF2E.Damage.IWR.Type.vorpal","vorpal-adamantine":"PF2E.Damage.IWR.Type.vorpal-adamantine",water:"PF2E.Damage.IWR.Type.water",weapons:"PF2E.Damage.IWR.Type.weapons","weapons-shedding-bright-light":"PF2E.Damage.IWR.Type.weapons-shedding-bright-light",wood:"PF2E.Damage.IWR.Type.wood"},ATTRIBUTE_ABBREVIATIONS=new Set(["str","dex","con","int","wis","cha"]),CREATURE_ACTOR_TYPES=["character","npc","familiar"],SAVE_TYPES=["fortitude","reflex","will"],IMMUNITY_TYPES=new Set(Object.keys(immunityTypes)),WEAKNESS_TYPES=new Set(Object.keys(weaknessTypes)),RESISTANCE_TYPES=new Set(Object.keys(resistanceTypes)),UNAFFECTED_TYPES=new Set(["bleed","good","evil","lawful","chaotic","spirit","vitality","void"]),SKILL_ABBREVIATIONS=new Set(["acr","arc","ath","cra","dec","dip","itm","med","nat","occ","prf","rel","soc","ste","sur","thi"]),SKILL_DICTIONARY={acr:"acrobatics",arc:"arcana",ath:"athletics",cra:"crafting",dec:"deception",dip:"diplomacy",itm:"intimidation",med:"medicine",nat:"nature",occ:"occultism",prf:"performance",rel:"religion",soc:"society",ste:"stealth",sur:"survival",thi:"thievery"},SKILL_LONG_FORMS=new Set(Object.values(SKILL_DICTIONARY));Object.fromEntries(Object.entries(SKILL_DICTIONARY).map(([abbrev,value])=>[value,abbrev])),[...SAVE_TYPES,...SKILL_LONG_FORMS];const SKILL_EXPANDED={acrobatics:{attribute:"dex",shortForm:"acr"},arcana:{attribute:"int",shortForm:"arc"},athletics:{attribute:"str",shortForm:"ath"},crafting:{attribute:"int",shortForm:"cra"},deception:{attribute:"cha",shortForm:"dec"},diplomacy:{attribute:"cha",shortForm:"dip"},intimidation:{attribute:"cha",shortForm:"itm"},medicine:{attribute:"wis",shortForm:"med"},nature:{attribute:"wis",shortForm:"nat"},occultism:{attribute:"int",shortForm:"occ"},performance:{attribute:"cha",shortForm:"prf"},religion:{attribute:"wis",shortForm:"rel"},society:{attribute:"int",shortForm:"soc"},stealth:{attribute:"dex",shortForm:"ste"},survival:{attribute:"wis",shortForm:"sur"},thievery:{attribute:"dex",shortForm:"thi"}},MOVEMENT_TYPES=["land","burrow","climb","fly","swim"],SIZE_LINKABLE_ACTOR_TYPES=new Set([...CREATURE_ACTOR_TYPES,"vehicle"]),_Migration672RemoveNPCBaseProperties=class extends MigrationBase{static{__name(this,"_Migration672RemoveNPCBaseProperties")}removeBase(property,replace="value"){property[replace]=Number(property[replace])||0,typeof property.base=="number"&&(property[replace]=property.base,"game"in globalThis?property["-=base?"]=null:delete property.base)}async updateActor(actorSource){if(actorSource.type!=="npc")return;const{ac,hp,perception}=actorSource.system.attributes;this.removeBase(ac),this.removeBase(hp,"max"),this.removeBase(perception);const{saves}=actorSource.system;for(const saveType of SAVE_TYPES)this.removeBase(saves[saveType])}async updateItem(itemSource,actorSource){actorSource?.type==="npc"&&itemSource.type==="lore"&&this.removeBase(itemSource.system.mod)}};__name2(_Migration672RemoveNPCBaseProperties,"Migration672RemoveNPCBaseProperties"),__publicField(_Migration672RemoveNPCBaseProperties,"version",.672);let Migration672RemoveNPCBaseProperties=_Migration672RemoveNPCBaseProperties;const _Migration673RemoveBulwarkREs=class extends MigrationBase{static{__name(this,"_Migration673RemoveBulwarkREs")}hasRuleElement(rules){return rules.some(r=>typeof r.key=="string"&&r.key.endsWith("FlatModifier")&&isObject(r.predicate)&&!!r.predicate.all?.includes("self:armor:trait:bulwark"))}async updateItem(item){const{rules}=item.system;if(item.type==="armor"){const index=rules.findIndex(rule=>typeof rule.key=="string"&&rule.key.endsWith("FlatModifier")&&rule.selector==="reflex"&&rule.type==="ability"&&/bulwark/i.test(String(rule.label??"")));index!==-1&&rules.splice(index)}const slug=item.system.slug??sluggify(item.name);if(item.type==="feat"&&slug==="mighty-bulwark"&&!this.hasRuleElement(rules)){const newRules=[{key:"FlatModifier",predicate:{all:["self:armor:trait:bulwark"]},selector:"reflex",type:"untyped",value:4},{key:"RollOption",domain:"reflex",option:"self:armor:bulwark-all"}];rules.push(...newRules)}}};__name2(_Migration673RemoveBulwarkREs,"Migration673RemoveBulwarkREs"),__publicField(_Migration673RemoveBulwarkREs,"version",.673);let Migration673RemoveBulwarkREs=_Migration673RemoveBulwarkREs;const HOMEBREW_TRAIT_KEYS=["creatureTraits","featTraits","languages","magicSchools","spellTraits","weaponCategories","weaponGroups","baseWeapons","weaponTraits","equipmentTraits"],SECONDARY_TRAIT_RECORDS={creatureTraits:["ancestryItemTraits"],equipmentTraits:["armorTraits","consumableTraits"],featTraits:["actionTraits"],weaponTraits:["npcAttackTraits"],magicSchools:["spellTraits"]};function itemIsOfType(item,...types){return types.some(t=>t==="physical"?setHasElement(PHYSICAL_ITEM_TYPES,item.type):item.type===t)}__name(itemIsOfType,"itemIsOfType"),__name2(itemIsOfType,"itemIsOfType");function reduceItemName(label){return label.includes(":")?label.replace(/^[^:]+:\s*|\s*\([^)]+\)$/g,""):label}__name(reduceItemName,"reduceItemName"),__name2(reduceItemName,"reduceItemName");const{fields:fields$2}=foundry.data,_LaxSchemaField=class extends fields$2.SchemaField{static{__name(this,"_LaxSchemaField")}_cleanType(data,options={}){options.source=options.source||data;for(const[name2,field]of this.entries())!(name2 in data)&&options.partial||(data[name2]=field.clean(data[name2],options),data[name2]===void 0&&delete data[name2]);return data}};__name2(_LaxSchemaField,"LaxSchemaField");let LaxSchemaField=_LaxSchemaField;const _StrictSchemaField=class extends fields$2.SchemaField{static{__name(this,"_StrictSchemaField")}_cast(value){return value}_cleanType(data,options){if(!isObject$1(data))throw Error(`${this.name} is not an object`);return super._cleanType(data,options)}};__name2(_StrictSchemaField,"StrictSchemaField");let StrictSchemaField=_StrictSchemaField;const _StrictStringField=class extends fields$2.StringField{static{__name(this,"_StrictStringField")}_cast(value){return value}};__name2(_StrictStringField,"StrictStringField");let StrictStringField=_StrictStringField;const _StrictNumberField=class extends fields$2.NumberField{static{__name(this,"_StrictNumberField")}_cast(value){return value}};__name2(_StrictNumberField,"StrictNumberField");let StrictNumberField=_StrictNumberField;const _StrictBooleanField=class extends fields$2.BooleanField{static{__name(this,"_StrictBooleanField")}_cast(value){return value}};__name2(_StrictBooleanField,"StrictBooleanField");let StrictBooleanField=_StrictBooleanField;const _StrictArrayField=class extends fields$2.ArrayField{static{__name(this,"_StrictArrayField")}_cast(value){return value}_cleanType(value){return value&&super._cleanType(value)}};__name2(_StrictArrayField,"StrictArrayField");let StrictArrayField=_StrictArrayField;const _StrictObjectField=class extends fields$2.ObjectField{static{__name(this,"_StrictObjectField")}_cast(value){return value}};__name2(_StrictObjectField,"StrictObjectField");let StrictObjectField=_StrictObjectField;const _DataUnionField=class extends fields$2.DataField{static{__name(this,"_DataUnionField")}fields;constructor(fields2,options){super(options),this.fields=fields2}_cast(value){return typeof value=="string"&&(value=value.trim()),value}clean(value,options){return Array.isArray(value)&&this.fields.some(f=>f instanceof foundry.data.fields.ArrayField)?this.fields.find(f=>f instanceof StrictArrayField)?.clean(value,options)??value:super.clean(value,options)}validate(value,options){const{DataModelValidationFailure}=foundry.data.validation,{StringField}=foundry.data.fields;for(const field of this.fields)if(!(field.validate(value,options)instanceof DataModelValidationFailure)){if(field instanceof StringField&&typeof value!="string")continue;return}return this.fields[0].validate(value,options)}initialize(value,model,options){return this.fields.find(f=>!f.validate(value))?.initialize(value,model,options)}};__name2(_DataUnionField,"DataUnionField");let DataUnionField=_DataUnionField;const _SlugField=class extends StrictStringField{static{__name(this,"_SlugField")}constructor(options={}){options.blank=!1,options.camel??=null,super(options)}static get _defaults(){return{...super._defaults,nullable:!0,initial:null,camel:null}}_cleanType(value,options){const slug=super._cleanType(value,options),camel=this.options.camel??null;return typeof slug=="string"?sluggify(slug,{camel}):slug}};__name2(_SlugField,"SlugField");let SlugField=_SlugField;const _PredicateStatementField=class extends fields$2.DataField{static{__name(this,"_PredicateStatementField")}constructor(options={}){super({...options,required:!0,nullable:!1,initial:void 0,validationError:"must be recognized predicated statement type"})}_validateType(value){return StatementValidator.isStatement(value)}_cast(value){return value}_cleanType(value){return typeof value=="string"?value.trim():value}};__name2(_PredicateStatementField,"PredicateStatementField");let PredicateStatementField=_PredicateStatementField;const _PredicateField=class extends StrictArrayField{static{__name(this,"_PredicateField")}constructor(options={}){super(new PredicateStatementField,{label:"PF2E.RuleEditor.General.Predicate",...options})}initialize(value,model,options){const statements=super.initialize(value,model,options);return statements&&new PredicatePF2e(...statements)}};__name2(_PredicateField,"PredicateField");let PredicateField=_PredicateField;const _RecordField=class extends fields$2.ObjectField{static{__name(this,"_RecordField")}keyField;valueField;constructor(keyField,valueField,options){if(super(options),!this._isValidKeyFieldType(keyField))throw new Error("key field must be a StringField or a NumberField");if(this.keyField=keyField,!(valueField instanceof fields$2.DataField))throw new Error(`${this.name} must have a DataField as its contained field`);this.valueField=valueField}_isValidKeyFieldType(keyField){if(keyField instanceof fields$2.StringField||keyField instanceof fields$2.NumberField){if(keyField.options.required!==!0||keyField.options.nullable===!0)throw new Error("key field must be required and non-nullable");return!0}return!1}_validateValues(values,options){const validationFailure=foundry.data.validation.DataModelValidationFailure,failures=new validationFailure;for(const[key,value]of Object.entries(values)){if(key.startsWith("-=")&&options?.partial)continue;const keyFailure=this.keyField.validate(key,options);keyFailure&&failures.elements.push({id:key,failure:keyFailure});const valueFailure=this.valueField.validate(value,options);valueFailure&&failures.elements.push({id:`${key}-value`,failure:valueFailure})}if(failures.elements.length)return failures}_cleanType(values,options){for(const[key,value]of Object.entries(values))values[key]=this.valueField.clean(value,options);return values}_validateType(values,options){return isObject$1(values)?this._validateValues(values,options):new foundry.data.validation.DataModelValidationFailure({message:"must be an Object"})}initialize(values,model,options){if(!values)return values;const data={};for(const[key,value]of Object.entries(values))data[key]=this.valueField.initialize(value,model,options);return data}};__name2(_RecordField,"RecordField"),__publicField(_RecordField,"recursive",!0);let RecordField=_RecordField;const _RuleElementPF2e=class extends foundry.abstract.DataModel{static{__name(this,"_RuleElementPF2e")}constructor(source,options){source.label??=options.parent.name,super(source,{parent:options.parent,strict:options.strict??!0,fallback:!1}),__privateAdd(this,_resolveBracketedValue),__publicField(this,"sourceIndex"),__publicField(this,"suppressWarnings");const{item}=this;if(this.suppressWarnings=options.suppressWarnings??!this.actor.id,this.sourceIndex=options.sourceIndex??null,!tupleHasValue(this.constructor.validActorTypes,item.actor.type)){const actorType=game.i18n.localize(`TYPES.Actor.${item.actor.type}`);this.failValidation(`this rule element type cannot be applied to a ${actorType}`),source.ignored=!0}this.label=typeof source.label=="string"?game.i18n.localize(this.resolveInjectedProperties(source.label)):item.name,this.invalid?this.ignored=!0:item instanceof PhysicalItemPF2e?(this.requiresEquipped=!!(source.requiresEquipped??!0),this.requiresInvestment=item.isInvested===null?null:!!(source.requiresInvestment??this.requiresEquipped),this.ignored===!1&&(this.ignored=!!this.requiresEquipped&&!item.isEquipped||item.system.equipped.carryType==="dropped"||!!this.requiresInvestment&&!item.isInvested)):(this.requiresEquipped=null,this.requiresInvestment=null)}static defineSchema(){const{fields:fields2}=foundry.data;return{key:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:void 0}),slug:new SlugField({required:!0,nullable:!0,label:"PF2E.RuleEditor.General.Slug"}),label:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:void 0,label:"PF2E.RuleEditor.General.Label"}),priority:new fields2.NumberField({required:!0,nullable:!1,integer:!0,initial:100}),ignored:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),predicate:new PredicateField,requiresEquipped:new fields2.BooleanField({required:!1,nullable:!0,initial:void 0}),requiresInvestment:new fields2.BooleanField({required:!1,nullable:!0,initial:void 0})}}static get schema(){if(this._schema&&Object.hasOwn(this,"_schema"))return this._schema;const schema=new LaxSchemaField(Object.freeze(this.defineSchema()));return schema.name=this.name,Object.defineProperty(this,"_schema",{value:schema,writable:!1}),schema}get item(){return this.parent}get actor(){return this.parent.actor}get token(){const actor=this.actor;if(actor.token)return actor.token;const tokens=actor.getActiveTokens();return tokens.find(token=>token.controlled)?.document??tokens.shift()?.document??null}getReducedLabel(label=this.label){return reduceItemName(label)}validate(options={}){try{return super.validate(options)}catch(error){if(error instanceof foundry.data.validation.DataModelValidationError){const message=error.message.replace(/validation errors|Joint Validation Error/,`validation errors on item ${this.item.name} (${this.item.uuid})`);return console.warn(message),!1}else throw error}}test(rollOptions){if(this.ignored)return!1;if(this.predicate.length===0)return!0;const optionSet=new Set([...rollOptions??this.actor.getRollOptions(),...this.item.getRollOptions("parent")]);return this.resolveInjectedProperties(this.predicate).test(optionSet)}failValidation(...message){const fullMessage=message.join(" "),{name:name2,uuid}=this.item;if(!this.suppressWarnings){const ruleName=game.i18n.localize(`PF2E.RuleElement.${this.key}`);this.actor.synthetics.preparationWarnings.add(`PF2e System | ${ruleName} rules element on item ${name2} (${uuid}) failed to validate: ${fullMessage}`)}this.ignored=!0}resolveInjectedProperties(source,{warn=!0}={}){if(source===null||typeof source=="number"||typeof source=="string"&&!source.includes("{"))return source;if(Array.isArray(source))for(let i=0;i{const data=key==="rule"?this:key==="actor"||key==="item"?this[key]:this.item,value=getProperty(data,prop);return value===void 0&&(this.ignored=!0,warn&&this.failValidation(`Failed to resolve injected property "${source}"`)),String(value)});return source}resolveValue(value,defaultValue=0,{evaluate=!0,resolvables={},warn=!0}={}){if(value??=defaultValue??null,typeof value=="number"||typeof value=="boolean"||value===null)return value;value=this.resolveInjectedProperties(value,{warn});const resolvedFromBracket=this.isBracketedValue(value)?__privateMethod(this,_resolveBracketedValue,resolveBracketedValue_fn).call(this,value,defaultValue):value;if(typeof resolvedFromBracket=="number")return resolvedFromBracket;if(resolvedFromBracket instanceof Object)return defaultValue instanceof Object?mergeObject(defaultValue,resolvedFromBracket,{inplace:!1}):resolvedFromBracket;if(typeof resolvedFromBracket=="string"){const saferEval=__name2(formula=>{try{const unresolveds=formula.match(/@[a-z.]+/gi)??[];if(unresolveds.length>0){const shouldWarn=warn&&!unresolveds.every(u=>u.startsWith("@target.")||u.startsWith("@actor.conditions."));return this.ignored=!0,shouldWarn&&this.failValidation(`Failed to resolve all components of formula, "${formula}"`),Number(defaultValue)}return Roll.safeEval(formula)}catch{return this.failValidation(`Error thrown while attempting to evaluate formula, "${formula}"`),0}},"saferEval");this.actor.isOfType("character")&&(resolvables.armor=this.actor.wornArmor);const trimmed=resolvedFromBracket.trim();return(trimmed.includes("@")||/^\d+$/.test(trimmed))&&evaluate?saferEval(Roll.replaceFormulaData(trimmed,{actor:this.actor,item:this.item,...resolvables})):trimmed}return defaultValue}isBracketedValue(value){return isObject(value)&&Array.isArray(value.brackets)&&(typeof value.field=="string"||!("fields"in value))}};_resolveBracketedValue=new WeakSet,resolveBracketedValue_fn=__name2(function(value,defaultValue){const bracketNumber=(()=>{if(!value.field)return this.actor.level;const field=String(value.field),separator=field.indexOf("|"),source=field.substring(0,separator),{actor,item}=this;switch(source){case"actor":return Number(getProperty(actor,field.substring(separator+1)))||0;case"item":return Number(getProperty(item,field.substring(separator+1)))||0;case"rule":return Number(getProperty(this,field.substring(separator+1)))||0;default:return Number(getProperty(actor,field.substring(0)))||0}})(),brackets=value.brackets??[],bracketFallthrough=(()=>{switch(typeof defaultValue){case"number":case"boolean":case"object":return defaultValue;case"string":return Number.isNaN(Number(defaultValue))?defaultValue:Number(defaultValue);default:return null}})();return brackets.find(bracket=>{const start=bracket.start??0,end=bracket.end??1/0;return start<=bracketNumber&&end>=bracketNumber})?.value??bracketFallthrough},"#resolveBracketedValue"),__name2(_RuleElementPF2e,"RuleElementPF2e"),__publicField(_RuleElementPF2e,"validActorTypes",["character","familiar","hazard","npc","party","vehicle"]);let RuleElementPF2e=_RuleElementPF2e;const _ResolvableValueField=class extends foundry.data.fields.DataField{static{__name(this,"_ResolvableValueField")}constructor(){super(...arguments),__privateAdd(this,_coerceNumber)}_validateType(value){return value!==null&&["string","number","object","boolean"].includes(typeof value)}_cast(value){return value}_cleanType(value){if(typeof value=="string")return __privateMethod(this,_coerceNumber,coerceNumber_fn).call(this,value);if(isObject(value)&&"brackets"in value){value.field||="actor|level";const brackets=value.brackets=compact(Object.values(value.brackets??{}));for(const bracket of brackets)bracket.start===null&&delete bracket.start,bracket.end===null&&delete bracket.end,bracket.value=typeof bracket.value=="string"?__privateMethod(this,_coerceNumber,coerceNumber_fn).call(this,bracket.value):bracket.value}return value}};_coerceNumber=new WeakSet,coerceNumber_fn=__name2(function(value){const trimmed=value.trim();return/^\d+(?:\.\d+)?$/.test(trimmed)?Number(trimmed):trimmed||0},"#coerceNumber"),__name2(_ResolvableValueField,"ResolvableValueField");let ResolvableValueField=_ResolvableValueField;const _ActorTraitsRuleElement=class extends RuleElementPF2e{static{__name(this,"_ActorTraitsRuleElement")}constructor(data,options){super({...data,priority:99},options),__privateAdd(this,_traitsDictionary),__privateAdd(this,_handleModeAffectingTrait)}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),add:new fields2.ArrayField(new fields2.StringField({required:!0,nullable:!1,blank:!1})),remove:new fields2.ArrayField(new fields2.StringField({required:!0,nullable:!1,blank:!1}))}}beforePrepareData(){if(this.test()&&this.actor.system.traits){const traits=this.actor.system.traits,newTraits=this.resolveInjectedProperties(this.add).filter(t=>!traits.value.includes(t)),traitsDictionary=__privateGet(this,_traitsDictionary,traitsDictionary_get);for(const trait of newTraits){if(!(trait in traitsDictionary))return this.failValidation(`${trait} is not a recognized trait`);traits.value.push(trait),this.actor.rollOptions.all[`self:trait:${trait}`]=!0,["construct","undead"].includes(trait)&&__privateMethod(this,_handleModeAffectingTrait,handleModeAffectingTrait_fn).call(this)}const toRemoves=this.resolveInjectedProperties(this.remove);for(const trait of toRemoves)traits.value=traits.value.filter(t=>t!==trait),delete this.actor.rollOptions.all[`self:trait:${trait}`],["construct","undead"].includes(trait)&&__privateMethod(this,_handleModeAffectingTrait,handleModeAffectingTrait_fn).call(this)}}};_traitsDictionary=new WeakSet,traitsDictionary_get=__name2(function(){switch(this.actor.type){case"character":case"familiar":case"npc":return CONFIG.PF2E.creatureTraits;case"hazard":return CONFIG.PF2E.hazardTraits;case"vehicle":return CONFIG.PF2E.vehicleTraits;default:throw ErrorPF2e("unexpected actor type")}},"#traitsDictionary"),_handleModeAffectingTrait=new WeakSet,handleModeAffectingTrait_fn=__name2(function(){const{actor}=this,{rollOptions}=actor;for(const mode of["construct","living","undead"])delete rollOptions.all[`self:mode:${mode}`];rollOptions.all[`self:mode:${actor.modeOfBeing}`]=!0},"#handleModeAffectingTrait"),__name2(_ActorTraitsRuleElement,"ActorTraitsRuleElement"),__publicField(_ActorTraitsRuleElement,"validActorTypes",["character","npc","familiar","hazard","vehicle"]);let ActorTraitsRuleElement=_ActorTraitsRuleElement;const _DegreeOfSuccess=class{static{__name(this,"_DegreeOfSuccess")}constructor(roll,dc,dosAdjustments=null){__privateAdd(this,_getDegreeAdjustment),__privateAdd(this,_adjustDegreeOfSuccess),__privateAdd(this,_adjustDegreeByDieValue),__privateAdd(this,_calculateDegreeOfSuccess),__publicField(this,"value"),__publicField(this,"unadjusted"),__publicField(this,"adjustment"),__publicField(this,"dieResult"),__publicField(this,"rollTotal"),__publicField(this,"dc"),roll instanceof Roll?(this.dieResult=(roll.isDeterministic?roll.terms.find(t=>t instanceof NumericTerm):roll.dice.find(d=>d instanceof Die&&d.faces===20))?.total??1,this.rollTotal=roll.total):(this.dieResult=roll.dieValue,this.rollTotal=roll.dieValue+roll.modifier),this.dc=typeof dc=="number"?{value:dc}:dc,this.unadjusted=__privateMethod(this,_calculateDegreeOfSuccess,calculateDegreeOfSuccess_fn).call(this),this.adjustment=__privateMethod(this,_getDegreeAdjustment,getDegreeAdjustment_fn).call(this,this.unadjusted,dosAdjustments),this.value=this.adjustment?__privateMethod(this,_adjustDegreeOfSuccess,adjustDegreeOfSuccess_fn).call(this,this.adjustment.amount,this.unadjusted):this.unadjusted}};_getDegreeAdjustment=new WeakSet,getDegreeAdjustment_fn=__name2(function(degree,adjustments){if(!adjustments)return null;for(const outcome of["all",...DEGREE_OF_SUCCESS_STRINGS]){const{label,amount}=adjustments[outcome]??{};if(amount&&label&&!(degree===_DegreeOfSuccess.CRITICAL_SUCCESS&&amount===DEGREE_ADJUSTMENT_AMOUNTS.INCREASE)&&!(degree===_DegreeOfSuccess.CRITICAL_FAILURE&&amount===DEGREE_ADJUSTMENT_AMOUNTS.LOWER)&&(outcome==="all"||DEGREE_OF_SUCCESS_STRINGS.indexOf(outcome)===degree))return{label,amount}}return null},"#getDegreeAdjustment"),_adjustDegreeOfSuccess=new WeakSet,adjustDegreeOfSuccess_fn=__name2(function(amount,degreeOfSuccess){switch(amount){case"criticalFailure":return 0;case"failure":return 1;case"success":return 2;case"criticalSuccess":return 3;default:return Math.clamped(degreeOfSuccess+amount,0,3)}},"#adjustDegreeOfSuccess"),_adjustDegreeByDieValue=new WeakSet,adjustDegreeByDieValue_fn=__name2(function(degree){return this.dieResult===20?__privateMethod(this,_adjustDegreeOfSuccess,adjustDegreeOfSuccess_fn).call(this,DEGREE_ADJUSTMENT_AMOUNTS.INCREASE,degree):this.dieResult===1?__privateMethod(this,_adjustDegreeOfSuccess,adjustDegreeOfSuccess_fn).call(this,DEGREE_ADJUSTMENT_AMOUNTS.LOWER,degree):degree},"#adjustDegreeByDieValue"),_calculateDegreeOfSuccess=new WeakSet,calculateDegreeOfSuccess_fn=__name2(function(){const dc=this.dc.value;return this.rollTotal-dc>=10?__privateMethod(this,_adjustDegreeByDieValue,adjustDegreeByDieValue_fn).call(this,_DegreeOfSuccess.CRITICAL_SUCCESS):dc-this.rollTotal>=10?__privateMethod(this,_adjustDegreeByDieValue,adjustDegreeByDieValue_fn).call(this,_DegreeOfSuccess.CRITICAL_FAILURE):this.rollTotal>=dc?__privateMethod(this,_adjustDegreeByDieValue,adjustDegreeByDieValue_fn).call(this,_DegreeOfSuccess.SUCCESS):__privateMethod(this,_adjustDegreeByDieValue,adjustDegreeByDieValue_fn).call(this,_DegreeOfSuccess.FAILURE)},"#calculateDegreeOfSuccess"),__name2(_DegreeOfSuccess,"DegreeOfSuccess"),__publicField(_DegreeOfSuccess,"CRITICAL_FAILURE",0),__publicField(_DegreeOfSuccess,"FAILURE",1),__publicField(_DegreeOfSuccess,"SUCCESS",2),__publicField(_DegreeOfSuccess,"CRITICAL_SUCCESS",3);let DegreeOfSuccess=_DegreeOfSuccess;const DEGREE_ADJUSTMENT_AMOUNTS={LOWER_BY_TWO:-2,LOWER:-1,INCREASE:1,INCREASE_BY_TWO:2,TO_CRITICAL_FAILURE:"criticalFailure",TO_FAILURE:"failure",TO_SUCCESS:"success",TO_CRITICAL_SUCCESS:"criticalSuccess"},DEGREE_OF_SUCCESS={CRITICAL_SUCCESS:3,SUCCESS:2,FAILURE:1,CRITICAL_FAILURE:0},DEGREE_OF_SUCCESS_STRINGS=["criticalFailure","failure","success","criticalSuccess"],_AdjustDegreeOfSuccessRuleElement=class extends RuleElementPF2e{static{__name(this,"_AdjustDegreeOfSuccessRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,nullable:!1,blank:!1}),adjustment:new RecordField(new fields2.StringField({required:!0,nullable:!1,choices:["all",...DEGREE_OF_SUCCESS_STRINGS]}),new fields2.StringField({required:!0,nullable:!1,choices:degreeAdjustmentAmountString}),{required:!0,nullable:!1})}}beforePrepareData(){if(this.ignored)return;const selector=this.resolveInjectedProperties(this.selector),adjustments=this.adjustment,stringToAdjustment={"two-degrees-better":DEGREE_ADJUSTMENT_AMOUNTS.INCREASE_BY_TWO,"one-degree-better":DEGREE_ADJUSTMENT_AMOUNTS.INCREASE,"one-degree-worse":DEGREE_ADJUSTMENT_AMOUNTS.LOWER,"two-degrees-worse":DEGREE_ADJUSTMENT_AMOUNTS.LOWER_BY_TWO,"to-critical-failure":DEGREE_ADJUSTMENT_AMOUNTS.TO_CRITICAL_FAILURE,"to-failure":DEGREE_ADJUSTMENT_AMOUNTS.TO_FAILURE,"to-success":DEGREE_ADJUSTMENT_AMOUNTS.TO_SUCCESS,"to-critical-success":DEGREE_ADJUSTMENT_AMOUNTS.TO_CRITICAL_SUCCESS},record=["all",...DEGREE_OF_SUCCESS_STRINGS].reduce((accumulated,outcome)=>{const adjustment=adjustments[outcome];return adjustment&&(accumulated[outcome]={label:this.label,amount:stringToAdjustment[adjustment]}),accumulated},{});(this.actor.synthetics.degreeOfSuccessAdjustments[selector]??=[]).push({adjustments:record,predicate:this.predicate})}};__name2(_AdjustDegreeOfSuccessRuleElement,"AdjustDegreeOfSuccessRuleElement"),__publicField(_AdjustDegreeOfSuccessRuleElement,"validActorTypes",["character","npc"]);let AdjustDegreeOfSuccessRuleElement=_AdjustDegreeOfSuccessRuleElement;const degreeAdjustmentAmountString=["one-degree-better","one-degree-worse","two-degrees-better","two-degrees-worse","to-critical-failure","to-failure","to-success","to-critical-success"],_AELikeRuleElement=class _AELikeRuleElement2 extends RuleElementPF2e{static{__name(this,"_AELikeRuleElement")}constructor(){super(...arguments),__privateAdd(this,_rewriteSkillLongFormPath),__privateAdd(this,_pathIsValid),__privateAdd(this,_logChange)}static defineSchema(){const{fields:fields2}=foundry.data,baseSchema=super.defineSchema(),PRIORITIES=this.CHANGE_MODE_DEFAULT_PRIORITIES;return baseSchema.priority.initial=d=>PRIORITIES[String(d.mode)]??50,{...baseSchema,mode:new fields2.StringField({required:!0,choices:keys.strict(this.CHANGE_MODE_DEFAULT_PRIORITIES),initial:void 0}),path:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:void 0}),phase:new fields2.StringField({required:!1,nullable:!1,choices:deepClone(this.PHASES),initial:"applyAEs"}),value:new ResolvableValueField({required:!0,nullable:!0,initial:void 0}),merge:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0})}}static validateJoint(data){if(super.validateJoint(data),data.merge){if(data.mode!=="override")throw new foundry.data.validation.DataModelValidationError(' merge: `mode` must be "override"');if(!isObject(data.value))throw new foundry.data.validation.DataModelValidationError(" merge: `value` must an object")}}onApplyActiveEffects(){this.phase==="applyAEs"&&this.applyAELike()}beforePrepareData(){this.phase==="beforeDerived"&&this.applyAELike()}afterPrepareData(){this.phase==="afterDerived"&&this.applyAELike()}beforeRoll(_domains,rollOptions){this.phase==="beforeRoll"&&this.applyAELike(rollOptions)}applyAELike(rollOptions){if(this.ignored)return;const path=__privateMethod(this,_rewriteSkillLongFormPath,rewriteSkillLongFormPath_fn).call(this,this.resolveInjectedProperties(this.path));if(this.ignored)return;if(!__privateMethod(this,_pathIsValid,pathIsValid_fn).call(this,path))return this.failValidation(`no data found at or near "${path}"`);if(rollOptions??=this.predicate.length>0?new Set(this.actor.getRollOptions()):new Set,!this.test(rollOptions))return;const{actor}=this,current=getProperty(actor,path),change=this.resolveValue(this.value),newValue=_AELikeRuleElement2.getNewValue(this.mode,current,change,this.merge);if(newValue instanceof foundry.data.validation.DataModelValidationFailure)return this.failValidation(newValue.asError().message);if(this.mode==="add"&&Array.isArray(current))current.includes(newValue)||current.push(newValue);else if(["subtract","remove"].includes(this.mode)&&Array.isArray(current))current.splice(current.indexOf(newValue),1);else try{setProperty(actor,path,newValue),__privateMethod(this,_logChange,logChange_fn).call(this,change)}catch(error){error instanceof Error?this.failValidation(error.message):console.warn(error)}}static getNewValue(mode,current,change,merge=!1){const{DataModelValidationFailure}=foundry.data.validation,addOrSubtract=__name2(value=>{const isNumericAdd=typeof value=="number"&&(typeof current=="number"||current===void 0||current===null),isArrayAdd=Array.isArray(current)&¤t.every(e=>typeof e==typeof value);return isNumericAdd?(current??0)+value:isArrayAdd?value:new DataModelValidationFailure({invalidValue:value,fallback:!1})},"addOrSubtract");switch(mode){case"multiply":return typeof change!="number"?new DataModelValidationFailure({invalidValue:change,fallback:!1}):typeof current=="number"||current===void 0?Math.trunc((current??0)*change):new DataModelValidationFailure({invalidValue:current,fallback:!1});case"add":return addOrSubtract(change);case"subtract":case"remove":{const addedChange=(typeof current=="number"||current===void 0)&&typeof change=="number"?-1*change:change;return addOrSubtract(addedChange)}case"downgrade":return typeof change!="number"?new DataModelValidationFailure({invalidValue:change,fallback:!1}):typeof current=="number"||current===void 0?Math.min(current??0,change):new DataModelValidationFailure({invalidValue:current,fallback:!1});case"upgrade":return typeof change!="number"?new DataModelValidationFailure({invalidValue:change,fallback:!1}):typeof current=="number"||current===void 0?Math.max(current??0,change):new DataModelValidationFailure({invalidValue:current,fallback:!1});case"override":return merge&&isObject(current)&&isObject(change)?mergeObject(current,change):change;default:return null}}};_SKILL_LONG_FORM_PATH=new WeakMap,_rewriteSkillLongFormPath=new WeakSet,rewriteSkillLongFormPath_fn=__name2(function(path){return path.replace(__privateGet(_AELikeRuleElement,_SKILL_LONG_FORM_PATH),(match,group)=>objectHasKey(SKILL_EXPANDED,group)?`system.skills.${SKILL_EXPANDED[group].shortForm}`:match)},"#rewriteSkillLongFormPath"),_pathIsValid=new WeakSet,pathIsValid_fn=__name2(function(path){const actor=this.item.actor;return path.length>0&&!/\bnull\b/.test(path)&&(path.startsWith("flags.")||[path,path.replace(/\.[-\w]+$/,""),path.replace(/\.?[-\w]+\.[-\w]+$/,"")].some(path2=>getProperty(actor,path2)!==void 0))},"#pathIsValid"),_logChange=new WeakSet,logChange_fn=__name2(function(value){const{item,mode}=this;if(!(!(typeof value=="number"||typeof value=="string")&&typeof value=="string"&&mode!=="override"))return;const level=item instanceof FeatPF2e?Number(/-(\d+)$/.exec(item.system.location??"")?.[1])||item.level:"level"in item&&typeof item.level=="number"?item.level:null,{autoChanges}=this.actor.system;(autoChanges[this.path]??=[]).push({mode,level,value,source:this.item.name})},"#logChange"),__name2(_AELikeRuleElement,"AELikeRuleElement"),__publicField(_AELikeRuleElement,"CHANGE_MODE_DEFAULT_PRIORITIES",{multiply:10,add:20,subtract:20,remove:20,downgrade:30,upgrade:40,override:50}),__publicField(_AELikeRuleElement,"PHASES",["applyAEs","beforeDerived","afterDerived","beforeRoll"]),__privateAdd(_AELikeRuleElement,_SKILL_LONG_FORM_PATH,(()=>{const skillLongForms=Array.from(SKILL_LONG_FORMS).join("|");return new RegExp(String.raw`^system\.skills\.(${skillLongForms})\b`)})());let AELikeRuleElement=_AELikeRuleElement;const _AdjustModifierRuleElement=class extends RuleElementPF2e{static{__name(this,"_AdjustModifierRuleElement")}applications=0;constructor(source,options){source.suppress&&(source.mode="override"),super(source,options),typeof source.selector=="string"&&this.selectors.length===0&&(this.selectors=[source.selector]),this.suppress??=!1,this.maxApplications??=1/0}static defineSchema(){const{fields:fields2}=foundry.data,baseSchema=super.defineSchema(),PRIORITIES=AELikeRuleElement.CHANGE_MODE_DEFAULT_PRIORITIES;return baseSchema.priority.initial=d=>PRIORITIES[String(d.mode)]??50,{...baseSchema,mode:new fields2.StringField({required:!0,choices:keys.strict(AELikeRuleElement.CHANGE_MODE_DEFAULT_PRIORITIES),initial:void 0}),selector:new fields2.StringField({required:!1,blank:!1,initial:void 0}),selectors:new StrictArrayField(new fields2.StringField({required:!0,blank:!1})),relabel:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),damageType:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),suppress:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),maxApplications:new fields2.NumberField({required:!1,nullable:!0,initial:null}),value:new ResolvableValueField({required:!1,nullable:!0,initial:null})}}static validateJoint(data){super.validateJoint(data);const{DataModelValidationError}=foundry.data.validation;if(data.suppress===!0){if(typeof data.maxApplications=="number")throw new DataModelValidationError(" use of `maxApplications` in combination with `suppress` is not currently supported")}else if(data.value===null&&!data.damageType)throw new DataModelValidationError(" value: must be provided unless damageType is provided or suppress is true")}beforePrepareData(){if(this.ignored)return;const predicate=new PredicatePF2e(this.resolveInjectedProperties(deepClone([...this.predicate]))),adjustment={slug:this.slug,test:options=>predicate.test([...options,...this.item.getRollOptions("parent")]),suppress:this.suppress,getNewValue:current=>{if(this.value===null)return current;const change=Number(this.resolveValue(this.value));if(Number.isNaN(change))return this.failValidation("value does not resolve to a number"),current;if(this.ignored)return current;this.applications+=1,this.applications===this.maxApplications&&(this.ignored=!0);const newValue=AELikeRuleElement.getNewValue(this.mode,current,change);return newValue instanceof foundry.data.validation.DataModelValidationFailure?(this.failValidation(newValue.asError().message),current):newValue},getDamageType:current=>{if(!this.damageType)return current;const damageType=this.resolveInjectedProperties(this.damageType);return objectHasKey(CONFIG.PF2E.damageTypes,damageType)?damageType:(this.failValidation(`${damageType} is an unrecognized damage type.`),current)}};this.relabel&&(adjustment.relabel=this.getReducedLabel(this.resolveInjectedProperties(this.relabel)));for(const selector of this.selectors.map(s=>this.resolveInjectedProperties(s))){if(selector==="null")continue;(this.actor.synthetics.modifierAdjustments[selector]??=[]).push(adjustment)}}};__name2(_AdjustModifierRuleElement,"AdjustModifierRuleElement");let AdjustModifierRuleElement=_AdjustModifierRuleElement;const _AdjustStrikeRuleElement=class _AdjustStrikeRuleElement2 extends RuleElementPF2e{static{__name(this,"_AdjustStrikeRuleElement")}constructor(data,options){super({...data,priority:110},options)}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),mode:new fields2.StringField({required:!0,choices:keys.strict(AELikeRuleElement.CHANGE_MODE_DEFAULT_PRIORITIES),initial:void 0}),property:new fields2.StringField({required:!0,choices:Array.from(this.VALID_PROPERTIES),initial:void 0}),definition:new PredicateField,value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0})}}beforePrepareData(){if(!this.test())return;const change=this.resolveValue(this.value),adjustment=(()=>{if(!this.property)throw ErrorPF2e("Unexpected error applying adjustment");const definition=this.resolveInjectedProperties(this.definition);switch(this.property){case"materials":return{adjustDamageRoll:(weapon,{materials})=>{if(!["add","subtract","remove"].includes(this.mode))return this.failValidation('A strike adjustment of material effects must be used with the "add", "subtract", or "remove" mode.');if(!definition.test(weapon.getRollOptions("item")))return;if(!objectHasKey(CONFIG.PF2E.materialDamageEffects,change))return this.failValidation(`"${change}" is not a supported weapon material effect.`);const method=this.mode==="add"?"add":"delete";materials?.[method](change)}};case"range-increment":return{adjustWeapon:weapon=>{if(weapon.isOfType("melee"))return;if(typeof change!="number")return this.failValidation("Change value is not a number.");if(!definition.test(weapon.getRollOptions("item")))return;const rangeIncrement=weapon.range?.increment;if(typeof rangeIncrement!="number")return this.failValidation("A weapon that meets the definition lacks a range increment.");const newRangeIncrement=AELikeRuleElement.getNewValue(this.mode,rangeIncrement,change);weapon.system.range=newRangeIncrement}};case"traits":return{adjustTraits:(weapon,traits)=>{if(!["add","subtract","remove"].includes(this.mode))return this.failValidation('A strike adjustment of traits must be used with the "add", "subtract", or "remove" mode.');if(!objectHasKey(CONFIG.PF2E.actionTraits,change))return this.failValidation(`"${change}" is not a recognized action trait.`);definition.test(weapon.getRollOptions("item"))&&(this.mode==="add"&&!traits.includes(change)?traits.push(change):["subtract","remove"].includes(this.mode)&&traits.includes(change)&&traits.splice(traits.indexOf(change),1))}};case"weapon-traits":return{adjustWeapon:weapon=>{if(!["add","subtract","remove"].includes(this.mode))return this.failValidation('A strike adjustment of weapon traits must be used with the "add", "subtract", or "remove" mode.');if(!objectHasKey(CONFIG.PF2E.weaponTraits,change)&&!(weapon.isOfType("melee")&&objectHasKey(CONFIG.PF2E.npcAttackTraits,change)))return this.failValidation(`"${change}" is not a recognized weapon trait.`);if(!definition.test(weapon.getRollOptions("item"))||weapon.slug==="basic-unarmed"&&/^(?:modular|versatile)/.test(change))return;const traits=weapon.system.traits.value,annotatedTraitMatch=change.match(/^([a-z][-a-z]+)-(\d*d?\d+)$/);if(this.mode==="add"&&annotatedTraitMatch){const changeBaseTrait=annotatedTraitMatch[1],changeValue=annotatedTraitMatch[2],traitRegex=new RegExp(`${changeBaseTrait}-(\\d*d?\\d*)`),existingTraitMatch=traits.map(trait=>trait.match(traitRegex)).find(match=>!!match);if(existingTraitMatch){const existingTrait=existingTraitMatch[1],existingValue=_AdjustStrikeRuleElement2.getTraitScore(existingTrait);_AdjustStrikeRuleElement2.getTraitScore(changeValue)>existingValue&&traits.findSplice(trait=>trait===existingTraitMatch[0],change);return}}this.mode==="add"&&!traits.includes(change)?traits.push(change):this.mode!=="add"&&traits.includes(change)&&traits.splice(traits.indexOf(change),1)}};case"property-runes":return{adjustWeapon:weapon=>{if(weapon.isOfType("melee"))return;if(!["add","subtract","remove"].includes(this.mode))return this.failValidation('A strike adjustment of weapon property runes must be used with the "add", "subtract", or "remove" mode.');const runeSlug=sluggify(String(change),{camel:"dromedary"});if(!objectHasKey(RUNE_DATA.weapon.property,runeSlug))return this.failValidation(`"${change}" is not a recognized weapon property rune.`);if(!definition.test(weapon.getRollOptions("item")))return;const propertyRunes=weapon.system.runes.property;this.mode==="add"?propertyRunes.push(runeSlug):propertyRunes.includes(runeSlug)&&propertyRunes.splice(propertyRunes.indexOf(runeSlug),1),weapon.system.runes.property=prunePropertyRunes(propertyRunes,RUNE_DATA.weapon.property)}}}})();this.actor.synthetics.strikeAdjustments.push(adjustment)}static getTraitScore(traitValue){const traitValueMatch=traitValue.match(/(\d*)d(\d+)/);return traitValueMatch?Number(traitValueMatch[1]||1)*((Number(traitValueMatch[2])+1)/2):Number(traitValue)}};__name2(_AdjustStrikeRuleElement,"AdjustStrikeRuleElement"),__publicField(_AdjustStrikeRuleElement,"validActorTypes",["character","familiar","npc"]),__publicField(_AdjustStrikeRuleElement,"VALID_PROPERTIES",new Set(["materials","property-runes","range-increment","traits","weapon-traits"]));let AdjustStrikeRuleElement=_AdjustStrikeRuleElement;const _AuraRuleElement=class extends RuleElementPF2e{static{__name(this,"_AuraRuleElement")}constructor(source,options){super(source,options),__privateAdd(this,_processEffects),__privateAdd(this,_processAppearanceData),this.slug??=this.item.slug??sluggify(this.item.name);for(const effect of this.effects)effect.includesSelf??=effect.affects!=="enemies",effect.removeOnExit??=Array.isArray(effect.events)?effect.events.includes("enter"):!1}static defineSchema(){const{fields:fields2}=foundry.data,auraTraitField=new StrictStringField({required:!0,nullable:!1,initial:void 0,choices:{...CONFIG.PF2E.spellTraits,...CONFIG.PF2E.actionTraits}}),effectSchemaField=new fields2.SchemaField({uuid:new StrictStringField({required:!0,blank:!1,nullable:!1,initial:void 0}),affects:new StrictStringField({required:!0,nullable:!1,blank:!1,initial:"all",choices:["allies","enemies","all"],label:"PF2E.RuleEditor.Aura.Effects.Affects"}),events:new StrictArrayField(new StrictStringField({required:!0,blank:!1,nullable:!1,initial:void 0,choices:["enter","turn-start","turn-end"]}),{required:!0,nullable:!1,initial:["enter"],label:"PF2E.RuleEditor.Aura.Effects.Events"}),save:new fields2.SchemaField({type:new StrictStringField({required:!0,nullable:!1,blank:!1,initial:void 0,choices:SAVE_TYPES,label:"PF2E.RuleEditor.Aura.Effects.Type"}),dc:new ResolvableValueField({required:!0,nullable:!1,initial:void 0,label:"PF2E.Check.DC.Unspecific"})},{required:!0,nullable:!0,initial:null,label:"PF2E.SavesHeader"}),predicate:new PredicateField({required:!1,nullable:!1}),removeOnExit:new StrictBooleanField({required:!0,nullable:!1,initial:!0,label:"PF2E.RuleEditor.Aura.Effects.RemoveOnExit"}),includesSelf:new StrictBooleanField({required:!1,nullable:!1,initial:void 0,label:"PF2E.RuleEditor.Aura.Effects.IncludesSelf"})}),xyPairSchema=__name2(({integer})=>({x:new StrictNumberField({required:!0,integer,nullable:!1,initial:void 0,label:"PF2E.RuleEditor.Aura.Appearance.Translation.X"}),y:new StrictNumberField({required:!0,integer,nullable:!1,initial:void 0,label:"PF2E.RuleEditor.Aura.Appearance.Translation.Y"})}),"xyPairSchema"),appearanceSchema={border:new fields2.SchemaField({color:new DataUnionField([new StrictStringField({required:!0,choices:["user-color"],initial:void 0}),new fields2.ColorField({required:!0,nullable:!1,initial:void 0})],{required:!0,nullable:!1,initial:"#000000",label:"PF2E.RuleEditor.Aura.Appearance.Color"}),alpha:new fields2.AlphaField({required:!0,nullable:!1,initial:.75,label:"PF2E.RuleEditor.General.Opacity"})},{required:!1,nullable:!0,initial:()=>({color:"#000000",alpha:.75}),label:"PF2E.RuleEditor.Aura.Appearance.Border"}),highlight:new fields2.SchemaField({color:new DataUnionField([new StrictStringField({required:!0,nullable:!1,choices:["user-color"],initial:void 0}),new fields2.ColorField({required:!0,nullable:!1,initial:void 0})],{required:!0,nullable:!1,initial:"user-color",label:"PF2E.RuleEditor.Aura.Appearance.Color"}),alpha:new fields2.AlphaField({required:!1,nullable:!1,initial:.25,label:"PF2E.RuleEditor.General.Opacity"})},{required:!1,nullable:!1,initial:()=>({color:"user-color",alpha:.25}),label:"PF2E.RuleEditor.Aura.Appearance.Highlight"}),texture:new fields2.SchemaField({src:new StrictStringField({required:!0,nullable:!1,initial:void 0,label:"TOKEN.ImagePath"}),alpha:new fields2.AlphaField({required:!0,nullable:!1,initial:1,label:"PF2E.RuleEditor.General.Opacity"}),scale:new StrictNumberField({required:!0,nullable:!1,positive:!0,initial:1,label:"Scale"}),translation:new fields2.SchemaField(xyPairSchema({integer:!0}),{required:!1,nullable:!0,initial:null,label:"PF2E.RuleEditor.Aura.Appearance.Translation.Label",hint:"PF2E.RuleEditor.Aura.Appearance.Translation.Hint"}),loop:new StrictBooleanField({required:!1,nullable:!1,initial:!0,label:"PF2E.RuleEditor.Aura.Appearance.Loop.Label",hint:"PF2E.RuleEditor.Aura.Appearance.Loop.Hint"}),playbackRate:new StrictNumberField({required:!1,nullable:!1,positive:!0,max:4,initial:1,label:"PF2E.RuleEditor.Aura.Appearance.PlaybackRate.Label",hint:"PF2E.RuleEditor.Aura.Appearance.PlaybackRate.Hint"})},{required:!1,nullable:!0,initial:null,label:"PF2E.RuleEditor.Aura.Appearance.Texture"})};return{...super.defineSchema(),radius:new ResolvableValueField({required:!0,nullable:!1,initial:5,label:"PF2E.RuleEditor.Aura.Basic.Radius"}),level:new ResolvableValueField({required:!1,nullable:!0,initial:null,label:"PF2E.RuleEditor.Aura.Basic.Level.Label",hint:"PF2E.RuleEditor.Aura.Basic.Level.Hint"}),traits:new StrictArrayField(auraTraitField,{required:!0,nullable:!1,label:"PF2E.TraitsLabel"}),effects:new StrictArrayField(effectSchemaField,{required:!0,nullable:!1,label:"PF2E.RuleEditor.Aura.Effects.Label"}),appearance:new fields2.SchemaField(appearanceSchema,{required:!0,nullable:!1,initial:()=>({border:{color:"#000000",alpha:.75},highlight:{color:"user-color",alpha:.25},texture:null}),label:"PF2E.RuleEditor.Aura.Appearance.Label"}),mergeExisting:new StrictBooleanField({required:!0,nullable:!1,initial:!0,label:"PF2E.RuleEditor.Aura.Basic.MergeExisting.Label",hint:"PF2E.RuleEditor.Aura.Basic.MergeExisting.Hint"})}}afterPrepareData(){if(!this.test())return;const radius=Math.clamped(Math.ceil(Number(this.resolveValue(this.radius))/5)*5,5,240);if(Number.isInteger(radius)&&radius>0){const level=this.resolveValue(this.level,null),data={slug:this.slug,radius,level:typeof level=="number"?Math.trunc(level):this.item.isOfType("effect")?this.item.level:null,effects:__privateMethod(this,_processEffects,processEffects_fn).call(this),traits:uniq(this.traits.filter(t=>t!=="aura")).sort(),appearance:__privateMethod(this,_processAppearanceData,processAppearanceData_fn).call(this)};for(const effect of data.effects){const indexEntry=fromUuidSync(effect.uuid);if(!(indexEntry&&"type"in indexEntry&&typeof indexEntry.type=="string")){this.failValidation(`Unable to resolve effect uuid: ${effect.uuid}`);return}["effect","affliction"].includes(indexEntry.type)||this.failValidation('effects transmitted by auras must be of type "effect" or "affliction"')}const existing=this.actor.auras.get(this.slug);if(existing&&this.mergeExisting){existing.radius=data.radius,existing.traits=uniq([...existing.traits,...data.traits]).sort(),existing.appearance=data.appearance;for(const effect of data.effects){const existingIndex=existing.effects.findIndex(e=>e.uuid===effect.uuid);existingIndex!==-1?existing.effects.splice(existingIndex,1,effect):existing.effects.push(effect)}}else this.actor.auras.set(this.slug,data)}}};_processEffects=new WeakSet,processEffects_fn=__name2(function(){return this.effects.map(e=>({...e,uuid:this.resolveInjectedProperties(e.uuid),save:null}))},"#processEffects"),_processAppearanceData=new WeakSet,processAppearanceData_fn=__name2(function(){const appearance=deepClone(this.appearance),{border,highlight,texture}=appearance,textureSrc=(()=>{if(!texture)return null;const maybeTextureSrc=this.resolveInjectedProperties(texture.src);return isImageOrVideoPath(maybeTextureSrc)?maybeTextureSrc:"icons/svg/hazard.svg"})();return border&&(border.color=border.color==="user-color"?userColorForActor(this.actor):border.color),highlight.color=highlight.color==="user-color"?userColorForActor(this.actor):highlight.color,{border:border&&{color:Number(Color.fromString(border.color)),alpha:border.alpha},highlight:{color:Number(Color.fromString(highlight.color)),alpha:highlight.alpha},texture:texture?.alpha&&textureSrc?{...texture,src:textureSrc}:null}},"#processAppearanceData"),__name2(_AuraRuleElement,"AuraRuleElement");let AuraRuleElement=_AuraRuleElement;const _BaseSpeedRuleElement=class extends RuleElementPF2e{static{__name(this,"_BaseSpeedRuleElement")}constructor(data,options){super(data,options),__privateAdd(this,_createMovementType),this.selector=this.selector?.trim().replace(/-speed$/,""),typeof this.value=="string"||typeof this.value=="number"||this.isBracketedValue(this.value)||this.failValidation("A value must be a number, string, or bracketed value")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1,initial:void 0}),value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0})}}beforePrepareData(){if(this.ignored)return;const speedType=this.resolveInjectedProperties(this.selector);if(!tupleHasValue(MOVEMENT_TYPES,speedType))return this.failValidation("Unrecognized or missing selector");const speed=__privateMethod(this,_createMovementType,createMovementType_fn).call(this,speedType);(this.actor.synthetics.movementTypes[speedType]??=[]).push(speed)}};_createMovementType=new WeakSet,createMovementType_fn=__name2(function(type){return()=>{if(!this.test())return null;const value=Math.trunc(Number(this.resolveValue(this.value)));if(!Number.isInteger(value))return this.failValidation("Failed to resolve value"),null;const derivedFromLand=type!=="land"&&typeof this.value=="string"&&/attributes\.speed\.(?:value|total)/.test(this.value);return value>0?{type,value,source:this.item.name,derivedFromLand}:null}},"#createMovementType"),__name2(_BaseSpeedRuleElement,"BaseSpeedRuleElement"),__publicField(_BaseSpeedRuleElement,"validActorTypes",["character","familiar","npc"]);let BaseSpeedRuleElement=_BaseSpeedRuleElement;const ALIGNMENTS=new Set(["LG","NG","CG","LN","N","CN","LE","NE","CE"]),ALIGNMENT_TRAITS=new Set(["chaotic","evil","good","lawful"]),ALLIANCES=new Set(["party","opposition",null]),SAVING_THROW_DEFAULT_ATTRIBUTES={fortitude:"con",reflex:"dex",will:"wis"},SIZE_TO_REACH={tiny:0,sm:5,med:5,lg:5,huge:10,grg:15},SENSES_WITH_MANDATORY_ACUITIES={darkvision:"precise",heatsight:"precise",greaterDarkvision:"precise",lowLightVision:"precise",seeInvisibility:"precise"},_CreatureSensePF2e=class{static{__name(this,"_CreatureSensePF2e")}type;acuity;value;source;get range(){return Number(this.value)||1/0}constructor(data){this.type=data.type,this.acuity=objectHasKey(SENSES_WITH_MANDATORY_ACUITIES,this.type)?SENSES_WITH_MANDATORY_ACUITIES[this.type]:data.acuity??"precise",this.value=data.value??"",this.source=data.source||void 0}get label(){const buildLabel=__name2((type,acuity,range2)=>{const senses2=CONFIG.PF2E.senses,sense=game.i18n.localize(senses2[type]??"")||type,acuityLabel=acuity?game.i18n.localize(CONFIG.PF2E.senseAcuity[acuity]):null;return acuity&&range2?game.i18n.format("PF2E.Actor.Creature.Sense.WithAcuityAndRange",{sense,acuity:acuityLabel,range:range2}):acuity?game.i18n.format("PF2E.Actor.Creature.Sense.WithAcuity",{sense,acuity:acuityLabel}):sense},"buildLabel"),range=this.range<1/0?this.range:void 0;switch(this.type){case"darkvision":case"greaterDarkvision":case"lowLightVision":case"seeInvisibility":return buildLabel(this.type);case"scent":return this.acuity==="vague"?null:buildLabel(this.type,this.acuity,range);default:return buildLabel(this.type,this.acuity,range)}}isMoreAcuteThan(sense){return this.acuity==="precise"&&["imprecise","vague"].includes(sense.acuity??"precise")||this.acuity==="imprecise"&&sense.acuity==="vague"}hasLongerRangeThan(sense){return this.range>Number(sense.value)}};__name2(_CreatureSensePF2e,"CreatureSensePF2e");let CreatureSensePF2e=_CreatureSensePF2e;const SENSE_ACUITIES=["precise","imprecise","vague"],SENSE_TYPES=new Set(["darkvision","echolocation","greaterDarkvision","heatsight","lifesense","lowLightVision","motionsense","scent","seeInvisibility","spiritsense","thoughtsense","tremorsense","wavesense"]),CONDITION_SLUGS=new Set(["blinded","broken","clumsy","concealed","confused","controlled","dazzled","deafened","doomed","drained","dying","encumbered","enfeebled","fascinated","fatigued","fleeing","friendly","frightened","grabbed","helpful","hidden","hostile","immobilized","indifferent","invisible","malevolence","observed","off-guard","paralyzed","persistent-damage","petrified","prone","quickened","restrained","sickened","slowed","stunned","stupefied","unconscious","undetected","unfriendly","unnoticed","wounded"]),_IWR=class{static{__name(this,"_IWR")}constructor(data){__publicField(this,"type"),__publicField(this,"exceptions"),__publicField(this,"definition"),__publicField(this,"source"),__privateAdd(this,_customLabel,void 0),this.type=data.type,this.exceptions=deepClone(data.exceptions??[]),this.definition=data.definition??null,this.source=data.source??null,__privateSet(this,_customLabel,this.type==="custom"?data.customLabel??null:null)}get applicationLabel(){const type=this.typeLabel,exceptions=this.createFormatData({list:this.exceptions,prefix:"exception"}),key=`Exceptions${this.exceptions.length}DoubleVs0`;return game.i18n.format(`PF2E.Damage.IWR.CompositeLabel.${key}`,{type,...exceptions,value:""}).replace(/\s+/g," ").trim()}get typeLabel(){return game.i18n.localize(__privateGet(this,_customLabel)??this.typeLabels[this.type])}describe(iwrType){if(setHasElement(CONDITION_SLUGS,iwrType))return["item:type:condition",`item:slug:${iwrType}`];if(isObject(iwrType))return iwrType.definition;switch(iwrType){case"air":case"earth":case"metal":case"radiation":case"visual":case"water":case"wood":return[`item:trait:${iwrType}`];case"all-damage":return["damage"];case"area-damage":return["area-damage"];case"arrow-vulnerability":return["item:group:bow",{not:"item:tag:crossbow"}];case"auditory":return["item:trait:auditory"];case"axe-vulnerability":return["item:group:axe"];case"critical-hits":return["damage:component:critical"];case"custom":return this.definition??[];case"damage-from-spells":return["damage","item:type:spell","impulse"];case"disease":return["item:trait:disease"];case"emotion":return["item:type:effect","item:trait:emotion"];case"energy":case"physical":return[`damage:category:${iwrType}`];case"fear-effects":return["item:type:effect","item:trait:fear"];case"ghost-touch":return["item:rune:property:ghost-touch"];case"magical":return["item:magical"];case"mental":return[{or:["damage:type:mental",{and:["item:type:effect","item:trait:mental"]}]}];case"non-magical":return[{not:"item:magical"}];case"object-immunities":return[{or:["damage:type:bleed","damage:type:mental","damage:type:poison","damage:type:spirit",{and:["item:type:condition",{or:["item:slug:doomed","item:slug:drained","item:slug:fatigued","item:slug:paralyzed","item:slug:sickened","item:slug:unconscious"]}]}]}];case"precision":case"splash-damage":return[`damage:component:${iwrType==="splash-damage"?"splash":"precision"}`];case"spells":return["damage",{or:["item:type:spell","item:from-spell","impulse"]}];case"unarmed-attacks":return["item:category:unarmed"];default:{if(iwrType in CONFIG.PF2E.damageTypes)return[`damage:type:${iwrType}`];if(objectHasKey(CONFIG.PF2E.materialDamageEffects,iwrType))switch(iwrType){case"adamantine":return[{or:["damage:material:adamantine","damage:material:keep-stone"]}];case"cold-iron":return[{or:["damage:material:cold-iron","damage:material:sovereign-steel"]}];case"darkwood":return[{or:["damage:material:darkwood",{and:["self:mode:undead","damage:material:peachwood"]}]}];case"silver":return[{or:["damage:material:silver","damage:material:mithral"]}];default:return[`damage:material:${iwrType}`]}return setHasElement(MAGIC_SCHOOLS,iwrType)?["item:type:effect",`item:trait:${iwrType}`]:[`unhandled:${iwrType}`]}}}get predicate(){const typeStatements=this.describe(this.type),exceptions=this.exceptions.flatMap(exception=>{const described=this.describe(exception).filter(s=>s!=="damage");return described.length===1?described:{and:described}}),statements=[typeStatements,exceptions.length===0?[]:exceptions.length===1?{not:exceptions[0]}:{nor:exceptions}].flat();return new PredicatePF2e(statements)}toObject(){return{type:this.type,exceptions:deepClone(this.exceptions),source:this.source,label:this.label}}createFormatData({list,prefix}){return list.slice(0,4).map((exception,index)=>{const label=typeof exception=="string"?this.typeLabels[exception]:exception.label;return{[`${prefix}${index+1}`]:game.i18n.localize(label)}}).reduce((accum,obj)=>({...accum,...obj}),{})}test(statements){return this.predicate.test(statements)}};_customLabel=new WeakMap,__name2(_IWR,"IWR");let IWR=_IWR;const _Immunity=class extends IWR{static{__name(this,"_Immunity")}typeLabels=CONFIG.PF2E.immunityTypes;get label(){return this.applicationLabel}};__name2(_Immunity,"Immunity");let Immunity=_Immunity;const _Weakness=class extends IWR{static{__name(this,"_Weakness")}typeLabels=CONFIG.PF2E.weaknessTypes;value;constructor(data){super(data),this.value=data.value}get label(){const type=this.typeLabel,exceptions=this.createFormatData({list:this.exceptions,prefix:"exception"}),key=`Exceptions${this.exceptions.length}DoubleVs0`;return game.i18n.format(`PF2E.Damage.IWR.CompositeLabel.${key}`,{type,value:this.value,...exceptions})}toObject(){return{...super.toObject(),value:this.value}}};__name2(_Weakness,"Weakness");let Weakness=_Weakness;const _Resistance=class extends IWR{static{__name(this,"_Resistance")}typeLabels=CONFIG.PF2E.resistanceTypes;value;doubleVs;constructor(data){super(data),this.value=data.value,this.doubleVs=deepClone(data.doubleVs??[])}get label(){const type=this.typeLabel,exceptions=this.createFormatData({list:this.exceptions,prefix:"exception"}),doubleVs=this.createFormatData({list:this.doubleVs,prefix:"doubleVs"}),key=`Exceptions${this.exceptions.length}DoubleVs${this.doubleVs.length}`;return game.i18n.format(`PF2E.Damage.IWR.CompositeLabel.${key}`,{type,value:this.value,...exceptions,...doubleVs})}get applicationLabel(){const type=this.typeLabel,exceptions=this.createFormatData({list:this.exceptions,prefix:"exception"}),doubleVs=this.createFormatData({list:this.doubleVs,prefix:"doubleVs"}),key=`Exceptions${this.exceptions.length}DoubleVs${this.doubleVs.length}`;return game.i18n.format(`PF2E.Damage.IWR.CompositeLabel.${key}`,{type,value:"",...exceptions,...doubleVs}).replace(/\s+/g," ").trim()}toObject(){return{...super.toObject(),value:this.value,doubleVs:deepClone(this.doubleVs)}}getDoubledValue(damageDescription){return this.doubleVs.length===0?this.value:new PredicatePF2e(this.doubleVs.flatMap(d=>this.describe(d))).test(damageDescription)?this.value*2:this.value}};__name2(_Resistance,"Resistance");let Resistance=_Resistance;const NON_DAMAGE_WEAKNESSES=new Set(["air","earth","ghost-touch","metal","plant","radiation","salt","salt-water","spells","water","wood"]),_AttackTraitHelpers=class{static{__name(this,"_AttackTraitHelpers")}static getLabel(traitOrTag){const traits=CONFIG.PF2E.weaponTraits,tags=CONFIG.PF2E.otherWeaponTags;return traits[traitOrTag]??tags[traitOrTag]??traitOrTag}static getUnannotatedTrait(trait){return trait.replace(/-d?\d{1,3}$/,"")}static createAttackModifiers({item}){const{actor}=item;if(!actor)throw ErrorPF2e("The weapon must be embedded");return item.system.traits.value.flatMap(trait=>{const unannotatedTrait=this.getUnannotatedTrait(trait);switch(unannotatedTrait){case"volley":{if(!item.range?.increment)return[];const penaltyRange=Number(/-(\d+)$/.exec(trait)[1]);return new ModifierPF2e({slug:unannotatedTrait,label:this.getLabel(trait),modifier:-2,type:"untyped",ignored:!0,predicate:new PredicatePF2e({lte:["target:distance",penaltyRange]},{not:"self:ignore-volley-penalty"})})}case"sweep":return new ModifierPF2e({slug:unannotatedTrait,label:this.getLabel(trait),modifier:1,type:"circumstance",predicate:new PredicatePF2e("sweep-bonus")});case"backswing":return new ModifierPF2e({slug:unannotatedTrait,label:this.getLabel(trait),modifier:1,type:"circumstance",predicate:new PredicatePF2e("backswing-bonus")});default:return[]}})}};__name2(_AttackTraitHelpers,"AttackTraitHelpers");let AttackTraitHelpers=_AttackTraitHelpers;function setImmunitiesFromTraits(actor){if(actor.isOfType("character"))return;const{traits}=actor,{immunities}=actor.attributes;if(traits.has("construct")&&!traits.has("eidolon")){const constructImmunities=["bleed","death-effects","disease","doomed","drained","fatigued","healing","necromancy","nonlethal-attacks","paralyzed","poison","sickened","spirit","unconscious"];for(const immunityType of constructImmunities)immunities.some(i=>i.type===immunityType)||immunities.push(new Immunity({type:immunityType,source:game.i18n.localize("PF2E.TraitConstruct")}))}traits.has("mindless")&&!immunities.some(i=>i.type==="mental")&&immunities.push(new Immunity({type:"mental",source:game.i18n.localize("PF2E.TraitMindless")}))}__name(setImmunitiesFromTraits,"setImmunitiesFromTraits"),__name2(setImmunitiesFromTraits,"setImmunitiesFromTraits");function imposeEncumberedCondition(actor){if(game.settings.get("pf2e","automation.encumbrance")&&actor.inventory.bulk.isEncumbered&&actor.conditions.bySlug("encumbered").length===0){const source=game.pf2e.ConditionManager.getCondition("encumbered").toObject(),encumbered=new ConditionPF2e(mergeObject(source,{_id:"xxxENCUMBEREDxxx"}),{parent:actor});encumbered.prepareSiblingData(),encumbered.prepareActorData();for(const rule of encumbered.prepareRuleElements())rule.beforePrepareData?.();actor.conditions.set(encumbered.id,encumbered)}}__name(imposeEncumberedCondition,"imposeEncumberedCondition"),__name2(imposeEncumberedCondition,"imposeEncumberedCondition");const _WeaponTraitToggles=class{static{__name(this,"_WeaponTraitToggles")}constructor(weapon){__privateAdd(this,_resolveOptions),__privateAdd(this,_weapon,void 0),__privateSet(this,_weapon,weapon)}get modular(){const options=__privateMethod(this,_resolveOptions,resolveOptions_fn).call(this,"modular"),sourceSelection=__privateGet(this,_weapon)._source.system.traits.toggles?.modular?.selection,selection=tupleHasValue(options,sourceSelection)?sourceSelection:options.includes(__privateGet(this,_weapon).system.damage.damageType)?__privateGet(this,_weapon).system.damage.damageType:null;return{options,selection}}get versatile(){const options=__privateMethod(this,_resolveOptions,resolveOptions_fn).call(this,"versatile"),sourceSelection=__privateGet(this,_weapon)._source.system.traits.toggles?.versatile?.selection??null,selection=tupleHasValue(options,sourceSelection)?sourceSelection:null;return{options,selection}}};_weapon=new WeakMap,_resolveOptions=new WeakSet,resolveOptions_fn=__name2(function(toggle){const types=__privateGet(this,_weapon).system.traits.value.filter(t=>t.startsWith(toggle)).flatMap(trait=>{if(trait==="modular")return["bludgeoning","piercing","slashing"];const damageType=/^versatile-(\w+)$/.exec(trait)?.at(1);switch(damageType){case"b":return"bludgeoning";case"p":return"piercing";case"s":return"slashing";default:return objectHasKey(CONFIG.PF2E.damageTypes,damageType)?damageType:[]}}),allOptions=Array.from(new Set(types));return toggle==="modular"?allOptions:allOptions.filter(t=>__privateGet(this,_weapon).system.damage.damageType!==t)},"#resolveOptions"),__name2(_WeaponTraitToggles,"WeaponTraitToggles");let WeaponTraitToggles=_WeaponTraitToggles;async function toggleWeaponTrait({weapon,trait,selection}){if(weapon.system.traits.toggles[trait].selection===selection)return!1;const item=weapon.actor?.items.get(weapon.id);return item?.isOfType("weapon")&&item===weapon?await item.update({[`system.traits.toggles.${trait}.selection`]:selection}):item?.isOfType("weapon")&&weapon.altUsageType==="melee"?item.update({[`system.meleeUsage.traitToggles.${trait}`]:selection}):await item?.rules.find(r=>r.key==="Strike"&&!r.ignored&&r.slug===weapon.slug)?.toggleTrait({trait,selection}),!0}__name(toggleWeaponTrait,"toggleWeaponTrait"),__name2(toggleWeaponTrait,"toggleWeaponTrait");function createSheetOptions(options,selections=[],{selected=!1}={}){const sheetOptions=Object.entries(options).reduce((compiledOptions,[stringKey,label])=>{const selectionList=Array.isArray(selections)?selections:selections.value,key=typeof selectionList[0]=="number"?Number(stringKey):stringKey,isSelected=selectionList.includes(key);return(isSelected||!selected)&&(compiledOptions[key]={label:game.i18n.localize(label),value:stringKey,selected:isSelected}),compiledOptions},{});return sortLabeledRecord(sheetOptions)}__name(createSheetOptions,"createSheetOptions"),__name2(createSheetOptions,"createSheetOptions");function createSheetTags(options,selections){return createSheetOptions(options,selections,{selected:!0})}__name(createSheetTags,"createSheetTags"),__name2(createSheetTags,"createSheetTags");function createTagifyTraits(traits,{sourceTraits,record}){const sourceSet=new Set(sourceTraits),traitSlugs=[...traits],readonlyTraits=traitSlugs.filter(t=>!sourceSet.has(t));return traitSlugs.map(slug=>{const label=game.i18n.localize(record?.[slug]??slug);return{id:slug,value:label,readonly:readonlyTraits.includes(slug)}}).sort((t1,t2)=>t1.value.localeCompare(t2.value))}__name(createTagifyTraits,"createTagifyTraits"),__name2(createTagifyTraits,"createTagifyTraits");function processTagifyInSubmitData(form,data){const tagifyInputElements=form.querySelectorAll("tags.tagify ~ input");for(const inputEl of tagifyInputElements.values()){const path=inputEl.name,inputValue=data[path],selections=inputValue&&typeof inputValue=="string"?JSON.parse(inputValue):inputValue;Array.isArray(selections)&&(data[path]=selections.filter(s=>!s.readonly).map(s=>s.id??s.value))}}__name(processTagifyInSubmitData,"processTagifyInSubmitData"),__name2(processTagifyInSubmitData,"processTagifyInSubmitData");function getAdjustment(value,reference){const adjustedHigher=value>reference,adjustedLower=value{const unannotatedTrait=this.getUnannotatedTrait(trait);switch(unannotatedTrait){case"kickback":return new ModifierPF2e({slug:unannotatedTrait,label:CONFIG.PF2E.weaponTraits.kickback,modifier:-2,type:"circumstance",predicate:new PredicatePF2e({lt:["attribute:str:mod",2]}),adjustments:extractModifierAdjustments(synthetics,domains,unannotatedTrait)});case"improvised":return new ModifierPF2e({slug:unannotatedTrait,label:this.getLabel(trait),modifier:-2,type:"item",predicate:new PredicatePF2e({not:"self:ignore-improvised-penalty"}),adjustments:extractModifierAdjustments(synthetics,domains,unannotatedTrait)});default:return[]}});return[...super.createAttackModifiers({item}),...pcSpecificModifiers]}};__name2(_PCAttackTraitHelpers,"PCAttackTraitHelpers");let PCAttackTraitHelpers=_PCAttackTraitHelpers;const _WeaponAuxiliaryAction=class{static{__name(this,"_WeaponAuxiliaryAction")}weapon;action;actions;carryType;hands;purpose;fullPurpose;constructor({weapon,action:action2,purpose,hands}){this.weapon=weapon,this.action=action2,this.purpose=purpose,this.hands=hands??null;const[actions,carryType,fullPurpose]=(()=>{switch(purpose){case"Draw":return[1,"held",`${purpose}${hands}H`];case"PickUp":return[1,"held",`${purpose}${hands}H`];case"Retrieve":{const{container}=weapon;return[container?.system.usage.type==="worn"&&container.isWorn?1:container?.isHeld?2:3,"held",`${purpose}${hands}H`]}case"Grip":return[action2==="Interact"?1:0,"held",purpose];case"Sheathe":return[1,"worn",purpose];case"Modular":return[1,null,purpose];case"Drop":return[0,"dropped",purpose]}})();this.actions=actions,this.carryType=carryType,this.fullPurpose=fullPurpose}get actor(){return this.weapon.parent}get label(){return game.i18n.localize(`PF2E.Actions.${this.action}.${this.fullPurpose}.Title`)}get glyph(){return getActionGlyph(this.actions)}get options(){return this.purpose==="Modular"?createSheetOptions(pick(CONFIG.PF2E.damageTypes,this.weapon.system.traits.toggles.modular.options),[this.weapon.system.traits.toggles.modular.selection??[]].flat()):null}async execute({selection=null}={}){const{actor,weapon}=this;if(typeof this.carryType=="string")await actor.adjustCarryType(this.weapon,{carryType:this.carryType,handsHeld:this.hands??0});else if(selection&&tupleHasValue(weapon.system.traits.toggles.modular.options,selection)&&!await toggleWeaponTrait({weapon,trait:"modular",selection}))return;if(!game.combat)return;const templates={flavor:"./systems/pf2e/templates/chat/action/flavor.hbs",content:"./systems/pf2e/templates/chat/action/content.hbs"},flavorAction={title:`PF2E.Actions.${this.action}.Title`,subtitle:`PF2E.Actions.${this.action}.${this.fullPurpose}.Title`,glyph:this.glyph},flavor=await renderTemplate(templates.flavor,{action:flavorAction,traits:[traitSlugToObject("manipulate",CONFIG.PF2E.actionTraits)]}),content=await renderTemplate(templates.content,{imgPath:weapon.img,message:game.i18n.format(`PF2E.Actions.${this.action}.${this.fullPurpose}.Description`,{actor:actor.name,weapon:weapon.name,damageType:game.i18n.localize(`PF2E.Damage.RollFlavor.${selection}`)})}),token=actor.getActiveTokens(!1,!0).shift();await ChatMessagePF2e.create({content,speaker:ChatMessagePF2e.getSpeaker({actor,token}),flavor,type:CONST.CHAT_MESSAGE_TYPES.EMOTE})}};__name2(_WeaponAuxiliaryAction,"WeaponAuxiliaryAction");let WeaponAuxiliaryAction=_WeaponAuxiliaryAction;function imposeOversizedWeaponCondition(actor){const wieldedOversizedWeapon=actor.itemTypes.weapon.find(w=>w.isEquipped&&w.isOversized&&w.category!=="unarmed"),compendiumCondition=game.pf2e.ConditionManager.getCondition("clumsy"),conditionSource=wieldedOversizedWeapon&&actor.conditions.bySlug("clumsy").length===0?mergeObject(compendiumCondition.toObject(),{_id:"xxxxOVERSIZExxxx",system:{slug:"clumsy",references:{parent:{id:wieldedOversizedWeapon.id}}}}):null;if(!conditionSource)return;const clumsyOne=new ConditionPF2e(conditionSource,{parent:actor});clumsyOne.prepareSiblingData(),clumsyOne.prepareActorData();for(const rule of clumsyOne.prepareRuleElements())rule.beforePrepareData?.()}__name(imposeOversizedWeaponCondition,"imposeOversizedWeaponCondition"),__name2(imposeOversizedWeaponCondition,"imposeOversizedWeaponCondition");function createForceOpenPenalty(actor,domains){const slug="no-crowbar",{modifierAdjustments}=actor.synthetics;return new ModifierPF2e({slug,label:"PF2E.Actions.ForceOpen.NoCrowbarPenalty",type:"item",modifier:-2,predicate:["action:force-open","action:force-open:prying"],hideIfDisabled:!0,adjustments:extractModifierAdjustments(modifierAdjustments,domains,slug)})}__name(createForceOpenPenalty,"createForceOpenPenalty"),__name2(createForceOpenPenalty,"createForceOpenPenalty");function createShoddyPenalty(actor,item,domains){if(!actor.isOfType("character")||!item?.isShoddy)return null;const slug="shoddy";return new ModifierPF2e({label:"PF2E.Item.Physical.OtherTag.Shoddy",type:"item",slug,modifier:-2,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,slug)})}__name(createShoddyPenalty,"createShoddyPenalty"),__name2(createShoddyPenalty,"createShoddyPenalty");function createHinderingPenalty(actor){const slug="hindering";return actor.wornArmor?.traits.has(slug)?new ModifierPF2e({label:"PF2E.TraitHindering",type:"untyped",slug,modifier:-5,adjustments:[]}):null}__name(createHinderingPenalty,"createHinderingPenalty"),__name2(createHinderingPenalty,"createHinderingPenalty");function createPonderousPenalty(actor){const armor=actor.wornArmor,slug="ponderous";if(!armor?.traits.has(slug))return null;const penaltyValue=actor.abilities.str.mod>=(armor.strength??-1/0)?-1:armor.checkPenalty||-1;return new ModifierPF2e({label:"PF2E.TraitPonderous",type:"untyped",slug,modifier:penaltyValue,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,["all","initiative"],slug)})}__name(createPonderousPenalty,"createPonderousPenalty"),__name2(createPonderousPenalty,"createPonderousPenalty");const adjustmentScale=["incredibly-easy","very-easy","easy","normal","hard","very-hard","incredibly-hard"],dcAdjustments=new Map([["incredibly-easy",-10],["very-easy",-5],["easy",-2],["normal",0],["hard",2],["very-hard",5],["incredibly-hard",10]]),dcByLevel=new Map([[-1,13],[0,14],[1,15],[2,16],[3,18],[4,19],[5,20],[6,22],[7,23],[8,24],[9,26],[10,27],[11,28],[12,30],[13,31],[14,32],[15,34],[16,35],[17,36],[18,38],[19,39],[20,40],[21,42],[22,44],[23,46],[24,48],[25,50]]),simpleDCs=new Map([["untrained",10],["trained",15],["expert",20],["master",30],["legendary",40]]),simpleDCsWithoutLevel=new Map([["untrained",10],["trained",15],["expert",20],["master",25],["legendary",30]]);function rarityToDCAdjustment(rarity="common"){switch(rarity){case"uncommon":return"hard";case"rare":return"very-hard";case"unique":return"incredibly-hard";default:return"normal"}}__name(rarityToDCAdjustment,"rarityToDCAdjustment"),__name2(rarityToDCAdjustment,"rarityToDCAdjustment");function adjustDC(dc,adjustment="normal"){return dc+(dcAdjustments.get(adjustment)??0)}__name(adjustDC,"adjustDC"),__name2(adjustDC,"adjustDC");function adjustDCByRarity(dc,rarity="common"){return adjustDC(dc,rarityToDCAdjustment(rarity))}__name(adjustDCByRarity,"adjustDCByRarity"),__name2(adjustDCByRarity,"adjustDCByRarity");function calculateDC(level,{proficiencyWithoutLevel,rarity="common"}={}){proficiencyWithoutLevel??=game.settings.get("pf2e","proficiencyVariant");const dc=dcByLevel.get(level)??14;return adjustDCByRarity(proficiencyWithoutLevel?dc-Math.max(level,0):dc,rarity)}__name(calculateDC,"calculateDC"),__name2(calculateDC,"calculateDC");function calculateSimpleDC(rank,{proficiencyWithoutLevel=!1}={}){return proficiencyWithoutLevel?simpleDCsWithoutLevel.get(rank)??10:simpleDCs.get(rank)??10}__name(calculateSimpleDC,"calculateSimpleDC"),__name2(calculateSimpleDC,"calculateSimpleDC");function combineDCAdjustments(first,second){const startingIndex=adjustmentScale.indexOf(first),lowerByIndex=adjustmentScale.indexOf(second),resultIndex=Math.min(Math.max(startingIndex+lowerByIndex-3,0),6);return adjustmentScale[resultIndex]}__name(combineDCAdjustments,"combineDCAdjustments"),__name2(combineDCAdjustments,"combineDCAdjustments");function createDifficultyScale(dc,startAt){const beginAtIndex=adjustmentScale.indexOf(startAt);return adjustmentScale.filter((_value2,index)=>index>=beginAtIndex).map(value=>adjustDC(dc,value))}__name(createDifficultyScale,"createDifficultyScale"),__name2(createDifficultyScale,"createDifficultyScale");function loreSkillsFromActors(actors){const characters=(Array.isArray(actors)?actors:[actors]).filter(a=>a?.type==="character");return Object.fromEntries(characters.flatMap(m=>Object.values(m.skills)).filter(s=>!!s?.lore).map(s=>[s.slug,s.label]))}__name(loreSkillsFromActors,"loreSkillsFromActors"),__name2(loreSkillsFromActors,"loreSkillsFromActors");async function getActions(){const indexFields=["system.slug"],pack=game.packs.get("pf2e.actionspf2e");if(pack){const actions=(await pack.getIndex({fields:indexFields})).map(a=>[a.system.slug,a.name]);return Object.fromEntries(actions)}else return{}}__name(getActions,"getActions"),__name2(getActions,"getActions");const _CheckPromptDialog=class extends Application{static{__name(this,"_CheckPromptDialog")}constructor(){super(...arguments),__privateAdd(this,_prepareProficiencyRanks),__privateAdd(this,_prepareDCAdjustments),__privateAdd(this,_generatePrompt),__privateAdd(this,_htmlQueryTags),__privateAdd(this,_formatLoreType),__privateAdd(this,_formatActionType),__privateAdd(this,_getDC),__privateAdd(this,_constructCheck),__privateAdd(this,_actions,void 0),__privateAdd(this,_lores,void 0)}static get defaultOptions(){return{...super.defaultOptions,classes:["dialog"],id:"generate-check-prompt",tabs:[{navSelector:".skill-save-navigation",contentSelector:".check-prompt-content",initial:"skills"},{navSelector:".dc-navigation",contentSelector:".dc-content",initial:"set-dc"}],template:"systems/pf2e/templates/gm/check-prompt.hbs",title:game.i18n.localize("PF2E.Actor.Party.CheckPrompt.Title"),width:400,height:"auto"}}async getData(){return __privateSet(this,_actions,await getActions()),__privateSet(this,_lores,loreSkillsFromActors(this.options.actors??game.actors.party?.members??[])),{proficiencyRanks:__privateMethod(this,_prepareProficiencyRanks,prepareProficiencyRanks_fn).call(this),dcAdjustments:__privateMethod(this,_prepareDCAdjustments,prepareDCAdjustments_fn).call(this)}}activateListeners($html){const html=$html[0],skillEl=html.querySelector("input#check-prompt-skills"),skills={...omit(CONFIG.PF2E.skillList,["lore"]),perception:"PF2E.PerceptionLabel"};tagify$1(skillEl,{whitelist:skills});const saveEl=html.querySelector("input#check-prompt-saves");tagify$1(saveEl,{whitelist:CONFIG.PF2E.saves});const loreEl=html.querySelector("input#check-prompt-lores"),loreOptions=isEmpty(__privateGet(this,_lores)||{})?{}:{whitelist:__privateGet(this,_lores)};tagify$1(loreEl,loreOptions);const actionEl=html.querySelector("input#check-prompt-actions"),actionOptions=isEmpty(__privateGet(this,_actions)||{})?{}:{whitelist:__privateGet(this,_actions),enforceWhitelist:!1};tagify$1(actionEl,actionOptions);const traitEl=html.querySelector("input#check-prompt-traits");tagify$1(traitEl,{whitelist:CONFIG.PF2E.actionTraits,enforceWhitelist:!1}),html.querySelector("div.form-group a.add-roll-options")?.addEventListener("click",()=>{const sectionEl=html.querySelector("section.check-prompt-content");sectionEl&§ionEl.classList.toggle("show-roll-options")}),htmlQuery(html,"[data-action=post]")?.addEventListener("click",async()=>{__privateMethod(this,_generatePrompt,generatePrompt_fn).call(this)}),htmlQuery(html,"[data-action=cancel]")?.addEventListener("click",async()=>{this.close()})}};_actions=new WeakMap,_lores=new WeakMap,_prepareProficiencyRanks=new WeakSet,prepareProficiencyRanks_fn=__name2(function(){const proficiencyWithoutLevel=game.settings.get("pf2e","proficiencyVariant");return PROFICIENCY_RANKS.map(value=>({value,label:`${value} (${calculateSimpleDC(value,{proficiencyWithoutLevel})})`}))},"#prepareProficiencyRanks"),_prepareDCAdjustments=new WeakSet,prepareDCAdjustments_fn=__name2(function(){return Object.entries(CONFIG.PF2E.dcAdjustments).filter(([value,_])=>value!=="normal").map(([value,name2])=>({value,label:`${game.i18n.localize(name2)} (${signedInteger(adjustDC(0,value))})`}))},"#prepareDCAdjustments"),_generatePrompt=new WeakSet,generatePrompt_fn=__name2(function(){const html=this.element[0],types=[],traits=[],extras=[],activeSkillSaveTab=htmlQuery(html,"section.check-prompt-content section.tab.active");if(activeSkillSaveTab?.dataset.tab==="skills"?(types.push(...__privateMethod(this,_htmlQueryTags,htmlQueryTags_fn).call(this,html,"input#check-prompt-skills")),types.push(...__privateMethod(this,_htmlQueryTags,htmlQueryTags_fn).call(this,html,"input#check-prompt-lores").map(t=>__privateMethod(this,_formatLoreType,formatLoreType_fn).call(this,t))),traits.push(...__privateMethod(this,_htmlQueryTags,htmlQueryTags_fn).call(this,html,"input#check-prompt-traits")),traits.push(...__privateMethod(this,_htmlQueryTags,htmlQueryTags_fn).call(this,html,"input#check-prompt-actions").map(a=>__privateMethod(this,_formatActionType,formatActionType_fn).call(this,a))),html.querySelector("input#check-prompt-secret:checked")&&!traits.includes("secret")&&traits.push("secret")):activeSkillSaveTab?.dataset.tab==="saves"&&(types.push(...__privateMethod(this,_htmlQueryTags,htmlQueryTags_fn).call(this,html,"input#check-prompt-saves")),htmlQuery(html,"input#check-prompt-basic-save:checked")&&extras.push("basic:true")),types.length>0){const titleEl=htmlQuery(html,"input#check-prompt-title"),flavor=titleEl?.value?`

${titleEl.value}


`:"",dc=__privateMethod(this,_getDC,getDC_fn).call(this,html),content=types.map(type=>__privateMethod(this,_constructCheck,constructCheck_fn).call(this,type,dc,traits,extras)).join("");ChatMessagePF2e.create({user:game.user.id,flavor,content})}},"#generatePrompt"),_htmlQueryTags=new WeakSet,htmlQueryTags_fn=__name2(function(html,selector){const el=htmlQuery(html,selector);return(el instanceof HTMLInputElement&&el.value?JSON.parse(el.value):[]).map(tag=>tag.id||tag.value)},"#htmlQueryTags"),_formatLoreType=new WeakSet,formatLoreType_fn=__name2(function(type){let loreType=type.toLowerCase().replaceAll(" ","-").trim();return loreType.includes("lore")||(loreType=loreType.concat("-lore")),loreType},"#formatLoreType"),_formatActionType=new WeakSet,formatActionType_fn=__name2(function(type){return`action:${type.toLowerCase().replace("action:","").trim()}`},"#formatActionType"),_getDC=new WeakSet,getDC_fn=__name2(function(html){const proficiencyWithoutLevel=game.settings.get("pf2e","proficiencyVariant"),dc=(()=>{const activeDCTab=htmlQuery(html,"section.dc-content section.tab.active");if(activeDCTab?.dataset.tab==="set-dc")return Number(htmlQuery(html,"input#check-prompt-dc")?.value||NaN);if(activeDCTab?.dataset.tab==="simple-dc"){const profRank=htmlQuery(html,"select#check-prompt-simple-dc")?.value;if(tupleHasValue(PROFICIENCY_RANKS,profRank))return calculateSimpleDC(profRank,{proficiencyWithoutLevel})}else if(activeDCTab?.dataset.tab==="level-dc"){const level=Number(htmlQuery(html,"input#check-prompt-level-dc")?.value||NaN);if(Number.isInteger(level))return calculateDC(+level,{proficiencyWithoutLevel})}return NaN})();if(Number.isInteger(dc)){const dcAdjustment=htmlQuery(html,"select#check-prompt-adjust-difficulty")?.value;return dcAdjustment?adjustDC(dc,dcAdjustment):dc}return null},"#getDC"),_constructCheck=new WeakSet,constructCheck_fn=__name2(function(type,dc,traits,extras){return`

@Check[${[type,Number.isInteger(dc)?`dc:${dc}`:null,traits.length?`traits:${traits.join(",")}`:null].concat(...extras).filter(p=>p).join("|")}]

`},"#constructCheck"),__name2(_CheckPromptDialog,"CheckPromptDialog");let CheckPromptDialog=_CheckPromptDialog;async function checkPrompt(options={}){new CheckPromptDialog(options.actors?{actors:options.actors}:{}).render(!0)}__name(checkPrompt,"checkPrompt"),__name2(checkPrompt,"checkPrompt");function buildRewards(...rewards){const[trained,expert,master,legendary]=rewards;return{1:new CoinsPF2e(trained),2:new CoinsPF2e(expert??trained),3:new CoinsPF2e(master??expert??trained),4:new CoinsPF2e(legendary??master??expert??trained)}}__name(buildRewards,"buildRewards"),__name2(buildRewards,"buildRewards");const earnIncomeTable={0:{failure:{cp:1},rewards:buildRewards({cp:5})},1:{failure:{cp:2},rewards:buildRewards({sp:2})},2:{failure:{cp:4},rewards:buildRewards({sp:3})},3:{failure:{cp:8},rewards:buildRewards({sp:5})},4:{failure:{sp:1},rewards:buildRewards({sp:7},{sp:8})},5:{failure:{sp:2},rewards:buildRewards({sp:9},{gp:1})},6:{failure:{sp:3},rewards:buildRewards({gp:1,sp:5},{gp:2})},7:{failure:{sp:4},rewards:buildRewards({gp:2},{gp:2,sp:5})},8:{failure:{sp:5},rewards:buildRewards({gp:2,sp:5},{gp:3})},9:{failure:{sp:6},rewards:buildRewards({gp:3},{gp:4})},10:{failure:{sp:7},rewards:buildRewards({gp:4},{gp:5},{gp:6})},11:{failure:{sp:8},rewards:buildRewards({gp:5},{gp:6},{gp:8})},12:{failure:{sp:9},rewards:buildRewards({gp:6},{gp:8},{gp:10})},13:{failure:{gp:1},rewards:buildRewards({gp:7},{gp:10},{gp:15})},14:{failure:{gp:1,sp:5},rewards:buildRewards({gp:8},{gp:15},{gp:20})},15:{failure:{gp:2},rewards:buildRewards({gp:10},{gp:20},{gp:28})},16:{failure:{gp:2,sp:5},rewards:buildRewards({gp:13},{gp:25},{gp:36},{gp:40})},17:{failure:{gp:3},rewards:buildRewards({gp:15},{gp:30},{gp:45},{gp:55})},18:{failure:{gp:4},rewards:buildRewards({gp:20},{gp:45},{gp:70},{gp:90})},19:{failure:{gp:6},rewards:buildRewards({gp:30},{gp:60},{gp:100},{gp:130})},20:{failure:{gp:8},rewards:buildRewards({gp:40},{gp:75},{gp:150},{gp:200})},21:{failure:{cp:0},rewards:buildRewards({gp:50},{gp:90},{gp:175},{gp:300})}};function getIncomeForLevel(level){const income=earnIncomeTable[Math.clamped(level,0,21)];return{failure:new CoinsPF2e(income.failure),rewards:income.rewards}}__name(getIncomeForLevel,"getIncomeForLevel"),__name2(getIncomeForLevel,"getIncomeForLevel");function applyIncomeOptions({result,options,level,proficiency}){options.useLoreAsExperiencedProfessional&&(result.degreeOfSuccess===DegreeOfSuccess.CRITICAL_FAILURE?(result.degreeOfSuccess=DegreeOfSuccess.FAILURE,result.rewards=new CoinsPF2e(getIncomeForLevel(level).failure)):result.degreeOfSuccess===DegreeOfSuccess.FAILURE&&proficiency!==1&&(result.rewards=new CoinsPF2e(result.rewards).scale(2)))}__name(applyIncomeOptions,"applyIncomeOptions"),__name2(applyIncomeOptions,"applyIncomeOptions");function earnIncome({level,days,rollBrief,proficiency,options,dc}){const degree=new DegreeOfSuccess(rollBrief,dc),result={rewards:new CoinsPF2e,degreeOfSuccess:degree.value};return degree.value===DegreeOfSuccess.CRITICAL_SUCCESS?result.rewards=getIncomeForLevel(level+1).rewards[proficiency]:degree.value===DegreeOfSuccess.SUCCESS?result.rewards=getIncomeForLevel(level).rewards[proficiency]:degree.value===DegreeOfSuccess.FAILURE&&(result.rewards=getIncomeForLevel(level).failure),applyIncomeOptions({result,options,level,proficiency}),{rewards:{perDay:result.rewards,combined:new CoinsPF2e(result.rewards).scale(days)},degreeOfSuccess:result.degreeOfSuccess,daysSpentWorking:days,level,dc,roll:degree.rollTotal}}__name(earnIncome,"earnIncome"),__name2(earnIncome,"earnIncome");function escapeHtml(text){const p=document.createElement("p");return p.innerText=text,p.innerHTML}__name(escapeHtml,"escapeHtml"),__name2(escapeHtml,"escapeHtml");function isExperiencedProfessional(actor){return actor.itemTypes.feat.some(i=>i.slug==="experienced-professional")}__name(isExperiencedProfessional,"isExperiencedProfessional"),__name2(isExperiencedProfessional,"isExperiencedProfessional");function degreeOfSuccessLabel(degreeIndex){const degreeSlug=DEGREE_OF_SUCCESS_STRINGS[degreeIndex];return game.i18n.localize(`PF2E.Check.Result.Degree.Check.${degreeSlug}`)}__name(degreeOfSuccessLabel,"degreeOfSuccessLabel"),__name2(degreeOfSuccessLabel,"degreeOfSuccessLabel");function coinsToString(coins,degreeOfSuccess){return degreeOfSuccess===0?"none":coins.toString()}__name(coinsToString,"coinsToString"),__name2(coinsToString,"coinsToString");function chatTemplate(skillName,earnIncomeResult){const degreeOfSuccess=degreeOfSuccessLabel(earnIncomeResult.degreeOfSuccess),payPerDay=escapeHtml(coinsToString(earnIncomeResult.rewards.perDay,earnIncomeResult.degreeOfSuccess)),combinedPay=escapeHtml(coinsToString(earnIncomeResult.rewards.combined,earnIncomeResult.degreeOfSuccess)),level=earnIncomeResult.level,daysSpentWorking=earnIncomeResult.daysSpentWorking,forDays=daysSpentWorking>1?`

Salary for ${daysSpentWorking} days ${combinedPay}

`:"",successColor=earnIncomeResult.degreeOfSuccess>1?"darkgreen":"darkred",dc=earnIncomeResult.dc,roll=earnIncomeResult.roll;return` +var __defProp=Object.defineProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __defProp2=Object.defineProperty,__getProtoOf=Object.getPrototypeOf,__reflectGet=Reflect.get,__defNormalProp=__name((obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,"__defNormalProp"),__name2=__name((target,value)=>__defProp2(target,"name",{value,configurable:!0}),"__name"),__publicField=__name((obj,key,value)=>(__defNormalProp(obj,typeof key!="symbol"?key+"":key,value),value),"__publicField"),__accessCheck=__name((obj,member,msg)=>{if(!member.has(obj))throw TypeError("Cannot "+msg)},"__accessCheck"),__privateGet=__name((obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),"__privateGet"),__privateAdd=__name((obj,member,value)=>{if(member.has(obj))throw TypeError("Cannot add the same private member more than once");member instanceof WeakSet?member.add(obj):member.set(obj,value)},"__privateAdd"),__privateSet=__name((obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),"__privateSet"),__privateMethod=__name((obj,member,method)=>(__accessCheck(obj,member,"access private method"),method),"__privateMethod"),__superGet=__name((cls,obj,key)=>__reflectGet(__getProtoOf(cls),key,obj),"__superGet"),_updateMigrationRecord,updateMigrationRecord_fn,_migrateDocuments,migrateDocuments_fn,_migrateItem,migrateItem_fn,_migrateActor,migrateActor_fn,_migrateWorldJournalEntry,migrateWorldJournalEntry_fn,_migrateWorldMacro,migrateWorldMacro_fn,_migrateWorldTable,migrateWorldTable_fn,_migrateSceneToken,migrateSceneToken_fn,_migrateUser,migrateUser_fn,_data,_diehardPromise,_featSlugs,_featsPromise,_IMAGE_PATHS,_regexp,_renameToWebP,renameToWebP_fn,_isABCK,isABCK_fn,_BASE_ARMORS,_MAGIC_ARMOR_TO_BASE,_BASE_WEAPONS,_isTrue,isTrue_fn,_testBinaryOp,testBinaryOp_fn,_testCompound,testCompound_fn,_binaryOperators,_imageOverrides,_sizeOverrides,_isTokenImageFlag,isTokenImageFlag_fn,_isTokenSizeFlag,isTokenSizeFlag_fn,_needsRuleElement,needsRuleElement_fn,_increasesByOne,_isClassFeature,isClassFeature_fn,_pathsToRemove,_isRemovableAE,isRemovableAE_fn,_isRemoveableChange,isRemoveableChange_fn,_fixClassKeyAbilities,fixClassKeyAbilities_fn,_isTokenSizeRE,isTokenSizeRE_fn,_isActorSizeAELike,isActorSizeAELike_fn,_isBracketedValue,isBracketedValue_fn,_setAncestryVision,setAncestryVision_fn,_resolveBracketedValue,resolveBracketedValue_fn,_coerceNumber,coerceNumber_fn,_traitsDictionary,traitsDictionary_get,_handleModeAffectingTrait,handleModeAffectingTrait_fn,_getDegreeAdjustment,getDegreeAdjustment_fn,_adjustDegreeOfSuccess,adjustDegreeOfSuccess_fn,_adjustDegreeByDieValue,adjustDegreeByDieValue_fn,_calculateDegreeOfSuccess,calculateDegreeOfSuccess_fn,_SKILL_LONG_FORM_PATH,_rewriteSkillLongFormPath,rewriteSkillLongFormPath_fn,_pathIsValid,pathIsValid_fn,_logChange,logChange_fn,_processEffects,processEffects_fn,_processAppearanceData,processAppearanceData_fn,_createMovementType,createMovementType_fn,_customLabel,_weapon,_resolveOptions,resolveOptions_fn,_actions,_lores,_prepareProficiencyRanks,prepareProficiencyRanks_fn,_prepareDCAdjustments,prepareDCAdjustments_fn,_generatePrompt,generatePrompt_fn,_htmlQueryTags,htmlQueryTags_fn,_formatLoreType,formatLoreType_fn,_formatActionType,formatActionType_fn,_getDC,getDC_fn,_constructCheck,constructCheck_fn,_renderFormula,renderFormula_fn,_prepareDamageTypes,prepareDamageTypes_fn,_getInputElements,getInputElements_fn,_disableScale,disableScale_fn,_reestablishPrototype,reestablishPrototype_fn,_disableVisionInputs,disableVisionInputs_fn,_drawBorder,drawBorder_fn,_drawTexture,drawTexture_fn,_drawLabel,drawLabel_fn,_showBordersHighlights,showBordersHighlights_get,_moveTime,_wheelListenerOptions,_onPreviewMouseMove,_onPreviewLeftClick,_onPreviewRightClick,_onPreviewMouseWheel,_squares,_prepareDerivedPerception,prepareDerivedPerception_fn,_getChoices,getChoices_fn,_filterTimeout,_getUpdateData,getUpdateData_fn,_search,search_fn,_onFilterResults,onFilterResults_fn,_updateIWR,updateIWR_fn,_sortableOnMoveData,_activateInventoryDragDrop,activateInventoryDragDrop_fn,_sortableOnMove,sortableOnMove_fn,_sortableOnEnd,sortableOnEnd_fn,_onClickDeleteItem,onClickDeleteItem_fn,_onClickBrowseEquipment,onClickBrowseEquipment_fn,_onClickCreateItem,onClickCreateItem_fn,_onClickSellAllTreasure,onClickSellAllTreasure_fn,_resolve,_originallyEnabled,_getModifierIcon,getModifierIcon_fn,_getTypeLabel,getTypeLabel_fn,_applyStackingRules,applyStackingRules_fn,_localize,localize_fn,_createTemplate,createTemplate_fn,_parseInlineParams,parseInlineParams_fn,_createCheck,createCheck_fn,_createSingleCheck,createSingleCheck_fn,_createDamageRoll,createDamageRoll_fn,_createActionOptions,createActionOptions_fn,_originallyEnabled2,_resolveSubstitutions,resolveSubstitutions_fn,_createTagFlavor,createTagFlavor_fn,_createResultFlavor,createResultFlavor_fn,_resolveCheckDC,resolveCheckDC_fn,_item,_resolve2,_action,_canSetAttribute,canSetAttribute_fn,_searchEngine,_getSpellFromEvent,getSpellFromEvent_fn,_onConfigureActor,onConfigureActor_fn,_onToggleSignatureSpell,onToggleSignatureSpell_fn,_onClickBrowseActions,onClickBrowseActions_fn,_onClickBrowseSpellCompendia,onClickBrowseSpellCompendia_fn,_abpEnabled,_createButtons,createButtons_fn,_calculateAncestryBoosts,calculateAncestryBoosts_fn,_calculateBackgroundBoosts,calculateBackgroundBoosts_fn,_calculateLeveledBoosts,calculateLeveledBoosts_fn,_getBoostFlawLabels,getBoostFlawLabels_fn,_updateRE,updateRE_fn,_blastConfigSchema,_blastInfusionSchema,_prepareBlastConfigs,prepareBlastConfigs_fn,_prepareBlastInfusion,prepareBlastInfusion_fn,_getBlastConfig,getBlastConfig_fn,_createModifiedItem,createModifiedItem_fn,_strengthModToDamage,strengthModToDamage_fn,_knownFormulas,_formulaQuantities,_prepareAbilities,prepareAbilities_fn,_prepareCraftingEntries,prepareCraftingEntries_fn,_getBlastData,getBlastData_fn,_activateBlastListeners,activateBlastListeners_fn,_onClickBrowseFeats,onClickBrowseFeats_fn,_onChangeAdjustStat,onChangeAdjustStat_fn,_onChangeAdjustItemStat,onChangeAdjustItemStat_fn,_onClickAdjustItemStat,onClickAdjustItemStat_fn,_getFeatSlotData,getFeatSlotData_fn,_sortFormulas,sortFormulas_fn,_strikeItemId,_strikeSlug,_strike,_elementTrait,_blasts,_getReach,getReach_fn,_isValid,isValid_fn,_constructWeapon,constructWeapon_fn,_defaultIcons,_setRollOptions,setRollOptions_fn,_prepareAC,prepareAC_fn,_prepareSenses,prepareSenses_fn,_prepareSize,prepareSize_fn,_prepareSpeeds,prepareSpeeds_fn,_prepareSkills,prepareSkills_fn,_prepareStrikes,prepareStrikes_fn,_prepareIWR,prepareIWR_fn,_suppressModifiers,suppressModifiers_fn,_filterModifier,filterModifier_fn,_suppressNotes,suppressNotes_fn,_resolveStrikeQueries,resolveStrikeQueries_fn,_resolve3,_setDefaultFlag,setDefaultFlag_fn,_choicesFromArray,choicesFromArray_fn,_choicesFromPath,choicesFromPath_fn,_choicesFromOwnedItems,choicesFromOwnedItems_fn,_choicesFromAttacks,choicesFromAttacks_fn,_getPreselection,getPreselection_fn,_setRollOption,setRollOption_fn,_getEffect,getEffect_fn,_isValidOverride,isValidOverride_fn,_resolvedBracketsIsValid,resolvedBracketsIsValid_fn,_validateForItem,_adjustCreatureShieldData,adjustCreatureShieldData_fn,_getNewInterval,getNewInterval_fn,_createDeferredEffect,createDeferredEffect_fn,_getOnDeleteActions,getOnDeleteActions_fn,_applyChoiceSelections,applyChoiceSelections_fn,_setGrantFlags,setGrantFlags_fn,_runGrantedItemPreCreates,runGrantedItemPreCreates_fn,_createInMemoryCondition,createInMemoryCondition_fn,_trackItem,trackItem_fn,_resolveOption,resolveOption_fn,_setFlag,setFlag_fn,_setRollOption2,setRollOption_fn2,_effect,_srcIsValid,srcIsValid_fn,_target,_resolve4,_cancelHandler,cancelHandler_fn,_checkRuleSource,checkRuleSource_fn,_activeTab,_getFormHelpers,getFormHelpers_fn,_effectsMap,_addEffect,addEffect_fn,_updateEffectsMap,updateEffectsMap_fn,_deleteEffect,deleteEffect_fn,_selectedRuleElementType,_editingRuleElementIndex,_rulesLastScrollTop,_ruleElementForms,_createRuleElementForms,createRuleElementForms_fn,_initialRefresh,_damageManager,_processDeletions,processDeletions_fn,_refreshSettings,refreshSettings_fn,_registerModuleTags,registerModuleTags_fn,_getConfigRecord,getConfigRecord_fn,_updateConfigRecords,updateConfigRecords_fn,_isFlatModifier,isFlatModifier_fn,_toRuleElement,toRuleElement_fn,_rationsSourceId,_rationsPromise,_isOldRations,isOldRations_fn,_getRationRefs,getRationRefs_fn,_migrateClass,migrateClass_fn,_migrateFeature,migrateFeature_fn,_isClassFeature2,isClassFeature_fn2,_isClassFeature3,isClassFeature_fn3,_isHeritageFeature,isHeritageFeature_fn,_officialAncestries,_heritagesWithoutAncestryInName,_ancestrySlugs,_heritageFromFeat,heritageFromFeat_fn,_explorersClothingVariants,_pathPattern,_hasWellFormedFeatType,hasWellFormedFeatType_fn,_needsTrait,needsTrait_fn,_hasBrokenThreshold,hasBrokenThreshold_fn,_shadowPromise,_cascadePromise,_isEffectTargetRE,isEffectTargetRE_fn,_toChoiceSet,toChoiceSet_fn,_loadedSpells,_isChoiceSetWithSelection,isChoiceSetWithSelection_fn,_newRules,newRules_fn,_toSkip,_hasThrownTrait,hasThrownTrait_fn,_cleanText,cleanText_fn,_updateEffect,updateEffect_fn,_updateFeat,updateFeat_fn,_vivaciousRules,vivaciousRules_get,_auraOfLife,_enlightenedPresence,_eternalBlessing,_marshalsAura,_findDamageDiceRE,findDamageDiceRE_fn,_isClassFeature4,isClassFeature_fn4,_athleticStrategist,athleticStrategist_get,_deviseAStratagem,deviseAStratagem_get,_ruffianPredicate,ruffianPredicate_get,_sneakAttackPredicate,sneakAttackPredicate_get,_updateSpeed,updateSpeed_fn,_suppressNoCrowbar,suppressNoCrowbar_get,_convertToUUIDs,convertToUUIDs_fn,_getRules,getRules_fn,_preciseStrikeRules,preciseStrikeRules_get,_finishingPrecisionRules,finishingPrecisionRules_get,_otherClassDCs,_isClassFeature5,isClassFeature_fn5,_critSpec,critSpec_get,_hands,hands_get,_convertLegacyData,convertLegacyData_fn,_isOldRawPredicate,isOldRawPredicate_fn,_isArrayChoiceSet,isArrayChoiceSet_fn,_isObjectChoiceSet,isObjectChoiceSet_fn,_shapeFeats,_flatFootedToggle,flatFootedToggle_get,_isFlatFootedToggle,isFlatFootedToggle_fn,_convertToEntry,convertToEntry_fn,_modifyFlag,modifyFlag_fn,_oldIdsPattern,_colorDarkvision,colorDarkvision_get,_AREA_TYPES,_isAreaType,isAreaType_fn,_hasDetails,hasDetails_fn,_pattern,_damageTypeLabelPattern,_updateDamageFormula,updateDamageFormula_fn,_automatonEnhancements,automatonEnhancements_get,_conditionPattern,_pattern2,_updateDamageFormula2,updateDamageFormula_fn2,_getWR,getWR_fn,_oldENmappings,_parseExceptions,parseExceptions_fn,_normalizeType,normalizeType_fn,_updateWeaponMaterialData,updateWeaponMaterialData_fn,_updateChoiceSet,updateChoiceSet_fn,_bomberSetFlags,bomberSetFlags_get,_chirurgeonSetFlags,chirurgeonSetFlags_get,_mutagenistSetFlags,mutagenistSetFlags_get,_toxicologistSetFlags,toxicologistSetFlags_get,_needsRE,needsRE_fn,_splashPattern1,_splashPattern2,_damagePatternSingle,_damagePatternPair,_cleanFormula,cleanFormula_fn,_buildSplashFormula,buildSplashFormula_fn,_buildDamageFormula,buildDamageFormula_fn,_updateDamageFormula3,updateDamageFormula_fn3,_rename,rename_fn,_removeLinks,removeLinks_fn,_cloisteredClericSetFlags,cloisteredClericSetFlags_get,_warpriestSetFlags,warpriestSetFlags_get,_updateCategoryData,updateCategoryData_fn,_rename2,rename_fn2,_wrapPredicate,wrapPredicate_fn,_replaceUUID,replaceUUID_fn,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn,_updateUUIDs,updateUUIDs_fn,_idMap,_oldToNew,_oldNamePattern,_newName,_imgPattern,_aToAnUUIDPatern,_replace,replace_fn,_OLD_TO_NEW_LANGUAGES,_testHasOption,testHasOption_fn,_hasOldMaterialData,hasOldMaterialData_fn,_resilientRuneValues,_replaceStrings,replaceStrings_fn,_mightyBulwarkRules,mightyBulwarkRules_get,_defensePathPattern,_mvSchema,mvSchema_fn,_setPublicationData,setPublicationData_fn,_list,_finalizeDamage,finalizeDamage_fn,_excludeDamage,excludeDamage_fn,_strengthModToDamage2,strengthModToDamage_fn2,_check,_dc,_determineLabel,determineLabel_fn,_createBonusesAndPenalties,createBonusesAndPenalties_fn,_createShieldBonus,createShieldBonus_fn,_baseMax,_currentFilter,_lastClick,_onClickButton,onClickButton_fn,_rollActorSaves,rollActorSaves_fn,_onHoverIn,onHoverIn_fn,_onHoverOut,onHoverOut_fn,_initialized,_value,_actorStrength,actorStrength_get,_flattenNonStowing,flattenNonStowing_fn,_localize2,_initialize,initialize_fn,_handleTrickItem,handleTrickItem_fn,_assertEntryIsDocument,assertEntryIsDocument_fn,_getRitualData,getRitualData_fn,_idMap2,_slugMap,_templatePaths,_getActor,getActor_fn,_getSource,getSource_fn,_getTarget,getTarget_fn,_tokenName,tokenName_fn,_sendMessage,sendMessage_fn,_messageFlavor,messageFlavor_fn,_findBestLocation,findBestLocation_fn,_getChildSlots,getChildSlots_fn,_editingSettlements,_prepareSettlement,prepareSettlement_fn,_activateSettlementEvents,activateSettlementEvents_fn,_getFeatSlotData2,getFeatSlotData_fn2,_prepareAbilityBuilder,prepareAbilityBuilder_fn,_originalValue,_slider,_noRefreshHook,_hasRollOptionData,hasRollOptionData_fn,_createItemMacro,createItemMacro_fn,_createRollOptionToggleMacro,createRollOptionToggleMacro_fn,_draggingParty,_onDragHighlightFolderLike,onDragHighlightFolderLike_fn,_appendBrowseButton,appendBrowseButton_fn,_appendBrowseButton2,appendBrowseButton_fn2,_messageFromEvent,messageFromEvent_fn,_onClickDamageButton,onClickDamageButton_fn,_onClickRevertDamage,onClickRevertDamage_fn,_onClickShieldBlock,onClickShieldBlock_fn,_onClickSender,onClickSender_fn,_dragPreview,dragPreview_get,_onToggleTarget,onToggleTarget_fn,_onDropCombatant,onDropCombatant_fn,_setModuleArt,setModuleArt_fn,_getSources,getSources_fn,_createFilteredIndex,createFilteredIndex_fn,_loadSources,loadSources_fn,_getSourceFromDocument,getSourceFromDocument_fn,_domParser,_getRollTableResults,getRollTableResults_fn,_localizeCoins,_creatureTraits,_resetInitializedTabs,resetInitializedTabs_fn,_renderResultList,renderResultList_fn,_activateResultListeners,activateResultListeners_fn,_takePhysicalItem,takePhysicalItem_fn,_buyPhysicalItem,buyPhysicalItem_fn,_getPhysicalItem,getPhysicalItem_fn,_resetFilters,resetFilters_fn,_clearScrollLimit,clearScrollLimit_fn,_getRemainingDurationLabel,getRemainingDurationLabel_fn,_getEnrichedDescriptions,getEnrichedDescriptions_fn,_lastCombatantToken,_ICON_THEME_DIRS,_conditionSummaries,_activateListeners,activateListeners_fn,_updateStatusIcons,updateStatusIcons_fn,_showStatusLabel,showStatusLabel_fn,_setStatusValue,setStatusValue_fn,_toggleStatus,toggleStatus_fn,_createChatMessage,createChatMessage_fn,_action2,_cost,_description,_slug,_traits,_variants,_action3,_effect2,_action4,_difficultyClass,_modifiers,_notes,_rollOptions,_statistic,_insert,insert_fn,_removeExpired,removeExpired_fn,_getArtMap,getArtMap_fn,_isModuleArt,isModuleArt_fn,_retrieve,retrieve_fn,_deposit,deposit_fn,_getDepositSpaces,getDepositSpaces_fn,_prepareActions,prepareActions_fn,_prepareSaves,prepareSaves_fn,_identificationData,_padAttempts,padAttempts_fn,_prepareAbilities2,prepareAbilities_fn2,_prepareAlignment,prepareAlignment_fn,_prepareSkills2,prepareSkills_fn2,_prepareSaves2,prepareSaves_fn2,_onClickRollable,onClickRollable_fn,_rollAbility,rollAbility_fn,_prepareActions2,prepareActions_fn2,_onChangeSpellcastingEntry,onChangeSpellcastingEntry_fn,_prepareMembers,prepareMembers_fn,_prepareOverviewSummary,prepareOverviewSummary_fn,_getActorsThatUnderstand,getActorsThatUnderstand_fn,_renderRegions,renderRegions_fn,_isValidDrop,isValidDrop_fn,_formatSpellComponents,formatSpellComponents_fn,_prepareHeighteningLevels,prepareHeighteningLevels_fn,_activateRBVListeners,activateRBVListeners_fn;import{i as isNil,T as Tagify,p as pick$1,m as mapToObj,a as mapValues$1,o as omit,b as isObject$1,c as compact,k as keys,u as uniq,d as isEmpty,g as groupBy$1,e as equals,s as sortBy$1,S as Sortable,f as uniqBy,M as MiniSearch,h as difference,D as Duration,j as meanBy,E as EditorView,l as basicSetup,n as json,q as linter,r as keymap,t as indentWithTab,v as autocompletion,w as syntaxTree,x as jsonParseLinter,y as fromPairs,z as maxBy,A as sumBy,B as pipe,C as filter,F as map,I as Interval,G as DateTime,H as noUiSlider,P as PipsMode,J as findLast,K as omitBy}from"./vendor.mjs";const BabeleReady={listen(){Hooks.once("babele.ready",()=>{game.pf2e.ConditionManager.initialize(!0)})}},CanvasInit={listen:()=>{Hooks.on("canvasInit",async canvas2=>{SquareGrid.prototype.measureDistances=__name2(__name(function(segments,options={}){if(!options.gridSpaces)return BaseGrid.prototype.measureDistances.call(this,segments,options);let nDiagonal=0;const d=canvas2.dimensions;return segments.map(s=>{const r=s.ray,nx=Math.abs(Math.ceil(r.dx/d.size)),ny=Math.abs(Math.ceil(r.dy/d.size)),nd=Math.min(nx,ny),ns=Math.abs(ny-nx);nDiagonal+=nd;const nd10=Math.floor(nDiagonal/2)-Math.floor((nDiagonal-nd)/2);return(nd10*2+(nd-nd10)+ns)*canvas2.dimensions.distance})},"measureDistances"),"measureDistances")})}},_BaseStatistic=class{static{__name(this,"_BaseStatistic")}actor;slug;label;data;domains;modifiers;constructor(actor,data){this.actor=actor,this.slug=data.slug,this.label=game.i18n.localize(data.label).trim(),this.data={...data},this.domains=[...data.domains??=[]];const modifiers=[data.modifiers??[],extractModifiers(this.actor.synthetics,this.domains)].flat();if(this.modifiers=new StatisticModifier("",modifiers).modifiers.map(m=>m.clone()),this.domains.length>0){const options=this.createRollOptions();for(const modifier of this.modifiers)modifier.test(options)}}createRollOptions(domains=this.domains){return new Set(this.actor.getRollOptions(domains))}};__name2(_BaseStatistic,"BaseStatistic");let BaseStatistic=_BaseStatistic;const _MigrationRunnerBase=class{static{__name(this,"_MigrationRunnerBase")}constructor(migrations=[]){__privateAdd(this,_updateMigrationRecord),__publicField(this,"migrations"),this.migrations=migrations.sort((a,b)=>a.version-b.version)}needsMigration(currentVersion){return currentVersion0&&__privateMethod(this,_updateMigrationRecord,updateMigrationRecord_fn).call(this,current.system._migration,migrations.slice(-1)[0]),current}async getUpdatedTable(tableSource,migrations){const current=deepClone(tableSource);for(const migration of migrations)try{await migration.updateTable?.(current)}catch(err){console.error(err)}return current}async getUpdatedMacro(macroSource,migrations){const current=deepClone(macroSource);for(const migration of migrations)try{await migration.updateMacro?.(current)}catch(err){console.error(err)}return current}async getUpdatedJournalEntry(source,migrations){const clone=deepClone(source);for(const migration of migrations)try{await migration.updateJournalEntry?.(clone)}catch(err){console.error(err)}return clone}async getUpdatedToken(token,migrations){const current=token.toObject();for(const migration of migrations)await migration.updateToken?.(current,token.actor,token.scene);return current}async getUpdatedUser(userData,migrations){const current=deepClone(userData);for(const migration of migrations)try{await migration.updateUser?.(current)}catch(err){console.error(err)}return current}};_updateMigrationRecord=new WeakSet,updateMigrationRecord_fn=__name2(function(migrations,latestMigration){if(!("game"in globalThis&&latestMigration))return;const fromVersion=typeof migrations.version=="number"?migrations.version:null;migrations.version=latestMigration.version,migrations.previous={schema:fromVersion,foundry:game.version,system:game.system.version}},"#updateMigrationRecord"),__name2(_MigrationRunnerBase,"MigrationRunnerBase"),__publicField(_MigrationRunnerBase,"LATEST_SCHEMA_VERSION",.878),__publicField(_MigrationRunnerBase,"MINIMUM_SAFE_VERSION",.618),__publicField(_MigrationRunnerBase,"RECOMMENDED_SAFE_VERSION",.634),__publicField(_MigrationRunnerBase,"FOUNDRY_SCHEMA_VERSIONS",{.8:.634,9:.7,10:.781,11:.841});let MigrationRunnerBase=_MigrationRunnerBase;const _Progress=class{static{__name(this,"_Progress")}value=0;max;label;constructor({max,label}){this.label=label??"",this.max=max}advance({by=1,label=this.label}={}){if(this.value===this.max)return;this.value+=Math.abs(by);const pct=Math.floor(this.value/this.max*100);SceneNavigation.displayProgressBar({label,pct})}close({label=""}={}){SceneNavigation.displayProgressBar({label,pct:100})}};__name2(_Progress,"Progress");let Progress=_Progress;const _MigrationRunner=class _MigrationRunner2 extends MigrationRunnerBase{static{__name(this,"_MigrationRunner")}constructor(){super(...arguments),__privateAdd(this,_migrateDocuments),__privateAdd(this,_migrateItem),__privateAdd(this,_migrateActor),__privateAdd(this,_migrateWorldJournalEntry),__privateAdd(this,_migrateWorldMacro),__privateAdd(this,_migrateWorldTable),__privateAdd(this,_migrateSceneToken),__privateAdd(this,_migrateUser)}needsMigration(){return super.needsMigration(game.settings.get("pf2e","worldSchemaVersion"))}static async ensureSchemaVersion(document2,migrations){if(migrations.length===0)return;const currentVersion=this.LATEST_SCHEMA_VERSION;if((Number(document2.schemaVersion)||0){try{return"items"in source?await runner.getUpdatedActor(source,runner.migrations):await runner.getUpdatedItem(source,runner.migrations)}catch{return null}})();updated&&document2.updateSource(updated)}if(document2.updateSource({"system._migration.version":currentVersion}),"items"in document2&&"token"in document2)for(const item of document2.items)item.schemaVersion||item.updateSource({"system._migration.version":currentVersion})}async runCompendiumMigration(compendium){const pack=compendium.metadata.id;ui.notifications.info(game.i18n.format("PF2E.Migrations.Starting",{version:game.system.version}));const documents=await compendium.getDocuments();await compendium.documentClass.updateDocuments(documents,{diff:!1,recursive:!1,pack}),ui.notifications.info(game.i18n.format("PF2E.Migrations.Finished",{version:game.system.version}))}async runMigrations(migrations){if(migrations.length===0)return;const progress=new Progress({label:game.i18n.localize("PF2E.Migrations.Running"),max:Math.floor(game.actors.size+game.items.size+game.scenes.map(s=>s.tokens.contents).flat().filter(t=>t.actor?.isToken).length)});await __privateMethod(this,_migrateDocuments,migrateDocuments_fn).call(this,game.actors,migrations,progress),await __privateMethod(this,_migrateDocuments,migrateDocuments_fn).call(this,game.items,migrations,progress);for(const entry of game.journal)await __privateMethod(this,_migrateWorldJournalEntry,migrateWorldJournalEntry_fn).call(this,entry,migrations);const promises=[];for(const macro of game.macros)promises.push(__privateMethod(this,_migrateWorldMacro,migrateWorldMacro_fn).call(this,macro,migrations));for(const table of game.tables)promises.push(__privateMethod(this,_migrateWorldTable,migrateWorldTable_fn).call(this,table,migrations));for(const user of game.users)promises.push(__privateMethod(this,_migrateUser,migrateUser_fn).call(this,user,migrations));for(const migration of migrations)migration.migrate&&promises.push(migration.migrate());await Promise.allSettled(promises);for(const scene of game.scenes)for(const token of scene.tokens){const{actor}=token;if(!actor||!!!await __privateMethod(this,_migrateSceneToken,migrateSceneToken_fn).call(this,token,migrations))continue;const deltaSource=token.delta?._source,hasMigratableData=!!deltaSource&&!!deltaSource.flags?.pf2e||((deltaSource??{}).items??[]).length>0||Object.keys(deltaSource?.system??{}).length>0;if(actor.isToken){if(hasMigratableData){const updated=await __privateMethod(this,_migrateActor,migrateActor_fn).call(this,migrations,actor);if(updated)try{await actor.update(updated,{noHook:!0})}catch(error){console.warn(error)}}progress.advance()}}progress.valueschemaVersion.current0&&await this.runMigrations(migrationPhase);await game.settings.set("pf2e","worldSchemaVersion",schemaVersion.latest)}};_migrateDocuments=new WeakSet,migrateDocuments_fn=__name2(async function(collection,migrations,progress){const DocumentClass=collection.documentClass,pack="metadata"in collection?collection.metadata.id:null,updateGroup=[];for(const document2 of collection.contents.sort(a=>a.type==="familiar"?1:-1)){if(updateGroup.length===50)try{await DocumentClass.updateDocuments(updateGroup,{noHook:!0,pack}),progress?.advance({by:updateGroup.length})}catch(error){console.warn(error)}finally{updateGroup.length=0}const updated="items"in document2?await __privateMethod(this,_migrateActor,migrateActor_fn).call(this,migrations,document2,{pack}):await __privateMethod(this,_migrateItem,migrateItem_fn).call(this,migrations,document2);updated&&updateGroup.push(updated)}if(updateGroup.length>0)try{await DocumentClass.updateDocuments(updateGroup,{noHook:!0,pack}),progress?.advance({by:updateGroup.length})}catch(error){console.warn(error)}},"#migrateDocuments"),_migrateItem=new WeakSet,migrateItem_fn=__name2(async function(migrations,item){const baseItem=item.toObject();try{return this.getUpdatedItem(baseItem,migrations)}catch(error){return error instanceof Error&&console.error(`Error thrown while migrating ${item.uuid}: ${error.message}`),null}},"#migrateItem"),_migrateActor=new WeakSet,migrateActor_fn=__name2(async function(migrations,actor,options={}){const{pack}=options,baseActor=actor.toObject(),updatedActor=await(()=>{try{return this.getUpdatedActor(baseActor,migrations)}catch(error){return error instanceof Error&&console.error(`Error thrown while migrating ${actor.uuid}: ${error.message}`),null}})();if(!updatedActor)return null;actor.effects.size>0&&actor.deleteEmbeddedDocuments("ActiveEffect",[],{deleteAll:!0});const baseItems=[...baseActor.items],updatedItems=[...updatedActor.items],itemDiff=this.diffCollection(baseItems,updatedItems),finalDeleted=itemDiff.deleted.filter(id=>actor.items.has(id));if(finalDeleted.length>0)try{await actor.deleteEmbeddedDocuments("Item",finalDeleted,{noHook:!0,pack})}catch(error){console.warn(error)}const finalUpdated=itemDiff.updated.filter(i=>actor.items.has(i._id));return updatedActor.items=[...itemDiff.inserted,...finalUpdated],updatedActor},"#migrateActor"),_migrateWorldJournalEntry=new WeakSet,migrateWorldJournalEntry_fn=__name2(async function(journalEntry,migrations){if(migrations.some(migration=>!!migration.updateJournalEntry))try{const updated=await this.getUpdatedJournalEntry(journalEntry.toObject(),migrations),changes=diffObject(journalEntry.toObject(),updated);Object.keys(changes).length>0&&await journalEntry.update(changes,{noHook:!0})}catch(error){console.warn(error)}},"#migrateWorldJournalEntry"),_migrateWorldMacro=new WeakSet,migrateWorldMacro_fn=__name2(async function(macro,migrations){if(migrations.some(migration=>!!migration.updateMacro))try{const updatedMacro=await this.getUpdatedMacro(macro.toObject(),migrations),changes=diffObject(macro.toObject(),updatedMacro);Object.keys(changes).length>0&&await macro.update(changes,{noHook:!0})}catch(error){console.warn(error)}},"#migrateWorldMacro"),_migrateWorldTable=new WeakSet,migrateWorldTable_fn=__name2(async function(table,migrations){if(migrations.some(migration=>!!migration.updateTable))try{const updatedMacro=await this.getUpdatedTable(table.toObject(),migrations),changes=diffObject(table.toObject(),updatedMacro);Object.keys(changes).length>0&&table.update(changes,{noHook:!0})}catch(error){console.warn(error)}},"#migrateWorldTable"),_migrateSceneToken=new WeakSet,migrateSceneToken_fn=__name2(async function(token,migrations){if(!migrations.some(migration=>!!migration.updateToken))return token.toObject();try{const updatedToken=await this.getUpdatedToken(token,migrations),changes=diffObject(token.toObject(),updatedToken);if(Object.keys(changes).length>0)try{await token.update(changes,{noHook:!0})}catch(error){console.warn(error)}return updatedToken}catch(error){return console.error(error),null}},"#migrateSceneToken"),_migrateUser=new WeakSet,migrateUser_fn=__name2(async function(user,migrations){if(migrations.some(migration=>!!migration.updateUser))try{const baseUser=user.toObject(),updatedUser=await this.getUpdatedUser(baseUser,migrations),changes=diffObject(user.toObject(),updatedUser);Object.keys(changes).length>0&&await user.update(changes,{noHook:!0})}catch(error){console.error(error)}},"#migrateUser"),__name2(_MigrationRunner,"MigrationRunner");let MigrationRunner=_MigrationRunner;const _MigrationBase=class{static{__name(this,"_MigrationBase")}version=this.constructor.version;requiresFlush=!1};__name2(_MigrationBase,"MigrationBase"),__publicField(_MigrationBase,"version");let MigrationBase=_MigrationBase;const _Migration600Reach=class extends MigrationBase{static{__name(this,"_Migration600Reach")}async updateItem(item){item.type==="ancestry"&&(item.system.reach=5)}};__name2(_Migration600Reach,"Migration600Reach"),__publicField(_Migration600Reach,"version",.6);let Migration600Reach=_Migration600Reach;function createHTMLElement(nodeName,{classes=[],dataset={},children=[],innerHTML}={}){const element=document.createElement(nodeName);classes.length>0&&element.classList.add(...classes);for(const[key,value]of Object.entries(dataset).filter(([,v])=>!isNil(v)))element.dataset[key]=String(value);if(innerHTML)element.innerHTML=innerHTML;else for(const child of children){const childElement=child instanceof HTMLElement?child:new Text(child);element.appendChild(childElement)}return element}__name(createHTMLElement,"createHTMLElement"),__name2(createHTMLElement,"createHTMLElement");function htmlQuery(parent,selectors){return parent instanceof Element||parent instanceof Document?parent.querySelector(selectors):null}__name(htmlQuery,"htmlQuery"),__name2(htmlQuery,"htmlQuery");function htmlQueryAll(parent,selectors){return parent instanceof Element||parent instanceof Document?Array.from(parent.querySelectorAll(selectors)):[]}__name(htmlQueryAll,"htmlQueryAll"),__name2(htmlQueryAll,"htmlQueryAll");function htmlClosest(child,selectors){return child instanceof Element?child.closest(selectors):null}__name(htmlClosest,"htmlClosest"),__name2(htmlClosest,"htmlClosest");function groupBy(array,criterion){const result=new Map;for(const elem of array){const key=criterion(elem),group=result.get(key);group?group.push(elem):result.set(key,[elem])}return result}__name(groupBy,"groupBy"),__name2(groupBy,"groupBy");function sortBy(mapping){return(a,b)=>{const value1=mapping(a),value2=mapping(b);return value1(result[key]=mapping(value,key),result),{})}__name(mapValues,"mapValues"),__name2(mapValues,"mapValues");function isBlank(text){return text==null||text.trim()===""}__name(isBlank,"isBlank"),__name2(isBlank,"isBlank");function addSign(number){return number<0?`${number}`:`+${number}`}__name(addSign,"addSign"),__name2(addSign,"addSign");function sum(values){return values.reduce((a,b)=>a+b,0)}__name(sum,"sum"),__name2(sum,"sum");function zip(a,b,zipFunction){return a.length>b.length?b.map((elem,index)=>zipFunction(a[index],elem)):a.map((elem,index)=>zipFunction(elem,b[index]))}__name(zip,"zip"),__name2(zip,"zip");function applyNTimes(func,times,start){let result=start;for(let i=0;i(key in obj&&(result[key]=obj[key]),result),{})}__name(pick,"pick"),__name2(pick,"pick");let intlNumberFormat;function signedInteger(value,{emptyStringZero=!1}={}){return value===0&&emptyStringZero?"":(intlNumberFormat??=new Intl.NumberFormat(game.i18n.lang,{maximumFractionDigits:0,signDisplay:"always"})).format(value)}__name(signedInteger,"signedInteger"),__name2(signedInteger,"signedInteger");const wordCharacter=String.raw`[\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Join_Control}]`,nonWordCharacter=String.raw`[^\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Join_Control}]`,nonWordCharacterRE=new RegExp(nonWordCharacter,"gu"),wordBoundary=String.raw`(?:${wordCharacter})(?=${nonWordCharacter})|(?:${nonWordCharacter})(?=${wordCharacter})`,nonWordBoundary=String.raw`(?:${wordCharacter})(?=${wordCharacter})`,lowerCaseLetter=String.raw`\p{Lowercase_Letter}`,upperCaseLetter=String.raw`\p{Uppercase_Letter}`,lowerCaseThenUpperCaseRE=new RegExp(`(${lowerCaseLetter})(${upperCaseLetter}${nonWordBoundary})`,"gu"),nonWordCharacterHyphenOrSpaceRE=/[^-\p{White_Space}\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Join_Control}]/gu,upperOrWordBoundariedLowerRE=new RegExp(`${upperCaseLetter}|(?:${wordBoundary})${lowerCaseLetter}`,"gu");function sluggify(text,{camel=null}={}){if(typeof text!="string")return console.warn("Non-string argument passed to `sluggify`"),"";if(text==="-")return text;switch(camel){case null:return text.replace(lowerCaseThenUpperCaseRE,"$1-$2").toLowerCase().replace(/['’]/g,"").replace(nonWordCharacterRE," ").trim().replace(/[-\s]+/g,"-");case"bactrian":{const dromedary=sluggify(text,{camel:"dromedary"});return dromedary.charAt(0).toUpperCase()+dromedary.slice(1)}case"dromedary":return text.replace(nonWordCharacterHyphenOrSpaceRE,"").replace(/[-_]+/g," ").replace(upperOrWordBoundariedLowerRE,(part,index)=>index===0?part.toLowerCase():part.toUpperCase()).replace(/\s+/g,"");default:throw ErrorPF2e("I don't think that's a real camel.")}}__name(sluggify,"sluggify"),__name2(sluggify,"sluggify");function parseHTML(unparsed){const fragment=document.createElement("template");fragment.innerHTML=unparsed;const element=fragment.content.firstElementChild;if(!(element instanceof HTMLElement))throw ErrorPF2e("Unexpected error parsing HTML");return element}__name(parseHTML,"parseHTML"),__name2(parseHTML,"parseHTML");function getActionTypeLabel(type,cost){switch(type){case"action":return cost===1?"PF2E.Item.Action.Type.Single":"PF2E.Item.Action.Type.Activity";case"free":return"PF2E.Item.Action.Type.Free";case"reaction":return"PF2E.Item.Action.Type.Reaction";default:return null}}__name(getActionTypeLabel,"getActionTypeLabel"),__name2(getActionTypeLabel,"getActionTypeLabel");const actionImgMap={0:"systems/pf2e/icons/actions/FreeAction.webp",free:"systems/pf2e/icons/actions/FreeAction.webp",1:"systems/pf2e/icons/actions/OneAction.webp",2:"systems/pf2e/icons/actions/TwoActions.webp",3:"systems/pf2e/icons/actions/ThreeActions.webp","1 or 2":"systems/pf2e/icons/actions/OneTwoActions.webp","1 to 3":"systems/pf2e/icons/actions/OneThreeActions.webp","2 or 3":"systems/pf2e/icons/actions/TwoThreeActions.webp",reaction:"systems/pf2e/icons/actions/Reaction.webp",passive:"systems/pf2e/icons/actions/Passive.webp"};function getActionIcon(action2,fallback="systems/pf2e/icons/actions/Empty.webp"){if(action2===null)return actionImgMap.passive;const value=typeof action2!="object"?action2:action2.type==="action"?action2.value:action2.type,sanitized=String(value??"").toLowerCase().trim();return actionImgMap[sanitized]??fallback}__name(getActionIcon,"getActionIcon"),__name2(getActionIcon,"getActionIcon");const actionGlyphMap={0:"F",free:"F",1:"A",2:"D",3:"T","1 or 2":"A/D","1 to 3":"A - T","2 or 3":"D/T",reaction:"R"};function getActionGlyph(action2){if(!action2&&action2!==0)return"";const value=typeof action2!="object"?action2:action2.type==="action"?action2.value:action2.type,sanitized=String(value??"").toLowerCase().trim();return actionGlyphMap[sanitized]??""}__name(getActionGlyph,"getActionGlyph"),__name2(getActionGlyph,"getActionGlyph");function ErrorPF2e(message){return Error(`PF2e System | ${message}`)}__name(ErrorPF2e,"ErrorPF2e"),__name2(ErrorPF2e,"ErrorPF2e");function ordinal(value){const pluralRules=new Intl.PluralRules(game.i18n.lang,{type:"ordinal"}),suffix=game.i18n.localize(`PF2E.OrdinalSuffixes.${pluralRules.select(value)}`);return game.i18n.format("PF2E.OrdinalNumber",{value,suffix})}__name(ordinal,"ordinal"),__name2(ordinal,"ordinal");function localizeList(items,{conjunction="or"}={}){items=[...items].sort((a,b)=>a.localeCompare(b,game.i18n.lang));const parts=conjunction==="or"?"PF2E.ListPartsOr":"PF2E.ListPartsAnd";if(items.length===0)return"";if(items.length===1)return items[0];if(items.length===2)return game.i18n.format(`${parts}.two`,{first:items[0],second:items[1]});let result=game.i18n.format(`${parts}.start`,{first:items[0],second:"{second}"});for(let i=1;i<=items.length-2;i++)if(i===items.length-2){const end=game.i18n.format(`${parts}.end`,{first:items[i],second:items[items.length-1]});result=result.replace("{second}",end)}else{const newSegment=game.i18n.format(`${parts}.middle`,{first:items[i],second:"{second}"});result=result.replace("{second}",newSegment)}return result}__name(localizeList,"localizeList"),__name2(localizeList,"localizeList");function fontAwesomeIcon(glyph,{style="solid",fixedWidth=!1}={}){const styleClass=`fa-${style}`,glyphClass=glyph.startsWith("fa-")?glyph:`fa-${glyph}`,icon=document.createElement("i");return icon.classList.add(styleClass,glyphClass),fixedWidth&&icon.classList.add("fa-fw"),icon}__name(fontAwesomeIcon,"fontAwesomeIcon"),__name2(fontAwesomeIcon,"fontAwesomeIcon");function isObject(value){return typeof value=="object"&&value!==null}__name(isObject,"isObject"),__name2(isObject,"isObject");function sortLabeledRecord(record){return Object.entries(record).sort((a,b)=>a[1].label.localeCompare(b[1].label,game.i18n.lang)).reduce((copy,[key,value])=>mergeObject(copy,{[key]:value}),{})}__name(sortLabeledRecord,"sortLabeledRecord"),__name2(sortLabeledRecord,"sortLabeledRecord");function sortStringRecord(record){return Object.fromEntries(Object.entries(record).map(entry=>(entry[1]=game.i18n.localize(entry[1]),entry)).sort((a,b)=>a[1].localeCompare(b[1],game.i18n.lang)))}__name(sortStringRecord,"sortStringRecord"),__name2(sortStringRecord,"sortStringRecord");function recursiveReplaceString(source,replace){const clone=Array.isArray(source)||isObject(source)?deepClone(source):source;if(typeof clone=="string")return replace(clone);if(Array.isArray(clone))return clone.map(e=>recursiveReplaceString(e,replace));if(isObject(clone))for(const key of Object.keys(clone))clone[key]=recursiveReplaceString(clone[key],replace);return clone}__name(recursiveReplaceString,"recursiveReplaceString"),__name2(recursiveReplaceString,"recursiveReplaceString");function localizer(prefix){return(...[suffix,formatArgs])=>formatArgs?game.i18n.format(`${prefix}.${suffix}`,formatArgs):game.i18n.localize(`${prefix}.${suffix}`)}__name(localizer,"localizer"),__name2(localizer,"localizer");function configFromLocalization(localization,prefix){return Object.entries(localization).reduce((result,[key,value])=>(result[key]=typeof value=="string"?`${prefix}.${key}`:configFromLocalization(value,`${prefix}.${key}`),result),{})}__name(configFromLocalization,"configFromLocalization"),__name2(configFromLocalization,"configFromLocalization");function isImageFilePath(path){return typeof path=="string"&&Object.keys(CONST.IMAGE_FILE_EXTENSIONS).some(e=>path.endsWith(`.${e}`))}__name(isImageFilePath,"isImageFilePath"),__name2(isImageFilePath,"isImageFilePath");function isVideoFilePath(path){return typeof path=="string"&&Object.keys(CONST.VIDEO_FILE_EXTENSIONS).some(e=>path.endsWith(`.${e}`))}__name(isVideoFilePath,"isVideoFilePath"),__name2(isVideoFilePath,"isVideoFilePath");function isImageOrVideoPath(path){return isImageFilePath(path)||isVideoFilePath(path)}__name(isImageOrVideoPath,"isImageOrVideoPath"),__name2(isImageOrVideoPath,"isImageOrVideoPath");const SORTABLE_DEFAULTS={animation:200,direction:"vertical",dragClass:"drag-preview",dragoverBubble:!0,easing:"cubic-bezier(1, 0, 0, 1)",ghostClass:"drag-gap",scroll:!0,scrollSensitivity:30,scrollSpeed:15};function traitSlugToObject(trait,dictionary){const traitObject={name:trait,label:game.i18n.localize(dictionary[trait]??trait)};return objectHasKey(CONFIG.PF2E.traitsDescriptions,trait)&&(traitObject.description=CONFIG.PF2E.traitsDescriptions[trait]),traitObject}__name(traitSlugToObject,"traitSlugToObject"),__name2(traitSlugToObject,"traitSlugToObject");function transformWhitelist(whitelist){return Array.isArray(whitelist)?whitelist:Object.entries(whitelist).map(([key,locPath])=>({id:key,value:game.i18n.localize(typeof locPath=="string"?locPath:locPath.label)})).sort((a,b)=>a.value.localeCompare(b.value,game.i18n.lang))}__name(transformWhitelist,"transformWhitelist"),__name2(transformWhitelist,"transformWhitelist");function tagify$1(input,{whitelist,maxTags,enforceWhitelist=!0}={}){if(input?.hasAttribute("name")&&input.dataset.dtype!=="JSON")throw ErrorPF2e("Usable only on input elements with JSON data-dtype");if(!input)return null;const whitelistTransformed=whitelist?transformWhitelist(whitelist):[],maxItems=whitelist?Object.keys(whitelistTransformed).length:void 0,tagify2=new Tagify(input,{enforceWhitelist:!!whitelist&&enforceWhitelist,keepInvalidTags:!1,skipInvalid:!!whitelist,maxTags:maxTags??maxItems,dropdown:{enabled:0,maxItems,searchKeys:["id","value"]},whitelist:whitelistTransformed});return input.name&&(tagify2.DOM.scope.dataset.name=input.name),tagify2.DOM.input.blur(),tagify2}__name(tagify$1,"tagify$1"),__name2(tagify$1,"tagify$1");const _DelegatedCollection=class{static{__name(this,"_DelegatedCollection")}constructor(entries=[]){__privateAdd(this,_data,void 0),__privateSet(this,_data,new Collection(entries))}[Symbol.iterator](){return __privateGet(this,_data).values()}get size(){return __privateGet(this,_data).size}get contents(){return __privateGet(this,_data).contents}get(key,options){return __privateGet(this,_data).get(key,options)}set(key,value){return __privateGet(this,_data).set(key,value),this}has(key){return __privateGet(this,_data).has(key)}find(predicate){return __privateGet(this,_data).find(predicate)}some(predicate){return __privateGet(this,_data).some(predicate)}filter(predicate){return __privateGet(this,_data).filter(predicate)}map(callback){return __privateGet(this,_data).map(callback)}delete(key){return __privateGet(this,_data).delete(key)}clear(){__privateGet(this,_data).clear()}};_data=new WeakMap,__name2(_DelegatedCollection,"DelegatedCollection");let DelegatedCollection=_DelegatedCollection;const _Migration601SplitEffectCompendia=class _Migration601SplitEffectCompendia2 extends MigrationBase{static{__name(this,"_Migration601SplitEffectCompendia")}async updateItem(item){typeof item.system.description.value=="string"&&(item.system.description.value=item.system.description.value.replace(/(@Compendium\[pf2e\.)(spell-effects)(\.)([a-zA-Z0-9]{16})(\]{.*?})/g,(_full,first,_replace2,dot,itemId,rest)=>{const packName=objectHasKey(_Migration601SplitEffectCompendia2.effectLocations,itemId)?_Migration601SplitEffectCompendia2.effectLocations[itemId]:"??";return first+packName+dot+itemId+rest})),typeof item.flags.core?.sourceId=="string"&&(item.flags.core.sourceId=item.flags.core.sourceId.replace(/(Compendium\.pf2e\.)(spell-effects)(\.)([a-zA-Z0-9]{16})/g,(_full,first,_replace2,dot,itemId)=>{const packName=objectHasKey(_Migration601SplitEffectCompendia2.effectLocations,itemId)?_Migration601SplitEffectCompendia2.effectLocations[itemId]:"??";return first+packName+dot+itemId}))}async migrate(){for(const macro of game.macros)macro._source.command=macro._source.command.replace(/(Compendium\.pf2e\.)(spell-effects)(\.)([a-zA-Z0-9]{16})/g,(_full,first,_replace2,dot,itemId)=>{const packName=objectHasKey(_Migration601SplitEffectCompendia2.effectLocations,itemId)?_Migration601SplitEffectCompendia2.effectLocations[itemId]:"??";return first+packName+dot+itemId})}};__name2(_Migration601SplitEffectCompendia,"Migration601SplitEffectCompendia"),__publicField(_Migration601SplitEffectCompendia,"version",.601),__publicField(_Migration601SplitEffectCompendia,"effectLocations",{QuZ5frBMJF3gi7RY:"consumable-effects","7z1iY4AaNEAIKuAU":"consumable-effects","1mKjaWC65KWPuFR4":"consumable-effects",mi4Md1fB2XThCand:"consumable-effects",R106i7WCXvHLGMTu:"consumable-effects",kkDbalYEavzRpYlp:"consumable-effects",qVKrrKpTghgMIuGH:"consumable-effects",HeRHBo2NaKy5IxhU:"consumable-effects",tTBJ33UGtzXjWOJp:"consumable-effects",xVAdPzFaSvJXPMKv:"consumable-effects",fYjvLx9DHIdCHdDx:"consumable-effects",kwD0wuW5Ndkc9YXB:"consumable-effects",fIpzDpuwLdIS4tW5:"consumable-effects","1ouUo8lLK6H79Rqh":"consumable-effects",xFQRiVU6h8EA6Lw9:"consumable-effects",MI5OCkF9IXmD2lPF:"consumable-effects",S4MZzALqFoXJsr6o:"consumable-effects",wFF0SZs1Hcf87Kk1:"consumable-effects","2C1HuKDQDGFZuv7l":"consumable-effects",q1EhQ716bPSgJVnC:"consumable-effects",eh7EqmDBDW30ShCu:"consumable-effects",wTZnKkT0K4Tdy8mD:"consumable-effects",Cxa7MdgMCUoMqbKm:"consumable-effects",PeuUz7JaabCgl6Yh:"consumable-effects",lNWACCNe9RYgaFxb:"consumable-effects",j9zVZwRBVAcnpEkE:"consumable-effects",qit1mLbJUyRTYcPU:"consumable-effects",jaBMZKdoywOTrQvP:"consumable-effects",RT1BxXrbbGgk40Ti:"consumable-effects",ztxW3lBPRcesF7wK:"consumable-effects","7vCenP9j6FuHRv5C":"consumable-effects","7UL8belWmo7U5YGM":"consumable-effects",bcxVvIbuZWOvsKcA:"consumable-effects","4tepFOJLhZSelPoa":"consumable-effects",qwoLV4awdezlEJ60:"consumable-effects",GBBjw61g4ekJymT0:"consumable-effects",vFOr2JAJxiVvvn2E:"consumable-effects",BV8RPntjc9FUzD3g:"consumable-effects",kgotU0sFmtAHYySB:"consumable-effects",VCypzSu659eC6jNi:"consumable-effects",wyLEew86nhNUXASu:"consumable-effects",Wa4317cqU4lJ8vAQ:"consumable-effects",Z9oPh462q82IYIZ6:"consumable-effects",EpB7yJPEuG6ez4z3:"consumable-effects",PpLxndUSgzgs6dd0:"consumable-effects",lPRuIRbu0rHBkoKY:"consumable-effects",Yxssrnh9UZJAM0V7:"consumable-effects","9MeHc072G4L8AJkp":"consumable-effects",xLilBqqf34ZJYO9i:"consumable-effects","1l139A2Qik4lBHKO":"consumable-effects","2PNo8u4wxSbz5WEs":"consumable-effects",fUrZ4xcMJz0CfTyG:"consumable-effects","6A8jsLR7upLGuRiv":"consumable-effects",Zdh2uO1vVYJmaqld:"consumable-effects",Mf9EBLhYmZerf0nS:"consumable-effects",ModBoFdCi7YQU4gP:"consumable-effects",W3xQBLj5hLOtb6Tj:"consumable-effects","2Bds6d4UGQZqYSZM":"consumable-effects","6PNLBIdlqqWNCFMy":"consumable-effects","988f6NpOo4YzFzIr":"consumable-effects",VPtsrpbP0AE642al:"consumable-effects",MCny5ohCGf09a7Wl:"consumable-effects",RRusoN3HEGnDO1Dg:"consumable-effects",thOpQunbQr77XWdF:"consumable-effects","9keegq0GdS1eSrNr":"consumable-effects",jw6Tr9FbErjLAFLQ:"consumable-effects","5xgapIXn5DwbXHKh":"consumable-effects",t7VUJHSUT6bkVUjg:"consumable-effects",yrbz0rZzp8aZEqbv:"consumable-effects","16tOZk4qy329s2aK":"consumable-effects",zd85Ny1RS46OL0TD:"consumable-effects",oAewXfq9c0ecaSfw:"consumable-effects",dpIrjd1UPY7EnWUD:"consumable-effects","9FfFhu2kl2wMTsiI":"consumable-effects",v5Ht1V4MZvRKRBjL:"consumable-effects",TkRuKKYyPHTGPfgf:"consumable-effects",XrlChFETfe8avLsX:"consumable-effects",qzRcSQ0HTTp58hV2:"consumable-effects",TsWUTODTVi487SEz:"consumable-effects","5Gof60StUppR2Xn9":"consumable-effects",mG6S6zm6hxaF7Tla:"consumable-effects",zlSNbMDIlTOpcO8R:"consumable-effects",b9DTIJyBT8kvIBpj:"consumable-effects",PEPOd38VfVzQMKG5:"consumable-effects","1xHHvQlW4pRR89qj":"consumable-effects",AMhUb42NAJ1aisZp:"consumable-effects",kwOtHtmlH69ctK0O:"consumable-effects",VrYfR2WuyA15zFhq:"consumable-effects",OAN5Fj21PJPhIqRU:"consumable-effects",e6dXfbKzv5sNr1zh:"consumable-effects",Hnt3Trd7TiFICB06:"consumable-effects",p2aGtovaY1feytws:"equipment-effects",yvabfuAO74pvH8hh:"equipment-effects",etJW0w4CiSFgMrWP:"equipment-effects",vOU4Yv2MyAfYBbmF:"equipment-effects",FbFl95WRpzrrijh3:"equipment-effects",iK6JeCsZwm5Vakks:"equipment-effects",P7Y7pO2ulZ5wBgxU:"equipment-effects",cg5qyeMJUh6b4fta:"equipment-effects",fbSFwwp60AuDDKpK:"equipment-effects","88kqcDmsoAEddzUt":"equipment-effects",lLP56tbG689TNKW5:"equipment-effects",PeiuJ951kkBPTCSM:"equipment-effects",G0lG7IIZnCZtYi6v:"equipment-effects",gDefAEEMXVVZgqXH:"equipment-effects",uXEp1rPU5fY4OiBf:"equipment-effects",Uadsb25G18pKdZ2e:"equipment-effects",viCX9fZzTWGuoO85:"equipment-effects",eeGWTG9ZAha4IIOY:"equipment-effects",ioGzmVSmMGXWWBYb:"equipment-effects",pAMyEbJzWBoYoGhs:"equipment-effects","7dLsA9PAb5ij7Bc6":"equipment-effects",NE7Fm5YnUhD4ySX3:"equipment-effects","8ersuvNJXX00XaIQ":"equipment-effects",EpNflrkmWzQ0lEb4:"equipment-effects",iEkH8BKLMUa2wxLX:"equipment-effects",bP40jr6wE6MCsRvY:"equipment-effects",eSIYyxi6uTKiP6W5:"equipment-effects",E4B02mJmNexQLa8F:"equipment-effects","3O5lvuX4VHqtpCkU":"equipment-effects",ah41XCrV4LFsVyzl:"equipment-effects",W3BCLbX6j1IqL0uB:"equipment-effects",zqKzWGLODgIvtiKf:"equipment-effects",lBMhT2W2raYMa8JS:"equipment-effects","5uK3fmGlfJrbWQz4":"equipment-effects",i0tm2ZHekp7rGGR3:"equipment-effects",Zb8RYgmzCI6fQE0o:"equipment-effects",QapoFh0tbUgMwSIB:"equipment-effects",UlalLihKzDxcOdXL:"equipment-effects",lO95TwgihBdTilAB:"equipment-effects","9PASRixhNM0ogqmG":"equipment-effects","7MgpgF8tOXOiDEwv":"equipment-effects","1S51uIRb9bnZtpFU":"equipment-effects","1nCwQErK6hpkNvfw":"feat-effects","5IGz4iheaiUWm5KR":"feat-effects",uFYvW3kFP9iyNfVX:"feat-effects",CgxYa0lrLUjS2ZhI:"feat-effects",nwkYZs6YwXYAJ4ps:"feat-effects",qUowHpn79Dpt1hVn:"feat-effects",RozqjLocahvQWERr:"feat-effects",tPKXLtDJ3bzJcXlv:"feat-effects",gYpy9XBPScIlY93p:"feat-effects",Im5JBInybWFbHEYS:"feat-effects",BCyGDKcplkJiSAKJ:"feat-effects",PMHwCrnh9W4sMu5b:"feat-effects",pf9yvKNg6jZLrE30:"feat-effects",eeAlh6edygcZIz9c:"feat-effects",b2kWJuCPj1rDMdwz:"feat-effects",UQ7vZgmfK0VSFS8A:"feature-effects",s1tulrmW6teTFjVd:"feature-effects",aKRo5TIhUtu0kyEr:"feature-effects",yfbP64r4a9e5oyli:"feature-effects",n1vhmOd7aNiuR3nk:"feature-effects",FNTTeJHiK6iOjrSq:"feature-effects","3gGBZHcUFsHLJeQH":"feature-effects",rJpkKaPRGaH0pLse:"feature-effects","9AUcoY48H5LrVZiF":"feature-effects",KVbS7AbhQdeuA0J6:"feature-effects","6fb15XuSV4TNuVAT":"feature-effects",vguxP8ukwVTWWWaA:"feature-effects",SVGW8CLKwixFlnTv:"feature-effects",ruRAfGJnik7lRavk:"feature-effects",uBJsxCzNhje8m8jj:"feature-effects","7BFd8A9HFrmg6vwL":"feature-effects",z3uyCMBddrPK5umr:"feature-effects",Nv70aqcQgCBpDYp8:"feature-effects",OqH6IaeOwRWkGPrk:"feature-effects",Lb4q2bBAgxamtix5:"feature-effects",Gqy7K6FnbLtwGpud:"spell-effects","41WThj17MZBXTO2X":"spell-effects",sPCWrhUHqlbGhYSD:"spell-effects","3qHKBDF7lrHw8jFK":"spell-effects",l9HRQggofFGIxEse:"spell-effects",beReeFroAx24hj83:"spell-effects",qkwb5DD3zmKwvbk0:"spell-effects",GnWkI3T3LYRlm3X8:"spell-effects",dWbg2gACxMkSnZag:"spell-effects",Jemq5UknGdMO7b73:"spell-effects",LXf1Cqi1zyo4DaLv:"spell-effects"});let Migration601SplitEffectCompendia=_Migration601SplitEffectCompendia;const _Migration602UpdateDiehardFeat=class extends MigrationBase{static{__name(this,"_Migration602UpdateDiehardFeat")}constructor(){super(),__publicField(this,"requiresFlush",!0),__privateAdd(this,_diehardPromise,void 0),__privateSet(this,_diehardPromise,fromUuid("Compendium.pf2e.feats-srd.I0BhPWqYf1bbzEYg"))}async updateActor(source){const diehard=source.items.find(itemData=>itemData.system.slug==="diehard"&&itemData.type==="feat");if(source.type==="character"&&diehard!==void 0&&"dying"in source.system.attributes&&isObject(source.system.attributes.dying)){source.system.attributes.dying.max=4;const diehardIndex=source.items.indexOf(diehard),newDiehard=await __privateGet(this,_diehardPromise);if(!(newDiehard instanceof FeatPF2e))throw Error("PF2E System | Expected item not found in Compendium");source.items.splice(diehardIndex,1,newDiehard.toObject())}}};_diehardPromise=new WeakMap,__name2(_Migration602UpdateDiehardFeat,"Migration602UpdateDiehardFeat"),__publicField(_Migration602UpdateDiehardFeat,"version",.602);let Migration602UpdateDiehardFeat=_Migration602UpdateDiehardFeat;const _Migration603ResetQuickRollDefault=class extends MigrationBase{static{__name(this,"_Migration603ResetQuickRollDefault")}async updateUser(userData){const flags=userData.flags;isObject(flags.PF2e)&&isObject(flags.PF2e.settings)&&typeof flags.PF2e.settings.quickD20roll=="boolean"&&(flags.PF2e.settings.quickD20roll=!1)}};__name2(_Migration603ResetQuickRollDefault,"Migration603ResetQuickRollDefault"),__publicField(_Migration603ResetQuickRollDefault,"version",.603);let Migration603ResetQuickRollDefault=_Migration603ResetQuickRollDefault;const _Migration604FixClassItem=class extends MigrationBase{static{__name(this,"_Migration604FixClassItem")}async updateItem(item){item.type==="class"&&(Array.isArray(item.system.ancestryFeatLevels)&&(item.system.ancestryFeatLevels={value:item.system.ancestryFeatLevels}),Array.isArray(item.system.classFeatLevels)&&(item.system.classFeatLevels={value:item.system.classFeatLevels}),Array.isArray(item.system.skillFeatLevels)&&(item.system.skillFeatLevels={value:item.system.skillFeatLevels}),Array.isArray(item.system.generalFeatLevels)&&(item.system.generalFeatLevels={value:item.system.generalFeatLevels}),Array.isArray(item.system.skillIncreaseLevels)&&(item.system.skillIncreaseLevels={value:item.system.skillIncreaseLevels}),Array.isArray(item.system.abilityBoostLevels)&&(item.system.abilityBoostLevels={value:item.system.abilityBoostLevels}))}};__name2(_Migration604FixClassItem,"Migration604FixClassItem"),__publicField(_Migration604FixClassItem,"version",.604);let Migration604FixClassItem=_Migration604FixClassItem;const PHYSICAL_ITEM_TYPES=new Set(["armor","backpack","book","consumable","equipment","treasure","weapon"]),BULK_VALUES=["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","L"],PRECIOUS_MATERIAL_TYPES=new Set(["abysium","adamantine","cold-iron","darkwood","djezet","dragonhide","grisantian-pelt","inubrix","keep-stone","mithral","noqual","orichalcum","peachwood","siccatite","silver","sisterstone","sisterstone-dusk","sisterstone-scarlet","sovereign-steel","warpglass"]),PRECIOUS_MATERIAL_GRADES=new Set(["low","standard","high"]),DENOMINATIONS=["pp","gp","sp","cp"];function isItemSystemData(data){return isObject(data)&&isObject(data.description)&&typeof data.description.value=="string"&&Array.isArray(data.rules)&&(data.slug===null||typeof data.slug=="string")}__name(isItemSystemData,"isItemSystemData"),__name2(isItemSystemData,"isItemSystemData");function isPhysicalData(source){return setHasElement(PHYSICAL_ITEM_TYPES,source.type)}__name(isPhysicalData,"isPhysicalData"),__name2(isPhysicalData,"isPhysicalData");function hasInvestedProperty(source){return isPhysicalData(source)&&"invested"in source.system.equipped}__name(hasInvestedProperty,"hasInvestedProperty"),__name2(hasInvestedProperty,"hasInvestedProperty");const _Migration605CatchUpToTemplateJSON=class extends MigrationBase{static{__name(this,"_Migration605CatchUpToTemplateJSON")}addEffects(entityData){Array.isArray(entityData.effects)||(entityData.effects=[])}async updateActor(actorData){if(this.addEffects(actorData),actorData.type==="character"||actorData.type==="npc"){if("max"in actorData.system.attributes.hp&&typeof actorData.system.attributes.hp.max=="string"){const newMax=parseInt(actorData.system.attributes.hp.max,10);Number.isInteger(newMax)&&(actorData.system.attributes.hp.max=newMax)}if(typeof actorData.system.attributes.hp.value=="string"){const newValue=parseInt(actorData.system.attributes.hp.value,10);Number.isInteger(newValue)&&(actorData.system.attributes.hp.value=newValue)}if(typeof actorData.system.details.level.value=="string"){const newLevel=parseInt(actorData.system.details.level.value,10);Number.isInteger(newLevel)&&(actorData.system.details.level.value=newLevel)}"tempmax"in actorData.system.attributes.hp&&delete actorData.system.attributes.hp.tempmax,"special"in actorData.system.attributes.speed&&delete actorData.system.attributes.speed.special}}async updateItem(itemData,actorData){this.addEffects(itemData),!itemData.system.slug&&actorData&&(itemData.system.slug=null),Array.isArray(itemData.system.rules)||(itemData.system.rules=[]);const traits=itemData.system.traits;if(traits&&!traits.custom&&(traits.custom=""),traits&&!traits.rarity&&(traits.rarity={value:"common"}),isPhysicalData(itemData)&&!itemData.system.identification){const withoutIdentifyData=itemData.system;withoutIdentifyData.identification.status="identified"}itemData.type==="spell"&&!itemData.system.hasCounteractCheck&&(itemData.system.hasCounteractCheck={value:!1}),itemData.type==="lore"&&"featType"in itemData.system&&delete itemData.system.featType,itemData.type==="action"&&"skill_requirements"in itemData.system&&delete itemData.system.skill_requirements,itemData.type==="action"&&"skill_requirement"in itemData.system&&itemData.system.skill_requirement}};__name2(_Migration605CatchUpToTemplateJSON,"Migration605CatchUpToTemplateJSON"),__publicField(_Migration605CatchUpToTemplateJSON,"version",.605);let Migration605CatchUpToTemplateJSON=_Migration605CatchUpToTemplateJSON;const _Migration606SignatureSpells=class extends MigrationBase{static{__name(this,"_Migration606SignatureSpells")}async updateItem(item){if(item.type==="spellcastingEntry"){const data=item.system;data.signatureSpells||(data.signatureSpells={value:[]})}}};__name2(_Migration606SignatureSpells,"Migration606SignatureSpells"),__publicField(_Migration606SignatureSpells,"version",.606);let Migration606SignatureSpells=_Migration606SignatureSpells;const _Migration607MeleeItemDamageRolls=class extends MigrationBase{static{__name(this,"_Migration607MeleeItemDamageRolls")}async updateItem(itemData){if(itemData.type==="melee"&&Array.isArray(itemData.system.damageRolls)){const damageRolls={};itemData.system.damageRolls.forEach(roll=>{const key=randomID(20);damageRolls[key]=roll}),itemData.system.damageRolls=damageRolls}}};__name2(_Migration607MeleeItemDamageRolls,"Migration607MeleeItemDamageRolls"),__publicField(_Migration607MeleeItemDamageRolls,"version",.607);let Migration607MeleeItemDamageRolls=_Migration607MeleeItemDamageRolls;const _Migration608DeletePersistedKits=class extends MigrationBase{static{__name(this,"_Migration608DeletePersistedKits")}async updateItem(itemData,actorData){if(actorData&&itemData.type==="kit"){const index=actorData.items.indexOf(itemData);actorData.items.splice(index,1)}}};__name2(_Migration608DeletePersistedKits,"Migration608DeletePersistedKits"),__publicField(_Migration608DeletePersistedKits,"version",.608);let Migration608DeletePersistedKits=_Migration608DeletePersistedKits;const _Migration609LootActorTraits=class extends MigrationBase{static{__name(this,"_Migration609LootActorTraits")}async updateActor(source){if(source.type==="loot"&&source.system.traits&&"traits"in source.system.traits){const systemData=source.system;systemData.traits||(systemData.traits={rarity:{value:"common"},size:{value:"med"},traits:{value:[]},di:{value:[]},dr:[],dv:[],ci:[]})}}};__name2(_Migration609LootActorTraits,"Migration609LootActorTraits"),__publicField(_Migration609LootActorTraits,"version",.609);let Migration609LootActorTraits=_Migration609LootActorTraits;const _Migration610SetHeritageFeatType=class extends MigrationBase{static{__name(this,"_Migration610SetHeritageFeatType")}async updateItem(source){const itemTraits=source.system.traits?.value;if(source.type==="feat"&&itemTraits?.includes("heritage")){const{system}=source,featType="featType"in system&&isObject(system.featType)&&"value"in system.featType&&typeof system.featType.value=="string"?system.featType:{value:""};featType.value="heritage";const index=itemTraits.indexOf("heritage");itemTraits.splice(index,1)}}};__name2(_Migration610SetHeritageFeatType,"Migration610SetHeritageFeatType"),__publicField(_Migration610SetHeritageFeatType,"version",.61);let Migration610SetHeritageFeatType=_Migration610SetHeritageFeatType;const _Migration611UpdateToughnessMountainsStoutness=class extends MigrationBase{static{__name(this,"_Migration611UpdateToughnessMountainsStoutness")}constructor(){super(),__publicField(this,"requiresFlush",!0),__privateAdd(this,_featSlugs,["mountains-stoutness","mountain-s-stoutness","toughness"]),__privateAdd(this,_featsPromise,void 0),__privateSet(this,_featsPromise,game.packs.get("pf2e.feats-srd").getDocuments())}async updateActor(actorData){if(actorData.type!=="character")return;const oldFeatsData=actorData.items.filter(itemData=>__privateGet(this,_featSlugs).includes(itemData.system.slug??"")&&itemData.type==="feat");for(const oldFeatData of oldFeatsData){oldFeatData.system.slug==="mountain-s-stoutness"&&(oldFeatData.system.slug="mountains-stoutness");const newFeat=oldFeatData.system.slug==="toughness"?(await __privateGet(this,_featsPromise)).find(feat=>feat.slug==="toughness"):(await __privateGet(this,_featsPromise)).find(feat=>feat.slug==="mountains-stoutness");if(!(newFeat instanceof FeatPF2e))throw ErrorPF2e("Expected item not found in Compendium");newFeat._source.system.location=oldFeatData.system.location;const oldFeatIndex=actorData.items.indexOf(oldFeatData);actorData.items.splice(oldFeatIndex,1,newFeat.toObject())}}};_featSlugs=new WeakMap,_featsPromise=new WeakMap,__name2(_Migration611UpdateToughnessMountainsStoutness,"Migration611UpdateToughnessMountainsStoutness"),__publicField(_Migration611UpdateToughnessMountainsStoutness,"version",.611);let Migration611UpdateToughnessMountainsStoutness=_Migration611UpdateToughnessMountainsStoutness;const _Migration612NormalizeRarities=class extends MigrationBase{static{__name(this,"_Migration612NormalizeRarities")}async updateActor(source){const traitsRaw=source.system.traits;if(source.type==="familiar"||!traitsRaw)return;const traitsAndOtherMiscellany=traitsRaw;"rarity"in traitsAndOtherMiscellany||(traitsAndOtherMiscellany.rarity={value:"common"});const rarities=["common","uncommon","rare","unique"];for(const rarity of rarities){const{traits}=traitsAndOtherMiscellany;if(traits?.value.includes(rarity)){const index=traits.value.indexOf(rarity);traits.value.splice(index,1),traitsAndOtherMiscellany.rarity={value:rarity}}}}};__name2(_Migration612NormalizeRarities,"Migration612NormalizeRarities"),__publicField(_Migration612NormalizeRarities,"version",.612);let Migration612NormalizeRarities=_Migration612NormalizeRarities;const _Migration613RemoveAmmoCharges=class extends MigrationBase{static{__name(this,"_Migration613RemoveAmmoCharges")}async updateItem(itemData){itemData.type==="consumable"&&itemData.system.consumableType.value==="ammo"&&(itemData.system.charges.value=0,itemData.system.charges.max=0)}};__name2(_Migration613RemoveAmmoCharges,"Migration613RemoveAmmoCharges"),__publicField(_Migration613RemoveAmmoCharges,"version",.613);let Migration613RemoveAmmoCharges=_Migration613RemoveAmmoCharges;const _Migration614NumifyMeleeBonuses=class extends MigrationBase{static{__name(this,"_Migration614NumifyMeleeBonuses")}async updateItem(itemData){itemData.type==="melee"&&(itemData.system.bonus={value:Number(itemData.system.bonus.value)})}};__name2(_Migration614NumifyMeleeBonuses,"Migration614NumifyMeleeBonuses"),__publicField(_Migration614NumifyMeleeBonuses,"version",.614);let Migration614NumifyMeleeBonuses=_Migration614NumifyMeleeBonuses;const _Migration615RemoveInstinctTrait=class extends MigrationBase{static{__name(this,"_Migration615RemoveInstinctTrait")}async updateItem(itemData){const traits=itemData.system.traits;traits&&(typeof traits.value=="string"?traits.value=[]:traits.value=traits.value?.filter(trait=>trait!=="instinct"))}};__name2(_Migration615RemoveInstinctTrait,"Migration615RemoveInstinctTrait"),__publicField(_Migration615RemoveInstinctTrait,"version",.615);let Migration615RemoveInstinctTrait=_Migration615RemoveInstinctTrait;const _Migration616MigrateFeatPrerequisites=class extends MigrationBase{static{__name(this,"_Migration616MigrateFeatPrerequisites")}async updateItem(source){if(source.type==="feat"){const update=[],prerequisites=source.system.prerequisites;if(prerequisites.value){if(typeof prerequisites.value=="string")update.push({value:prerequisites.value});else if(Array.isArray(prerequisites.value))for(const p of prerequisites.value)p&&update.push({value:isObject(p)&&typeof p.value=="string"?p.value:String(p)})}else if(Array.isArray(prerequisites))for(const p of prerequisites)p&&update.push({value:p?.value?p.value:p});source.system.prerequisites={value:update}}}};__name2(_Migration616MigrateFeatPrerequisites,"Migration616MigrateFeatPrerequisites"),__publicField(_Migration616MigrateFeatPrerequisites,"version",.616);let Migration616MigrateFeatPrerequisites=_Migration616MigrateFeatPrerequisites;const _Migration617FixUserFlags=class extends MigrationBase{static{__name(this,"_Migration617FixUserFlags")}async updateUser(source){const flags=source.flags,settings=flags.PF2e?.settings;if(isObject(settings)&&typeof settings.color=="string"){const uiTheme=settings.color??"blue",showRollDialogs=!settings.quickD20roll;flags.pf2e??={},flags.pf2e.settings={uiTheme,showEffectPanel:flags.pf2e?.showEffectPanel??!0,showRollDialogs},delete flags.PF2e,flags["-=PF2e"]=null}}};__name2(_Migration617FixUserFlags,"Migration617FixUserFlags"),__publicField(_Migration617FixUserFlags,"version",.617);let Migration617FixUserFlags=_Migration617FixUserFlags;const _Migration618MigrateItemImagePaths=class extends MigrationBase{static{__name(this,"_Migration618MigrateItemImagePaths")}constructor(){super(...arguments),__privateAdd(this,_IMAGE_PATHS,{"systems/pf2e/icons/equipment/weapons/blowgun.png":"systems/pf2e/icons/equipment/weapons/blowgun.jpg","systems/pf2e/icons/equipment/weapons/trident.png":"systems/pf2e/icons/equipment/weapons/trident.jpg","systems/pf2e/icons/equipment/weapons/longsword.png":"systems/pf2e/icons/equipment/weapons/longsword.jpg","systems/pf2e/icons/equipment/weapons/composite-longbow.png":"systems/pf2e/icons/equipment/weapons/composite-longbow.jpg","systems/pf2e/icons/equipment/weapons/composite-shortbow.png":"systems/pf2e/icons/equipment/weapons/composite-shortbow.jpg","systems/pf2e/icons/equipment/weapons/dagger.png":"systems/pf2e/icons/equipment/weapons/dagger.jpg","systems/pf2e/icons/equipment/weapons/katar.png":"systems/pf2e/icons/equipment/weapons/katar.jpg","systems/pf2e/icons/equipment/weapons/kukri.png":"systems/pf2e/icons/equipment/weapons/kukri.jpg","systems/pf2e/icons/equipment/weapons/shortbow.png":"systems/pf2e/icons/equipment/weapons/shortbow.jpg","systems/pf2e/icons/equipment/weapons/scimitar.png":"systems/pf2e/icons/equipment/weapons/scimitar.jpg","systems/pf2e/icons/equipment/weapons/hatchet.png":"systems/pf2e/icons/equipment/weapons/hatchet.jpg","systems/pf2e/icons/equipment/weapons/halfling-sling-staff.png":"systems/pf2e/icons/equipment/weapons/halfling-sling-staff.jpg","systems/pf2e/icons/equipment/weapons/halberd.png":"systems/pf2e/icons/equipment/weapons/halberd.jpg","systems/pf2e/icons/equipment/weapons/shield-spikes.png":"systems/pf2e/icons/equipment/weapons/shield-spikes.jpg","systems/pf2e/icons/equipment/weapons/light-mace.jpg":"systems/pf2e/icons/equipment/weapons/light-mace.jpg","systems/pf2e/icons/equipment/weapons/morningstar.png":"systems/pf2e/icons/equipment/weapons/morningstar.jpg","systems/pf2e/icons/equipment/weapons/sling.png":"systems/pf2e/icons/equipment/weapons/sling.jpg","systems/pf2e/icons/equipment/weapons/main-gauche.png":"systems/pf2e/icons/equipment/weapons/main-gauche.jpg","systems/pf2e/icons/equipment/weapons/bastard-sword.png":"systems/pf2e/icons/equipment/weapons/bastard-sword.jpg","systems/pf2e/icons/equipment/weapons/spear.png":"systems/pf2e/icons/equipment/weapons/spear.jpg","systems/pf2e/icons/equipment/weapons/staff.png":"systems/pf2e/icons/equipment/weapons/staff.jpg","systems/pf2e/icons/equipment/weapons/katana.png":"systems/pf2e/icons/equipment/weapons/katana.jpg","systems/pf2e/icons/equipment/weapons/elven-curve-blade.png":"systems/pf2e/icons/equipment/weapons/elven-curve-blade.jpg","systems/pf2e/icons/equipment/weapons/bo-staff.png":"systems/pf2e/icons/equipment/weapons/bo-staff.jpg","systems/pf2e/icons/equipment/weapons/clan-dagger.png":"systems/pf2e/icons/equipment/weapons/clan-dagger.jpg","systems/pf2e/icons/equipment/weapons/dogslicer.png":"systems/pf2e/icons/equipment/weapons/dogslicer.jpg","systems/pf2e/icons/equipment/weapons/falchion.png":"systems/pf2e/icons/equipment/weapons/falchion.jpg","systems/pf2e/icons/equipment/weapons/fist.png":"systems/pf2e/icons/equipment/weapons/fist.jpg","systems/pf2e/icons/equipment/weapons/gauntlet.png":"systems/pf2e/icons/equipment/weapons/gauntlet.jpg","systems/pf2e/icons/equipment/weapons/gnome-hooked-hammer.png":"systems/pf2e/icons/equipment/weapons/gnome-hooked-hammer.jpg","systems/pf2e/icons/equipment/weapons/greatpick.png":"systems/pf2e/icons/equipment/weapons/greatpick.jpg","systems/pf2e/icons/equipment/weapons/guisarme.png":"systems/pf2e/icons/equipment/weapons/guisarme.jpg","systems/pf2e/icons/equipment/weapons/horsechopper.png":"systems/pf2e/icons/equipment/weapons/horsechopper.jpg","systems/pf2e/icons/equipment/weapons/lance.png":"systems/pf2e/icons/equipment/weapons/lance.jpg","systems/pf2e/icons/equipment/weapons/maul.png":"systems/pf2e/icons/equipment/weapons/maul.jpg","systems/pf2e/icons/equipment/weapons/pick.png":"systems/pf2e/icons/equipment/weapons/pick.jpg","systems/pf2e/icons/equipment/weapons/ranseur.png":"systems/pf2e/icons/equipment/weapons/ranseur.jpg","systems/pf2e/icons/equipment/weapons/sai.png":"systems/pf2e/icons/equipment/weapons/sai.jpg","systems/pf2e/icons/equipment/weapons/sawtooth-saber.png":"systems/pf2e/icons/equipment/weapons/sawtooth-saber.jpg","systems/pf2e/icons/equipment/weapons/shield-bash.png":"systems/pf2e/icons/equipment/weapons/shield-bash.jpg","systems/pf2e/icons/equipment/weapons/shield-boss.png":"systems/pf2e/icons/equipment/weapons/shield-boss.jpg","systems/pf2e/icons/equipment/weapons/shuriken.png":"systems/pf2e/icons/equipment/weapons/shuriken.jpg","systems/pf2e/icons/equipment/weapons/spiked-gauntlet.png":"systems/pf2e/icons/equipment/weapons/spiked-gauntlet.jpg","systems/pf2e/icons/equipment/weapons/broom.png":"systems/pf2e/icons/equipment/held-items/broom-of-flying.jpg","systems/pf2e/icons/equipment/weapons/cutlass.png":"systems/pf2e/icons/equipment/weapons/scimitar.jpg","systems/pf2e/icons/equipment/weapons/scalpel.png":"systems/pf2e/icons/equipment/weapons/war-razor.jpg","systems/pf2e/icons/equipment/weapons/cane.png":"systems/pf2e/icons/equipment/weapons/cane.jpg"})}async updateItem(itemData){itemData.img=__privateGet(this,_IMAGE_PATHS)[itemData.img]??itemData.img}};_IMAGE_PATHS=new WeakMap,__name2(_Migration618MigrateItemImagePaths,"Migration618MigrateItemImagePaths"),__publicField(_Migration618MigrateItemImagePaths,"version",.618);let Migration618MigrateItemImagePaths=_Migration618MigrateItemImagePaths;const LEGIT_TRADITIONS=["arcane","divine","occult","primal","focus","ritual","halcyon",""];function makeLowercase(value){return value.toLowerCase()}__name(makeLowercase,"makeLowercase"),__name2(makeLowercase,"makeLowercase");const _Migration619TraditionLowercaseAndRemoveWandScroll=class extends MigrationBase{static{__name(this,"_Migration619TraditionLowercaseAndRemoveWandScroll")}async updateItem(item,actorData){if(!actorData||item.type!=="spellcastingEntry")return;const tradition=item.system.tradition;if(tradition.value=makeLowercase(tradition.value),tupleHasValue(LEGIT_TRADITIONS,item.system.tradition.value))return;const highestTradition=actorData.items.filter(itemData=>itemData.type==="spellcastingEntry").reduce((prev,current)=>{if(tupleHasValue(LEGIT_TRADITIONS,current.system.tradition.value)){const value=current.system.spelldc.value??0;if(value>prev.value)return{name:current.system.tradition.value,value}}return prev},{name:"arcane",value:0});tradition.value=highestTradition.name}};__name2(_Migration619TraditionLowercaseAndRemoveWandScroll,"Migration619TraditionLowercaseAndRemoveWandScroll"),__publicField(_Migration619TraditionLowercaseAndRemoveWandScroll,"version",.619);let Migration619TraditionLowercaseAndRemoveWandScroll=_Migration619TraditionLowercaseAndRemoveWandScroll;const _Migration620RenameToWebp=class extends MigrationBase{static{__name(this,"_Migration620RenameToWebp")}constructor(){super(...arguments),__privateAdd(this,_renameToWebP),__privateAdd(this,_isABCK),__privateAdd(this,_regexp,/(\/?systems\/pf2e\/[^"]+)\.(?:jpg|png)\b/)}async updateActor(source){source.img=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,source.img),typeof source.prototypeToken?.texture.src=="string"&&(source.prototypeToken.texture.src=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,source.prototypeToken.texture.src));for(const effect of source.effects??[])effect.icon=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,effect.icon);if(source.type==="character"){const details=source.system.details;details.deity&&(details.deity.image=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,details.deity.image))}}async updateItem(itemData){itemData.img=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,itemData.img);for(const effect of itemData.effects??[])effect.icon=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,effect.icon);if(__privateMethod(this,_isABCK,isABCK_fn).call(this,itemData)){const embedData=itemData.system.items,embeds=Object.values(embedData).filter(maybeEmbed=>!!maybeEmbed);for(const embed of embeds)if(embed.img=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,embed.img),"items"in embed&&embed.items){const deepEmbeds=Object.values(embed.items).filter(maybeDeepEmbed=>!!maybeDeepEmbed);for(const deepEmbed of deepEmbeds)deepEmbed.img=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,deepEmbed.img)}}}async updateMacro(macroData){macroData.img=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,macroData.img)}async updateTable(tableData){tableData.img=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,tableData.img);for(const result of tableData.results)result.img=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,result.img)}async updateToken(tokenData){tokenData.texture.src=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,tokenData.texture.src),tokenData.effects=tokenData.effects.filter(texture=>!__privateGet(this,_regexp).test(texture))}async updateUser(source){source.avatar=__privateMethod(this,_renameToWebP,renameToWebP_fn).call(this,source.avatar)}};_regexp=new WeakMap,_renameToWebP=new WeakSet,renameToWebP_fn=__name2(function(imgPath){return typeof imgPath=="string"&&__privateGet(this,_regexp).test(imgPath)?imgPath.replace(__privateGet(this,_regexp),"$1.webp"):imgPath?.replace("icons/svg/mystery-man.svg","systems/pf2e/icons/default-icons/mystery-man.svg")},"#renameToWebP"),_isABCK=new WeakSet,isABCK_fn=__name2(function(itemData){return["ancestry","background","class","kit"].includes(itemData.type)},"#isABCK"),__name2(_Migration620RenameToWebp,"Migration620RenameToWebp"),__publicField(_Migration620RenameToWebp,"version",.62);let Migration620RenameToWebp=_Migration620RenameToWebp;const MAGIC_SCHOOLS=new Set(["abjuration","conjuration","divination","enchantment","evocation","illusion","necromancy","transmutation"]),MAGIC_TRADITIONS=new Set(["arcane","divine","occult","primal"]),_Migration621RemoveConfigSpellSchools=class extends MigrationBase{static{__name(this,"_Migration621RemoveConfigSpellSchools")}KEY_MAP={abj:"abjuration",con:"conjuration",div:"divination",enc:"enchantment",evo:"evocation",ill:"illusion",nec:"necromancy",trs:"transmutation"};reassignSchool(abbreviation){return objectHasKey(this.KEY_MAP,abbreviation)?this.KEY_MAP[abbreviation]:setHasElement(MAGIC_SCHOOLS,abbreviation)?abbreviation:this.KEY_MAP.evo}async updateItem(itemData){if(itemData.type==="spell"){const school=itemData.system.school??{value:"evocation"};school.value=this.reassignSchool(school.value)}}};__name2(_Migration621RemoveConfigSpellSchools,"Migration621RemoveConfigSpellSchools"),__publicField(_Migration621RemoveConfigSpellSchools,"version",.621);let Migration621RemoveConfigSpellSchools=_Migration621RemoveConfigSpellSchools;const _Migration623NumifyPotencyRunes=class extends MigrationBase{static{__name(this,"_Migration623NumifyPotencyRunes")}async updateItem(itemData){if(!(itemData.type==="weapon"||itemData.type==="armor"))return;const potencyRune=itemData.system.potencyRune;potencyRune?potencyRune.value=Number(itemData.system.potencyRune.value)||null:itemData.system.potencyRune={value:null}}};__name2(_Migration623NumifyPotencyRunes,"Migration623NumifyPotencyRunes"),__publicField(_Migration623NumifyPotencyRunes,"version",.623);let Migration623NumifyPotencyRunes=_Migration623NumifyPotencyRunes;const _Migration624RemoveTokenEffectIconFlags=class extends MigrationBase{static{__name(this,"_Migration624RemoveTokenEffectIconFlags")}async updateActor(actorData){const flags=actorData.flags;flags.pf2e?.token?.effects&&(delete flags.pf2e.token.effects,"game"in globalThis&&(flags.pf2e.token["-=effects"]=null))}async updateToken(tokenData){const flags=tokenData.delta?.flags??{};flags.pf2e?.token?.effects&&(delete flags.pf2e.token.effects,"game"in globalThis&&(flags.pf2e.token["-=effects"]=null))}};__name2(_Migration624RemoveTokenEffectIconFlags,"Migration624RemoveTokenEffectIconFlags"),__publicField(_Migration624RemoveTokenEffectIconFlags,"version",.624);let Migration624RemoveTokenEffectIconFlags=_Migration624RemoveTokenEffectIconFlags;const _Migration625EnsurePresenceOfSaves=class extends MigrationBase{static{__name(this,"_Migration625EnsurePresenceOfSaves")}async updateActor(actorData){if(actorData.type!=="npc")return;const saves=actorData.system.saves;for(const key of["fortitude","reflex","will"])saves[key]??={value:0,saveDetail:""},typeof saves[key].value!="number"&&(saves[key].value=Number(saves[key].value)||0),typeof saves[key].saveDetail!="string"&&(saves[key].saveDetail="")}};__name2(_Migration625EnsurePresenceOfSaves,"Migration625EnsurePresenceOfSaves"),__publicField(_Migration625EnsurePresenceOfSaves,"version",.625);let Migration625EnsurePresenceOfSaves=_Migration625EnsurePresenceOfSaves;const _Migration626UpdateSpellCategory=class extends MigrationBase{static{__name(this,"_Migration626UpdateSpellCategory")}async updateItem(source){if(source.type!=="spell")return;const systemData=source.system,traditions=systemData.traditions,isFocus=traditions.value.includes("focus"),isRitual=traditions.value.includes("ritual");if(typeof traditions.value=="string"&&(traditions.value=[]),systemData.spellCategorie||systemData.spellCategory){const currentCategory=systemData.spellCategorie?.value??systemData.spellCategory?.value??"";source.system.category={value:isFocus?"focus":isRitual?"ritual":currentCategory===""?"spell":currentCategory},delete systemData.spellCategorie,delete systemData.spellCategory,"game"in globalThis&&(systemData["-=spellCategorie"]=null,systemData["-=spellCategory"]=null)}["focus","ritual"].includes(source.system.spellType.value)&&(source.system.spellType.value="utility"),traditions.value=traditions.value.filter(tradition=>!["focus","ritual"].includes(tradition))}};__name2(_Migration626UpdateSpellCategory,"Migration626UpdateSpellCategory"),__publicField(_Migration626UpdateSpellCategory,"version",.626);let Migration626UpdateSpellCategory=_Migration626UpdateSpellCategory;const _Migration627LowerCaseSpellSaves=class extends MigrationBase{static{__name(this,"_Migration627LowerCaseSpellSaves")}async updateItem(itemData){if(itemData.type!=="spell")return;const saveType=itemData.system.save.value?.toLowerCase()??"";tupleHasValue(["fortitude","reflex","will"],saveType)?itemData.system.save.value=saveType:itemData.system.save.value=""}};__name2(_Migration627LowerCaseSpellSaves,"Migration627LowerCaseSpellSaves"),__publicField(_Migration627LowerCaseSpellSaves,"version",.627);let Migration627LowerCaseSpellSaves=_Migration627LowerCaseSpellSaves;const _Migration629SetBaseItems=class extends MigrationBase{static{__name(this,"_Migration629SetBaseItems")}constructor(){super(...arguments),__privateAdd(this,_BASE_ARMORS,["explorers-clothing","padded-armor","leather-armor","studded-leather-armor","chain-shirt","hide-armor","scale-mail","chain-mail","breastplate","splint-mail","half-plate","full-plate","hellknight-plate"]),__privateAdd(this,_MAGIC_ARMOR_TO_BASE,{"breastplate-of-command-greater":"breastplate","breastplate-of-command":"breastplate","celestial-armor":"chain-mail","demon-armor":"full-plate",dragonplate:"full-plate","electric-eelskin":"leather-armor","forgotten-shell":"full-plate","ghoul-hide":"hide-armor","glorious-plate":"full-plate","impenetrable-scale":"scale-mail","jerkin-of-liberation":"studded-leather-armor","mail-of-luck":"splint-mail","moonlit-chain":"chain-shirt","noxious-jerkin":"padded-armor","numerian-steel-breastplate":"breastplate","plate-armor-of-the-deep":"full-plate","rhino-hide":"hide-armor","spangled-riders-suit":"studded-leather-armor","victory-plate":"full-plate"}),__privateAdd(this,_BASE_WEAPONS,["adze","aklys","alchemical-bomb","alchemical-crossbow","aldori-dueling-sword","arrows","bastard-sword","battle-axe","battle-lute","bladed-diabolo","bladed-hoop","bladed-scarf","blowgun-darts","blowgun","bo-staff","boarding-axe","boarding-pike","bola","bolts","buugeng","clan-dagger","claw","claw-blade","club","combat-grapnel","composite-longbow","composite-shortbow","crossbow","dagger","daikyu","dart","dogslicer","dwarven-war-axe","elven-curve-blade","exquisite-sword-cane-sheath","exquisite-sword-cane","falchion","fangwire","fauchard","fighting-fan","filchers-fork","fire-poi","fist","flail","gaff","gauntlet","gill-hook","glaive","gnome-flickmace","gnome-hooked-hammer","greataxe","greatclub","greatpick","greatsword","guisarme","halberd","halfling-sling-staff","hand-adze","hand-crossbow","hatchet","heavy-crossbow","horsechopper","javelin","jaws","juggling-club","kama","katana","katar","khakkhara","khopesh","kukri","lance","light-hammer","light-mace","light-pick","longbow","longspear","longsword","mace","machete","main-gauche","mambele","maul","meteor-hammer","monkeys-fist","morningstar","naginata","nightstick","nine-ring-sword","nunchaku","ogre-hook","orc-knuckle-dagger","orc-necksplitter","pick","poi","polytool","ranseur","rapier","rhoka-sword","rungu","sai","sap","sawtooth-saber","scimitar","scorpion-whip","scourge","scythe","shears","shield-bash","shield-boss","shield-spikes","shortbow","shortsword","shuriken","sickle","sling-bullets","sling","spear","spiked-chain","spiked-gauntlet","staff","starknife","stiletto-pen","sword-cane","tamchal-chakram","taw-launcher","tekko-kagi","temple-sword","tengu-gale-blade","throwing-knife","thunder-sling","tricky-pick","trident","urumi","wakizashi","war-flail","war-razor","warhammer","whip-claw","whip","wish-blade","wish-knife","wooden-taws"])}async updateItem(itemData){if(!isPhysicalData(itemData))return;const systemData=itemData.system;!systemData.slug||itemData.type!=="armor"&&itemData.type!=="weapon"||(itemData.type==="armor"?((systemData.slug==="hide"||sluggify(itemData.name)==="hide")&&(systemData.slug="hide-armor"),__privateGet(this,_BASE_ARMORS).includes(systemData.slug??"")?systemData.baseItem=systemData.slug:systemData.slug in __privateGet(this,_MAGIC_ARMOR_TO_BASE)&&(systemData.baseItem=__privateGet(this,_MAGIC_ARMOR_TO_BASE)[systemData.slug])):itemData.type==="weapon"&&(__privateGet(this,_BASE_WEAPONS).includes(systemData.slug)&&(systemData.baseItem=systemData.slug),systemData.slug==="cinderclaw-gauntlet"&&(systemData.baseItem="spiked-gauntlet")))}};_BASE_ARMORS=new WeakMap,_MAGIC_ARMOR_TO_BASE=new WeakMap,_BASE_WEAPONS=new WeakMap,__name2(_Migration629SetBaseItems,"Migration629SetBaseItems"),__publicField(_Migration629SetBaseItems,"version",.629);let Migration629SetBaseItems=_Migration629SetBaseItems;const _Migration630FixTalismanSpelling=class extends MigrationBase{static{__name(this,"_Migration630FixTalismanSpelling")}async updateItem(itemData){if(itemData.type==="consumable"){const consumableType=itemData.system.consumableType;consumableType.value==="talasman"&&(consumableType.value="talisman")}}};__name2(_Migration630FixTalismanSpelling,"Migration630FixTalismanSpelling"),__publicField(_Migration630FixTalismanSpelling,"version",.63);let Migration630FixTalismanSpelling=_Migration630FixTalismanSpelling;const _Migration631FixSenseRuleElementSelector=class extends MigrationBase{static{__name(this,"_Migration631FixSenseRuleElementSelector")}SENSE_SELECTOR_CONVERSION={lowlightvision:"lowLightVision",Tremorsense:"tremorsense"};async updateItem(source){const rules=source.system.rules;for(const rule of rules)rule.key==="PF2E.RuleElement.Sense"&&typeof rule.selector=="string"&&(rule.selector=this.SENSE_SELECTOR_CONVERSION[rule.selector]??rule.selector)}};__name2(_Migration631FixSenseRuleElementSelector,"Migration631FixSenseRuleElementSelector"),__publicField(_Migration631FixSenseRuleElementSelector,"version",.631);let Migration631FixSenseRuleElementSelector=_Migration631FixSenseRuleElementSelector;const _Migration632DeleteOrphanedSpells=class extends MigrationBase{static{__name(this,"_Migration632DeleteOrphanedSpells")}requiresFlush=!0;async updateActor(actorData){const spells=actorData.items.filter(itemData=>itemData.type==="spell"),entries=actorData.items.filter(itemData=>itemData.type==="spellcastingEntry"),orphans=spells.filter(spellData=>!entries.some(entryData=>entryData._id===spellData.system.location.value));actorData.items=actorData.items.filter(itemData=>!orphans.some(orphan=>orphan._id===itemData._id))}};__name2(_Migration632DeleteOrphanedSpells,"Migration632DeleteOrphanedSpells"),__publicField(_Migration632DeleteOrphanedSpells,"version",.632);let Migration632DeleteOrphanedSpells=_Migration632DeleteOrphanedSpells;const _Migration633DeleteUnidentifiedTraits=class extends MigrationBase{static{__name(this,"_Migration633DeleteUnidentifiedTraits")}async updateItem(itemData){if(itemData.type==="melee"){const systemData=itemData.system;systemData.identification&&("game"in globalThis?itemData["system.-=identification"]=null:delete systemData.identification)}if(!isPhysicalData(itemData))return;const unidentifiedDataData=itemData.system.identification?.unidentified?.data;unidentifiedDataData?.traits&&("game"in globalThis?itemData["system.identification.unidentified.data.-=traits"]=null:delete unidentifiedDataData.traits)}};__name2(_Migration633DeleteUnidentifiedTraits,"Migration633DeleteUnidentifiedTraits"),__publicField(_Migration633DeleteUnidentifiedTraits,"version",.633);let Migration633DeleteUnidentifiedTraits=_Migration633DeleteUnidentifiedTraits;const _Migration634PurgeMartialItems=class extends MigrationBase{static{__name(this,"_Migration634PurgeMartialItems")}async updateActor(actorData){const martialIds=actorData.items.filter(itemData=>itemData.type==="martial").map(itemData=>itemData._id),martialItemWeapons=actorData.items.filter(itemData=>{if(itemData.type!=="weapon")return!1;const systemData=itemData.system;return martialIds.includes(systemData.weaponType?.value??"")});for(const weaponData of martialItemWeapons)weaponData.data.category="simple";actorData.items=actorData.items.filter(itemData=>itemData.type!=="martial")}};__name2(_Migration634PurgeMartialItems,"Migration634PurgeMartialItems"),__publicField(_Migration634PurgeMartialItems,"version",.634);let Migration634PurgeMartialItems=_Migration634PurgeMartialItems;const _Migration635NumifyACAndQuantity=class extends MigrationBase{static{__name(this,"_Migration635NumifyACAndQuantity")}async updateActor(actorData){(actorData.type==="hazard"||actorData.type==="npc"||actorData.type==="vehicle")&&(actorData.system.attributes.ac.value=Number(actorData.system.attributes.ac.value))}async updateItem(itemData){if(isPhysicalData(itemData)){const quantity=itemData.system.quantity||{value:0};quantity instanceof Object&&(quantity.value=Number(quantity.value))}}};__name2(_Migration635NumifyACAndQuantity,"Migration635NumifyACAndQuantity"),__publicField(_Migration635NumifyACAndQuantity,"version",.635);let Migration635NumifyACAndQuantity=_Migration635NumifyACAndQuantity;const _Migration636NumifyArmorData=class extends MigrationBase{static{__name(this,"_Migration636NumifyArmorData")}async updateItem(source){if(source.type!=="armor")return;const systemData=source.system;isObject(systemData.armor)&&(systemData.armor.value=Number(systemData.armor.value)||0),isObject(systemData.check)&&(systemData.check.value=Number(systemData.check.value)||0),isObject(systemData.dex)&&(systemData.dex.value=Number(systemData.dex.value)||0),isObject(systemData.strength)&&(systemData.strength.value=Number(systemData.strength.value)||0),isObject(systemData.speed)&&typeof systemData.speed.value=="string"&&(systemData.speed.value=parseInt(systemData.speed.value,10)||0)}};__name2(_Migration636NumifyArmorData,"Migration636NumifyArmorData"),__publicField(_Migration636NumifyArmorData,"version",.636);let Migration636NumifyArmorData=_Migration636NumifyArmorData;const meleeKeys=new Set(["description","source","traits","rules","slug","weaponType","attack","damageRolls","bonus","attackEffects"]),_Migration637CleanMeleeItems=class extends MigrationBase{static{__name(this,"_Migration637CleanMeleeItems")}async updateItem(itemData){if(itemData.type!=="melee")return;const systemData=itemData.system;for(const key of Object.keys(systemData))meleeKeys.has(key)||delete systemData[key]}};__name2(_Migration637CleanMeleeItems,"Migration637CleanMeleeItems");let Migration637CleanMeleeItems=_Migration637CleanMeleeItems;const validComponents=["material","somatic","verbal"],_Migration638SpellComponents=class extends MigrationBase{static{__name(this,"_Migration638SpellComponents")}async updateItem(itemData){if(itemData.type!=="spell")return;const components=itemData.system.components,oldComponents=new Set(components.value?.split(",").map(v=>v.trim().toLowerCase()));for(const component of validComponents)components[component]=components[component]||oldComponents.has(component);delete components.value,"game"in globalThis&&(components["-=value"]=null)}};__name2(_Migration638SpellComponents,"Migration638SpellComponents"),__publicField(_Migration638SpellComponents,"version",.638);let Migration638SpellComponents=_Migration638SpellComponents;const SIZES=["tiny","sm","med","lg","huge","grg"],SIZE_SLUGS=["tiny","small","medium","large","huge","gargantuan"],RARITIES=["common","uncommon","rare","unique"];function goesToEleven(value){return value>=0&&value<=11}__name(goesToEleven,"goesToEleven"),__name2(goesToEleven,"goesToEleven");const PROFICIENCY_RANKS=["untrained","trained","expert","master","legendary"],STACK_DEFINITIONS={bolts:{size:10,lightBulk:1},arrows:{size:10,lightBulk:1},slingBullets:{size:10,lightBulk:1},blowgunDarts:{size:10,lightBulk:1},woodenTaws:{size:10,lightBulk:1},rounds5:{size:5,lightBulk:1},rounds10:{size:10,lightBulk:1},rations:{size:7,lightBulk:1},sacks:{size:5,lightBulk:1},coins:{size:1e3,lightBulk:10},gems:{size:2e3,lightBulk:10}},_Bulk=class _Bulk2{static{__name(this,"_Bulk")}normal;light;constructor({normal=0,light=0}={}){this.normal=normal+Math.floor(light/10),this.light=light%10}get isNegligible(){return this.normal===0&&this.light===0}get isLight(){return this.toLightBulk()<10&&!this.isNegligible}toLightBulk(){return this.normal*10+this.light}plus(bulk){return new _Bulk2({normal:this.normal+bulk.normal,light:this.light+bulk.light})}minus(bulk){const[thisBulk,otherBulk]=this._toSingleNumber(bulk),result=thisBulk-otherBulk;return result<0?new _Bulk2:new _Bulk2({normal:Math.floor(result/10),light:result%10})}_toSingleNumber(bulk){return[this.normal*10+this.light,bulk.normal*10+bulk.light]}times(factor){const normal=this.normal*factor,lightCarryOver=normal<1&&normal>0?1:0,light=Math.floor(this.light*factor)+lightCarryOver;return new _Bulk2({normal:Math.floor(normal),light})}isSmallerThan(bulk){const[thisBulk,otherBulk]=this._toSingleNumber(bulk);return thisBulkotherBulk}isEqualTo(bulk){return this.normal===bulk.normal&&this.light===bulk.light}isPositive(){return this.normal>0||this.light>0}toString(){const{light,normal}=this;return normal===0&&light===0?game.i18n.localize("PF2E.Item.Physical.Bulk.Negligible"):normal>0&&light===0?normal.toString():light===1&&normal===0?game.i18n.localize("PF2E.Item.Physical.Bulk.Light"):light>0&&normal===0?game.i18n.format("PF2E.Item.Physical.Bulk.NLight",{light}):game.i18n.format("PF2E.Item.Physical.Bulk.WithLight",{bulk:normal,light})}double(){return this.isNegligible?new _Bulk2({light:1}):this.isLight?this.times(10):this.times(2)}halve(){return this.isNegligible?new _Bulk2:this.isLight?new _Bulk2:this.normal===1?new _Bulk2({light:1}):this.times(.5)}convertToSize(itemSize,actorSize){const sizes=Array.from(SIZES).filter(size=>size!=="sm"),itemSizeIndex=sizes.indexOf(itemSize==="sm"?"med":itemSize),actorSizeIndex=sizes.indexOf(actorSize==="sm"?"med":actorSize);return itemSizeIndex===actorSizeIndex?this:itemSizeIndex>actorSizeIndex?applyNTimes(bulk=>bulk.double(),itemSizeIndex-actorSizeIndex,this):applyNTimes(bulk=>bulk.halve(),actorSizeIndex-itemSizeIndex,this)}};__name2(_Bulk,"Bulk");let Bulk=_Bulk;const lightBulkRegex=/^(\d*)l$/i,complexBulkRegex=/^(\d+);\s*(\d*)l$/i;function weightToBulk(weight){if(typeof weight!="string"&&typeof weight!="number")return null;const trimmed=String(weight).trim();if(/^\d+$/.test(trimmed))return new Bulk({normal:parseInt(trimmed,10)});const lightMatch=trimmed.match(lightBulkRegex);if(lightMatch)return new Bulk({light:parseInt(lightMatch[1]||"1",10)});const complexMatch=trimmed.match(complexBulkRegex);if(complexMatch){const[,normal,light]=complexMatch;return new Bulk({normal:Number(normal)||0,light:Number(light||1)||0})}return null}__name(weightToBulk,"weightToBulk"),__name2(weightToBulk,"weightToBulk");const _CoinsPF2e=class _CoinsPF2e2{static{__name(this,"_CoinsPF2e")}constructor(data){data??={};for(const denomination of DENOMINATIONS)this[denomination]=Math.max(Math.floor(Math.abs(data[denomination]??0)),0)}get copperValue(){const{cp,sp,gp,pp}=this;return cp+sp*10+gp*100+pp*1e3}get goldValue(){return this.copperValue/100}add(coins){const other=new _CoinsPF2e2(coins);return new _CoinsPF2e2({pp:this.pp+other.pp,gp:this.gp+other.gp,sp:this.sp+other.sp,cp:this.cp+other.cp})}scale(factor){const result=new _CoinsPF2e2(this);if(result.pp*=factor,result.gp*=factor,result.sp*=factor,result.cp*=factor,factor%1!==0){result.gp+=result.pp%1*10,result.sp+=result.gp%1*10,result.cp+=result.sp%1*10;for(const denomination of DENOMINATIONS)result[denomination]=Math.floor(Number(result[denomination].toFixed(1)))}return result}adjustForSize(size){const basePrice=new _CoinsPF2e2(this);switch(size){case"lg":return basePrice.scale(2);case"huge":return basePrice.scale(4);case"grg":return basePrice.scale(8);default:return basePrice}}toObject(){return DENOMINATIONS.reduce((result,denomination)=>this[denomination]!==0?{...result,[denomination]:this[denomination]}:result,{})}static fromString(coinString,quantity=1){return[...String(coinString).trim().replace(/,/g,"").matchAll(/(\d+)\s*([pgsc]p)/g)].map(match=>{const[value,denomination]=match.slice(1,3),computedValue=(Number(value)||0)*quantity;return{[denomination]:computedValue}}).reduce((first,second)=>first.add(second),new _CoinsPF2e2)}static fromPrice(price,factor){const per=Math.max(1,price.per??1);return new _CoinsPF2e2(price.value).scale(factor/per)}toString(){if(DENOMINATIONS.every(denomination=>!this[denomination]))return"0 gp";const DENOMINATIONS_REVERSED=[...DENOMINATIONS].reverse(),parts=[];for(const denomation of DENOMINATIONS_REVERSED)this[denomation]&&parts.push(`${this[denomation]} ${denomation}`);return parts.join(", ")}};__name2(_CoinsPF2e,"CoinsPF2e");let CoinsPF2e=_CoinsPF2e;const coinCompendiumIds={pp:"JuNPeK5Qm1w6wpb4",gp:"B6B7tBWJSqOBz5zz",sp:"5Ew82vBF9YfaiY9f",cp:"lzJ8AVhRcbFul5fh"};function getMaterialValuationData(item){const valuationData=item.isOfType("weapon")?WEAPON_MATERIAL_VALUATION_DATA:item.isOfType("armor")&&!item.isShield?ARMOR_MATERIAL_VALUATION_DATA:null;if(!valuationData)return null;const{material}=item;return!material.type||!material.grade?null:valuationData[material.type]?.[material.grade]??null}__name(getMaterialValuationData,"getMaterialValuationData"),__name2(getMaterialValuationData,"getMaterialValuationData");const WEAPON_MATERIAL_VALUATION_DATA={"":{low:null,standard:null,high:null},abysium:{low:null,standard:{level:12,price:2e3,rarity:"rare"},high:{level:18,price:24e3,rarity:"rare"}},adamantine:{low:null,standard:{level:11,price:1400,rarity:"uncommon"},high:{level:17,price:13500,rarity:"uncommon"}},"cold-iron":{low:{level:2,price:40,rarity:"common"},standard:{level:10,price:880,rarity:"common"},high:{level:16,price:9e3,rarity:"common"}},darkwood:{low:null,standard:{level:11,price:1400,rarity:"uncommon"},high:{level:17,price:13500,rarity:"uncommon"}},djezet:{low:null,standard:{level:12,price:1800,rarity:"rare"},high:{level:18,price:22e3,rarity:"rare"}},inubrix:{low:null,standard:{level:11,price:1400,rarity:"rare"},high:{level:17,price:13500,rarity:"rare"}},"keep-stone":{low:null,standard:null,high:{level:18,price:22500,rarity:"rare"}},mithral:{low:null,standard:{level:11,price:1400,rarity:"uncommon"},high:{level:17,price:13500,rarity:"uncommon"}},noqual:{low:null,standard:{level:12,price:1600,rarity:"rare"},high:{level:18,price:24e3,rarity:"rare"}},peachwood:{low:null,standard:{level:12,price:2e3,rarity:"uncommon"},high:{level:18,price:19e3,rarity:"uncommon"}},orichalcum:{low:null,standard:null,high:{level:18,price:22500,rarity:"rare"}},siccatite:{low:null,standard:{level:11,price:1400,rarity:"rare"},high:{level:17,price:15e3,rarity:"rare"}},silver:{low:{level:2,price:40,rarity:"common"},standard:{level:10,price:880,rarity:"common"},high:{level:16,price:9e3,rarity:"common"}},"sisterstone-dusk":{low:{level:3,price:70,rarity:"rare"},standard:{level:11,price:1200,rarity:"rare"},high:{level:19,price:32e3,rarity:"rare"}},"sisterstone-scarlet":{low:{level:3,price:70,rarity:"rare"},standard:{level:11,price:1200,rarity:"rare"},high:{level:19,price:32e3,rarity:"rare"}},"sovereign-steel":{low:null,standard:{level:12,price:1600,rarity:"rare"},high:{level:19,price:32e3,rarity:"rare"}},warpglass:{low:null,standard:null,high:{level:17,price:14e3,rarity:"rare"}}},ARMOR_MATERIAL_VALUATION_DATA={"":{low:null,standard:null,high:null},abysium:{low:null,standard:{level:12,price:2e3,rarity:"rare"},high:{level:19,price:4e4,rarity:"rare"}},adamantine:{low:null,standard:{level:11,price:1600,rarity:"uncommon"},high:{level:19,price:32e3,rarity:"uncommon"}},"cold-iron":{low:{level:5,price:140,rarity:"common"},standard:{level:11,price:1200,rarity:"common"},high:{level:18,price:2e4,rarity:"common"}},darkwood:{low:null,standard:{level:12,price:1600,rarity:"uncommon"},high:{level:19,price:32e3,rarity:"uncommon"}},djezet:{low:null,standard:{level:12,price:1800,rarity:"rare"},high:{level:19,price:35e3,rarity:"rare"}},dragonhide:{low:null,standard:{level:12,price:1600,rarity:"uncommon"},high:{level:19,price:32e3,rarity:"uncommon"}},"grisantian-pelt":{low:null,standard:{level:12,price:1800,rarity:"rare"},high:{level:19,price:33e3,rarity:"rare"}},inubrix:{low:null,standard:{level:11,price:1200,rarity:"rare"},high:{level:18,price:18e3,rarity:"rare"}},"keep-stone":{low:null,standard:null,high:{level:20,price:56e3,rarity:"rare"}},mithral:{low:null,standard:{level:12,price:1600,rarity:"uncommon"},high:{level:19,price:32e3,rarity:"uncommon"}},noqual:{low:null,standard:{level:12,price:1600,rarity:"rare"},high:{level:19,price:32e3,rarity:"rare"}},peachwood:{low:null,standard:null,high:null},orichalcum:{low:null,standard:null,high:{level:20,price:55e3,rarity:"rare"}},siccatite:{low:null,standard:{level:12,price:1600,rarity:"rare"},high:{level:19,price:32e3,rarity:"rare"}},silver:{low:{level:5,price:140,rarity:"common"},standard:{level:11,price:1200,rarity:"common"},high:{level:18,price:2e4,rarity:"common"}},"sisterstone-dusk":{low:{level:5,price:140,rarity:"rare"},standard:{level:10,price:1e3,rarity:"rare"},high:{level:18,price:19500,rarity:"rare"}},"sisterstone-scarlet":{low:{level:5,price:140,rarity:"rare"},standard:{level:10,price:1e3,rarity:"rare"},high:{level:18,price:19500,rarity:"rare"}},"sovereign-steel":{low:null,standard:{level:13,price:2400,rarity:"rare"},high:{level:20,price:5e4,rarity:"rare"}},warpglass:{low:null,standard:null,high:null}},_PredicatePF2e=class _PredicatePF2e2 extends Array{static{__name(this,"_PredicatePF2e")}constructor(...statements){super(...Array.isArray(statements[0])?statements[0]:statements),__privateAdd(this,_isTrue),__privateAdd(this,_testBinaryOp),__privateAdd(this,_testCompound),__publicField(this,"isValid"),this.isValid=_PredicatePF2e2.isValid(this)}static isValid(statements){return this.isArray(statements)}static isArray(statements){return super.isArray(statements)&&statements.every(s=>StatementValidator.isStatement(s))}static test(predicate=[],options){return predicate instanceof _PredicatePF2e2?predicate.test(options):new _PredicatePF2e2(...predicate).test(options)}test(options){if(this.length===0)return!0;if(!this.isValid)return console.warn("PF2e System | The provided predicate set is malformed."),!1;const domain=options instanceof Set?options:new Set(options);return this.every(s=>__privateMethod(this,_isTrue,isTrue_fn).call(this,s,domain))}toObject(){return deepClone([...this])}clone(){return new _PredicatePF2e2(this.toObject())}};_isTrue=new WeakSet,isTrue_fn=__name2(function(statement,domain){return typeof statement=="string"&&domain.has(statement)||StatementValidator.isBinaryOp(statement)&&__privateMethod(this,_testBinaryOp,testBinaryOp_fn).call(this,statement,domain)||StatementValidator.isCompound(statement)&&__privateMethod(this,_testCompound,testCompound_fn).call(this,statement,domain)},"#isTrue"),_testBinaryOp=new WeakSet,testBinaryOp_fn=__name2(function(statement,domain){if("eq"in statement)return domain.has(`${statement.eq[0]}:${statement.eq[1]}`);{const operator=Object.keys(statement)[0],[left,right]=Object.values(statement)[0],domainArray=Array.from(domain),getValues=__name2(operand=>{const maybeNumber=Number(operand);if(!Number.isNaN(maybeNumber))return[maybeNumber];const pattern=new RegExp(String.raw`^${operand}:([^:]+)$`),values=domainArray.map(s=>Number(pattern.exec(s)?.[1]||NaN)).filter(v=>!Number.isNaN(v));return values.length>0?values:[NaN]},"getValues"),leftValues=getValues(left),rightValues=getValues(right);switch(operator){case"gt":return leftValues.some(l=>rightValues.every(r=>l>r));case"gte":return leftValues.some(l=>rightValues.every(r=>l>=r));case"lt":return leftValues.some(l=>rightValues.every(r=>lrightValues.every(r=>l<=r));default:return console.warn("PF2e System | Malformed binary operation encountered"),!1}}},"#testBinaryOp"),_testCompound=new WeakSet,testCompound_fn=__name2(function(statement,domain){return"and"in statement&&statement.and.every(subProp=>__privateMethod(this,_isTrue,isTrue_fn).call(this,subProp,domain))||"nand"in statement&&!statement.nand.every(subProp=>__privateMethod(this,_isTrue,isTrue_fn).call(this,subProp,domain))||"or"in statement&&statement.or.some(subProp=>__privateMethod(this,_isTrue,isTrue_fn).call(this,subProp,domain))||"xor"in statement&&statement.xor.filter(subProp=>__privateMethod(this,_isTrue,isTrue_fn).call(this,subProp,domain)).length===1||"nor"in statement&&!statement.nor.some(subProp=>__privateMethod(this,_isTrue,isTrue_fn).call(this,subProp,domain))||"not"in statement&&!__privateMethod(this,_isTrue,isTrue_fn).call(this,statement.not,domain)||"if"in statement&&!(__privateMethod(this,_isTrue,isTrue_fn).call(this,statement.if,domain)&&!__privateMethod(this,_isTrue,isTrue_fn).call(this,statement.then,domain))},"#testCompound"),__name2(_PredicatePF2e,"PredicatePF2e");let PredicatePF2e=_PredicatePF2e;const _StatementValidator=class{static{__name(this,"_StatementValidator")}static isStatement(statement){return statement instanceof Object?this.isCompound(statement)||this.isBinaryOp(statement):typeof statement=="string"?this.isAtomic(statement):!1}static isAtomic(statement){return typeof statement=="string"&&statement.length>0||this.isBinaryOp(statement)}static isBinaryOp(statement){if(!isObject(statement))return!1;const entries=Object.entries(statement);if(entries.length>1)return!1;const[operator,operands]=entries[0];return __privateGet(this,_binaryOperators).has(operator)&&Array.isArray(operands)&&operands.length===2&&typeof operands[0]=="string"&&["string","number"].includes(typeof operands[1])}static isCompound(statement){return isObject(statement)&&(this.isAnd(statement)||this.isOr(statement)||this.isNand(statement)||this.isXor(statement)||this.isNor(statement)||this.isNot(statement)||this.isIf(statement))}static isAnd(statement){return Object.keys(statement).length===1&&Array.isArray(statement.and)&&statement.and.every(subProp=>this.isStatement(subProp))}static isNand(statement){return Object.keys(statement).length===1&&Array.isArray(statement.nand)&&statement.nand.every(subProp=>this.isStatement(subProp))}static isOr(statement){return Object.keys(statement).length===1&&Array.isArray(statement.or)&&statement.or.every(subProp=>this.isStatement(subProp))}static isXor(statement){return Object.keys(statement).length===1&&Array.isArray(statement.xor)&&statement.xor.every(subProp=>this.isStatement(subProp))}static isNor(statement){return Object.keys(statement).length===1&&Array.isArray(statement.nor)&&statement.nor.every(subProp=>this.isStatement(subProp))}static isNot(statement){return Object.keys(statement).length===1&&!!statement.not&&this.isStatement(statement.not)}static isIf(statement){return Object.keys(statement).length===2&&this.isStatement(statement.if)&&this.isStatement(statement.then)}};_binaryOperators=new WeakMap,__name2(_StatementValidator,"StatementValidator"),__privateAdd(_StatementValidator,_binaryOperators,new Set(["eq","gt","gte","lt","lte"]));let StatementValidator=_StatementValidator;const _AutomaticBonusProgression=class{static{__name(this,"_AutomaticBonusProgression")}static isEnabled(actor){if(actor&&!actor.flags?.pf2e)return!1;const settingEnabled=game.settings.get("pf2e","automaticBonusVariant")!=="noABP",abpDisabledForActor=!!actor?.flags.pf2e.disableABP;return settingEnabled&&!abpDisabledForActor}static getStrikingDice(level){return level<4?0:level<12?1:level<19?2:3}static concatModifiers(actor){if(!this.isEnabled(actor))return;const{level,synthetics}=actor,values=this.abpValues(level),ac=values.ac,perception=values.perception,save=values.save,setting=game.settings.get("pf2e","automaticBonusVariant");if(save>0&&(synthetics.modifiers["saving-throw"]??=[]).push(()=>new ModifierPF2e({slug:"save-potency",label:"PF2E.AutomaticBonusProgression.savePotency",modifier:save,type:"potency"})),ac>0&&(synthetics.modifiers.ac??=[]).push(()=>new ModifierPF2e({slug:"defense-potency",label:"PF2E.AutomaticBonusProgression.defensePotency",modifier:ac,type:"potency"})),perception>0&&(synthetics.modifiers.perception??=[]).push(()=>new ModifierPF2e({slug:"perception-potency",label:"PF2E.AutomaticBonusProgression.perceptionPotency",modifier:perception,type:"potency"})),setting==="ABPRulesAsWritten"){const attack=this.abpValues(level).attack;attack>0&&(synthetics.modifiers["strike-attack-roll"]??=[]).push(()=>new ModifierPF2e({slug:"attack-potency",label:"PF2E.AutomaticBonusProgression.attackPotency",modifier:attack,type:"potency"}))}if(setting==="ABPFundamentalPotency"){const attack=this.abpValues(level).attack;if(attack>0){const potency={label:game.i18n.localize("PF2E.AutomaticBonusProgression.attackPotency"),type:"potency",bonus:attack,predicate:new PredicatePF2e};(synthetics.weaponPotency["strike-attack-roll"]??=[]).push(potency)}}}static cleanupRunes(item){if(!this.isEnabled(item.actor))return;item.system.potencyRune.value=null;const otherFundamental=item.isOfType("weapon")?item.system.strikingRune:item.system.resiliencyRune;if(otherFundamental.value=null,game.settings.get("pf2e","automaticBonusVariant")==="ABPRulesAsWritten"){const propertyRunes=[1,2,3,4].map(n=>item.system[`propertyRune${n}`]);for(const rune of propertyRunes)rune.value=null}}static suppressRuleElement(rule,value){return this.isEnabled(rule.actor)&&rule.type==="item"&&value>=0&&rule.fromEquipment}static getAttackPotency(level){return level<2?0:level<10?1:level<16?2:3}static abpValues(level){const attack=this.getAttackPotency(level);let ac,perception,save;return level>=5&&level<11?ac=1:level>=11&&level<18?ac=2:level>=18?ac=3:ac=0,level>=7&&level<13?perception=1:level>=13&&level<19?perception=2:level>=19?perception=3:perception=0,level>=8&&level<14?save=1:level>=14&&level<20?save=2:level>=20?save=3:save=0,{attack,ac,perception,save}}};__name2(_AutomaticBonusProgression,"AutomaticBonusProgression");let AutomaticBonusProgression=_AutomaticBonusProgression;function getPropertySlots(item){const fromMaterial=item.system.material.type==="orichalcum"?1:0,fromPotency=AutomaticBonusProgression.isEnabled(item.actor)?AutomaticBonusProgression.getAttackPotency(!item.actor||item.actor.isOfType("loot")?20:item.actor.level):item.system.runes.potency;return fromMaterial+fromPotency}__name(getPropertySlots,"getPropertySlots"),__name2(getPropertySlots,"getPropertySlots");function prunePropertyRunes(runes,validTypes){const runeSet=new Set(runes);return Array.from(runeSet).filter(r=>!!r&&r in validTypes&&!runeSet.has(`greater${r.titleCase()}`)&&!runeSet.has(`major${r.replace(/^greater/,"").titleCase()}`)&&!runeSet.has(`true${r.replace(/^greater|^major/,"").titleCase()}`))}__name(prunePropertyRunes,"prunePropertyRunes"),__name2(prunePropertyRunes,"prunePropertyRunes");function getRuneValuationData(item){if(!item.isOfType("armor","weapon")||item.isOfType("armor")&&item.isShield)return[];const itemRunes=item.system.runes,data=item.isOfType("armor")?{runes:RUNE_DATA.armor,secondaryFundamental:"resilient"}:{runes:RUNE_DATA.weapon,secondaryFundamental:"striking"};return[data.runes.potency[item.system.runes.potency],data.runes[data.secondaryFundamental][itemRunes[data.secondaryFundamental]??""],...item.system.runes.property.map(p=>data.runes.property[p])].filter(d=>!!d)}__name(getRuneValuationData,"getRuneValuationData"),__name2(getRuneValuationData,"getRuneValuationData");const strikingRuneValues=new Map([["striking",1],["greaterStriking",2],["majorStriking",3]]);function getStrikingDice(itemData){return strikingRuneValues.get(itemData.strikingRune.value)??0}__name(getStrikingDice,"getStrikingDice"),__name2(getStrikingDice,"getStrikingDice");const resilientRuneValues=new Map([[null,0],["resilient",1],["greaterResilient",2],["majorResilient",3]]);function getResilientBonus(itemData){return resilientRuneValues.get(itemData.resiliencyRune.value)??0}__name(getResilientBonus,"getResilientBonus"),__name2(getResilientBonus,"getResilientBonus");function getPropertyRuneDice(runes,options){return runes.flatMap(rune=>{const runeData=WEAPON_PROPERTY_RUNES[rune];return deepClone(runeData.damage?.dice??[]).map(data=>{const dice=new DamageDicePF2e({selector:"strike-damage",slug:rune,label:RUNE_DATA.weapon.property[rune]?.name,diceNumber:data.diceNumber??1,dieSize:data.dieSize??"d6",damageType:data.damageType,category:data.category??null,predicate:data.predicate,critical:data.critical??null});return dice.test(options),dice})})}__name(getPropertyRuneDice,"getPropertyRuneDice"),__name2(getPropertyRuneDice,"getPropertyRuneDice");function getPropertyRuneStrikeAdjustments(runes){return runes.flatMap(r=>RUNE_DATA.weapon.property[r].strikeAdjustments??[])}__name(getPropertyRuneStrikeAdjustments,"getPropertyRuneStrikeAdjustments"),__name2(getPropertyRuneStrikeAdjustments,"getPropertyRuneStrikeAdjustments");function getPropertyRuneModifierAdjustments(runes){return runes.flatMap(r=>RUNE_DATA.weapon.property[r].damage?.adjustments??[])}__name(getPropertyRuneModifierAdjustments,"getPropertyRuneModifierAdjustments"),__name2(getPropertyRuneModifierAdjustments,"getPropertyRuneModifierAdjustments");const FUNDAMENTAL_ARMOR_RUNE_DATA={potency:{0:null,1:{name:"PF2E.ArmorPotencyRune1",value:1,level:5,price:160,rarity:"common",traits:["abjuration"]},2:{name:"PF2E.ArmorPotencyRune2",value:2,level:11,price:1060,rarity:"common",traits:["abjuration"]},3:{name:"PF2E.ArmorPotencyRune3",value:3,level:18,price:20560,rarity:"common",traits:["abjuration"]},4:{name:"PF2E.ArmorPotencyRune4",value:4,level:18,price:20560,rarity:"common",traits:["abjuration"]}},resilient:{0:null,1:{name:"PF2E.ArmorResilientRune",level:8,price:340,rarity:"common",slug:"resilient",traits:["abjuration"]},2:{name:"PF2E.ArmorGreaterResilientRune",level:14,price:3440,rarity:"common",slug:"greaterResilient",traits:["abjuration"]},3:{name:"PF2E.ArmorMajorResilientRune",level:20,price:49440,rarity:"common",slug:"majorResilient",traits:["abjuration"]}}},FUNDAMENTAL_WEAPON_RUNE_DATA={potency:{0:null,1:{name:"PF2E.WeaponPotencyRune1",value:1,level:2,price:35,rarity:"common",traits:["evocation"]},2:{name:"PF2E.WeaponPotencyRune2",value:2,level:10,price:935,rarity:"common",traits:["evocation"]},3:{name:"PF2E.WeaponPotencyRune3",value:3,level:16,price:8935,rarity:"common",traits:["evocation"]},4:{name:"PF2E.WeaponPotencyRune4",value:4,level:16,price:8935,rarity:"common",traits:["evocation"]}},striking:{0:null,1:{name:"PF2E.Item.Weapon.Rune.Striking.Striking",level:4,price:65,rarity:"common",slug:"striking",traits:["evocation"]},2:{name:"PF2E.Item.Weapon.Rune.Striking.Greater",level:12,price:1065,rarity:"common",slug:"greaterStriking",traits:["evocation"]},3:{name:"PF2E.Item.Weapon.Rune.Striking.Major",level:19,price:31065,rarity:"common",slug:"majorStriking",traits:["evocation"]}}},ARMOR_PROPERTY_RUNES={acidResistant:{name:"PF2E.ArmorPropertyRuneAcidResistant",level:8,price:420,rarity:"common",slug:"acidResistant",traits:["abjuration","magical"]},advancing:{name:"PF2E.ArmorPropertyRuneAdvancing",level:9,price:625,rarity:"common",slug:"advancing",traits:["magical","necromancy"]},aimAiding:{name:"PF2E.ArmorPropertyRuneAimAiding",level:6,price:225,rarity:"common",slug:"aimAiding",traits:["magical","transmutation"]},antimagic:{name:"PF2E.ArmorPropertyRuneAntimagic",level:15,price:6500,rarity:"uncommon",slug:"antimagic",traits:["abjuration","magical"]},assisting:{name:"PF2E.ArmorPropertyRuneAssisting",level:5,price:125,rarity:"common",slug:"assisting",traits:["magical","transmutation"]},bitter:{name:"PF2E.ArmorPropertyRuneBitter",level:9,price:135,rarity:"uncommon",slug:"bitter",traits:["magical","poison","transmutation"]},coldResistant:{name:"PF2E.ArmorPropertyRuneColdResistant",level:8,price:420,rarity:"common",slug:"coldResistant",traits:["abjuration","magical"]},deathless:{name:"PF2E.ArmorPropertyRuneDeathless",level:7,price:330,rarity:"uncommon",slug:"deathless",traits:["healing","magical","necromancy"]},electricityResistant:{name:"PF2E.ArmorPropertyRuneElectricityResistant",level:8,price:420,rarity:"common",slug:"electricityResistant",traits:["abjuration","magical"]},energyAdaptive:{name:"PF2E.ArmorPropertyRuneEnergyAdaptive",level:6,price:225,rarity:"common",slug:"energyAdaptive",traits:["magical","transmutation"]},ethereal:{name:"PF2E.ArmorPropertyRuneEthereal",level:17,price:13500,rarity:"common",slug:"ethereal",traits:["conjuration","magical"]},fireResistant:{name:"PF2E.ArmorPropertyRuneFireResistant",level:8,price:420,rarity:"common",slug:"fireResistant",traits:["abjuration","magical"]},fortification:{name:"PF2E.ArmorPropertyRuneFortification",level:12,price:2e3,rarity:"common",slug:"fortification",traits:["abjuration","magical"]},glamered:{name:"PF2E.ArmorPropertyRuneGlamered",level:5,price:140,rarity:"common",slug:"glamered",traits:["illusion","magical"]},gliding:{name:"PF2E.ArmorPropertyRuneGliding",level:8,price:450,rarity:"common",slug:"gliding",traits:["magical","transmutation"]},greaterAcidResistant:{name:"PF2E.ArmorPropertyRuneGreaterAcidResistant",level:12,price:1650,rarity:"common",slug:"greaterAcidResistant",traits:["abjuration","magical"]},greaterAdvancing:{name:"PF2E.ArmorPropertyRuneGreaterAdvancing",level:16,price:8e3,rarity:"common",slug:"greaterAdvancing",traits:["magical","necromancy"]},greaterColdResistant:{name:"PF2E.ArmorPropertyRuneGreaterColdResistant",level:12,price:1650,rarity:"common",slug:"greaterColdResistant",traits:["abjuration","magical"]},greaterDread:{name:"PF2E.ArmorPropertyRuneGreaterDread",level:18,price:21e3,rarity:"uncommon",slug:"greaterDread",traits:["emotion","enchantment","fear","magical","mental","visual"]},greaterElectricityResistant:{name:"PF2E.ArmorPropertyRuneGreaterElectricityResistant",level:12,price:1650,rarity:"common",slug:"greaterElectricityResistant",traits:["abjuration","magical"]},greaterFireResistant:{name:"PF2E.ArmorPropertyRuneGreaterFireResistant",level:12,price:1650,rarity:"common",slug:"greaterFireResistant",traits:["abjuration","magical"]},greaterFortification:{name:"PF2E.ArmorPropertyRuneGreaterFortification",level:19,price:24e3,rarity:"common",slug:"greaterFortification",traits:["abjuration","magical"]},greaterInvisibility:{name:"PF2E.ArmorPropertyRuneGreaterInvisibility",level:10,price:1e3,rarity:"common",slug:"greaterInvisibility",traits:["illusion","magical"]},greaterReady:{name:"PF2E.ArmorPropertyRuneGreaterReady",level:11,price:1200,rarity:"common",slug:"greaterReady",traits:["evocation","magical"]},greaterShadow:{name:"PF2E.ArmorPropertyRuneGreaterShadow",level:9,price:650,rarity:"common",slug:"greaterShadow",traits:["magical","transmutation"]},greaterSlick:{name:"PF2E.ArmorPropertyRuneGreaterSlick",level:8,price:450,rarity:"common",slug:"greaterSlick",traits:["magical","transmutation"]},greaterStanching:{name:"PF2E.ArmorPropertyRuneGreaterStanching",level:9,price:600,rarity:"uncommon",slug:"greaterStanching",traits:["magical","necromancy"]},greaterQuenching:{name:"PF2E.ArmorPropertyRuneGreaterQuenching",level:10,price:1e3,rarity:"common",slug:"greaterQuenching",traits:["abjuration","magical"]},greaterSwallowSpike:{name:"PF2E.ArmorPropertyRuneGreaterSwallowSpike",level:12,price:1750,rarity:"common",slug:"greaterSwallowSpike",traits:["magical","transmutation"]},greaterWinged:{name:"PF2E.ArmorPropertyRuneGreaterWinged",level:19,price:35e3,rarity:"common",slug:"greaterWinged",traits:["magical","transmutation"]},immovable:{name:"PF2E.ArmorPropertyRuneImmovable",level:12,price:1800,rarity:"uncommon",slug:"immovable",traits:["magical","transmutation"]},implacable:{name:"PF2E.ArmorPropertyRuneImplacable",level:11,price:1200,rarity:"uncommon",slug:"implacable",traits:["magical","transmutation"]},invisibility:{name:"PF2E.ArmorPropertyRuneInvisibility",level:8,price:500,rarity:"common",slug:"invisibility",traits:["illusion","magical"]},lesserDread:{name:"PF2E.ArmorPropertyRuneLesserDread",level:6,price:225,rarity:"uncommon",slug:"lesserDread",traits:["emotion","enchantment","fear","magical","mental","visual"]},magnetizing:{name:"PF2E.ArmorPropertyRuneMagnetizing",level:10,price:900,rarity:"common",slug:"magnetizing",traits:["evocation","magical"]},majorQuenching:{name:"PF2E.ArmorPropertyRuneMajorQuenching",level:14,price:4500,rarity:"common",slug:"majorQuenching",traits:["abjuration","magical"]},majorShadow:{name:"PF2E.ArmorPropertyRuneMajorShadow",level:17,price:14e3,rarity:"common",slug:"majorShadow",traits:["magical","transmutation"]},majorSlick:{name:"PF2E.ArmorPropertyRuneMajorSlick",level:16,price:9e3,rarity:"common",slug:"majorSlick",traits:["magical","transmutation"]},majorStanching:{name:"PF2E.ArmorPropertyRuneMajorStanching",level:13,price:2500,rarity:"uncommon",slug:"majorStanching",traits:["magical","necromancy"]},majorSwallowSpike:{name:"PF2E.ArmorPropertyRuneMajorSwallowSpike",level:16,price:19250,rarity:"common",slug:"majorSwallowSpike",traits:["magical","transmutation"]},malleable:{name:"PF2E.ArmorPropertyRuneMalleable",level:9,price:650,rarity:"common",slug:"malleable",traits:["magical","metal"]},misleading:{name:"PF2E.ArmorPropertyRuneMisleading",level:16,price:8e3,rarity:"common",slug:"misleading",traits:["illusion","magical"]},moderateDread:{name:"PF2E.ArmorPropertyRuneModerateDread",level:12,price:1800,rarity:"uncommon",slug:"moderateDread",traits:["emotion","enchantment","fear","magical","mental","visual"]},portable:{name:"PF2E.ArmorPropertyRunePortable",level:9,price:660,rarity:"common",slug:"portable",traits:["magical","transmutation"]},quenching:{name:"PF2E.ArmorPropertyRuneQuenching",level:6,price:250,rarity:"common",slug:"quenching",traits:["abjuration","magical"]},ready:{name:"PF2E.ArmorPropertyRuneReady",level:6,price:200,rarity:"common",slug:"ready",traits:["evocation","magical"]},rockBraced:{name:"PF2E.ArmorPropertyRuneRockBraced",level:13,price:3e3,rarity:"rare",slug:"rockBraced",traits:["abjuration","dwarf","magical","saggorak"]},shadow:{name:"PF2E.ArmorPropertyRuneShadow",level:5,price:55,rarity:"common",slug:"shadow",traits:["magical","transmutation"]},sinisterKnight:{name:"PF2E.ArmorPropertyRuneSinisterKnight",level:8,price:500,rarity:"uncommon",slug:"sinisterKnight",traits:["abjuration","illusion","magical"]},slick:{name:"PF2E.ArmorPropertyRuneSlick",level:5,price:45,rarity:"common",slug:"slick",traits:["magical","transmutation"]},soaring:{name:"PF2E.ArmorPropertyRuneSoaring",level:14,price:3750,rarity:"common",slug:"soaring",traits:["abjuration","magical"]},stanching:{name:"PF2E.ArmorPropertyRuneStanching",level:5,price:130,rarity:"uncommon",slug:"stanching",traits:["magical","necromancy"]},swallowSpike:{name:"PF2E.ArmorPropertyRuneSwallowSpike",level:6,price:200,rarity:"common",slug:"swallowSpike",traits:["magical","transmutation"]},trueQuenching:{name:"PF2E.ArmorPropertyRuneTrueQuenching",level:18,price:24e3,rarity:"common",slug:"trueQuenching",traits:["abjuration","magical"]},trueStanching:{name:"PF2E.ArmorPropertyRuneTrueStanching",level:17,price:12500,rarity:"uncommon",slug:"trueStanching",traits:["magical","necromancy"]},winged:{name:"PF2E.ArmorPropertyRuneWinged",level:13,price:2500,rarity:"common",slug:"winged",traits:["magical","transmutation"]}},WEAPON_PROPERTY_RUNES={anarchic:{damage:{dice:[{damageType:"chaotic",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.anarchic.Name",text:"PF2E.WeaponPropertyRune.anarchic.Note.criticalSuccess"}]},level:11,name:"PF2E.WeaponPropertyRune.anarchic.Name",price:1400,rarity:"common",slug:"anarchic",traits:["chaotic","evocation","magical"]},ancestralEchoing:{level:15,name:"PF2E.WeaponPropertyRune.ancestralEchoing.Name",price:9500,rarity:"rare",slug:"ancestralEchoing",traits:["dwarf","evocation","magical","saggorak"]},anchoring:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.anchoring.Name",text:"PF2E.WeaponPropertyRune.anchoring.Note.criticalSuccess"}]},level:10,name:"PF2E.WeaponPropertyRune.anchoring.Name",price:900,rarity:"uncommon",slug:"anchoring",traits:["abjuration","magical"]},ashen:{damage:{dice:[{damageType:"fire",category:"persistent",diceNumber:1,dieSize:"d4"}],notes:[{outcome:["success"],title:"PF2E.WeaponPropertyRune.ashen.Name",text:"PF2E.WeaponPropertyRune.ashen.Note.success"}]},level:9,name:"PF2E.WeaponPropertyRune.ashen.Name",price:700,rarity:"common",slug:"ashen",traits:["enchantment","magical"]},authorized:{level:3,name:"PF2E.WeaponPropertyRune.authorized.Name",price:50,rarity:"common",slug:"authorized",traits:["abjuration","magical"]},axiomatic:{damage:{dice:[{damageType:"lawful",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.axiomatic.Name",text:"PF2E.WeaponPropertyRune.axiomatic.Note.criticalSuccess"}]},level:11,name:"PF2E.WeaponPropertyRune.axiomatic.Name",price:1400,rarity:"common",slug:"axiomatic",traits:["evocation","lawful","magical"]},bane:{level:4,name:"PF2E.WeaponPropertyRune.bane.Name",price:100,rarity:"uncommon",slug:"bane",traits:["divination","magical"]},bloodbane:{level:8,name:"PF2E.WeaponPropertyRune.bloodbane.Name",price:475,rarity:"uncommon",slug:"bloodbane",traits:["dwarf","evocation","magical"]},bloodthirsty:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.bloodbane.Name",text:"PF2E.WeaponPropertyRune.bloodthirsty.Note.criticalSuccess"}]},level:16,name:"PF2E.WeaponPropertyRune.bloodthirsty.Name",price:8500,rarity:"uncommon",slug:"bloodthirsty",traits:["magical","necromancy"]},brilliant:{damage:{dice:[{damageType:"fire",diceNumber:1,dieSize:"d4"},{damageType:"good",diceNumber:1,dieSize:"d4",predicate:[{or:["target:trait:fiend",{not:"target"}]}]},{damageType:"vitality",diceNumber:1,dieSize:"d4"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.brilliant.Name",text:"PF2E.WeaponPropertyRune.brilliant.Note.criticalSuccess"}]},level:12,name:"PF2E.WeaponPropertyRune.brilliant.Name",price:2e3,rarity:"common",slug:"brilliant",traits:["evocation","magical"]},called:{level:7,name:"PF2E.WeaponPropertyRune.called.Name",price:350,rarity:"common",slug:"called",traits:["conjuration","magical"]},coating:{level:9,name:"PF2E.WeaponPropertyRune.coating.Name",price:700,rarity:"common",slug:"coating",traits:["conjuration","extradimensional","magical"]},conducting:{level:7,name:"PF2E.WeaponPropertyRune.conducting.Name",price:300,rarity:"common",slug:"conducting",traits:["evocation","magical"]},corrosive:{damage:{dice:[{damageType:"acid",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.corrosive.Name",text:"PF2E.WeaponPropertyRune.corrosive.Note.criticalSuccess"}]},level:8,name:"PF2E.WeaponPropertyRune.corrosive.Name",price:500,rarity:"common",slug:"corrosive",traits:["acid","conjuration","magical"]},crushing:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.crushing.Name",text:"PF2E.WeaponPropertyRune.crushing.Note.criticalSuccess"}]},level:3,name:"PF2E.WeaponPropertyRune.crushing.Name",price:50,rarity:"uncommon",slug:"crushing",traits:["magical","necromancy"]},cunning:{level:5,name:"PF2E.WeaponPropertyRune.cunning.Name",price:140,rarity:"common",slug:"cunning",traits:["divination","magical"]},dancing:{level:13,name:"PF2E.WeaponPropertyRune.dancing.Name",price:2700,rarity:"uncommon",slug:"dancing",traits:["evocation","magical"]},deathdrinking:{damage:{dice:[{slug:"deathdrinking-negative",damageType:"void",diceNumber:1,dieSize:"d6",critical:!0,predicate:["target:mode:living",{not:"target:negative-healing"}]},{slug:"deathdrinking-positive",damageType:"vitality",diceNumber:1,dieSize:"d6",critical:!0,predicate:["target:negative-healing"]}]},level:7,name:"PF2E.WeaponPropertyRune.deathdrinking.Name",price:360,rarity:"rare",slug:"deathdrinking",traits:["magical","necromancy"]},demolishing:{damage:{dice:[{damageType:"force",category:"persistent",diceNumber:1,dieSize:"d6",predicate:["target:trait:construct"]}]},level:6,name:"PF2E.WeaponPropertyRune.demolishing.Name",price:225,rarity:"rare",slug:"demolishing",traits:["evocation","magical"]},disrupting:{damage:{dice:[{damageType:"vitality",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.disrupting.Name",text:"PF2E.WeaponPropertyRune.disrupting.Note.criticalSuccess"}]},level:5,name:"PF2E.WeaponPropertyRune.disrupting.Name",price:150,rarity:"common",slug:"disrupting",traits:["magical","necromancy"]},earthbinding:{level:5,name:"PF2E.WeaponPropertyRune.earthbinding.Name",price:125,rarity:"common",slug:"earthbinding",traits:["magical","transmutation"]},energizing:{level:6,name:"PF2E.WeaponPropertyRune.energizing.Name",price:250,rarity:"uncommon",slug:"energizing",traits:["abjuration","magical"]},extending:{level:7,name:"PF2E.WeaponPropertyRune.extending.Name",price:700,rarity:"common",slug:"extending",traits:["magical","transmutation"]},fanged:{level:2,name:"PF2E.WeaponPropertyRune.fanged.Name",price:30,rarity:"uncommon",slug:"fanged",traits:["magical","transmutation"]},fearsome:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.fearsome.Name",text:"PF2E.WeaponPropertyRune.fearsome.Note.criticalSuccess"}]},level:5,name:"PF2E.WeaponPropertyRune.fearsome.Name",price:160,rarity:"common",slug:"fearsome",traits:["emotion","enchantment","fear","magical","mental"]},flaming:{damage:{dice:[{damageType:"fire",diceNumber:1,dieSize:"d6"},{damageType:"fire",category:"persistent",diceNumber:1,dieSize:"d10",critical:!0}]},level:8,name:"PF2E.WeaponPropertyRune.flaming.Name",price:500,rarity:"common",slug:"flaming",traits:["conjuration","fire","magical"]},flurrying:{level:7,name:"PF2E.WeaponPropertyRune.flurrying.Name",price:360,rarity:"common",slug:"flurrying",traits:["evocation","magical"]},frost:{damage:{dice:[{damageType:"cold",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.frost.Name",text:"PF2E.WeaponPropertyRune.frost.Note.criticalSuccess"}]},level:8,name:"PF2E.WeaponPropertyRune.frost.Name",price:500,rarity:"common",slug:"frost",traits:["cold","conjuration","magical"]},ghostTouch:{damage:{notes:[{predicate:[{or:["target:trait:incorporeal",{not:"target"}]}],title:"PF2E.WeaponPropertyRune.ghostTouch.Name",text:"PF2E.WeaponPropertyRune.ghostTouch.Note"}]},level:4,name:"PF2E.WeaponPropertyRune.ghostTouch.Name",price:75,rarity:"common",slug:"ghostTouch",traits:["magical","transmutation"]},giantKilling:{damage:{dice:[{slug:"giantKilling",damageType:"mental",diceNumber:1,dieSize:"d6",predicate:["target:trait:giant"]}],notes:[{outcome:["criticalSuccess"],predicate:["target:trait:giant"],title:"PF2E.WeaponPropertyRune.giantKilling.Name",text:"PF2E.WeaponPropertyRune.giantKilling.Note.criticalSuccess"}]},level:8,name:"PF2E.WeaponPropertyRune.giantKilling.Name",price:450,rarity:"rare",slug:"giantKilling",traits:["magical","necromancy"]},greaterAnchoring:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterAnchoring.Name",text:"PF2E.WeaponPropertyRune.greaterAnchoring.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterAnchoring.Name",text:"PF2E.WeaponPropertyRune.greaterAnchoring.Note.success"}]},level:18,name:"PF2E.WeaponPropertyRune.greaterAnchoring.Name",price:22e3,rarity:"uncommon",slug:"greaterAnchoring",traits:["abjuration","magical"]},greaterAshen:{damage:{dice:[{damageType:"fire",category:"persistent",diceNumber:1,dieSize:"d8"}],notes:[{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterAshen.Name",text:"PF2E.WeaponPropertyRune.greaterAshen.Note.success"}]},level:16,name:"PF2E.WeaponPropertyRune.greaterAshen.Name",price:9e3,rarity:"common",slug:"greaterAshen",traits:["enchantment","magical"]},greaterBloodbane:{level:13,name:"PF2E.WeaponPropertyRune.greaterBloodbane.Name",price:2800,rarity:"uncommon",slug:"greaterBloodbane",traits:["dwarf","evocation","magical"]},greaterBrilliant:{damage:{dice:[{damageType:"fire",diceNumber:1,dieSize:"d4"},{damageType:"good",diceNumber:1,dieSize:"d4",predicate:[{or:["target:trait:fiend",{not:"target"}]}]},{damageType:"vitality",diceNumber:1,dieSize:"d4"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterBrilliant.Name",text:"PF2E.WeaponPropertyRune.greaterBrilliant.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterBrilliant.Name",text:"PF2E.WeaponPropertyRune.greaterBrilliant.Note.success"}],ignoredResistances:[{type:"fire",max:null},{type:"good",max:null},{type:"vitality",max:null}]},level:18,name:"PF2E.WeaponPropertyRune.greaterBrilliant.Name",price:24e3,rarity:"common",slug:"greaterBrilliant",traits:["evocation","magical"]},greaterCorrosive:{damage:{dice:[{damageType:"acid",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterCorrosive.Name",text:"PF2E.WeaponPropertyRune.greaterCorrosive.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterCorrosive.Name",text:"PF2E.WeaponPropertyRune.greaterCorrosive.Note.success"}]},level:15,name:"PF2E.WeaponPropertyRune.greaterCorrosive.Name",price:6500,rarity:"common",slug:"greaterCorrosive",traits:["acid","conjuration","magical"]},greaterCrushing:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterCrushing.Name",text:"PF2E.WeaponPropertyRune.greaterCrushing.Note.criticalSuccess"}]},level:9,name:"PF2E.WeaponPropertyRune.greaterCrushing.Name",price:650,rarity:"uncommon",slug:"greaterCrushing",traits:["magical","necromancy"]},greaterDisrupting:{damage:{dice:[{damageType:"vitality",diceNumber:2,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterDisrupting.Name",text:"PF2E.WeaponPropertyRune.greaterDisrupting.Note.criticalSuccess"}]},level:14,name:"PF2E.WeaponPropertyRune.greaterDisrupting.Name",price:4300,rarity:"uncommon",slug:"greaterDisrupting",traits:["magical","necromancy"]},greaterExtending:{level:13,name:"PF2E.WeaponPropertyRune.greaterExtending.Name",price:3e3,rarity:"common",slug:"greaterExtending",traits:["magical","transmutation"]},greaterFanged:{level:8,name:"PF2E.WeaponPropertyRune.greaterFanged.Name",price:425,rarity:"uncommon",slug:"greaterFanged",traits:["magical","transmutation"]},greaterFearsome:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterFearsome.Name",text:"PF2E.WeaponPropertyRune.greaterFearsome.Note.criticalSuccess"}]},level:12,name:"PF2E.WeaponPropertyRune.greaterFearsome.Name",price:2e3,rarity:"common",slug:"greaterFearsome",traits:["emotion","enchantment","fear","magical","mental"]},greaterFlaming:{damage:{dice:[{damageType:"fire",diceNumber:1,dieSize:"d6"},{damageType:"fire",category:"persistent",diceNumber:2,dieSize:"d10",critical:!0}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterFlaming.Name",text:"PF2E.WeaponPropertyRune.greaterFlaming.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterFlaming.Name",text:"PF2E.WeaponPropertyRune.greaterFlaming.Note.success"}],ignoredResistances:[{type:"fire",max:null}]},level:15,name:"PF2E.WeaponPropertyRune.greaterFlaming.Name",price:6500,rarity:"common",slug:"greaterFlaming",traits:["conjuration","fire","magical"]},greaterFrost:{damage:{dice:[{damageType:"cold",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterFrost.Name",text:"PF2E.WeaponPropertyRune.greaterFrost.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterFrost.Name",text:"PF2E.WeaponPropertyRune.greaterFrost.Note.success"}],ignoredResistances:[{type:"cold",max:null}]},level:15,name:"PF2E.WeaponPropertyRune.greaterFrost.Name",price:6500,rarity:"common",slug:"greaterFrost",traits:["cold","conjuration","magical"]},greaterGiantKilling:{damage:{dice:[{slug:"greaterGiantKilling",damageType:"mental",diceNumber:2,dieSize:"d6",predicate:["target:trait:giant"]}],ignoredResistances:[{type:"mental",max:null}],notes:[{outcome:["criticalSuccess"],predicate:["target:trait:giant"],title:"PF2E.WeaponPropertyRune.greaterGiantKilling.Name",text:"PF2E.WeaponPropertyRune.greaterGiantKilling.Note.criticalSuccess"}]},level:15,name:"PF2E.WeaponPropertyRune.greaterGiantKilling.Name",price:6e3,rarity:"rare",slug:"greaterGiantKilling",traits:["magical","necromancy"]},greaterHauling:{level:11,name:"PF2E.WeaponPropertyRune.greaterHauling.Name",price:1300,rarity:"uncommon",slug:"greaterHauling",traits:["evocation","magical"]},greaterImpactful:{damage:{dice:[{damageType:"force",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterImpactful.Name",text:"PF2E.WeaponPropertyRune.greaterImpactful.Note.criticalSuccess"}]},level:17,name:"PF2E.WeaponPropertyRune.greaterImpactful.Name",price:15e3,rarity:"common",slug:"greaterImpactful",traits:["evocation","force","magical"]},greaterRooting:{level:11,name:"PF2E.WeaponPropertyRune.greaterRooting.Name",price:1400,rarity:"common",slug:"greaterRooting",traits:["plant","magical","wood"],damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterRooting.Name",text:"PF2E.WeaponPropertyRune.greaterRooting.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterRooting.Name",text:"PF2E.WeaponPropertyRune.greaterRooting.Note.success"}]}},greaterShock:{damage:{dice:[{damageType:"electricity",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterShock.Name",text:"PF2E.WeaponPropertyRune.greaterShock.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterShock.Name",text:"PF2E.WeaponPropertyRune.greaterShock.Note.success"}],ignoredResistances:[{type:"electricity",max:null}]},level:15,name:"PF2E.WeaponPropertyRune.greaterShock.Name",price:6500,rarity:"common",slug:"greaterShock",traits:["electricity","evocation","magical"]},greaterThundering:{damage:{dice:[{damageType:"sonic",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterThundering.Name",text:"PF2E.WeaponPropertyRune.greaterThundering.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterThundering.Name",text:"PF2E.WeaponPropertyRune.greaterThundering.Note.success"}],ignoredResistances:[{type:"sonic",max:null}]},level:15,name:"PF2E.WeaponPropertyRune.greaterThundering.Name",price:6500,rarity:"common",slug:"greaterThundering",traits:["evocation","magical","sonic"]},grievous:{damage:{dice:[{damageType:"bleed",diceNumber:1,dieSize:"d6",critical:!0,predicate:["critical-specialization","item:group:dart"]}],notes:[{outcome:["criticalSuccess"],predicate:["item:group:axe"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Axe"},{outcome:["criticalSuccess"],predicate:["item:group:brawling"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Brawling"},{outcome:["criticalSuccess"],predicate:["item:group:club"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Club"},{outcome:["criticalSuccess"],predicate:["item:group:flail"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Flail"},{outcome:["criticalSuccess"],predicate:["item:group:hammer"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Hammer"},{outcome:["criticalSuccess"],predicate:["item:group:knife"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Knife"},{outcome:["criticalSuccess"],predicate:["item:group:polearm"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Polearm"},{outcome:["criticalSuccess"],predicate:["item:group:shield"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Shield"},{outcome:["criticalSuccess"],predicate:["item:group:sling"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Sling"},{outcome:["criticalSuccess"],predicate:["item:group:spear"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Spear"},{outcome:["criticalSuccess"],predicate:["item:group:sword"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Sword"}],adjustments:[{slug:"critical-specialization",test:options=>new PredicatePF2e("item:group:pick").test(options),getNewValue:current=>current*2}]},level:9,name:"PF2E.WeaponPropertyRune.grievous.Name",price:700,rarity:"common",slug:"grievous",traits:["enchantment","magical"]},hauling:{level:6,name:"PF2E.WeaponPropertyRune.hauling.Name",price:225,rarity:"uncommon",slug:"hauling",traits:["evocation","magical"]},holy:{damage:{dice:[{damageType:"good",diceNumber:1,dieSize:"d6"}]},level:11,name:"PF2E.WeaponPropertyRune.holy.Name",price:1400,rarity:"common",slug:"holy",traits:["evocation","good","magical"]},hopeful:{attack:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.hopeful.Name",text:"PF2E.WeaponPropertyRune.hopeful.Note.criticalSuccess"}]},level:11,name:"PF2E.WeaponPropertyRune.hopeful.Name",price:1200,rarity:"uncommon",slug:"hopeful",traits:["enchantment","magical"]},hooked:{level:5,name:"PF2E.WeaponPropertyRune.hooked.Name",price:140,rarity:"rare",slug:"hooked",traits:["conjuration","magical"],strikeAdjustments:[{adjustWeapon:weapon=>{weapon.system.traits.value.includes("trip")||weapon.system.traits.value.push("trip")}}]},impactful:{damage:{dice:[{damageType:"force",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.impactful.Name",text:"PF2E.WeaponPropertyRune.impactful.Note.criticalSuccess"}]},level:10,name:"PF2E.WeaponPropertyRune.impactful.Name",price:1e3,rarity:"common",slug:"impactful",traits:["evocation","force","magical"]},impossible:{level:20,name:"PF2E.WeaponPropertyRune.impossible.Name",price:7e4,rarity:"common",slug:"impossible",traits:["conjuration","magical"],strikeAdjustments:[{adjustWeapon:weapon=>{if(weapon.isOfType("weapon")&&weapon.system.range&&weapon._source.system.range){const sourceRange=weapon._source.system.range,preparedRange=weapon.system.range;weapon.system.range=sourceRange*2+Math.abs(preparedRange-sourceRange)}}}]},keen:{attack:{notes:[{outcome:["success"],title:"PF2E.WeaponPropertyRune.keen.Name",text:"PF2E.WeaponPropertyRune.keen.Note"}]},level:13,name:"PF2E.WeaponPropertyRune.keen.Name",price:3e3,rarity:"uncommon",slug:"keen",traits:["magical","transmutation"]},kinWarding:{level:3,name:"PF2E.WeaponPropertyRune.kinWarding.Name",price:52,rarity:"uncommon",slug:"kinWarding",traits:["abjuration","dwarf","magical"]},majorFanged:{level:15,name:"PF2E.WeaponPropertyRune.majorFanged.Name",price:6e3,rarity:"uncommon",slug:"majorFanged",traits:["magical","transmutation"]},majorRooting:{level:15,name:"PF2E.WeaponPropertyRune.majorRooting.Name",price:6500,rarity:"common",slug:"majorRooting",traits:["plant","magical","wood"],damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.majorRooting.Name",text:"PF2E.WeaponPropertyRune.majorRooting.Note.criticalSuccess"}]}},merciful:{strikeAdjustments:[{adjustWeapon:weapon=>{weapon.system.traits.value.includes("nonlethal")||weapon.system.traits.value.push("nonlethal")}}],level:4,name:"PF2E.WeaponPropertyRune.merciful.Name",price:70,rarity:"common",slug:"merciful",traits:["abjuration","magical","mental"]},pacifying:{level:5,name:"PF2E.WeaponPropertyRune.pacifying.Name",price:150,rarity:"uncommon",slug:"pacifying",traits:["enchantment","magical"]},returning:{attack:{notes:[{title:"PF2E.WeaponPropertyRune.returning.Name",text:"PF2E.WeaponPropertyRune.returning.Note"}]},level:3,name:"PF2E.WeaponPropertyRune.returning.Name",price:55,rarity:"common",slug:"returning",traits:["evocation","magical"]},rooting:{level:7,name:"PF2E.WeaponPropertyRune.rooting.Name",price:360,rarity:"common",slug:"rooting",traits:["plant","magical","wood"],damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.rooting.Name",text:"PF2E.WeaponPropertyRune.rooting.Note.criticalSuccess"}]}},serrating:{damage:{dice:[{damageType:"slashing",diceNumber:1,dieSize:"d4"}]},level:10,name:"PF2E.WeaponPropertyRune.serrating.Name",price:1e3,rarity:"uncommon",slug:"serrating",traits:["evocation","magical"]},shifting:{level:6,name:"PF2E.WeaponPropertyRune.shifting.Name",price:225,rarity:"common",slug:"shifting",traits:["magical","transmutation"]},shock:{damage:{dice:[{damageType:"electricity",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.shock.Name",text:"PF2E.WeaponPropertyRune.shock.Note.criticalSuccess"}]},level:8,name:"PF2E.WeaponPropertyRune.shock.Name",price:500,rarity:"common",slug:"shock",traits:["electricity","conjuration","magical"]},speed:{level:16,name:"PF2E.WeaponPropertyRune.speed.Name",price:1e4,rarity:"rare",slug:"speed",traits:["magical","transmutation"]},spellStoring:{level:13,name:"PF2E.WeaponPropertyRune.spellStoring.Name",price:2700,rarity:"uncommon",slug:"spellStoring",traits:["abjuration","magical"]},swarming:{level:9,name:"PF2E.WeaponPropertyRune.swarming.Name",price:700,rarity:"common",slug:"swarming",traits:["conjuration","magical"]},thundering:{damage:{dice:[{damageType:"sonic",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.thundering.Name",text:"PF2E.WeaponPropertyRune.thundering.Note.criticalSuccess"}]},level:8,name:"PF2E.WeaponPropertyRune.thundering.Name",price:500,rarity:"common",slug:"thundering",traits:["evocation","magical","sonic"]},trueRooting:{level:19,name:"PF2E.WeaponPropertyRune.trueRooting.Name",price:4e4,rarity:"common",slug:"trueRooting",traits:["plant","magical","wood"],damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.trueRooting.Name",text:"PF2E.WeaponPropertyRune.trueRooting.Note.criticalSuccess"}]}},underwater:{level:3,name:"PF2E.WeaponPropertyRune.underwater.Name",price:50,rarity:"common",slug:"underwater",traits:["magical","water"]},unholy:{damage:{dice:[{damageType:"evil",diceNumber:1,dieSize:"d6"}]},level:11,name:"PF2E.WeaponPropertyRune.unholy.Name",price:1400,rarity:"common",slug:"unholy",traits:["evil","evocation","magical"]},vorpal:{level:17,name:"PF2E.WeaponPropertyRune.vorpal.Name",price:15e3,rarity:"rare",slug:"vorpal",traits:["evocation","magical"]},wounding:{damage:{dice:[{damageType:"bleed",diceNumber:1,dieSize:"d6"}]},level:7,name:"PF2E.WeaponPropertyRune.wounding.Name",price:340,rarity:"common",slug:"wounding",traits:["magical","necromancy"]}},RUNE_DATA={armor:{...FUNDAMENTAL_ARMOR_RUNE_DATA,property:ARMOR_PROPERTY_RUNES},weapon:{...FUNDAMENTAL_WEAPON_RUNE_DATA,property:WEAPON_PROPERTY_RUNES}};function computePrice(item){const basePrice=item.price.value;if(item.isOfType("treasure"))return basePrice;const materialPrice=getMaterialValuationData(item)?.price??0,heldOrStowedBulk=new Bulk({light:item.system.bulk.heldOrStowed}),bulk=Math.max(Math.ceil(heldOrStowedBulk.normal),1),materialValue=materialPrice+bulk*materialPrice/10,runesData=getRuneValuationData(item),runeValue=item.isSpecific?0:runesData.reduce((sum2,rune)=>sum2+rune.price,0),afterMaterialAndRunes=runeValue?new CoinsPF2e({gp:runeValue+materialValue}):basePrice.add({gp:materialValue}),higher=afterMaterialAndRunes.copperValue>basePrice.copperValue?afterMaterialAndRunes:basePrice,afterShoddy=item.isShoddy?higher.scale(.5):higher;return item.isMagical?afterShoddy:afterShoddy.adjustForSize(item.size)}__name(computePrice,"computePrice"),__name2(computePrice,"computePrice");function computeLevelRarityPrice(item){const materialData=getMaterialValuationData(item),price=computePrice(item);if(!(item.isMagical||materialData)||item.isSpecific||item.isOfType("armor")&&item.isShield)return{...pick$1(item,["level","rarity"]),price};const runesData=getRuneValuationData(item),level=runesData.map(runeData=>runeData.level).concat(materialData?.level??0).reduce((highest,level2)=>level2>highest?level2:highest,item.level),rarityOrder={common:0,uncommon:1,rare:2,unique:3},baseRarity=item.rarity,rarity=runesData.map(runeData=>runeData.rarity).concat(materialData?.rarity??"common").reduce((highest,rarity2)=>rarityOrder[rarity2]>rarityOrder[highest]?rarity2:highest,baseRarity);return{level,rarity,price}}__name(computeLevelRarityPrice,"computeLevelRarityPrice"),__name2(computeLevelRarityPrice,"computeLevelRarityPrice");function generateItemName(item){if(!item.isOfType("armor","weapon")||item.isOfType("armor")&&item.isShield)return item.name;const[baseItemDictionary,propertyDictionary,fundamentalTwoDictionary]=item.isOfType("armor")?[CONFIG.PF2E.baseArmorTypes,RUNE_DATA.armor.property,RUNE_DATA.armor.resilient]:[CONFIG.PF2E.baseWeaponTypes,RUNE_DATA.weapon.property,RUNE_DATA.weapon.striking],storedName=item._source.name,baseType=item.baseType??"";if(!baseType||!(baseType in baseItemDictionary)||item.isSpecific||storedName!==game.i18n.localize(baseItemDictionary[baseType]??""))return item.name;const{material}=item,{runes}=item.system,potencyRune=runes.potency,fundamental2="resilient"in runes?runes.resilient:runes.striking,params={base:baseType?game.i18n.localize(baseItemDictionary[baseType]??""):item.name,material:material.type&&game.i18n.localize(CONFIG.PF2E.preciousMaterials[material.type]),potency:potencyRune,fundamental2:game.i18n.localize(fundamentalTwoDictionary[fundamental2]?.name??"")||null,property1:game.i18n.localize(propertyDictionary[runes.property[0]]?.name??"")||null,property2:game.i18n.localize(propertyDictionary[runes.property[1]]?.name??"")||null,property3:game.i18n.localize(propertyDictionary[runes.property[2]]?.name??"")||null,property4:game.i18n.localize(propertyDictionary[runes.property[3]]?.name??"")||null},formatString=(()=>{const potency=params.potency&&"Potency",fundamental22=params.fundamental2&&"Fundamental2",properties=params.property4?"FourProperties":params.property3?"ThreeProperties":params.property2?"TwoProperties":params.property1?"OneProperty":null,material2=params.material&&"Material",key=[potency,fundamental22,properties,material2].filter(keyPart=>!!keyPart).join("")||null;return key&&game.i18n.localize(key)})();return formatString?game.i18n.format(`PF2E.Item.Physical.GeneratedName.${formatString}`,params):item.name}__name(generateItemName,"generateItemName"),__name2(generateItemName,"generateItemName");function organizeBulkData(item){const stackData=STACK_DEFINITIONS[item.system.stackGroup??""]??null,per=stackData?.size??1,heldOrStowed=stackData?.lightBulk??weightToBulk(item.system.weight.value)?.toLightBulk()??0,worn=item.system.equippedBulk.value?weightToBulk(item.system.equippedBulk.value)?.toLightBulk()??0:heldOrStowed,value=item.isOfType("armor","equipment","backpack")&&item.isEquipped?worn:heldOrStowed;return{heldOrStowed,worn,value,per}}__name(organizeBulkData,"organizeBulkData"),__name2(organizeBulkData,"organizeBulkData");const _Migration639NormalizeLevelAndPrice=class extends MigrationBase{static{__name(this,"_Migration639NormalizeLevelAndPrice")}coinSlugs=new Set(["platinum-pieces","gold-pieces","silver-pieces","copper-pieces"]);async updateItem(source){if(source.system.level&&(source.system.level.value=Number(source.system.level.value)||0),!isPhysicalData(source)||this.coinSlugs.has(source.system.slug??""))return;const system=source.system,price=system.price;if(!(typeof price.value!="string"&&isObject(price.value)))if(price.value?price.value=price.value.trim():price.value="0 gp",/^[0-9]+$/.test(price.value))price.value=`${price.value} gp`;else{const quantity=system.quantity,priceValue=price.value;CoinsPF2e.fromString(priceValue,quantity).copperValue&&(price.value="0 gp")}}};__name2(_Migration639NormalizeLevelAndPrice,"Migration639NormalizeLevelAndPrice"),__publicField(_Migration639NormalizeLevelAndPrice,"version",.639);let Migration639NormalizeLevelAndPrice=_Migration639NormalizeLevelAndPrice;const _Migration640CantripsAreNotZeroLevel=class extends MigrationBase{static{__name(this,"_Migration640CantripsAreNotZeroLevel")}async updateItem(itemData){if(itemData.type!=="spell")return;const level=itemData.system.level;level.value===0&&(level.value=1,itemData.system.traits.value.includes("cantrip")||itemData.system.traits.value.push("cantrip"))}};__name2(_Migration640CantripsAreNotZeroLevel,"Migration640CantripsAreNotZeroLevel"),__publicField(_Migration640CantripsAreNotZeroLevel,"version",.64);let Migration640CantripsAreNotZeroLevel=_Migration640CantripsAreNotZeroLevel;const _Migration641SovereignSteelValue=class extends MigrationBase{static{__name(this,"_Migration641SovereignSteelValue")}async updateItem(source){if(source.type!=="weapon")return;const material=source.system.preciousMaterial??{};material.value?.toLowerCase()==="sovereign steel"&&(material.value="sovereignSteel")}};__name2(_Migration641SovereignSteelValue,"Migration641SovereignSteelValue"),__publicField(_Migration641SovereignSteelValue,"version",.641);let Migration641SovereignSteelValue=_Migration641SovereignSteelValue;const _Migration642TrackSchemaVersion=class extends MigrationBase{static{__name(this,"_Migration642TrackSchemaVersion")}async updateActor(actorSource){actorSource.system.schema??={version:null,lastMigration:null}}async updateItem(itemSource){itemSource.system.schema??={version:null,lastMigration:null}}};__name2(_Migration642TrackSchemaVersion,"Migration642TrackSchemaVersion"),__publicField(_Migration642TrackSchemaVersion,"version",.642);let Migration642TrackSchemaVersion=_Migration642TrackSchemaVersion;const _Migration643HazardLevel=class extends MigrationBase{static{__name(this,"_Migration643HazardLevel")}async updateActor(actorSource){if(actorSource.type!=="hazard")return;const hazardDetails=actorSource.system.details;if(typeof hazardDetails.level=="number"){const level=hazardDetails.level;hazardDetails.level={value:level}}}};__name2(_Migration643HazardLevel,"Migration643HazardLevel"),__publicField(_Migration643HazardLevel,"version",.643);let Migration643HazardLevel=_Migration643HazardLevel;const defaultTraditionByClass$1={wizard:"arcane",cleric:"divine",druid:"primal",bard:"occult",ranger:"primal",champion:"divine",monk:"divine"},_Migration644SpellcastingCategory=class extends MigrationBase{static{__name(this,"_Migration644SpellcastingCategory")}async updateItem(item,actor){if(!actor||item.type!=="spellcastingEntry")return;const spellcasting=item.system;if(spellcasting.tradition.value==="ritual")spellcasting.prepared.value="ritual",spellcasting.tradition.value="";else if(spellcasting.tradition.value==="focus"){spellcasting.prepared.value="focus";const possibleMatch=actor.items.find(testItem=>{if(testItem.type!=="spellcastingEntry")return!1;const testSpellcasting=testItem.system;return tupleHasValue(["prepared","spontaneous"],testSpellcasting.prepared.value)&&testSpellcasting.tradition.value!=="focus"&&(actor.type==="character"?testSpellcasting.proficiency.value===spellcasting.proficiency.value:testSpellcasting.spelldc.value===spellcasting.spelldc.value)&&(testSpellcasting.ability.value||"int")===(spellcasting.ability.value||"int")});if(possibleMatch)spellcasting.tradition.value=possibleMatch.system.tradition.value;else{const classItem=actor.items.find(testItem=>testItem.type==="class"),className=classItem?.system.slug||sluggify(classItem?.name??"");spellcasting.tradition.value=defaultTraditionByClass$1[className]??"arcane"}}}};__name2(_Migration644SpellcastingCategory,"Migration644SpellcastingCategory"),__publicField(_Migration644SpellcastingCategory,"version",.644);let Migration644SpellcastingCategory=_Migration644SpellcastingCategory;const _Migration645TokenImageSize=class extends MigrationBase{static{__name(this,"_Migration645TokenImageSize")}constructor(){super(...arguments),__privateAdd(this,_isTokenImageFlag),__privateAdd(this,_isTokenSizeFlag),__privateAdd(this,_imageOverrides,new Map),__privateAdd(this,_sizeOverrides,new Map)}async updateActor(actorSource){const flags=actorSource.flags,originalImg=flags.pf2e?.token?.img;__privateMethod(this,_isTokenImageFlag,isTokenImageFlag_fn).call(this,originalImg)&&__privateGet(this,_imageOverrides).set(actorSource._id,originalImg);const originalSize=flags.pf2e?.token?.size;__privateMethod(this,_isTokenSizeFlag,isTokenSizeFlag_fn).call(this,originalSize)&&__privateGet(this,_sizeOverrides).set(actorSource._id,originalSize),typeof flags.pf2e?.token=="object"&&("game"in globalThis&&(flags.pf2e["-=token"]=null),delete flags.pf2e.token)}async updateToken(tokenSource,actor){tokenSource.texture.src=__privateGet(this,_imageOverrides).get(actor?.id??"")??tokenSource.texture.src;const sizeOverride=__privateGet(this,_sizeOverrides).get(actor?.id??"");tokenSource.height=sizeOverride?.height??tokenSource.height,tokenSource.width=sizeOverride?.width??tokenSource.width}};_imageOverrides=new WeakMap,_sizeOverrides=new WeakMap,_isTokenImageFlag=new WeakSet,isTokenImageFlag_fn=__name2(function(flag){return typeof flag=="string"},"#isTokenImageFlag"),_isTokenSizeFlag=new WeakSet,isTokenSizeFlag_fn=__name2(function(flag){return flag instanceof Object&&"height"in flag&&typeof flag.height=="number"&&"width"in flag&&typeof flag.width=="number"},"#isTokenSizeFlag"),__name2(_Migration645TokenImageSize,"Migration645TokenImageSize"),__publicField(_Migration645TokenImageSize,"version",.645);let Migration645TokenImageSize=_Migration645TokenImageSize;const _Migration646UpdateInlineLinks=class extends MigrationBase{static{__name(this,"_Migration646UpdateInlineLinks")}updateCheckAttributes(markup=""){return markup.replace(/\bdata-pf2-([a-z]+)-check="\w*"/g,'data-pf2-check="$1"').replace(/\bdata-pf2-(?:saving-throw|skill-check)\b/g,"data-pf2-check")}async updateActor(actorData){if(actorData.type==="hazard"){const hazardDetails=actorData.system.details;hazardDetails.disable=this.updateCheckAttributes(hazardDetails.disable??"")}}async updateItem(itemData){const description=itemData.system.description;description.value=this.updateCheckAttributes(description.value??"")}};__name2(_Migration646UpdateInlineLinks,"Migration646UpdateInlineLinks"),__publicField(_Migration646UpdateInlineLinks,"version",.646);let Migration646UpdateInlineLinks=_Migration646UpdateInlineLinks;const _Migration647FixPCSenses=class extends MigrationBase{static{__name(this,"_Migration647FixPCSenses")}async updateActor(actorData){if(actorData.type!=="character")return;const notTraits=actorData.system.traits;Array.isArray(notTraits.senses)?notTraits.senses=notTraits.senses.filter(sense=>!!sense):notTraits.senses=[]}};__name2(_Migration647FixPCSenses,"Migration647FixPCSenses"),__publicField(_Migration647FixPCSenses,"version",.647);let Migration647FixPCSenses=_Migration647FixPCSenses;const _Migration648RemoveInvestedProperty=class extends MigrationBase{static{__name(this,"_Migration648RemoveInvestedProperty")}async updateItem(itemSource){if(!(itemSource.type==="treasure"||itemSource.type==="consumable"))return;const systemData=itemSource.system;delete systemData.invested,"game"in globalThis&&(systemData["-=invested"]=null)}};__name2(_Migration648RemoveInvestedProperty,"Migration648RemoveInvestedProperty"),__publicField(_Migration648RemoveInvestedProperty,"version",.648);let Migration648RemoveInvestedProperty=_Migration648RemoveInvestedProperty;function isCreatureSource(source){return["character","npc"].includes(source.type)}__name(isCreatureSource,"isCreatureSource"),__name2(isCreatureSource,"isCreatureSource");const _Migration649FocusToActor=class extends MigrationBase{static{__name(this,"_Migration649FocusToActor")}async updateActor(actorData){if(!isCreatureSource(actorData))return;const systemData=actorData.system;systemData.resources||(systemData.resources={});const spellLists=actorData.items.filter(i=>i.type==="spellcastingEntry").sort((a,b)=>(a.sort||0)-(b.sort||0)).map(i=>i.system).filter(i=>i.prepared.value==="focus"&&i.focus).sort((a,b)=>(b.focus?.pool||0)-(a.focus?.pool||0));if(spellLists.length===0)return;const focusOld=spellLists[0].focus,resources=actorData.system.resources;resources.focus={value:focusOld?.points??0,max:focusOld?.pool??1}}async updateItem(itemData){if(itemData.type!=="spellcastingEntry")return;const data=itemData.system;delete data.focus,"game"in globalThis&&(data["-=focus"]=null)}};__name2(_Migration649FocusToActor,"Migration649FocusToActor"),__publicField(_Migration649FocusToActor,"version",.649);let Migration649FocusToActor=_Migration649FocusToActor;const _Migration650StringifyWeaponProperties=class extends MigrationBase{static{__name(this,"_Migration650StringifyWeaponProperties")}async updateItem(itemData){if(itemData.type!=="weapon")return;const systemData=itemData.system;systemData.weaponType&&(systemData.weaponType.value||="simple");const range=systemData.range??={value:"melee"};range instanceof Object&&typeof range.value=="string"&&(range.value=range.value.trim()||"melee",range.value==="reach"&&(range.value="melee"))}};__name2(_Migration650StringifyWeaponProperties,"Migration650StringifyWeaponProperties"),__publicField(_Migration650StringifyWeaponProperties,"version",.65);let Migration650StringifyWeaponProperties=_Migration650StringifyWeaponProperties;const _Migration651EphemeralFocusPool=class extends MigrationBase{static{__name(this,"_Migration651EphemeralFocusPool")}constructor(){super(...arguments),__privateAdd(this,_needsRuleElement),__privateAdd(this,_isClassFeature),__privateAdd(this,_increasesByOne,new Set(["abundant-step","achaekeks-grip","advanced-bloodline","advanced-deitys-domain","advanced-domain","advanced-revelation","advanced-school-spell","advanced-seeker-of-truths","animal-feature","arcane-school-spell","apex-companion","basic-lesson","beastmasters-trance","blessed-sacrifice","cackle","champions-sacrifice","clinging-shadows-initiate","counter-perform","debilitating-dichotomy","domain-acumen","domain-fluency","empty-body","enlarge-companion","ephemeral-tracking","familiar-form","fatal-aria","gaze-of-veracity","greater-bloodline","greater-lesson","greater-revelation","heal-animal","healing-touch","hunters-luck","hunters-vision","impaling-briars","inspire-heroics","invoke-disaster","invoke-the-crimson-oath","ki-blast","ki-form","ki-rush","ki-strike","leaf-order","light-of-revelation","lingering-composition","litany-against-sloth","litany-against-wrath","litany-of-depravity","litany-of-righteousness","litany-of-self-interest","loremasters-etude","magic-hide","major-lesson","mantis-form","medusas-wrath","order-spell","perfect-ki-adept","perfect-strike","quivering-palm","rangers-bramble","shadow-magic","shadows-web","shall-not-falter-shall-not-rout","snare-hopping","song-of-the-fallen","soothing-ballad","soothing-mist","speaking-sky","spellmasters-ward","steal-the-sky","storm-order","sun-blade","suns-fury","terrain-transposition","transcribe-moment","universal-versatility","vision-of-weakness","wholeness-of-body","wild-winds-initiate","wind-caller","wind-jump","wronged-monks-wrath"]))}async updateActor(source){if(source.type!=="character")return;const systemData=source.system;systemData.resources??={};const resources=systemData.resources;typeof resources.focus?.max=="number"&&"game"in globalThis?resources.focus["-=max"]=null:delete resources.focus?.max}async updateItem(source){if(source.type!=="feat")return;const systemData=source.system,rule=(()=>{const slug=systemData.slug??sluggify(source.name);return slug==="revelation-spells"?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"upgrade",value:2,priority:10}:slug==="major-curse"?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"upgrade",value:3}:["composition-spells","devotion-spells","druidic-order","hexes"].includes(slug)||/^(?:arcane-school|bloodline)-/.test(slug)&&__privateMethod(this,_isClassFeature,isClassFeature_fn).call(this,source)?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"upgrade",value:1,priority:10}:__privateGet(this,_increasesByOne).has(slug)||slug.startsWith("first-revelation-")?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"add",value:1}:null})();rule&&__privateMethod(this,_needsRuleElement,needsRuleElement_fn).call(this,source.system.rules)&&systemData.rules.push(rule)}};_needsRuleElement=new WeakSet,needsRuleElement_fn=__name2(function(rules){return!rules.some(rule=>rule.key==="ActiveEffectLike"&&rule.path==="system.resources.focus.max")},"#needsRuleElement"),_increasesByOne=new WeakMap,_isClassFeature=new WeakSet,isClassFeature_fn=__name2(function(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"},"#isClassFeature"),__name2(_Migration651EphemeralFocusPool,"Migration651EphemeralFocusPool"),__publicField(_Migration651EphemeralFocusPool,"version",.651);let Migration651EphemeralFocusPool=_Migration651EphemeralFocusPool;const defaultTraditionByClass={wizard:"arcane",druid:"primal",ranger:"primal"},_Migration652KillHalcyonTradition=class extends MigrationBase{static{__name(this,"_Migration652KillHalcyonTradition")}async updateItem(itemData,actor){if(itemData.type!=="spellcastingEntry")return;const tradition=itemData.system.tradition;if(tradition.value==="halcyon"){const classItem=actor?.items.find(testItem=>testItem.type==="class"),className=classItem?.system.slug||sluggify(classItem?.name??"");tradition.value=defaultTraditionByClass[className]??"arcane"}}};__name2(_Migration652KillHalcyonTradition,"Migration652KillHalcyonTradition"),__publicField(_Migration652KillHalcyonTradition,"version",.652);let Migration652KillHalcyonTradition=_Migration652KillHalcyonTradition;const _Migration653AEstoREs=class extends MigrationBase{static{__name(this,"_Migration653AEstoREs")}constructor(){super(...arguments),__privateAdd(this,_isRemovableAE),__privateAdd(this,_isRemoveableChange),__privateAdd(this,_fixClassKeyAbilities),__privateAdd(this,_pathsToRemove,new Set([...["unarmored","light","medium","heavy"].map(category=>`system.martial.${category}.rank`),...["unarmed","simple","martial","advanced"].map(category=>`system.martial.${category}.rank`),...["fortitude","reflex","will"].map(save=>`system.saves.${save}.rank`),"system.details.keyability.value","system.attributes.perception.rank","system.attributes.classDC.rank"]))}async updateActor(actorSource){if(actorSource.type!=="character")return;const systemData=actorSource.system;systemData.martial={},actorSource.effects=actorSource.effects.filter(effect=>{const origin=effect.origin??"",itemId=/\bItem\.([A-Za-z0-9]{16})$/.exec(origin)?.[1],itemSource=actorSource.items.find(maybeSource=>maybeSource._id===itemId);return itemSource&&!(["class","effect","feat"].includes(itemSource.type)&&__privateMethod(this,_isRemovableAE,isRemovableAE_fn).call(this,effect))})}async updateItem(itemSource){if(!(itemSource.type==="class"||itemSource.type==="effect"||itemSource.type==="feat"))return;itemSource.type==="class"&&__privateMethod(this,_fixClassKeyAbilities,fixClassKeyAbilities_fn).call(this,itemSource);const modes2={1:"multiply",2:"add",3:"downgrade",4:"upgrade",5:"override"};for(const effect of[...itemSource.effects]){itemSource.type==="class"&&(effect.changes=effect.changes.filter(change=>!__privateGet(this,_pathsToRemove).has(change.key)));const toAELikes=effect.changes.filter(__privateMethod(this,_isRemoveableChange,isRemoveableChange_fn)),rules=itemSource.system.rules;for(const change of toAELikes){if(change.mode===0)continue;const newRule={key:"ActiveEffectLike",path:change.key,mode:modes2[change.mode],value:Number.isNaN(Number(change.value))?change.value:Number(change.value),priority:change.priority??50};rules.push(newRule)}effect.changes=effect.changes.filter(change=>!__privateMethod(this,_isRemoveableChange,isRemoveableChange_fn).call(this,change))}itemSource.effects=itemSource.effects.filter(effect=>!__privateMethod(this,_isRemovableAE,isRemovableAE_fn).call(this,effect))}};_pathsToRemove=new WeakMap,_isRemovableAE=new WeakSet,isRemovableAE_fn=__name2(function(effect){return effect.changes.every(__privateMethod(this,_isRemoveableChange,isRemoveableChange_fn))},"#isRemovableAE"),_isRemoveableChange=new WeakSet,isRemoveableChange_fn=__name2(function(change){return change.mode!==0&&Number.isInteger(Number(change.value))||change.mode===5&&!change.value.startsWith("{")},"#isRemoveableChange"),_fixClassKeyAbilities=new WeakSet,fixClassKeyAbilities_fn=__name2(function(classSource){const keyAbility=classSource.system.keyAbility;keyAbility.value=keyAbility.value.map(value=>typeof value=="string"?value:value.value)},"#fixClassKeyAbilities"),__name2(_Migration653AEstoREs,"Migration653AEstoREs"),__publicField(_Migration653AEstoREs,"version",.653);let Migration653AEstoREs=_Migration653AEstoREs;const _Migration654ActionTypeAndCount=class extends MigrationBase{static{__name(this,"_Migration654ActionTypeAndCount")}async updateItem(item){if(item.type!=="feat"&&item.type!=="action")return;const systemData=item.system;systemData.actions.value=Math.min(3,Math.max(Number(systemData.actions.value),0))||null}};__name2(_Migration654ActionTypeAndCount,"Migration654ActionTypeAndCount"),__publicField(_Migration654ActionTypeAndCount,"version",.654);let Migration654ActionTypeAndCount=_Migration654ActionTypeAndCount;const _Migration655CreatureTokenSizes=class extends MigrationBase{static{__name(this,"_Migration655CreatureTokenSizes")}constructor(){super(...arguments),__privateAdd(this,_isTokenSizeRE),__privateAdd(this,_isActorSizeAELike),__privateAdd(this,_isBracketedValue),__publicField(this,"dimensionToSize",{.5:"tiny",2:"lg",3:"huge",4:"grg"})}async updateItem(itemSource){itemSource.system.rules??=[];const rules=itemSource.system.rules,actorSizeAELike=rules.find(__privateMethod(this,_isActorSizeAELike,isActorSizeAELike_fn)),tokenSizeRE=rules.find(__privateMethod(this,_isTokenSizeRE,isTokenSizeRE_fn));if(actorSizeAELike)actorSizeAELike.key="CreatureSize",delete actorSizeAELike.path,delete actorSizeAELike.mode;else if(tokenSizeRE&&["number","string","object"].includes(typeof tokenSizeRE.value))if(tokenSizeRE.key="CreatureSize",__privateMethod(this,_isBracketedValue,isBracketedValue_fn).call(this,tokenSizeRE.value))for(const bracket of tokenSizeRE.value.brackets)typeof bracket.value=="number"&&(bracket.value=this.dimensionToSize[bracket.value]??"med");else typeof tokenSizeRE.value=="number"&&(tokenSizeRE.value=this.dimensionToSize[tokenSizeRE.value]??"med");tokenSizeRE&&tokenSizeRE.key!=="CreatureSize"&&itemSource.system.rules.splice(itemSource.system.rules.indexOf(tokenSizeRE),1)}};_isTokenSizeRE=new WeakSet,isTokenSizeRE_fn=__name2(function(rule){return typeof rule.key=="string"&&rule.key.endsWith("TokenSize")},"#isTokenSizeRE"),_isActorSizeAELike=new WeakSet,isActorSizeAELike_fn=__name2(function(rule){return typeof rule.key=="string"&&rule.key.endsWith("ActiveEffectLike")&&rule.path==="system.traits.size.value"},"#isActorSizeAELike"),_isBracketedValue=new WeakSet,isBracketedValue_fn=__name2(function(value){return isObject(value)&&Array.isArray(value.brackets)},"#isBracketedValue"),__name2(_Migration655CreatureTokenSizes,"Migration655CreatureTokenSizes"),__publicField(_Migration655CreatureTokenSizes,"version",.655);let Migration655CreatureTokenSizes=_Migration655CreatureTokenSizes;const _Migration656OtherFocusPoolSources=class extends MigrationBase{static{__name(this,"_Migration656OtherFocusPoolSources")}needsRuleElement(rules){return!rules.some(rule=>rule.key==="ActiveEffectLike"&&rule.path==="system.resources.focus.max")}increasesByOne=new Set(["additional-shadow-magic","basic-bloodline-spell","blessed-one-dedication","breath-of-the-dragon","crystal-ward-spells","domain-initiate","expanded-domain-initiate","gravity-weapon","heal-companion","leaf-order","shadow-illusion","storm-order","wings-of-the-dragon"]);async updateItem(itemSource){if(itemSource.type!=="feat")return;const systemData=itemSource.system,rule=(()=>{const slug=systemData.slug??sluggify(itemSource.name);return slug==="druidic-order"?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"upgrade",value:1,priority:10}:this.increasesByOne.has(slug)?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"add",value:1}:null})();rule&&this.needsRuleElement(itemSource.system.rules)&&systemData.rules.push(rule)}};__name2(_Migration656OtherFocusPoolSources,"Migration656OtherFocusPoolSources"),__publicField(_Migration656OtherFocusPoolSources,"version",.656);let Migration656OtherFocusPoolSources=_Migration656OtherFocusPoolSources;const _Migration657RemoveSetProperty=class extends MigrationBase{static{__name(this,"_Migration657RemoveSetProperty")}async updateActor(actorSource){const systemFlags=actorSource.flags.pf2e??{};delete systemFlags["set-property"],"game"in globalThis&&"set-property"in systemFlags&&(systemFlags["-=set-property"]=null)}async updateItem(itemSource){itemSource.system.rules??=[];const rules=itemSource.system.rules,setPropertyRules=itemSource.system.rules.filter(rule=>typeof rule.key=="string"&&["SetProperty","PF2E.RuleElement.SetProperty"].includes(rule.key)&&typeof rule.property=="string"&&typeof rule.on=="object"&&rule.on!==null&&"added"in rule.on),aeLikes=setPropertyRules.map(setProperty2=>({key:"ActiveEffectLike",mode:"override",path:setProperty2.property.replace(/^flags\.2e/,"flags.pf2e"),value:setProperty2.on.added,priority:10}));for(const setPropertyRule of setPropertyRules){const index=rules.indexOf(setPropertyRule);rules.splice(index,1,aeLikes.shift())}itemSource.system.rules=itemSource.system.rules.filter(rule=>rule&&typeof rule.key=="string"&&!rule.key.trim().endsWith("SetProperty"))}};__name2(_Migration657RemoveSetProperty,"Migration657RemoveSetProperty"),__publicField(_Migration657RemoveSetProperty,"version",.657);let Migration657RemoveSetProperty=_Migration657RemoveSetProperty;const _Migration658MonkUnarmoredProficiency=class extends MigrationBase{static{__name(this,"_Migration658MonkUnarmoredProficiency")}async updateItem(itemSource){const slug=itemSource.system.slug??sluggify(itemSource.name);itemSource.type==="class"&&slug==="monk"&&itemSource.system.defenses.unarmored!==2&&(itemSource.system.defenses.unarmored=2)}};__name2(_Migration658MonkUnarmoredProficiency,"Migration658MonkUnarmoredProficiency"),__publicField(_Migration658MonkUnarmoredProficiency,"version",.658);let Migration658MonkUnarmoredProficiency=_Migration658MonkUnarmoredProficiency;const formulaHasValue=__name2(value=>!!value&&value!=="0","formulaHasValue"),modes=["level1","level2","level3","level4"],_Migration659MultipleDamageRows=class extends MigrationBase{static{__name(this,"_Migration659MultipleDamageRows")}async updateItem(source){if(source.type!=="spell")return;const data=source.system;if(data.scaling instanceof Object&&(typeof data.scaling.mode=="string"&&tupleHasValue(modes,data.scaling.mode)&&(data.scaling.interval=modes.indexOf(data.scaling.mode)+1),typeof data.scaling.formula=="string"&&formulaHasValue(data.scaling.formula)&&!data.scaling.damage&&(data.scaling.damage={0:data.scaling.formula}),!data.scaling.interval||!data.scaling.damage?"game"in globalThis?data["-=scaling"]=null:delete data.scaling:"game"in globalThis?(data.scaling["-=mode"]=null,data.scaling["-=formula"]=null):(delete data.scaling.mode,delete data.scaling.formula)),typeof data.damage.value=="string"){if(formulaHasValue(data.damage.value)||data.damage.applyMod){const value=data.damage.value;data.damage.value={0:{value,applyMod:data.damage.applyMod||void 0,type:{value:data.damageType?.value||"untyped",categories:[]}}}}else data.damage.value={};"game"in globalThis?data.damage["-=applyMod"]=null:delete data.damage.applyMod}"damageType"in data&&("game"in globalThis?data["-=damageType"]=null:data.damageType=void 0)}};__name2(_Migration659MultipleDamageRows,"Migration659MultipleDamageRows"),__publicField(_Migration659MultipleDamageRows,"version",.659);let Migration659MultipleDamageRows=_Migration659MultipleDamageRows;const _Migration660DerivedSpellTraits=class extends MigrationBase{static{__name(this,"_Migration660DerivedSpellTraits")}derivedTraits=[...MAGIC_SCHOOLS,...MAGIC_TRADITIONS];async updateItem(itemSource){if(itemSource.type==="spell"){const traits=itemSource.system.traits;traits.value=traits.value.filter(trait=>!this.derivedTraits.includes(trait))}}};__name2(_Migration660DerivedSpellTraits,"Migration660DerivedSpellTraits"),__publicField(_Migration660DerivedSpellTraits,"version",.66);let Migration660DerivedSpellTraits=_Migration660DerivedSpellTraits;const _Migration661NumifyVehicleDimensions=class extends MigrationBase{static{__name(this,"_Migration661NumifyVehicleDimensions")}async updateActor(actorSource){if(actorSource.type==="vehicle"){const{space}=actorSource.system.details;space.long=Number(space.long)||2,space.wide=Number(space.wide)||2,space.high=Number(space.high)||1}}};__name2(_Migration661NumifyVehicleDimensions,"Migration661NumifyVehicleDimensions"),__publicField(_Migration661NumifyVehicleDimensions,"version",.661);let Migration661NumifyVehicleDimensions=_Migration661NumifyVehicleDimensions;const _Migration662LinkToActorSizeDefaults=class extends MigrationBase{static{__name(this,"_Migration662LinkToActorSizeDefaults")}async updateActor(actorSource){const linkToActorSize=!["hazard","loot"].includes(actorSource.type);actorSource.prototypeToken.flags??={pf2e:{linkToActorSize}},actorSource.prototypeToken.flags.pf2e??={linkToActorSize},actorSource.prototypeToken.flags.pf2e.linkToActorSize??=linkToActorSize}async updateToken(tokenSource,actor){const linkToActorSize=!["hazard","loot"].includes(actor.type);tokenSource.flags.pf2e??={linkToActorSize},tokenSource.flags.pf2e.linkToActorSize??=linkToActorSize}};__name2(_Migration662LinkToActorSizeDefaults,"Migration662LinkToActorSizeDefaults"),__publicField(_Migration662LinkToActorSizeDefaults,"version",.662);let Migration662LinkToActorSizeDefaults=_Migration662LinkToActorSizeDefaults;function createBasicDamage(value,applyMod,damageType){return{0:{applyMod,type:{categories:[],value:damageType},value}}}__name(createBasicDamage,"createBasicDamage"),__name2(createBasicDamage,"createBasicDamage");function createBasicScaling(interval,scaling){return{interval,damage:{0:scaling}}}__name(createBasicScaling,"createBasicScaling"),__name2(createBasicScaling,"createBasicScaling");const _Migration663FixSpellDamage=class extends MigrationBase{static{__name(this,"_Migration663FixSpellDamage")}async updateItem(source){if(source.type!=="spell"||Object.keys(source.system.damage?.value??{}).length>0)return;const itemName=source.system.slug??sluggify(source.name),systemData=source.system;switch(itemName){case"animated-assault":systemData.damage.value=createBasicDamage("2d10",!1,"bludgeoning"),systemData.scaling=createBasicScaling(2,"2d10");break;case"daze":systemData.damage.value=createBasicDamage("0",!0,"mental"),systemData.scaling=createBasicScaling(2,"1d6");break;case"personal-blizzard":systemData.damage.value={0:{applyMod:!1,type:{value:"cold",categories:[]},value:"1d6"},1:{applyMod:!1,type:{value:"cold",subtype:"persistent",categories:[]},value:"1d6"}},systemData.scaling={interval:1,damage:{0:"1",1:"1"}};break;case"power-word-kill":systemData.damage.value=createBasicDamage("50",!1,"untyped");break}}};__name2(_Migration663FixSpellDamage,"Migration663FixSpellDamage"),__publicField(_Migration663FixSpellDamage,"version",.663);let Migration663FixSpellDamage=_Migration663FixSpellDamage;const _Migration664DeleteCUBConditions=class extends MigrationBase{static{__name(this,"_Migration664DeleteCUBConditions")}async updateActor(actorSource){const cubConditions=actorSource.items.filter(item=>item.type==="condition"&&!item.system.references?.overriddenBy);for(const condition of cubConditions)actorSource.items.findSplice(item=>item===condition)}};__name2(_Migration664DeleteCUBConditions,"Migration664DeleteCUBConditions"),__publicField(_Migration664DeleteCUBConditions,"version",.664);let Migration664DeleteCUBConditions=_Migration664DeleteCUBConditions;const _Migration665HandwrapsCorrections=class extends MigrationBase{static{__name(this,"_Migration665HandwrapsCorrections")}async updateItem(itemSource){const slug=itemSource.system.slug??sluggify(itemSource.name);if(itemSource.type==="weapon"&&slug==="handwraps-of-mighty-blows"){const usage=itemSource.system.usage;usage.value="worn-gloves"}const dirPath="systems/pf2e/icons/equipment/worn-items/other-worn-items";itemSource.img===`${dirPath}/handwraps-of-nighty-blows.webp`&&(itemSource.img=`${dirPath}/handwraps-of-mighty-blows.webp`)}};__name2(_Migration665HandwrapsCorrections,"Migration665HandwrapsCorrections"),__publicField(_Migration665HandwrapsCorrections,"version",.665);let Migration665HandwrapsCorrections=_Migration665HandwrapsCorrections;const _Migration666UsageAndStowingContainers=class extends MigrationBase{static{__name(this,"_Migration666UsageAndStowingContainers")}backpacks=new Set(["backpack","knapsack-of-halflingkind","knapsack-of-halflingkind-greater","sturdy-satchel","vaultbreaker-harness","voyagers-pack"]);wornGarment=new Set(["sleeves-of-storage","sleeves-of-storage-greater"]);wornGloves=new Set(["gloves-of-storing"]);heldInTwoHands=new Set(["bag-of-devouring-type-i","bag-of-devouring-type-ii","bag-of-devouring-type-iii","bag-of-holding-type-i","bag-of-holding-type-ii","bag-of-holding-type-iii","bag-of-holding-type-iv","bag-of-weasels","chest","sealing-chest-greater","sealing-chest-lesser","sealing-chest-moderate"]);stowingContainers=new Set([...this.backpacks,...this.heldInTwoHands,...this.wornGarment,...this.wornGloves,"extradimensional-stash"]);async updateItem(itemSource){if(!itemSource.system.traits)return;const traits=itemSource.system.traits;if(typeof traits.usage?.value=="string"){const traitUsage=traits.usage.value,isPhysical=isPhysicalData(itemSource),keepUsage=isPhysical&&(traitUsage!=="held-in-one-hand"||itemSource.system.usage.value==="");isPhysical&&keepUsage&&(itemSource.system.usage.value=traits.usage.value),"game"in globalThis?traits["-=usage"]=null:delete traits.usage}if(itemSource.type!=="backpack")return;const slug=itemSource.system.slug??sluggify(itemSource.name);this.backpacks.has(slug)?itemSource.system.usage.value="wornbackpack":this.heldInTwoHands.has(slug)?itemSource.system.usage.value="held-in-two-hands":this.wornGarment.has(slug)?itemSource.system.usage.value="worngarment":this.wornGloves.has(slug)?itemSource.system.usage.value="worngloves":itemSource.system.usage.value="worn",itemSource.system.stowing=this.stowingContainers.has(slug)}};__name2(_Migration666UsageAndStowingContainers,"Migration666UsageAndStowingContainers"),__publicField(_Migration666UsageAndStowingContainers,"version",.666);let Migration666UsageAndStowingContainers=_Migration666UsageAndStowingContainers;const _Migration667HPSubProperties=class extends MigrationBase{static{__name(this,"_Migration667HPSubProperties")}addRecoveryMultiplier(itemSource,slug){if(!["dream-may","fast-recovery"].includes(slug))return;const rules=itemSource.system.rules;if(!rules.some(rule=>"path"in rule&&rule.path==="system.attributes.hp.recoveryMultiplier")){const element={key:"ActiveEffectLike",mode:"add",path:"system.attributes.hp.recoveryMultiplier",value:1};rules.push(element)}}addNegativeHealing(itemSource,slug){if(!["dhampir","negative-healing"].includes(slug))return;const rules=itemSource.system.rules;if(!rules.some(rule=>"path"in rule&&rule.path==="system.attributes.hp.negativeHealing")){const element={key:"ActiveEffectLike",mode:"override",path:"system.attributes.hp.negativeHealing",value:!0};rules.push(element)}}async updateItem(itemSource){if(itemSource.type!=="feat"&&itemSource.type!=="action")return;const slug=itemSource.system.slug??sluggify(itemSource.name);this.addRecoveryMultiplier(itemSource,slug),this.addNegativeHealing(itemSource,slug)}};__name2(_Migration667HPSubProperties,"Migration667HPSubProperties"),__publicField(_Migration667HPSubProperties,"version",.667);let Migration667HPSubProperties=_Migration667HPSubProperties;const _Migration668ArmorSpeedPenalty=class extends MigrationBase{static{__name(this,"_Migration668ArmorSpeedPenalty")}async updateItem(itemSource){const slug=itemSource.system.slug??sluggify(itemSource.name);if(itemSource.type==="armor"){const rules=itemSource.system.rules??=[],rule=rules.find(r=>typeof r.key=="string"&&r.key.endsWith("FlatModifier")&&r.selector==="speed"&&typeof r.value=="object"&&JSON.stringify(r.predicate??null)===JSON.stringify({not:["unburdened-iron"]}));rule&&rules.splice(rules.indexOf(rule),1)}else if(itemSource.type==="feat"){if(slug==="unburdened-iron"){const rule={key:"RollOption",domain:"speed",option:"armor:ignore-speed-penalty"};itemSource.system.rules=[rule]}else if(slug==="armored-stealth"){const rule={key:"RollOption",domain:"stealth",option:"armor:ignore-noisy-penalty"};itemSource.system.rules=[rule]}}}};__name2(_Migration668ArmorSpeedPenalty,"Migration668ArmorSpeedPenalty"),__publicField(_Migration668ArmorSpeedPenalty,"version",.668);let Migration668ArmorSpeedPenalty=_Migration668ArmorSpeedPenalty;const _Migration669NPCAttackEffects=class extends MigrationBase{static{__name(this,"_Migration669NPCAttackEffects")}async updateItem(item,actor){!actor||item.type!=="melee"||(item.system.attackEffects??={value:[]},Array.isArray(item.system.attackEffects.value)&&item.system.attackEffects.value.forEach((entry,index,arr)=>{arr[index]=sluggify(entry)}))}};__name2(_Migration669NPCAttackEffects,"Migration669NPCAttackEffects"),__publicField(_Migration669NPCAttackEffects,"version",.669);let Migration669NPCAttackEffects=_Migration669NPCAttackEffects;const _Migration670AncestryVision=class extends MigrationBase{static{__name(this,"_Migration670AncestryVision")}constructor(){super(...arguments),__privateAdd(this,_setAncestryVision),__publicField(this,"DARKVISION_ID","HHVQDp61ehcpdiU8"),__publicField(this,"LOWLIGHTVISION_ID","DRtaqOHXTRtGRIUT")}async updateActor(source){if(source.type!=="character")return;const ancestry=source.items.find(item=>item.type==="ancestry");if(ancestry){__privateMethod(this,_setAncestryVision,setAncestryVision_fn).call(this,ancestry);for(const vision of["darkvision","low-light-vision"]){const index=source.items.findIndex(item=>item.type==="feat"&&(item.system.slug??sluggify(item.name))===vision);index!==-1&&source.items.splice(index,1)}}}async updateItem(source,actor){source.type==="ancestry"&&!actor&&__privateMethod(this,_setAncestryVision,setAncestryVision_fn).call(this,source)}};_setAncestryVision=new WeakSet,setAncestryVision_fn=__name2(function(ancestry){const features=ancestry.system.items;for(const[key,value]of Object.entries(features))value?.id===this.LOWLIGHTVISION_ID?("game"in globalThis?features[`-=${key}`]=null:delete features[key],ancestry.system.vision=ancestry.system.vision==="darkvision"?"darkvision":"lowLightVision"):value?.id===this.DARKVISION_ID&&("game"in globalThis?features[`-=${key}`]=null:delete features[key],ancestry.system.vision="darkvision");ancestry.system.vision??="normal"},"#setAncestryVision"),__name2(_Migration670AncestryVision,"Migration670AncestryVision"),__publicField(_Migration670AncestryVision,"version",.67);let Migration670AncestryVision=_Migration670AncestryVision;const _Migration670NoCustomTrait=class extends MigrationBase{static{__name(this,"_Migration670NoCustomTrait")}async updateItem(itemSource){const traits=itemSource.system.traits;traits&&(Array.isArray(traits.value)?traits.value=traits.value.filter(trait=>trait&&trait!=="custom"):traits.value=[])}};__name2(_Migration670NoCustomTrait,"Migration670NoCustomTrait"),__publicField(_Migration670NoCustomTrait,"version",.67);let Migration670NoCustomTrait=_Migration670NoCustomTrait;const _Migration671NoPCItemsOnNonPCs=class extends MigrationBase{static{__name(this,"_Migration671NoPCItemsOnNonPCs")}async updateActor(actorSource){if(actorSource.type==="character")return;const pcOnlyTypes=["ancestry","background","class","feat"],forbiddenItems=actorSource.items.filter(item=>pcOnlyTypes.includes(item.type));for(const forbiddenItem of forbiddenItems){const index=actorSource.items.findIndex(item=>item===forbiddenItem);index!==-1&&actorSource.items.splice(index,1)}}};__name2(_Migration671NoPCItemsOnNonPCs,"Migration671NoPCItemsOnNonPCs"),__publicField(_Migration671NoPCItemsOnNonPCs,"version",.671);let Migration671NoPCItemsOnNonPCs=_Migration671NoPCItemsOnNonPCs;const PHYSICAL_DAMAGE_TYPES=["bludgeoning","piercing","slashing","bleed"],LIFE_ENERGY_DAMAGE_TYPES=["vitality","void"],ENERGY_DAMAGE_TYPES=["acid","cold","electricity","fire","sonic","force",...LIFE_ENERGY_DAMAGE_TYPES],ALIGNMENT_DAMAGE_TYPES=["chaotic","lawful","good","evil"],DAMAGE_CATEGORIES_UNIQUE=new Set(["persistent","precision","splash"]),MATERIAL_DAMAGE_EFFECTS=new Set(["adamantine","cold-iron","darkwood","mithral","orichalcum","silver","sisterstone-dusk","sisterstone-scarlet","warpglass"]);[...DAMAGE_CATEGORIES_UNIQUE,...MATERIAL_DAMAGE_EFFECTS];const DAMAGE_DIE_FACES_TUPLE=["d4","d6","d8","d10","d12"],DAMAGE_DIE_FACES=new Set(DAMAGE_DIE_FACES_TUPLE),DAMAGE_TYPES=new Set([...PHYSICAL_DAMAGE_TYPES,...ENERGY_DAMAGE_TYPES,...ALIGNMENT_DAMAGE_TYPES,"mental","poison","spirit","untyped"]),BASE_DAMAGE_TYPES_TO_CATEGORIES={bludgeoning:"physical",piercing:"physical",slashing:"physical",bleed:"physical",acid:"energy",cold:"energy",electricity:"energy",fire:"energy",sonic:"energy",vitality:"energy",void:"energy",force:"energy",chaotic:"alignment",evil:"alignment",good:"alignment",lawful:"alignment",mental:null,poison:null,spirit:null,untyped:null},DAMAGE_TYPE_ICONS={bleed:"droplet",acid:"vial",bludgeoning:"hammer",chaotic:"face-zany",cold:"snowflake",electricity:"bolt",evil:"face-angry-horns",fire:"fire",force:"sparkles",good:"face-smile-halo",lawful:"scale-balanced",mental:"brain",piercing:"bow-arrow",poison:"spider",slashing:"axe",sonic:"waveform-lines",spirit:"ghost",vitality:"sun",void:"skull",untyped:null},PERSISTENT_DAMAGE_IMAGES={acid:"icons/magic/acid/dissolve-arm-flesh.webp",bludgeoning:"systems/pf2e/icons/equipment/weapons/bola.webp",chaotic:"systems/pf2e/icons/spells/dinosaur-form.webp",cold:"icons/magic/water/ice-snowman.webp",electricity:"systems/pf2e/icons/spells/chain-lightning.webp",evil:"icons/magic/unholy/strike-body-explode-disintegrate.webp",fire:"icons/magic/fire/flame-burning-creature-skeleton.webp",force:"systems/pf2e/icons/spells/magic-missile.webp",good:"systems/pf2e/icons/damage/persistent/good.webp",lawful:"systems/pf2e/icons/equipment/adventuring-gear/merchant-scale.webp",mental:"systems/pf2e/icons/spells/modify-memory.webp",piercing:"systems/pf2e/icons/equipment/weapons/throwing-knife.webp",poison:"systems/pf2e/icons/spells/acidic-burst.webp",slashing:"systems/pf2e/icons/equipment/weapons/scimitar.webp",sonic:"systems/pf2e/icons/spells/cry-of-destruction.webp",spirit:"icons/magic/unholy/hand-claw-fire-blue.webp",vitality:"systems/pf2e/icons/spells/moment-of-renewal.webp",void:"systems/pf2e/icons/spells/grim-tendrils.webp"},CRITICAL_INCLUSION={DOUBLE_ON_CRIT:null,CRITICAL_ONLY:!0,DONT_DOUBLE_ON_CRIT:!1},_MystifiedTraits=class{static{__name(this,"_MystifiedTraits")}static compile(){this.mystifiedTraits=new Set(["artifact","extradimensional","invested","shadow",...Object.keys(CONFIG.PF2E.consumableTraits).filter(t=>!["consumable","nonlethal"].includes(t))].sort())}static has(trait){return this.mystifiedTraits.has(trait)}};__name2(_MystifiedTraits,"MystifiedTraits"),__publicField(_MystifiedTraits,"mystifiedTraits",new Set);let MystifiedTraits=_MystifiedTraits;const ITEM_CARRY_TYPES=new Set(["held","worn","stowed","dropped"]),RANGE_TRAITS=["range-5","range-10","range-15","range-20","range-25","range-30","range-40","range-50","range-60","range-70","range-80","range-90","range-100","range-110","range-120","range-140","range-150","range-160","range-170","range-180","range-190","range-200","range-210","range-220","range-230","range-240","range-250","range-260","range-270","range-280","range-290","range-300","range-310","range-320","range-500","range-increment-5","range-increment-10","range-increment-15","range-increment-20","range-increment-25","range-increment-30","range-increment-40","range-increment-50","range-increment-60","range-increment-70","range-increment-75","range-increment-80","range-increment-90","range-increment-100","range-increment-110","range-increment-120","range-increment-130","range-increment-140","range-increment-150","range-increment-160","range-increment-170","range-increment-180","range-increment-190","range-increment-200","range-increment-210","range-increment-220","range-increment-230","range-increment-240","range-increment-250","range-increment-260","range-increment-270","range-increment-280","range-increment-290","range-increment-300","range-increment-310","range-increment-320"],ancestryTraits={"half-elf":"PF2E.TraitHalfElf","half-orc":"PF2E.TraitHalfOrc",aasimar:"PF2E.TraitAasimar",aberration:"PF2E.TraitAberration",anadi:"PF2E.TraitAnadi",android:"PF2E.TraitAndroid",aphorite:"PF2E.TraitAphorite",ardande:"PF2E.TraitArdande",automaton:"PF2E.TraitAutomaton",azarketi:"PF2E.TraitAzarketi",beastkin:"PF2E.TraitBeastkin",catfolk:"PF2E.TraitCatfolk",changeling:"PF2E.TraitChangeling",conrasu:"PF2E.TraitConrasu",dhampir:"PF2E.TraitDhampir",duskwalker:"PF2E.TraitDuskwalker",dwarf:"PF2E.TraitDwarf",elf:"PF2E.TraitElf",fetchling:"PF2E.TraitFetchling",fleshwarp:"PF2E.TraitFleshwarp",ganzi:"PF2E.TraitGanzi",geniekin:"PF2E.TraitGeniekin",ghoran:"PF2E.TraitGhoran",gnoll:"PF2E.TraitGnoll",gnome:"PF2E.TraitGnome",goblin:"PF2E.TraitGoblin",goloma:"PF2E.TraitGoloma",grippli:"PF2E.TraitGrippli",halfling:"PF2E.TraitHalfling",hobgoblin:"PF2E.TraitHobgoblin",human:"PF2E.TraitHuman",ifrit:"PF2E.TraitIfrit",kashrishi:"PF2E.TraitKashrishi",kitsune:"PF2E.TraitKitsune",kobold:"PF2E.TraitKobold",leshy:"PF2E.TraitLeshy",lizardfolk:"PF2E.TraitLizardfolk",nagaji:"PF2E.TraitNagaji",orc:"PF2E.TraitOrc",oread:"PF2E.TraitOread",poppet:"PF2E.TraitPoppet",ratfolk:"PF2E.TraitRatfolk",reflection:"PF2E.TraitReflection",shisk:"PF2E.TraitShisk",shoony:"PF2E.TraitShoony",skeleton:"PF2E.TraitSkeleton",sprite:"PF2E.TraitSprite",strix:"PF2E.TraitStrix",suli:"PF2E.TraitSuli",sylph:"PF2E.TraitSylph",talos:"PF2E.TraitTalos",tengu:"PF2E.TraitTengu",tiefling:"PF2E.TraitTiefling",undine:"PF2E.TraitUndine",vanara:"PF2E.TraitVanara",vishkanya:"PF2E.TraitVishkanya"},ancestryItemTraits={...ancestryTraits,aeon:"PF2E.TraitAeon",amphibious:"PF2E.TraitAmphibious",automaton:"PF2E.TraitAutomaton",construct:"PF2E.TraitConstruct",fey:"PF2E.TraitFey",fungus:"PF2E.TraitFungus",humanoid:"PF2E.TraitHumanoid",plant:"PF2E.TraitPlant",undead:"PF2E.TraitUndead"},elementTraits={air:"PF2E.TraitAir",earth:"PF2E.TraitEarth",fire:"PF2E.TraitFire",metal:"PF2E.TraitMetal",water:"PF2E.TraitWater",wood:"PF2E.TraitWood"},energyDamageTypes={acid:"PF2E.TraitAcid",cold:"PF2E.TraitCold",electricity:"PF2E.TraitElectricity",fire:"PF2E.TraitFire",force:"PF2E.TraitForce",sonic:"PF2E.TraitSonic",vitality:"PF2E.TraitVitality",void:"PF2E.TraitVoid"},magicTraditions={arcane:"PF2E.TraitArcane",divine:"PF2E.TraitDivine",occult:"PF2E.TraitOccult",primal:"PF2E.TraitPrimal"},creatureTraits={...ancestryItemTraits,...elementTraits,...energyDamageTypes,...magicTraditions,aberration:"PF2E.TraitAberration",aeon:"PF2E.TraitAeon",aesir:"PF2E.TraitAesir",agathion:"PF2E.TraitAgathion",alchemical:"PF2E.TraitAlchemical",angel:"PF2E.TraitAngel",animal:"PF2E.TraitAnimal",anugobu:"PF2E.TraitAnugobu",aquatic:"PF2E.TraitAquatic",archon:"PF2E.TraitArchon",astral:"PF2E.TraitAstral",asura:"PF2E.TraitAsura",azata:"PF2E.TraitAzata",beast:"PF2E.TraitBeast",boggard:"PF2E.TraitBoggard",caligni:"PF2E.TraitCaligni",celestial:"PF2E.TraitCelestial","charau-ka":"PF2E.TraitCharauKa",clockwork:"PF2E.TraitClockwork",construct:"PF2E.TraitConstruct",couatl:"PF2E.TraitCouatl",daemon:"PF2E.TraitDaemon",darvakka:"PF2E.TraitDarvakka",demon:"PF2E.TraitDemon",dero:"PF2E.TraitDero",devil:"PF2E.TraitDevil",dinosaur:"PF2E.TraitDinosaur",div:"PF2E.TraitDiv",dragon:"PF2E.TraitDragon",dream:"PF2E.TraitDream",drow:"PF2E.TraitDrow",duergar:"PF2E.TraitDuergar",duskwalker:"PF2E.TraitDuskwalker",eidolon:"PF2E.TraitEidolon",elemental:"PF2E.TraitElemental",ethereal:"PF2E.TraitEthereal",evocation:"PF2E.TraitEvocation",fiend:"PF2E.TraitFiend",formian:"PF2E.TraitFormian",fungus:"PF2E.TraitFungus",genie:"PF2E.TraitGenie",ghoran:"PF2E.TraitGhoran",ghost:"PF2E.TraitGhost",ghoul:"PF2E.TraitGhoul",ghul:"PF2E.TraitGhul",giant:"PF2E.TraitGiant",golem:"PF2E.TraitGolem",gremlin:"PF2E.TraitGremlin",grioth:"PF2E.TraitGrioth",grippli:"PF2E.TraitGrippli",hag:"PF2E.TraitHag",hantu:"PF2E.TraitHantu",herald:"PF2E.TraitHerald",hryngar:"PF2E.TraitHryngar",humanoid:"PF2E.TraitHumanoid",ifrit:"PF2E.TraitIfrit",ikeshti:"PF2E.TraitIkeshti",illusion:"PF2E.TraitIllusion",incorporeal:"PF2E.TraitIncorporeal",inevitable:"PF2E.TraitInevitable",kami:"PF2E.TraitKami",kovintus:"PF2E.TraitKovintus",light:"PF2E.TraitLight",lilu:"PF2E.TraitLilu",locathah:"PF2E.TraitLocathah",mental:"PF2E.TraitMental",merfolk:"PF2E.TraitMerfolk",mindless:"PF2E.TraitMindless",minion:"PF2E.TraitMinion",monitor:"PF2E.TraitMonitor",morlock:"PF2E.TraitMorlock",mortic:"PF2E.TraitMortic",mummy:"PF2E.TraitMummy",munavri:"PF2E.TraitMunavri",mutant:"PF2E.TraitMutant",nagaji:"PF2E.TraitNagaji",necromancy:"PF2E.TraitNecromancy",nymph:"PF2E.TraitNymph",oni:"PF2E.TraitOni",ooze:"PF2E.TraitOoze",orc:"PF2E.TraitOrc",oread:"PF2E.TraitOread",paaridar:"PF2E.TraitPaaridar",petitioner:"PF2E.TraitPetitioner",phantom:"PF2E.TraitPhantom",poison:"PF2E.TraitPoison",protean:"PF2E.TraitProtean",psychopomp:"PF2E.TraitPsychopomp",qlippoth:"PF2E.TraitQlippoth",rakshasa:"PF2E.TraitRakshasa",reflection:"PF2E.TraitReflection",sahkil:"PF2E.TraitSahkil",samsaran:"PF2E.TraitSamsaran","sea-devil":"PF2E.TraitSeaDevil",serpentfolk:"PF2E.TraitSerpentfolk",seugathi:"PF2E.TraitSeugathi",shabti:"PF2E.TraitShabti",shadow:"PF2E.TraitShadow",shobhad:"PF2E.TraitShobhad",siktempora:"PF2E.TraitSiktempora",skeleton:"PF2E.TraitSkeleton",skelm:"PF2E.TraitSkelm",skulk:"PF2E.TraitSkulk",soulbound:"PF2E.TraitSoulbound",spirit:"PF2E.TraitSpirit",sporeborn:"PF2E.TraitSporeborn",spriggan:"PF2E.TraitSpriggan",stheno:"PF2E.TraitStheno",summoned:"PF2E.TraitSummoned",swarm:"PF2E.TraitSwarm",sylph:"PF2E.TraitSylph",tane:"PF2E.TraitTane",tanggal:"PF2E.TraitTanggal",tengu:"PF2E.TraitTengu",time:"PF2E.TraitTime",titan:"PF2E.TraitTitan",troll:"PF2E.TraitTroll",troop:"PF2E.TraitTroop",undead:"PF2E.TraitUndead",undine:"PF2E.TraitUndine",urdefhan:"PF2E.TraitUrdefhan",vampire:"PF2E.TraitVampire",vanara:"PF2E.TraitVanara",velstrac:"PF2E.TraitVelstrac",vishkanya:"PF2E.TraitVishkanya",wayang:"PF2E.TraitWayang",werecreature:"PF2E.TraitWerecreature",wight:"PF2E.TraitWight","wild-hunt":"PF2E.TraitWildHunt",wraith:"PF2E.TraitWraith",wyrwood:"PF2E.TraitWyrwood",xulgath:"PF2E.TraitXulgath",zombie:"PF2E.TraitZombie"},backgroundTraits={"pervasive-magic":"PF2E.TraitPervasiveMagic"},classTraits={alchemist:"PF2E.TraitAlchemist",barbarian:"PF2E.TraitBarbarian",bard:"PF2E.TraitBard",champion:"PF2E.TraitChampion",cleric:"PF2E.TraitCleric",druid:"PF2E.TraitDruid",fighter:"PF2E.TraitFighter",gunslinger:"PF2E.TraitGunslinger",inventor:"PF2E.TraitInventor",investigator:"PF2E.TraitInvestigator",kineticist:"PF2E.TraitKineticist",magus:"PF2E.TraitMagus",monk:"PF2E.TraitMonk",oracle:"PF2E.TraitOracle",psychic:"PF2E.TraitPsychic",ranger:"PF2E.TraitRanger",rogue:"PF2E.TraitRogue",sorcerer:"PF2E.TraitSorcerer",summoner:"PF2E.TraitSummoner",swashbuckler:"PF2E.TraitSwashbuckler",thaumaturge:"PF2E.TraitThaumaturge",witch:"PF2E.TraitWitch",wizard:"PF2E.TraitWizard"},alignmentTraits={chaotic:"PF2E.TraitChaotic",evil:"PF2E.TraitEvil",good:"PF2E.TraitGood",lawful:"PF2E.TraitLawful"},damageTraits={...alignmentTraits,...elementTraits,...energyDamageTypes,light:"PF2E.TraitLight",magical:"PF2E.TraitMagical",mental:"PF2E.TraitMental",nonlethal:"PF2E.TraitNonlethal",plant:"PF2E.TraitPlant",radiation:"PF2E.TraitRadiation",vitality:"PF2E.TraitVitality",void:"PF2E.TraitVoid"},magicSchools={abjuration:"PF2E.TraitAbjuration",conjuration:"PF2E.TraitConjuration",divination:"PF2E.TraitDivination",enchantment:"PF2E.TraitEnchantment",evocation:"PF2E.TraitEvocation",illusion:"PF2E.TraitIllusion",necromancy:"PF2E.TraitNecromancy",transmutation:"PF2E.TraitTransmutation"},spellTraits={...alignmentTraits,...classTraits,...damageTraits,...elementTraits,...magicSchools,...magicTraditions,amp:"PF2E.TraitAmp",attack:"PF2E.TraitAttack",auditory:"PF2E.TraitAuditory",aura:"PF2E.TraitAura",beast:"PF2E.TraitBeast",cantrip:"PF2E.TraitCantrip",composition:"PF2E.TraitComposition",concentrate:"PF2E.TraitConcentrate",consecration:"PF2E.TraitConsecration",contingency:"PF2E.TraitContingency",curse:"PF2E.TraitCurse",cursebound:"PF2E.TraitCursebound",darkness:"PF2E.TraitDarkness",death:"PF2E.TraitDeath",detection:"PF2E.TraitDetection",disease:"PF2E.TraitDisease",dream:"PF2E.TraitDream",eidolon:"PF2E.TraitEidolon",emotion:"PF2E.TraitEmotion",extradimensional:"PF2E.TraitExtradimensional",fear:"PF2E.TraitFear",fortune:"PF2E.TraitFortune",fungus:"PF2E.TraitFungus",healing:"PF2E.TraitHealing",hex:"PF2E.TraitHex",incapacitation:"PF2E.TraitIncapacitation",incarnate:"PF2E.TraitIncarnate",incorporeal:"PF2E.TraitIncorporeal",inhaled:"PF2E.TraitInhaled",light:"PF2E.TraitLight",linguistic:"PF2E.TraitLinguistic",litany:"PF2E.TraitLitany",metamagic:"PF2E.TraitMetamagic",mindless:"PF2E.TraitMindless",misfortune:"PF2E.TraitMisfortune",morph:"PF2E.TraitMorph",move:"PF2E.TraitMove",nonlethal:"PF2E.TraitNonlethal",olfactory:"PF2E.TraitOlfactory",plant:"PF2E.TraitPlant",poison:"PF2E.TraitPoison",polymorph:"PF2E.TraitPolymorph",possession:"PF2E.TraitPossession",prediction:"PF2E.TraitPrediction",psyche:"PF2E.TraitPsyche",revelation:"PF2E.TraitRevelation",scrying:"PF2E.TraitScrying",shadow:"PF2E.TraitShadow",sleep:"PF2E.TraitSleep",stance:"PF2E.TraitStance",summoned:"PF2E.TraitSummoned",teleportation:"PF2E.TraitTeleportation","true-name":"PF2E.TraitTrueName",visual:"PF2E.TraitVisual"},weaponTraits={...alignmentTraits,...ancestryTraits,...elementTraits,...energyDamageTypes,...magicSchools,...magicTraditions,adjusted:"PF2E.TraitAdjusted",alchemical:"PF2E.TraitAlchemical",agile:"PF2E.TraitAgile",apex:"PF2E.TraitApex",artifact:"PF2E.TraitArtifact",attached:"PF2E.TraitAttached","attached-to-shield":"PF2E.TraitAttachedToShield","attached-to-crossbow-or-firearm":"PF2E.TraitAttachedToCrossbowOrFirearm",auditory:"PF2E.TraitAuditory",backstabber:"PF2E.TraitBackstabber",backswing:"PF2E.TraitBackswing",bomb:"PF2E.TraitBomb",brace:"PF2E.TraitBrace",brutal:"PF2E.TraitBrutal","capacity-2":"PF2E.TraitCapacity2","capacity-3":"PF2E.TraitCapacity3","capacity-4":"PF2E.TraitCapacity4","capacity-5":"PF2E.TraitCapacity5",climbing:"PF2E.TraitClimbing",clockwork:"PF2E.TraitClockwork",cobbled:"PF2E.TraitCobbled",combination:"PF2E.TraitCombination",concealable:"PF2E.TraitConcealable",concussive:"PF2E.TraitConcussive",consumable:"PF2E.TraitConsumable","critical-fusion":"PF2E.TraitCriticalFusion",cursed:"PF2E.TraitCursed","deadly-d4":"PF2E.TraitDeadlyD4","deadly-d6":"PF2E.TraitDeadlyD6","deadly-d8":"PF2E.TraitDeadlyD8","deadly-d10":"PF2E.TraitDeadlyD10","deadly-d12":"PF2E.TraitDeadlyD12",death:"PF2E.TraitDeath",disarm:"PF2E.TraitDisarm",disease:"PF2E.TraitDisease","double-barrel":"PF2E.TraitDoubleBarrel",emotion:"PF2E.TraitEmotion",extradimensional:"PF2E.TraitExtradimensional","fatal-aim-d10":"PF2E.TraitFatalAimD10","fatal-aim-d12":"PF2E.TraitFatalAimD12","fatal-d8":"PF2E.TraitFatalD8","fatal-d10":"PF2E.TraitFatalD10","fatal-d12":"PF2E.TraitFatalD12",fear:"PF2E.TraitFear",finesse:"PF2E.TraitFinesse",forceful:"PF2E.TraitForceful",fortune:"PF2E.TraitFortune","free-hand":"PF2E.TraitFreeHand",fungus:"PF2E.TraitFungus",grapple:"PF2E.TraitGrapple",hampering:"PF2E.TraitHampering",healing:"PF2E.TraitHealing",infused:"PF2E.TraitInfused",inhaled:"PF2E.TraitInhaled",injection:"PF2E.TraitInjection",intelligent:"PF2E.TraitIntelligent",invested:"PF2E.TraitInvested","jousting-d6":"PF2E.TraitJoustingD6",kickback:"PF2E.TraitKickback",light:"PF2E.TraitLight",magical:"PF2E.TraitMagical",mental:"PF2E.TraitMental",modular:"PF2E.TraitModular",monk:"PF2E.TraitMonk",nonlethal:"PF2E.TraitNonlethal",olfactory:"PF2E.TraitOlfactory",parry:"PF2E.TraitParry",plant:"PF2E.TraitPlant",poison:"PF2E.TraitPoison",propulsive:"PF2E.TraitPropulsive","ranged-trip":"PF2E.TraitRangedTrip",razing:"PF2E.TraitRazing",reach:"PF2E.TraitReach",recovery:"PF2E.TraitRecovery",relic:"PF2E.TraitRelic",repeating:"PF2E.TraitRepeating",resonant:"PF2E.TraitResonant",saggorak:"PF2E.TraitSaggorak","scatter-5":"PF2E.TraitScatter5","scatter-10":"PF2E.TraitScatter10","scatter-15":"PF2E.TraitScatter15","scatter-20":"PF2E.TraitScatter20",scrying:"PF2E.TraitScrying",shadow:"PF2E.TraitShadow",shove:"PF2E.TraitShove",splash:"PF2E.TraitSplash",staff:"PF2E.TraitStaff",sweep:"PF2E.TraitSweep",tech:"PF2E.TraitTech",teleportation:"PF2E.TraitTeleportation",tethered:"PF2E.TraitTethered",thrown:"PF2E.TraitThrown","thrown-10":"PF2E.TraitThrown10","thrown-15":"PF2E.TraitThrown15","thrown-20":"PF2E.TraitThrown20","thrown-30":"PF2E.TraitThrown30","thrown-40":"PF2E.TraitThrown40","thrown-60":"PF2E.TraitThrown60","thrown-80":"PF2E.TraitThrown80","thrown-100":"PF2E.TraitThrown100","thrown-200":"PF2E.TraitThrown200",training:"PF2E.TraitTraining",trip:"PF2E.TraitTrip",twin:"PF2E.TraitTwin","two-hand-d6":"PF2E.TraitTwoHandD6","two-hand-d8":"PF2E.TraitTwoHandD8","two-hand-d10":"PF2E.TraitTwoHandD10","two-hand-d12":"PF2E.TraitTwoHandD12",unarmed:"PF2E.TraitUnarmed",vehicular:"PF2E.TraitVehicular","versatile-acid":"PF2E.TraitVersatileAcid","versatile-b":"PF2E.TraitVersatileB","versatile-chaotic":"PF2E.TraitVersatileChaotic","versatile-cold":"PF2E.TraitVersatileCold","versatile-electricity":"PF2E.TraitVersatileElectricity","versatile-evil":"PF2E.TraitVersatileEvil","versatile-fire":"PF2E.TraitVersatileFire","versatile-force":"PF2E.TraitVersatileForce","versatile-good":"PF2E.TraitVersatileGood","versatile-lawful":"PF2E.TraitVersatileLawful","versatile-p":"PF2E.TraitVersatileP","versatile-poison":"PF2E.TraitVersatilePoison","versatile-s":"PF2E.TraitVersatileS","versatile-sonic":"PF2E.TraitVersatileSonic","versatile-vitality":"PF2E.TraitVersatileVitality","versatile-void":"PF2E.TraitVersatileVoid","volley-20":"PF2E.TraitVolley20","volley-30":"PF2E.TraitVolley30","volley-50":"PF2E.TraitVolley50"},preciousMaterials={abysium:"PF2E.PreciousMaterialAbysium",adamantine:"PF2E.PreciousMaterialAdamantine","cold-iron":"PF2E.PreciousMaterialColdIron",darkwood:"PF2E.PreciousMaterialDarkwood",djezet:"PF2E.PreciousMaterialDjezet",dragonhide:"PF2E.PreciousMaterialDragonhide","grisantian-pelt":"PF2E.PreciousMaterialGrisantianPelt",inubrix:"PF2E.PreciousMaterialInubrix","keep-stone":"PF2E.PreciousMaterialKeepStone",mithral:"PF2E.PreciousMaterialMithral",noqual:"PF2E.PreciousMaterialNoqual",orichalcum:"PF2E.PreciousMaterialOrichalcum",peachwood:"PF2E.PreciousMaterialPeachwood",siccatite:"PF2E.PreciousMaterialSiccatite",silver:"PF2E.PreciousMaterialSilver",sisterstone:"PF2E.PreciousMaterialSisterstone","sisterstone-dusk":"PF2E.PreciousMaterialSisterstoneDusk","sisterstone-scarlet":"PF2E.PreciousMaterialSisterstoneScarlet","sovereign-steel":"PF2E.PreciousMaterialSovereignSteel",warpglass:"PF2E.PreciousMaterialWarpglass"},otherArmorTags={shoddy:"PF2E.Item.Physical.OtherTag.Shoddy"},otherConsumableTags={herbal:"PF2E.Item.Physical.OtherTag.Herbal"},otherWeaponTags={crossbow:"PF2E.Weapon.Base.crossbow",improvised:"PF2E.Item.Physical.OtherTag.Improvised",shoddy:"PF2E.Item.Physical.OtherTag.Shoddy"},rangeTraits=mapToObj(RANGE_TRAITS,trait=>[trait,`PF2E.Trait${sluggify(trait,{camel:"bactrian"})}`]),npcAttackTraits={...weaponTraits,...preciousMaterials,...rangeTraits,curse:"PF2E.TraitCurse","deadly-2d8":"PF2E.TraitDeadly2D8","deadly-3d8":"PF2E.TraitDeadly3D8","deadly-4d8":"PF2E.TraitDeadly4D8","deadly-2d10":"PF2E.TraitDeadly2D10","deadly-3d10":"PF2E.TraitDeadly3D10","deadly-4d10":"PF2E.TraitDeadly4D10","deadly-2d12":"PF2E.TraitDeadly2D12","deadly-3d12":"PF2E.TraitDeadly3D12","deadly-4d12":"PF2E.TraitDeadly4D12",incorporeal:"PF2E.TraitIncorporeal",radiation:"PF2E.TraitRadiation","reach-0":"PF2E.TraitReach0","reach-10":"PF2E.TraitReach10","reach-15":"PF2E.TraitReach15","reach-20":"PF2E.TraitReach20","reach-25":"PF2E.TraitReach25","reach-30":"PF2E.TraitReach30","reach-40":"PF2E.TraitReach40","reach-50":"PF2E.TraitReach50","reach-60":"PF2E.TraitReach60","reach-100":"PF2E.TraitReach100","reach-120":"PF2E.TraitReach120","reach-200":"PF2E.TraitReach200","reach-1000":"PF2E.TraitReach1000","reload-0":"PF2E.TraitReload0","reload-1":"PF2E.TraitReload1","reload-2":"PF2E.TraitReload2","reload-1-min":"PF2E.TraitReload1Min"},featTraits={...ancestryTraits,...classTraits,...damageTraits,...magicSchools,...magicTraditions,...spellTraits,additive1:"PF2E.TraitAdditive1",additive2:"PF2E.TraitAdditive2",additive3:"PF2E.TraitAdditive3",aftermath:"PF2E.TraitAftermath",alchemical:"PF2E.TraitAlchemical",archetype:"PF2E.TraitArchetype",artifact:"PF2E.TraitArtifact",auditory:"PF2E.TraitAuditory",aura:"PF2E.TraitAura",circus:"PF2E.TraitCircus",class:"PF2E.Class",composite:"PF2E.TraitComposite",concentrate:"PF2E.TraitConcentrate",dedication:"PF2E.TraitDedication",detection:"PF2E.TraitDetection",deviant:"PF2E.TraitDeviant",downtime:"PF2E.TraitDowntime",emotion:"PF2E.TraitEmotion",evolution:"PF2E.TraitEvolution",esoterica:"PF2E.TraitEsoterica",exploration:"PF2E.TraitExploration",fear:"PF2E.TraitFear",finisher:"PF2E.TraitFinisher",flourish:"PF2E.TraitFlourish",fortune:"PF2E.TraitFortune",general:"PF2E.TraitGeneral",impulse:"PF2E.TraitImpulse",infusion:"PF2E.TraitInfusion",injury:"PF2E.TraitInjury",lineage:"PF2E.TraitLineage",manipulate:"PF2E.TraitManipulate",metamagic:"PF2E.TraitMetamagic",mindshift:"PF2E.TraitMindshift",modification:"PF2E.TraitModification",move:"PF2E.TraitMove",multiclass:"PF2E.TraitMulticlass",oath:"PF2E.TraitOath",olfactory:"PF2E.TraitOlfactory",open:"PF2E.TraitOpen",overflow:"PF2E.TraitOverflow","pervasive-magic":"PF2E.TraitPervasiveMagic",poison:"PF2E.TraitPoison",press:"PF2E.TraitPress",rage:"PF2E.TraitRage",reckless:"PF2E.TraitReckless",reflection:"PF2E.TraitReflection",secret:"PF2E.TraitSecret",skill:"PF2E.TraitSkill",social:"PF2E.TraitSocial",spellshot:"PF2E.TraitSpellshot",stamina:"PF2E.TraitStamina",stance:"PF2E.TraitStance",tandem:"PF2E.TraitTandem",time:"PF2E.TraitTime","true-name":"PF2E.TraitTrueName",unstable:"PF2E.TraitUnstable",vigilante:"PF2E.TraitVigilante",virulent:"PF2E.TraitVirulent",vitality:"PF2E.TraitVitality",void:"PF2E.TraitVoid"},consumableTraits={...damageTraits,...elementTraits,...magicSchools,...magicTraditions,additive1:"PF2E.TraitAdditive1",additive2:"PF2E.TraitAdditive2",additive3:"PF2E.TraitAdditive3",alchemical:"PF2E.TraitAlchemical",attack:"PF2E.TraitAttack",auditory:"PF2E.TraitAuditory",aura:"PF2E.TraitAura","bottled-breath":"PF2E.TraitBottledBreath",catalyst:"PF2E.TraitCatalyst",clockwork:"PF2E.TraitClockwork",consumable:"PF2E.TraitConsumable",contact:"PF2E.TraitContact",curse:"PF2E.TraitCurse",cursed:"PF2E.TraitCursed",drug:"PF2E.TraitDrug",elixir:"PF2E.TraitElixir",emotion:"PF2E.TraitEmotion",expandable:"PF2E.TraitExpandable",fear:"PF2E.TraitFear",fey:"PF2E.TraitFey",fortune:"PF2E.TraitFortune",fulu:"PF2E.TraitFulu",gadget:"PF2E.TraitGadget",healing:"PF2E.TraitHealing",incapacitation:"PF2E.TraitIncapacitation",infused:"PF2E.TraitInfused",ingested:"PF2E.TraitIngested",inhaled:"PF2E.TraitInhaled",injury:"PF2E.TraitInjury",kobold:"PF2E.TraitKobold",light:"PF2E.TraitLight",linguistic:"PF2E.TraitLinguistic",lozenge:"PF2E.TraitLozenge",magical:"PF2E.TraitMagical",mechanical:"PF2E.TraitMechanical",misfortune:"PF2E.TraitMisfortune",missive:"PF2E.TraitMissive",morph:"PF2E.TraitMorph",mutagen:"PF2E.TraitMutagen",oil:"PF2E.TraitOil",olfactory:"PF2E.TraitOlfactory",poison:"PF2E.TraitPoison",polymorph:"PF2E.TraitPolymorph",possession:"PF2E.TraitPossession",potion:"PF2E.TraitPotion",precious:"PF2E.TraitPrecious",processed:"PF2E.TraitProcessed",scroll:"PF2E.TraitScroll",scrying:"PF2E.TraitScrying",sleep:"PF2E.TraitSleep",snare:"PF2E.TraitSnare",spellgun:"PF2E.TraitSpellgun",splash:"PF2E.TraitSplash",structure:"PF2E.TraitStructure",talisman:"PF2E.TraitTalisman",teleportation:"PF2E.TraitTeleportation",trap:"PF2E.TraitTrap",virulent:"PF2E.TraitVirulent",visual:"PF2E.TraitVisual",wand:"PF2E.TraitWand"},actionTraits={...featTraits,...consumableTraits,...spellTraits,...pick$1(weaponTraits,["agile","propulsive","backswing","forceful","reach","sweep","thrown","volley-20","volley-30","volley-50"]),summon:"PF2E.TraitSummon"},hazardTraits={...damageTraits,...magicSchools,...magicTraditions,aberration:"PF2E.TraitAberration",alchemical:"PF2E.TraitAlchemical",animal:"PF2E.TraitAnimal",aquatic:"PF2E.TraitAquatic",auditory:"PF2E.TraitAuditory",beast:"PF2E.TraitBeast",clockwork:"PF2E.TraitClockwork",consumable:"PF2E.TraitConsumable",curse:"PF2E.TraitCurse",environmental:"PF2E.TraitEnvironmental",fungus:"PF2E.TraitFungus",haunt:"PF2E.TraitHaunt",inhaled:"PF2E.TraitInhaled",kaiju:"PF2E.TraitKaiju",magical:"PF2E.TraitMagical",mechanical:"PF2E.TraitMechanical",poison:"PF2E.TraitPoison",polymorph:"PF2E.TraitPolymorph",shadow:"PF2E.TraitShadow",steam:"PF2E.TraitSteam",summoned:"PF2E.TraitSummoned",technological:"PF2E.TraitTechnological",teleportation:"PF2E.TraitTeleportation",trap:"PF2E.TraitTrap",virulent:"PF2E.TraitVirulent",visual:"PF2E.TraitVisual"},vehicleTraits={...magicSchools,artifact:"PF2E.TraitArtifact",clockwork:"PF2E.TraitClockwork",magical:"PF2E.TraitMagical",teleportation:"PF2E.TraitTeleportation"},equipmentTraits={...alignmentTraits,...ancestryTraits,...elementTraits,...energyDamageTypes,...magicSchools,...magicTraditions,additive0:"PF2E.TraitAdditive0",additive1:"PF2E.TraitAdditive1",adjusted:"PF2E.TraitAdjusted",adjustment:"PF2E.TraitAdjustment",alchemical:"PF2E.TraitAlchemical",apex:"PF2E.TraitApex",artifact:"PF2E.TraitArtifact",auditory:"PF2E.TraitAuditory",aura:"PF2E.TraitAura",barding:"PF2E.TraitBarding",censer:"PF2E.TraitCenser",clockwork:"PF2E.TraitClockwork",coda:"PF2E.TraitCoda",companion:"PF2E.TraitCompanion",contract:"PF2E.TraitContract",consecration:"PF2E.TraitConsecration",cursed:"PF2E.TraitCursed",darkness:"PF2E.TraitDarkness",death:"PF2E.TraitDeath",detection:"PF2E.TraitDetection",eidolon:"PF2E.TraitEidolon",emotion:"PF2E.TraitEmotion",expandable:"PF2E.TraitExpandable",extradimensional:"PF2E.TraitExtradimensional",fear:"PF2E.TraitFear",figurehead:"PF2E.TraitFigurehead",focused:"PF2E.TraitFocused",fortune:"PF2E.TraitFortune",fulu:"PF2E.TraitFulu",gadget:"PF2E.TraitGadget",grimoire:"PF2E.TraitGrimoire","harrow-court":"PF2E.TraitHarrowCourt",healing:"PF2E.TraitHealing",incapacitation:"PF2E.TraitIncapacitation",incorporeal:"PF2E.TraitIncorporeal",infused:"PF2E.TraitInfused",intelligent:"PF2E.TraitIntelligent",invested:"PF2E.TraitInvested",light:"PF2E.TraitLight",magical:"PF2E.TraitMagical",mechanical:"PF2E.TraitMechanical",mental:"PF2E.TraitMental",misfortune:"PF2E.TraitMisfortune",morph:"PF2E.TraitMorph",mounted:"PF2E.TraitMounted",nonlethal:"PF2E.TraitNonlethal",plant:"PF2E.TraitPlant",poison:"PF2E.TraitPoison",polymorph:"PF2E.TraitPolymorph",portable:"PF2E.TraitPortable",precious:"PF2E.TraitPrecious",prediction:"PF2E.TraitPrediction",relic:"PF2E.TraitRelic",revelation:"PF2E.TraitRevelation",saggorak:"PF2E.TraitSaggorak",scrying:"PF2E.TraitScrying",shadow:"PF2E.TraitShadow",sleep:"PF2E.TraitSleep",spellgun:"PF2E.TraitSpellgun",spellheart:"PF2E.TraitSpellheart",staff:"PF2E.TraitStaff",steam:"PF2E.TraitSteam",structure:"PF2E.TraitStructure",tattoo:"PF2E.TraitTattoo",teleportation:"PF2E.TraitTeleportation",visual:"PF2E.TraitVisual",wand:"PF2E.TraitWand"},shieldTraits={"deflecting-bludgeoning":"PF2E.TraitDeflectingBludgeoning","deflecting-physical-ranged":"PF2E.TraitDeflectingPhysicalRanged","deflecting-piercing":"PF2E.TraitDeflectingPiercing","deflecting-slashing":"PF2E.TraitDeflectingSlashing",foldaway:"PF2E.TraitFoldaway",harnessed:"PF2E.TraitHarnessed","hefty-14":"PF2E.TraitHefty14",inscribed:"PF2E.TraitInscribed","integrated-1d6-b":"PF2E.TraitIntegrated1d6B","integrated-1d6-p":"PF2E.TraitIntegrated1d6P","integrated-1d6-s":"PF2E.TraitIntegrated1d6S","integrated-1d6-s-versatile-p":"PF2E.TraitIntegrated1d6SVersatileP","launching-dart":"PF2E.TraitLaunching","shield-throw-20":"PF2E.TraitShieldThrow20","shield-throw-30":"PF2E.TraitShieldThrow30"},armorTraits={...alignmentTraits,...elementTraits,...magicSchools,...magicTraditions,...shieldTraits,adjusted:"PF2E.TraitAdjusted",alchemical:"PF2E.TraitAlchemical",apex:"PF2E.TraitApex",aquadynamic:"PF2E.TraitAquadynamic",artifact:"PF2E.TraitArtifact",auditory:"PF2E.TraitAuditory",aura:"PF2E.TraitAura",barding:"PF2E.TraitBarding",bulwark:"PF2E.TraitBulwark",clockwork:"PF2E.TraitClockwork",comfort:"PF2E.TraitComfort",companion:"PF2E.TraitCompanion",cursed:"PF2E.TraitCursed","entrench-melee":"PF2E.TraitEntrenchMelee","entrench-ranged":"PF2E.TraitEntrenchRanged",extradimensional:"PF2E.TraitExtradimensional",focused:"PF2E.TraitFocused",force:"PF2E.TraitForce",flexible:"PF2E.TraitFlexible",healing:"PF2E.TraitHealing",hindering:"PF2E.TraitHindering",inscribed:"PF2E.TraitInscribed",intelligent:"PF2E.TraitIntelligent",invested:"PF2E.TraitInvested",laminar:"PF2E.TraitLaminar",light:"PF2E.TraitLight",magical:"PF2E.TraitMagical",noisy:"PF2E.TraitNoisy",plant:"PF2E.TraitPlant",ponderous:"PF2E.TraitPonderous"},rangeDescriptions=mapToObj(RANGE_TRAITS,trait=>[trait,"PF2E.TraitDescriptionRange"]),preciousMaterialDescriptions={abysium:"PF2E.PreciousMaterialAbysiumDescription",adamantine:"PF2E.PreciousMaterialAdamantineDescription","cold-iron":"PF2E.PreciousMaterialColdIronDescription",darkwood:"PF2E.PreciousMaterialDarkwoodDescription",djezet:"PF2E.PreciousMaterialDjezetDescription",dragonhide:"PF2E.PreciousMaterialDragonhideDescription","grisantian-pelt":"PF2E.PreciousMaterialGrisantianPeltDescription",inubrix:"PF2E.PreciousMaterialInubrixDescription",mithral:"PF2E.PreciousMaterialMithralDescription",noqual:"PF2E.PreciousMaterialNoqualDescription",orichalcum:"PF2E.PreciousMaterialOrichalcumDescription",siccatite:"PF2E.PreciousMaterialSiccatiteDescription",silver:"PF2E.PreciousMaterialSilverDescription",sisterstone:"PF2E.PreciousMaterialSisterstoneDescription","sisterstone-dusk":"PF2E.PreciousMaterialSisterstoneDescription","sisterstone-scarlet":"PF2E.PreciousMaterialSisterstoneDescription","sovereign-steel":"PF2E.PreciousMaterialSovereignSteelDescription",warpglass:"PF2E.PreciousMaterialWarpglassDescription"},traitDescriptions={aasimar:"PF2E.TraitDescriptionAasimar",aberration:"PF2E.TraitDescriptionAberration",abjuration:"PF2E.TraitDescriptionAbjuration",acid:"PF2E.TraitDescriptionAcid",additive0:"PF2E.TraitDescriptionAdditive",additive1:"PF2E.TraitDescriptionAdditive",additive2:"PF2E.TraitDescriptionAdditive",additive3:"PF2E.TraitDescriptionAdditive",adjusted:"PF2E.TraitDescriptionAdjusted",adjustment:"PF2E.TraitDescriptionAdjustment",aeon:"PF2E.TraitDescriptionAeon",aesir:"PF2E.TraitDescriptionAesir",aftermath:"PF2E.TraitDescriptionAftermath",agathion:"PF2E.TraitDescriptionAgathion",agile:"PF2E.TraitDescriptionAgile",air:"PF2E.TraitDescriptionAir",alchemical:"PF2E.TraitDescriptionAlchemical",alchemist:"PF2E.TraitDescriptionAlchemist",amphibious:"PF2E.TraitDescriptionAmphibious",anadi:"PF2E.TraitDescriptionAnadi",android:"PF2E.TraitDescriptionAndroid",apex:"PF2E.TraitDescriptionApex",aphorite:"PF2E.TraitDescriptionAphorite",aquadynamic:"PF2E.TraitDescriptionAquadynamic",arcane:"PF2E.TraitDescriptionArcane",archetype:"PF2E.TraitDescriptionArchetype",ardande:"PF2E.TraitDescriptionArdande",artifact:"PF2E.TraitDescriptionArtifact",attached:"PF2E.TraitDescriptionAttached","attached-to-crossbow-or-firearm":"PF2E.TraitDescriptionAttached","attached-to-shield":"PF2E.TraitDescriptionAttached",attack:"PF2E.TraitDescriptionAttack",auditory:"PF2E.TraitDescriptionAuditory",aura:"PF2E.TraitDescriptionAura",automaton:"PF2E.TraitDescriptionAutomaton",azarketi:"PF2E.TraitDescriptionAzarketi",backstabber:"PF2E.TraitDescriptionBackstabber",backswing:"PF2E.TraitDescriptionBackswing",barbarian:"PF2E.TraitDescriptionBarbarian",bard:"PF2E.TraitDescriptionBard",beastkin:"PF2E.TraitDescriptionBeastkin",bomb:"PF2E.TraitDescriptionBomb","bottled-breath":"PF2E.TraitDescriptionBottledBreath",brace:"PF2E.TraitDescriptionBrace",brutal:"PF2E.TraitDescriptionBrutal",bulwark:"PF2E.TraitDescriptionBulwark",cantrip:"PF2E.TraitDescriptionCantrip","capacity-2":"PF2E.TraitDescriptionCapacity","capacity-3":"PF2E.TraitDescriptionCapacity","capacity-4":"PF2E.TraitDescriptionCapacity","capacity-5":"PF2E.TraitDescriptionCapacity",catalyst:"PF2E.TraitDescriptionCatalyst",catfolk:"PF2E.TraitDescriptionCatfolk",censer:"PF2E.TraitDescriptionCenser",champion:"PF2E.TraitDescriptionChampion",changeling:"PF2E.TraitDescriptionChangeling",chaotic:"PF2E.TraitDescriptionChaotic",class:"PF2E.TraitDescriptionClass",cleric:"PF2E.TraitDescriptionCleric",climbing:"PF2E.TraitDescriptionClimbing",clockwork:"PF2E.TraitDescriptionClockwork",cobbled:"PF2E.TraitDescriptionCobbled",coda:"PF2E.TraitDescriptionCoda",cold:"PF2E.TraitDescriptionCold",combination:"PF2E.TraitDescriptionCombination",comfort:"PF2E.TraitDescriptionComfort",common:"PF2E.TraitDescriptionCommon",companion:"PF2E.TraitDescriptionCompanion",complex:"PF2E.TraitDescriptionComplex",composite:"PF2E.TraitDescriptionComposite",composition:"PF2E.TraitDescriptionComposition",concealable:"PF2E.TraitDescriptionConcealable",concentrate:"PF2E.TraitDescriptionConcentrate",concussive:"PF2E.TraitDescriptionConcussive",conjuration:"PF2E.TraitDescriptionConjuration",conrasu:"PF2E.TraitDescriptionConrasu",consecration:"PF2E.TraitDescriptionConsecration",consumable:"PF2E.TraitDescriptionConsumable",contact:"PF2E.TraitDescriptionContact",contingency:"PF2E.TraitDescriptionContingency",contract:"PF2E.TraitDescriptionContract","critical-fusion":"PF2E.TraitDescriptionCriticalFusion",curse:"PF2E.TraitDescriptionCurse",cursebound:"PF2E.TraitDescriptionCursebound",cursed:"PF2E.TraitDescriptionCursed",darkness:"PF2E.TraitDescriptionDarkness",darvakka:"PF2E.TraitDescriptionDarvakka","deadly-2d10":"PF2E.TraitDescriptionDeadly","deadly-2d12":"PF2E.TraitDescriptionDeadly","deadly-2d8":"PF2E.TraitDescriptionDeadly","deadly-3d10":"PF2E.TraitDescriptionDeadly","deadly-3d12":"PF2E.TraitDescriptionDeadly","deadly-3d8":"PF2E.TraitDescriptionDeadly","deadly-4d10":"PF2E.TraitDescriptionDeadly","deadly-4d12":"PF2E.TraitDescriptionDeadly","deadly-4d8":"PF2E.TraitDescriptionDeadly","deadly-d10":"PF2E.TraitDescriptionDeadly","deadly-d12":"PF2E.TraitDescriptionDeadly","deadly-d6":"PF2E.TraitDescriptionDeadly","deadly-d8":"PF2E.TraitDescriptionDeadly","deadly-d4":"PF2E.TraitDescriptionDeadly",death:"PF2E.TraitDescriptionDeath","deflecting-bludgeoning":"PF2E.TraitDescriptionDeflecting","deflecting-physical-ranged":"PF2E.TraitDescriptionDeflecting","deflecting-slashing":"PF2E.TraitDescriptionDeflecting",dedication:"PF2E.TraitDescriptionDedication",detection:"PF2E.TraitDescriptionDetection",deviant:"PF2E.TraitDescriptionDeviant",dhampir:"PF2E.TraitDescriptionDhampir",disarm:"PF2E.TraitDescriptionDisarm",disease:"PF2E.TraitDescriptionDisease",divination:"PF2E.TraitDescriptionDivination",divine:"PF2E.TraitDescriptionDivine","double-barrel":"PF2E.TraitDescriptionDoubleBarrel",downtime:"PF2E.TraitDescriptionDowntime",drug:"PF2E.TraitDescriptionDrug",druid:"PF2E.TraitDescriptionDruid",duskwalker:"PF2E.TraitDescriptionDuskwalker",dwarf:"PF2E.TraitDescriptionDwarf",earth:"PF2E.TraitDescriptionEarth",eidolon:"PF2E.TraitDescriptionEidolon",electricity:"PF2E.TraitDescriptionElectricity",elf:"PF2E.TraitDescriptionElf",elixir:"PF2E.TraitDescriptionElixir",emotion:"PF2E.TraitDescriptionEmotion",enchantment:"PF2E.TraitDescriptionEnchantment","entrench-melee":"PF2E.TraitDescriptionEntrench","entrench-ranged":"PF2E.TraitDescriptionEntrench",environment:"PF2E.TraitDescriptionEnvironment",esoterica:"PF2E.TraitDescriptionEsoterica",evil:"PF2E.TraitDescriptionEvil",evocation:"PF2E.TraitDescriptionEvocation",evolution:"PF2E.TraitDescriptionEvolution",expandable:"PF2E.TraitDescriptionExpandable",exploration:"PF2E.TraitDescriptionExploration",extradimensional:"PF2E.TraitDescriptionExtradimensional","fatal-aim-d10":"PF2E.TraitDescriptionFatalAim","fatal-aim-d12":"PF2E.TraitDescriptionFatalAim","fatal-d10":"PF2E.TraitDescriptionFatal","fatal-d12":"PF2E.TraitDescriptionFatal","fatal-d8":"PF2E.TraitDescriptionFatal",fear:"PF2E.TraitDescriptionFear",fetchling:"PF2E.TraitDescriptionFetchling",fey:"PF2E.TraitDescriptionFey",fighter:"PF2E.TraitDescriptionFighter",figurehead:"PF2E.TraitDescriptionFigurehead",finesse:"PF2E.TraitDescriptionFinesse",finisher:"PF2E.TraitDescriptionFinisher",fire:"PF2E.TraitDescriptionFire",fleshwarp:"PF2E.TraitDescriptionFleshwarp",flexible:"PF2E.TraitDescriptionFlexible",flourish:"PF2E.TraitDescriptionFlourish",focused:"PF2E.TraitDescriptionFocused",foldaway:"PF2E.TraitDescriptionFoldaway",force:"PF2E.TraitDescriptionForce",forceful:"PF2E.TraitDescriptionForceful",fortune:"PF2E.TraitDescriptionFortune","free-hand":"PF2E.TraitDescriptionFreeHand",fulu:"PF2E.TraitDescriptionFulu",fungus:"PF2E.TraitDescriptionFungus",gadget:"PF2E.TraitDescriptionGadget",ganzi:"PF2E.TraitDescriptionGanzi",general:"PF2E.TraitDescriptionGeneral",genie:"PF2E.TraitDescriptionGenie",geniekin:"PF2E.TraitDescriptionGeniekin",ghoran:"PF2E.TraitDescriptionGhoran",ghul:"PF2E.TraitDescriptionGhul",gnoll:"PF2E.TraitDescriptionGnoll",gnome:"PF2E.TraitDescriptionGnome",goblin:"PF2E.TraitDescriptionGoblin",goloma:"PF2E.TraitDescriptionGoloma",good:"PF2E.TraitDescriptionGood",grapple:"PF2E.TraitDescriptionGrapple",grimoire:"PF2E.TraitDescriptionGrimoire",grippli:"PF2E.TraitDescriptionGrippli",gunslinger:"PF2E.TraitDescriptionGunslinger",halfling:"PF2E.TraitDescriptionHalfling","half-elf":"PF2E.TraitDescriptionHalfElf","half-orc":"PF2E.TraitDescriptionHalfOrc","jousting-d6":"PF2E.TraitDescriptionJousting",hampering:"PF2E.TraitDescriptionHampering",harnessed:"PF2E.TraitDescriptionHarnessed",haunt:"PF2E.TraitDescriptionHaunt",healing:"PF2E.TraitDescriptionHealing","hefty-14":"PF2E.TraitDescriptionHefty",hex:"PF2E.TraitDescriptionHex",hindering:"PF2E.TraitDescriptionHindering",hobgoblin:"PF2E.TraitDescriptionHobgoblin",human:"PF2E.TraitDescriptionHuman",humanoid:"PF2E.TraitDescriptionHumanoid",ifrit:"PF2E.TraitDescriptionIfrit",illusion:"PF2E.TraitDescriptionIllusion",impulse:"PF2E.TraitDescriptionImpulse",incapacitation:"PF2E.TraitDescriptionIncapacitation",incarnate:"PF2E.TraitDescriptionIncarnate",incorporeal:"PF2E.TraitDescriptionIncorporeal",infused:"PF2E.TraitDescriptionInfused",infusion:"PF2E.TraitDescriptionInfusion",ingested:"PF2E.TraitDescriptionIngested",inhaled:"PF2E.TraitDescriptionInhaled",injection:"PF2E.TraitDescriptionInjection",injury:"PF2E.TraitDescriptionInjury",inscribed:"PF2E.TraitDescriptionInscribed","integrated-1d6-b":"PF2E.TraitDescriptionIntegrated","integrated-1d6-p":"PF2E.TraitDescriptionIntegrated","integrated-1d6-s":"PF2E.TraitDescriptionIntegrated","integrated-1d6-s-versatile-p":"PF2E.TraitDescriptionIntegrated",intelligent:"PF2E.TraitDescriptionIntelligent",inventor:"PF2E.TraitDescriptionInventor",invested:"PF2E.TraitDescriptionInvested",investigator:"PF2E.TraitDescriptionInvestigator",kashrishi:"PF2E.TraitDescriptionKashrishi","keep-stone":"PF2E.PreciousMaterialKeepStoneDescription",kickback:"PF2E.TraitDescriptionKickback",kineticist:"PF2E.TraitDescriptionKineticist",kitsune:"PF2E.TraitDescriptionKitsune",kobold:"PF2E.TraitDescriptionKobold",laminar:"PF2E.TraitDescriptionLaminar","launching-dart":"PF2E.TraitDescriptionLaunching",lawful:"PF2E.TraitDescriptionLawful",leshy:"PF2E.TraitDescriptionLeshy",light:"PF2E.TraitDescriptionLight",linguistic:"PF2E.TraitDescriptionLinguistic",litany:"PF2E.TraitDescriptionLitany",lizardfolk:"PF2E.TraitDescriptionLizardfolk",lozenge:"PF2E.TraitDescriptionLozenge",magical:"PF2E.TraitDescriptionMagical",magus:"PF2E.TraitDescriptionMagus",manipulate:"PF2E.TraitDescriptionManipulate",mechanical:"PF2E.TraitDescriptionMechanical",mental:"PF2E.TraitDescriptionMental",metal:"PF2E.TraitDescriptionMetal",metamagic:"PF2E.TraitDescriptionMetamagic",mindless:"PF2E.TraitDescriptionMindless",mindshift:"PF2E.TraitDescriptionMindshift",minion:"PF2E.TraitDescriptionMinion",misfortune:"PF2E.TraitDescriptionMisfortune",missive:"PF2E.TraitDescriptionMissive",modification:"PF2E.TraitDescriptionModification",modular:"PF2E.TraitDescriptionModular",monk:"PF2E.TraitDescriptionMonk",morph:"PF2E.TraitDescriptionMorph",mounted:"PF2E.TraitDescriptionMounted",move:"PF2E.TraitDescriptionMove",multiclass:"PF2E.TraitDescriptionMulticlass",mutagen:"PF2E.TraitDescriptionMutagen",nagaji:"PF2E.TraitDescriptionNagaji",necromancy:"PF2E.TraitDescriptionNecromancy",noisy:"PF2E.TraitDescriptionNoisy",nonlethal:"PF2E.TraitDescriptionNonlethal",oath:"PF2E.TraitDescriptionOath",occult:"PF2E.TraitDescriptionOccult",oil:"PF2E.TraitDescriptionOil",olfactory:"PF2E.TraitDescriptionOlfactory",open:"PF2E.TraitDescriptionOpen",oracle:"PF2E.TraitDescriptionOracle",orc:"PF2E.TraitDescriptionOrc",oread:"PF2E.TraitDescriptionOread",overflow:"PF2E.TraitDescriptionOverflow",parry:"PF2E.TraitDescriptionParry",peachwood:"PF2E.PreciousMaterialPeachwoodDescription",plant:"PF2E.TraitDescriptionPlant",poison:"PF2E.TraitDescriptionPoison",polymorph:"PF2E.TraitDescriptionPolymorph",ponderous:"PF2E.TraitDescriptionPonderous",poppet:"PF2E.TraitDescriptionPoppet",portable:"PF2E.TraitDescriptionPortable",possession:"PF2E.TraitDescriptionPossession",potion:"PF2E.TraitDescriptionPotion",precious:"PF2E.TraitDescriptionPrecious",prediction:"PF2E.TraitDescriptionPrediction",press:"PF2E.TraitDescriptionPress",primal:"PF2E.TraitDescriptionPrimal",propulsive:"PF2E.TraitDescriptionPropulsive",psyche:"PF2E.TraitDescriptionPsyche",psychic:"PF2E.TraitDescriptionPsychic",radiation:"PF2E.TraitDescriptionRadiation",rage:"PF2E.TraitDescriptionRage",ranger:"PF2E.TraitDescriptionRanger",...rangeDescriptions,"ranged-trip":"PF2E.TraitDescriptionRangedTrip",rare:"PF2E.TraitDescriptionRare",ratfolk:"PF2E.TraitDescriptionRatfolk",razing:"PF2E.TraitDescriptionRazing",reach:"PF2E.TraitDescriptionReach","reach-0":"PF2E.TraitDescriptionReach","reach-10":"PF2E.TraitDescriptionReach","reach-100":"PF2E.TraitDescriptionReach","reach-120":"PF2E.TraitDescriptionReach","reach-1000":"PF2E.TraitDescriptionReach","reach-15":"PF2E.TraitDescriptionReach","reach-20":"PF2E.TraitDescriptionReach","reach-200":"PF2E.TraitDescriptionReach","reach-25":"PF2E.TraitDescriptionReach","reach-30":"PF2E.TraitDescriptionReach","reach-40":"PF2E.TraitDescriptionReach","reach-50":"PF2E.TraitDescriptionReach","reach-60":"PF2E.TraitDescriptionReach",recovery:"PF2E.TraitDescriptionRecovery",reflection:"PF2E.TraitDescriptionReflection",relic:"PF2E.TraitDescriptionRelic",reload:"PF2E.TraitDescriptionReload","reload-0":"PF2E.TraitDescriptionReload","reload-1":"PF2E.TraitDescriptionReload","reload-1-min":"PF2E.TraitDescriptionReload","reload-2":"PF2E.TraitDescriptionReload",repeating:"PF2E.TraitDescriptionRepeating",resonant:"PF2E.TraitDescriptionResonant",revelation:"PF2E.TraitDescriptionRevelation",rogue:"PF2E.TraitDescriptionRogue",saggorak:"PF2E.TraitDescriptionSaggorak","scatter-10":"PF2E.TraitDescriptionScatter","scatter-15":"PF2E.TraitDescriptionScatter","scatter-20":"PF2E.TraitDescriptionScatter","scatter-5":"PF2E.TraitDescriptionScatter",scroll:"PF2E.TraitDescriptionScroll",scrying:"PF2E.TraitDescriptionScrying",secret:"PF2E.TraitDescriptionSecret",shadow:"PF2E.TraitDescriptionShadow","shield-throw-20":"PF2E.TraitDescriptionShieldThrow","shield-throw-30":"PF2E.TraitDescriptionShieldThrow",shisk:"PF2E.TraitDescriptionShisk",shoony:"PF2E.TraitDescriptionShoony",shove:"PF2E.TraitDescriptionShove",skeleton:"PF2E.TraitDescriptionSkeleton",skill:"PF2E.TraitDescriptionSkill",sleep:"PF2E.TraitDescriptionSleep",snare:"PF2E.TraitDescriptionSnare",social:"PF2E.TraitDescriptionSocial",sonic:"PF2E.TraitDescriptionSonic",sorcerer:"PF2E.TraitDescriptionSorcerer",spellgun:"PF2E.TraitDescriptionSpellgun",spellheart:"PF2E.TraitDescriptionSpellheart",spellshot:"PF2E.TraitNoDescription",splash:"PF2E.TraitDescriptionSplash","splash-10":"PF2E.TraitDescriptionSplash10",sprite:"PF2E.TraitDescriptionSprite",staff:"PF2E.TraitDescriptionStaff",stance:"PF2E.TraitDescriptionStance",steam:"PF2E.TraitDescriptionSteam",strix:"PF2E.TraitDescriptionStrix",structure:"PF2E.TraitDescriptionStructure",suli:"PF2E.TraitDescriptionSuli",summon:"PF2E.TraitDescriptionSummon",summoned:"PF2E.TraitDescriptionSummoned",summoner:"PF2E.TraitDescriptionSummoner",swashbuckler:"PF2E.TraitDescriptionSwashbuckler",sweep:"PF2E.TraitDescriptionSweep",sylph:"PF2E.TraitDescriptionSylph",talisman:"PF2E.TraitDescriptionTalisman",talos:"PF2E.TraitDescriptionTalos",tandem:"PF2E.TraitDescriptionTandem",tattoo:"PF2E.TraitDescriptionTattoo",tech:"PF2E.TraitDescriptionTech",telepathy:"PF2E.TraitDescriptionTelepathy",teleportation:"PF2E.TraitDescriptionTeleportation",tengu:"PF2E.TraitDescriptionTengu",tethered:"PF2E.TraitDescriptionTethered",thaumaturge:"PF2E.TraitDescriptionThaumaturge",thrown:"PF2E.TraitDescriptionThrown","thrown-10":"PF2E.TraitDescriptionThrown","thrown-100":"PF2E.TraitDescriptionThrown","thrown-15":"PF2E.TraitDescriptionThrown","thrown-20":"PF2E.TraitDescriptionThrown","thrown-200":"PF2E.TraitDescriptionThrown","thrown-25":"PF2E.TraitDescriptionThrown","thrown-30":"PF2E.TraitDescriptionThrown","thrown-40":"PF2E.TraitDescriptionThrown","thrown-50":"PF2E.TraitDescriptionThrown","thrown-60":"PF2E.TraitDescriptionThrown","thrown-80":"PF2E.TraitDescriptionThrown",tiefling:"PF2E.TraitDescriptionTiefling",time:"PF2E.TraitDescriptionTime",training:"PF2E.TraitDescriptionTraining",transmutation:"PF2E.TraitDescriptionTransmutation",trap:"PF2E.TraitDescriptionTrap",trip:"PF2E.TraitDescriptionTrip","true-name":"PF2E.TraitDescriptionTrueName",twin:"PF2E.TraitDescriptionTwin","two-hand-d10":"PF2E.TraitDescriptionTwoHand","two-hand-d12":"PF2E.TraitDescriptionTwoHand","two-hand-d6":"PF2E.TraitDescriptionTwoHand","two-hand-d8":"PF2E.TraitDescriptionTwoHand",unarmed:"PF2E.TraitDescriptionUnarmed",uncommon:"PF2E.TraitDescriptionUncommon",undine:"PF2E.TraitDescriptionUndine",unique:"PF2E.TraitDescriptionUnique",unstable:"PF2E.TraitDescriptionUnstable",vanara:"PF2E.TraitDescriptionVanara",vishkanya:"PF2E.TraitDescriptionVishkanya",vehicular:"PF2E.TraitDescriptionVehicular","versatile-acid":"PF2E.TraitDescriptionVersatile","versatile-b":"PF2E.TraitDescriptionVersatile","versatile-chaotic":"PF2E.TraitDescriptionVersatile","versatile-cold":"PF2E.TraitDescriptionVersatile","versatile-electricity":"PF2E.TraitDescriptionVersatile","versatile-evil":"PF2E.TraitDescriptionVersatile","versatile-fire":"PF2E.TraitDescriptionVersatile","versatile-force":"PF2E.TraitDescriptionVersatile","versatile-good":"PF2E.TraitDescriptionVersatile","versatile-lawful":"PF2E.TraitDescriptionVersatile","versatile-p":"PF2E.TraitDescriptionVersatile","versatile-poison":"PF2E.TraitDescriptionVersatile","versatile-s":"PF2E.TraitDescriptionVersatile","versatile-sonic":"PF2E.TraitDescriptionVersatile","versatile-vitality":"PF2E.TraitDescriptionVersatile","versatile-void":"PF2E.TraitDescriptionVersatile",virulent:"PF2E.TraitDescriptionVirulent",visual:"PF2E.TraitDescriptionVisual",vitality:"PF2E.TraitDescriptionVitality",void:"PF2E.TraitDescriptionVoid","volley-20":"PF2E.TraitDescriptionVolley","volley-30":"PF2E.TraitDescriptionVolley","volley-50":"PF2E.TraitDescriptionVolley",wand:"PF2E.TraitDescriptionWand",water:"PF2E.TraitDescriptionWater",witch:"PF2E.TraitDescriptionWitch",wizard:"PF2E.TraitDescriptionWizard",wood:"PF2E.TraitDescriptionWood",...preciousMaterialDescriptions},kingmakerTraits={...actionTraits,army:"PF2E.Kingmaker.Trait.army",cavalry:"PF2E.Kingmaker.Trait.cavalry",civic:"PF2E.Kingmaker.Trait.civic",commerce:"PF2E.Kingmaker.Trait.commerce",infantry:"PF2E.Kingmaker.Trait.infantry",kingdom:"PF2E.Kingmaker.Trait.kingdom",leadership:"PF2E.Kingmaker.Trait.leadership",maneuver:"PF2E.Kingmaker.Trait.maneuver",morale:"PF2E.Kingmaker.Trait.morale",region:"PF2E.Kingmaker.Trait.region",siege:"PF2E.Kingmaker.Trait.siege",skirmisher:"PF2E.Kingmaker.Trait.skirmisher",upkeep:"PF2E.Kingmaker.Trait.upkeep"},damageCategoriesUnique={persistent:"PF2E.ConditionTypePersistentShort",precision:"PF2E.Damage.Precision",splash:"PF2E.TraitSplash"},materialDamageEffects=pick$1(preciousMaterials,["abysium","adamantine","cold-iron","darkwood","djezet","inubrix","keep-stone","mithral","noqual","orichalcum","peachwood","siccatite","silver","sisterstone-dusk","sisterstone-scarlet","sovereign-steel","warpglass"]),damageCategories={...damageCategoriesUnique,...materialDamageEffects,alignment:"PF2E.Alignment",energy:"PF2E.TraitEnergy",physical:"PF2E.TraitPhysical"},physicalDamageTypes={bleed:"PF2E.TraitBleed",bludgeoning:"PF2E.TraitBludgeoning",piercing:"PF2E.TraitPiercing",slashing:"PF2E.TraitSlashing"},damageTypes={...alignmentTraits,...energyDamageTypes,...physicalDamageTypes,mental:"PF2E.TraitMental",poison:"PF2E.TraitPoison",spirit:"PF2E.TraitSpirit",untyped:"PF2E.TraitUntyped"},damageRollFlavors=[...DAMAGE_TYPES].reduce((result,key)=>(result[key]=`PF2E.Damage.RollFlavor.${key}`,result),{}),materialIWR=mapValues$1(omit(materialDamageEffects,["keep-stone","peachwood","sisterstone-dusk","sisterstone-scarlet","sovereign-steel","warpglass"]),(_v,k)=>`PF2E.Damage.IWR.Type.${k}`),immunityTypes={...materialIWR,acid:"PF2E.Damage.RollFlavor.acid",air:"PF2E.Damage.RollFlavor.air","area-damage":"PF2E.Damage.IWR.Type.area-damage",auditory:"PF2E.Damage.IWR.Type.auditory",bleed:"PF2E.Damage.RollFlavor.bleed",blinded:"PF2E.Damage.IWR.Type.blinded",bludgeoning:"PF2E.Damage.RollFlavor.bludgeoning",chaotic:"PF2E.Damage.RollFlavor.chaotic",clumsy:"PF2E.Damage.IWR.Type.clumsy",cold:"PF2E.Damage.RollFlavor.cold",confused:"PF2E.Damage.IWR.Type.confused",conjuration:"PF2E.Damage.IWR.Type.conjuration",controlled:"PF2E.Damage.IWR.Type.controlled","critical-hits":"PF2E.Damage.IWR.Type.critical-hits",curse:"PF2E.Damage.IWR.Type.curse",custom:"",darkwood:"PF2E.Damage.IWR.Type.darkwood",dazzled:"PF2E.Damage.IWR.Type.dazzled",deafened:"PF2E.Damage.IWR.Type.deafened","death-effects":"PF2E.Damage.IWR.Type.death-effects",disease:"PF2E.Damage.IWR.Type.disease",doomed:"PF2E.Damage.IWR.Type.doomed",drained:"PF2E.Damage.IWR.Type.drained",earth:"PF2E.Damage.RollFlavor.earth",electricity:"PF2E.Damage.RollFlavor.electricity",emotion:"PF2E.Damage.IWR.Type.emotion",enchantment:"PF2E.Damage.IWR.Type.enchantment",energy:"PF2E.Damage.IWR.Type.energy",enfeebled:"PF2E.Damage.IWR.Type.enfeebled",evil:"PF2E.Damage.RollFlavor.evil",evocation:"PF2E.Damage.IWR.Type.evocation",fascinated:"PF2E.Damage.IWR.Type.fascinated",fatigued:"PF2E.Damage.IWR.Type.fatigued","fear-effects":"PF2E.Damage.IWR.Type.fear-effects",fire:"PF2E.Damage.RollFlavor.fire",fleeing:"PF2E.Damage.IWR.Type.fleeing",force:"PF2E.Damage.RollFlavor.force",frightened:"PF2E.Damage.IWR.Type.frightened",good:"PF2E.Damage.RollFlavor.good",grabbed:"PF2E.Damage.IWR.Type.grabbed",healing:"PF2E.Damage.IWR.Type.healing",illusion:"PF2E.Damage.IWR.Type.illusion",immobilized:"PF2E.Damage.IWR.Type.immobilized",inhaled:"PF2E.Damage.IWR.Type.inhaled",lawful:"PF2E.Damage.RollFlavor.lawful",light:"PF2E.Damage.IWR.Type.light",magic:"PF2E.Damage.IWR.Type.magic",mental:"PF2E.Damage.RollFlavor.mental",metal:"PF2E.Damage.IWR.Type.metal","misfortune-effects":"PF2E.Damage.IWR.Type.misfortune-effects",necromancy:"PF2E.Damage.IWR.Type.necromancy","non-magical":"PF2E.Damage.IWR.Type.non-magical","nonlethal-attacks":"PF2E.Damage.IWR.Type.nonlethal-attacks","object-immunities":"PF2E.Damage.IWR.Type.object-immunities","off-guard":"PF2E.Damage.IWR.Type.off-guard",olfactory:"PF2E.Damage.IWR.Type.olfactory",paralyzed:"PF2E.Damage.IWR.Type.paralyzed","persistent-damage":"PF2E.Damage.IWR.Type.persistent-damage",petrified:"PF2E.Damage.IWR.Type.petrified",physical:"PF2E.Damage.IWR.Type.physical",piercing:"PF2E.Damage.RollFlavor.piercing",plant:"PF2E.Damage.IWR.Type.plant",poison:"PF2E.Damage.RollFlavor.poison",polymorph:"PF2E.Damage.IWR.Type.polymorph",possession:"PF2E.Damage.IWR.Type.possession",precision:"PF2E.Damage.RollFlavor.precision",prone:"PF2E.Damage.IWR.Type.prone",radiation:"PF2E.Damage.IWR.Type.radiation",restrained:"PF2E.Damage.IWR.Type.restrained","salt-water":"PF2E.Damage.IWR.Type.salt-water",scrying:"PF2E.Damage.IWR.Type.scrying",sickened:"PF2E.Damage.IWR.Type.sickened",slashing:"PF2E.Damage.RollFlavor.slashing",sleep:"PF2E.Damage.IWR.Type.sleep",slowed:"PF2E.Damage.IWR.Type.slowed",sonic:"PF2E.Damage.RollFlavor.sonic","spell-deflection":"PF2E.Damage.IWR.Type.spell-deflection",spirit:"PF2E.Damage.RollFlavor.spirit",stunned:"PF2E.Damage.IWR.Type.stunned",stupefied:"PF2E.Damage.IWR.Type.stupefied","swarm-attacks":"PF2E.Damage.IWR.Type.swarm-attacks","swarm-mind":"PF2E.Damage.IWR.Type.swarm-mind",transmutation:"PF2E.Damage.IWR.Type.transmutation",trip:"PF2E.Damage.IWR.Type.trip","unarmed-attacks":"PF2E.Damage.IWR.Type.unarmed-attacks",unconscious:"PF2E.Damage.IWR.Type.unconscious",visual:"PF2E.Damage.IWR.Type.visual",vitality:"PF2E.Damage.RollFlavor.vitality",void:"PF2E.Damage.RollFlavor.void",water:"PF2E.Damage.IWR.Type.water",wood:"PF2E.Damage.IWR.Type.wood",wounded:"PF2E.Damage.IWR.Type.wounded"},weaknessTypes={...materialIWR,acid:"PF2E.Damage.RollFlavor.acid",air:"PF2E.Damage.RollFlavor.air","area-damage":"PF2E.Damage.IWR.Type.area-damage","arrow-vulnerability":"PF2E.Damage.IWR.Type.arrow-vulnerability","axe-vulnerability":"PF2E.Damage.IWR.Type.axe-vulnerability",bleed:"PF2E.Damage.RollFlavor.bleed",bludgeoning:"PF2E.Damage.RollFlavor.bludgeoning",chaotic:"PF2E.Damage.RollFlavor.chaotic",cold:"PF2E.Damage.RollFlavor.cold","critical-hits":"PF2E.Damage.IWR.Type.critical-hits",custom:"",earth:"PF2E.Damage.RollFlavor.earth",electricity:"PF2E.Damage.RollFlavor.electricity",emotion:"PF2E.Damage.IWR.Type.emotion",energy:"PF2E.Damage.IWR.Type.energy",evil:"PF2E.Damage.RollFlavor.evil",fire:"PF2E.Damage.RollFlavor.fire",force:"PF2E.Damage.RollFlavor.force","ghost-touch":"PF2E.Damage.IWR.Type.ghost-touch",glass:"PF2E.Damage.IWR.Type.glass",good:"PF2E.Damage.RollFlavor.good",lawful:"PF2E.Damage.RollFlavor.lawful",light:"PF2E.Damage.IWR.Type.light",magical:"PF2E.Damage.IWR.Type.magical",mental:"PF2E.Damage.RollFlavor.mental",metal:"PF2E.Damage.RollFlavor.metal","non-magical":"PF2E.Damage.IWR.Type.non-magical","nonlethal-attacks":"PF2E.Damage.IWR.Type.nonlethal-attacks",physical:"PF2E.Damage.IWR.Type.physical",piercing:"PF2E.Damage.RollFlavor.piercing",plant:"PF2E.Damage.IWR.Type.plant",poison:"PF2E.Damage.RollFlavor.poison",precision:"PF2E.Damage.RollFlavor.precision",radiation:"PF2E.Damage.IWR.Type.radiation",salt:"PF2E.Damage.IWR.Type.salt","salt-water":"PF2E.Damage.IWR.Type.salt-water",slashing:"PF2E.Damage.RollFlavor.slashing",sonic:"PF2E.Damage.RollFlavor.sonic",spells:"PF2E.Damage.IWR.Type.spells",spirit:"PF2E.Damage.RollFlavor.spirit","splash-damage":"PF2E.Damage.IWR.Type.splash-damage","unarmed-attacks":"PF2E.Damage.IWR.Type.unarmed-attacks","vampire-weaknesses":"PF2E.Damage.IWR.Type.vampire-weaknesses",vitality:"PF2E.Damage.RollFlavor.vitality",void:"PF2E.Damage.RollFlavor.void",vorpal:"PF2E.Damage.IWR.Type.vorpal","vorpal-fear":"PF2E.Damage.IWR.Type.vorpal-fear","vulnerable-to-sunlight":"PF2E.Damage.IWR.Type.vulnerable-to-sunlight",water:"PF2E.Damage.IWR.Type.water",weapons:"PF2E.Damage.IWR.Type.weapons","weapons-shedding-bright-light":"PF2E.Damage.IWR.Type.weapons-shedding-bright-light",wood:"PF2E.Damage.IWR.Type.wood"},resistanceTypes={...materialIWR,acid:"PF2E.Damage.RollFlavor.acid",air:"PF2E.Damage.RollFlavor.air","all-damage":"PF2E.Damage.IWR.Type.all-damage","area-damage":"PF2E.Damage.IWR.Type.area-damage",bleed:"PF2E.Damage.RollFlavor.bleed",bludgeoning:"PF2E.Damage.RollFlavor.bludgeoning",chaotic:"PF2E.Damage.RollFlavor.chaotic",cold:"PF2E.Damage.RollFlavor.cold","critical-hits":"PF2E.Damage.IWR.Type.critical-hits",custom:"","damage-from-spells":"PF2E.Damage.IWR.Type.damage-from-spells",earth:"PF2E.Damage.RollFlavor.earth",electricity:"PF2E.Damage.RollFlavor.electricity",energy:"PF2E.Damage.IWR.Type.energy",evil:"PF2E.Damage.RollFlavor.evil",fire:"PF2E.Damage.RollFlavor.fire",force:"PF2E.Damage.RollFlavor.force","ghost-touch":"PF2E.Damage.IWR.Type.ghost-touch",good:"PF2E.Damage.RollFlavor.good",lawful:"PF2E.Damage.RollFlavor.lawful",light:"PF2E.Damage.IWR.Type.light",magical:"PF2E.Damage.IWR.Type.magical",mental:"PF2E.Damage.RollFlavor.mental",metal:"PF2E.Damage.RollFlavor.metal","non-magical":"PF2E.Damage.IWR.Type.non-magical",nonlethal:"PF2E.Damage.IWR.Type.nonlethal","nonlethal-attacks":"PF2E.Damage.IWR.Type.nonlethal-attacks",physical:"PF2E.Damage.IWR.Type.physical",piercing:"PF2E.Damage.RollFlavor.piercing",plant:"PF2E.Damage.IWR.Type.plant",poison:"PF2E.Damage.RollFlavor.poison",precision:"PF2E.Damage.RollFlavor.precision","protean-anatomy":"PF2E.Damage.IWR.Type.protean-anatomy",radiation:"PF2E.Damage.IWR.Type.radiation",salt:"PF2E.Damage.IWR.Type.salt","salt-water":"PF2E.Damage.IWR.Type.salt-water",slashing:"PF2E.Damage.RollFlavor.slashing",sonic:"PF2E.Damage.RollFlavor.sonic",spells:"PF2E.Damage.IWR.Type.spells",spirit:"PF2E.Damage.RollFlavor.spirit","unarmed-attacks":"PF2E.Damage.IWR.Type.unarmed-attacks",vitality:"PF2E.Damage.RollFlavor.vitality",void:"PF2E.Damage.RollFlavor.void",vorpal:"PF2E.Damage.IWR.Type.vorpal","vorpal-adamantine":"PF2E.Damage.IWR.Type.vorpal-adamantine",water:"PF2E.Damage.IWR.Type.water",weapons:"PF2E.Damage.IWR.Type.weapons","weapons-shedding-bright-light":"PF2E.Damage.IWR.Type.weapons-shedding-bright-light",wood:"PF2E.Damage.IWR.Type.wood"},ATTRIBUTE_ABBREVIATIONS=new Set(["str","dex","con","int","wis","cha"]),CREATURE_ACTOR_TYPES=["character","npc","familiar"],SAVE_TYPES=["fortitude","reflex","will"],IMMUNITY_TYPES=new Set(Object.keys(immunityTypes)),WEAKNESS_TYPES=new Set(Object.keys(weaknessTypes)),RESISTANCE_TYPES=new Set(Object.keys(resistanceTypes)),UNAFFECTED_TYPES=new Set(["bleed","good","evil","lawful","chaotic","spirit","vitality","void"]),SKILL_ABBREVIATIONS=new Set(["acr","arc","ath","cra","dec","dip","itm","med","nat","occ","prf","rel","soc","ste","sur","thi"]),SKILL_DICTIONARY={acr:"acrobatics",arc:"arcana",ath:"athletics",cra:"crafting",dec:"deception",dip:"diplomacy",itm:"intimidation",med:"medicine",nat:"nature",occ:"occultism",prf:"performance",rel:"religion",soc:"society",ste:"stealth",sur:"survival",thi:"thievery"},SKILL_LONG_FORMS=new Set(Object.values(SKILL_DICTIONARY));Object.fromEntries(Object.entries(SKILL_DICTIONARY).map(([abbrev,value])=>[value,abbrev])),[...SAVE_TYPES,...SKILL_LONG_FORMS];const SKILL_EXPANDED={acrobatics:{attribute:"dex",shortForm:"acr"},arcana:{attribute:"int",shortForm:"arc"},athletics:{attribute:"str",shortForm:"ath"},crafting:{attribute:"int",shortForm:"cra"},deception:{attribute:"cha",shortForm:"dec"},diplomacy:{attribute:"cha",shortForm:"dip"},intimidation:{attribute:"cha",shortForm:"itm"},medicine:{attribute:"wis",shortForm:"med"},nature:{attribute:"wis",shortForm:"nat"},occultism:{attribute:"int",shortForm:"occ"},performance:{attribute:"cha",shortForm:"prf"},religion:{attribute:"wis",shortForm:"rel"},society:{attribute:"int",shortForm:"soc"},stealth:{attribute:"dex",shortForm:"ste"},survival:{attribute:"wis",shortForm:"sur"},thievery:{attribute:"dex",shortForm:"thi"}},MOVEMENT_TYPES=["land","burrow","climb","fly","swim"],SIZE_LINKABLE_ACTOR_TYPES=new Set([...CREATURE_ACTOR_TYPES,"vehicle"]),_Migration672RemoveNPCBaseProperties=class extends MigrationBase{static{__name(this,"_Migration672RemoveNPCBaseProperties")}removeBase(property,replace="value"){property[replace]=Number(property[replace])||0,typeof property.base=="number"&&(property[replace]=property.base,"game"in globalThis?property["-=base?"]=null:delete property.base)}async updateActor(actorSource){if(actorSource.type!=="npc")return;const{ac,hp,perception}=actorSource.system.attributes;this.removeBase(ac),this.removeBase(hp,"max"),this.removeBase(perception);const{saves}=actorSource.system;for(const saveType of SAVE_TYPES)this.removeBase(saves[saveType])}async updateItem(itemSource,actorSource){actorSource?.type==="npc"&&itemSource.type==="lore"&&this.removeBase(itemSource.system.mod)}};__name2(_Migration672RemoveNPCBaseProperties,"Migration672RemoveNPCBaseProperties"),__publicField(_Migration672RemoveNPCBaseProperties,"version",.672);let Migration672RemoveNPCBaseProperties=_Migration672RemoveNPCBaseProperties;const _Migration673RemoveBulwarkREs=class extends MigrationBase{static{__name(this,"_Migration673RemoveBulwarkREs")}hasRuleElement(rules){return rules.some(r=>typeof r.key=="string"&&r.key.endsWith("FlatModifier")&&isObject(r.predicate)&&!!r.predicate.all?.includes("self:armor:trait:bulwark"))}async updateItem(item){const{rules}=item.system;if(item.type==="armor"){const index=rules.findIndex(rule=>typeof rule.key=="string"&&rule.key.endsWith("FlatModifier")&&rule.selector==="reflex"&&rule.type==="ability"&&/bulwark/i.test(String(rule.label??"")));index!==-1&&rules.splice(index)}const slug=item.system.slug??sluggify(item.name);if(item.type==="feat"&&slug==="mighty-bulwark"&&!this.hasRuleElement(rules)){const newRules=[{key:"FlatModifier",predicate:{all:["self:armor:trait:bulwark"]},selector:"reflex",type:"untyped",value:4},{key:"RollOption",domain:"reflex",option:"self:armor:bulwark-all"}];rules.push(...newRules)}}};__name2(_Migration673RemoveBulwarkREs,"Migration673RemoveBulwarkREs"),__publicField(_Migration673RemoveBulwarkREs,"version",.673);let Migration673RemoveBulwarkREs=_Migration673RemoveBulwarkREs;const HOMEBREW_TRAIT_KEYS=["creatureTraits","featTraits","languages","magicSchools","spellTraits","weaponCategories","weaponGroups","baseWeapons","weaponTraits","equipmentTraits"],SECONDARY_TRAIT_RECORDS={creatureTraits:["ancestryItemTraits"],equipmentTraits:["armorTraits","consumableTraits"],featTraits:["actionTraits"],weaponTraits:["npcAttackTraits"],magicSchools:["spellTraits"]};function itemIsOfType(item,...types){return types.some(t=>t==="physical"?setHasElement(PHYSICAL_ITEM_TYPES,item.type):item.type===t)}__name(itemIsOfType,"itemIsOfType"),__name2(itemIsOfType,"itemIsOfType");function reduceItemName(label){return label.includes(":")?label.replace(/^[^:]+:\s*|\s*\([^)]+\)$/g,""):label}__name(reduceItemName,"reduceItemName"),__name2(reduceItemName,"reduceItemName");const{fields:fields$2}=foundry.data,_LaxSchemaField=class extends fields$2.SchemaField{static{__name(this,"_LaxSchemaField")}_cleanType(data,options={}){options.source=options.source||data;for(const[name2,field]of this.entries())!(name2 in data)&&options.partial||(data[name2]=field.clean(data[name2],options),data[name2]===void 0&&delete data[name2]);return data}};__name2(_LaxSchemaField,"LaxSchemaField");let LaxSchemaField=_LaxSchemaField;const _StrictSchemaField=class extends fields$2.SchemaField{static{__name(this,"_StrictSchemaField")}_cast(value){return value}_cleanType(data,options){if(!isObject$1(data))throw Error(`${this.name} is not an object`);return super._cleanType(data,options)}};__name2(_StrictSchemaField,"StrictSchemaField");let StrictSchemaField=_StrictSchemaField;const _StrictStringField=class extends fields$2.StringField{static{__name(this,"_StrictStringField")}_cast(value){return value}};__name2(_StrictStringField,"StrictStringField");let StrictStringField=_StrictStringField;const _StrictNumberField=class extends fields$2.NumberField{static{__name(this,"_StrictNumberField")}_cast(value){return value}};__name2(_StrictNumberField,"StrictNumberField");let StrictNumberField=_StrictNumberField;const _StrictBooleanField=class extends fields$2.BooleanField{static{__name(this,"_StrictBooleanField")}_cast(value){return value}};__name2(_StrictBooleanField,"StrictBooleanField");let StrictBooleanField=_StrictBooleanField;const _StrictArrayField=class extends fields$2.ArrayField{static{__name(this,"_StrictArrayField")}_cast(value){return value}_cleanType(value){return value&&super._cleanType(value)}};__name2(_StrictArrayField,"StrictArrayField");let StrictArrayField=_StrictArrayField;const _StrictObjectField=class extends fields$2.ObjectField{static{__name(this,"_StrictObjectField")}_cast(value){return value}};__name2(_StrictObjectField,"StrictObjectField");let StrictObjectField=_StrictObjectField;const _DataUnionField=class extends fields$2.DataField{static{__name(this,"_DataUnionField")}fields;constructor(fields2,options){super(options),this.fields=fields2}_cast(value){return typeof value=="string"&&(value=value.trim()),value}clean(value,options){return Array.isArray(value)&&this.fields.some(f=>f instanceof foundry.data.fields.ArrayField)?this.fields.find(f=>f instanceof StrictArrayField)?.clean(value,options)??value:super.clean(value,options)}validate(value,options){const{DataModelValidationFailure}=foundry.data.validation,{StringField}=foundry.data.fields;for(const field of this.fields)if(!(field.validate(value,options)instanceof DataModelValidationFailure)){if(field instanceof StringField&&typeof value!="string")continue;return}return this.fields[0].validate(value,options)}initialize(value,model,options){return this.fields.find(f=>!f.validate(value))?.initialize(value,model,options)}};__name2(_DataUnionField,"DataUnionField");let DataUnionField=_DataUnionField;const _SlugField=class extends StrictStringField{static{__name(this,"_SlugField")}constructor(options={}){options.blank=!1,options.camel??=null,super(options)}static get _defaults(){return{...super._defaults,nullable:!0,initial:null,camel:null}}_cleanType(value,options){const slug=super._cleanType(value,options),camel=this.options.camel??null;return typeof slug=="string"?sluggify(slug,{camel}):slug}};__name2(_SlugField,"SlugField");let SlugField=_SlugField;const _PredicateStatementField=class extends fields$2.DataField{static{__name(this,"_PredicateStatementField")}constructor(options={}){super({...options,required:!0,nullable:!1,initial:void 0,validationError:"must be recognized predicated statement type"})}_validateType(value){return StatementValidator.isStatement(value)}_cast(value){return value}_cleanType(value){return typeof value=="string"?value.trim():value}};__name2(_PredicateStatementField,"PredicateStatementField");let PredicateStatementField=_PredicateStatementField;const _PredicateField=class extends StrictArrayField{static{__name(this,"_PredicateField")}constructor(options={}){super(new PredicateStatementField,{label:"PF2E.RuleEditor.General.Predicate",...options})}initialize(value,model,options){const statements=super.initialize(value,model,options);return statements&&new PredicatePF2e(...statements)}};__name2(_PredicateField,"PredicateField");let PredicateField=_PredicateField;const _RecordField=class extends fields$2.ObjectField{static{__name(this,"_RecordField")}keyField;valueField;constructor(keyField,valueField,options){if(super(options),!this._isValidKeyFieldType(keyField))throw new Error("key field must be a StringField or a NumberField");if(this.keyField=keyField,!(valueField instanceof fields$2.DataField))throw new Error(`${this.name} must have a DataField as its contained field`);this.valueField=valueField}_isValidKeyFieldType(keyField){if(keyField instanceof fields$2.StringField||keyField instanceof fields$2.NumberField){if(keyField.options.required!==!0||keyField.options.nullable===!0)throw new Error("key field must be required and non-nullable");return!0}return!1}_validateValues(values,options){const validationFailure=foundry.data.validation.DataModelValidationFailure,failures=new validationFailure;for(const[key,value]of Object.entries(values)){if(key.startsWith("-=")&&options?.partial)continue;const keyFailure=this.keyField.validate(key,options);keyFailure&&failures.elements.push({id:key,failure:keyFailure});const valueFailure=this.valueField.validate(value,options);valueFailure&&failures.elements.push({id:`${key}-value`,failure:valueFailure})}if(failures.elements.length)return failures}_cleanType(values,options){for(const[key,value]of Object.entries(values))values[key]=this.valueField.clean(value,options);return values}_validateType(values,options){return isObject$1(values)?this._validateValues(values,options):new foundry.data.validation.DataModelValidationFailure({message:"must be an Object"})}initialize(values,model,options){if(!values)return values;const data={};for(const[key,value]of Object.entries(values))data[key]=this.valueField.initialize(value,model,options);return data}};__name2(_RecordField,"RecordField"),__publicField(_RecordField,"recursive",!0);let RecordField=_RecordField;const _RuleElementPF2e=class extends foundry.abstract.DataModel{static{__name(this,"_RuleElementPF2e")}constructor(source,options){source.label??=options.parent.name,super(source,{parent:options.parent,strict:options.strict??!0,fallback:!1}),__privateAdd(this,_resolveBracketedValue),__publicField(this,"sourceIndex"),__publicField(this,"suppressWarnings");const{item}=this;if(this.suppressWarnings=options.suppressWarnings??!this.actor.id,this.sourceIndex=options.sourceIndex??null,!tupleHasValue(this.constructor.validActorTypes,item.actor.type)){const actorType=game.i18n.localize(`TYPES.Actor.${item.actor.type}`);this.failValidation(`this rule element type cannot be applied to a ${actorType}`),source.ignored=!0}this.label=typeof source.label=="string"?game.i18n.localize(this.resolveInjectedProperties(source.label)):item.name,this.invalid?this.ignored=!0:item instanceof PhysicalItemPF2e?(this.requiresEquipped=!!(source.requiresEquipped??!0),this.requiresInvestment=item.isInvested===null?null:!!(source.requiresInvestment??this.requiresEquipped),this.ignored===!1&&(this.ignored=!!this.requiresEquipped&&!item.isEquipped||item.system.equipped.carryType==="dropped"||!!this.requiresInvestment&&!item.isInvested)):(this.requiresEquipped=null,this.requiresInvestment=null)}static defineSchema(){const{fields:fields2}=foundry.data;return{key:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:void 0}),slug:new SlugField({required:!0,nullable:!0,label:"PF2E.RuleEditor.General.Slug"}),label:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:void 0,label:"PF2E.RuleEditor.General.Label"}),priority:new fields2.NumberField({required:!0,nullable:!1,integer:!0,initial:100}),ignored:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),predicate:new PredicateField,requiresEquipped:new fields2.BooleanField({required:!1,nullable:!0,initial:void 0}),requiresInvestment:new fields2.BooleanField({required:!1,nullable:!0,initial:void 0})}}static get schema(){if(this._schema&&Object.hasOwn(this,"_schema"))return this._schema;const schema=new LaxSchemaField(Object.freeze(this.defineSchema()));return schema.name=this.name,Object.defineProperty(this,"_schema",{value:schema,writable:!1}),schema}get item(){return this.parent}get actor(){return this.parent.actor}get token(){const actor=this.actor;if(actor.token)return actor.token;const tokens=actor.getActiveTokens();return tokens.find(token=>token.controlled)?.document??tokens.shift()?.document??null}getReducedLabel(label=this.label){return reduceItemName(label)}validate(options={}){try{return super.validate(options)}catch(error){if(error instanceof foundry.data.validation.DataModelValidationError){const message=error.message.replace(/validation errors|Joint Validation Error/,`validation errors on item ${this.item.name} (${this.item.uuid})`);return console.warn(message),!1}else throw error}}test(rollOptions){if(this.ignored)return!1;if(this.predicate.length===0)return!0;const optionSet=new Set([...rollOptions??this.actor.getRollOptions(),...this.item.getRollOptions("parent")]);return this.resolveInjectedProperties(this.predicate).test(optionSet)}failValidation(...message){const fullMessage=message.join(" "),{name:name2,uuid}=this.item;if(!this.suppressWarnings){const ruleName=game.i18n.localize(`PF2E.RuleElement.${this.key}`);this.actor.synthetics.preparationWarnings.add(`PF2e System | ${ruleName} rules element on item ${name2} (${uuid}) failed to validate: ${fullMessage}`)}this.ignored=!0}resolveInjectedProperties(source,{warn=!0}={}){if(source===null||typeof source=="number"||typeof source=="string"&&!source.includes("{"))return source;if(Array.isArray(source))for(let i=0;i{const data=key==="rule"?this:key==="actor"||key==="item"?this[key]:this.item,value=getProperty(data,prop);return value===void 0&&(this.ignored=!0,warn&&this.failValidation(`Failed to resolve injected property "${source}"`)),String(value)});return source}resolveValue(value,defaultValue=0,{evaluate=!0,resolvables={},warn=!0}={}){if(value??=defaultValue??null,typeof value=="number"||typeof value=="boolean"||value===null)return value;value=this.resolveInjectedProperties(value,{warn});const resolvedFromBracket=this.isBracketedValue(value)?__privateMethod(this,_resolveBracketedValue,resolveBracketedValue_fn).call(this,value,defaultValue):value;if(typeof resolvedFromBracket=="number")return resolvedFromBracket;if(resolvedFromBracket instanceof Object)return defaultValue instanceof Object?mergeObject(defaultValue,resolvedFromBracket,{inplace:!1}):resolvedFromBracket;if(typeof resolvedFromBracket=="string"){const saferEval=__name2(formula=>{try{const unresolveds=formula.match(/@[a-z.]+/gi)??[];if(unresolveds.length>0){const shouldWarn=warn&&!unresolveds.every(u=>u.startsWith("@target.")||u.startsWith("@actor.conditions."));return this.ignored=!0,shouldWarn&&this.failValidation(`Failed to resolve all components of formula, "${formula}"`),Number(defaultValue)}return Roll.safeEval(formula)}catch{return this.failValidation(`Error thrown while attempting to evaluate formula, "${formula}"`),0}},"saferEval");this.actor.isOfType("character")&&(resolvables.armor=this.actor.wornArmor);const trimmed=resolvedFromBracket.trim();return(trimmed.includes("@")||/^\d+$/.test(trimmed))&&evaluate?saferEval(Roll.replaceFormulaData(trimmed,{actor:this.actor,item:this.item,...resolvables})):trimmed}return defaultValue}isBracketedValue(value){return isObject(value)&&Array.isArray(value.brackets)&&(typeof value.field=="string"||!("fields"in value))}};_resolveBracketedValue=new WeakSet,resolveBracketedValue_fn=__name2(function(value,defaultValue){const bracketNumber=(()=>{if(!value.field)return this.actor.level;const field=String(value.field),separator=field.indexOf("|"),source=field.substring(0,separator),{actor,item}=this;switch(source){case"actor":return Number(getProperty(actor,field.substring(separator+1)))||0;case"item":return Number(getProperty(item,field.substring(separator+1)))||0;case"rule":return Number(getProperty(this,field.substring(separator+1)))||0;default:return Number(getProperty(actor,field.substring(0)))||0}})(),brackets=value.brackets??[],bracketFallthrough=(()=>{switch(typeof defaultValue){case"number":case"boolean":case"object":return defaultValue;case"string":return Number.isNaN(Number(defaultValue))?defaultValue:Number(defaultValue);default:return null}})();return brackets.find(bracket=>{const start=bracket.start??0,end=bracket.end??1/0;return start<=bracketNumber&&end>=bracketNumber})?.value??bracketFallthrough},"#resolveBracketedValue"),__name2(_RuleElementPF2e,"RuleElementPF2e"),__publicField(_RuleElementPF2e,"validActorTypes",["character","familiar","hazard","npc","party","vehicle"]);let RuleElementPF2e=_RuleElementPF2e;const _ResolvableValueField=class extends foundry.data.fields.DataField{static{__name(this,"_ResolvableValueField")}constructor(){super(...arguments),__privateAdd(this,_coerceNumber)}_validateType(value){return value!==null&&["string","number","object","boolean"].includes(typeof value)}_cast(value){return value}_cleanType(value){if(typeof value=="string")return __privateMethod(this,_coerceNumber,coerceNumber_fn).call(this,value);if(isObject(value)&&"brackets"in value){value.field||="actor|level";const brackets=value.brackets=compact(Object.values(value.brackets??{}));for(const bracket of brackets)bracket.start===null&&delete bracket.start,bracket.end===null&&delete bracket.end,bracket.value=typeof bracket.value=="string"?__privateMethod(this,_coerceNumber,coerceNumber_fn).call(this,bracket.value):bracket.value}return value}};_coerceNumber=new WeakSet,coerceNumber_fn=__name2(function(value){const trimmed=value.trim();return/^\d+(?:\.\d+)?$/.test(trimmed)?Number(trimmed):trimmed||0},"#coerceNumber"),__name2(_ResolvableValueField,"ResolvableValueField");let ResolvableValueField=_ResolvableValueField;const _ActorTraitsRuleElement=class extends RuleElementPF2e{static{__name(this,"_ActorTraitsRuleElement")}constructor(data,options){super({...data,priority:99},options),__privateAdd(this,_traitsDictionary),__privateAdd(this,_handleModeAffectingTrait)}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),add:new fields2.ArrayField(new fields2.StringField({required:!0,nullable:!1,blank:!1})),remove:new fields2.ArrayField(new fields2.StringField({required:!0,nullable:!1,blank:!1}))}}beforePrepareData(){if(this.test()&&this.actor.system.traits){const traits=this.actor.system.traits,newTraits=this.resolveInjectedProperties(this.add).filter(t=>!traits.value.includes(t)),traitsDictionary=__privateGet(this,_traitsDictionary,traitsDictionary_get);for(const trait of newTraits){if(!(trait in traitsDictionary))return this.failValidation(`${trait} is not a recognized trait`);traits.value.push(trait),this.actor.rollOptions.all[`self:trait:${trait}`]=!0,["construct","undead"].includes(trait)&&__privateMethod(this,_handleModeAffectingTrait,handleModeAffectingTrait_fn).call(this)}const toRemoves=this.resolveInjectedProperties(this.remove);for(const trait of toRemoves)traits.value=traits.value.filter(t=>t!==trait),delete this.actor.rollOptions.all[`self:trait:${trait}`],["construct","undead"].includes(trait)&&__privateMethod(this,_handleModeAffectingTrait,handleModeAffectingTrait_fn).call(this)}}};_traitsDictionary=new WeakSet,traitsDictionary_get=__name2(function(){switch(this.actor.type){case"character":case"familiar":case"npc":return CONFIG.PF2E.creatureTraits;case"hazard":return CONFIG.PF2E.hazardTraits;case"vehicle":return CONFIG.PF2E.vehicleTraits;default:throw ErrorPF2e("unexpected actor type")}},"#traitsDictionary"),_handleModeAffectingTrait=new WeakSet,handleModeAffectingTrait_fn=__name2(function(){const{actor}=this,{rollOptions}=actor;for(const mode of["construct","living","undead"])delete rollOptions.all[`self:mode:${mode}`];rollOptions.all[`self:mode:${actor.modeOfBeing}`]=!0},"#handleModeAffectingTrait"),__name2(_ActorTraitsRuleElement,"ActorTraitsRuleElement"),__publicField(_ActorTraitsRuleElement,"validActorTypes",["character","npc","familiar","hazard","vehicle"]);let ActorTraitsRuleElement=_ActorTraitsRuleElement;const _DegreeOfSuccess=class{static{__name(this,"_DegreeOfSuccess")}constructor(roll,dc,dosAdjustments=null){__privateAdd(this,_getDegreeAdjustment),__privateAdd(this,_adjustDegreeOfSuccess),__privateAdd(this,_adjustDegreeByDieValue),__privateAdd(this,_calculateDegreeOfSuccess),__publicField(this,"value"),__publicField(this,"unadjusted"),__publicField(this,"adjustment"),__publicField(this,"dieResult"),__publicField(this,"rollTotal"),__publicField(this,"dc"),roll instanceof Roll?(this.dieResult=(roll.isDeterministic?roll.terms.find(t=>t instanceof NumericTerm):roll.dice.find(d=>d instanceof Die&&d.faces===20))?.total??1,this.rollTotal=roll.total):(this.dieResult=roll.dieValue,this.rollTotal=roll.dieValue+roll.modifier),this.dc=typeof dc=="number"?{value:dc}:dc,this.unadjusted=__privateMethod(this,_calculateDegreeOfSuccess,calculateDegreeOfSuccess_fn).call(this),this.adjustment=__privateMethod(this,_getDegreeAdjustment,getDegreeAdjustment_fn).call(this,this.unadjusted,dosAdjustments),this.value=this.adjustment?__privateMethod(this,_adjustDegreeOfSuccess,adjustDegreeOfSuccess_fn).call(this,this.adjustment.amount,this.unadjusted):this.unadjusted}};_getDegreeAdjustment=new WeakSet,getDegreeAdjustment_fn=__name2(function(degree,adjustments){if(!adjustments)return null;for(const outcome of["all",...DEGREE_OF_SUCCESS_STRINGS]){const{label,amount}=adjustments[outcome]??{};if(amount&&label&&!(degree===_DegreeOfSuccess.CRITICAL_SUCCESS&&amount===DEGREE_ADJUSTMENT_AMOUNTS.INCREASE)&&!(degree===_DegreeOfSuccess.CRITICAL_FAILURE&&amount===DEGREE_ADJUSTMENT_AMOUNTS.LOWER)&&(outcome==="all"||DEGREE_OF_SUCCESS_STRINGS.indexOf(outcome)===degree))return{label,amount}}return null},"#getDegreeAdjustment"),_adjustDegreeOfSuccess=new WeakSet,adjustDegreeOfSuccess_fn=__name2(function(amount,degreeOfSuccess){switch(amount){case"criticalFailure":return 0;case"failure":return 1;case"success":return 2;case"criticalSuccess":return 3;default:return Math.clamped(degreeOfSuccess+amount,0,3)}},"#adjustDegreeOfSuccess"),_adjustDegreeByDieValue=new WeakSet,adjustDegreeByDieValue_fn=__name2(function(degree){return this.dieResult===20?__privateMethod(this,_adjustDegreeOfSuccess,adjustDegreeOfSuccess_fn).call(this,DEGREE_ADJUSTMENT_AMOUNTS.INCREASE,degree):this.dieResult===1?__privateMethod(this,_adjustDegreeOfSuccess,adjustDegreeOfSuccess_fn).call(this,DEGREE_ADJUSTMENT_AMOUNTS.LOWER,degree):degree},"#adjustDegreeByDieValue"),_calculateDegreeOfSuccess=new WeakSet,calculateDegreeOfSuccess_fn=__name2(function(){const dc=this.dc.value;return this.rollTotal-dc>=10?__privateMethod(this,_adjustDegreeByDieValue,adjustDegreeByDieValue_fn).call(this,_DegreeOfSuccess.CRITICAL_SUCCESS):dc-this.rollTotal>=10?__privateMethod(this,_adjustDegreeByDieValue,adjustDegreeByDieValue_fn).call(this,_DegreeOfSuccess.CRITICAL_FAILURE):this.rollTotal>=dc?__privateMethod(this,_adjustDegreeByDieValue,adjustDegreeByDieValue_fn).call(this,_DegreeOfSuccess.SUCCESS):__privateMethod(this,_adjustDegreeByDieValue,adjustDegreeByDieValue_fn).call(this,_DegreeOfSuccess.FAILURE)},"#calculateDegreeOfSuccess"),__name2(_DegreeOfSuccess,"DegreeOfSuccess"),__publicField(_DegreeOfSuccess,"CRITICAL_FAILURE",0),__publicField(_DegreeOfSuccess,"FAILURE",1),__publicField(_DegreeOfSuccess,"SUCCESS",2),__publicField(_DegreeOfSuccess,"CRITICAL_SUCCESS",3);let DegreeOfSuccess=_DegreeOfSuccess;const DEGREE_ADJUSTMENT_AMOUNTS={LOWER_BY_TWO:-2,LOWER:-1,INCREASE:1,INCREASE_BY_TWO:2,TO_CRITICAL_FAILURE:"criticalFailure",TO_FAILURE:"failure",TO_SUCCESS:"success",TO_CRITICAL_SUCCESS:"criticalSuccess"},DEGREE_OF_SUCCESS={CRITICAL_SUCCESS:3,SUCCESS:2,FAILURE:1,CRITICAL_FAILURE:0},DEGREE_OF_SUCCESS_STRINGS=["criticalFailure","failure","success","criticalSuccess"],_AdjustDegreeOfSuccessRuleElement=class extends RuleElementPF2e{static{__name(this,"_AdjustDegreeOfSuccessRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,nullable:!1,blank:!1}),adjustment:new RecordField(new fields2.StringField({required:!0,nullable:!1,choices:["all",...DEGREE_OF_SUCCESS_STRINGS]}),new fields2.StringField({required:!0,nullable:!1,choices:degreeAdjustmentAmountString}),{required:!0,nullable:!1})}}beforePrepareData(){if(this.ignored)return;const selector=this.resolveInjectedProperties(this.selector),adjustments=this.adjustment,stringToAdjustment={"two-degrees-better":DEGREE_ADJUSTMENT_AMOUNTS.INCREASE_BY_TWO,"one-degree-better":DEGREE_ADJUSTMENT_AMOUNTS.INCREASE,"one-degree-worse":DEGREE_ADJUSTMENT_AMOUNTS.LOWER,"two-degrees-worse":DEGREE_ADJUSTMENT_AMOUNTS.LOWER_BY_TWO,"to-critical-failure":DEGREE_ADJUSTMENT_AMOUNTS.TO_CRITICAL_FAILURE,"to-failure":DEGREE_ADJUSTMENT_AMOUNTS.TO_FAILURE,"to-success":DEGREE_ADJUSTMENT_AMOUNTS.TO_SUCCESS,"to-critical-success":DEGREE_ADJUSTMENT_AMOUNTS.TO_CRITICAL_SUCCESS},record=["all",...DEGREE_OF_SUCCESS_STRINGS].reduce((accumulated,outcome)=>{const adjustment=adjustments[outcome];return adjustment&&(accumulated[outcome]={label:this.label,amount:stringToAdjustment[adjustment]}),accumulated},{});(this.actor.synthetics.degreeOfSuccessAdjustments[selector]??=[]).push({adjustments:record,predicate:this.predicate})}};__name2(_AdjustDegreeOfSuccessRuleElement,"AdjustDegreeOfSuccessRuleElement"),__publicField(_AdjustDegreeOfSuccessRuleElement,"validActorTypes",["character","npc"]);let AdjustDegreeOfSuccessRuleElement=_AdjustDegreeOfSuccessRuleElement;const degreeAdjustmentAmountString=["one-degree-better","one-degree-worse","two-degrees-better","two-degrees-worse","to-critical-failure","to-failure","to-success","to-critical-success"],_AELikeRuleElement=class _AELikeRuleElement2 extends RuleElementPF2e{static{__name(this,"_AELikeRuleElement")}constructor(){super(...arguments),__privateAdd(this,_rewriteSkillLongFormPath),__privateAdd(this,_pathIsValid),__privateAdd(this,_logChange)}static defineSchema(){const{fields:fields2}=foundry.data,baseSchema=super.defineSchema(),PRIORITIES=this.CHANGE_MODE_DEFAULT_PRIORITIES;return baseSchema.priority.initial=d=>PRIORITIES[String(d.mode)]??50,{...baseSchema,mode:new fields2.StringField({required:!0,choices:keys.strict(this.CHANGE_MODE_DEFAULT_PRIORITIES),initial:void 0}),path:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:void 0}),phase:new fields2.StringField({required:!1,nullable:!1,choices:deepClone(this.PHASES),initial:"applyAEs"}),value:new ResolvableValueField({required:!0,nullable:!0,initial:void 0}),merge:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0})}}static validateJoint(data){if(super.validateJoint(data),data.merge){if(data.mode!=="override")throw new foundry.data.validation.DataModelValidationError(' merge: `mode` must be "override"');if(!isObject(data.value))throw new foundry.data.validation.DataModelValidationError(" merge: `value` must an object")}}onApplyActiveEffects(){this.phase==="applyAEs"&&this.applyAELike()}beforePrepareData(){this.phase==="beforeDerived"&&this.applyAELike()}afterPrepareData(){this.phase==="afterDerived"&&this.applyAELike()}beforeRoll(_domains,rollOptions){this.phase==="beforeRoll"&&this.applyAELike(rollOptions)}applyAELike(rollOptions){if(this.ignored)return;const path=__privateMethod(this,_rewriteSkillLongFormPath,rewriteSkillLongFormPath_fn).call(this,this.resolveInjectedProperties(this.path));if(this.ignored)return;if(!__privateMethod(this,_pathIsValid,pathIsValid_fn).call(this,path))return this.failValidation(`no data found at or near "${path}"`);if(rollOptions??=this.predicate.length>0?new Set(this.actor.getRollOptions()):new Set,!this.test(rollOptions))return;const{actor}=this,current=getProperty(actor,path),change=this.resolveValue(this.value),newValue=_AELikeRuleElement2.getNewValue(this.mode,current,change,this.merge);if(newValue instanceof foundry.data.validation.DataModelValidationFailure)return this.failValidation(newValue.asError().message);if(this.mode==="add"&&Array.isArray(current))current.includes(newValue)||current.push(newValue);else if(["subtract","remove"].includes(this.mode)&&Array.isArray(current))current.splice(current.indexOf(newValue),1);else try{setProperty(actor,path,newValue),__privateMethod(this,_logChange,logChange_fn).call(this,change)}catch(error){error instanceof Error?this.failValidation(error.message):console.warn(error)}}static getNewValue(mode,current,change,merge=!1){const{DataModelValidationFailure}=foundry.data.validation,addOrSubtract=__name2(value=>{const isNumericAdd=typeof value=="number"&&(typeof current=="number"||current===void 0||current===null),isArrayAdd=Array.isArray(current)&¤t.every(e=>typeof e==typeof value);return isNumericAdd?(current??0)+value:isArrayAdd?value:new DataModelValidationFailure({invalidValue:value,fallback:!1})},"addOrSubtract");switch(mode){case"multiply":return typeof change!="number"?new DataModelValidationFailure({invalidValue:change,fallback:!1}):typeof current=="number"||current===void 0?Math.trunc((current??0)*change):new DataModelValidationFailure({invalidValue:current,fallback:!1});case"add":return addOrSubtract(change);case"subtract":case"remove":{const addedChange=(typeof current=="number"||current===void 0)&&typeof change=="number"?-1*change:change;return addOrSubtract(addedChange)}case"downgrade":return typeof change!="number"?new DataModelValidationFailure({invalidValue:change,fallback:!1}):typeof current=="number"||current===void 0?Math.min(current??0,change):new DataModelValidationFailure({invalidValue:current,fallback:!1});case"upgrade":return typeof change!="number"?new DataModelValidationFailure({invalidValue:change,fallback:!1}):typeof current=="number"||current===void 0?Math.max(current??0,change):new DataModelValidationFailure({invalidValue:current,fallback:!1});case"override":return merge&&isObject(current)&&isObject(change)?mergeObject(current,change):change;default:return null}}};_SKILL_LONG_FORM_PATH=new WeakMap,_rewriteSkillLongFormPath=new WeakSet,rewriteSkillLongFormPath_fn=__name2(function(path){return path.replace(__privateGet(_AELikeRuleElement,_SKILL_LONG_FORM_PATH),(match,group)=>objectHasKey(SKILL_EXPANDED,group)?`system.skills.${SKILL_EXPANDED[group].shortForm}`:match)},"#rewriteSkillLongFormPath"),_pathIsValid=new WeakSet,pathIsValid_fn=__name2(function(path){const actor=this.item.actor;return path.length>0&&!/\bnull\b/.test(path)&&(path.startsWith("flags.")||[path,path.replace(/\.[-\w]+$/,""),path.replace(/\.?[-\w]+\.[-\w]+$/,"")].some(path2=>getProperty(actor,path2)!==void 0))},"#pathIsValid"),_logChange=new WeakSet,logChange_fn=__name2(function(value){const{item,mode}=this;if(!(!(typeof value=="number"||typeof value=="string")&&typeof value=="string"&&mode!=="override"))return;const level=item instanceof FeatPF2e?Number(/-(\d+)$/.exec(item.system.location??"")?.[1])||item.level:"level"in item&&typeof item.level=="number"?item.level:null,{autoChanges}=this.actor.system;(autoChanges[this.path]??=[]).push({mode,level,value,source:this.item.name})},"#logChange"),__name2(_AELikeRuleElement,"AELikeRuleElement"),__publicField(_AELikeRuleElement,"CHANGE_MODE_DEFAULT_PRIORITIES",{multiply:10,add:20,subtract:20,remove:20,downgrade:30,upgrade:40,override:50}),__publicField(_AELikeRuleElement,"PHASES",["applyAEs","beforeDerived","afterDerived","beforeRoll"]),__privateAdd(_AELikeRuleElement,_SKILL_LONG_FORM_PATH,(()=>{const skillLongForms=Array.from(SKILL_LONG_FORMS).join("|");return new RegExp(String.raw`^system\.skills\.(${skillLongForms})\b`)})());let AELikeRuleElement=_AELikeRuleElement;const _AdjustModifierRuleElement=class extends RuleElementPF2e{static{__name(this,"_AdjustModifierRuleElement")}applications=0;constructor(source,options){source.suppress&&(source.mode="override"),super(source,options),typeof source.selector=="string"&&this.selectors.length===0&&(this.selectors=[source.selector]),this.suppress??=!1,this.maxApplications??=1/0}static defineSchema(){const{fields:fields2}=foundry.data,baseSchema=super.defineSchema(),PRIORITIES=AELikeRuleElement.CHANGE_MODE_DEFAULT_PRIORITIES;return baseSchema.priority.initial=d=>PRIORITIES[String(d.mode)]??50,{...baseSchema,mode:new fields2.StringField({required:!0,choices:keys.strict(AELikeRuleElement.CHANGE_MODE_DEFAULT_PRIORITIES),initial:void 0}),selector:new fields2.StringField({required:!1,blank:!1,initial:void 0}),selectors:new StrictArrayField(new fields2.StringField({required:!0,blank:!1})),relabel:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),damageType:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),suppress:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),maxApplications:new fields2.NumberField({required:!1,nullable:!0,initial:null}),value:new ResolvableValueField({required:!1,nullable:!0,initial:null})}}static validateJoint(data){super.validateJoint(data);const{DataModelValidationError}=foundry.data.validation;if(data.suppress===!0){if(typeof data.maxApplications=="number")throw new DataModelValidationError(" use of `maxApplications` in combination with `suppress` is not currently supported")}else if(data.value===null&&!data.damageType)throw new DataModelValidationError(" value: must be provided unless damageType is provided or suppress is true")}beforePrepareData(){if(this.ignored)return;const predicate=new PredicatePF2e(this.resolveInjectedProperties(deepClone([...this.predicate]))),adjustment={slug:this.slug,test:options=>predicate.test([...options,...this.item.getRollOptions("parent")]),suppress:this.suppress,getNewValue:current=>{if(this.value===null)return current;const change=Number(this.resolveValue(this.value));if(Number.isNaN(change))return this.failValidation("value does not resolve to a number"),current;if(this.ignored)return current;this.applications+=1,this.applications===this.maxApplications&&(this.ignored=!0);const newValue=AELikeRuleElement.getNewValue(this.mode,current,change);return newValue instanceof foundry.data.validation.DataModelValidationFailure?(this.failValidation(newValue.asError().message),current):newValue},getDamageType:current=>{if(!this.damageType)return current;const damageType=this.resolveInjectedProperties(this.damageType);return objectHasKey(CONFIG.PF2E.damageTypes,damageType)?damageType:(this.failValidation(`${damageType} is an unrecognized damage type.`),current)}};this.relabel&&(adjustment.relabel=this.getReducedLabel(this.resolveInjectedProperties(this.relabel)));for(const selector of this.selectors.map(s=>this.resolveInjectedProperties(s))){if(selector==="null")continue;(this.actor.synthetics.modifierAdjustments[selector]??=[]).push(adjustment)}}};__name2(_AdjustModifierRuleElement,"AdjustModifierRuleElement");let AdjustModifierRuleElement=_AdjustModifierRuleElement;const _AdjustStrikeRuleElement=class _AdjustStrikeRuleElement2 extends RuleElementPF2e{static{__name(this,"_AdjustStrikeRuleElement")}constructor(data,options){super({...data,priority:110},options)}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),mode:new fields2.StringField({required:!0,choices:keys.strict(AELikeRuleElement.CHANGE_MODE_DEFAULT_PRIORITIES),initial:void 0}),property:new fields2.StringField({required:!0,choices:Array.from(this.VALID_PROPERTIES),initial:void 0}),definition:new PredicateField,value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0})}}beforePrepareData(){if(!this.test())return;const change=this.resolveValue(this.value),adjustment=(()=>{if(!this.property)throw ErrorPF2e("Unexpected error applying adjustment");const definition=this.resolveInjectedProperties(this.definition);switch(this.property){case"materials":return{adjustDamageRoll:(weapon,{materials})=>{if(!["add","subtract","remove"].includes(this.mode))return this.failValidation('A strike adjustment of material effects must be used with the "add", "subtract", or "remove" mode.');if(!definition.test(weapon.getRollOptions("item")))return;if(!objectHasKey(CONFIG.PF2E.materialDamageEffects,change))return this.failValidation(`"${change}" is not a supported weapon material effect.`);const method=this.mode==="add"?"add":"delete";materials?.[method](change)}};case"range-increment":return{adjustWeapon:weapon=>{if(weapon.isOfType("melee"))return;if(typeof change!="number")return this.failValidation("Change value is not a number.");if(!definition.test(weapon.getRollOptions("item")))return;const rangeIncrement=weapon.range?.increment;if(typeof rangeIncrement!="number")return this.failValidation("A weapon that meets the definition lacks a range increment.");const newRangeIncrement=AELikeRuleElement.getNewValue(this.mode,rangeIncrement,change);weapon.system.range=newRangeIncrement}};case"traits":return{adjustTraits:(weapon,traits)=>{if(!["add","subtract","remove"].includes(this.mode))return this.failValidation('A strike adjustment of traits must be used with the "add", "subtract", or "remove" mode.');if(!objectHasKey(CONFIG.PF2E.actionTraits,change))return this.failValidation(`"${change}" is not a recognized action trait.`);definition.test(weapon.getRollOptions("item"))&&(this.mode==="add"&&!traits.includes(change)?traits.push(change):["subtract","remove"].includes(this.mode)&&traits.includes(change)&&traits.splice(traits.indexOf(change),1))}};case"weapon-traits":return{adjustWeapon:weapon=>{if(!["add","subtract","remove"].includes(this.mode))return this.failValidation('A strike adjustment of weapon traits must be used with the "add", "subtract", or "remove" mode.');if(!objectHasKey(CONFIG.PF2E.weaponTraits,change)&&!(weapon.isOfType("melee")&&objectHasKey(CONFIG.PF2E.npcAttackTraits,change)))return this.failValidation(`"${change}" is not a recognized weapon trait.`);if(!definition.test(weapon.getRollOptions("item"))||weapon.slug==="basic-unarmed"&&/^(?:modular|versatile)/.test(change))return;const traits=weapon.system.traits.value,annotatedTraitMatch=change.match(/^([a-z][-a-z]+)-(\d*d?\d+)$/);if(this.mode==="add"&&annotatedTraitMatch){const changeBaseTrait=annotatedTraitMatch[1],changeValue=annotatedTraitMatch[2],traitRegex=new RegExp(`${changeBaseTrait}-(\\d*d?\\d*)`),existingTraitMatch=traits.map(trait=>trait.match(traitRegex)).find(match=>!!match);if(existingTraitMatch){const existingTrait=existingTraitMatch[1],existingValue=_AdjustStrikeRuleElement2.getTraitScore(existingTrait);_AdjustStrikeRuleElement2.getTraitScore(changeValue)>existingValue&&traits.findSplice(trait=>trait===existingTraitMatch[0],change);return}}this.mode==="add"&&!traits.includes(change)?traits.push(change):this.mode!=="add"&&traits.includes(change)&&traits.splice(traits.indexOf(change),1)}};case"property-runes":return{adjustWeapon:weapon=>{if(weapon.isOfType("melee"))return;if(!["add","subtract","remove"].includes(this.mode))return this.failValidation('A strike adjustment of weapon property runes must be used with the "add", "subtract", or "remove" mode.');const runeSlug=sluggify(String(change),{camel:"dromedary"});if(!objectHasKey(RUNE_DATA.weapon.property,runeSlug))return this.failValidation(`"${change}" is not a recognized weapon property rune.`);if(!definition.test(weapon.getRollOptions("item")))return;const propertyRunes=weapon.system.runes.property;this.mode==="add"?propertyRunes.push(runeSlug):propertyRunes.includes(runeSlug)&&propertyRunes.splice(propertyRunes.indexOf(runeSlug),1),weapon.system.runes.property=prunePropertyRunes(propertyRunes,RUNE_DATA.weapon.property)}}}})();this.actor.synthetics.strikeAdjustments.push(adjustment)}static getTraitScore(traitValue){const traitValueMatch=traitValue.match(/(\d*)d(\d+)/);return traitValueMatch?Number(traitValueMatch[1]||1)*((Number(traitValueMatch[2])+1)/2):Number(traitValue)}};__name2(_AdjustStrikeRuleElement,"AdjustStrikeRuleElement"),__publicField(_AdjustStrikeRuleElement,"validActorTypes",["character","familiar","npc"]),__publicField(_AdjustStrikeRuleElement,"VALID_PROPERTIES",new Set(["materials","property-runes","range-increment","traits","weapon-traits"]));let AdjustStrikeRuleElement=_AdjustStrikeRuleElement;const _AuraRuleElement=class extends RuleElementPF2e{static{__name(this,"_AuraRuleElement")}constructor(source,options){super(source,options),__privateAdd(this,_processEffects),__privateAdd(this,_processAppearanceData),this.slug??=this.item.slug??sluggify(this.item.name);for(const effect of this.effects)effect.includesSelf??=effect.affects!=="enemies",effect.removeOnExit??=Array.isArray(effect.events)?effect.events.includes("enter"):!1}static defineSchema(){const{fields:fields2}=foundry.data,auraTraitField=new StrictStringField({required:!0,nullable:!1,initial:void 0,choices:{...CONFIG.PF2E.spellTraits,...CONFIG.PF2E.actionTraits}}),effectSchemaField=new fields2.SchemaField({uuid:new StrictStringField({required:!0,blank:!1,nullable:!1,initial:void 0}),affects:new StrictStringField({required:!0,nullable:!1,blank:!1,initial:"all",choices:["allies","enemies","all"],label:"PF2E.RuleEditor.Aura.Effects.Affects"}),events:new StrictArrayField(new StrictStringField({required:!0,blank:!1,nullable:!1,initial:void 0,choices:["enter","turn-start","turn-end"]}),{required:!0,nullable:!1,initial:["enter"],label:"PF2E.RuleEditor.Aura.Effects.Events"}),save:new fields2.SchemaField({type:new StrictStringField({required:!0,nullable:!1,blank:!1,initial:void 0,choices:SAVE_TYPES,label:"PF2E.RuleEditor.Aura.Effects.Type"}),dc:new ResolvableValueField({required:!0,nullable:!1,initial:void 0,label:"PF2E.Check.DC.Unspecific"})},{required:!0,nullable:!0,initial:null,label:"PF2E.SavesHeader"}),predicate:new PredicateField({required:!1,nullable:!1}),removeOnExit:new StrictBooleanField({required:!0,nullable:!1,initial:!0,label:"PF2E.RuleEditor.Aura.Effects.RemoveOnExit"}),includesSelf:new StrictBooleanField({required:!1,nullable:!1,initial:void 0,label:"PF2E.RuleEditor.Aura.Effects.IncludesSelf"})}),xyPairSchema=__name2(({integer})=>({x:new StrictNumberField({required:!0,integer,nullable:!1,initial:void 0,label:"PF2E.RuleEditor.Aura.Appearance.Translation.X"}),y:new StrictNumberField({required:!0,integer,nullable:!1,initial:void 0,label:"PF2E.RuleEditor.Aura.Appearance.Translation.Y"})}),"xyPairSchema"),appearanceSchema={border:new fields2.SchemaField({color:new DataUnionField([new StrictStringField({required:!0,choices:["user-color"],initial:void 0}),new fields2.ColorField({required:!0,nullable:!1,initial:void 0})],{required:!0,nullable:!1,initial:"#000000",label:"PF2E.RuleEditor.Aura.Appearance.Color"}),alpha:new fields2.AlphaField({required:!0,nullable:!1,initial:.75,label:"PF2E.RuleEditor.General.Opacity"})},{required:!1,nullable:!0,initial:()=>({color:"#000000",alpha:.75}),label:"PF2E.RuleEditor.Aura.Appearance.Border"}),highlight:new fields2.SchemaField({color:new DataUnionField([new StrictStringField({required:!0,nullable:!1,choices:["user-color"],initial:void 0}),new fields2.ColorField({required:!0,nullable:!1,initial:void 0})],{required:!0,nullable:!1,initial:"user-color",label:"PF2E.RuleEditor.Aura.Appearance.Color"}),alpha:new fields2.AlphaField({required:!1,nullable:!1,initial:.25,label:"PF2E.RuleEditor.General.Opacity"})},{required:!1,nullable:!1,initial:()=>({color:"user-color",alpha:.25}),label:"PF2E.RuleEditor.Aura.Appearance.Highlight"}),texture:new fields2.SchemaField({src:new StrictStringField({required:!0,nullable:!1,initial:void 0,label:"TOKEN.ImagePath"}),alpha:new fields2.AlphaField({required:!0,nullable:!1,initial:1,label:"PF2E.RuleEditor.General.Opacity"}),scale:new StrictNumberField({required:!0,nullable:!1,positive:!0,initial:1,label:"Scale"}),translation:new fields2.SchemaField(xyPairSchema({integer:!0}),{required:!1,nullable:!0,initial:null,label:"PF2E.RuleEditor.Aura.Appearance.Translation.Label",hint:"PF2E.RuleEditor.Aura.Appearance.Translation.Hint"}),loop:new StrictBooleanField({required:!1,nullable:!1,initial:!0,label:"PF2E.RuleEditor.Aura.Appearance.Loop.Label",hint:"PF2E.RuleEditor.Aura.Appearance.Loop.Hint"}),playbackRate:new StrictNumberField({required:!1,nullable:!1,positive:!0,max:4,initial:1,label:"PF2E.RuleEditor.Aura.Appearance.PlaybackRate.Label",hint:"PF2E.RuleEditor.Aura.Appearance.PlaybackRate.Hint"})},{required:!1,nullable:!0,initial:null,label:"PF2E.RuleEditor.Aura.Appearance.Texture"})};return{...super.defineSchema(),radius:new ResolvableValueField({required:!0,nullable:!1,initial:5,label:"PF2E.RuleEditor.Aura.Basic.Radius"}),level:new ResolvableValueField({required:!1,nullable:!0,initial:null,label:"PF2E.RuleEditor.Aura.Basic.Level.Label",hint:"PF2E.RuleEditor.Aura.Basic.Level.Hint"}),traits:new StrictArrayField(auraTraitField,{required:!0,nullable:!1,label:"PF2E.TraitsLabel"}),effects:new StrictArrayField(effectSchemaField,{required:!0,nullable:!1,label:"PF2E.RuleEditor.Aura.Effects.Label"}),appearance:new fields2.SchemaField(appearanceSchema,{required:!0,nullable:!1,initial:()=>({border:{color:"#000000",alpha:.75},highlight:{color:"user-color",alpha:.25},texture:null}),label:"PF2E.RuleEditor.Aura.Appearance.Label"}),mergeExisting:new StrictBooleanField({required:!0,nullable:!1,initial:!0,label:"PF2E.RuleEditor.Aura.Basic.MergeExisting.Label",hint:"PF2E.RuleEditor.Aura.Basic.MergeExisting.Hint"})}}afterPrepareData(){if(!this.test())return;const radius=Math.clamped(Math.ceil(Number(this.resolveValue(this.radius))/5)*5,5,240);if(Number.isInteger(radius)&&radius>0){const level=this.resolveValue(this.level,null),data={slug:this.slug,radius,level:typeof level=="number"?Math.trunc(level):this.item.isOfType("effect")?this.item.level:null,effects:__privateMethod(this,_processEffects,processEffects_fn).call(this),traits:uniq(this.traits.filter(t=>t!=="aura")).sort(),appearance:__privateMethod(this,_processAppearanceData,processAppearanceData_fn).call(this)};for(const effect of data.effects){const indexEntry=fromUuidSync(effect.uuid);if(!(indexEntry&&"type"in indexEntry&&typeof indexEntry.type=="string")){this.failValidation(`Unable to resolve effect uuid: ${effect.uuid}`);return}["effect","affliction"].includes(indexEntry.type)||this.failValidation('effects transmitted by auras must be of type "effect" or "affliction"')}const existing=this.actor.auras.get(this.slug);if(existing&&this.mergeExisting){existing.radius=data.radius,existing.traits=uniq([...existing.traits,...data.traits]).sort(),existing.appearance=data.appearance;for(const effect of data.effects){const existingIndex=existing.effects.findIndex(e=>e.uuid===effect.uuid);existingIndex!==-1?existing.effects.splice(existingIndex,1,effect):existing.effects.push(effect)}}else this.actor.auras.set(this.slug,data)}}};_processEffects=new WeakSet,processEffects_fn=__name2(function(){return this.effects.map(e=>({...e,uuid:this.resolveInjectedProperties(e.uuid),save:null}))},"#processEffects"),_processAppearanceData=new WeakSet,processAppearanceData_fn=__name2(function(){const appearance=deepClone(this.appearance),{border,highlight,texture}=appearance,textureSrc=(()=>{if(!texture)return null;const maybeTextureSrc=this.resolveInjectedProperties(texture.src);return isImageOrVideoPath(maybeTextureSrc)?maybeTextureSrc:"icons/svg/hazard.svg"})();return border&&(border.color=border.color==="user-color"?userColorForActor(this.actor):border.color),highlight.color=highlight.color==="user-color"?userColorForActor(this.actor):highlight.color,{border:border&&{color:Number(Color.fromString(border.color)),alpha:border.alpha},highlight:{color:Number(Color.fromString(highlight.color)),alpha:highlight.alpha},texture:texture?.alpha&&textureSrc?{...texture,src:textureSrc}:null}},"#processAppearanceData"),__name2(_AuraRuleElement,"AuraRuleElement");let AuraRuleElement=_AuraRuleElement;const _BaseSpeedRuleElement=class extends RuleElementPF2e{static{__name(this,"_BaseSpeedRuleElement")}constructor(data,options){super(data,options),__privateAdd(this,_createMovementType),this.selector=this.selector?.trim().replace(/-speed$/,""),typeof this.value=="string"||typeof this.value=="number"||this.isBracketedValue(this.value)||this.failValidation("A value must be a number, string, or bracketed value")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1,initial:void 0}),value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0})}}beforePrepareData(){if(this.ignored)return;const speedType=this.resolveInjectedProperties(this.selector);if(!tupleHasValue(MOVEMENT_TYPES,speedType))return this.failValidation("Unrecognized or missing selector");const speed=__privateMethod(this,_createMovementType,createMovementType_fn).call(this,speedType);(this.actor.synthetics.movementTypes[speedType]??=[]).push(speed)}};_createMovementType=new WeakSet,createMovementType_fn=__name2(function(type){return()=>{if(!this.test())return null;const value=Math.trunc(Number(this.resolveValue(this.value)));if(!Number.isInteger(value))return this.failValidation("Failed to resolve value"),null;const derivedFromLand=type!=="land"&&typeof this.value=="string"&&/attributes\.speed\.(?:value|total)/.test(this.value);return value>0?{type,value,source:this.item.name,derivedFromLand}:null}},"#createMovementType"),__name2(_BaseSpeedRuleElement,"BaseSpeedRuleElement"),__publicField(_BaseSpeedRuleElement,"validActorTypes",["character","familiar","npc"]);let BaseSpeedRuleElement=_BaseSpeedRuleElement;const ALIGNMENTS=new Set(["LG","NG","CG","LN","N","CN","LE","NE","CE"]),ALIGNMENT_TRAITS=new Set(["chaotic","evil","good","lawful"]),ALLIANCES=new Set(["party","opposition",null]),SAVING_THROW_DEFAULT_ATTRIBUTES={fortitude:"con",reflex:"dex",will:"wis"},SIZE_TO_REACH={tiny:0,sm:5,med:5,lg:5,huge:10,grg:15},SENSES_WITH_MANDATORY_ACUITIES={darkvision:"precise",heatsight:"precise",greaterDarkvision:"precise",lowLightVision:"precise",seeInvisibility:"precise"},_CreatureSensePF2e=class{static{__name(this,"_CreatureSensePF2e")}type;acuity;value;source;get range(){return Number(this.value)||1/0}constructor(data){this.type=data.type,this.acuity=objectHasKey(SENSES_WITH_MANDATORY_ACUITIES,this.type)?SENSES_WITH_MANDATORY_ACUITIES[this.type]:data.acuity??"precise",this.value=data.value??"",this.source=data.source||void 0}get label(){const buildLabel=__name2((type,acuity,range2)=>{const senses2=CONFIG.PF2E.senses,sense=game.i18n.localize(senses2[type]??"")||type,acuityLabel=acuity?game.i18n.localize(CONFIG.PF2E.senseAcuity[acuity]):null;return acuity&&range2?game.i18n.format("PF2E.Actor.Creature.Sense.WithAcuityAndRange",{sense,acuity:acuityLabel,range:range2}):acuity?game.i18n.format("PF2E.Actor.Creature.Sense.WithAcuity",{sense,acuity:acuityLabel}):sense},"buildLabel"),range=this.range<1/0?this.range:void 0;switch(this.type){case"darkvision":case"greaterDarkvision":case"lowLightVision":case"seeInvisibility":return buildLabel(this.type);case"scent":return this.acuity==="vague"?null:buildLabel(this.type,this.acuity,range);default:return buildLabel(this.type,this.acuity,range)}}isMoreAcuteThan(sense){return this.acuity==="precise"&&["imprecise","vague"].includes(sense.acuity??"precise")||this.acuity==="imprecise"&&sense.acuity==="vague"}hasLongerRangeThan(sense){return this.range>Number(sense.value)}};__name2(_CreatureSensePF2e,"CreatureSensePF2e");let CreatureSensePF2e=_CreatureSensePF2e;const SENSE_ACUITIES=["precise","imprecise","vague"],SENSE_TYPES=new Set(["darkvision","echolocation","greaterDarkvision","heatsight","lifesense","lowLightVision","motionsense","scent","seeInvisibility","spiritsense","thoughtsense","tremorsense","wavesense"]),CONDITION_SLUGS=new Set(["blinded","broken","clumsy","concealed","confused","controlled","dazzled","deafened","doomed","drained","dying","encumbered","enfeebled","fascinated","fatigued","fleeing","friendly","frightened","grabbed","helpful","hidden","hostile","immobilized","indifferent","invisible","malevolence","observed","off-guard","paralyzed","persistent-damage","petrified","prone","quickened","restrained","sickened","slowed","stunned","stupefied","unconscious","undetected","unfriendly","unnoticed","wounded"]),_IWR=class{static{__name(this,"_IWR")}constructor(data){__publicField(this,"type"),__publicField(this,"exceptions"),__publicField(this,"definition"),__publicField(this,"source"),__privateAdd(this,_customLabel,void 0),this.type=data.type,this.exceptions=deepClone(data.exceptions??[]),this.definition=data.definition??null,this.source=data.source??null,__privateSet(this,_customLabel,this.type==="custom"?data.customLabel??null:null)}get applicationLabel(){const type=this.typeLabel,exceptions=this.createFormatData({list:this.exceptions,prefix:"exception"}),key=`Exceptions${this.exceptions.length}DoubleVs0`;return game.i18n.format(`PF2E.Damage.IWR.CompositeLabel.${key}`,{type,...exceptions,value:""}).replace(/\s+/g," ").trim()}get typeLabel(){return game.i18n.localize(__privateGet(this,_customLabel)??this.typeLabels[this.type])}describe(iwrType){if(setHasElement(CONDITION_SLUGS,iwrType))return["item:type:condition",`item:slug:${iwrType}`];if(isObject(iwrType))return iwrType.definition;switch(iwrType){case"air":case"earth":case"metal":case"radiation":case"visual":case"water":case"wood":return[`item:trait:${iwrType}`];case"all-damage":return["damage"];case"area-damage":return["area-damage"];case"arrow-vulnerability":return["item:group:bow",{not:"item:tag:crossbow"}];case"auditory":return["item:trait:auditory"];case"axe-vulnerability":return["item:group:axe"];case"critical-hits":return["damage:component:critical"];case"custom":return this.definition??[];case"damage-from-spells":return["damage","item:type:spell","impulse"];case"disease":return["item:trait:disease"];case"emotion":return["item:type:effect","item:trait:emotion"];case"energy":case"physical":return[`damage:category:${iwrType}`];case"fear-effects":return["item:type:effect","item:trait:fear"];case"ghost-touch":return["item:rune:property:ghost-touch"];case"magical":return["item:magical"];case"mental":return[{or:["damage:type:mental",{and:["item:type:effect","item:trait:mental"]}]}];case"non-magical":return[{not:"item:magical"}];case"object-immunities":return[{or:["damage:type:bleed","damage:type:mental","damage:type:poison","damage:type:spirit",{and:["item:type:condition",{or:["item:slug:doomed","item:slug:drained","item:slug:fatigued","item:slug:paralyzed","item:slug:sickened","item:slug:unconscious"]}]}]}];case"precision":case"splash-damage":return[`damage:component:${iwrType==="splash-damage"?"splash":"precision"}`];case"spells":return["damage",{or:["item:type:spell","item:from-spell","impulse"]}];case"unarmed-attacks":return["item:category:unarmed"];default:{if(iwrType in CONFIG.PF2E.damageTypes)return[`damage:type:${iwrType}`];if(objectHasKey(CONFIG.PF2E.materialDamageEffects,iwrType))switch(iwrType){case"adamantine":return[{or:["damage:material:adamantine","damage:material:keep-stone"]}];case"cold-iron":return[{or:["damage:material:cold-iron","damage:material:sovereign-steel"]}];case"darkwood":return[{or:["damage:material:darkwood",{and:["self:mode:undead","damage:material:peachwood"]}]}];case"silver":return[{or:["damage:material:silver","damage:material:mithral"]}];default:return[`damage:material:${iwrType}`]}return setHasElement(MAGIC_SCHOOLS,iwrType)?["item:type:effect",`item:trait:${iwrType}`]:[`unhandled:${iwrType}`]}}}get predicate(){const typeStatements=this.describe(this.type),exceptions=this.exceptions.flatMap(exception=>{const described=this.describe(exception).filter(s=>s!=="damage");return described.length===1?described:{and:described}}),statements=[typeStatements,exceptions.length===0?[]:exceptions.length===1?{not:exceptions[0]}:{nor:exceptions}].flat();return new PredicatePF2e(statements)}toObject(){return{type:this.type,exceptions:deepClone(this.exceptions),source:this.source,label:this.label}}createFormatData({list,prefix}){return list.slice(0,4).map((exception,index)=>{const label=typeof exception=="string"?this.typeLabels[exception]:exception.label;return{[`${prefix}${index+1}`]:game.i18n.localize(label)}}).reduce((accum,obj)=>({...accum,...obj}),{})}test(statements){return this.predicate.test(statements)}};_customLabel=new WeakMap,__name2(_IWR,"IWR");let IWR=_IWR;const _Immunity=class extends IWR{static{__name(this,"_Immunity")}typeLabels=CONFIG.PF2E.immunityTypes;get label(){return this.applicationLabel}};__name2(_Immunity,"Immunity");let Immunity=_Immunity;const _Weakness=class extends IWR{static{__name(this,"_Weakness")}typeLabels=CONFIG.PF2E.weaknessTypes;value;constructor(data){super(data),this.value=data.value}get label(){const type=this.typeLabel,exceptions=this.createFormatData({list:this.exceptions,prefix:"exception"}),key=`Exceptions${this.exceptions.length}DoubleVs0`;return game.i18n.format(`PF2E.Damage.IWR.CompositeLabel.${key}`,{type,value:this.value,...exceptions})}toObject(){return{...super.toObject(),value:this.value}}};__name2(_Weakness,"Weakness");let Weakness=_Weakness;const _Resistance=class extends IWR{static{__name(this,"_Resistance")}typeLabels=CONFIG.PF2E.resistanceTypes;value;doubleVs;constructor(data){super(data),this.value=data.value,this.doubleVs=deepClone(data.doubleVs??[])}get label(){const type=this.typeLabel,exceptions=this.createFormatData({list:this.exceptions,prefix:"exception"}),doubleVs=this.createFormatData({list:this.doubleVs,prefix:"doubleVs"}),key=`Exceptions${this.exceptions.length}DoubleVs${this.doubleVs.length}`;return game.i18n.format(`PF2E.Damage.IWR.CompositeLabel.${key}`,{type,value:this.value,...exceptions,...doubleVs})}get applicationLabel(){const type=this.typeLabel,exceptions=this.createFormatData({list:this.exceptions,prefix:"exception"}),doubleVs=this.createFormatData({list:this.doubleVs,prefix:"doubleVs"}),key=`Exceptions${this.exceptions.length}DoubleVs${this.doubleVs.length}`;return game.i18n.format(`PF2E.Damage.IWR.CompositeLabel.${key}`,{type,value:"",...exceptions,...doubleVs}).replace(/\s+/g," ").trim()}toObject(){return{...super.toObject(),value:this.value,doubleVs:deepClone(this.doubleVs)}}getDoubledValue(damageDescription){return this.doubleVs.length===0?this.value:new PredicatePF2e(this.doubleVs.flatMap(d=>this.describe(d))).test(damageDescription)?this.value*2:this.value}};__name2(_Resistance,"Resistance");let Resistance=_Resistance;const NON_DAMAGE_WEAKNESSES=new Set(["air","earth","ghost-touch","metal","plant","radiation","salt","salt-water","spells","water","wood"]),_AttackTraitHelpers=class{static{__name(this,"_AttackTraitHelpers")}static getLabel(traitOrTag){const traits=CONFIG.PF2E.weaponTraits,tags=CONFIG.PF2E.otherWeaponTags;return traits[traitOrTag]??tags[traitOrTag]??traitOrTag}static getUnannotatedTrait(trait){return trait.replace(/-d?\d{1,3}$/,"")}static createAttackModifiers({item}){const{actor}=item;if(!actor)throw ErrorPF2e("The weapon must be embedded");return item.system.traits.value.flatMap(trait=>{const unannotatedTrait=this.getUnannotatedTrait(trait);switch(unannotatedTrait){case"volley":{if(!item.range?.increment)return[];const penaltyRange=Number(/-(\d+)$/.exec(trait)[1]);return new ModifierPF2e({slug:unannotatedTrait,label:this.getLabel(trait),modifier:-2,type:"untyped",ignored:!0,predicate:new PredicatePF2e({lte:["target:distance",penaltyRange]},{not:"self:ignore-volley-penalty"})})}case"sweep":return new ModifierPF2e({slug:unannotatedTrait,label:this.getLabel(trait),modifier:1,type:"circumstance",predicate:new PredicatePF2e("sweep-bonus")});case"backswing":return new ModifierPF2e({slug:unannotatedTrait,label:this.getLabel(trait),modifier:1,type:"circumstance",predicate:new PredicatePF2e("backswing-bonus")});default:return[]}})}};__name2(_AttackTraitHelpers,"AttackTraitHelpers");let AttackTraitHelpers=_AttackTraitHelpers;function setImmunitiesFromTraits(actor){if(actor.isOfType("character"))return;const{traits}=actor,{immunities}=actor.attributes;if(traits.has("construct")&&!traits.has("eidolon")){const constructImmunities=["bleed","death-effects","disease","doomed","drained","fatigued","healing","necromancy","nonlethal-attacks","paralyzed","poison","sickened","spirit","unconscious"];for(const immunityType of constructImmunities)immunities.some(i=>i.type===immunityType)||immunities.push(new Immunity({type:immunityType,source:game.i18n.localize("PF2E.TraitConstruct")}))}traits.has("mindless")&&!immunities.some(i=>i.type==="mental")&&immunities.push(new Immunity({type:"mental",source:game.i18n.localize("PF2E.TraitMindless")}))}__name(setImmunitiesFromTraits,"setImmunitiesFromTraits"),__name2(setImmunitiesFromTraits,"setImmunitiesFromTraits");function imposeEncumberedCondition(actor){if(game.settings.get("pf2e","automation.encumbrance")&&actor.inventory.bulk.isEncumbered&&actor.conditions.bySlug("encumbered").length===0){const source=game.pf2e.ConditionManager.getCondition("encumbered").toObject(),encumbered=new ConditionPF2e(mergeObject(source,{_id:"xxxENCUMBEREDxxx"}),{parent:actor});encumbered.prepareSiblingData(),encumbered.prepareActorData();for(const rule of encumbered.prepareRuleElements())rule.beforePrepareData?.();actor.conditions.set(encumbered.id,encumbered)}}__name(imposeEncumberedCondition,"imposeEncumberedCondition"),__name2(imposeEncumberedCondition,"imposeEncumberedCondition");const _WeaponTraitToggles=class{static{__name(this,"_WeaponTraitToggles")}constructor(weapon){__privateAdd(this,_resolveOptions),__privateAdd(this,_weapon,void 0),__privateSet(this,_weapon,weapon)}get modular(){const options=__privateMethod(this,_resolveOptions,resolveOptions_fn).call(this,"modular"),sourceSelection=__privateGet(this,_weapon)._source.system.traits.toggles?.modular?.selection,selection=tupleHasValue(options,sourceSelection)?sourceSelection:options.includes(__privateGet(this,_weapon).system.damage.damageType)?__privateGet(this,_weapon).system.damage.damageType:null;return{options,selection}}get versatile(){const options=__privateMethod(this,_resolveOptions,resolveOptions_fn).call(this,"versatile"),sourceSelection=__privateGet(this,_weapon)._source.system.traits.toggles?.versatile?.selection??null,selection=tupleHasValue(options,sourceSelection)?sourceSelection:null;return{options,selection}}};_weapon=new WeakMap,_resolveOptions=new WeakSet,resolveOptions_fn=__name2(function(toggle){const types=__privateGet(this,_weapon).system.traits.value.filter(t=>t.startsWith(toggle)).flatMap(trait=>{if(trait==="modular")return["bludgeoning","piercing","slashing"];const damageType=/^versatile-(\w+)$/.exec(trait)?.at(1);switch(damageType){case"b":return"bludgeoning";case"p":return"piercing";case"s":return"slashing";default:return objectHasKey(CONFIG.PF2E.damageTypes,damageType)?damageType:[]}}),allOptions=Array.from(new Set(types));return toggle==="modular"?allOptions:allOptions.filter(t=>__privateGet(this,_weapon).system.damage.damageType!==t)},"#resolveOptions"),__name2(_WeaponTraitToggles,"WeaponTraitToggles");let WeaponTraitToggles=_WeaponTraitToggles;async function toggleWeaponTrait({weapon,trait,selection}){if(weapon.system.traits.toggles[trait].selection===selection)return!1;const item=weapon.actor?.items.get(weapon.id);return item?.isOfType("weapon")&&item===weapon?await item.update({[`system.traits.toggles.${trait}.selection`]:selection}):item?.isOfType("weapon")&&weapon.altUsageType==="melee"?item.update({[`system.meleeUsage.traitToggles.${trait}`]:selection}):await item?.rules.find(r=>r.key==="Strike"&&!r.ignored&&r.slug===weapon.slug)?.toggleTrait({trait,selection}),!0}__name(toggleWeaponTrait,"toggleWeaponTrait"),__name2(toggleWeaponTrait,"toggleWeaponTrait");function createSheetOptions(options,selections=[],{selected=!1}={}){const sheetOptions=Object.entries(options).reduce((compiledOptions,[stringKey,label])=>{const selectionList=Array.isArray(selections)?selections:selections.value,key=typeof selectionList[0]=="number"?Number(stringKey):stringKey,isSelected=selectionList.includes(key);return(isSelected||!selected)&&(compiledOptions[key]={label:game.i18n.localize(label),value:stringKey,selected:isSelected}),compiledOptions},{});return sortLabeledRecord(sheetOptions)}__name(createSheetOptions,"createSheetOptions"),__name2(createSheetOptions,"createSheetOptions");function createSheetTags(options,selections){return createSheetOptions(options,selections,{selected:!0})}__name(createSheetTags,"createSheetTags"),__name2(createSheetTags,"createSheetTags");function createTagifyTraits(traits,{sourceTraits,record}){const sourceSet=new Set(sourceTraits),traitSlugs=[...traits],readonlyTraits=traitSlugs.filter(t=>!sourceSet.has(t));return traitSlugs.map(slug=>{const label=game.i18n.localize(record?.[slug]??slug);return{id:slug,value:label,readonly:readonlyTraits.includes(slug)}}).sort((t1,t2)=>t1.value.localeCompare(t2.value))}__name(createTagifyTraits,"createTagifyTraits"),__name2(createTagifyTraits,"createTagifyTraits");function processTagifyInSubmitData(form,data){const tagifyInputElements=form.querySelectorAll("tags.tagify ~ input");for(const inputEl of tagifyInputElements.values()){const path=inputEl.name,inputValue=data[path],selections=inputValue&&typeof inputValue=="string"?JSON.parse(inputValue):inputValue;Array.isArray(selections)&&(data[path]=selections.filter(s=>!s.readonly).map(s=>s.id??s.value))}}__name(processTagifyInSubmitData,"processTagifyInSubmitData"),__name2(processTagifyInSubmitData,"processTagifyInSubmitData");function getAdjustment(value,reference){const adjustedHigher=value>reference,adjustedLower=value{const unannotatedTrait=this.getUnannotatedTrait(trait);switch(unannotatedTrait){case"kickback":return new ModifierPF2e({slug:unannotatedTrait,label:CONFIG.PF2E.weaponTraits.kickback,modifier:-2,type:"circumstance",predicate:new PredicatePF2e({lt:["attribute:str:mod",2]}),adjustments:extractModifierAdjustments(synthetics,domains,unannotatedTrait)});case"improvised":return new ModifierPF2e({slug:unannotatedTrait,label:this.getLabel(trait),modifier:-2,type:"item",predicate:new PredicatePF2e({not:"self:ignore-improvised-penalty"}),adjustments:extractModifierAdjustments(synthetics,domains,unannotatedTrait)});default:return[]}});return[...super.createAttackModifiers({item}),...pcSpecificModifiers]}};__name2(_PCAttackTraitHelpers,"PCAttackTraitHelpers");let PCAttackTraitHelpers=_PCAttackTraitHelpers;const _WeaponAuxiliaryAction=class{static{__name(this,"_WeaponAuxiliaryAction")}weapon;action;actions;carryType;hands;purpose;fullPurpose;constructor({weapon,action:action2,purpose,hands}){this.weapon=weapon,this.action=action2,this.purpose=purpose,this.hands=hands??null;const[actions,carryType,fullPurpose]=(()=>{switch(purpose){case"Draw":return[1,"held",`${purpose}${hands}H`];case"PickUp":return[1,"held",`${purpose}${hands}H`];case"Retrieve":{const{container}=weapon;return[container?.system.usage.type==="worn"&&container.isWorn?1:container?.isHeld?2:3,"held",`${purpose}${hands}H`]}case"Grip":return[action2==="Interact"?1:0,"held",purpose];case"Sheathe":return[1,"worn",purpose];case"Modular":return[1,null,purpose];case"Drop":return[0,"dropped",purpose]}})();this.actions=actions,this.carryType=carryType,this.fullPurpose=fullPurpose}get actor(){return this.weapon.parent}get label(){return game.i18n.localize(`PF2E.Actions.${this.action}.${this.fullPurpose}.Title`)}get glyph(){return getActionGlyph(this.actions)}get options(){return this.purpose==="Modular"?createSheetOptions(pick(CONFIG.PF2E.damageTypes,this.weapon.system.traits.toggles.modular.options),[this.weapon.system.traits.toggles.modular.selection??[]].flat()):null}async execute({selection=null}={}){const{actor,weapon}=this;if(typeof this.carryType=="string")await actor.adjustCarryType(this.weapon,{carryType:this.carryType,handsHeld:this.hands??0});else if(selection&&tupleHasValue(weapon.system.traits.toggles.modular.options,selection)&&!await toggleWeaponTrait({weapon,trait:"modular",selection}))return;if(!game.combat)return;const templates={flavor:"./systems/pf2e/templates/chat/action/flavor.hbs",content:"./systems/pf2e/templates/chat/action/content.hbs"},flavorAction={title:`PF2E.Actions.${this.action}.Title`,subtitle:`PF2E.Actions.${this.action}.${this.fullPurpose}.Title`,glyph:this.glyph},flavor=await renderTemplate(templates.flavor,{action:flavorAction,traits:[traitSlugToObject("manipulate",CONFIG.PF2E.actionTraits)]}),content=await renderTemplate(templates.content,{imgPath:weapon.img,message:game.i18n.format(`PF2E.Actions.${this.action}.${this.fullPurpose}.Description`,{actor:actor.name,weapon:weapon.name,damageType:game.i18n.localize(`PF2E.Damage.RollFlavor.${selection}`)})}),token=actor.getActiveTokens(!1,!0).shift();await ChatMessagePF2e.create({content,speaker:ChatMessagePF2e.getSpeaker({actor,token}),flavor,type:CONST.CHAT_MESSAGE_TYPES.EMOTE})}};__name2(_WeaponAuxiliaryAction,"WeaponAuxiliaryAction");let WeaponAuxiliaryAction=_WeaponAuxiliaryAction;function imposeOversizedWeaponCondition(actor){const wieldedOversizedWeapon=actor.itemTypes.weapon.find(w=>w.isEquipped&&w.isOversized&&w.category!=="unarmed"),compendiumCondition=game.pf2e.ConditionManager.getCondition("clumsy"),conditionSource=wieldedOversizedWeapon&&actor.conditions.bySlug("clumsy").length===0?mergeObject(compendiumCondition.toObject(),{_id:"xxxxOVERSIZExxxx",system:{slug:"clumsy",references:{parent:{id:wieldedOversizedWeapon.id}}}}):null;if(!conditionSource)return;const clumsyOne=new ConditionPF2e(conditionSource,{parent:actor});clumsyOne.prepareSiblingData(),clumsyOne.prepareActorData();for(const rule of clumsyOne.prepareRuleElements())rule.beforePrepareData?.()}__name(imposeOversizedWeaponCondition,"imposeOversizedWeaponCondition"),__name2(imposeOversizedWeaponCondition,"imposeOversizedWeaponCondition");function createForceOpenPenalty(actor,domains){const slug="no-crowbar",{modifierAdjustments}=actor.synthetics;return new ModifierPF2e({slug,label:"PF2E.Actions.ForceOpen.NoCrowbarPenalty",type:"item",modifier:-2,predicate:["action:force-open","action:force-open:prying"],hideIfDisabled:!0,adjustments:extractModifierAdjustments(modifierAdjustments,domains,slug)})}__name(createForceOpenPenalty,"createForceOpenPenalty"),__name2(createForceOpenPenalty,"createForceOpenPenalty");function createShoddyPenalty(actor,item,domains){if(!actor.isOfType("character")||!item?.isShoddy)return null;const slug="shoddy";return new ModifierPF2e({label:"PF2E.Item.Physical.OtherTag.Shoddy",type:"item",slug,modifier:-2,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,slug)})}__name(createShoddyPenalty,"createShoddyPenalty"),__name2(createShoddyPenalty,"createShoddyPenalty");function createHinderingPenalty(actor){const slug="hindering";return actor.wornArmor?.traits.has(slug)?new ModifierPF2e({label:"PF2E.TraitHindering",type:"untyped",slug,modifier:-5,adjustments:[]}):null}__name(createHinderingPenalty,"createHinderingPenalty"),__name2(createHinderingPenalty,"createHinderingPenalty");function createPonderousPenalty(actor){const armor=actor.wornArmor,slug="ponderous";if(!armor?.traits.has(slug))return null;const penaltyValue=actor.abilities.str.mod>=(armor.strength??-1/0)?-1:armor.checkPenalty||-1;return new ModifierPF2e({label:"PF2E.TraitPonderous",type:"untyped",slug,modifier:penaltyValue,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,["all","initiative"],slug)})}__name(createPonderousPenalty,"createPonderousPenalty"),__name2(createPonderousPenalty,"createPonderousPenalty");const adjustmentScale=["incredibly-easy","very-easy","easy","normal","hard","very-hard","incredibly-hard"],dcAdjustments=new Map([["incredibly-easy",-10],["very-easy",-5],["easy",-2],["normal",0],["hard",2],["very-hard",5],["incredibly-hard",10]]),dcByLevel=new Map([[-1,13],[0,14],[1,15],[2,16],[3,18],[4,19],[5,20],[6,22],[7,23],[8,24],[9,26],[10,27],[11,28],[12,30],[13,31],[14,32],[15,34],[16,35],[17,36],[18,38],[19,39],[20,40],[21,42],[22,44],[23,46],[24,48],[25,50]]),simpleDCs=new Map([["untrained",10],["trained",15],["expert",20],["master",30],["legendary",40]]),simpleDCsWithoutLevel=new Map([["untrained",10],["trained",15],["expert",20],["master",25],["legendary",30]]);function rarityToDCAdjustment(rarity="common"){switch(rarity){case"uncommon":return"hard";case"rare":return"very-hard";case"unique":return"incredibly-hard";default:return"normal"}}__name(rarityToDCAdjustment,"rarityToDCAdjustment"),__name2(rarityToDCAdjustment,"rarityToDCAdjustment");function adjustDC(dc,adjustment="normal"){return dc+(dcAdjustments.get(adjustment)??0)}__name(adjustDC,"adjustDC"),__name2(adjustDC,"adjustDC");function adjustDCByRarity(dc,rarity="common"){return adjustDC(dc,rarityToDCAdjustment(rarity))}__name(adjustDCByRarity,"adjustDCByRarity"),__name2(adjustDCByRarity,"adjustDCByRarity");function calculateDC(level,{proficiencyWithoutLevel,rarity="common"}={}){proficiencyWithoutLevel??=game.settings.get("pf2e","proficiencyVariant");const dc=dcByLevel.get(level)??14;return adjustDCByRarity(proficiencyWithoutLevel?dc-Math.max(level,0):dc,rarity)}__name(calculateDC,"calculateDC"),__name2(calculateDC,"calculateDC");function calculateSimpleDC(rank,{proficiencyWithoutLevel=!1}={}){return proficiencyWithoutLevel?simpleDCsWithoutLevel.get(rank)??10:simpleDCs.get(rank)??10}__name(calculateSimpleDC,"calculateSimpleDC"),__name2(calculateSimpleDC,"calculateSimpleDC");function combineDCAdjustments(first,second){const startingIndex=adjustmentScale.indexOf(first),lowerByIndex=adjustmentScale.indexOf(second),resultIndex=Math.min(Math.max(startingIndex+lowerByIndex-3,0),6);return adjustmentScale[resultIndex]}__name(combineDCAdjustments,"combineDCAdjustments"),__name2(combineDCAdjustments,"combineDCAdjustments");function createDifficultyScale(dc,startAt){const beginAtIndex=adjustmentScale.indexOf(startAt);return adjustmentScale.filter((_value2,index)=>index>=beginAtIndex).map(value=>adjustDC(dc,value))}__name(createDifficultyScale,"createDifficultyScale"),__name2(createDifficultyScale,"createDifficultyScale");function loreSkillsFromActors(actors){const characters=(Array.isArray(actors)?actors:[actors]).filter(a=>a?.type==="character");return Object.fromEntries(characters.flatMap(m=>Object.values(m.skills)).filter(s=>!!s?.lore).map(s=>[s.slug,s.label]))}__name(loreSkillsFromActors,"loreSkillsFromActors"),__name2(loreSkillsFromActors,"loreSkillsFromActors");async function getActions(){const indexFields=["system.slug"],pack=game.packs.get("pf2e.actionspf2e");if(pack){const actions=(await pack.getIndex({fields:indexFields})).map(a=>[a.system.slug,a.name]);return Object.fromEntries(actions)}else return{}}__name(getActions,"getActions"),__name2(getActions,"getActions");const _CheckPromptDialog=class extends Application{static{__name(this,"_CheckPromptDialog")}constructor(){super(...arguments),__privateAdd(this,_prepareProficiencyRanks),__privateAdd(this,_prepareDCAdjustments),__privateAdd(this,_generatePrompt),__privateAdd(this,_htmlQueryTags),__privateAdd(this,_formatLoreType),__privateAdd(this,_formatActionType),__privateAdd(this,_getDC),__privateAdd(this,_constructCheck),__privateAdd(this,_actions,void 0),__privateAdd(this,_lores,void 0)}static get defaultOptions(){return{...super.defaultOptions,classes:["dialog"],id:"generate-check-prompt",tabs:[{navSelector:".skill-save-navigation",contentSelector:".check-prompt-content",initial:"skills"},{navSelector:".dc-navigation",contentSelector:".dc-content",initial:"set-dc"}],template:"systems/pf2e/templates/gm/check-prompt.hbs",title:game.i18n.localize("PF2E.Actor.Party.CheckPrompt.Title"),width:400,height:"auto"}}async getData(){return __privateSet(this,_actions,await getActions()),__privateSet(this,_lores,loreSkillsFromActors(this.options.actors??game.actors.party?.members??[])),{proficiencyRanks:__privateMethod(this,_prepareProficiencyRanks,prepareProficiencyRanks_fn).call(this),dcAdjustments:__privateMethod(this,_prepareDCAdjustments,prepareDCAdjustments_fn).call(this)}}activateListeners($html){const html=$html[0],skillEl=html.querySelector("input#check-prompt-skills"),skills={...omit(CONFIG.PF2E.skillList,["lore"]),perception:"PF2E.PerceptionLabel"};tagify$1(skillEl,{whitelist:skills});const saveEl=html.querySelector("input#check-prompt-saves");tagify$1(saveEl,{whitelist:CONFIG.PF2E.saves});const loreEl=html.querySelector("input#check-prompt-lores"),loreOptions=isEmpty(__privateGet(this,_lores)||{})?{}:{whitelist:__privateGet(this,_lores)};tagify$1(loreEl,loreOptions);const actionEl=html.querySelector("input#check-prompt-actions"),actionOptions=isEmpty(__privateGet(this,_actions)||{})?{}:{whitelist:__privateGet(this,_actions),enforceWhitelist:!1};tagify$1(actionEl,actionOptions);const traitEl=html.querySelector("input#check-prompt-traits");tagify$1(traitEl,{whitelist:CONFIG.PF2E.actionTraits,enforceWhitelist:!1}),html.querySelector("div.form-group a.add-roll-options")?.addEventListener("click",()=>{const sectionEl=html.querySelector("section.check-prompt-content");sectionEl&§ionEl.classList.toggle("show-roll-options")}),htmlQuery(html,"[data-action=post]")?.addEventListener("click",async()=>{__privateMethod(this,_generatePrompt,generatePrompt_fn).call(this)}),htmlQuery(html,"[data-action=cancel]")?.addEventListener("click",async()=>{this.close()})}};_actions=new WeakMap,_lores=new WeakMap,_prepareProficiencyRanks=new WeakSet,prepareProficiencyRanks_fn=__name2(function(){const proficiencyWithoutLevel=game.settings.get("pf2e","proficiencyVariant");return PROFICIENCY_RANKS.map(value=>({value,label:`${value} (${calculateSimpleDC(value,{proficiencyWithoutLevel})})`}))},"#prepareProficiencyRanks"),_prepareDCAdjustments=new WeakSet,prepareDCAdjustments_fn=__name2(function(){return Object.entries(CONFIG.PF2E.dcAdjustments).filter(([value,_])=>value!=="normal").map(([value,name2])=>({value,label:`${game.i18n.localize(name2)} (${signedInteger(adjustDC(0,value))})`}))},"#prepareDCAdjustments"),_generatePrompt=new WeakSet,generatePrompt_fn=__name2(function(){const html=this.element[0],types=[],traits=[],extras=[],activeSkillSaveTab=htmlQuery(html,"section.check-prompt-content section.tab.active");if(activeSkillSaveTab?.dataset.tab==="skills"?(types.push(...__privateMethod(this,_htmlQueryTags,htmlQueryTags_fn).call(this,html,"input#check-prompt-skills")),types.push(...__privateMethod(this,_htmlQueryTags,htmlQueryTags_fn).call(this,html,"input#check-prompt-lores").map(t=>__privateMethod(this,_formatLoreType,formatLoreType_fn).call(this,t))),traits.push(...__privateMethod(this,_htmlQueryTags,htmlQueryTags_fn).call(this,html,"input#check-prompt-traits")),traits.push(...__privateMethod(this,_htmlQueryTags,htmlQueryTags_fn).call(this,html,"input#check-prompt-actions").map(a=>__privateMethod(this,_formatActionType,formatActionType_fn).call(this,a))),html.querySelector("input#check-prompt-secret:checked")&&!traits.includes("secret")&&traits.push("secret")):activeSkillSaveTab?.dataset.tab==="saves"&&(types.push(...__privateMethod(this,_htmlQueryTags,htmlQueryTags_fn).call(this,html,"input#check-prompt-saves")),htmlQuery(html,"input#check-prompt-basic-save:checked")&&extras.push("basic:true")),types.length>0){const titleEl=htmlQuery(html,"input#check-prompt-title"),flavor=titleEl?.value?`

${titleEl.value}


`:"",dc=__privateMethod(this,_getDC,getDC_fn).call(this,html),content=types.map(type=>__privateMethod(this,_constructCheck,constructCheck_fn).call(this,type,dc,traits,extras)).join("");ChatMessagePF2e.create({user:game.user.id,flavor,content})}},"#generatePrompt"),_htmlQueryTags=new WeakSet,htmlQueryTags_fn=__name2(function(html,selector){const el=htmlQuery(html,selector);return(el instanceof HTMLInputElement&&el.value?JSON.parse(el.value):[]).map(tag=>tag.id||tag.value)},"#htmlQueryTags"),_formatLoreType=new WeakSet,formatLoreType_fn=__name2(function(type){let loreType=type.toLowerCase().replaceAll(" ","-").trim();return loreType.includes("lore")||(loreType=loreType.concat("-lore")),loreType},"#formatLoreType"),_formatActionType=new WeakSet,formatActionType_fn=__name2(function(type){return`action:${type.toLowerCase().replace("action:","").trim()}`},"#formatActionType"),_getDC=new WeakSet,getDC_fn=__name2(function(html){const proficiencyWithoutLevel=game.settings.get("pf2e","proficiencyVariant"),dc=(()=>{const activeDCTab=htmlQuery(html,"section.dc-content section.tab.active");if(activeDCTab?.dataset.tab==="set-dc")return Number(htmlQuery(html,"input#check-prompt-dc")?.value||NaN);if(activeDCTab?.dataset.tab==="simple-dc"){const profRank=htmlQuery(html,"select#check-prompt-simple-dc")?.value;if(tupleHasValue(PROFICIENCY_RANKS,profRank))return calculateSimpleDC(profRank,{proficiencyWithoutLevel})}else if(activeDCTab?.dataset.tab==="level-dc"){const level=Number(htmlQuery(html,"input#check-prompt-level-dc")?.value||NaN);if(Number.isInteger(level))return calculateDC(+level,{proficiencyWithoutLevel})}return NaN})();if(Number.isInteger(dc)){const dcAdjustment=htmlQuery(html,"select#check-prompt-adjust-difficulty")?.value;return dcAdjustment?adjustDC(dc,dcAdjustment):dc}return null},"#getDC"),_constructCheck=new WeakSet,constructCheck_fn=__name2(function(type,dc,traits,extras){return`

@Check[${[type,Number.isInteger(dc)?`dc:${dc}`:null,traits.length?`traits:${traits.join(",")}`:null].concat(...extras).filter(p=>p).join("|")}]

`},"#constructCheck"),__name2(_CheckPromptDialog,"CheckPromptDialog");let CheckPromptDialog=_CheckPromptDialog;async function checkPrompt(options={}){new CheckPromptDialog(options.actors?{actors:options.actors}:{}).render(!0)}__name(checkPrompt,"checkPrompt"),__name2(checkPrompt,"checkPrompt");function buildRewards(...rewards){const[trained,expert,master,legendary]=rewards;return{1:new CoinsPF2e(trained),2:new CoinsPF2e(expert??trained),3:new CoinsPF2e(master??expert??trained),4:new CoinsPF2e(legendary??master??expert??trained)}}__name(buildRewards,"buildRewards"),__name2(buildRewards,"buildRewards");const earnIncomeTable={0:{failure:{cp:1},rewards:buildRewards({cp:5})},1:{failure:{cp:2},rewards:buildRewards({sp:2})},2:{failure:{cp:4},rewards:buildRewards({sp:3})},3:{failure:{cp:8},rewards:buildRewards({sp:5})},4:{failure:{sp:1},rewards:buildRewards({sp:7},{sp:8})},5:{failure:{sp:2},rewards:buildRewards({sp:9},{gp:1})},6:{failure:{sp:3},rewards:buildRewards({gp:1,sp:5},{gp:2})},7:{failure:{sp:4},rewards:buildRewards({gp:2},{gp:2,sp:5})},8:{failure:{sp:5},rewards:buildRewards({gp:2,sp:5},{gp:3})},9:{failure:{sp:6},rewards:buildRewards({gp:3},{gp:4})},10:{failure:{sp:7},rewards:buildRewards({gp:4},{gp:5},{gp:6})},11:{failure:{sp:8},rewards:buildRewards({gp:5},{gp:6},{gp:8})},12:{failure:{sp:9},rewards:buildRewards({gp:6},{gp:8},{gp:10})},13:{failure:{gp:1},rewards:buildRewards({gp:7},{gp:10},{gp:15})},14:{failure:{gp:1,sp:5},rewards:buildRewards({gp:8},{gp:15},{gp:20})},15:{failure:{gp:2},rewards:buildRewards({gp:10},{gp:20},{gp:28})},16:{failure:{gp:2,sp:5},rewards:buildRewards({gp:13},{gp:25},{gp:36},{gp:40})},17:{failure:{gp:3},rewards:buildRewards({gp:15},{gp:30},{gp:45},{gp:55})},18:{failure:{gp:4},rewards:buildRewards({gp:20},{gp:45},{gp:70},{gp:90})},19:{failure:{gp:6},rewards:buildRewards({gp:30},{gp:60},{gp:100},{gp:130})},20:{failure:{gp:8},rewards:buildRewards({gp:40},{gp:75},{gp:150},{gp:200})},21:{failure:{cp:0},rewards:buildRewards({gp:50},{gp:90},{gp:175},{gp:300})}};function getIncomeForLevel(level){const income=earnIncomeTable[Math.clamped(level,0,21)];return{failure:new CoinsPF2e(income.failure),rewards:income.rewards}}__name(getIncomeForLevel,"getIncomeForLevel"),__name2(getIncomeForLevel,"getIncomeForLevel");function applyIncomeOptions({result,options,level,proficiency}){options.useLoreAsExperiencedProfessional&&(result.degreeOfSuccess===DegreeOfSuccess.CRITICAL_FAILURE?(result.degreeOfSuccess=DegreeOfSuccess.FAILURE,result.rewards=new CoinsPF2e(getIncomeForLevel(level).failure)):result.degreeOfSuccess===DegreeOfSuccess.FAILURE&&proficiency!==1&&(result.rewards=new CoinsPF2e(result.rewards).scale(2)))}__name(applyIncomeOptions,"applyIncomeOptions"),__name2(applyIncomeOptions,"applyIncomeOptions");function earnIncome({level,days,rollBrief,proficiency,options,dc}){const degree=new DegreeOfSuccess(rollBrief,dc),result={rewards:new CoinsPF2e,degreeOfSuccess:degree.value};return degree.value===DegreeOfSuccess.CRITICAL_SUCCESS?result.rewards=getIncomeForLevel(level+1).rewards[proficiency]:degree.value===DegreeOfSuccess.SUCCESS?result.rewards=getIncomeForLevel(level).rewards[proficiency]:degree.value===DegreeOfSuccess.FAILURE&&(result.rewards=getIncomeForLevel(level).failure),applyIncomeOptions({result,options,level,proficiency}),{rewards:{perDay:result.rewards,combined:new CoinsPF2e(result.rewards).scale(days)},degreeOfSuccess:result.degreeOfSuccess,daysSpentWorking:days,level,dc,roll:degree.rollTotal}}__name(earnIncome,"earnIncome"),__name2(earnIncome,"earnIncome");function escapeHtml(text){const p=document.createElement("p");return p.innerText=text,p.innerHTML}__name(escapeHtml,"escapeHtml"),__name2(escapeHtml,"escapeHtml");function isExperiencedProfessional(actor){return actor.itemTypes.feat.some(i=>i.slug==="experienced-professional")}__name(isExperiencedProfessional,"isExperiencedProfessional"),__name2(isExperiencedProfessional,"isExperiencedProfessional");function degreeOfSuccessLabel(degreeIndex){const degreeSlug=DEGREE_OF_SUCCESS_STRINGS[degreeIndex];return game.i18n.localize(`PF2E.Check.Result.Degree.Check.${degreeSlug}`)}__name(degreeOfSuccessLabel,"degreeOfSuccessLabel"),__name2(degreeOfSuccessLabel,"degreeOfSuccessLabel");function coinsToString(coins,degreeOfSuccess){return degreeOfSuccess===0?"none":coins.toString()}__name(coinsToString,"coinsToString"),__name2(coinsToString,"coinsToString");function chatTemplate(skillName,earnIncomeResult){const degreeOfSuccess=degreeOfSuccessLabel(earnIncomeResult.degreeOfSuccess),payPerDay=escapeHtml(coinsToString(earnIncomeResult.rewards.perDay,earnIncomeResult.degreeOfSuccess)),combinedPay=escapeHtml(coinsToString(earnIncomeResult.rewards.combined,earnIncomeResult.degreeOfSuccess)),level=earnIncomeResult.level,daysSpentWorking=earnIncomeResult.daysSpentWorking,forDays=daysSpentWorking>1?`

Salary for ${daysSpentWorking} days ${combinedPay}

`:"",successColor=earnIncomeResult.degreeOfSuccess>1?"darkgreen":"darkred",dc=earnIncomeResult.dc,roll=earnIncomeResult.roll;return`
@@ -30,7 +30,7 @@ var __defProp=Object.defineProperty;var __name=(target,value)=>__defProp(target,
- `}__name(askSkillPopupTemplate,"askSkillPopupTemplate"),__name2(askSkillPopupTemplate,"askSkillPopupTemplate");function showEarnIncomePopup(actor){if(!actor?.isOfType("character")){ui.notifications.error("You must select at least one PC");return}const skills=Object.values(actor.skills).filter(s=>!!s?.proficient);new Dialog({title:"Earn Income",content:askSkillPopupTemplate(skills),buttons:{no:{icon:fontAwesomeIcon("times").outerHTML,label:"Cancel"},yes:{icon:fontAwesomeIcon("coins").outerHTML,label:"Earn Income",callback:($html,event)=>{const html=$html[0],level=Number(html.querySelector("[name=level]")?.value)||0,days=Number(html.querySelector("[name=days]")?.value)||1,skillAcronym=html.querySelector("[name=skillAcronym]")?.value??"soc",skill=skills.find(s=>s.slug===skillAcronym);if(!skill)throw ErrorPF2e("Skill not found");localStorage.setItem("earnIncomeLevel",level.toString()),localStorage.setItem("earnIncomeDays",days.toString()),localStorage.setItem("earnIncomeSkillAcronym",skillAcronym),runEarnIncome({actor,event,skill,level,days})}}},default:"yes"}).render(!0)}__name(showEarnIncomePopup,"showEarnIncomePopup"),__name2(showEarnIncomePopup,"showEarnIncomePopup");function createDamageFormula(damage,degree=DEGREE_OF_SUCCESS.SUCCESS){if(damage=deepClone(damage),degree===DEGREE_OF_SUCCESS.CRITICAL_FAILURE)return null;degree===DEGREE_OF_SUCCESS.FAILURE&&(damage.dice=damage.dice.filter(d=>d.category==="splash"),damage.modifiers=damage.modifiers.filter(m=>m.damageCategory==="splash"));const critical=degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS;if(!damage.base.length)return null;const typeMap=new Map;for(const baseEntry of damage.base){const list=typeMap.get(baseEntry.damageType)??[];if(typeMap.set(baseEntry.damageType,list),baseEntry.terms)list.push(...baseEntry.terms.map(t=>({...baseEntry,...t,label:null,critical:null})));else if(baseEntry.diceNumber&&baseEntry.dieSize||baseEntry.modifier){const{diceNumber,dieSize,damageType}=baseEntry,modifier=baseEntry.modifier??0,label=(()=>{const diceSection=diceNumber?`${diceNumber}${dieSize}`:null;if(!diceSection)return String(modifier);const displayedModifier=modifier?Math.abs(modifier):null,operator=modifier<0?" - ":" + ";return[diceSection,displayedModifier].filter(p=>p!==null).join(operator)})();list.push({label,dice:diceNumber&&dieSize?{number:diceNumber,faces:Number(dieSize.replace("d",""))}:null,modifier,critical:null,damageType,category:baseEntry.category,materials:baseEntry.materials??[]})}}const BONUS_BASE_LABELS=["PF2E.ConditionTypePersistent"].map(l=>game.i18n.localize(l)),outcomeMatches=__name2(m=>critical||m.critical!==!0,"outcomeMatches");for(const dice of damage.dice.filter(d=>d.enabled&&outcomeMatches(d))){const matchingBase=damage.base.find(b=>b.damageType===dice.damageType)??damage.base[0],baseDieSize=Number(matchingBase.dieSize?.replace("d",""))||matchingBase.terms?.[0].dice?.faces,faces=Number(dice.dieSize?.replace("d",""))||baseDieSize||null,damageType=dice.damageType??matchingBase.damageType;if(dice.diceNumber>0&&faces){const list=typeMap.get(damageType)??[];list.push({label:BONUS_BASE_LABELS.includes(dice.label)?null:`${dice.label} +${dice.diceNumber}d${faces}`,dice:{number:dice.diceNumber,faces},modifier:0,damageType,category:dice.category,critical:dice.critical}),typeMap.set(damageType,list)}}for(const modifier of damage.modifiers.filter(m=>m.enabled&&outcomeMatches(m))){const matchingBase=modifier.kind==="bonus"?damage.base.find(b=>b.damageType===(modifier.damageType??b.damageType)&&b.category===modifier.category):damage.base.find(b=>b.damageType===(modifier.damageType??b.damageType))??damage.base.at(0);if(!matchingBase)continue;const damageType=modifier.damageType??matchingBase.damageType,list=typeMap.get(damageType)??[];list.push({label:BONUS_BASE_LABELS.includes(modifier.label)?null:`${modifier.label} ${addSign(modifier.value)}`,dice:null,modifier:modifier.value,damageType,category:modifier.damageCategory,critical:modifier.critical}),typeMap.set(damageType,list)}const instances=[instancesFromTypeMap(typeMap,{degree}),instancesFromTypeMap(typeMap,{degree,persistent:!0})].flat(),commaSeparated=instances.map(i=>i.formula).join(","),breakdown=instances.flatMap(i=>i.breakdown);return{formula:`{${commaSeparated}}`,breakdown}}__name(createDamageFormula,"createDamageFormula"),__name2(createDamageFormula,"createDamageFormula");function instancesFromTypeMap(typeMap,{degree,persistent=!1}){return Array.from(typeMap.entries()).flatMap(([damageType,typePartials])=>{const partials=typePartials.filter(p=>p.category==="persistent"===persistent);if(partials.length===0)return[];const groups=groupBy(partials,partial=>partial.category),nonCriticalDamage=(()=>{const criticalInclusion=degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS?[CRITICAL_INCLUSION.DOUBLE_ON_CRIT]:[CRITICAL_INCLUSION.DOUBLE_ON_CRIT,CRITICAL_INCLUSION.DONT_DOUBLE_ON_CRIT],doubleDice=degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS&&criticalInclusion.includes(null)&&game.settings.get("pf2e","critRule")==="doubledice",double=degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS&&!doubleDice;return sumExpression(createPartialFormulas(groups,{criticalInclusion,doubleDice}),{double})})(),criticalDamage=(()=>{if(degree!==DEGREE_OF_SUCCESS.CRITICAL_SUCCESS)return null;const criticalInclusion=[CRITICAL_INCLUSION.CRITICAL_ONLY,CRITICAL_INCLUSION.DONT_DOUBLE_ON_CRIT];return sumExpression(createPartialFormulas(groups,{criticalInclusion}))})(),summedDamage=sumExpression(degree?[nonCriticalDamage,criticalDamage]:[nonCriticalDamage]),enclosed=ensureValidFormulaHead(summedDamage)||"0";if(enclosed==="0"&&persistent)return[];const flavor=(()=>{const typeFlavor=damageType==="untyped"&&!persistent?[]:[damageType],persistentFlavor=persistent?["persistent"]:[],materialFlavor=typePartials.flatMap(p=>p.materials??[]),allFlavor=[typeFlavor,persistentFlavor,materialFlavor].flat().join(",");return allFlavor.length>0?`[${allFlavor}]`:""})(),breakdown=(()=>{const flattenedDamage=[null,"persistent","precision","splash"].flatMap(c=>{const partials2=groups.get(c)??[],breakdownDamage2=partials2.filter(e=>e.label!==null),leadingTerms=partials2.filter(p=>p.label===null&&(p.modifier||p.dice?.number||partials2.every(pp=>pp.label===null)));if(leadingTerms.length){const append=c==="splash"?` ${game.i18n.localize("PF2E.Damage.RollFlavor.splash")}`:"",label=createSimpleFormula(leadingTerms)+append;breakdownDamage2.unshift({...leadingTerms[0],label})}return breakdownDamage2}),breakdownDamage=flattenedDamage.filter(d=>d.critical!==!0);if(degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS&&breakdownDamage.push(...flattenedDamage.filter(d=>d.critical===!0)),!breakdownDamage.length)return[];const damageTypeLabel=breakdownDamage[0].category==="persistent"?game.i18n.format("PF2E.Damage.PersistentTooltip",{damageType:game.i18n.localize(CONFIG.PF2E.damageTypes[damageType]??damageType)}):game.i18n.localize(CONFIG.PF2E.damageTypes[damageType]??damageType),labelParts=breakdownDamage.map(d=>d.label);return labelParts[0]=`${labelParts[0].replace(/^\s+\+/,"")} ${damageTypeLabel}`,labelParts})(),formula=enclosed&&flavor?`${enclosed}${flavor}`:enclosed;return formula?{formula,breakdown}:[]})}__name(instancesFromTypeMap,"instancesFromTypeMap"),__name2(instancesFromTypeMap,"instancesFromTypeMap");function createPartialFormulas(partials,{criticalInclusion,doubleDice=!1}){return[null,"persistent","precision","splash"].flatMap(category=>{const requestedPartials=(partials.get(category)??[]).filter(p=>criticalInclusion.includes(p.critical)),term=(()=>{const expression=createSimpleFormula(requestedPartials,{doubleDice});return expression==="0"?"":["precision","splash"].includes(category??"")&&hasOperators(expression)?`(${expression})`:expression})();return(term&&category&&category!=="persistent"?`${term}[${category}]`:term)||[]})}__name(createPartialFormulas,"createPartialFormulas"),__name2(createPartialFormulas,"createPartialFormulas");function combinePartialTerms(terms){const modifier=terms.reduce((total,p)=>total+p.modifier,0),constantTerm=modifier?{dice:null,modifier}:null,dice=terms.filter(p=>!!p.dice&&p.dice.number>0).sort(sortBy(t=>-t.dice.faces)),combinedDice=[...groupBy(dice,t=>t.dice.faces).values()].map(terms2=>({modifier:0,dice:{...terms2[0].dice,number:sum(terms2.map(d=>d.dice.number))}})),combined=compact([...combinedDice,constantTerm]);return combined.length?combined:[{dice:null,modifier:0}]}__name(combinePartialTerms,"combinePartialTerms"),__name2(combinePartialTerms,"combinePartialTerms");function createSimpleFormula(terms,{doubleDice}={}){terms=combinePartialTerms(terms);const constant=terms.find(t=>!!t.modifier)?.modifier??0;return[terms.filter(t=>!!t.dice&&t.dice.number>0).map(term=>{const number=doubleDice?term.dice.number*2:term.dice.number,faces=term.dice.faces;return doubleDice?`${number}d${faces}[doubled]`:`${number}d${faces}`}).join(" + "),Math.abs(constant)].filter(e=>!!e).map(e=>typeof e=="number"&&doubleDice?`2 * ${e}`:e).join(constant>0?" + ":" - ")||"0"}__name(createSimpleFormula,"createSimpleFormula"),__name2(createSimpleFormula,"createSimpleFormula");function parseTermsFromSimpleFormula(formula,options){return(formula instanceof Roll?formula:new Roll(formula,options?.rollData)).terms.reduceRight((result,term)=>{if(term.expression===" + ")return result;if(term.expression===" - "){const termToModify=result[0];return termToModify&&(termToModify.modifier&&(termToModify.modifier*=-1),termToModify.dice&&(termToModify.dice.number*=-1)),result}return result.unshift({modifier:term instanceof NumericTerm?term.number:0,dice:term instanceof Die?{faces:term.faces,number:term.number}:null}),result},[])}__name(parseTermsFromSimpleFormula,"parseTermsFromSimpleFormula"),__name2(parseTermsFromSimpleFormula,"parseTermsFromSimpleFormula");function sumExpression(terms,{double=!1}={}){if(terms.every(t=>!t))return null;const summed=terms.filter(p=>!!p).join(" + ")||null,enclosed=double&&hasOperators(summed)?`(${summed})`:summed;return double?`2 * ${enclosed}`:enclosed}__name(sumExpression,"sumExpression"),__name2(sumExpression,"sumExpression");function hasOperators(formula){return/[-+*/]/.test(formula??"")}__name(hasOperators,"hasOperators"),__name2(hasOperators,"hasOperators");function ensureValidFormulaHead(formula){if(!formula)return null;const isWrapped=/^\(.*\)$/.test(formula),isSimple=/^\d+(d\d+)?$/.test(formula);return isWrapped||isSimple?formula:`(${formula})`}__name(ensureValidFormulaHead,"ensureValidFormulaHead"),__name2(ensureValidFormulaHead,"ensureValidFormulaHead");const _ArithmeticExpression=class _ArithmeticExpression2 extends RollTerm{static{__name(this,"_ArithmeticExpression")}operator;operands;constructor(termData){super(termData),this.operator=termData.operator,this.operands=termData.operands.slice(0,2).map(datum=>{if(datum instanceof RollTerm)return datum;const TermCls=CONFIG.Dice.termTypes[datum.class??""]??Object.values(CONFIG.Dice.terms).find(t=>t.name===datum.class)??Die;return simplifyTerm(TermCls.fromData(datum))}),this.operator==="*"&&this.operands[0]instanceof NumericTerm&&tupleHasValue([2,3],this.operands[0].number)&&markAsCrit(this.operands[1],this.operands[0].number)}static fromData(data){return super.fromData({...data,class:"ArithmeticExpression"})}static totalOf(operator,left,right){if(!(left===void 0||right===void 0))switch(operator){case"+":return left+right;case"-":return left-right;case"*":return left*right;case"/":return left/right;case"%":return left%right}}get dice(){return this.operands.flatMap(o=>o instanceof DiceTerm?o:o instanceof Grouping||o instanceof _ArithmeticExpression2||o instanceof IntermediateDie?o.dice:[])}get expression(){if(this.isDeterministic&&typeof this.total=="number"&&!Number.isNaN(this.total)&&!isFlavoredArithmetic(this))return this.total.toString();const{operator,operands}=this;return`${operands[0].expression} ${operator} ${operands[1].expression}`}get formula(){const{operator,operands}=this;return`${operands[0].formula} ${operator} ${operands[1].formula}`}get total(){if(!this._evaluated&&!this.isDeterministic)return;const operands=[Number(this.operands[0].total),Number(this.operands[1].total)];return _ArithmeticExpression2.totalOf(this.operator,...operands)}get critImmuneTotal(){if(!this._evaluated)return;const[left,right]=this.operands;if(left instanceof NumericTerm&&left.number===2&&this.operator==="*")return typeof right.total=="string"?Number(right.total):right.total;const undoubledLeft=(()=>left instanceof _ArithmeticExpression2||left instanceof Grouping?Number(left.critImmuneTotal):Number(left.total))(),undoubledRight=right instanceof _ArithmeticExpression2||right instanceof Grouping?Number(right.critImmuneTotal):Number(right.total);return _ArithmeticExpression2.totalOf(this.operator,undoubledLeft,undoubledRight)}get isDeterministic(){return this.operands.every(o=>o.isDeterministic)}get minimumValue(){const left=DamageInstance.getValue(this.operands[0],"minimum"),right=DamageInstance.getValue(this.operands[1],"minimum");return _ArithmeticExpression2.totalOf(this.operator,left,right)}get expectedValue(){const left=DamageInstance.getValue(this.operands[0]),right=DamageInstance.getValue(this.operands[1]);return _ArithmeticExpression2.totalOf(this.operator,left,right)}get maximumValue(){const left=DamageInstance.getValue(this.operands[0],"maximum"),right=DamageInstance.getValue(this.operands[1],"maximum");return _ArithmeticExpression2.totalOf(this.operator,left,right)}render(){const fragment=new DocumentFragment,{operator,operands}=this;if(operator==="*"&&operands[0]instanceof NumericTerm&&operands[1]instanceof NumericTerm)return fragment.append((operands[0].total*operands[1].total).toString()),fragment;const[left,right]=operands.map(o=>["precision","splash"].includes(o.flavor)?renderComponentDamage(o):isSystemDamageTerm(o)?o.render():o.expression);return fragment.append(left,` ${this.operator} `,right),fragment}async _evaluate(options={}){for(const operand of this.operands)operand._evaluated||await operand.evaluate({async:!0,...options});return this._evaluated=!0,this}toJSON(){return{...super.toJSON(),operands:[this.operands[0].toJSON(),this.operands[1].toJSON()]}}};__name2(_ArithmeticExpression,"ArithmeticExpression"),__publicField(_ArithmeticExpression,"SERIALIZE_ATTRIBUTES",["operator","operands"]);let ArithmeticExpression=_ArithmeticExpression;const _Grouping=class _Grouping2 extends RollTerm{static{__name(this,"_Grouping")}term;constructor(termData){const TermCls=CONFIG.Dice.termTypes[termData.term.class??""]??Object.values(CONFIG.Dice.terms).find(t=>t.name===termData.term.class)??NumericTerm,childTerm=simplifyTerm(TermCls.fromData(termData.term));childTerm instanceof _Grouping2?(super(childTerm.toJSON()),this.term=childTerm.term):(super(termData),this.term=childTerm),this._evaluated=termData.evaluated??this.term._evaluated??!0}static fromData(data){return super.fromData({...data,class:"Grouping"})}get dice(){if(this.term instanceof DiceTerm)return[this.term];if(isObject(this.term)&&"dice"in this.term){const{dice}=this.term;if(Array.isArray(dice)&&dice.every(d=>d instanceof DiceTerm))return dice}return[]}get expression(){return this.isDeterministic&&typeof this.total=="number"&&!Number.isNaN(this.total)&&!isFlavoredArithmetic(this.term)?this.total.toString():this.term instanceof DiceTerm||this.term instanceof MathTerm?this.term.expression:`(${this.term.expression})`}get formula(){const termFormula=this.term.formula,flavor=this.flavor?`[${this.flavor}]`:"";return`(${termFormula})${flavor}`}get total(){return this._evaluated||this.isDeterministic?Number(this.term.total):void 0}get critImmuneTotal(){return this.term instanceof ArithmeticExpression||this.term instanceof _Grouping2?this.term.critImmuneTotal:this.total}get isDeterministic(){return this.term.isDeterministic}get minimumValue(){return DamageInstance.getValue(this.term,"minimum")}get expectedValue(){return DamageInstance.getValue(this.term)}get maximumValue(){return DamageInstance.getValue(this.term,"maximum")}async _evaluate(options={}){return this.term._evaluated||await this.term.evaluate({async:!0,...options}),this._evaluated=!0,this}toJSON(){return{...super.toJSON(),term:this.term.toJSON()}}render(){const expression=["precision","splash"].includes(this.flavor)?renderComponentDamage(this.term):isSystemDamageTerm(this.term)?this.term.render():this.expression,fragment=new DocumentFragment,nodes=this.term instanceof NumericTerm||this.term instanceof Die?[expression]:["(",expression,")"];return fragment.append(...nodes),fragment}};__name2(_Grouping,"Grouping"),__publicField(_Grouping,"SERIALIZE_ATTRIBUTES",["term"]);let Grouping=_Grouping;const _IntermediateDie=class extends RollTerm{static{__name(this,"_IntermediateDie")}number;faces;die;constructor(data){super(data);const setTerm=__name2(termData=>{if(typeof termData=="number")return termData;const TermCls=CONFIG.Dice.termTypes[termData.class??"NumericTerm"],term=simplifyTerm(TermCls.fromData(termData));return term instanceof NumericTerm?term.number:term.isDeterministic?Roll.safeEval(term.formula):term instanceof Grouping?(term.isIntermediate=!0,term):(term instanceof MathTerm||console.warn(`Unexpected term type: ${term.constructor.name}`),term)},"setTerm");this.number=setTerm(data.number),this.faces=setTerm(data.faces),this.die=(()=>data.die?Die.fromData({...data.die,class:"Die"}):typeof this.number=="number"&&typeof this.faces=="number"?Die.fromData({number:this.number,faces:this.faces,evaluated:this._evaluated,options:this.options}):null)()}get expression(){return this.die?.expression??`${this.number}d${this.faces}`}get total(){return this.isDeterministic?Number(this.number)*Number(this.faces):this.die?.total}get dice(){return this.die?[this.die]:[]}get isDeterministic(){return this.number===0||this.faces===0||this.faces===1}get minimumValue(){return DamageInstance.getValue(this.die??new Die({number:Number(this.number),faces:Number(this.faces)}),"minimum")}get expectedValue(){return DamageInstance.getValue(this.die??new Die({number:Number(this.number),faces:Number(this.faces)}))}get maximumValue(){return DamageInstance.getValue(this.die??new Die({number:Number(this.number),faces:Number(this.faces)}),"maximum")}async _evaluate(){return typeof this.number!="number"&&(this.number=(await this.number.evaluate({async:!0})).total),typeof this.faces!="number"&&(this.faces=(await this.faces.evaluate({async:!0})).total),this.die=await new Die({number:this.number,faces:this.faces,options:this.options}).evaluate({async:!0}),this._evaluated=!0,this}toJSON(){return this.die?this.die.toJSON():typeof this.number=="number"&&typeof this.faces=="number"?Die.fromData({class:"Die",number:this.number,faces:this.faces,evaluated:this._evaluated,options:this.options}):{...super.toJSON(),number:typeof this.number=="number"?this.number:this.number.toJSON(),faces:typeof this.faces=="number"?this.faces:this.faces.toJSON()}}};__name2(_IntermediateDie,"IntermediateDie"),__publicField(_IntermediateDie,"SERIALIZE_ATTRIBUTES",["number","faces","die"]);let IntermediateDie=_IntermediateDie;const _InstancePool=class extends PoolTerm{static{__name(this,"_InstancePool")}static fromRolls(rolls=[]){const allEvaluated=rolls.every(r=>r._evaluated),noneEvaluated=!rolls.some(r=>r._evaluated);if(!(allEvaluated||noneEvaluated))return super.fromRolls(rolls);const pool=new this({terms:rolls.map(r=>r._formula),modifiers:[],rolls,results:allEvaluated?rolls.map(r=>({result:r.total,active:!0})):[]});return pool._evaluated=allEvaluated,pool}};__name2(_InstancePool,"InstancePool");let InstancePool=_InstancePool;const _AbstractDamageRoll=class extends Roll{static{__name(this,"_AbstractDamageRoll")}constructor(formula,data={},options={}){options.critRule=(()=>tupleHasValue(["double-damage","double-dice"],options.critRule)?options.critRule:game.settings.get("pf2e","critRule")==="doubledamage"?"double-damage":"double-dice")(),super(formula,data,options)}static replaceFormulaData(formula,data,options={}){return super.replaceFormulaData(formula.trim(),data,options).replace(/(?{AbstractDamageRoll.parser=function(){function createNumericTerm(number,{flavor=null,truncate=!1}={}){number=truncate?Math.trunc(number):number;const formula=flavor?`${number}[${flavor}]`:number.toString(),obj={class:"NumericTerm",number,formula,evaluated:!1};return flavor&&(obj.options={flavor}),obj}__name(createNumericTerm,"createNumericTerm"),__name2(createNumericTerm,"createNumericTerm");function peg$subclass(child,parent){function C(){this.constructor=child}__name(C,"C"),__name2(C,"C"),C.prototype=parent.prototype,child.prototype=new C}__name(peg$subclass,"peg$subclass"),__name2(peg$subclass,"peg$subclass");function peg$SyntaxError(message,expected,found,location){var self=Error.call(this,message);return Object.setPrototypeOf&&Object.setPrototypeOf(self,peg$SyntaxError.prototype),self.expected=expected,self.found=found,self.location=location,self.name="SyntaxError",self}__name(peg$SyntaxError,"peg$SyntaxError"),__name2(peg$SyntaxError,"peg$SyntaxError"),peg$subclass(peg$SyntaxError,Error);function peg$padEnd(str,targetLength,padString){return padString=padString||" ",str.length>targetLength?str:(targetLength-=str.length,padString+=padString.repeat(targetLength),str+padString.slice(0,targetLength))}__name(peg$padEnd,"peg$padEnd"),__name2(peg$padEnd,"peg$padEnd"),peg$SyntaxError.prototype.format=function(sources){var str="Error: "+this.message;if(this.location){var src=null,k;for(k=0;k!!s?.proficient);new Dialog({title:"Earn Income",content:askSkillPopupTemplate(skills),buttons:{no:{icon:fontAwesomeIcon("times").outerHTML,label:"Cancel"},yes:{icon:fontAwesomeIcon("coins").outerHTML,label:"Earn Income",callback:($html,event)=>{const html=$html[0],level=Number(html.querySelector("[name=level]")?.value)||0,days=Number(html.querySelector("[name=days]")?.value)||1,skillAcronym=html.querySelector("[name=skillAcronym]")?.value??"soc",skill=skills.find(s=>s.slug===skillAcronym);if(!skill)throw ErrorPF2e("Skill not found");localStorage.setItem("earnIncomeLevel",level.toString()),localStorage.setItem("earnIncomeDays",days.toString()),localStorage.setItem("earnIncomeSkillAcronym",skillAcronym),runEarnIncome({actor,event,skill,level,days})}}},default:"yes"}).render(!0)}__name(showEarnIncomePopup,"showEarnIncomePopup"),__name2(showEarnIncomePopup,"showEarnIncomePopup");function createDamageFormula(damage,degree=DEGREE_OF_SUCCESS.SUCCESS){if(damage=deepClone(damage),degree===DEGREE_OF_SUCCESS.CRITICAL_FAILURE)return null;degree===DEGREE_OF_SUCCESS.FAILURE&&(damage.dice=damage.dice.filter(d=>d.category==="splash"),damage.modifiers=damage.modifiers.filter(m=>m.damageCategory==="splash"));const critical=degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS;if(!damage.base.length)return null;const typeMap=new Map;for(const baseEntry of damage.base){const list=typeMap.get(baseEntry.damageType)??[];if(typeMap.set(baseEntry.damageType,list),baseEntry.terms)list.push(...baseEntry.terms.map(t=>({...baseEntry,...t,label:null,critical:null})));else if(baseEntry.diceNumber&&baseEntry.dieSize||baseEntry.modifier){const{diceNumber,dieSize,damageType}=baseEntry,modifier=baseEntry.modifier??0,label=(()=>{const diceSection=diceNumber?`${diceNumber}${dieSize}`:null;if(!diceSection)return String(modifier);const displayedModifier=modifier?Math.abs(modifier):null,operator=modifier<0?" - ":" + ";return[diceSection,displayedModifier].filter(p=>p!==null).join(operator)})();list.push({label,dice:diceNumber&&dieSize?{number:diceNumber,faces:Number(dieSize.replace("d",""))}:null,modifier,critical:null,damageType,category:baseEntry.category,materials:baseEntry.materials??[]})}}const BONUS_BASE_LABELS=["PF2E.ConditionTypePersistent"].map(l=>game.i18n.localize(l)),outcomeMatches=__name2(m=>critical||m.critical!==!0,"outcomeMatches");for(const dice of damage.dice.filter(d=>d.enabled&&outcomeMatches(d))){const matchingBase=damage.base.find(b=>b.damageType===dice.damageType)??damage.base[0],baseDieSize=Number(matchingBase.dieSize?.replace("d",""))||matchingBase.terms?.[0].dice?.faces,faces=Number(dice.dieSize?.replace("d",""))||baseDieSize||null,damageType=dice.damageType??matchingBase.damageType;if(dice.diceNumber>0&&faces){const list=typeMap.get(damageType)??[];list.push({label:BONUS_BASE_LABELS.includes(dice.label)?null:`${dice.label} +${dice.diceNumber}d${faces}`,dice:{number:dice.diceNumber,faces},modifier:0,damageType,category:dice.category,critical:dice.critical}),typeMap.set(damageType,list)}}for(const modifier of damage.modifiers.filter(m=>m.enabled&&outcomeMatches(m))){const bonusableDamage=[...damage.base,...damage.dice,...damage.modifiers.filter(m=>m.value>0&&m.type==="untyped")],matchingDamage=modifier.kind==="modifier"?bonusableDamage.find(b=>b.damageType===(modifier.damageType??b.damageType))??damage.base.at(0):bonusableDamage.find(b=>b.damageType===(modifier.damageType??b.damageType)&&b.category===modifier.category);if(!matchingDamage)continue;const damageType=modifier.damageType??matchingDamage.damageType??"untyped",list=typeMap.get(damageType)??[];list.push({label:BONUS_BASE_LABELS.includes(modifier.label)?null:`${modifier.label} ${signedInteger(modifier.value)}`,dice:null,modifier:modifier.value,damageType,category:modifier.damageCategory,critical:modifier.critical}),typeMap.set(damageType,list)}const instances=[instancesFromTypeMap(typeMap,{degree}),instancesFromTypeMap(typeMap,{degree,persistent:!0})].flat(),commaSeparated=instances.map(i=>i.formula).join(","),breakdown=instances.flatMap(i=>i.breakdown);return{formula:`{${commaSeparated}}`,breakdown}}__name(createDamageFormula,"createDamageFormula"),__name2(createDamageFormula,"createDamageFormula");function instancesFromTypeMap(typeMap,{degree,persistent=!1}){return Array.from(typeMap.entries()).flatMap(([damageType,typePartials])=>{const partials=typePartials.filter(p=>p.category==="persistent"===persistent);if(partials.length===0)return[];const groups=groupBy(partials,partial=>partial.category),nonCriticalDamage=(()=>{const criticalInclusion=degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS?[CRITICAL_INCLUSION.DOUBLE_ON_CRIT]:[CRITICAL_INCLUSION.DOUBLE_ON_CRIT,CRITICAL_INCLUSION.DONT_DOUBLE_ON_CRIT],doubleDice=degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS&&criticalInclusion.includes(null)&&game.settings.get("pf2e","critRule")==="doubledice",double=degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS&&!doubleDice;return sumExpression(createPartialFormulas(groups,{criticalInclusion,doubleDice}),{double})})(),criticalDamage=(()=>{if(degree!==DEGREE_OF_SUCCESS.CRITICAL_SUCCESS)return null;const criticalInclusion=[CRITICAL_INCLUSION.CRITICAL_ONLY,CRITICAL_INCLUSION.DONT_DOUBLE_ON_CRIT];return sumExpression(createPartialFormulas(groups,{criticalInclusion}))})(),summedDamage=sumExpression(degree?[nonCriticalDamage,criticalDamage]:[nonCriticalDamage]),enclosed=ensureValidFormulaHead(summedDamage)||"0";if(enclosed==="0"&&persistent)return[];const flavor=(()=>{const typeFlavor=damageType==="untyped"&&!persistent?[]:[damageType],persistentFlavor=persistent?["persistent"]:[],materialFlavor=typePartials.flatMap(p=>p.materials??[]),allFlavor=[typeFlavor,persistentFlavor,materialFlavor].flat().join(",");return allFlavor.length>0?`[${allFlavor}]`:""})(),breakdown=(()=>{const flattenedDamage=[null,"persistent","precision","splash"].flatMap(c=>{const partials2=groups.get(c)??[],breakdownDamage2=partials2.filter(e=>e.label!==null),leadingTerms=partials2.filter(p=>p.label===null&&(p.modifier||p.dice?.number||partials2.every(pp=>pp.label===null)));if(leadingTerms.length){const append=c==="splash"?` ${game.i18n.localize("PF2E.Damage.RollFlavor.splash")}`:"",label=createSimpleFormula(leadingTerms)+append;breakdownDamage2.unshift({...leadingTerms[0],label})}return breakdownDamage2}),breakdownDamage=flattenedDamage.filter(d=>d.critical!==!0);if(degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS&&breakdownDamage.push(...flattenedDamage.filter(d=>d.critical===!0)),!breakdownDamage.length)return[];const damageTypeLabel=breakdownDamage[0].category==="persistent"?game.i18n.format("PF2E.Damage.PersistentTooltip",{damageType:game.i18n.localize(CONFIG.PF2E.damageTypes[damageType]??damageType)}):game.i18n.localize(CONFIG.PF2E.damageTypes[damageType]??damageType),labelParts=breakdownDamage.map(d=>d.label);return labelParts[0]=`${labelParts[0].replace(/^\s+\+/,"")} ${damageTypeLabel}`,labelParts})(),formula=enclosed&&flavor?`${enclosed}${flavor}`:enclosed;return formula?{formula,breakdown}:[]})}__name(instancesFromTypeMap,"instancesFromTypeMap"),__name2(instancesFromTypeMap,"instancesFromTypeMap");function createPartialFormulas(partials,{criticalInclusion,doubleDice=!1}){return[null,"persistent","precision","splash"].flatMap(category=>{const requestedPartials=(partials.get(category)??[]).filter(p=>criticalInclusion.includes(p.critical)),term=(()=>{const expression=createSimpleFormula(requestedPartials,{doubleDice});return expression==="0"?"":["precision","splash"].includes(category??"")&&hasOperators(expression)?`(${expression})`:expression})();return(term&&category&&category!=="persistent"?term.endsWith("]")?`(${term})[${category}]`:`${term}[${category}]`:term)||[]})}__name(createPartialFormulas,"createPartialFormulas"),__name2(createPartialFormulas,"createPartialFormulas");function combinePartialTerms(terms){const modifier=terms.reduce((total,p)=>total+p.modifier,0),constantTerm=modifier?{dice:null,modifier}:null,dice=terms.filter(p=>!!p.dice&&p.dice.number>0).sort(sortBy(t=>-t.dice.faces)),combinedDice=[...groupBy(dice,t=>t.dice.faces).values()].map(terms2=>({modifier:0,dice:{...terms2[0].dice,number:sum(terms2.map(d=>d.dice.number))}})),combined=compact([...combinedDice,constantTerm]);return combined.length?combined:[{dice:null,modifier:0}]}__name(combinePartialTerms,"combinePartialTerms"),__name2(combinePartialTerms,"combinePartialTerms");function createSimpleFormula(terms,{doubleDice}={}){terms=combinePartialTerms(terms);const constant=terms.find(t=>!!t.modifier)?.modifier??0;return[terms.filter(t=>!!t.dice&&t.dice.number>0).map(term=>{const number=doubleDice?term.dice.number*2:term.dice.number,faces=term.dice.faces;return doubleDice?`${number}d${faces}[doubled]`:`${number}d${faces}`}).join(" + "),Math.abs(constant)].filter(e=>!!e).map(e=>typeof e=="number"&&doubleDice?`2 * ${e}`:e).join(constant>0?" + ":" - ")||"0"}__name(createSimpleFormula,"createSimpleFormula"),__name2(createSimpleFormula,"createSimpleFormula");function parseTermsFromSimpleFormula(formula,options){return(formula instanceof Roll?formula:new Roll(formula,options?.rollData)).terms.reduceRight((result,term)=>{if(term.expression===" + ")return result;if(term.expression===" - "){const termToModify=result[0];return termToModify&&(termToModify.modifier&&(termToModify.modifier*=-1),termToModify.dice&&(termToModify.dice.number*=-1)),result}return result.unshift({modifier:term instanceof NumericTerm?term.number:0,dice:term instanceof Die?{faces:term.faces,number:term.number}:null}),result},[])}__name(parseTermsFromSimpleFormula,"parseTermsFromSimpleFormula"),__name2(parseTermsFromSimpleFormula,"parseTermsFromSimpleFormula");function sumExpression(terms,{double=!1}={}){if(terms.every(t=>!t))return null;const summed=terms.filter(p=>!!p).join(" + ")||null,enclosed=double&&hasOperators(summed)?`(${summed})`:summed;return double?`2 * ${enclosed}`:enclosed}__name(sumExpression,"sumExpression"),__name2(sumExpression,"sumExpression");function hasOperators(formula){return/[-+*/]/.test(formula??"")}__name(hasOperators,"hasOperators"),__name2(hasOperators,"hasOperators");function ensureValidFormulaHead(formula){if(!formula)return null;const isWrapped=/^\(.*\)$/.test(formula),isSimple=/^\d+(d\d+)?$/.test(formula);return isWrapped||isSimple?formula:`(${formula})`}__name(ensureValidFormulaHead,"ensureValidFormulaHead"),__name2(ensureValidFormulaHead,"ensureValidFormulaHead");const _ArithmeticExpression=class _ArithmeticExpression2 extends RollTerm{static{__name(this,"_ArithmeticExpression")}operator;operands;constructor(termData){super(termData),this.operator=termData.operator,this.operands=termData.operands.slice(0,2).map(datum=>{if(datum instanceof RollTerm)return datum;const TermCls=CONFIG.Dice.termTypes[datum.class??""]??Object.values(CONFIG.Dice.terms).find(t=>t.name===datum.class)??Die;return simplifyTerm(TermCls.fromData(datum))}),this.operator==="*"&&this.operands[0]instanceof NumericTerm&&tupleHasValue([2,3],this.operands[0].number)&&markAsCrit(this.operands[1],this.operands[0].number)}static fromData(data){return super.fromData({...data,class:"ArithmeticExpression"})}static totalOf(operator,left,right){if(!(left===void 0||right===void 0))switch(operator){case"+":return left+right;case"-":return left-right;case"*":return left*right;case"/":return left/right;case"%":return left%right}}get dice(){return this.operands.flatMap(o=>o instanceof DiceTerm?o:o instanceof Grouping||o instanceof _ArithmeticExpression2||o instanceof IntermediateDie?o.dice:[])}get expression(){if(this.isDeterministic&&typeof this.total=="number"&&!Number.isNaN(this.total)&&!isFlavoredArithmetic(this))return this.total.toString();const{operator,operands}=this;return`${operands[0].expression} ${operator} ${operands[1].expression}`}get formula(){const{operator,operands}=this;return`${operands[0].formula} ${operator} ${operands[1].formula}`}get total(){if(!this._evaluated&&!this.isDeterministic)return;const operands=[Number(this.operands[0].total),Number(this.operands[1].total)];return _ArithmeticExpression2.totalOf(this.operator,...operands)}get critImmuneTotal(){if(!this._evaluated)return;const[left,right]=this.operands;if(left instanceof NumericTerm&&left.number===2&&this.operator==="*")return typeof right.total=="string"?Number(right.total):right.total;const undoubledLeft=(()=>left instanceof _ArithmeticExpression2||left instanceof Grouping?Number(left.critImmuneTotal):Number(left.total))(),undoubledRight=right instanceof _ArithmeticExpression2||right instanceof Grouping?Number(right.critImmuneTotal):Number(right.total);return _ArithmeticExpression2.totalOf(this.operator,undoubledLeft,undoubledRight)}get isDeterministic(){return this.operands.every(o=>o.isDeterministic)}get minimumValue(){const left=DamageInstance.getValue(this.operands[0],"minimum"),right=DamageInstance.getValue(this.operands[1],"minimum");return _ArithmeticExpression2.totalOf(this.operator,left,right)}get expectedValue(){const left=DamageInstance.getValue(this.operands[0]),right=DamageInstance.getValue(this.operands[1]);return _ArithmeticExpression2.totalOf(this.operator,left,right)}get maximumValue(){const left=DamageInstance.getValue(this.operands[0],"maximum"),right=DamageInstance.getValue(this.operands[1],"maximum");return _ArithmeticExpression2.totalOf(this.operator,left,right)}render(){const fragment=new DocumentFragment,{operator,operands}=this;if(operator==="*"&&operands[0]instanceof NumericTerm&&operands[1]instanceof NumericTerm)return fragment.append((operands[0].total*operands[1].total).toString()),fragment;const[left,right]=operands.map(o=>["precision","splash"].includes(o.flavor)?renderComponentDamage(o):isSystemDamageTerm(o)?o.render():o.expression);return fragment.append(left,` ${this.operator} `,right),fragment}async _evaluate(options={}){for(const operand of this.operands)operand._evaluated||await operand.evaluate({async:!0,...options});return this._evaluated=!0,this}toJSON(){return{...super.toJSON(),operands:[this.operands[0].toJSON(),this.operands[1].toJSON()]}}};__name2(_ArithmeticExpression,"ArithmeticExpression"),__publicField(_ArithmeticExpression,"SERIALIZE_ATTRIBUTES",["operator","operands"]);let ArithmeticExpression=_ArithmeticExpression;const _Grouping=class _Grouping2 extends RollTerm{static{__name(this,"_Grouping")}term;constructor(termData){const TermCls=CONFIG.Dice.termTypes[termData.term.class??""]??Object.values(CONFIG.Dice.terms).find(t=>t.name===termData.term.class)??NumericTerm,childTerm=simplifyTerm(TermCls.fromData(termData.term));childTerm instanceof _Grouping2?(super(childTerm.toJSON()),this.term=childTerm.term):(super(termData),this.term=childTerm),this._evaluated=termData.evaluated??this.term._evaluated??!0}static fromData(data){return super.fromData({...data,class:"Grouping"})}get dice(){if(this.term instanceof DiceTerm)return[this.term];if(isObject(this.term)&&"dice"in this.term){const{dice}=this.term;if(Array.isArray(dice)&&dice.every(d=>d instanceof DiceTerm))return dice}return[]}get expression(){return this.isDeterministic&&typeof this.total=="number"&&!Number.isNaN(this.total)&&!isFlavoredArithmetic(this.term)?this.total.toString():this.term instanceof DiceTerm||this.term instanceof MathTerm?this.term.expression:`(${this.term.expression})`}get formula(){const termFormula=this.term.formula,flavor=this.flavor?`[${this.flavor}]`:"";return`(${termFormula})${flavor}`}get total(){return this._evaluated||this.isDeterministic?Number(this.term.total):void 0}get critImmuneTotal(){return this.term instanceof ArithmeticExpression||this.term instanceof _Grouping2?this.term.critImmuneTotal:this.total}get isDeterministic(){return this.term.isDeterministic}get minimumValue(){return DamageInstance.getValue(this.term,"minimum")}get expectedValue(){return DamageInstance.getValue(this.term)}get maximumValue(){return DamageInstance.getValue(this.term,"maximum")}async _evaluate(options={}){return this.term._evaluated||await this.term.evaluate({async:!0,...options}),this._evaluated=!0,this}toJSON(){return{...super.toJSON(),term:this.term.toJSON()}}render(){const expression=["precision","splash"].includes(this.flavor)?renderComponentDamage(this.term):isSystemDamageTerm(this.term)?this.term.render():this.expression,fragment=new DocumentFragment,nodes=this.term instanceof NumericTerm||this.term instanceof Die?[expression]:["(",expression,")"];return fragment.append(...nodes),fragment}};__name2(_Grouping,"Grouping"),__publicField(_Grouping,"SERIALIZE_ATTRIBUTES",["term"]);let Grouping=_Grouping;const _IntermediateDie=class extends RollTerm{static{__name(this,"_IntermediateDie")}number;faces;die;constructor(data){super(data);const setTerm=__name2(termData=>{if(typeof termData=="number")return termData;const TermCls=CONFIG.Dice.termTypes[termData.class??"NumericTerm"],term=simplifyTerm(TermCls.fromData(termData));return term instanceof NumericTerm?term.number:term.isDeterministic?Roll.safeEval(term.formula):term instanceof Grouping?(term.isIntermediate=!0,term):(term instanceof MathTerm||console.warn(`Unexpected term type: ${term.constructor.name}`),term)},"setTerm");this.number=setTerm(data.number),this.faces=setTerm(data.faces),this.die=(()=>data.die?Die.fromData({...data.die,class:"Die"}):typeof this.number=="number"&&typeof this.faces=="number"?Die.fromData({number:this.number,faces:this.faces,evaluated:this._evaluated,options:this.options}):null)()}get expression(){return this.die?.expression??`${this.number}d${this.faces}`}get total(){return this.isDeterministic?Number(this.number)*Number(this.faces):this.die?.total}get dice(){return this.die?[this.die]:[]}get isDeterministic(){return this.number===0||this.faces===0||this.faces===1}get minimumValue(){return DamageInstance.getValue(this.die??new Die({number:Number(this.number),faces:Number(this.faces)}),"minimum")}get expectedValue(){return DamageInstance.getValue(this.die??new Die({number:Number(this.number),faces:Number(this.faces)}))}get maximumValue(){return DamageInstance.getValue(this.die??new Die({number:Number(this.number),faces:Number(this.faces)}),"maximum")}async _evaluate(){return typeof this.number!="number"&&(this.number=(await this.number.evaluate({async:!0})).total),typeof this.faces!="number"&&(this.faces=(await this.faces.evaluate({async:!0})).total),this.die=await new Die({number:this.number,faces:this.faces,options:this.options}).evaluate({async:!0}),this._evaluated=!0,this}toJSON(){return this.die?this.die.toJSON():typeof this.number=="number"&&typeof this.faces=="number"?Die.fromData({class:"Die",number:this.number,faces:this.faces,evaluated:this._evaluated,options:this.options}):{...super.toJSON(),number:typeof this.number=="number"?this.number:this.number.toJSON(),faces:typeof this.faces=="number"?this.faces:this.faces.toJSON()}}};__name2(_IntermediateDie,"IntermediateDie"),__publicField(_IntermediateDie,"SERIALIZE_ATTRIBUTES",["number","faces","die"]);let IntermediateDie=_IntermediateDie;const _InstancePool=class extends PoolTerm{static{__name(this,"_InstancePool")}static fromRolls(rolls=[]){const allEvaluated=rolls.every(r=>r._evaluated),noneEvaluated=!rolls.some(r=>r._evaluated);if(!(allEvaluated||noneEvaluated))return super.fromRolls(rolls);const pool=new this({terms:rolls.map(r=>r._formula),modifiers:[],rolls,results:allEvaluated?rolls.map(r=>({result:r.total,active:!0})):[]});return pool._evaluated=allEvaluated,pool}};__name2(_InstancePool,"InstancePool");let InstancePool=_InstancePool;const _AbstractDamageRoll=class extends Roll{static{__name(this,"_AbstractDamageRoll")}constructor(formula,data={},options={}){options.critRule=(()=>tupleHasValue(["double-damage","double-dice"],options.critRule)?options.critRule:game.settings.get("pf2e","critRule")==="doubledamage"?"double-damage":"double-dice")(),super(formula,data,options)}static replaceFormulaData(formula,data,options={}){return super.replaceFormulaData(formula.trim(),data,options).replace(/(?{AbstractDamageRoll.parser=function(){function createNumericTerm(number,{flavor=null,truncate=!1}={}){number=truncate?Math.trunc(number):number;const formula=flavor?`${number}[${flavor}]`:number.toString(),obj={class:"NumericTerm",number,formula,evaluated:!1};return flavor&&(obj.options={flavor}),obj}__name(createNumericTerm,"createNumericTerm"),__name2(createNumericTerm,"createNumericTerm");function peg$subclass(child,parent){function C(){this.constructor=child}__name(C,"C"),__name2(C,"C"),C.prototype=parent.prototype,child.prototype=new C}__name(peg$subclass,"peg$subclass"),__name2(peg$subclass,"peg$subclass");function peg$SyntaxError(message,expected,found,location){var self=Error.call(this,message);return Object.setPrototypeOf&&Object.setPrototypeOf(self,peg$SyntaxError.prototype),self.expected=expected,self.found=found,self.location=location,self.name="SyntaxError",self}__name(peg$SyntaxError,"peg$SyntaxError"),__name2(peg$SyntaxError,"peg$SyntaxError"),peg$subclass(peg$SyntaxError,Error);function peg$padEnd(str,targetLength,padString){return padString=padString||" ",str.length>targetLength?str:(targetLength-=str.length,padString+=padString.repeat(targetLength),str+padString.slice(0,targetLength))}__name(peg$padEnd,"peg$padEnd"),__name2(peg$padEnd,"peg$padEnd"),peg$SyntaxError.prototype.format=function(sources){var str="Error: "+this.message;if(this.location){var src=null,k;for(k=0;k `+loc+` `+filler+` | `+offset_s.line+" | "+line+` @@ -56,8 +56,10 @@ var __defProp=Object.defineProperty;var __name=(target,value)=>__defProp(target, `,buttons:{yes:{icon:fontAwesomeIcon("hand-holding-medical").outerHTML,label:localize("Title"),callback:applyChanges},no:{icon:fontAwesomeIcon("times").outerHTML,label:localize("Cancel")}},default:"yes"}).render(!0)}__name(encouragingWords,"encouragingWords"),__name2(encouragingWords,"encouragingWords");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();consumableSource.system.traits.value.push(...spell.traditions),consumableSource.name=getNameForSpellConsumable(type,spell.name,heightenedLevel);const description=consumableSource.system.description.value;return consumableSource.system.description.value=(()=>{const paragraphElement=document.createElement("p"),linkElement=document.createElement("em");linkElement.append(spell.sourceId?`@UUID[${spell.sourceId}]{${spell.name}}`:spell.description),paragraphElement.append(linkElement);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={proficiencyWithoutLevel:!1}){const level=Number(item.level),saveDC=calculateDC(level,options),skills=item.system.traits.value.filter(t=>setHasElement(MAGIC_TRADITIONS,t)).map(tradition=>[traditionSkills[tradition],saveDC]);return Object.fromEntries(skills)}__name(calculateTrickMagicItemCheckDC,"calculateTrickMagicItemCheckDC"),__name2(calculateTrickMagicItemCheckDC,"calculateTrickMagicItemCheckDC");const WEAPON_CATEGORIES=new Set(["unarmed","simple","martial","advanced"]),MELEE_OR_RANGED_GROUPS=new Set(["dart","knife"]),MELEE_WEAPON_GROUPS=new Set([...MELEE_OR_RANGED_GROUPS,"axe","brawling","club","flail","hammer","pick","polearm","shield","spear","sword"]),MANDATORY_RANGED_GROUPS=new Set(["bomb","bow","firearm","sling"]);[...MELEE_WEAPON_GROUPS,...MANDATORY_RANGED_GROUPS];const THROWN_RANGES=new Set([10,15,20,30,40,60,80,100]),WEAPON_RANGES=new Set([...THROWN_RANGES,50,70,90,110,120,140,150,180,200,240,300]),CROSSBOW_WEAPONS=new Set(["arbalest","alchemical-crossbow","crossbow","hand-crossbow","heavy-crossbow","repeating-crossbow","repeating-hand-crossbow","repeating-heavy-crossbow","taw-launcher"]);function isRelevantEvent(event){return!!event&&"ctrlKey"in event&&"metaKey"in event&&"shiftKey"in event}__name(isRelevantEvent,"isRelevantEvent"),__name2(isRelevantEvent,"isRelevantEvent");function eventToRollParams(event){const skipDefault=!game.user.settings.showRollDialogs;if(!isRelevantEvent(event))return{skipDialog:skipDefault};const params={skipDialog:event.shiftKey?!skipDefault:skipDefault};return(event.ctrlKey||event.metaKey)&&(params.rollMode=game.user.isGM?"gmroll":"blindroll"),params}__name(eventToRollParams,"eventToRollParams"),__name2(eventToRollParams,"eventToRollParams");function calculateDaysToNoCost(costs){return Math.ceil((costs.itemPrice.copperValue-costs.materials.copperValue)/costs.reductionPerDay.copperValue)}__name(calculateDaysToNoCost,"calculateDaysToNoCost"),__name2(calculateDaysToNoCost,"calculateDaysToNoCost");async function prepStrings(costs,item){const rollData=item.getRollData();return{reductionPerDay:costs.reductionPerDay.toString(),materialCost:game.i18n.format("PF2E.Actions.Craft.Details.PayMaterials",{cost:costs.materials.toString()}),itemCost:game.i18n.format("PF2E.Actions.Craft.Details.PayFull",{cost:costs.itemPrice.toString()}),lostMaterials:game.i18n.format("PF2E.Actions.Craft.Details.LostMaterials",{cost:costs.lostMaterials.toString()}),itemLink:await TextEditor.enrichHTML(item.link,{rollData,async:!0})}}__name(prepStrings,"prepStrings"),__name2(prepStrings,"prepStrings");function calculateCosts(item,quantity,actor,degreeOfSuccess){const itemPrice=CoinsPF2e.fromPrice(item.price,quantity),materialCosts=itemPrice.scale(.5),lostMaterials=new CoinsPF2e,reductionPerDay=new CoinsPF2e,proficiency=actor.skills.crafting.rank;return proficiency?(degreeOfSuccess===DegreeOfSuccess.CRITICAL_SUCCESS?Object.assign(reductionPerDay,getIncomeForLevel(actor.level+1).rewards[proficiency]):degreeOfSuccess===DegreeOfSuccess.SUCCESS?Object.assign(reductionPerDay,getIncomeForLevel(actor.level).rewards[proficiency]):degreeOfSuccess===DegreeOfSuccess.CRITICAL_FAILURE&&Object.assign(lostMaterials,materialCosts.scale(.1)),{itemPrice,materials:materialCosts,lostMaterials,reductionPerDay}):null}__name(calculateCosts,"calculateCosts"),__name2(calculateCosts,"calculateCosts");async function craftItem(item,itemQuantity,actor,infused){const itemSource=item.toObject();itemSource.system.quantity=itemQuantity,itemSource.system.size=actor.size==="tiny"?"tiny":"med";const itemTraits=item.traits;if(infused&&itemTraits.has("alchemical")&&itemTraits.has("consumable")&&(itemSource.system.traits.value.push("infused"),itemSource.system.temporary=!0),!await actor.addToInventory(itemSource)){ui.notifications.warn(game.i18n.localize("PF2E.Actions.Craft.Warning.CantAddItem"));return}await ChatMessagePF2e.create({user:game.user.id,content:game.i18n.format("PF2E.Actions.Craft.Information.ReceiveItem",{actorName:actor.name,quantity:itemQuantity,itemName:item.name}),speaker:{alias:actor.name}})}__name(craftItem,"craftItem"),__name2(craftItem,"craftItem");async function craftSpellConsumable(item,itemQuantity,actor){const consumableType=item.category;if(!(consumableType==="scroll"||consumableType==="wand"))return;const spellLevel=consumableType==="wand"?Math.ceil(item.level/2)-1:Math.ceil(item.level/2),validSpells=actor.itemTypes.spell.filter(s=>s.baseRank<=spellLevel&&!s.isCantrip&&!s.isFocusSpell&&!s.isRitual).reduce((result,spell)=>(result[spell.baseRank]=[...result[spell.baseRank]||[],spell],result),{}),content=await renderTemplate("systems/pf2e/templates/actors/crafting-select-spell-dialog.hbs",{spells:validSpells});new Dialog({title:game.i18n.localize("PF2E.Actions.Craft.SelectSpellDialog.Title"),content,buttons:{cancel:{icon:'',label:game.i18n.localize("Cancel")},craft:{icon:'',label:game.i18n.localize("PF2E.Actions.Craft.SelectSpellDialog.CraftButtonLabel"),callback:async $dialog=>{const spellId=String($dialog.find("select[name=spell]").val()),spell=actor.items.get(spellId);if(!spell?.isOfType("spell"))return;const item2=await createConsumableFromSpell(spell,{type:consumableType,heightenedLevel:spellLevel});return craftItem(new ConsumablePF2e(item2),itemQuantity,actor)}}},default:"craft"}).render(!0)}__name(craftSpellConsumable,"craftSpellConsumable"),__name2(craftSpellConsumable,"craftSpellConsumable");async function renderCraftingInline(item,roll,quantity,actor,free){if(!actor.isOfType("character"))return null;const degreeOfSuccess=roll.options.degreeOfSuccess??0,costs=calculateCosts(item,quantity,actor,degreeOfSuccess);if(!costs)return null;const daysForZeroCost=degreeOfSuccess>1?calculateDaysToNoCost(costs):0;return await renderTemplate("systems/pf2e/templates/chat/crafting-result.hbs",{daysForZeroCost,strings:await prepStrings(costs,item),item,quantity,success:degreeOfSuccess>1,criticalFailure:degreeOfSuccess===0,free})}__name(renderCraftingInline,"renderCraftingInline"),__name2(renderCraftingInline,"renderCraftingInline");const _RollNotePF2e=class _RollNotePF2e2{static{__name(this,"_RollNotePF2e")}selector;title;text;predicate;outcome;visibility;rule;constructor(params){this.selector=params.selector,this.title=params.title??null,this.text=params.text,this.predicate=new PredicatePF2e(params.predicate??[]),this.outcome=[...params.outcome??[]],this.visibility=params.visibility??null,this.rule=params.rule??null}static notesToHTML(notes){return createHTMLElement("ul",{classes:["notes"],children:notes.flatMap(n=>[` -`,n.toHTML()]).slice(1)})}toHTML(){const element=createHTMLElement("li",{classes:["roll-note"],dataset:{itemId:this.rule?.item.id,visibility:this.visibility},innerHTML:game.i18n.localize(this.text)});if(element.childNodes.length===1&&element.firstChild instanceof HTMLElement&&(element.innerHTML=element.firstChild.innerHTML),this.title){const strong=createHTMLElement("strong",{innerHTML:game.i18n.localize(this.title)});element.prepend(strong," ")}return element}clone(){return new _RollNotePF2e2({...this.toObject(),rule:this.rule})}toObject(){return{selector:this.selector,title:this.title,text:this.text,predicate:this.predicate.toObject(),outcome:this.outcome,visibility:this.visibility}}};__name2(_RollNotePF2e,"RollNotePF2e");let RollNotePF2e=_RollNotePF2e;function normalizeActionChangeData(document2,changed){if(changed.system&&("actionType"in changed.system||"actions"in changed.system)){const actionType=changed.system?.actionType?.value??document2.system.actionType.value,actionCount=Number(changed.system?.actions?.value??document2.system.actions.value);changed.system=mergeObject(changed.system,{actionType:{value:actionType},actions:{value:actionType!=="action"?null:Math.clamped(actionCount,1,3)}})}}__name(normalizeActionChangeData,"normalizeActionChangeData"),__name2(normalizeActionChangeData,"normalizeActionChangeData");function activateActionSheetListeners(item,html){htmlQuery(html,"a[data-action=frequency-add]")?.addEventListener("click",()=>{const frequency={max:1,per:"day"};item.update({system:{frequency}})}),htmlQuery(html,"a[data-action=frequency-delete]")?.addEventListener("click",()=>{item.update({"system.-=frequency":null})}),item.isOfType("action","feat")&&htmlQuery(html,"a[data-action=delete-effect]")?.addEventListener("click",()=>{item._source.system.selfEffect&&item.update({"system.-=selfEffect":null})})}__name(activateActionSheetListeners,"activateActionSheetListeners"),__name2(activateActionSheetListeners,"activateActionSheetListeners");function createSelfEffectSheetData(data){if(!data)return null;const indexEntry=fromUuidSync(data.uuid);indexEntry?.name&&isImageFilePath(indexEntry.img)&&(data.name=indexEntry.name,data.img=indexEntry.img);const parsedUUID=foundry.utils.parseUuid(data.uuid),linkData={id:parsedUUID.documentId??null,type:parsedUUID.documentType??null,pack:parsedUUID.collection instanceof CompendiumCollection?parsedUUID.collection.metadata.id:null};return{...data,...linkData}}__name(createSelfEffectSheetData,"createSelfEffectSheetData"),__name2(createSelfEffectSheetData,"createSelfEffectSheetData");async function handleSelfEffectDrop(sheet,event){if(!sheet.isEditable||sheet.item.system.actionType.value==="passive")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))throw ErrorPF2e("Invalid item drop");await sheet.item.update({"system.selfEffect":{uuid:item.uuid,name:item.name}})}__name(handleSelfEffectDrop,"handleSelfEffectDrop"),__name2(handleSelfEffectDrop,"handleSelfEffectDrop");function createActionRangeLabel(range){if(!range?.max)return null;const[key,value]=range.increment?["PF2E.Action.Range.IncrementN",range.increment]:["PF2E.Action.Range.MaxN",range.max];return game.i18n.format(key,{n:value})}__name(createActionRangeLabel,"createActionRangeLabel"),__name2(createActionRangeLabel,"createActionRangeLabel");var LightLevels=(LightLevels2=>(LightLevels2[LightLevels2.DARKNESS=.25]="DARKNESS",LightLevels2[LightLevels2.BRIGHT_LIGHT=.75]="BRIGHT_LIGHT",LightLevels2))(LightLevels||{});let auraCheckLock=Promise.resolve();const checkAuras=foundry.utils.debounce(async function(){if(!(canvas.ready&&this.isInFocus&&this.grid.type===CONST.GRID_TYPES.SQUARE))return;await auraCheckLock;const lock={release:()=>{}};auraCheckLock=new Promise(resolve=>{lock.release=resolve});try{const tokens=this.tokens.reduce((list,token)=>(token.isLinked&&list.some(t=>t.actor===token.actor)||list.push(token),list),[]);for(const token of tokens)await token.object?._animation;for(const aura of tokens.flatMap(t=>Array.from(t.auras.values())))await aura.notifyActors();const sceneActors=new Set(tokens.flatMap(t=>t.actor?.primaryUpdater===game.user?t.actor:[]));for(const actor of sceneActors)actor.checkAreaEffects()}finally{lock.release()}},100),_ScenePF2e=class extends Scene{static{__name(this,"_ScenePF2e")}get rulesBasedVision(){return this.tokenVision?this.flags.pf2e.rulesBasedVision??game.settings.get("pf2e","automation.rulesBasedVision"):!1}get hearingRange(){return this.flags.pf2e.hearingRange}get darknessSyncedToTime(){return this.flags.pf2e.syncDarkness==="enabled"||this.flags.pf2e.syncDarkness==="default"&&game.settings.get("pf2e","worldClock.syncDarkness")}get lightLevel(){return 1-this.darkness}get isBright(){return this.lightLevel>=LightLevels.BRIGHT_LIGHT}get isDimlyLit(){return!this.isBright&&!this.isDark}get isDark(){return this.lightLevel<=LightLevels.DARKNESS}get hasHexGrid(){return![CONST.GRID_TYPES.GRIDLESS,CONST.GRID_TYPES.SQUARE].includes(this.grid.type)}get isInFocus(){const soleUserIsGM=game.user.isGM&&game.users.filter(u=>u.active).length===1;return this.active&&!soleUserIsGM||this.isView&&soleUserIsGM}prepareData(){super.prepareData(),Promise.resolve().then(()=>{this.checkAuras()})}prepareBaseData(){super.prepareBaseData(),this.flags.pf2e=mergeObject({hearingRange:null,rulesBasedVision:null,syncDarkness:"default"},this.flags.pf2e??{}),this.rulesBasedVision&&(this.globalLight=!0,this.globalLightThreshold=1-(LightLevels.DARKNESS+.001))}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId);const flagChanges=changed.flags?.pf2e??{};if(this.isView&&["rulesBasedVision","hearingRange"].some(k=>flagChanges[k]!==void 0)&&canvas.perception.update({initializeLighting:!0,initializeVision:!0}),changed.active&&canvas.scene===this)for(const token of canvas.tokens.placeables)token.auras.reset()}_onDeleteDescendantDocuments(parent,collection,documents,ids,options,userId){super._onDeleteDescendantDocuments(parent,collection,documents,ids,options,userId),documents.some(d=>d instanceof TokenDocumentPF2e&&!(d._source.light.dim||d._source.light.bright)&&d.actor?.synthetics.tokenOverrides.light)&&canvas.perception.update({initializeLighting:!0,initializeVision:!0})}};__name2(_ScenePF2e,"ScenePF2e");let ScenePF2e=_ScenePF2e;Object.defineProperty(ScenePF2e.prototype,"checkAuras",{configurable:!1,enumerable:!1,writable:!1,value:checkAuras});const _AmbientLightDocumentPF2e=class extends AmbientLightDocument{static{__name(this,"_AmbientLightDocumentPF2e")}get isDarkness(){return this.object?.source.isDarkness??!1}};__name2(_AmbientLightDocumentPF2e,"AmbientLightDocumentPF2e");let AmbientLightDocumentPF2e=_AmbientLightDocumentPF2e;const _MeasuredTemplateDocumentPF2e=class extends MeasuredTemplateDocument{static{__name(this,"_MeasuredTemplateDocumentPF2e")}get item(){const origin=this.flags.pf2e?.origin,uuid=origin?.uuid;if(!uuid)return null;const item=fromUuidSync(uuid);if(!(item instanceof ItemPF2e))return null;if(item?.isOfType("spell")){const overlayIds=origin?.variant?.overlays,castRank=origin?.castLevel??item.rank;return item.loadVariant({overlayIds,castLevel:castRank})??item}return item}get message(){return game.messages.get(this.flags.pf2e?.messageId??"")??null}_onCreate(data,options,userId){super._onCreate(data,options,userId),toggleClearTemplatesButton(this.message)}_onDelete(options,userId){super._onDelete(options,userId),toggleClearTemplatesButton(this.message)}};__name2(_MeasuredTemplateDocumentPF2e,"MeasuredTemplateDocumentPF2e");let MeasuredTemplateDocumentPF2e=_MeasuredTemplateDocumentPF2e;const _TileDocumentPF2e=class extends TileDocument{static{__name(this,"_TileDocumentPF2e")}};__name2(_TileDocumentPF2e,"TileDocumentPF2e");let TileDocumentPF2e=_TileDocumentPF2e;const _TokenConfigPF2e=class extends TokenConfig{static{__name(this,"_TokenConfigPF2e")}constructor(){super(...arguments),__privateAdd(this,_disableScale),__privateAdd(this,_reestablishPrototype),__privateAdd(this,_disableVisionInputs)}static get defaultOptions(){return{...super.defaultOptions,template:"systems/pf2e/templates/scene/token/sheet.hbs",sheetConfig:!1}}get dimensionsFromActorSize(){const actorSize=this.actor?.size??"med";return{tiny:.5,sm:1,med:1,lg:2,huge:3,grg:4}[actorSize]}async getData(options){return{...await super.getData(options),sizeLinkable:!!this.actor&&SIZE_LINKABLE_ACTOR_TYPES.has(this.actor.type),linkToSizeTitle:this.token.flags.pf2e.linkToActorSize?"Unlink":"Link",autoscaleTitle:this.token.flags.pf2e.autoscale?"Unlink":"Link"}}_getFilePickerOptions(event){return{...super._getFilePickerOptions(event),redirectToRoot:this.actor?[ActorPF2e.getDefaultArtwork(this.actor.toObject()).texture.src]:[]}}activateListeners($html){super.activateListeners($html);const html=$html[0];__privateMethod(this,_disableVisionInputs,disableVisionInputs_fn).call(this,html),this.token.flags.pf2e.autoscale&&__privateMethod(this,_disableScale,disableScale_fn).call(this,html),htmlQuery(html,"a[data-action=toggle-link-to-size]")?.addEventListener("click",async()=>{await this.token.update({"flags.pf2e.linkToActorSize":!this.token.flags.pf2e.linkToActorSize}),__privateMethod(this,_reestablishPrototype,reestablishPrototype_fn).call(this),await this.render()}),htmlQuery(html,"a[data-action=toggle-autoscale]")?.addEventListener("click",async()=>{await this.token.update({"flags.pf2e.autoscale":!this.token.flags.pf2e.autoscale}),__privateMethod(this,_reestablishPrototype,reestablishPrototype_fn).call(this),await this.render()})}_getSubmitData(updateData={}){const changes=updateData??{};return this.form.querySelector("input[name=scale]")?.disabled&&(changes.scale=Math.abs(this.token._source.texture.scaleX)),super._getSubmitData(changes)}async _updateObject(event,formData){if(formData["flags.pf2e.linkToActorSize"]===!0)if(this.actor?.isOfType("vehicle")){const{dimensions}=this.actor,width=Math.max(Math.round(dimensions.width/5),1),length=Math.max(Math.round(dimensions.length/5),1);formData.width=width,formData.height=length}else formData.width=formData.height=this.dimensionsFromActorSize;return super._updateObject(event,formData)}};_disableScale=new WeakSet,disableScale_fn=__name2(function(html){if(!game.settings.get("pf2e","tokens.autoscale"))return;const scale=html.querySelector(".form-group.scale");if(!scale)throw ErrorPF2e("Scale form group missing");scale.classList.add("children-disabled");const constrainedScale=String(this.actor?.size==="sm"?.8:1),rangeInput=scale.querySelector("input[type=range]");if(rangeInput){rangeInput.disabled=!0,rangeInput.value=constrainedScale;const rangeDisplayValue=scale.querySelector(".range-value");rangeDisplayValue&&(rangeDisplayValue.innerHTML=constrainedScale)}},"#disableScale"),_reestablishPrototype=new WeakSet,reestablishPrototype_fn=__name2(function(){if(this.isPrototype&&this.actor){const realPrototype=this.actor.prototypeToken;this.object=this.token=realPrototype}},"#reestablishPrototype"),_disableVisionInputs=new WeakSet,disableVisionInputs_fn=__name2(function(html){if(!(["character","familiar"].includes(this.actor?.type??"")&&(this.token.rulesBasedVision||this.isPrototype&&game.settings.get("pf2e","automation.rulesBasedVision"))))return;const sightInputNames=["angle","brightness","range","saturation","visionMode"].map(n=>`sight.${n}`),sightInputs=Array.from(html.querySelectorAll(sightInputNames.map(n=>`[name="${n}"]`).join(", "))),sightEnabledInput=html.querySelector('input[name="sight.enabled"]');if(!sightEnabledInput)throw ErrorPF2e("sight.enabled input not found");sightEnabledInput.addEventListener("change",()=>{for(const input of sightInputs)if(input.disabled=!sightEnabledInput.checked,input.type==="range")sightEnabledInput.checked?input.closest(".form-group")?.classList.remove("children-disabled"):input.closest(".form-group")?.classList.add("children-disabled");else if(input.name==="sight.color"){const colorInput=input.parentElement?.querySelector("input[type=color]");colorInput&&(colorInput.disabled=!sightEnabledInput.checked)}});for(const input of sightInputs)input.disabled=!0,input.type==="range"&&input.closest(".form-group")?.classList.add("children-disabled");html.querySelector("a.item[data-tab=detection]")?.classList.add("disabled");const managedBy=document.createElement("a");managedBy.className="managed-by-rbv",managedBy.append(fontAwesomeIcon("robot")),managedBy.title=game.i18n.localize("PF2E.SETTINGS.Automation.RulesBasedVision.ManagedBy").replace(/<\/?rbv>/g,"");for(const sightInput of sightInputs){const anchor=managedBy.cloneNode(!0);anchor.addEventListener("click",()=>{const menu=game.settings.menus.get("pf2e.automation");if(!menu)throw ErrorPF2e("Automation Settings application not found");new menu.type().render(!0)}),sightInput.closest(".form-group")?.querySelector("label")?.append(anchor)}},"#disableVisionInputs"),__name2(_TokenConfigPF2e,"TokenConfigPF2e");let TokenConfigPF2e=_TokenConfigPF2e;const _AmbientLightPF2e=class extends AmbientLight{static{__name(this,"_AmbientLightPF2e")}get isDarkness(){return this.source.isDarkness}};__name2(_AmbientLightPF2e,"AmbientLightPF2e");let AmbientLightPF2e=_AmbientLightPF2e;const _EffectsCanvasGroupPF2e=class extends EffectsCanvasGroup{static{__name(this,"_EffectsCanvasGroupPF2e")}get rulesBasedVision(){return game.settings.get("pf2e","automation.rulesBasedVision")&&canvas.ready&&!!canvas.scene?.tokenVision}};__name2(_EffectsCanvasGroupPF2e,"EffectsCanvasGroupPF2e");let EffectsCanvasGroupPF2e=_EffectsCanvasGroupPF2e;const _LightingLayerPF2e=class extends LightingLayer{static{__name(this,"_LightingLayerPF2e")}get lightingLevel(){return 1-canvas.darknessLevel}};__name2(_LightingLayerPF2e,"LightingLayerPF2e");let LightingLayerPF2e=_LightingLayerPF2e;const _TemplateLayerPF2e=class extends TemplateLayer{static{__name(this,"_TemplateLayerPF2e")}_onDragLeftMove(event){if(!canvas.scene||!canvas.dimensions)return;const interaction=event.interactionData,{destination,layerDragState,preview:template,origin}=interaction;if(!template||template.destroyed)return;if(template.parent===null&&this.preview.addChild(template),(layerDragState??0)>=1){const{x,y}=canvas.grid.getSnappedPosition(destination.x,destination.y,2);if(destination.x=x,destination.y=y,!template)return;const ray=new Ray(origin,destination),ratio=canvas.dimensions.size/canvas.dimensions.distance;if(["cone","circle"].includes(template.type)){const direction=ray.angle,snapAngle=Math.PI/(canvas.scene.hasHexGrid?6:4);template.document.direction=Math.toDegrees(Math.floor((direction+Math.PI*.125)/snapAngle)*snapAngle);const distance=Math.max(ray.distance/ratio,canvas.dimensions.distance);template.document.distance=Math.floor(distance/canvas.dimensions.distance)*canvas.dimensions.distance}else template.document.direction=Math.toDegrees(ray.angle),template.document.distance=ray.distance/ratio;template.refresh(),event.interactionData.layerDragState=2}}_onMouseWheel(event){const template=this.hover;if(!(template&&canvas.scene))return;const increment=event.shiftKey?15:5,coneMultiplier=template.type==="cone"?canvas.scene.hasHexGrid?2:3:1,snap=increment*coneMultiplier,delta=snap*Math.sign(event.deltaY);return template.rotate(template.document.direction+delta,snap)}};__name2(_TemplateLayerPF2e,"TemplateLayerPF2e");let TemplateLayerPF2e=_TemplateLayerPF2e;const _TokenLayerPF2e=class extends TokenLayer{static{__name(this,"_TokenLayerPF2e")}cycleStack(){const hovered=this.hover;if(!hovered)return!1;const stack=this.placeables.filter(t=>hovered.distanceTo(t)===0&&hovered.document.elevation===t.document.elevation).sort((a,b)=>a.mesh.sort-b.mesh.sort);if(stack.length<2)return!1;const first=stack.shift();stack.push(first);for(let sort=stack.length-1;sort>=0;sort--){const token=stack[sort];token.document.sort=sort,token.mesh.initialize({sort}),sort===stack.length-1&&(token.emitHoverIn(new PointerEvent("pointerenter")),this.hover=token)}return!0}};__name2(_TokenLayerPF2e,"TokenLayerPF2e");let TokenLayerPF2e=_TokenLayerPF2e;const _HearingSource=class extends SoundSource{static{__name(this,"_HearingSource")}_initialize(data){super._initialize(data),this.data.x=this.object.center.x,this.data.y=this.object.center.y,this.data.elevation=this.object.document.elevation,this.data.radius=canvas.dimensions?.maxR??1e3,this.data.walls=!0}};__name2(_HearingSource,"HearingSource");let HearingSource=_HearingSource;const _EffectAreaSquare=class extends PIXI.Rectangle{static{__name(this,"_EffectAreaSquare")}active;constructor(x,y,width,height,active=!0){super(x,y,width,height),this.active=active}get center(){return{x:this.x+this.width/2,y:this.y+this.height/2}}highlight(layer,{border,highlight}){this.x<0||this.y<0||(this.active?canvas.grid.grid.highlightGridPosition(layer,{x:this.x,y:this.y,border:border?.color,color:highlight.color,alpha:highlight.alpha}):(canvas.grid.grid.highlightGridPosition(layer,{x:this.x,y:this.y,border:0,color:0}),layer.beginFill(0,.5).moveTo(this.x,this.y).lineTo(this.x+this.width,this.y+this.height).endFill()))}};__name2(_EffectAreaSquare,"EffectAreaSquare");let EffectAreaSquare=_EffectAreaSquare;function getAreaSquares(data){if(!canvas.dimensions)return[];const squareWidth=canvas.dimensions.size,rowCount=Math.ceil(data.bounds.width/squareWidth),emptyVector=Array(rowCount-1).fill(null),genColumn=__name2(square=>emptyVector.reduce(colSquares=>{const squareAbove=colSquares.at(-1),squareBelow=new EffectAreaSquare(square.x,squareAbove.y+squareWidth,squareWidth,squareWidth);return colSquares.push(squareBelow),colSquares},[square]),"genColumn"),topLeftSquare=new EffectAreaSquare(data.bounds.x,data.bounds.y,squareWidth,squareWidth),collisionType=data.traits?.includes("visual")&&!data.traits.includes("auditory")?"sight":data.traits?.includes("auditory")&&!data.traits.includes("visual")?"sound":"move",tokenBounds=data.token.mechanicalBounds,tokenCenter=data.token.center,tokenCenters=[tokenCenter,...[{x:0,y:1},{x:1,y:0},{x:0,y:-1},{x:-1,y:0}].map(c=>({x:tokenCenter.x+c.x*Math.round(tokenBounds.width/8),y:tokenCenter.y+c.y*Math.round(tokenBounds.height/8)}))];return emptyVector.reduce(squares=>{const lastSquare=squares.at(-1).at(-1),column=genColumn(new EffectAreaSquare(lastSquare.x+squareWidth,topLeftSquare.y,squareWidth,squareWidth));return squares.push(column),squares},[genColumn(topLeftSquare)]).flat().filter(s=>measureDistanceCuboid(tokenBounds,s)<=data.radius).map(square=>(square.active=tokenCenters.some(c=>!CONFIG.Canvas.polygonBackends[collisionType].testCollision(c,square.center,{type:collisionType,mode:"any"})),square))}__name(getAreaSquares,"getAreaSquares"),__name2(getAreaSquares,"getAreaSquares");const _AuraRenderer=class extends PIXI.Graphics{static{__name(this,"_AuraRenderer")}constructor(params){super(),__privateAdd(this,_drawBorder),__privateAdd(this,_drawTexture),__privateAdd(this,_drawLabel),__publicField(this,"slug"),__publicField(this,"token"),__publicField(this,"radius"),__publicField(this,"radiusPixels"),__publicField(this,"traits"),__publicField(this,"appearance"),__publicField(this,"border",new PIXI.Graphics),__publicField(this,"texture",null),this.slug=params.slug,this.token=params.token,this.appearance=params.appearance,this.radius=params.radius,this.radiusPixels=.5*this.token.mechanicalBounds.width+this.radius/(canvas.dimensions?.distance??0)*canvas.grid.size,this.traits=params.traits,this.addChild(this.border)}get bounds(){const{token,radiusPixels}=this,bounds=token.mechanicalBounds;return new PIXI.Rectangle(bounds.x-(radiusPixels-bounds.width/2),bounds.y-(radiusPixels-bounds.width/2),radiusPixels*2,radiusPixels*2)}get highlightLayer(){return canvas.grid?.getHighlightLayer(this.token.highlightId)??null}get squares(){return getAreaSquares(this)}async draw(showBorder){const{mechanicalBounds}=this.token;return this.x=mechanicalBounds.width/2,this.y=mechanicalBounds.height/2,this.token.document.width<1&&(this.x+=mechanicalBounds.x-this.token.x,this.y+=mechanicalBounds.y-this.token.y),__privateMethod(this,_drawBorder,drawBorder_fn).call(this),this.border.visible=showBorder,__privateMethod(this,_drawTexture,drawTexture_fn).call(this)}highlight(){const{dimensions}=canvas;if(!dimensions)return;if(__privateMethod(this,_drawLabel,drawLabel_fn).call(this),!!(this.token.actor?.isOfType("familiar")?this.token.actor.master?.combatant?.encounter.active:this.token.combatant?.encounter.active)){const{highlightLayer}=this;if(!highlightLayer)return;for(const square of this.squares)square.highlight(highlightLayer,this.appearance)}}};_drawBorder=new WeakSet,drawBorder_fn=__name2(function(){const data=this.appearance.border;!data||this.border.geometry.graphicsData.length>0||this.border.lineStyle(_AuraRenderer.LINE_THICKNESS,data.color,data.alpha).drawCircle(0,0,this.radiusPixels)},"#drawBorder"),_drawTexture=new WeakSet,drawTexture_fn=__name2(async function(){const data=this.appearance.texture;if(!data||this.token.isPreview||this.texture)return;const maybeTexture=await loadTexture(data.src,{fallback:"icons/svg/hazard.svg"});if(this.texture=maybeTexture instanceof PIXI.Texture?maybeTexture:null,!this.texture)return;const globalVideo=isVideoFilePath(data.src)?game.video.getVideoSource(this.texture):null;if(globalVideo){this.texture.destroy(),this.texture=await game.video.cloneTexture(globalVideo);const video=game.video.getVideoSource(this.texture)??globalVideo;video.playbackRate=data.playbackRate;const offset=data.loop?Math.random()*video.duration:0;game.video.play(video,{volume:0,offset,loop:data.loop})}const radius=data.scale*this.radiusPixels,diameter=radius*2,scale={x:diameter/this.texture.width,y:diameter/this.texture.height},matrix=new PIXI.Matrix(scale.x,void 0,void 0,scale.y,radius,radius);this.beginTextureFill({texture:this.texture,alpha:data.alpha,matrix}).drawCircle(0,0,radius).endFill()},"#drawTexture"),_drawLabel=new WeakSet,drawLabel_fn=__name2(function(){const style=CONFIG.canvasTextStyle.clone(),gridSize=canvas.dimensions?.size??100;style.fontSize=Math.max(Math.round(gridSize*.36*12)/12,36),style.align="center";const bounds=this.token.mechanicalBounds,gridUnits=canvas.scene?.grid.units.trim()||game.system.gridUnits,label=[this.radius,gridUnits].join(""),text=new PreciseText(label,style),center={x:bounds.x+bounds.width/2,y:bounds.y+bounds.height/2},textOffset=Math.sqrt(style.fontSize);text.position.set(center.x+textOffset,center.y-this.radiusPixels-style.fontSize-textOffset),this.highlightLayer?.beginFill(0,.5).lineStyle(_AuraRenderer.LINE_THICKNESS,0).drawCircle(center.x,center.y-this.radiusPixels,6).endFill().addChild(text)},"#drawLabel"),__name2(_AuraRenderer,"AuraRenderer"),__publicField(_AuraRenderer,"LINE_THICKNESS",3);let AuraRenderer=_AuraRenderer;const _AuraRenderers=class extends Map{static{__name(this,"_AuraRenderers")}constructor(token){super(),__privateAdd(this,_showBordersHighlights),__publicField(this,"token"),this.token=token}get highlightId(){return this.token.highlightId}async reset(slugs){if(!slugs)this.clear();else for(const slug of slugs)this.delete(slug);if(!this.token.actor)return;const data=Array.from(this.token.document.auras.values()).filter(a=>slugs?.includes(a.slug)??!0);for(const datum of data){const renderer=new AuraRenderer({...datum,token:this.token});this.set(datum.slug,this.token.addChild(renderer))}return this.draw()}async draw(){if(this.size===0||(this.clearHighlights(),this.token.isAnimating))return;const showBordersHighlights=__privateGet(this,_showBordersHighlights,showBordersHighlights_get);for(const aura of this.values())await aura.draw(showBordersHighlights);if(showBordersHighlights&&(this.token.hover||this.token.layer.highlightObjects)){const{highlightId}=this;(canvas.grid.highlightLayers[highlightId]??canvas.grid.addHighlightLayer(highlightId)).clear();for(const aura of this.values())aura.highlight()}}delete(key){const aura=this.get(key);return aura?(aura.destroyed||aura.destroy(!0),this.token.removeChild(aura),super.delete(key)):!1}clear(){this.clearHighlights();for(const aura of this.values())aura.destroyed||aura.destroy(!0),this.token.removeChild(aura);return super.clear()}destroy(){this.clear()}clearHighlights(){canvas.grid.destroyHighlightLayer(this.highlightId)}};_showBordersHighlights=new WeakSet,showBordersHighlights_get=__name2(function(){const inEncounter=__name2(()=>!!(this.token.actor?.isOfType("familiar")?this.token.actor.master?.combatant?.encounter.active:this.token.combatant?.encounter.active),"inEncounter");return canvas.scene?.grid.type===CONST.GRID_TYPES.SQUARE&&canvas.scene.tokenVision&&canvas.scene.isInFocus&&(game.user.isGM||this.token.actor?.alliance==="party")&&(this.token.controlled||this.token.hover||this.token.layer.highlightObjects||inEncounter())},"#showBordersHighlights"),__name2(_AuraRenderers,"AuraRenderers");let AuraRenderers=_AuraRenderers;const _FlankingHighlightRenderer=class{static{__name(this,"_FlankingHighlightRenderer")}_layer;token;labelText;lineColor;constructor(token){this._layer=null,this.token=token,this.labelText=game.i18n.localize("PF2E.Token.Flanking"),this.lineColor=CONFIG.Canvas.dispositionColors.CONTROLLED}get layer(){return this._layer??this.addLayer()}get shouldRender(){return canvas.ready&&!!canvas.scene?.isInFocus&&this.tokenIsSelectedOrOwn&&this.tokenIsReady}get tokenIsSelectedOrOwn(){return this.token.controlled&&this.token.isOwner||!!this.token.actor&&this.token.actor?.id===game.user.character?.id}get tokenIsReady(){return!this.token.isPreview&&!this.token.isAnimating}draw(){this.clear(),canvas.tokens.highlightObjects&&game.user.targets.size&&this.shouldRender&&game.user.targets.forEach(target=>this.drawForTarget(target))}drawForTarget(target){const buddies=this.token.buddiesFlanking(target,{ignoreFlankable:!0});this.drawBuddyLines(buddies)}drawBuddyLines(buddies){buddies.forEach(b=>this.drawBuddyLine(b))}drawBuddyLine(buddy){const t=CONFIG.Canvas.objectBorderThickness,o=Math.round(t*1.5),c=Math.round(t*2);this.layer.lineStyle(o,0,.5).moveTo(this.token.center.x,this.token.center.y).lineTo(buddy.center.x,buddy.center.y),this.layer.lineStyle(t,this.lineColor,.5).moveTo(this.token.center.x,this.token.center.y).lineTo(buddy.center.x,buddy.center.y),this.layer.beginFill(this.lineColor).lineStyle(1,0).drawCircle(this.token.center.x,this.token.center.y,c),this.layer.beginFill(this.lineColor).lineStyle(1,0).drawCircle(buddy.center.x,buddy.center.y,c),this.drawLabel(buddy)}drawLabel(buddy){const mid_x=Math.round((this.token.center.x+buddy.center.x)/2),mid_y=Math.round((this.token.center.y+buddy.center.y)/2),vect_x=buddy.center.x-this.token.center.x,vect_y=buddy.center.y-this.token.center.y,perp_vect_x=vect_x<=-vect_x?-vect_y:vect_y,perp_vect_y=vect_x<=-vect_x?vect_x:-vect_x,offsetScale=20/Math.sqrt(perp_vect_x**2+perp_vect_y**2),perp_x=mid_x+Math.round(perp_vect_x*offsetScale),perp_y=mid_y+Math.round(perp_vect_y*offsetScale),style=CONFIG.canvasTextStyle.clone();style.fontSize=24,canvas.dimensions?.size&&canvas.dimensions.size>=200?style.fontSize=28:canvas.dimensions?.size&&canvas.dimensions.size<50&&(style.fontSize=20),style.fill=this.lineColor,style.stroke=0;const text=new PreciseText(this.labelText,style);text.anchor.set(.5,.5);let rotation=Math.atan2(vect_y,vect_x);rotation>Math.PI/2?rotation=rotation-Math.PI:rotation<-Math.PI/2&&(rotation=rotation+Math.PI),text.rotation=rotation,text.position.set(perp_x,perp_y),this.layer.addChild(text)}clear(){this._layer?.destroy({children:!0}),this._layer=null}destroy(){this.clear()}addLayer(){return this._layer=new PIXI.Graphics,this.token.layer.addChild(this._layer)}};__name2(_FlankingHighlightRenderer,"FlankingHighlightRenderer");let FlankingHighlightRenderer=_FlankingHighlightRenderer;const _TokenPF2e=class extends Token{static{__name(this,"_TokenPF2e")}auras;flankingHighlight;hearing;constructor(document2){super(document2),this.hearing=new HearingSource({object:this}),this.auras=new AuraRenderers(this),Object.defineProperty(this,"auras",{configurable:!1,writable:!1}),this.flankingHighlight=new FlankingHighlightRenderer(this),Object.defineProperty(this,"flankingHighlight",{configurable:!1,writable:!1})}get isVisible(){if(this.detectionFilter=null,this.document.hidden&&!game.user.isGM)return!1;if(!canvas.effects.visibility.tokenVision||this.controlled||canvas.effects.visionSources.get(this.sourceId)?.active)return!0;const tolerance=Math.floor(.35*Math.min(this.w,this.h));return canvas.effects.visibility.testVisibility(this.center,{tolerance,object:this})}get isAnimating(){return!!this._animation}get emitsDarkness(){return this.document.emitsDarkness}get hasLowLightVision(){return this.document.hasLowLightVision}get hasDarkvision(){return this.document.hasDarkvision}get linkToActorSize(){return this.document.linkToActorSize}get highlightId(){return`Token.${this.id}`}get mechanicalBounds(){const bounds=super.bounds;if(this.document.width<1){const position=canvas.grid.getTopLeft(bounds.x+bounds.width/2,bounds.y+bounds.height/2);return new PIXI.Rectangle(position[0],position[1],Math.max(canvas.grid.size,bounds.width),Math.max(canvas.grid.size,bounds.height))}return bounds}get sightRange(){return this.document.sight.range>=canvas.dimensions.maxR?canvas.dimensions.maxR:super.sightRange}isAdjacentTo(token){return this.distanceTo(token)===5}canFlank(flankee,context={}){if(this===flankee||!game.settings.get("pf2e","automation.flankingDetection"))return!1;const flankable=context.ignoreFlankable||flankee.actor?.attributes.flanking.flankable;if(!(this.actor?.attributes.flanking.canFlank&&flankable)||!this.actor.isOfType("character","npc")||!flankee.actor?.isOfType("creature")||this.actor.isAllyOf(flankee.actor))return!1;const reach=context.reach??this.actor.getReach({action:"attack"});return this.actor.canAttack&&reach>=this.distanceTo(flankee,{reach})}onOppositeSides(flankerA,flankerB,flankee){const{lineSegmentIntersects}=foundry.utils,[centerA,centerB]=[flankerA.center,flankerB.center],{bounds}=flankee,left=new Ray({x:bounds.left,y:bounds.top},{x:bounds.left,y:bounds.bottom}),right=new Ray({x:bounds.right,y:bounds.top},{x:bounds.right,y:bounds.bottom}),top=new Ray({x:bounds.left,y:bounds.top},{x:bounds.right,y:bounds.top}),bottom=new Ray({x:bounds.left,y:bounds.bottom},{x:bounds.right,y:bounds.bottom}),intersectsSide=__name2(side=>lineSegmentIntersects(centerA,centerB,side.A,side.B),"intersectsSide");return intersectsSide(left)&&intersectsSide(right)||intersectsSide(top)&&intersectsSide(bottom)}isFlanking(flankee,context={}){if(!(this.actor&&this.canFlank(flankee,context)))return!1;const{flanking}=this.actor.attributes,flankingBuddies=canvas.tokens.placeables.filter(t=>t!==this&&t.canFlank(flankee,pick$1(context,["ignoreFlankable"])));return flankingBuddies.length===0?!1:flanking.canGangUp.some(g=>typeof g=="number"&&g<=flankingBuddies.length)||this.isAdjacentTo(flankee)&&flanking.canGangUp.includes("animal-companion")&&flankingBuddies.some(b=>{if(!b.actor?.isOfType("character"))return!1;const traits=b.actor.traits;return traits.has("minion")&&!traits.has("construct")&&b.isAdjacentTo(flankee)})?!0:flankingBuddies.some(b=>this.onOppositeSides(this,b,flankee))}buddiesFlanking(flankee,context={}){return!this.actor||!this.canFlank(flankee,context)?[]:canvas.tokens.placeables.filter(t=>t!==this&&t.canFlank(flankee,pick$1(context,["ignoreFlankable"]))).filter(b=>this.onOppositeSides(this,b,flankee))}_refreshVisibility(){super._refreshVisibility(),this.auras.draw(),this.flankingHighlight.draw()}_getBorderColor(options){const isHovered=options?.hover??(this.hover||this.layer.highlightObjects),isControlled=this.controlled||!game.user.isGM&&this.isOwner,isFriendly=this.document.disposition===CONST.TOKEN_DISPOSITIONS.FRIENDLY;if(!isHovered||isControlled||isFriendly||!this.actor?.hasPlayerOwner)return super._getBorderColor();const colors=CONFIG.Canvas.dispositionColors;switch(this.document.disposition){case CONST.TOKEN_DISPOSITIONS.NEUTRAL:return colors.NEUTRAL;case CONST.TOKEN_DISPOSITIONS.HOSTILE:return colors.HOSTILE;case CONST.TOKEN_DISPOSITIONS.SECRET:return this.isOwner?colors.SECRET:null;default:return super._getBorderColor(options)}}_drawBar(number,bar,data){if(!canvas.dimensions)return;const actor=this.document.actor;if(!(data.attribute==="attributes.hp"&&actor?.attributes.hp))return super._drawBar(number,bar,data);const{value,max,temp}=actor.attributes.hp??{},healthPercent=Math.clamped(value,0,max)/max,black=0,color=Number(number?Color.fromRGB([.5*healthPercent,.7*healthPercent,.5+healthPercent/2]):Color.fromRGB([1-healthPercent/2,healthPercent,0]));let h=Math.max(canvas.dimensions.size/12,8);const bs=Math.clamped(h/8,1,2);this.document.height>=2&&(h*=1.6);const numBars=temp>0?2:1,barHeight=h/numBars;if(bar.clear(),bar.lineStyle(0).beginFill(black,.5).drawRoundedRect(0,0,this.w,h,3),bar.lineStyle(bs/2,black,1),temp>0){const tempWidth=Math.clamped(temp,0,max)/max*this.w-2*(bs-1);bar.beginFill(6737151,1).drawRoundedRect(0,0,tempWidth,barHeight,2)}const healthBarY=(numBars-1)*barHeight;bar.beginFill(color,1).drawRoundedRect(0,healthBarY,healthPercent*this.w,barHeight,2),bar.beginFill(black,0).lineStyle(bs,black,1).drawRoundedRect(0,0,this.w,h,3),bar.position.set(0,number===0?this.h-h:0)}async drawEffects(){if(await super.drawEffects(),await this._animation,this.auras.size===0)return this.auras.reset();const changedAndDeletedAuraSlugs=Array.from(this.auras.entries()).filter(([slug,aura])=>{const properties=["radius","appearance"],sceneData=pick$1(this.document.auras.get(slug)??{radius:null,appearance:null},properties),canvasData=pick$1(aura,properties);return sceneData.radius===null?!0:Object.keys(diffObject(canvasData,sceneData)).length+Object.keys(diffObject(sceneData,canvasData)).length>0}).map(([slug])=>slug),newAuraSlugs=Array.from(this.document.auras.keys()).filter(s=>!this.auras.has(s));return this.auras.reset([changedAndDeletedAuraSlugs,newAuraSlugs].flat())}emitHoverIn(nativeEvent){const event=new PIXI.FederatedPointerEvent(new PIXI.EventBoundary(this));event.type="pointerover",event.nativeEvent=nativeEvent,this._onHoverIn(event,{hoverOutOthers:!0})}emitHoverOut(nativeEvent){const event=new PIXI.FederatedPointerEvent(new PIXI.EventBoundary(this));event.type="pointerout",event.nativeEvent=nativeEvent,this._onHoverOut(event)}_isVisionSource(){return!!this.actor?.hasPlayerOwner&&!game.user.isGM&&game.settings.get("pf2e","metagame_partyVision")||super._isVisionSource()}clone(){const clone=super.clone();return clone.isPreview&&(clone.document.height=this.document.height,clone.document.width=this.document.width,clone.document.texture.scaleX=this.document.texture.scaleX,clone.document.texture.scaleY=this.document.texture.scaleY,clone.document.texture.src=this.document.texture.src),clone}async showFloatyText(params){if(!this.isVisible)return;if(!game.user.isGM&&typeof params!="number"){const[_,document2]=Object.entries(params)[0];if(document2 instanceof EffectPF2e&&document2.system.unidentified)return}const scrollingTextArgs=(()=>{if(typeof params=="number"){const quantity=params,maxHP=this.actor?.hitPoints?.max;if(!(quantity&&typeof maxHP=="number"))return null;const percent=Math.clamped(Math.abs(quantity)/maxHP,0,1),textColors={damage:16711680,healing:65280};return[this.center,params.signedString(),{anchor:CONST.TEXT_ANCHOR_POINTS.TOP,jitter:.25,fill:textColors[quantity<0?"damage":"healing"],fontSize:16+32*percent,stroke:0,strokeThickness:4}]}else{const[change,details]=Object.entries(params)[0],isAdded=change==="create",sign=isAdded?"+ ":"- ",appendedNumber=!/ \d+$/.test(details.name)&&details.value?` ${details.value}`:"",content=`${sign}${details.name}${appendedNumber}`,anchorDirection=isAdded?CONST.TEXT_ANCHOR_POINTS.TOP:CONST.TEXT_ANCHOR_POINTS.BOTTOM,textStyle=pick$1(this._getTextStyle(),["fill","fontSize","stroke","strokeThickness"]);return[this.center,content,{...textStyle,anchor:anchorDirection,direction:anchorDirection,jitter:.25}]}})();scrollingTextArgs&&(await this._animation,await canvas.interface?.createScrollingText(...scrollingTextArgs))}distanceTo(target,{reach=null}={}){if(!canvas.dimensions)return NaN;if(this===target)return 0;if(canvas.grid.type!==CONST.GRID_TYPES.SQUARE)return canvas.grid.measureDistance(this.position,target.position);const selfElevation=this.document.elevation,targetElevation=target.document.elevation;return selfElevation===targetElevation||!this.actor||!target.actor?measureDistanceCuboid(this.bounds,target.bounds,{reach}):measureDistanceCuboid(this.bounds,target.bounds,{reach,token:this,target})}async animate(updateData,options){if(options?.spin){let attributeAdded=!1;const currentRotation=this.document.rotation,rotationAngle=this.x<=this.document.x?360:-360;options.ontick=(_frame,data)=>{if(this.document.lockRotation=!1,!attributeAdded&&data.attributes.length>0){const duration=(data.duration??1e3)/1e3;data.attributes.push({attribute:"rotation",parent:data.attributes[0].parent,from:currentRotation,to:currentRotation+duration*rotationAngle,delta:data.attributes[0].delta}),attributeAdded=!0}}}await super.animate(updateData,options),this.document.lockRotation=this.document._source.lockRotation}updateVisionSource({defer=!1,deleted=!1}={}){super.updateVisionSource({defer,deleted}),this._isVisionSource()&&!deleted&&this.hearing.initialize()}render(renderer){if(super.render(renderer),!this.mesh)return;const configuredTint=this.document.texture.tint??"#FFFFFF";this.mesh.tint!==0&&this.detectionFilter instanceof OutlineOverlayFilter?this.mesh.tint=0:this.mesh.tint===0&&configuredTint!=="#000000"&&!this.detectionFilter&&(this.mesh.tint=Number(Color.fromString(configuredTint)))}_destroy(){super._destroy(),this.auras.destroy(),this.hearing.destroy(),this.flankingHighlight.destroy()}_canView(user,event){return super._canView(user,event)||!!(this.actor?.isOfType("npc")&&this.actor.isLootable)}_onControl(options={}){return game.ready&&game.pf2e.effectPanel.refresh(),super._onControl(options)}_onRelease(options){return game.pf2e.effectPanel.refresh(),super._onRelease(options)}_onApplyStatusEffect(statusId,active){super._onApplyStatusEffect(statusId,active),["undetected","unnoticed"].includes(statusId)&&(canvas.perception.update({refreshVision:!0,refreshLighting:!0},!0),this.mesh.refresh())}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId),changed.width&&(this._animation?this._animation.then(()=>{this.auras.reset()}):this.auras.reset())}};__name2(_TokenPF2e,"TokenPF2e");let TokenPF2e=_TokenPF2e;function measureDistanceCuboid(r0,r1,{reach=null,token=null,target=null}={}){if(!canvas.dimensions)return NaN;if(canvas.grid.type!==CONST.GRID_TYPES.SQUARE)return canvas.grid.measureDistance(r0,r1);const gridWidth=canvas.grid.grid.w,distance={dx:0,dy:0,dz:0};if([[r0,r1],[r1,r0]].some(([rA,rB])=>rB.right>rA.left&&rB.leftrA.top&&rB.top{const roundLeft=rectangle.leftrB.bottom>rA.top&&rB.top{const roundLeft=rectangle.lefta-b),squares={doubleDiagonal:sortedDistance[0],diagonal:sortedDistance[1]-sortedDistance[0],straight:sortedDistance[2]-sortedDistance[1]},reduction=squares.diagonal+squares.doubleDiagonal>1&&reach===10?1:0;return(Math.floor(squares.doubleDiagonal*1.75+squares.diagonal*1.5+squares.straight)-reduction)*gridDistance}__name(measureDistanceOnGrid,"measureDistanceOnGrid"),__name2(measureDistanceOnGrid,"measureDistanceOnGrid");function highlightGrid({areaType,object,colors,document:document2,collisionType="move",preview=!1}){if(!object.id&&!preview)return;const{grid,dimensions}=canvas;if(!(grid&&dimensions))return;const angle=document2.angle??0,direction=document2.direction??45,highlightLayer=grid.getHighlightLayer(object.highlightId)?.clear();if(!highlightLayer)return;const[cx,cy]=grid.getCenter(document2.x,document2.y),[col0,row0]=grid.grid.getGridPositionFromPixels(cx,cy),minAngle=(360+(direction-angle*.5)%360)%360,maxAngle=(360+(direction+angle*.5)%360)%360,snappedOrigin=canvas.grid.getSnappedPosition(document2.x,document2.y,object.layer.gridPrecision),withinAngle=__name2((min,max,value)=>(min=(360+min%360)%360,max=(360+max%360)%360,value=(360+value%360)%360,min=min&&value<=max:value>=min||value<=max),"withinAngle"),coneOriginOffset=(()=>{if(areaType!=="cone")return{x:0,y:0};const dir=(direction>=0?360-direction:-direction)%360,xOffset=snappedOrigin.x%dimensions.size!==0?Math.sign(1*Math.round(Math.cos(Math.toRadians(dir))*100)/100)/2:0,yOffset=snappedOrigin.y%dimensions.size!==0?-Math.sign(1*Math.round(Math.sin(Math.toRadians(dir))*100)/100)/2:0;return{x:xOffset*dimensions.size,y:yOffset*dimensions.size}})(),padding=Math.clamped(document2.width??0,1.5,2),docDistance=document2.distance??0,padded=docDistance*padding/dimensions.distance,rowCount=Math.ceil(padded/(dimensions.size/grid.h)),columnCount=Math.ceil(padded/(dimensions.size/grid.w)),offsetEmanationOrigin=__name2(destination=>{if(!(areaType==="emanation"&&object instanceof TokenPF2e))return{x:0,y:0};if(object.w<=dimensions.size)return{x:0,y:0};const offset=(object.w-dimensions.size)/2,getCoordinate=__name2((centerCoord,destCoord)=>destCoord===centerCoord?0:destCoord>centerCoord?offset:-offset,"getCoordinate");return{x:getCoordinate(object.center.x,destination.x),y:getCoordinate(object.center.y,destination.y)}},"offsetEmanationOrigin");for(let a=-columnCount;a0&&!withinAngle(minAngle,maxAngle,rayAngle))continue}if(measureDistance(destination,origin)>docDistance)continue;canvas.ready&&CONFIG.Canvas.polygonBackends[collisionType].testCollision(origin,destination,{type:collisionType,mode:"any"})?(grid.grid.highlightGridPosition(highlightLayer,{x:gx,y:gy,border:1,color:0}),highlightLayer.beginFill(0,.5).moveTo(gx,gy).lineTo(gx+dimensions.size,gy+dimensions.size).endFill()):grid.grid.highlightGridPosition(highlightLayer,{x:gx,y:gy,border:colors.border,color:colors.fill})}}__name(highlightGrid,"highlightGrid"),__name2(highlightGrid,"highlightGrid");const _MeasuredTemplatePF2e=class _MeasuredTemplatePF2e2 extends MeasuredTemplate{static{__name(this,"_MeasuredTemplatePF2e")}constructor(){super(...arguments),__privateAdd(this,_moveTime,0),__privateAdd(this,_wheelListenerOptions,{passive:!1}),__privateAdd(this,_onPreviewMouseMove,__name2(event=>{event.stopPropagation();const now=Date.now();if(now-__privateGet(this,_moveTime)<=20)return;const center=event.getLocalPosition(this.layer),snapped=canvas.grid.getSnappedPosition(center.x,center.y,2),hexTypes=[CONST.GRID_TYPES.HEXODDR,CONST.GRID_TYPES.HEXEVENR],direction=__privateGet(this,_moveTime)===0&&hexTypes.includes(canvas.grid.type)?this.document.direction+30:this.document.direction;this.document.updateSource({...snapped,direction}),this.refresh(),__privateSet(this,_moveTime,now)},"#onPreviewMouseMove")),__privateAdd(this,_onPreviewLeftClick,__name2(()=>{canvas.scene&&canvas.scene.createEmbeddedDocuments("MeasuredTemplate",[this.document.toObject()]).then(()=>{_MeasuredTemplatePF2e2.currentPreview&&(_MeasuredTemplatePF2e2.currentPreview.placed=!0)}),canvas.tokens.activate(),this.destroy()},"#onPreviewLeftClick")),__privateAdd(this,_onPreviewRightClick,__name2(()=>{canvas.tokens.activate(),this.destroy(),_MeasuredTemplatePF2e2.currentPreview?.resolve(null)},"#onPreviewRightClick")),__privateAdd(this,_onPreviewMouseWheel,__name2(event=>{if(event instanceof WheelEvent){if(event.ctrlKey){event.preventDefault(),event.stopPropagation();const snap=event.shiftKey?15:5;this.document.updateSource({direction:this.document.direction+snap*Math.sign(event.deltaY)}),this.refresh()}else if(event.shiftKey){event.stopPropagation();const snap=canvas.grid.type>=CONST.GRID_TYPES.HEXODDR&&canvas.grid.type<=CONST.GRID_TYPES.HEXEVENQ?60:45;this.document.updateSource({direction:this.document.direction+snap*Math.sign(event.deltaY)}),this.refresh()}}},"#onPreviewMouseWheel"))}get type(){return this.document.t}highlightGrid(){if(!["circle","cone"].includes(this.type)||canvas.grid.type!==CONST.GRID_TYPES.SQUARE)return super.highlightGrid();if(!this.isVisible){canvas.grid.getHighlightLayer(this.highlightId)?.clear();return}highlightGrid({areaType:this.type==="circle"?"burst":"cone",object:this,document:this.document,colors:{border:this.borderColor,fill:this.fillColor},preview:!0})}async drawPreview(){return this.layer.activate(),await this.draw(),this.layer.preview.addChild(this),canvas.stage.on("mousemove",__privateGet(this,_onPreviewMouseMove)),canvas.stage.on("mousedown",__privateGet(this,_onPreviewLeftClick)),canvas.stage.on("rightdown",__privateGet(this,_onPreviewRightClick)),canvas.app.view.addEventListener?.("wheel",__privateGet(this,_onPreviewMouseWheel),__privateGet(this,_wheelListenerOptions)),_MeasuredTemplatePF2e2.currentPreview?.resolve(null),new Promise(res=>{_MeasuredTemplatePF2e2.currentPreview={resolve:value=>{res(value),_MeasuredTemplatePF2e2.currentPreview=null},placed:!1}})}destroy(options){canvas.stage.off("mousemove",__privateGet(this,_onPreviewMouseMove)),canvas.stage.off("mousedown",__privateGet(this,_onPreviewLeftClick)),canvas.stage.off("rightdown",__privateGet(this,_onPreviewRightClick)),canvas.app.view.removeEventListener?.("wheel",__privateGet(this,_onPreviewMouseWheel),__privateGet(this,_wheelListenerOptions)),super.destroy(options)}applyRenderFlags(){super.applyRenderFlags(),_MeasuredTemplatePF2e2.currentPreview?.placed&&_MeasuredTemplatePF2e2.currentPreview.resolve(this)}get item(){return this.document.item}};_moveTime=new WeakMap,_wheelListenerOptions=new WeakMap,_onPreviewMouseMove=new WeakMap,_onPreviewLeftClick=new WeakMap,_onPreviewRightClick=new WeakMap,_onPreviewMouseWheel=new WeakMap,__name2(_MeasuredTemplatePF2e,"MeasuredTemplatePF2e"),__publicField(_MeasuredTemplatePF2e,"currentPreview",null);let MeasuredTemplatePF2e=_MeasuredTemplatePF2e;const _TokenAura=class{static{__name(this,"_TokenAura")}constructor(params){__publicField(this,"slug"),__publicField(this,"token"),__publicField(this,"level"),__publicField(this,"radius"),__publicField(this,"traits"),__publicField(this,"effects"),__publicField(this,"appearance"),__privateAdd(this,_squares,void 0),this.slug=params.slug,this.token=params.token,this.level=params.level,this.radius=params.radius,this.traits=params.traits,this.effects=params.effects,this.appearance=params.appearance}get radiusPixels(){const gridSize=this.scene.grid.distance,gridSizePixels=this.scene.grid.size;return .5*this.token.mechanicalBounds.width+this.radius/gridSize*gridSizePixels}get scene(){return this.token.scene}get bounds(){const{token,radiusPixels}=this,bounds=token.mechanicalBounds;return new PIXI.Rectangle(bounds.x-(radiusPixels-bounds.width/2),bounds.y-(radiusPixels-bounds.width/2),radiusPixels*2,radiusPixels*2)}get center(){return this.token.center}get squares(){return __privateGet(this,_squares)??__privateSet(this,_squares,getAreaSquares(this))}containsToken(token){return token===this.token?!0:!this.token.object||!token.object||this.token.object.distanceTo(token.object)>this.radius?!1:this.squares.some(s=>s.active&&measureDistanceCuboid(s,token.mechanicalBounds)===0)}async notifyActors(){if(!this.scene.isInFocus)return;const auraActor=this.token.actor,auraData=auraActor?.auras.get(this.slug);if(!(auraActor&&auraData))return;const auradTokens=this.scene.tokens.filter(t=>t.actor?.primaryUpdater===game.user&&this.containsToken(t)),affectedActors=new Set(auradTokens.flatMap(t=>t.actor??[])),origin={actor:auraActor,token:this.token};for(const actor of affectedActors)await actor.applyAreaEffects(auraData,origin)}};_squares=new WeakMap,__name2(_TokenAura,"TokenAura");let TokenAura=_TokenAura;const _TokenDocumentPF2e=class _TokenDocumentPF2e2 extends TokenDocument{static{__name(this,"_TokenDocumentPF2e")}constructor(){super(...arguments),__privateAdd(this,_prepareDerivedPerception),__publicField(this,"constructed",!0)}get inCombat(){return this.actor?.isOfType("party")?this.actor.members.every(a=>game.combat?.getCombatantByActor(a.id)):super.inCombat}hasStatusEffect(statusId){if(statusId==="dead")return this.overlayEffect===CONFIG.controlIcons.defeated;const{actor}=this;return!actor||!game.settings.get("pf2e","automation.rulesBasedVision")?!1:objectHasKey(CONFIG.PF2E.conditionTypes,statusId)&&actor.hasCondition(statusId)||__name2(()=>actor.itemTypes.effect.some(e=>(e.slug??sluggify(e.name))===statusId),"hasEffect")()}static getTrackedAttributes(data={},_path=[]){if(_path.length===0&&Object.keys(data).length===0)for(const[type,model]of Object.entries(game.system.model.Actor))["character","npc"].includes(type)&&foundry.utils.mergeObject(data,model);if(_path.length>0)return super.getTrackedAttributes(data,_path);const patterns={positive:/^(?:attributes|resources)\./,negative:/\b(?:rank|_?modifiers|item|classdc|dexcap|familiar|\w+hp\b)|bonus/i},prunedData=expandObject(Object.fromEntries(Object.entries(flattenObject(data)).filter(([k,v])=>patterns.positive.test(k)&&!patterns.negative.test(k)&&!["boolean","string"].includes(typeof v))));return super.getTrackedAttributes(prunedData,_path)}get scene(){return this.parent}get emitsDarkness(){return this.light.bright<0}get rulesBasedVision(){return!!(this.sight.enabled&&this.actor?.isOfType("character","familiar")&&this.scene?.rulesBasedVision)}get hasLowLightVision(){return!!(this.rulesBasedVision&&this.actor?.isOfType("creature")&&this.actor.hasLowLightVision)}get hasDarkvision(){return!!(this.rulesBasedVision&&this.actor?.isOfType("creature")&&this.actor.hasDarkvision)}get linkToActorSize(){return this.flags.pf2e.linkToActorSize}get autoscale(){return this.flags.pf2e.autoscale}get playersCanSeeName(){const anyoneCanSee=[CONST.TOKEN_DISPLAY_MODES.ALWAYS,CONST.TOKEN_DISPLAY_MODES.HOVER],nameDisplayMode=this.displayName;return anyoneCanSee.includes(nameDisplayMode)||this.actor?.alliance==="party"}get bounds(){const gridSize=this.scene?.grid.size??100;return new PIXI.Rectangle(this._source.x,this._source.y,this.width*gridSize,this.height*gridSize)}get mechanicalBounds(){const bounds=this.bounds;if(this.width<1){const position=canvas.grid.getTopLeft(bounds.x+bounds.width/2,bounds.y+bounds.height/2);return new PIXI.Rectangle(position[0],position[1],Math.max(canvas.grid.size,bounds.width),Math.max(canvas.grid.size,bounds.height))}return bounds}get center(){const{bounds}=this;return{x:bounds.x+bounds.width/2,y:bounds.y+bounds.height/2}}_initialize(options){this.constructed??=!1,this.auras=new Map,super._initialize(options)}prepareData(){this.parent&&!this.parent.flags?.pf2e||super.prepareData()}prepareBaseData(){if(super.prepareBaseData(),this.flags=mergeObject(this.flags,{pf2e:{}}),this.auras.clear(),!this.actor||!this.isEmbedded)return;_TokenDocumentPF2e2.assignDefaultImage(this);for(const[key,data]of this.actor.auras.entries())this.auras.set(key,new TokenAura({token:this,...deepClone(data)}));if(!this.constructed)return;const linkDefault=SIZE_LINKABLE_ACTOR_TYPES.has(this.actor.type),linkToActorSize=this.flags.pf2e?.linkToActorSize??linkDefault,autoscaleDefault=game.settings.get("pf2e","tokens.autoscale"),autoscale=linkToActorSize?this.flags.pf2e.autoscale??autoscaleDefault:!1;this.flags.pf2e=mergeObject(this.flags.pf2e??{},{linkToActorSize,autoscale});const{alliance}=this.actor.system.details;this.disposition=this.disposition===CONST.TOKEN_DISPOSITIONS.SECRET?CONST.TOKEN_DISPOSITIONS.SECRET:alliance?{party:CONST.TOKEN_DISPOSITIONS.FRIENDLY,opposition:CONST.TOKEN_DISPOSITIONS.HOSTILE}[alliance]:CONST.TOKEN_DISPOSITIONS.NEUTRAL}_prepareDetectionModes(){if(!(this.constructed&&this.actor&&this.rulesBasedVision))return super._prepareDetectionModes();this.detectionModes=[{id:"basicSight",enabled:!0,range:0}],["character","familiar"].includes(this.actor.type)&&(this.sight.attenuation=.1,this.sight.brightness=0,this.sight.contrast=0,this.sight.range=0,this.sight.saturation=0,this.sight.visionMode="basic")}prepareDerivedData(){if(super.prepareDerivedData(),!(this.constructed&&this.actor&&this.scene))return;const{tokenOverrides}=this.actor.synthetics;this.name=tokenOverrides.name??this.name,tokenOverrides.texture&&(this.texture.src=tokenOverrides.texture.src,"scaleX"in tokenOverrides.texture&&(this.texture.scaleX=tokenOverrides.texture.scaleX,this.texture.scaleY=tokenOverrides.texture.scaleY,this.flags.pf2e.autoscale=!1),this.texture.tint=tokenOverrides.texture.tint??this.texture.tint),this.alpha=tokenOverrides.alpha??this.alpha,tokenOverrides.light&&(this.light=new foundry.data.LightData(tokenOverrides.light,{parent:this})),_TokenDocumentPF2e2.prepareSize(this),__privateMethod(this,_prepareDerivedPerception,prepareDerivedPerception_fn).call(this)}static assignDefaultImage(token){const{actor}=token;if(!actor)return;const defaultIcons=[ActorPF2e.DEFAULT_ICON,`systems/pf2e/icons/default-icons/${actor.type}.svg`];game.settings.get("pf2e","nathMode")&&defaultIcons.includes(token.texture.src)?token.texture.src=(()=>{switch(actor.alliance){case"party":return"systems/pf2e/icons/default-icons/alternatives/nath/ally.webp";case"opposition":return"systems/pf2e/icons/default-icons/alternatives/nath/enemy.webp";default:return token.texture.src}})():defaultIcons.some(path=>token.texture.src?.endsWith(path))&&(token.texture.src=actor._source.img)}static prepareSize(token){const{actor}=token;if(!(actor&&token.flags.pf2e.linkToActorSize))return;const size={tiny:.5,sm:1,med:1,lg:2,huge:3,grg:Math.max(token.width,4)}[actor.size];if(actor.isOfType("vehicle")){const{width,height}=actor.getTokenDimensions();token.width=width,token.height=height}else if(token.width=size,token.height=size,game.settings.get("pf2e","tokens.autoscale")&&token.flags.pf2e.autoscale!==!1){const absoluteScale=actor.size==="sm"?.8:1,mirrorX=token.texture.scaleX<0?-1:1;token.texture.scaleX=mirrorX*absoluteScale;const mirrorY=token.texture.scaleY<0?-1:1;token.texture.scaleY=mirrorY*absoluteScale}}async setInitiative({initiative,sendMessage=!0}){if(!game.combat){ui.notifications.error("PF2E.Encounter.NoActiveEncounter");return}const currentId=game.combat.combatant?.id;this.combatant&&game.combat.combatants.has(this.combatant.id)?await game.combat.setInitiative(this.combatant.id,initiative):await game.combat.createEmbeddedDocuments("Combatant",[{tokenId:this.id,initiative}]),await this.update({turn:game.combat.turns.findIndex(c=>c.id===currentId)}),sendMessage&&await ChatMessagePF2e.createDocuments([{speaker:{scene:this.scene?.id,token:this.id},whisper:this.actor?.hasPlayerOwner?[]:game.users.contents.flatMap(user=>user.isGM?user.id:[]),content:game.i18n.format("PF2E.InitiativeIsNow",{name:this.name,value:initiative})}])}_onCreate(data,options,userId){super._onCreate(data,options,userId),game.user.id===userId&&this.actor?.isOfType("loot")&&this.actor.toggleTokenHiding()}_onUpdate(changed,options,userId){const tokenSetsNameVisibility=game.settings.get("pf2e","metagame_tokenSetsNameVisibility");return"displayName"in changed&&tokenSetsNameVisibility&&this.combatant&&ui.combat.render(),changed.actorLink===!1&&this.rendered&&this.object?.controlled&&this.object.release(),super._onUpdate(changed,options,userId)}_onRelatedUpdate(update={},options={}){super._onRelatedUpdate(update,options);const initializeVision=!!this.scene?.isView&&this.sight.enabled&&Object.keys(flattenObject(update)).some(k=>k.startsWith("system.traits.senses"));initializeVision&&canvas.perception.update({initializeVision},!0);const preUpdate=this.toObject(!1),preUpdateAuras=Array.from(this.auras.values()).map(a=>omit(a,["appearance","token"]));this.reset();const postUpdate=this.toObject(!1),postUpdateAuras=Array.from(this.auras.values()).map(a=>omit(a,["appearance","token"])),tokenChanges=diffObject(preUpdate,postUpdate);this.scene?.isView&&Object.keys(tokenChanges).length>0&&this.object?._onUpdate(tokenChanges,{},game.user.id);const aurasChanged=__name2(()=>!!this.scene?.isInFocus&&!equals(preUpdateAuras,postUpdateAuras),"aurasChanged");("disposition"in tokenChanges||"width"in tokenChanges||"height"in tokenChanges||aurasChanged())&&this.scene?.checkAuras?.()}_onDelete(options,userId){if(super._onDelete(options,userId),!!this.actor)if(this.isLinked)this.scene?.tokens.some(t=>t.actor===this.actor)||this.actor.checkAreaEffects();else for(const effect of this.actor.itemTypes.effect)game.pf2e.effectTracker.unregister(effect)}};_prepareDerivedPerception=new WeakSet,prepareDerivedPerception_fn=__name2(function(){if(!(this.rulesBasedVision&&this.actor&&this.scene&&this.sight.enabled))return;const visionMode=this.hasDarkvision?"darkvision":"basic";this.sight.visionMode=visionMode;const{defaults}=CONFIG.Canvas.visionModes[visionMode].vision;if(this.sight.brightness=defaults.brightness??0,this.sight.saturation=defaults.saturation??0,visionMode==="darkvision"||this.scene.lightLevel>LightLevels.DARKNESS){const basicDetection=this.detectionModes.at(0);if(!basicDetection)return;this.sight.range=basicDetection.range=defaults.range??0,this.actor.isOfType("character")&&this.actor.flags.pf2e.colorDarkvision?this.sight.saturation=1:game.user.settings.monochromeDarkvision||(this.sight.saturation=0)}this.actor.isOfType("character","familiar")&&this.actor.system.traits.senses.some(s=>s.type==="seeInvisibility")&&this.detectionModes.push({id:"seeInvisibility",enabled:!0,range:1e3});const tremorsense=this.actor.isOfType("character")?this.actor.system.traits.senses.find(s=>s.type==="tremorsense"&&s.acuity!=="vague"):null;if(tremorsense&&this.detectionModes.push({id:"feelTremor",enabled:!0,range:tremorsense.range}),!this.actor.hasCondition("deafened")){const range=this.scene.flags.pf2e.hearingRange??canvas.dimensions?.maxR??1/0;this.detectionModes.push({id:"hearing",enabled:!0,range})}},"#prepareDerivedPerception"),__name2(_TokenDocumentPF2e,"TokenDocumentPF2e");let TokenDocumentPF2e=_TokenDocumentPF2e;const _BaseTagSelector=class extends DocumentSheet{static{__name(this,"_BaseTagSelector")}constructor(document2,options={}){super(document2,options),__privateAdd(this,_getChoices),__publicField(this,"choices"),__publicField(this,"flat"),this.flat=options.flat??!1,this.choices=__privateMethod(this,_getChoices,getChoices_fn).call(this)}static get defaultOptions(){return mergeObject(super.defaultOptions,{id:"tag-selector",classes:["pf2e","tag-selector"],width:"auto"})}get id(){return`${this.options.id}-${this.document.uuid}`}get title(){return game.i18n.localize(this.options.title||"PF2E.TraitsLabel")}async getData(options){return{...await super.getData(options),documentType:this.document.constructor.metadata.label}}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const input of htmlQueryAll(html,"input:not([type=checkbox])"))input.addEventListener("focusin",()=>{input.select()})}sortChoices(choices){return Object.entries(choices).map(([key,value])=>[key,game.i18n.localize(value)]).sort(([_keyA,valueA],[_keyB,valueB])=>valueA.localeCompare(valueB)).reduce((accumulated,[key,value])=>mergeObject(accumulated,{[key]:value}),{})}};_getChoices=new WeakSet,getChoices_fn=__name2(function(){const choices=this.configTypes.reduce((types,key)=>mergeObject(types,CONFIG.PF2E[key]),{});return this.sortChoices(choices)},"#getChoices"),__name2(_BaseTagSelector,"BaseTagSelector");let BaseTagSelector=_BaseTagSelector;function isValuesList(value){return!!(value&&typeof value=="object"&&"value"in value)}__name(isValuesList,"isValuesList"),__name2(isValuesList,"isValuesList");const _TagSelectorBasic=class extends BaseTagSelector{static{__name(this,"_TagSelectorBasic")}constructor(document2,options){super(document2,options),__privateAdd(this,_getUpdateData),__privateAdd(this,_search),__privateAdd(this,_onFilterResults),__publicField(this,"allowCustom"),__privateAdd(this,_filterTimeout,null),__publicField(this,"objectProperty"),this.objectProperty=options.objectProperty,this.allowCustom=options.allowCustom??!0,options.customChoices&&(mergeObject(this.choices,options.customChoices),this.choices=this.sortChoices(this.choices))}static get defaultOptions(){return mergeObject(super.defaultOptions,{template:"systems/pf2e/templates/system/tag-selector/basic.hbs"})}get configTypes(){return this.options.configTypes??[]}async getData(options){const{chosen,custom,flat,disabled}=(()=>{const document2=this.document,sourceProperty=getProperty(document2.toObject(),this.objectProperty),preparedProperty=getProperty(document2,this.objectProperty);if(Array.isArray(preparedProperty)){const manuallyChosen=Array.isArray(sourceProperty)?sourceProperty.map(prop=>String(prop)):[],automaticallyChosen=preparedProperty.filter(tag=>!manuallyChosen.includes(tag));return{chosen:Array.from(new Set([...manuallyChosen,...automaticallyChosen])),custom:null,flat:!0,disabled:automaticallyChosen}}else if(isValuesList(preparedProperty)&&isValuesList(sourceProperty)){const manuallyChosen=sourceProperty.value.map(prop=>prop.toString()),custom2=this.allowCustom?sourceProperty.custom:null,automaticallyChosen=preparedProperty.value.filter(tag=>!manuallyChosen.includes(tag));return{chosen:Array.from(new Set([...manuallyChosen,...automaticallyChosen])),custom:custom2,flat:!1,disabled:automaticallyChosen}}else return{chosen:[],custom:null,flat:this.flat,disabled:[]}})(),choices=Object.keys(this.choices).reduce((accumulated,type)=>(accumulated[type]={label:this.choices[type],selected:chosen.includes(type),disabled:disabled.includes(type)},accumulated),{});return{...await super.getData(options),choices,allowCustom:this.allowCustom&&!flat,custom,flat}}activateListeners($html){super.activateListeners($html);const html=$html[0],searchInput=htmlQuery(html,"input[type=search]");searchInput?.addEventListener("input",()=>{__privateMethod(this,_onFilterResults,onFilterResults_fn).call(this,searchInput)})}async _updateObject(event,formData){const{flat}=event.target?$(event.target).data():{flat:!1},value=__privateMethod(this,_getUpdateData,getUpdateData_fn).call(this,formData);return this.allowCustom&&typeof formData.custom=="string"?super._updateObject(event,{[this.objectProperty]:{value,custom:formData.custom}}):flat?super._updateObject(event,{[this.objectProperty]:value}):super._updateObject(event,{[`${this.objectProperty}.value`]:value})}};_filterTimeout=new WeakMap,_getUpdateData=new WeakSet,getUpdateData_fn=__name2(function(formData){const optionsAreNumeric=Object.keys(formData).every(tag=>Number.isInteger(Number(tag))),selections=Object.entries(formData).flatMap(([tag,selected])=>selected?tag:[]).filter(tag=>tag!=="custom");return optionsAreNumeric?selections.map(tag=>Number(tag)):selections},"#getUpdateData"),_search=new WeakSet,search_fn=__name2(function(searchString){const query=new RegExp(RegExp.escape(searchString),"i"),html=this.element[0];for(const row of htmlQueryAll(html,"li.trait-item")){const name2=row.getElementsByClassName("trait-label")[0]?.textContent??"";row.style.display=query.test(name2)?"flex":"none"}},"#search"),_onFilterResults=new WeakSet,onFilterResults_fn=__name2(function(input){__privateGet(this,_filterTimeout)&&(clearTimeout(__privateGet(this,_filterTimeout)),__privateSet(this,_filterTimeout,null)),__privateSet(this,_filterTimeout,window.setTimeout(()=>__privateMethod(this,_search,search_fn).call(this,input.value),100))},"#onFilterResults"),__name2(_TagSelectorBasic,"TagSelectorBasic");let TagSelectorBasic=_TagSelectorBasic;const _SenseSelector=class extends BaseTagSelector{static{__name(this,"_SenseSelector")}objectProperty="system.traits.senses";static get defaultOptions(){return mergeObject(super.defaultOptions,{height:"auto",template:"systems/pf2e/templates/system/tag-selector/senses.hbs",id:"sense-selector",title:"PF2E.Actor.Creature.Sense.Label"})}get configTypes(){return["senses"]}async getData(options){if(!this.document.isOfType("character"))throw ErrorPF2e("The Sense selector is usable only with PCs");const senses2=this.document.system.traits.senses,choices=Object.entries(this.choices).reduce((accum,[type,label])=>{const sense=senses2.find(sense2=>sense2.type===type),mandatoryAcuity=objectHasKey(SENSES_WITH_MANDATORY_ACUITIES,type),acuity=mandatoryAcuity?SENSES_WITH_MANDATORY_ACUITIES[type]:sense?.acuity??"precise";return{...accum,[type]:{acuity,mandatoryAcuity,disabled:!!sense?.source,label,selected:!!sense,value:sense?.value??""}}},{});return{...await super.getData(options),hasExceptions:!1,choices,senseAcuity:CONFIG.PF2E.senseAcuity}}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const input of htmlQueryAll(html,"input[type=number]")){const checkbox=htmlQuery(htmlClosest(input,"tr"),"input[type=checkbox]");checkbox&&input.addEventListener("input",()=>{checkbox.checked=!!Number(input.value)})}}_onSubmit(event,options){for(const input of htmlQueryAll(this.element[0],"input[type=number]")){const checkbox=htmlQuery(htmlClosest(input,"tr"),"input[type=checkbox]");checkbox&&!Number(input.value)&&(checkbox.checked=!1)}return super._onSubmit(event,options)}async _updateObject(event,formData){const update=Object.entries(formData).filter(e=>e[1]===!0||Array.isArray(e[1])&&e[1][0]).map(([type,values])=>{if(values===!0)return{type};if(Number(values[2])){const acuity=values[1],range=Number(values[2]);return{type,acuity,value:range}}else{const acuity=values[1];return{type,acuity}}});return super._updateObject(event,{[this.objectProperty]:update})}};__name2(_SenseSelector,"SenseSelector");let SenseSelector=_SenseSelector;const _SpeedSelector=class extends BaseTagSelector{static{__name(this,"_SpeedSelector")}objectProperty="system.attributes.speed.otherSpeeds";static get defaultOptions(){return mergeObject(super.defaultOptions,{id:"speed-selector",template:"systems/pf2e/templates/system/tag-selector/speeds.hbs",title:"PF2E.SpeedTypes"})}get configTypes(){return["speedTypes"]}async getData(options){if(!this.document.isOfType("creature"))throw ErrorPF2e("The Speed selector is usable only with creature-type actors");const speeds=this.document.system.attributes.speed.otherSpeeds,speedLabels=CONFIG.PF2E.speedTypes,choices=Object.keys(this.choices).reduce((accum,type)=>{const speed=speeds.find(s=>s.type===type);return{...accum,[type]:{selected:!!speed,disabled:!!speed?.source,label:game.i18n.localize(speedLabels[type]),value:Number(speed?.value)||""}}},{});return{...await super.getData(options),hasExceptions:this.document.isOfType("npc"),choices}}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const input of htmlQueryAll(html,"input[type=number]"))input.addEventListener("input",()=>{const checkbox=input.closest("li")?.querySelector("input[type=checkbox]");checkbox&&(checkbox.checked=!!Number(input.value))})}async _updateObject(event,formData){const update=Object.entries(formData).flatMap(([key,value])=>{if(!(Array.isArray(value)&&value.length===2))return[];const selected=!!value[0],distance=Math.trunc(Math.abs(value[1]));return selected&&distance?{type:key,value:Math.max(distance,5)}:[]});return super._updateObject(event,{[this.objectProperty]:update})}};__name2(_SpeedSelector,"SpeedSelector");let SpeedSelector=_SpeedSelector;const TAG_SELECTOR_TYPES=["basic","senses","speed-types"],SELECTABLE_TAG_FIELDS=["abilities","actionTraits","attackEffects","creatureTraits","damageCategories","languages","levels","materialDamageEffects","otherArmorTags","otherConsumableTags","otherWeaponTags","senses","skills","speedTypes","vehicleTraits","weaponTraits"],_UUIDUtils=class{static{__name(this,"_UUIDUtils")}static async fromUUIDs(uuids,options){const resolvedUUIDs=uniq(uuids).flatMap(u=>foundry.utils.parseUuid(u,options).uuid??[]),packEmbeddedLinks=resolvedUUIDs.filter(u=>{const parsed=foundry.utils.parseUuid(u,options);return parsed.collection instanceof CompendiumCollection&&parsed.embedded.length>0}),packEmbeddedDocs=compact(await Promise.all(packEmbeddedLinks.map(u=>fromUuid(u)))),documentsAndIndexData=compact(resolvedUUIDs.filter(u=>!packEmbeddedLinks.includes(u)).map(u=>fromUuidSync(u))),worldDocsAndCacheHits=documentsAndIndexData.filter(d=>d instanceof foundry.abstract.Document),indexEntries=documentsAndIndexData.filter(d=>!(d instanceof foundry.abstract.Document)),packs=uniq(indexEntries.flatMap(e=>game.packs.get(e.pack??"")??[])),packDocs=(await Promise.all(packs.map(async pack=>{const ids=indexEntries.filter(e=>e.pack===pack.metadata.id).map(e=>e._id);return pack.getDocuments({_id__in:ids})}))).flat();return sortBy$1([...packEmbeddedDocs,...worldDocsAndCacheHits,...packDocs],d=>uuids.indexOf(d.uuid))}static isItemUUID(uuid){return typeof uuid=="string"&&foundry.utils.parseUuid(uuid).documentType==="Item"}static isCompendiumUUID(uuid){return typeof uuid=="string"&&foundry.utils.parseUuid(uuid).collection instanceof CompendiumCollection}static isTokenUUID(uuid){if(typeof uuid!="string")return!1;const parsed=foundry.utils.parseUuid(uuid);return parsed.documentType==="Scene"&&parsed.embedded[0]==="Token"}};__name2(_UUIDUtils,"UUIDUtils");let UUIDUtils=_UUIDUtils;const _ActorSizePF2e=class _ActorSizePF2e2{static{__name(this,"_ActorSizePF2e")}value;length;width;constructor(params){(typeof params.value!="string"||params.smallIsMedium&¶ms.value==="sm")&&(params.value="med"),this.value=params.value;const spaces=_ActorSizePF2e2.defaultSpaces[params.value]??_ActorSizePF2e2.defaultSpaces.med;this.length=params.length??spaces.length,this.width=params.width??spaces.width}equals(size,{smallIsMedium=!1}={}){const thisSize=this.getEffectiveSize(this.value,{smallIsMedium}),otherSize=this.getEffectiveSize(size.value,{smallIsMedium});return thisSize===otherSize}isLargerThan(size,{smallIsMedium=!1}={}){const other=size instanceof _ActorSizePF2e2?size:new _ActorSizePF2e2({value:size}),thisSize=this.getEffectiveSize(this.value,{smallIsMedium}),otherSize=this.getEffectiveSize(other.value,{smallIsMedium});return _ActorSizePF2e2.sizeRanks[thisSize]>_ActorSizePF2e2.sizeRanks[otherSize]}isSmallerThan(size,{smallIsMedium=!1}={}){const other=size instanceof _ActorSizePF2e2?size:new _ActorSizePF2e2({value:size}),thisSize=this.getEffectiveSize(this.value,{smallIsMedium}),otherSize=this.getEffectiveSize(other.value,{smallIsMedium});return _ActorSizePF2e2.sizeRanks[thisSize]<_ActorSizePF2e2.sizeRanks[otherSize]}difference(size,{smallIsMedium=!1}={}){const thisSize=this.getEffectiveSize(this.value,{smallIsMedium}),otherSize=this.getEffectiveSize(size.value,{smallIsMedium});return _ActorSizePF2e2.sizeRanks[thisSize]-_ActorSizePF2e2.sizeRanks[otherSize]}getEffectiveSize(size,{smallIsMedium}){return smallIsMedium&&size==="sm"?"med":size}increment({skipSmall=!1}={}){this.value=this.value==="tiny"&&skipSmall?"med":this.value==="sm"&&skipSmall?"lg":this.value==="grg"?"grg":SIZES[SIZES.indexOf(this.value)+1];const newSpace=_ActorSizePF2e2.defaultSpaces[this.value];this.length=newSpace.length,this.width=newSpace.width}decrement({skipSmall=!1}={}){const toTiny=this.value==="med"&&skipSmall||this.value==="tiny";this.value=toTiny?"tiny":SIZES[SIZES.indexOf(this.value)-1];const newSpace=_ActorSizePF2e2.defaultSpaces[this.value];this.length=newSpace.length,this.width=newSpace.width}toString(){return game.i18n.localize(CONFIG.PF2E.actorSizes[this.value])}};__name2(_ActorSizePF2e,"ActorSizePF2e"),__publicField(_ActorSizePF2e,"defaultSpaces",{tiny:{length:2.5,width:2.5},sm:{length:5,width:5},med:{length:5,width:5},lg:{length:10,width:10},huge:{length:15,width:15},grg:{length:20,width:20}}),__publicField(_ActorSizePF2e,"sizeRanks",{grg:5,huge:4,lg:3,med:2,sm:1,tiny:0});let ActorSizePF2e=_ActorSizePF2e;function onClickCreateSpell(actor,data){if(!data.location)throw ErrorPF2e("Unexpected missing spellcasting-entry location");const rank=Number(data.level??1),newLabel=game.i18n.localize("PF2E.NewLabel"),[rankLabel,spellLabel]=rank>0?[game.i18n.localize(`PF2E.SpellLevel${rank}`),game.i18n.localize(data.location==="rituals"?"PF2E.SpellCategoryRitual":"PF2E.SpellLabel")]:[null,game.i18n.localize("PF2E.TraitCantrip")],source={type:"spell",name:compact([newLabel,rankLabel,spellLabel]).join(" "),system:{level:{value:rank||1},location:{value:String(data.location)},traits:{value:rank===0?["cantrip"]:[]}}};data.location==="rituals"&&(source.system=mergeObject(source.system,{category:{value:"ritual"}})),actor.createEmbeddedDocuments("Item",[source])}__name(onClickCreateSpell,"onClickCreateSpell"),__name2(onClickCreateSpell,"onClickCreateSpell");function getSelectedOrOwnActors(types,useOwnCharacter=!0){const actors=canvas.tokens.controlled.flatMap(token=>token.actor?token.actor:[]).filter(actor=>actor.isOwner).filter(actor=>!types||actor.isOfType(...types));return actors.length===0&&game.user.character&&useOwnCharacter&&actors.push(game.user.character),actors}__name(getSelectedOrOwnActors,"getSelectedOrOwnActors"),__name2(getSelectedOrOwnActors,"getSelectedOrOwnActors");const inlineSelector=["action","check","effect-area"].map(keyword=>`[data-pf2-${keyword}]`).join(","),InlineRollLinks={injectRepostElement:(links,foundryDoc)=>{for(const link of links){(!foundryDoc||foundryDoc.isOwner)&&link.classList.add("with-repost");const repostButtons=htmlQueryAll(link,"i[data-pf2-repost]");if(repostButtons.length>0){if(foundryDoc&&!foundryDoc.isOwner){for(const button of repostButtons)button.remove();link.classList.remove("with-repost")}continue}if(foundryDoc&&!foundryDoc.isOwner)continue;const newButton=document.createElement("i"),icon=link.parentElement?.dataset?.pf2Checkgroup!==void 0?"fa-comment-alt-dots":"fa-comment-alt";newButton.classList.add("fa-solid",icon),newButton.dataset.pf2Repost="",newButton.title=game.i18n.localize("PF2E.Repost"),link.appendChild(newButton),newButton.addEventListener("click",event=>{event.stopPropagation();const target=event.target;if(!(target instanceof HTMLElement))return;const parent=target?.parentElement;if(!parent)return;const document2=resolveDocument(target,foundryDoc);InlineRollLinks.repostAction(parent,document2)})}},listen:(html,foundryDoc=null)=>{foundryDoc??=resolveDocument(html,foundryDoc);const links=htmlQueryAll(html,inlineSelector).filter(l=>["A","SPAN"].includes(l.nodeName));InlineRollLinks.injectRepostElement(links,foundryDoc),InlineRollLinks.flavorDamageRolls(html,foundryDoc instanceof ActorPF2e?foundryDoc:null);for(const link of links.filter(l=>l.dataset.pf2Action)){const{pf2Action,pf2Glyph,pf2Variant,pf2Dc,pf2ShowDc,pf2Skill}=link.dataset;link.addEventListener("click",event=>{const action2=game.pf2e.actions[pf2Action?sluggify(pf2Action,{camel:"dromedary"}):""],visibility=pf2ShowDc??"all";pf2Action&&action2?action2({event,glyph:pf2Glyph,variant:pf2Variant,difficultyClass:pf2Dc?{scope:"check",value:Number(pf2Dc)||0,visibility}:void 0,skill:pf2Skill}):console.warn(`PF2e System | Skip executing unknown action '${pf2Action}'`)})}for(const link of links.filter(l=>l.dataset.pf2Check&&!l.dataset.invalid)){const{pf2Check,pf2Dc,pf2Traits,pf2Label,pf2Defense,pf2Adjustment,pf2Roller,pf2RollOptions}=link.dataset;if(!pf2Check)return;link.addEventListener("click",async event=>{const parent=resolveActor(foundryDoc,link),actors=(()=>{switch(pf2Roller){case"self":return parent?.canUserModify(game.user,"update")?[parent]:[];case"party":return parent?.isOfType("party")?[parent]:compact([game.actors.party])}const actors2=getSelectedOrOwnActors(),isSave=tupleHasValue(SAVE_TYPES,pf2Check);return parent?.isOfType("party")||actors2.length===0&&parent&&!isSave?[parent]:actors2})();if(actors.length===0){ui.notifications.warn(game.i18n.localize("PF2E.UI.errorTargetToken"));return}const extraRollOptions=[...pf2Traits?.split(",").map(o=>o.trim())??[],...pf2RollOptions?.split(",").map(o=>o.trim())??[]],eventRollParams=eventToRollParams(event);switch(pf2Check){case"flat":{for(const actor of actors){const flatCheck=new Statistic(actor,{label:"",slug:"flat",modifiers:[],check:{type:"flat-check"}}),dc=Number.isInteger(Number(pf2Dc))?{label:pf2Label,value:Number(pf2Dc)}:null;flatCheck.roll({...eventRollParams,extraRollOptions,dc})}break}default:{const isSavingThrow=tupleHasValue(SAVE_TYPES,pf2Check),traits=isSavingThrow?[]:extraRollOptions.filter(t=>t in CONFIG.PF2E.actionTraits)??[];for(const actor of actors){const statistic=(()=>{if(pf2Check in CONFIG.PF2E.magicTraditions){const bestSpellcasting=actor.spellcasting.filter(c=>c.tradition===pf2Check).flatMap(s=>s.statistic??[]).sort((a,b)=>b.check.mod-a.check.mod).shift()??null;if(bestSpellcasting)return bestSpellcasting}return actor.getStatistic(pf2Check)})();if(!statistic){console.warn(ErrorPF2e(`Skip rolling unknown statistic ${pf2Check}`).message);continue}const targetActor=pf2Defense?game.user.targets.first()?.actor:null,dcValue=(()=>{const adjustment=Number(pf2Adjustment)||0;return pf2Dc==="@self.level"?calculateDC(actor.level)+adjustment:Number(pf2Dc??"NaN")+adjustment})(),dc=(()=>{if(Number.isInteger(dcValue))return{label:pf2Label,value:dcValue};if(pf2Defense){const defenseStat=targetActor?.getStatistic(pf2Defense);return defenseStat?{statistic:defenseStat.dc,scope:"check",value:defenseStat.dc.value}:null}return null})(),item=(()=>{const itemFromDoc=foundryDoc instanceof ItemPF2e?foundryDoc:foundryDoc instanceof ChatMessagePF2e?foundryDoc.item:null;return itemFromDoc?.isOfType("action","feat","campaignFeature")||isSavingThrow&&!itemFromDoc?.isOfType("weapon")?itemFromDoc:null})(),args={...eventRollParams,extraRollOptions,origin:isSavingThrow&&parent instanceof ActorPF2e?parent:null,dc,target:!isSavingThrow&&dc?.statistic?targetActor:null,item,traits};if(!!(item?.isOfType("action","feat")&&item.actionCost)&&pf2Defense){const subtitleLocKey=pf2Check in CONFIG.PF2E.magicTraditions?"PF2E.ActionsCheck.spell":statistic.check.type==="attack-roll"?"PF2E.ActionsCheck.x-attack-roll":"PF2E.ActionsCheck.x";args.label=await renderTemplate("systems/pf2e/templates/chat/action/header.hbs",{glyph:getActionGlyph(item.actionCost),subtitle:game.i18n.format(subtitleLocKey,{type:statistic.label}),title:item.name})}statistic.roll(args)}}}})}const templateConversion={burst:"circle",cone:"cone",cube:"rect",emanation:"circle",line:"ray",rect:"rect",square:"rect"};for(const link of links.filter(l=>l.hasAttribute("data-pf2-effect-area"))){const{pf2EffectArea,pf2Distance,pf2TemplateData,pf2Traits,pf2Width}=link.dataset;link.addEventListener("click",()=>{if(typeof pf2EffectArea!="string"){console.warn("PF2e System | Could not create template'");return}const templateData=JSON.parse(pf2TemplateData??"{}");switch(templateData.distance||=Number(pf2Distance),templateData.fillColor||=game.user.color,templateData.t=templateConversion[pf2EffectArea],templateData.t){case"ray":templateData.width=Number(pf2Width)||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}}pf2Traits&&(templateData.flags={pf2e:{origin:{traits:pf2Traits.split(",")}}});const templateDoc=new MeasuredTemplateDocumentPF2e(templateData,{parent:canvas.scene});new MeasuredTemplatePF2e(templateDoc).drawPreview()})}},makeRepostHtml:(target,defaultVisibility)=>{const flavor=target.attributes.getNamedItem("data-pf2-repost-flavor")?.value??"";return`${flavor} ${target.outerHTML}`.trim()},repostAction:(target,foundryDoc=null)=>{if(!["pf2Action","pf2Check","pf2EffectArea"].some(d=>d in target.dataset))return;const actor=resolveActor(foundryDoc,target),defaultVisibility=(actor??foundryDoc)?.hasPlayerOwner?"all":"gm",content=(()=>target.parentElement?.dataset?.pf2Checkgroup!==void 0?`
${htmlQueryAll(target.parentElement,inlineSelector).map(target2=>InlineRollLinks.makeRepostHtml(target2,defaultVisibility)).join("
")}
`:InlineRollLinks.makeRepostHtml(target,defaultVisibility))(),speaker=actor?ChatMessagePF2e.getSpeaker({actor,token:actor.getActiveTokens(!1,!0).shift()}):ChatMessagePF2e.getSpeaker(),message=game.messages.get(htmlClosest(target,"[data-message-id]")?.dataset.messageId??""),flags=foundryDoc instanceof JournalEntry?{pf2e:{journalEntry:foundryDoc.uuid}}:message?.flags.pf2e.origin?{pf2e:{origin:deepClone(message.flags.pf2e.origin)}}:{};ChatMessagePF2e.create({speaker,content,flags})},flavorDamageRolls(html,actor=null){for(const rollLink of htmlQueryAll(html,"a.inline-roll[data-damage-roll]")){const itemId=htmlClosest(rollLink,"[data-item-id]")?.dataset.itemId,item=actor?.items.get(itemId??"");item&&(rollLink.dataset.flavor||=item.name)}}};function resolveDocument(html,foundryDoc){if(foundryDoc)return foundryDoc;const document2=(ui.windows[Number(html.closest(".app.sheet")?.dataset.appid)]??null)?.document;return document2 instanceof ActorPF2e||document2 instanceof JournalEntry?document2:null}__name(resolveDocument,"resolveDocument"),__name2(resolveDocument,"resolveDocument");function resolveActor(foundryDoc,anchor){if(foundryDoc instanceof ActorPF2e)return foundryDoc;if(foundryDoc instanceof ItemPF2e||foundryDoc instanceof ChatMessagePF2e)return foundryDoc.actor;const itemUuid=anchor.dataset.itemUuid,itemByUUID=itemUuid&&!itemUuid.startsWith("Compendium.")?fromUuidSync(itemUuid):null;return itemByUUID instanceof ItemPF2e?itemByUUID.actor:null}__name(resolveActor,"resolveActor"),__name2(resolveActor,"resolveActor");const _UserVisibilityPF2e=class{static{__name(this,"_UserVisibilityPF2e")}static process(html,options={}){const visibilityElements=htmlQueryAll(html,"[data-visibility]");for(const element of visibilityElements.filter(e=>e.dataset.visibility==="none"))element.remove();const{message}=options,document2=options.document??message?.actor??message?.journalEntry??message??null;if(document2){const ownerElements=visibilityElements.filter(e=>e.dataset.visibility==="owner");for(const element of ownerElements){if(element.dataset.action){document2.isOwner||element.remove(),delete element.dataset.visibility;continue}const whoseData=element.dataset.whose??"self";if(whoseData==="self"){element.dataset.visibility=document2.hasPlayerOwner?"all":"gm";continue}message?.target&&whoseData==="target"&&(element.dataset.visibility=message.target.actor.hasPlayerOwner?"all":"gm")}}const hasOwnership=document2?.isOwner??game.user.isGM,dcSetting=game.settings.get("pf2e","metagame_showDC"),saveButtons=htmlQueryAll(html,"button[data-action=save]");if(!document2?.hasPlayerOwner&&!hasOwnership&&!dcSetting)for(const button of saveButtons){const saveType=button.dataset.save;if(objectHasKey(CONFIG.PF2E.saves,saveType)){const saveName=game.i18n.localize(CONFIG.PF2E.saves[saveType]);button.innerText=game.i18n.format("PF2E.SavingThrowWithName",{saveName})}}else if(!document2?.hasPlayerOwner&&!dcSetting)for(const button of saveButtons)button.classList.add("hidden-to-others");for(const element of htmlQueryAll(html,"[data-owner-title]"))if(hasOwnership){const value=element.dataset.ownerTitle??"";element.title=value}else element.removeAttribute("data-owner-title");if(!game.user.isGM)for(const element of visibilityElements.filter(e=>e.dataset.visibility==="gm"))element.remove()}static processMessageSender(message,html){if(!game.settings.get("pf2e","metagame_tokenSetsNameVisibility"))return;const token=message.token??(message.actor?new TokenDocumentPF2e(message.actor.prototypeToken.toObject()):null);if(token){const sender=html.querySelector("h4.message-sender"),nameToHide=token.name.trim(),shouldHideName=!token.playersCanSeeName&&sender?.innerText.trim()===nameToHide;sender&&shouldHideName&&(game.user.isGM?sender.dataset.visibility="gm":sender.innerText=message.user?.name??"Gamemaster")}}};__name2(_UserVisibilityPF2e,"UserVisibilityPF2e");let UserVisibilityPF2e=_UserVisibilityPF2e;const USER_VISIBILITIES=new Set(["all","owner","gm","none"]),_ItemSummaryRenderer=class{static{__name(this,"_ItemSummaryRenderer")}constructor(sheet){this.sheet=sheet}activateListeners(html){const selectors=[".item .item-name h4",".item .melee-name h4",".item .action-name h4","a[data-action=toggle-summary]"].join(",");for(const link of htmlQueryAll(html,selectors))link.addEventListener("click",async()=>{const element=htmlClosest(link,"[data-item-id], .expandable");element&&await this.toggleSummary(element)})}async toggleSummary(element,options={}){const actor=this.sheet.actor,{itemId,itemType,actionIndex}=element.dataset,isFormula=!!element.dataset.isFormula,duration=.4;if(itemType==="spellSlot")return;const item=isFormula?await fromUuid(itemId??""):itemType==="condition"?actor.conditions.get(itemId,{strict:!0}):actionIndex?actor.system.actions?.[Number(actionIndex)].item??null:actor.items.get(itemId??"")??null,summary=await(async()=>{const existing=htmlQuery(element,":scope > .item-summary");if(existing?.hasChildNodes()||options.visible)return existing;if(item instanceof ItemPF2e&&!item.isOfType("spellcastingEntry")){const insertLocation=htmlQueryAll(element,":scope > .item-name, :scope > .item-controls, :scope > .action-header").at(-1)?.parentNode?.lastChild;if(!insertLocation&&!existing)return null;const summary2=existing??createHTMLElement("div",{classes:["item-summary"]});summary2.hidden=!0,insertLocation?.after(summary2);const chatData=await item.getChatData({secrets:actor.isOwner},element.dataset);return await this.renderItemSummary(summary2,item,chatData),InlineRollLinks.listen(summary2,item),summary2}return null})();if(!summary)return;const showSummary=typeof options.visible=="boolean"?options.visible:!element.classList.contains("expanded")||summary.hidden;options.instant?(summary.hidden=!showSummary,element.classList.toggle("expanded",showSummary)):showSummary?(element.classList.add("expanded"),await gsap.fromTo(summary,{height:0,opacity:0,hidden:!1},{height:"auto",opacity:1,duration})):await gsap.to(summary,{height:0,duration,opacity:0,paddingTop:0,paddingBottom:0,margin:0,clearProps:"all",onComplete:()=>{summary.hidden=!0,element.classList.remove("expanded")}})}async renderItemSummary(div,item,chatData){const description=isItemSystemData(chatData)?chatData.description.value:await TextEditor.enrichHTML(item.description,{rollData:item.getRollData(),async:!0}),rarity=item.system.traits?.rarity,isEffect=item instanceof AbstractEffectPF2e,selfEffect=item.isOfType("action","feat")&&item.system.selfEffect?await TextEditor.enrichHTML(`@UUID[${item.system.selfEffect.uuid}]{${item.system.selfEffect.name}}`,{async:!0}):null,summary=await renderTemplate("systems/pf2e/templates/actors/partials/item-summary.hbs",{item,description,identified:game.user.isGM||!(item.isOfType("physical")||isEffect)||item.isIdentified,rarityLabel:rarity&&item.isOfType("physical")?CONFIG.PF2E.rarityTraits[rarity]:null,isCreature:item.actor?.isOfType("creature"),chatData,selfEffect});if(div.innerHTML=summary,UserVisibilityPF2e.process(div,{document:item}),item.actor?.isOfType("creature"))for(const button of htmlQueryAll(div,"button"))button.addEventListener("click",event=>{event.preventDefault(),event.stopPropagation();const spell=item.isOfType("spell")?item:item.isOfType("consumable")?item.embeddedSpell:null;switch(button.dataset.action){case"spellAttack":spell?.rollAttack(event);break;case"spellDamage":spell?.rollDamage(event);break;case"consume":item.isOfType("consumable")&&item.consume();break}})}async saveAndRestoreState(callback){const element=this.sheet.element[0],expandedSummaryElements=htmlQueryAll(element,".item.expanded[data-item-summary-id]"),expandedItemElements=htmlQueryAll(element,".item.expanded[data-item-id]:not([data-item-summary-id])"),expandedActionElements=htmlQueryAll(element,".item.expanded[data-action-index]"),openActionIdxs=new Set(expandedActionElements.map(el=>el.dataset.actionIndex)),openItemsIds=expandedItemElements.map(el=>el.dataset.itemId),openSummaryIds=expandedSummaryElements.map(el=>el.dataset.itemSummaryId),$result=await callback.apply(null),result=$result[0];InlineRollLinks.listen(result,this.sheet.actor);for(const itemId of openItemsIds){const item=htmlQuery(result,`.item[data-item-id="${itemId}"]:not([data-item-summary-id])`);item&&await this.toggleSummary(item,{instant:!0})}for(const summaryId of openSummaryIds){const item=htmlQuery(result,`.item[data-item-summary-id="${summaryId}"]`);item&&await this.toggleSummary(item,{instant:!0})}for(const elementIdx of openActionIdxs)$result.find(`.item[data-action-index=${elementIdx}]`).toggleClass("expanded");return $result}};__name2(_ItemSummaryRenderer,"ItemSummaryRenderer");let ItemSummaryRenderer=_ItemSummaryRenderer;const _MoveLootPopup=class extends FormApplication{static{__name(this,"_MoveLootPopup")}onSubmitCallback;constructor(object,options,callback){super(object,options),this.onSubmitCallback=callback}async getData(){const[prompt,buttonLabel]=this.options.isPurchase?["PF2E.loot.PurchaseLootMessage","PF2E.loot.PurchaseLoot"]:["PF2E.loot.MoveLootMessage","PF2E.loot.MoveLoot"];return{...await super.getData(),quantity:{default:this.options.quantity.default,max:this.options.quantity.max},newStack:this.options.newStack,lockStack:this.options.lockStack,prompt,buttonLabel}}static get defaultOptions(){return{...super.defaultOptions,id:"MoveLootPopup",classes:[],title:game.i18n.localize("PF2E.loot.MoveLootPopupTitle"),template:"systems/pf2e/templates/popups/loot/move-loot-popup.hbs",width:"auto",quantity:{default:1,max:1},newStack:!1,lockStack:!1,isPurchase:!1}}async _updateObject(_event,formData){this.onSubmitCallback(formData.quantity,formData.newStack)}};__name2(_MoveLootPopup,"MoveLootPopup");let MoveLootPopup=_MoveLootPopup;const _AddCoinsPopup=class extends FormApplication{static{__name(this,"_AddCoinsPopup")}static get defaultOptions(){return{...super.defaultOptions,id:"add-coins",title:"PF2E.AddCoinsTitle",template:"systems/pf2e/templates/actors/add-coins.hbs"}}async _updateObject(_event,formData){const combineStacks=!!formData.combineStacks,coins={pp:Number(formData.pp)||0,gp:Number(formData.gp)||0,sp:Number(formData.sp)||0,cp:Number(formData.cp)||0};return this.object.inventory.addCoins(coins,{combineStacks})}};__name2(_AddCoinsPopup,"AddCoinsPopup");let AddCoinsPopup=_AddCoinsPopup;const itemTypeOptions=Object.fromEntries(new Map([["scroll","PF2E.CastingItemCreateDialog.scroll"],["wand","PF2E.CastingItemCreateDialog.wand"],["cantripDeck5","PF2E.CastingItemCreateDialog.cantripDeck5"]])),_CastingItemCreateDialog=class extends FormApplication{static{__name(this,"_CastingItemCreateDialog")}onSubmitCallback;spell;formDataCache;constructor(object,options,callback,spell){super(object,options),this.spell=spell,this.formDataCache={itemType:this.spell.isCantrip?"cantripDeck5":"scroll",level:spell.baseRank},this.onSubmitCallback=callback}static get defaultOptions(){const options=super.defaultOptions;return options.classes=[],options.title=game.i18n.localize("PF2E.CastingItemCreateDialog.title"),options.template="systems/pf2e/templates/popups/casting-item-create-dialog.hbs",options.width="auto",options.submitOnChange=!0,options.closeOnSubmit=!1,options}async getData(){if(!this.spell)throw ErrorPF2e("CastingItemCreateDialog | Could not read spelldata");const{cantripDeck5,...nonCantripOptions}=itemTypeOptions,minimumRank=this.spell.baseRank,ranks=Array.from(Array(11-minimumRank).keys()).map(index=>minimumRank+index);return{...await super.getData(),validLevels:ranks,itemTypeOptions:this.spell.isCantrip?{cantripDeck5}:nonCantripOptions,itemType:this.formDataCache.itemType,level:this.formDataCache.level}}async _updateObject(event,formData){if(Object.assign(this.formDataCache,formData),event.type!=="submit"){await this.render();return}this.formDataCache.itemType==="wand"&&this.formDataCache.level===10?ui.notifications.warn(game.i18n.localize("PF2E.CastingItemCreateDialog.10thLevelWand")):this.onSubmitCallback&&this.spell&&this.onSubmitCallback(this.formDataCache.level,this.formDataCache.itemType,this.spell),this.close()}};__name2(_CastingItemCreateDialog,"CastingItemCreateDialog");let CastingItemCreateDialog=_CastingItemCreateDialog;function getMagicTraditions(item){const traits=item.system.traits.value;return new Set(traits.filter(t=>setHasElement(MAGIC_TRADITIONS,t)))}__name(getMagicTraditions,"getMagicTraditions"),__name2(getMagicTraditions,"getMagicTraditions");function getDcRarity(item){return item.traits.has("cursed")?"unique":item.rarity}__name(getDcRarity,"getDcRarity"),__name2(getDcRarity,"getDcRarity");function getIdentifyMagicDCs(item,baseDC,notMatchingTraditionModifier){const result={occult:baseDC,primal:baseDC,divine:baseDC,arcane:baseDC},traditions=getMagicTraditions(item);for(const key of MAGIC_TRADITIONS)traditions.size>0&&!traditions.has(key)&&(result[key]=baseDC+notMatchingTraditionModifier);return{arcana:result.arcane,nature:result.primal,religion:result.divine,occultism:result.occult}}__name(getIdentifyMagicDCs,"getIdentifyMagicDCs"),__name2(getIdentifyMagicDCs,"getIdentifyMagicDCs");function getItemIdentificationDCs(item,{proficiencyWithoutLevel=!1,notMatchingTraditionModifier}){const baseDC=calculateDC(item.level,{proficiencyWithoutLevel}),rarity=getDcRarity(item),dc=adjustDCByRarity(baseDC,rarity);return item.isMagical?getIdentifyMagicDCs(item,dc,notMatchingTraditionModifier):item.isAlchemical?{crafting:dc}:{dc}}__name(getItemIdentificationDCs,"getItemIdentificationDCs"),__name2(getItemIdentificationDCs,"getItemIdentificationDCs");function getUnidentifiedPlaceholderImage(item){return`systems/pf2e/icons/unidentified_item_icons/${(()=>{if(item.isOfType("weapon")){const{traits}=item;return traits.has("bomb")?"alchemical_bomb":traits.has("staff")?"staves":traits.has("artifact")?"artifact":"weapon"}else{if(item.isOfType("armor"))return item.category==="shield"?"shields":"armor";if(item.isOfType("consumable"))switch(item.category){case"ammo":return"ammunition";case"oil":return"oils";case"scroll":return"infernal-contracts";case"talisman":return"talisman";case"elixir":case"mutagen":return"alchemical_elixir";case"poison":return"alchemical_poison";case"tool":return"alchemical_tool";case"wand":return"wands";case"potion":return"potions";case"snare":case"other":default:return item.traits.has("drug")?"drugs":"other-consumables"}else if(item.isOfType("equipment")&&item.traits.has("precious"))return"material-chunk"}return"adventuring_gear"})()}.webp`}__name(getUnidentifiedPlaceholderImage,"getUnidentifiedPlaceholderImage"),__name2(getUnidentifiedPlaceholderImage,"getUnidentifiedPlaceholderImage");const _IdentifyItemPopup=class extends FormApplication{static{__name(this,"_IdentifyItemPopup")}static get defaultOptions(){return{...super.defaultOptions,id:"identify-item",title:game.i18n.localize("PF2E.identification.Identify"),template:"systems/pf2e/templates/actors/identify-item.hbs",width:"auto",classes:["identify-popup"]}}get item(){return this.object}async getData(){const item=this.object,notMatchingTraditionModifier=game.settings.get("pf2e","identifyMagicNotMatchingTraditionModifier"),proficiencyWithoutLevel=game.settings.get("pf2e","proficiencyVariant"),dcs=getItemIdentificationDCs(item,{proficiencyWithoutLevel,notMatchingTraditionModifier});return{...await super.getData(),isMagic:item.isMagical,isAlchemical:item.isAlchemical,dcs}}activateListeners($form){$form.find("button.update-identification").on("click",event=>{const $button=$(event.delegateTarget);this.submit({updateData:{status:$button.val()}})}),$form.find("button.post-skill-checks").on("click",async()=>{const item=this.item,itemImg=item.system.identification.unidentified.img,itemName=item.system.identification.unidentified.name,identifiedName=item.system.identification.identified.name,skills=$("div#identify-item").find("tr").toArray().flatMap(row=>{const slug=row.dataset.skill,dc=Number(row.dataset.dc);if(!(Number.isInteger(dc)&&objectHasKey(CONFIG.PF2E.skillList,slug)))return[];const name2=game.i18n.localize(CONFIG.PF2E.skillList[slug]);return{slug,name:name2,dc}}),actionOption=item.isMagical?"action:identify-magic":item.isAlchemical?"action:identify-alchemy":null,content=await renderTemplate("systems/pf2e/templates/actors/identify-item-chat-skill-checks.hbs",{itemImg,itemName,identifiedName,rollOptions:compact(["concentrate","exploration","secret",actionOption]),skills});await ChatMessagePF2e.create({user:game.user.id,content})})}async _updateObject(_event,formData){const status=formData.status;status==="identified"&&await this.item.setIdentificationStatus(status)}};__name2(_IdentifyItemPopup,"IdentifyItemPopup");let IdentifyItemPopup=_IdentifyItemPopup;const _IWREditor=class extends DocumentSheet{static{__name(this,"_IWREditor")}constructor(actor,options){if(super(actor,options),__privateAdd(this,_updateIWR),__publicField(this,"category"),__publicField(this,"types"),this.actor.isOfType("familiar","loot"))throw ErrorPF2e(`Actor ${this.actor.name} (${this.actor.uuid}) may not have stored IWR data`);this.category=options.category,this.types={immunities:omit(CONFIG.PF2E.immunityTypes,["custom"]),weaknesses:omit(CONFIG.PF2E.weaknessTypes,["custom"]),resistances:omit(CONFIG.PF2E.resistanceTypes,["custom"])}[this.category]}static get defaultOptions(){return{...super.defaultOptions,closeOnSubmit:!1,classes:["iwr-editor"],template:"systems/pf2e/templates/actors/iwr-editor.hbs",sheetConfig:!1,width:500,height:"auto"}}get id(){return`${this.category}-editor-${this.actor.uuid}`}get title(){return game.i18n.format("PF2E.Actor.IWREditor.Title",{actor:this.actor.name,category:game.i18n.localize(this.categoryLabel)})}get actor(){return this.document}get categoryLabel(){return{immunities:"PF2E.ImmunitiesLabel",weaknesses:"PF2E.WeaknessesLabel",resistances:"PF2E.ResistancesLabel"}[this.category]}async getData(options={}){return this.options.id=this.id,{...await super.getData(options),category:this.category,header:this.categoryLabel,list:this.actor.attributes[this.category],sourceData:this.actor._source.system.attributes?.[this.category]??[],types:this.types}}getUpdatedData({includeNew=!1}={}){const entryElems=htmlQueryAll(this.element[0],".entry:not(.new,[data-synthetic])");return includeNew&&entryElems.push(...htmlQueryAll(this.element[0],".entry.new")),entryElems.flatMap(entryElem=>{const iwrType=htmlQuery(entryElem,"select")?.value;if(!iwrType)return[];const value=Math.trunc(Math.abs(Number(htmlQuery(entryElem,"input[data-property=value]")?.value??"NaN")))||5,exceptionsData=JSON.parse(htmlQuery(entryElem,"input[data-property=exceptions]")?.value||"[]");if(!(Array.isArray(exceptionsData)&&exceptionsData.every(o=>isObject(o))))throw ErrorPF2e("Unexpected data encountered while submitting form");const exceptions=exceptionsData.map(e=>e.id),doubleVsData=JSON.parse(htmlQuery(entryElem,"input[data-property=doubleVs]")?.value||"[]"),doubleVs=Array.isArray(doubleVsData)&&doubleVsData.every(o=>isObject(o)&&typeof o.id=="string"&&o.id in this.types)&&this.category==="resistances"?doubleVsData.map(d=>d.id):void 0;return exceptions.every(e=>typeof e=="string")?{type:iwrType,value:this.category==="immunities"?void 0:value||1,exceptions,doubleVs}:[]})}_getHeaderButtons(){return super._getHeaderButtons().filter(b=>b.class==="close")}activateListeners($html){const html=$html[0];for(const input of htmlQueryAll(html,"input[type=text]"))tagify$1(input,{whitelist:this.types,maxTags:4});htmlQuery(html,"a[data-action=add]")?.addEventListener("click",event=>{const entryElem=htmlClosest(event.target,".entry.new");htmlQuery(entryElem,"select[data-property=type]")?.value&&__privateMethod(this,_updateIWR,updateIWR_fn).call(this,{includeNew:!0})});for(const inputOrSelect of htmlQueryAll(html,"select, input")){const entryElem=htmlClosest(inputOrSelect,".entry");entryElem&&!entryElem.classList.contains("new")&&inputOrSelect.addEventListener("change",()=>{__privateMethod(this,_updateIWR,updateIWR_fn).call(this)})}for(const removeButton of htmlQueryAll(html,"a[data-action=remove]"))removeButton.addEventListener("click",async event=>{htmlClosest(event.target,".entry")?.remove(),__privateMethod(this,_updateIWR,updateIWR_fn).call(this)})}};_updateIWR=new WeakSet,updateIWR_fn=__name2(async function({includeNew=!1}={}){const data=this.getUpdatedData({includeNew}),formInput=htmlQuery(this.element[0],"input[name]");if(!formInput)throw ErrorPF2e("Unexpected error getting for input element");formInput.value=JSON.stringify(data),await this.submit({preventRender:!1})},"#updateIWR"),__name2(_IWREditor,"IWREditor");let IWREditor=_IWREditor;const _RemoveCoinsPopup=class extends FormApplication{static{__name(this,"_RemoveCoinsPopup")}static get defaultOptions(){return{...super.defaultOptions,id:"remove-coins",title:"PF2E.RemoveCoinsTitle",template:"systems/pf2e/templates/actors/remove-coins.hbs"}}async _updateObject(_event,formData){const actor=this.object,coinsToRemove={pp:Number(formData.pp)||0,gp:Number(formData.gp)||0,sp:Number(formData.sp)||0,cp:Number(formData.cp)||0};await actor.inventory.removeCoins(coinsToRemove,{byValue:!!formData.removeByValue})||ui.notifications.warn("PF2E.ErrorMessage.NotEnoughCoins",{localize:!0})}};__name2(_RemoveCoinsPopup,"RemoveCoinsPopup");let RemoveCoinsPopup=_RemoveCoinsPopup;const _ActorSheetPF2e=class _ActorSheetPF2e2 extends ActorSheet{static{__name(this,"_ActorSheetPF2e")}constructor(){super(...arguments),__privateAdd(this,_activateInventoryDragDrop),__privateAdd(this,_sortableOnMove),__privateAdd(this,_sortableOnEnd),__privateAdd(this,_onClickDeleteItem),__privateAdd(this,_onClickBrowseEquipment),__privateAdd(this,_onClickCreateItem),__privateAdd(this,_onClickSellAllTreasure),__publicField(this,"itemRenderer",new ItemSummaryRenderer(this)),__privateAdd(this,_sortableOnMoveData,{})}static get defaultOptions(){const options=super.defaultOptions;return options.dragDrop=[{dragSelector:"[data-foundry-list] .drag-handle"},{dragSelector:".item[draggable=true]"},{dragSelector:".item-list .item:not(.inventory-list *)"}],mergeObject(options,{classes:["default","sheet","actor"],scrollY:[".sheet-sidebar",".tab.active",".inventory-list"]})}get isLootSheet(){return!1}async getData(options=this.options){options.id||=this.id,options.editable=this.isEditable,options.sheetConfig&&=Object.values(CONFIG.Actor.sheetClasses[this.actor.type]).filter(c=>c.canConfigure).length>1;for(const item of[...this.actor.itemTypes.action,...this.actor.itemTypes.feat])item.system.selfEffect&&(item.system.selfEffect.img??=fromUuidSync(item.system.selfEffect.uuid)?.img??null);const actorData=this.actor.toObject(!1),iwrKeys=["immunities","weaknesses","resistances"],attributes=actorData.system.attributes;for(const key of iwrKeys)attributes[key]=[...attributes[key]].sort((a,b)=>a.label.localeCompare(b.label));const coins=this.actor.inventory.coins,totalCoinage=_ActorSheetPF2e2.coinsToSheetData(coins),totalCoinageGold=(coins.copperValue/100).toFixed(2),totalWealth=this.actor.inventory.totalWealth,totalWealthGold=(totalWealth.copperValue/100).toFixed(2),traitsMap=(()=>{switch(this.actor.type){case"hazard":return CONFIG.PF2E.hazardTraits;case"vehicle":return CONFIG.PF2E.vehicleTraits;default:return CONFIG.PF2E.creatureTraits}})(),sheetData={cssClass:this.actor.isOwner?"editable":"locked",editable:this.isEditable,document:this.actor,limited:this.actor.limited,options,owner:this.actor.isOwner,title:this.title,actor:actorData,data:actorData.system,effects:[],items:actorData.items,user:{isGM:game.user.isGM},traits:createSheetTags(traitsMap,{value:Array.from(this.actor.traits)}),toggles:this.actor.synthetics.toggles,isTargetFlatFooted:!!this.actor.rollOptions.all["target:condition:off-guard"],totalCoinage,totalCoinageGold,totalWealth,totalWealthGold,inventory:this.prepareInventory(),enrichedContent:{}};return await this.prepareItems?.(sheetData),sheetData}prepareInventory(){const sections={weapon:{label:game.i18n.localize("PF2E.InventoryWeaponsHeader"),type:"weapon",items:[]},armor:{label:game.i18n.localize("PF2E.InventoryArmorHeader"),type:"armor",items:[]},equipment:{label:game.i18n.localize("PF2E.InventoryEquipmentHeader"),type:"equipment",items:[]},consumable:{label:game.i18n.localize("PF2E.InventoryConsumablesHeader"),type:"consumable",items:[]},treasure:{label:game.i18n.localize("PF2E.InventoryTreasureHeader"),type:"treasure",items:[]},backpack:{label:game.i18n.localize("PF2E.InventoryBackpackHeader"),type:"backpack",items:[]}};for(const item of this.actor.inventory.contents.sort((a,b)=>(a.sort||0)-(b.sort||0))){if(!objectHasKey(sections,item.type)||item.isInContainer)continue;(item.isOfType("book")?sections.equipment:sections[item.type]).items.push(this.prepareInventoryItem(item))}return{sections,bulk:this.actor.inventory.bulk,showValueAlways:this.actor.isOfType("npc","loot","party"),showIndividualPricing:this.actor.isOfType("loot"),hasStowingContainers:this.actor.itemTypes.backpack.some(c=>c.system.stowing&&!c.isInContainer),invested:this.actor.inventory.invested}}prepareInventoryItem(item){const editable=game.user.isGM||item.isIdentified,heldItems=item.isOfType("backpack")?item.contents.map(i=>this.prepareInventoryItem(i)):void 0;heldItems?.sort((a,b)=>(a.item.sort||0)-(b.item.sort||0));const actorSize=new ActorSizePF2e({value:this.actor.size}),itemSize=new ActorSizePF2e({value:item.size}),sizeDifference=itemSize.difference(actorSize,{smallIsMedium:!0}),canBeEquipped=!item.isInContainer;return{item,itemSize:sizeDifference!==0?itemSize:null,editable,isContainer:item.isOfType("backpack"),canBeEquipped,isInvestable:!1,isSellable:editable&&item.isOfType("treasure")&&!item.isCoinage,hasCharges:item.isOfType("consumable")&&item.uses.max>0,heldItems}}static coinsToSheetData(coins){return DENOMINATIONS.reduce((accumulated,d)=>({...accumulated,[d]:{value:coins[d],label:CONFIG.PF2E.currencies[d]}}),{})}getStrikeFromDOM(button){const actionIndex=Number(htmlClosest(button,"[data-action-index]")?.dataset.actionIndex??"NaN"),rootAction=this.actor.system.actions?.at(actionIndex)??null,altUsage=tupleHasValue(["thrown","melee"],button?.dataset.altUsage)?button?.dataset.altUsage:null;return altUsage?rootAction?.altUsages?.find(s=>altUsage==="thrown"?s.item.isThrown:s.item.isMelee)??null:rootAction}activateListeners($html){super.activateListeners($html);const html=$html[0];this.itemRenderer.activateListeners(html),htmlQuery(html,"a[data-action=show-image]")?.addEventListener("click",()=>{const actor=this.actor,title=actor.token?.name??actor.prototypeToken?.name??actor.name;new ImagePopout(actor.img,{title,uuid:actor.uuid}).render(!0)});const inventoryPanel=(()=>{const selector=this.actor.isOfType("loot")?".sheet-body":".tab[data-tab=inventory]";return htmlQuery(html,selector)})();this.activateInventoryListeners(inventoryPanel);for(const element of htmlQueryAll(html,".item[data-item-id] .item-image, .item[data-item-id] .item-chat"))element.addEventListener("click",async event=>{const itemId=htmlClosest(element,"[data-item-id]")?.dataset.itemId??"",[item,fromFormula]=(()=>{if(UUIDUtils.isItemUUID(itemId)){if("knownFormulas"in this&&isObject(this.knownFormulas)){const formula=this.knownFormulas[itemId];if(formula)return[new ItemProxyPF2e(formula.item.toObject(),{parent:this.actor}),!0]}throw ErrorPF2e(`Invalid UUID [${itemId}]!`)}return[this.actor.items.get(itemId,{strict:!0}),!1]})();(!item.isOfType("physical")||item.isIdentified)&&await item.toMessage(event,{create:!0,data:{fromFormula}})});if(!this.options.editable)return;const manualPropertyInputs=htmlQueryAll(html,"select[data-property],input[data-property]");for(const input of manualPropertyInputs)input.addEventListener("focus",()=>{const propertyPath=input.dataset.property??"";if(input.name=propertyPath,input instanceof HTMLInputElement){const baseValue=Math.trunc(Number(getProperty(this.actor._source,propertyPath))||0);input.value=baseValue.toString(),input.type==="text"&&input.dataset.dtype==="Number"&&(input.type="number")}}),input.addEventListener("blur",()=>{input.removeAttribute("name");const propertyPath=input.dataset.property??"",preparedValue=Number(getProperty(this.actor,propertyPath))||0,baseValue=Math.trunc(Number(getProperty(this.actor._source,propertyPath))||0),newValue=Math.trunc(Number(input.value));input instanceof HTMLInputElement&&(input.type==="number"&&input.dataset.dtype==="Number"&&(input.type="text"),baseValue===newValue&&(input.value=input.classList.contains("modifier")?signedInteger(preparedValue):String(preparedValue)))});for(const link of htmlQueryAll(html,".item-delete"))link.addEventListener("click",event=>__privateMethod(this,_onClickDeleteItem,onClickDeleteItem_fn).call(this,event));for(const link of htmlQueryAll(html,".inventory-browse"))link.addEventListener("click",()=>__privateMethod(this,_onClickBrowseEquipment,onClickBrowseEquipment_fn).call(this,link));for(const link of htmlQueryAll(html,".save-name"))link.addEventListener("click",event=>{const saveType=htmlClosest(link,"[data-save]")?.dataset.save;if(!tupleHasValue(SAVE_TYPES,saveType))throw ErrorPF2e(`"${saveType}" is not a recognized save type`);this.actor.saves?.[saveType]?.check.roll(eventToRollParams(event))});const rollInitElem=htmlQuery(html,".roll-init");rollInitElem?.addEventListener("click",event=>{!rollInitElem.classList.contains("disabled")&&this.actor.initiative&&this.actor.initiative.roll(eventToRollParams(event))}),htmlQuery(html,".actions-options")?.addEventListener("change",event=>{const toggleRow=htmlClosest(event.target,"[data-item-id][data-domain][data-option]"),checkbox=htmlQuery(toggleRow,"input[data-action=toggle-roll-option]"),suboptionsSelect=htmlQuery(toggleRow,"select[data-action=set-suboption"),{domain,option,itemId}=toggleRow?.dataset??{},suboption=suboptionsSelect?.value??null;checkbox&&domain&&option&&this.actor.toggleRollOption(domain,option,itemId??null,checkbox.checked,suboption)});for(const listName of["immunities","weaknesses","resistances"])htmlQuery(html,`a[data-action=edit-${listName}]`)?.addEventListener("click",()=>{new IWREditor(this.actor,{category:listName}).render(!0)});for(const strikeElem of htmlQueryAll(html,"ol.strikes-list > li[data-strike]")){const attackSelectors=".item-image[data-action=strike-attack], button[data-action=strike-attack]";for(const button of htmlQueryAll(strikeElem,attackSelectors))button.addEventListener("click",async event=>{if(!Array.isArray(this.actor.system.actions))throw ErrorPF2e("Strikes are not supported on this actor");const altUsage=tupleHasValue(["thrown","melee"],button.dataset.altUsage)?button.dataset.altUsage:null,strike=this.getStrikeFromDOM(button),variantIndex=Number(button.dataset.variantIndex);await strike?.variants[variantIndex]?.roll({event,altUsage})});const damageSelectors="button[data-action=strike-damage], button[data-action=strike-critical]";for(const button of htmlQueryAll(strikeElem,damageSelectors)){const strike=this.getStrikeFromDOM(button),method=button.dataset.action==="strike-damage"?"damage":"critical";button.addEventListener("click",async event=>{await strike?.[method]?.({event})});const altUsage=tupleHasValue(["thrown","melee"],button.dataset.altUsage)?button.dataset.altUsage:null;strike?.[method]?.({getFormula:!0,altUsage}).then(formula=>{formula&&(button.title=formula.toString(),$(button).tooltipster({position:"top",theme:"crb-hover"}))})}}for(const button of htmlQueryAll(html,"button[data-action=use-action]"))button.addEventListener("click",()=>{const itemId=htmlClosest(button,"[data-item-id]")?.dataset.itemId,item=this.actor.items.get(itemId,{strict:!0});item.isOfType("action","feat")&&createSelfEffectMessage(item)});for(const anchor of htmlQueryAll(html,".item-unprepare"))anchor.addEventListener("click",()=>{const row=htmlClosest(anchor,".item"),slotLevel=Number(row?.dataset.slotLevel)||0,slotId=Number(row?.dataset.slotId)||0,entryId=row?.dataset.entryId??"";this.actor.spellcasting.collections.get(entryId)?.unprepareSpell(slotLevel,slotId)});for(const anchor of htmlQueryAll(html,".item-toggle-prepare"))anchor.addEventListener("click",()=>{const row=htmlClosest(anchor,".item"),slotLevel=Number(row?.dataset.slotLevel)||0,slotId=Number(row?.dataset.slotId)||0,entryId=row?.dataset.entryId??"",expendedState=row?.dataset.expendedState!=="true";this.actor.spellcasting.collections.get(entryId)?.setSlotExpendedState(slotLevel,slotId,expendedState)});for(const link of htmlQueryAll(html,".tag-selector"))link.addEventListener("click",()=>this.openTagSelector(link));for(const link of htmlQueryAll(html,".item-create, .item-control.spell-create"))link.addEventListener("click",()=>__privateMethod(this,_onClickCreateItem,onClickCreateItem_fn).call(this,link));for(const anchor of htmlQueryAll(html,".item-edit"))anchor.addEventListener("click",()=>{const itemId=htmlClosest(anchor,"[data-item-id]")?.dataset.itemId;this.actor.items.get(itemId??"")?.sheet.render(!0,{focus:!0})});for(const effectDecrement of htmlQueryAll(html,".effects-list .decrement"))effectDecrement.addEventListener("click",event=>{const parent=htmlClosest(event.currentTarget,".item"),effect=this.actor.items.get(parent?.dataset.itemId??"");effect instanceof AbstractEffectPF2e&&effect.decrease()});for(const effectIncrement of htmlQueryAll(html,".effects-list .increment"))effectIncrement.addEventListener("click",event=>{const parent=htmlClosest(event.currentTarget,".item"),effect=this.actor?.items.get(parent?.dataset.itemId??"");effect instanceof AbstractEffectPF2e&&effect.increase()});for(const element of htmlQueryAll(html,".effects-list [data-action=effect-toggle-unidentified]")??[])element.addEventListener("click",async event=>{const effectId=htmlClosest(event.currentTarget,"[data-item-id]")?.dataset.itemId,effect=this.actor.items.get(effectId,{strict:!0});if(effect.isOfType("effect")){const isUnidentified=effect.system.unidentified;await effect.update({"system.unidentified":!isUnidentified})}});for(const inputElem of htmlQueryAll(html,"input[type=text], input[type=number]"))inputElem.addEventListener("focus",()=>{inputElem.select()});for(const deltaInput of htmlQueryAll(html,"input[data-allow-delta]"))deltaInput.addEventListener("input",()=>{const match=/[+-]?\d*/.exec(deltaInput.value)?.at(0);deltaInput.value=match??deltaInput.value})}activateInventoryListeners(panel){if(this._canDragDrop(".item-list")&&__privateMethod(this,_activateInventoryDragDrop,activateInventoryDragDrop_fn).call(this,panel),!!this.isEditable){panel?.addEventListener("click",event=>{const link=htmlClosest(event.target,"a[data-action], button[data-action]");if(!link)return;const getItem=__name2(()=>{const itemId=htmlClosest(link,".item")?.dataset.itemId??"",item=this.actor.items.get(itemId);if(!item?.isOfType("physical"))throw ErrorPF2e("Item not found or isn't physical");return item},"getItem");switch(link.dataset.action){case"add-coins":{new AddCoinsPopup(this.actor).render(!0);return}case"remove-coins":{new RemoveCoinsPopup(this.actor).render(!0);return}case"increase-quantity":{const item=getItem(),addend=event.ctrlKey?10:event.shiftKey?5:1;item.update({"system.quantity":item.quantity+addend});return}case"decrease-quantity":{const item=getItem();if(item.quantity>0){const subtrahend=Math.min(item.quantity,event.ctrlKey?10:event.shiftKey?5:1);item.update({"system.quantity":item.quantity-subtrahend})}return}case"repair":{const item=getItem();game.pf2e.actions.repair({event,item});return}case"toggle-identified":{const item=getItem();item.isIdentified?item.setIdentificationStatus("unidentified"):new IdentifyItemPopup(item).render(!0);return}case"toggle-container":{const item=getItem();if(!item.isOfType("backpack"))return;const isCollapsed=item.system.collapsed??!1;item.update({"system.collapsed":!isCollapsed});return}case"sell-treasure":{const item=getItem(),sellItem=__name2(async()=>{item?.isOfType("treasure")&&!item.isCoinage&&(await item.delete(),await this.actor.inventory.addCoins(item.assetValue))},"sellItem");if(event.ctrlKey){sellItem();return}const content=document.createElement("p");content.innerText=game.i18n.format("PF2E.SellItemQuestion",{item:item.name}),new Dialog({title:game.i18n.localize("PF2E.SellItemConfirmHeader"),content:content.outerHTML,buttons:{Yes:{icon:fontAwesomeIcon("check").outerHTML,label:game.i18n.localize("Yes"),callback:sellItem},cancel:{icon:fontAwesomeIcon("times").outerHTML,label:game.i18n.localize("Cancel")}},default:"Yes"}).render(!0);return}case"sell-all-treasure":__privateMethod(this,_onClickSellAllTreasure,onClickSellAllTreasure_fn).call(this)}});for(const anchor of htmlQueryAll(panel,".carry-type-hover"))$(anchor).tooltipster({animation:"fade",delay:200,animationDuration:10,trigger:"click",arrow:!1,contentAsHTML:!0,debug:!1,interactive:!0,side:["bottom"],theme:"crb-hover",minWidth:120})}}async deleteItem(element,item,event){(event?.ctrlKey||await Dialog.confirm({title:game.i18n.localize("PF2E.DeleteItemTitle"),content:`

${game.i18n.format("PF2E.DeleteQuestion",{name:`"${item.name}"`})}

`}))&&(await item.delete(),$(element).slideUp(200,()=>this.render(!1)))}_canDragStart(selector){return this.isLootSheet?!0:super._canDragStart(selector)}_canDragDrop(selector){return this.isLootSheet?!0:super._canDragDrop(selector)}_onDragStart(event){if(!(event.target instanceof HTMLElement)||!event.dataTransfer)return;const isContentLink=event.target.classList.contains("content-link"),isPersistent="persistent"in event.target.dataset;if(event.target!==event.currentTarget&&(isContentLink||isPersistent))return;const targetElement=event.currentTarget,previewElement=htmlClosest(targetElement,".item");if(previewElement&&targetElement&&targetElement!==previewElement){const{x,y}=previewElement.getBoundingClientRect();event.dataTransfer.setDragImage(previewElement,event.pageX-x,event.pageY-y)}const itemId=previewElement?.dataset.itemId,item=this.actor.items.get(itemId??""),baseDragData={actorId:this.actor.id,actorUUID:this.actor.uuid,sceneId:canvas.scene?.id??null,tokenId:this.actor.token?.id??null,...item?.toDragData()};previewElement?.dataset.isFormula&&(baseDragData.isFormula=!0,baseDragData.entrySelector=previewElement.dataset.entrySelector);const supplementalData=(()=>{const actionIndex=previewElement?.dataset.actionIndex;if(actionIndex)return"itemType"in baseDragData&&baseDragData.itemType==="melee"?{index:Number(actionIndex)}:{type:"Action",index:Number(actionIndex)};const elementTrait=previewElement?.dataset.element;if(elementTrait)return{type:"Action",elementTrait};const label=previewElement?.innerText.trim(),rollOptionData=previewElement?.dataset??{};return item&&label&&rollOptionData.domain&&rollOptionData.option?{type:"RollOption",label,...rollOptionData}:baseDragData.isFormula?{pf2e:{type:"CraftingFormula",itemUuid:itemId}}:null})();event.dataTransfer.setData("text/plain",JSON.stringify({...baseDragData,...supplementalData}))}async emulateItemDrop(data){const event=new DragEvent("drop",{altKey:game.keyboard.isModifierActive("Alt")});return this._onDropItem(event,data)}async _onDropItem(event,data){event.preventDefault();const item=await ItemPF2e.fromDropData(data);return item?item.actor?.uuid===this.actor.uuid?data.fromInventory?[]:this._onSortItem(event,item.toObject()):item.actor&&item.isOfType("physical")?(await this.moveItemBetweenActors(event,item.actor.id,item.actor?.token?.id??null,this.actor.id,this.actor.token?.id??null,item.id),[item]):this._handleDroppedItem(event,item,data):[]}async _handleDroppedItem(event,item,data){const{actor}=this,itemSource=item.toObject(),mystified=game.user.isGM&&event.altKey;mystified&&itemSource.type==="effect"&&(itemSource.system.unidentified=!0),mystified&&item.isOfType("physical")&&isPhysicalData(itemSource)&&(itemSource.system.identification.unidentified=item.getMystifiedData("unidentified"),itemSource.system.identification.status="unidentified");const containerAttribute=htmlClosest(event.target,".item-container")?.dataset.containerType,dropContainerType=this._tabs[0]?.active==="inventory"&&!containerAttribute?"actorInventory":containerAttribute,craftingTab=this._tabs[0]?.active==="crafting";if(item.isOfType("spell")&&itemSource.type==="spell")return item.isRitual?this._onDropItemCreate(item.clone().toObject()):dropContainerType==="actorInventory"&&itemSource.system.level.value>0?(new CastingItemCreateDialog(actor,{},async(heightenedLevel,itemType,spell)=>{const createdItem=await createConsumableFromSpell(spell,{type:itemType,heightenedLevel,mystified});await this._onDropItemCreate(createdItem)},item).render(!0),[item]):[];if(itemSource.type==="spellcastingEntry")return[];if(itemSource.type==="condition"){const value=data.value;return typeof value=="number"&&itemSource.system.value.isValued&&(itemSource.system.value.value=value),actor.canUserModify(game.user,"update")?[await actor.increaseCondition(itemSource.system.slug,{value})??[]].flat():(ui.notifications.error("PF2E.ErrorMessage.NoUpdatePermission",{localize:!0}),[])}else if(itemIsOfType(itemSource,"affliction","effect")){const{level,value,context}=data;typeof level=="number"&&level>=0&&(itemSource.system.level.value=Math.floor(level)),itemSource.type==="effect"&&itemSource.system.badge?.type==="counter"&&typeof value=="number"&&(itemSource.system.badge.value=value),itemSource.system.context=context??null;const originItem=fromUuidSync(context?.origin.item??"");itemSource.system.traits?.value.length===0&&originItem instanceof SpellPF2e&&itemSource.system.traits.value.push(...originItem.traits)}else if(item.isOfType("physical")&&actor.isOfType("character")&&craftingTab){const actorFormulas=deepClone(actor.system.crafting.formulas);return actorFormulas.some(f=>f.uuid===item.uuid)||(actorFormulas.push({uuid:item.uuid}),await actor.update({"system.crafting.formulas":actorFormulas})),[item]}if(isPhysicalData(itemSource)){const containerId=htmlClosest(event.target,"[data-item-is-container=true]")?.dataset.itemId?.trim()||null;this.actor.itemTypes.backpack.find(container2=>container2.id===containerId)?(itemSource.system.containerId=containerId,itemSource.system.equipped.carryType="stowed"):itemSource.system.equipped.carryType="worn",data?.uuid?.startsWith("Compendium")&&itemSource.type!=="treasure"&&!["med","sm"].includes(actor.size)&&actor.isOfType("creature")&&(itemSource.system.size=actor.size)}return this._onDropItemCreate(new ItemProxyPF2e(itemSource).clone().toObject())}async _onDropFolder(_event,data){if(!(this.actor.isOwner&&data.documentName==="Item"))return[];const folder=await Folder.fromDropData(data);if(!folder)return[];const itemSources=[folder,...folder.getSubfolders()].flatMap(f=>f.contents).map(i=>i.toObject());return this._onDropItemCreate(itemSources)}async moveItemBetweenActors(event,sourceActorId,sourceTokenId,targetActorId,targetTokenId,itemId){const sourceActor=canvas.scene?.tokens.get(sourceTokenId??"")?.actor??game.actors.get(sourceActorId),targetActor=canvas.scene?.tokens.get(targetTokenId??"")?.actor??game.actors.get(targetActorId),item=sourceActor?.items.get(itemId);if(!sourceActor||!targetActor)throw ErrorPF2e("Unexpected missing actor(s)");if(!item?.isOfType("physical"))throw ErrorPF2e("Missing or invalid item");const containerId=htmlClosest(event.target,"[data-item-is-container=true]")?.dataset.containerId?.trim(),sourceItemQuantity=item.quantity,stackable=!!targetActor.inventory.findStackableItem(item._source),isPurchase=sourceActor.isOfType("loot")&&sourceActor.isMerchant&&!sourceActor.isOwner,isAmmunition=item.isOfType("consumable")&&item.isAmmunition;if(sourceItemQuantity>1){const defaultQuantity=isPurchase?isAmmunition?Math.min(10,sourceItemQuantity):1:sourceItemQuantity;new MoveLootPopup(sourceActor,{quantity:{max:sourceItemQuantity,default:defaultQuantity},lockStack:!stackable,isPurchase},(quantity,newStack)=>{sourceActor.transferItemToActor(targetActor,item,quantity,containerId,newStack)}).render(!0)}else sourceActor.transferItemToActor(targetActor,item,1,containerId)}openTagSelector(anchor,options={}){const selectorType=anchor.dataset.tagSelector;if(!tupleHasValue(TAG_SELECTOR_TYPES,selectorType))throw ErrorPF2e(`Unrecognized tag selector type "${selectorType}"`);if(selectorType==="basic"){const objectProperty=anchor.dataset.property??"",title=anchor.dataset.title??"",configTypes=(anchor.dataset.configTypes??"").split(",").map(type=>type.trim()).filter(tag=>tupleHasValue(SELECTABLE_TAG_FIELDS,tag));this.tagSelector("basic",{...options,objectProperty,configTypes,title})}else this.tagSelector(selectorType,options)}tagSelector(selectorType,options){if(selectorType==="basic"&&options&&"objectProperty"in options)new TagSelectorBasic(this.object,options).render(!0);else{if(selectorType==="basic")throw ErrorPF2e("Insufficient options provided to render basic tag selector");{const TagSelector={senses:SenseSelector,"speed-types":SpeedSelector}[selectorType];new TagSelector(this.object,options).render(!0)}}}openTab(name2){this._tabs[0].activate(name2)}async _renderInner(data,options){return this.itemRenderer.saveAndRestoreState(()=>super._renderInner(data,options))}async _render(force,options){await maintainFocusInRender(this,()=>super._render(force,options)),options?.tab&&this.openTab(options.tab)}async _onSubmit(event,{updateData=null,preventClose=!1,preventRender=!1}={}){for(const input of htmlQueryAll(this.form,"tags ~ input"))input.value===""&&(input.value="[]");return super._onSubmit(event,{updateData,preventClose,preventRender})}_getSubmitData(updateData){const data=super._getSubmitData(updateData);processTagifyInSubmitData(this.form,data);for(const el of this.form.elements)if(el instanceof HTMLInputElement&&el.dataset.allowDelta!==void 0){const strValue=el.value.trim(),value=Number(strValue);(strValue.startsWith("+")||strValue.startsWith("-"))&&!Number.isNaN(value)&&(data[el.name]=Number(getProperty(this.actor,el.name))+value)}return data}};_sortableOnMoveData=new WeakMap,_activateInventoryDragDrop=new WeakSet,activateInventoryDragDrop_fn=__name2(function(panel){const inventoryList=htmlQuery(panel,"section.inventory-list, ol[data-container-type=actorInventory]");if(!inventoryList)return;const sortableOptions={...SORTABLE_DEFAULTS,filter:"div.item-summary",preventOnFilter:!1,scroll:inventoryList,setData:(dataTransfer,dragEl)=>{const item=this.actor.inventory.get(htmlQuery(dragEl,"div[data-item-id]")?.dataset.itemId,{strict:!0});dataTransfer.setData("text/plain",JSON.stringify({...item.toDragData(),fromInventory:!0}))},onStart:()=>{__privateSet(this,_sortableOnMoveData,{})},onClone:event=>{for(const link of htmlQueryAll(htmlQuery(event.item,"div.item-summary"),"a.content-link"))link.draggable=!0},onMove:(event,originalEvent)=>__privateMethod(this,_sortableOnMove,sortableOnMove_fn).call(this,event,originalEvent),onEnd:event=>__privateMethod(this,_sortableOnEnd,sortableOnEnd_fn).call(this,event)};for(const list of htmlQueryAll(inventoryList,"ol.inventory-items, ol.item-list")){const itemType=list.dataset.itemType;if(!(list.dataset.containerId||!itemType)){if(itemType==="backpack"){Sortable.create(list,{...sortableOptions,group:{name:"container",put:(_to,_from,dragEl)=>dragEl.dataset.itemType==="backpack"},swapThreshold:.2});for(const subList of htmlQueryAll(list,"ol.container-held-items"))Sortable.create(subList,{...sortableOptions,group:{name:"nested-item",put:!0},swapThreshold:.2});continue}Sortable.create(list,{...sortableOptions,group:{name:itemType,put:(to,from,dragEl)=>from===to?!0:dragEl.dataset.itemType===to.el.dataset.itemType}})}}},"#activateInventoryDragDrop"),_sortableOnMove=new WeakSet,sortableOnMove_fn=__name2(function(event,originalEvent){if(!this.isEditable)return!1;__privateSet(this,_sortableOnMoveData,{related:event.related,willInsertAfter:event.willInsertAfter});const sourceItem=this.actor.inventory.get(htmlQuery(event.dragged,"div[data-item-id]")?.dataset.itemId??""),targetItem=this.actor.inventory.get(htmlClosest(originalEvent.target,"div[data-item-id]")?.dataset.itemId??"");if(sourceItem&&targetItem)return sourceItem.isOfType("backpack")&&targetItem.isOfType("backpack")&&targetItem.isCollapsed?!1:!sourceItem.isStackableWith(targetItem)},"#sortableOnMove"),_sortableOnEnd=new WeakSet,sortableOnEnd_fn=__name2(async function(event){const itemId=htmlQuery(event.item,"div[data-item-id]")?.dataset.itemId,sourceItem=this.actor.inventory.get(itemId,{strict:!0}),targetElement=event.originalEvent?.target instanceof HTMLElement?event.originalEvent.target:null,targetItemId=htmlClosest(targetElement,"div[data-item-id]")?.dataset.itemId??"",targetItem=this.actor.inventory.get(targetItemId);if(!targetItem&&!event.from.contains(targetElement)&&!event.to.contains(targetElement)){if(this.isEditable&&sourceItem.isInContainer&&htmlClosest(targetElement,".inventory-header"))return sourceItem.move({toContainer:null});const itemIsOnlyOneOfType=this.actor.itemTypes[sourceItem.type].length===1;(event.newIndex!==event.oldIndex||itemIsOnlyOneOfType)&&this.render();return}if(!this.isEditable)return;if(targetItem?.isOfType("backpack")&&(!!!htmlClosest(targetElement,"ol[data-container-id]")||targetItem.contents.size===0))return sourceItem.move({toContainer:targetItem});const{related,willInsertAfter}=__privateGet(this,_sortableOnMoveData),relativeItemId=htmlQuery(related,"div[data-item-id]")?.dataset.itemId??"",relativeItem=this.actor.inventory.get(relativeItemId);if(relativeItem||targetItem)return targetItem&&!targetItem.isOfType("backpack")?sourceItem.move({toStack:targetItem}):sourceItem.move({relativeTo:relativeItem,sortBefore:!willInsertAfter})},"#sortableOnEnd"),_onClickDeleteItem=new WeakSet,onClickDeleteItem_fn=__name2(async function(event){const row=htmlClosest(event.currentTarget,"[data-item-id]"),itemId=row?.dataset.itemId,item=this.actor.items.get(itemId??"");if(item?.isOfType("condition")){const references=htmlQuery(row,".condition-references"),deleteCondition=__name2(async()=>{this.actor.decreaseCondition(item,{forceRemove:!0})},"deleteCondition");if(event.ctrlKey){deleteCondition();return}const content=await renderTemplate("systems/pf2e/templates/actors/delete-condition-dialog.hbs",{question:game.i18n.format("PF2E.DeleteQuestion",{name:item.name}),ref:references?.innerHTML});new Dialog({title:game.i18n.localize("PF2E.DeleteConditionTitle"),content,buttons:{Yes:{icon:'',label:"Yes",callback:deleteCondition},cancel:{icon:'',label:"Cancel"}},default:"Yes"}).render(!0)}else if(row&&item)this.deleteItem(row,item,event);else throw ErrorPF2e("Item not found")},"#onClickDeleteItem"),_onClickBrowseEquipment=new WeakSet,onClickBrowseEquipment_fn=__name2(async function(element){const checkboxesFilterCodes=(element.dataset.filter??"").split(",").filter(s=>!!s).map(s=>s.trim()),tab=game.pf2e.compendiumBrowser.tabs.equipment,filter2=await tab.getFilterData(),{checkboxes}=filter2;for(const filterCode of checkboxesFilterCodes){const splitValues=filterCode.split("-");if(splitValues.length!==2)throw ErrorPF2e(`Invalid filter value for opening the compendium browser: "${filterCode}"`);const[filterType,value]=splitValues;if(objectHasKey(checkboxes,filterType)){const checkbox=checkboxes[filterType];objectHasKey(checkbox.options,value)&&(checkbox.options[value].selected=!0,checkbox.selected.push(value),checkbox.isExpanded=!0)}}tab.open(filter2)},"#onClickBrowseEquipment"),_onClickCreateItem=new WeakSet,onClickCreateItem_fn=__name2(function(link){const data=link.dataset;if(!objectHasKey(CONFIG.PF2E.Item.documentClasses,data.type))throw ErrorPF2e(`Unrecognized item type: "${data.type}"`);if(data.type==="spell")return onClickCreateSpell(this.actor,data);const img=`systems/pf2e/icons/default-icons/${data.type}.svg`,type=data.type,itemSource=(()=>{switch(type){case"action":{const name2=game.i18n.localize(`PF2E.ActionType${String(data.actionType).capitalize()}`),actionType=data.actionType;return{type,img,name:name2,system:{actionType:{value:actionType}}}}case"melee":{const name2=game.i18n.localize(`PF2E.NewPlaceholders.${type.capitalize()}`),weaponType=data.actionType;return{type,img,name:name2,system:{weaponType:{value:weaponType}}}}case"lore":{const name2=this.actor.type==="npc"?game.i18n.localize("PF2E.SkillLabel"):game.i18n.localize("PF2E.NewPlaceholders.Lore");return{type,img,name:name2}}default:{if(!setHasElement(PHYSICAL_ITEM_TYPES,type))throw ErrorPF2e(`Unsupported item type: ${type}`);return{name:game.i18n.localize(`PF2E.NewPlaceholders.${data.type.capitalize()}`),type}}}})();if(itemSource){if(data.traits){const traits=String(data.traits).split(",");itemSource.system=mergeObject(itemSource.system??{},{traits:{value:traits}})}this.actor.createEmbeddedDocuments("Item",[itemSource])}},"#onClickCreateItem"),_onClickSellAllTreasure=new WeakSet,onClickSellAllTreasure_fn=__name2(async function(){const content=await renderTemplate("systems/pf2e/templates/actors/sell-all-treasure-dialog.hbs");new Dialog({title:game.i18n.localize("PF2E.SellAllTreasureTitle"),content,buttons:{yes:{icon:fontAwesomeIcon("check").outerHTML,label:"Yes",callback:async()=>this.actor.inventory.sellAllTreasure()},cancel:{icon:fontAwesomeIcon("times").outerHTML,label:"Cancel"}},default:"cancel"}).render(!0)},"#onClickSellAllTreasure"),__name2(_ActorSheetPF2e,"ActorSheetPF2e");let ActorSheetPF2e=_ActorSheetPF2e;const _DamagePF2e=class{static{__name(this,"_DamagePF2e")}static async roll(data,context,callback){const outcome=context.outcome??null;context.rollMode??=(context.secret?"blindroll":void 0)??game.settings.get("core","rollMode"),context.createMessage??=!0,context.options.has("secret")&&(context.secret=!0);const subtitle=outcome?context.sourceType==="attack"?game.i18n.localize(`PF2E.Check.Result.Degree.Attack.${outcome}`):game.i18n.localize(`PF2E.Check.Result.Degree.Check.${outcome}`):null;let flavor=await renderTemplate("systems/pf2e/templates/chat/action/header.hbs",{title:data.name,subtitle});if(data.traits){const toTags=__name2((slugs,{labels={},descriptions={},cssClass,dataAttr})=>slugs.map(s=>({value:s,label:game.i18n.localize(labels[s]??"")})).sort((a,b)=>a.label.localeCompare(b.label)).map(tag=>{const description=descriptions[tag.value]??"",span=document.createElement("span");return span.className="tag",cssClass&&span.classList.add(cssClass),span.dataset[dataAttr]=tag.value,span.dataset.description=description,span.innerText=tag.label,span.outerHTML}).join(""),"toTags"),traits=toTags(data.traits,{labels:CONFIG.PF2E.actionTraits,descriptions:CONFIG.PF2E.traitsDescriptions,cssClass:null,dataAttr:"trait"}),item2=context.self?.item,itemTraits=item2?.isOfType("weapon","melee","spell")?toTags(Array.from(item2.traits).filter(t=>!(t in CONFIG.PF2E.materialDamageEffects)),{labels:item2.isOfType("spell")?CONFIG.PF2E.spellTraits:CONFIG.PF2E.npcAttackTraits,descriptions:CONFIG.PF2E.traitsDescriptions,cssClass:"tag_alt",dataAttr:"trait"}):"",properties=(()=>{const range=item2?.isOfType("action","melee","weapon")?item2.range:null,label=createActionRangeLabel(range);if(label&&(range?.increment||range?.max)){const slug=range.increment?`range-increment-${range.increment}`:`range-${range.max}`;return toTags([slug],{labels:{[slug]:label},descriptions:{[slug]:"PF2E.Item.Weapon.RangeIncrementN.Hint"},cssClass:"tag_secondary",dataAttr:"slug"})}else return""})(),materialEffects=toTags(data.materials,{labels:CONFIG.PF2E.preciousMaterials,descriptions:CONFIG.PF2E.traitsDescriptions,cssClass:"tag_material",dataAttr:"material"}),otherTags=[itemTraits,properties,materialEffects].join("");flavor+=otherTags.length>0?`
${traits}
${otherTags}

`:`
${traits}

`}const breakdownTags=(Array.isArray(data.damage.breakdown)?data.damage.breakdown:data.damage.breakdown[outcome??"success"]).map(b=>`${b}`);flavor+=`
${breakdownTags.join("")}
`;const roll=await(()=>{const damage=data.damage;if("roll"in damage)return damage.roll.evaluate({async:!0});const formula=deepClone(damage.formula[outcome??"success"]);if(!formula)return ui.notifications.error(game.i18n.format("PF2E.UI.noDamageInfoForOutcome",{outcome})),null;const rollerId=game.userId,degreeOfSuccess=outcome?DEGREE_OF_SUCCESS_STRINGS.indexOf(outcome):null,critRule=game.settings.get("pf2e","critRule")==="doubledamage"?"double-damage":"double-dice",options={rollerId,damage:data,degreeOfSuccess,ignoredResistances:damage.ignoredResistances,critRule};return new DamageRoll(formula,{},options).evaluate({async:!0})})();if(roll===null)return null;const syntheticNotes=context.self?.actor?extractNotes(context.self?.actor.synthetics.rollNotes,context.domains??[]):[],contextNotes=context.notes?.map(n=>n instanceof RollNotePF2e?n:new RollNotePF2e(n))??[],notes=[...syntheticNotes,...contextNotes].filter(n=>(n.outcome.length===0||outcome&&n.outcome.includes(outcome))&&n.predicate.test(context.options)),notesList=RollNotePF2e.notesToHTML(notes);flavor+=notesList.outerHTML;const{self,target}=context,item=self?.item??null,targetFlag=target?{actor:target.actor.uuid,token:target.token.uuid}:null,strike=(()=>{if(item?.isOfType("melee","weapon")&&item&&self?.actor?.isOfType("character","npc")){const strikes=self.actor.system.actions,strike2=strikes.find(a=>a.item?.id===item.id&&a.item.slug===item.slug);if(strike2)return{actor:self.actor.uuid,index:strikes.indexOf(strike2),damaging:!0,name:strike2.item.name,altUsage:item.isOfType("weapon")?item.altUsageType:null}}return null})(),rollMode=context.rollMode??"roll",contextFlag={type:context.type,sourceType:context.sourceType,actor:context.self?.actor.id??null,token:context.self?.token?.id??null,target:targetFlag,domains:context.domains??[],options:Array.from(context.options).sort(),mapIncreases:context.mapIncreases,notes:notes.map(n=>n.toObject()),secret:context.secret??!1,rollMode,traits:context.traits??[],skipDialog:context.skipDialog??!game.user.settings.showRollDialogs,outcome,unadjustedOutcome:context.unadjustedOutcome??null},messageData=await roll.toMessage({speaker:ChatMessagePF2e.getSpeaker({actor:self?.actor,token:self?.token}),flavor,flags:{pf2e:{context:contextFlag,target:targetFlag,modifiers:data.modifiers?.map(m=>m.toObject())??[],origin:item?.getOriginData(),strike,preformatted:"both"}}},{create:!1}),splashRolls=await(async()=>{const splashInstances=roll.instances.map(i=>({damageType:i.type,total:i.componentTotal("splash")})).filter(s=>s.total>0),rolls=[];for(const splash of splashInstances){const formula=`(${splash.total}[splash])[${splash.damageType}]`,roll2=await new DamageRoll(formula).evaluate({async:!0});roll2.options.splashOnly=!0,rolls.push(roll2.toJSON())}return rolls})();return context.createMessage&&(messageData.rolls.push(...splashRolls),await ChatMessagePF2e.create(messageData,{rollMode})),Hooks.callAll("pf2e.damageRoll",roll),callback&&callback(roll),roll}};__name2(_DamagePF2e,"DamagePF2e");let DamagePF2e=_DamagePF2e;const _DamageModifierDialog=class extends Application{static{__name(this,"_DamageModifierDialog")}constructor(params){super(),__privateAdd(this,_getModifierIcon),__privateAdd(this,_getTypeLabel),__privateAdd(this,_applyStackingRules),__publicField(this,"formulaData"),__publicField(this,"context"),__publicField(this,"baseDamageType"),__publicField(this,"isCritical"),__privateAdd(this,_resolve,void 0),__publicField(this,"isRolled",!1),__privateAdd(this,_originallyEnabled,void 0),this.formulaData=params.formulaData,this.context=params.context,this.baseDamageType=params.formulaData.base.at(0)?.damageType??"untyped",this.isCritical=this.context.outcome==="criticalSuccess",__privateSet(this,_originallyEnabled,new Set(this.formulaData.modifiers.filter(m=>m.enabled)))}static get defaultOptions(){return{...super.defaultOptions,template:"systems/pf2e/templates/chat/damage/damage-modifier-dialog.hbs",classes:["roll-modifiers-dialog","damage-dialog","dialog"],popOut:!0,width:440,height:"auto"}}get title(){return this.isCritical?game.i18n.localize("PF2E.Damage.Dialog.CriticalDamageRoll"):game.i18n.localize("PF2E.Damage.Dialog.DamageRoll")}async getData(){const modifiers=this.formulaData.modifiers.map(m=>({label:m.label,category:m.category,type:m.type,modifier:m.modifier,hideIfDisabled:!__privateGet(this,_originallyEnabled).has(m)&&m.hideIfDisabled,damageType:m.damageType,typeLabel:__privateMethod(this,_getTypeLabel,getTypeLabel_fn).call(this,m.damageType,m.damageCategory),enabled:m.enabled,ignored:m.ignored,critical:m.critical,show:this.isCritical||!m.critical,icon:__privateMethod(this,_getModifierIcon,getModifierIcon_fn).call(this,m)})),dice=this.formulaData.dice.map(d=>({label:d.label,category:d.category,damageType:d.damageType,typeLabel:__privateMethod(this,_getTypeLabel,getTypeLabel_fn).call(this,d.damageType,d.category),diceLabel:d.diceNumber&&d.dieSize?`${d.diceNumber}${d.dieSize}`:d.diceNumber?game.i18n.format("PF2E.Damage.Dialog.BonusDice",{dice:addSign(d.diceNumber)}):"",enabled:d.enabled,ignored:d.ignored,critical:d.critical,show:!d.override&&(this.isCritical||!d.critical),icon:__privateMethod(this,_getModifierIcon,getModifierIcon_fn).call(this,d)})),hasVisibleModifiers=modifiers.filter(m=>m.show).length>0,hasVisibleDice=dice.filter(d=>d.show).length>0,baseResult=createDamageFormula({base:this.formulaData.base,modifiers:[],dice:[],ignoredResistances:[]}),baseRoll=new DamageRoll(baseResult.formula),baseFormulaTemplate=(await Promise.all(baseRoll.instances.map(i=>i.render()))).join(" + "),result=createDamageFormula(this.formulaData),roll=new DamageRoll(result.formula),formulaTemplate=(await Promise.all(roll.instances.map(i=>i.render()))).join(" + ");return{appId:this.id,baseFormula:baseFormulaTemplate,modifiers,dice,isCritical:this.isCritical,hasVisibleDice,hasVisibleModifiers,damageTypes:sortStringRecord(CONFIG.PF2E.damageTypes),damageSubtypes:sortStringRecord(pick(CONFIG.PF2E.damageCategories,DAMAGE_CATEGORIES_UNIQUE)),rollModes:CONFIG.Dice.rollModes,rollMode:this.context?.rollMode,showRollDialogs:game.user.settings.showRollDialogs,formula:formulaTemplate}}activateListeners($html){const html=$html[0];htmlQuery(html,"button.roll")?.addEventListener("click",()=>{this.isRolled=!0,this.close()});for(const checkbox of htmlQueryAll(html,".modifier-container input[type=checkbox]"))checkbox.addEventListener("click",()=>{const{dice,modifiers}=this.formulaData,modIndex=Number(checkbox.dataset.modifierIndex),dieIndex=Number(checkbox.dataset.diceIndex);Number.isNaN(modIndex)?Number.isNaN(dieIndex)||(dice[dieIndex].ignored=!checkbox.checked,dice[dieIndex].enabled=checkbox.checked):(modifiers[modIndex].ignored=!checkbox.checked,__privateMethod(this,_applyStackingRules,applyStackingRules_fn).call(this)),this.render()});const categorySelect=htmlQuery(html,"select.add-dice-category"),damageTypeSelect=htmlQuery(html,"select.add-dice-type");categorySelect?.addEventListener("change",()=>{damageTypeSelect&&(categorySelect.value==="precision"?(damageTypeSelect.value="",damageTypeSelect.disabled=!0):(damageTypeSelect.disabled=!1,damageTypeSelect.value=damageTypeSelect.firstElementChild?.value??"acid"))});const addModifierButton=htmlQuery(html,"button.add-modifier");addModifierButton?.addEventListener("click",()=>{const parent=addModifierButton.parentElement,value=Number(parent.querySelector(".add-modifier-value")?.value||1),type=String(parent.querySelector(".add-modifier-type")?.value),damageType=parent.querySelector(".add-modifier-damage-type")?.value??null,category=parent.querySelector(".add-modifier-category")?.value||null,errors=[];if(Number.isNaN(value)?errors.push("Modifier value must be a number."):value===0&&errors.push("Modifier value must not be zero."),!setHasElement(MODIFIER_TYPES,type))throw ErrorPF2e("Unexpected invalid modifier type");const label=String(parent.querySelector(".add-modifier-name")?.value).trim()||game.i18n.localize(value<0?`PF2E.PenaltyLabel.${type}`:`PF2E.BonusLabel.${type}`);errors.length>0?ui.notifications.error(errors.join(" ")):(this.formulaData.modifiers.push(new ModifierPF2e({label,modifier:value,type,damageType,damageCategory:category})),__privateMethod(this,_applyStackingRules,applyStackingRules_fn).call(this),this.render())});const addDiceButton=htmlQuery(html,"button.add-dice");addDiceButton?.addEventListener("click",()=>{const parent=addDiceButton.parentElement,count=Number(parent.querySelector(".add-dice-count")?.value||1),faces=parent.querySelector(".add-dice-faces")?.value??"d4",category=parent.querySelector(".add-dice-category")?.value||null,type=parent.querySelector(".add-dice-type")?.value||null;if(Number.isNaN(count)){ui.notifications.error("Damage dice count must be a number.");return}else if(count<1){ui.notifications.error("Damage dice count must be greater than zero.");return}if(!tupleHasValue(["persistent","precision","splash",null],category)){ui.notifications.error(`Unkown damage category: ${category}.`);return}const faceLabel=game.i18n.localize(`PF2E.DamageDie${faces.toUpperCase()}`),label=game.i18n.format("PF2E.Damage.Dialog.Bonus",{dice:`+${count}${faceLabel}`}),slug=sluggify(`${label}-${type}`);this.formulaData.dice.push(new DamageDicePF2e({label,category,diceNumber:count,dieSize:faces,damageType:type,slug,selector:"damage"})),this.render()});const rollModeInput=htmlQuery(html,"select[name=rollmode]");rollModeInput?.addEventListener("change",()=>{const rollMode=rollModeInput.value;if(!tupleHasValue(Object.values(CONST.DICE_ROLL_MODES),rollMode))throw ErrorPF2e("Unexpected roll mode");this.context.rollMode=rollMode});const settingsButton=htmlQuery(htmlClosest(html,".app"),"a.header-button.settings");if(settingsButton&&!settingsButton?.dataset.tooltipContent){settingsButton.dataset.tooltipContent=`#${this.id}-settings`;const $tooltip=$(settingsButton).tooltipster({animation:"fade",trigger:"click",arrow:!1,contentAsHTML:!0,debug:!1,interactive:!0,side:["top"],theme:"crb-hover",minWidth:165}),toggle=htmlQuery(html,".settings-list input.quick-rolls-submit");toggle?.addEventListener("click",async()=>{await game.user.setFlag("pf2e","settings.showRollDialogs",toggle.checked),$tooltip.tooltipster("close")})}}async resolve(){return this.render(!0),new Promise(resolve=>{__privateSet(this,_resolve,resolve)})}async close(options){var _a;(_a=__privateGet(this,_resolve))==null||_a.call(this,this.isRolled),super.close(options)}_getHeaderButtons(){const buttons=super._getHeaderButtons();return[{label:game.i18n.localize("PF2E.SETTINGS.Settings"),class:"settings",icon:"fa-solid fa-cog",onclick:()=>null},...buttons]}_injectHTML($html){super._injectHTML($html),$html[0]?.querySelector("button.roll")?.focus()}};_resolve=new WeakMap,_originallyEnabled=new WeakMap,_getModifierIcon=new WeakSet,getModifierIcon_fn=__name2(function(object){const damageTypeIconClass=object.damageType?DAMAGE_TYPE_ICONS[object.damageType]:null,damageTypeIcon=damageTypeIconClass?fontAwesomeIcon(damageTypeIconClass):null;return(()=>{switch(object.category){case"splash":return compact([fontAwesomeIcon("fa-burst"),damageTypeIcon]);case"persistent":return object.damageType!=="bleed"?[damageTypeIcon,fontAwesomeIcon("fa-hourglass",{style:"duotone"})]:[damageTypeIcon];case"precision":return[damageTypeIcon,fontAwesomeIcon("fa-crosshairs")];default:return[damageTypeIcon]}})().map(i=>i?.outerHTML??"").join("")},"#getModifierIcon"),_getTypeLabel=new WeakSet,getTypeLabel_fn=__name2(function(damageType,category){if(category==="precision")return game.i18n.localize("PF2E.Damage.Precision");if(!damageType)return null;const typeLabel=game.i18n.localize(CONFIG.PF2E.damageTypes[damageType]);switch(category){case"persistent":return game.i18n.format("PF2E.Damage.PersistentTooltip",{damageType:typeLabel});case"splash":return game.i18n.format("PF2E.Damage.Dialog.Splash",{damageType:typeLabel});default:return typeLabel}},"#getTypeLabel"),_applyStackingRules=new WeakSet,applyStackingRules_fn=__name2(function(){applyStackingRules(this.formulaData.modifiers.filter(m=>m.category!=="persistent")),applyStackingRules(this.formulaData.modifiers.filter(m=>m.category==="persistent"))},"#applyStackingRules"),__name2(_DamageModifierDialog,"DamageModifierDialog");let DamageModifierDialog=_DamageModifierDialog;const superEnrichHTML=TextEditor.enrichHTML,superEnrichContentLinks=TextEditor._enrichContentLinks,superCreateInlineRoll=TextEditor._createInlineRoll,superOnClickInlineRoll=TextEditor._onClickInlineRoll,_TextEditorPF2e=class _TextEditorPF2e2 extends TextEditor{static{__name(this,"_TextEditorPF2e")}static enrichHTML(content,options={}){content?.startsWith("

@Localize")&&(content=content.substring(3,content.length-4));const enriched=superEnrichHTML.apply(this,[content,options]);return typeof enriched=="string"&&(options.processVisibility??!0)?_TextEditorPF2e2.processUserVisibility(enriched,options):Promise.resolve().then(async()=>_TextEditorPF2e2.processUserVisibility(await enriched,options))}static _enrichContentLinks(text,options){if(options?.async){const documentTypes=[...CONST.DOCUMENT_LINK_TYPES,"Compendium","UUID"],pattern=new RegExp(`@(${documentTypes.join("|")})\\[([^#\\]]+)(?:#([^\\]]+))?](?:{([^}]+)})?`,"g"),uuids=text.map(t=>Array.from((t.textContent??"").matchAll(pattern))).flat(2).filter(m=>UUIDUtils.isCompendiumUUID(m));return UUIDUtils.fromUUIDs(uuids).then(()=>superEnrichContentLinks.apply(this,[text,options]))}return superEnrichContentLinks.apply(this,[text,options])}static async _createInlineRoll(match,rollData,options={}){const anchor=await superCreateInlineRoll.apply(this,[match,rollData,options]),formula=anchor?.dataset.formula;if(formula){const roll=(()=>{try{return new DamageRoll(formula)}catch{return null}})();if(!roll||!looksLikeDamageRoll(roll))return anchor;const icon=damageDiceIcon(roll),label=match[4]&&match[4].length>0?match[4]:roll.formula;anchor.innerHTML=`${icon.outerHTML}${label}`,anchor.dataset.tooltip=roll.formula,anchor.dataset.damageRoll="",roll.instances.length>0&&roll.instances.every(i=>i.persistent)&&(anchor.draggable=!0,anchor.dataset.persistent="")}return anchor}static async _onClickInlineRoll(event){const anchor=event.currentTarget??null;if(!(anchor instanceof HTMLAnchorElement&&anchor.dataset.formula&&"damageRoll"in anchor.dataset))return superOnClickInlineRoll.apply(this,[event]);const sheetElem=htmlClosest(anchor,".sheet"),messageElem=htmlClosest(anchor,"li.chat-message"),app=ui.windows[Number(sheetElem?.dataset.appid)],message=game.messages.get(messageElem?.dataset.messageId??""),[actor,rollData]=(()=>{if(message?.actor)return[message.actor,message.getRollData()];if(app instanceof ActorSheetPF2e){const itemId=anchor.dataset.pf2ItemId;return[app.actor,app.actor.items.get(itemId)?.getRollData()??app.actor.getRollData()]}if(app instanceof ItemSheetPF2e)return[app.actor,app.item.getRollData()];const itemUuid=anchor.dataset.itemUuid,itemByUUID=itemUuid&&!itemUuid.startsWith("Compendium.")?fromUuidSync(itemUuid):null;return itemByUUID instanceof ItemPF2e?[itemByUUID.actor,itemByUUID.getRollData()]:[null,{}]})(),options=anchor.dataset.flavor?{flavor:anchor.dataset.flavor}:{},speaker=ChatMessagePF2e.getSpeaker({actor}),rollMode=objectHasKey(CONFIG.Dice.rollModes,anchor.dataset.mode)?anchor.dataset.mode:"roll",baseFormula=anchor.dataset.pf2BaseFormula;if(baseFormula){const item=rollData.item instanceof ItemPF2e?rollData.item:null,traits=anchor.dataset.pf2Traits?.split(",")??[],domains=anchor.dataset.pf2Domains?.split(","),extraRollOptions=anchor.dataset.pf2RollOptions?.split(",")??[],result=await augmentInlineDamageRoll(baseFormula,{...eventToRollParams(event),actor,item,domains,traits,extraRollOptions});result&&await DamagePF2e.roll(result.template,result.context);return}const roll=new DamageRoll(anchor.dataset.formula,rollData,options);return roll.toMessage({speaker,flavor:roll.options.flavor},{rollMode})}static processUserVisibility(content,options){const html=createHTMLElement("div",{innerHTML:content}),document2=options.rollData?.actor??null;return UserVisibilityPF2e.process(html,{document:document2}),html.innerHTML}static async enrichString(data,options={}){if(data.length<4)return null;const item=options.rollData?.item??null,[_match,inlineType,paramString,inlineLabel]=data;switch(inlineType){case"Check":{const actor=options.rollData?.actor??item?.actor??null;return __privateMethod(this,_createCheck,createCheck_fn).call(this,{paramString,inlineLabel,item,actor})}case"Damage":return __privateMethod(this,_createDamageRoll,createDamageRoll_fn).call(this,{paramString,rollData:options.rollData,inlineLabel});case"Localize":return __privateMethod(this,_localize,localize_fn).call(this,paramString,options);case"Template":return __privateMethod(this,_createTemplate,createTemplate_fn).call(this,paramString,inlineLabel,item?.system);default:return null}}static convertXMLNode(html,name2,{visible,visibility,whose,tooltip,classes}){const node=html.querySelector(name2);if(!node)return null;const span=document.createElement("span"),{dataset,classList}=span;if(typeof visible=="boolean"&&(visibility=visible?"all":"gm"),visibility&&(dataset.visibility=visibility),whose&&(dataset.whose=whose),tooltip&&(dataset.tooltip=tooltip.trim()),classes)for(const cssClass of classes)classList.add(cssClass);return span.append(...Array.from(node.childNodes)),node.replaceWith(span),span}};_localize=new WeakSet,localize_fn=__name2(async function(paramString,options){const content=game.i18n.localize(paramString);if(content===paramString)return ui.notifications.error(`Failed to localize ${paramString}!`),null;const result=document.createElement("span");return result.innerHTML=await TextEditor.enrichHTML(content,{...options,async:!0}),result},"#localize"),_createTemplate=new WeakSet,createTemplate_fn=__name2(function(paramString,label,itemData){const params=__privateMethod(this,_parseInlineParams,parseInlineParams_fn).call(this,paramString,{first:"type"});if(!params)return null;if(!params.type)ui.notifications.error(game.i18n.localize("PF2E.InlineTemplateErrors.TypeMissing"));else if(params.distance)if(objectHasKey(CONFIG.PF2E.areaTypes,params.type)){if(isNaN(+params.distance))return ui.notifications.error(game.i18n.format("PF2E.InlineTemplateErrors.DistanceNoNumber",{distance:params.distance})),null;if(params.width&&isNaN(+params.width))return ui.notifications.error(game.i18n.format("PF2E.InlineTemplateErrors.WidthNoNumber",{width:params.width})),null;{params.traits||=itemData?.traits?.value?.toString()??"",label||(label=game.i18n.format("PF2E.TemplateLabel",{size:params.distance,unit:game.i18n.localize("PF2E.Foot"),shape:game.i18n.localize(CONFIG.PF2E.areaTypes[params.type])}));const html=document.createElement("span");return html.innerHTML=label,html.setAttribute("data-pf2-effect-area",params.type),html.setAttribute("data-pf2-distance",params.distance),params.traits!==""&&html.setAttribute("data-pf2-traits",params.traits),params.type==="line"&&html.setAttribute("data-pf2-width",params.width??"5"),html}}else return ui.notifications.error(game.i18n.format("PF2E.InlineTemplateErrors.TypeUnsupported",{type:params.type})),null;else return ui.notifications.error(game.i18n.localize("PF2E.InlineTemplateErrors.DistanceMissing")),null;return null},"#createTemplate"),_parseInlineParams=new WeakSet,parseInlineParams_fn=__name2(function(paramString,options={}){return paramString.split("|").reduce((result2,part,idx)=>{if(idx===0&&options.first&&!part.includes(":"))return result2[options.first]=part.trim(),result2;const colonIdx=part.indexOf(":"),portions=colonIdx>=0?[part.slice(0,colonIdx),part.slice(colonIdx+1)]:[part,""];return result2[portions[0]]=portions[1],result2},{})},"#parseInlineParams"),_createCheck=new WeakSet,createCheck_fn=__name2(function({paramString,inlineLabel,item=null,actor=item?.actor??null}){const rawParams=__privateMethod(this,_parseInlineParams,parseInlineParams_fn).call(this,paramString,{first:"type"});if(!rawParams)return null;if(!rawParams.type)return ui.notifications.warn(game.i18n.localize("PF2E.InlineCheck.Errors.TypeMissing")),null;const showDC=setHasElement(USER_VISIBILITIES,rawParams.showDC)?rawParams.showDC:actor?.hasPlayerOwner||actor?.isOfType("party")||game.settings.get("pf2e","metagame_showDC")?"all":"gm",params={...rawParams,type:rawParams.type,basic:rawParams.basic!==void 0&&["true",""].includes(rawParams.basic),showDC,traits:(()=>{const traits=[],itemTraits=item?.system.traits?.value??[];return rawParams.overrideTraits!=="true"&&traits.push(...itemTraits),rawParams.traits&&traits.push(...rawParams.traits.split(",").map(trait=>trait.trim())),Array.from(new Set(traits))})(),extraRollOptions:compact([...__privateMethod(this,_createActionOptions,createActionOptions_fn).call(this,item),...rawParams.basic==="true"?["damaging-effect"]:[],...rawParams.options?.split(",").map(t=>t.trim())??[]]).sort()};rawParams.dc&&(params.dc=rawParams.dc),rawParams.defense&&(params.defense=rawParams.defense);const types=params.type.split(",");let adjustments=params.adjustment?.split(",")??["0"];if(types.length!==adjustments.length&&adjustments.length>1)return ui.notifications.warn(game.i18n.localize("PF2E.InlineCheck.Errors.AdjustmentLengthMismatch")),null;if(types.length>adjustments.length&&(adjustments=new Array(types.length).fill(adjustments[0])),adjustments.some(adj=>adj!==""&&isNaN(parseInt(adj))))return ui.notifications.warn(game.i18n.localize("PF2E.InlineCheck.Errors.NonIntegerAdjustment")),null;const buttons=types.map((type,i)=>__privateMethod(this,_createSingleCheck,createSingleCheck_fn).call(this,{actor,item,inlineLabel,params:{...params,type,adjustment:adjustments[i]}}));if(buttons.length===1)return buttons[0];{const checkGroup=document.createElement("div");checkGroup.setAttribute("data-pf2-checkgroup","");for(const button of buttons){if(button===null)return null;checkGroup.hasChildNodes()&&checkGroup.appendChild(document.createElement("br")),checkGroup.appendChild(button)}return checkGroup}},"#createCheck"),_createSingleCheck=new WeakSet,createSingleCheck_fn=__name2(function({params,item,actor,inlineLabel}){const icon=(()=>{switch(params.type){case"fortitude":return fontAwesomeIcon("heart-pulse");case"reflex":return fontAwesomeIcon("person-running");case"will":return fontAwesomeIcon("brain");case"perception":return fontAwesomeIcon("eye");default:return fontAwesomeIcon("dice-d20")}})();icon.classList.add("icon");const name2=params.name??item?.name??params.type,localize=localizer("PF2E.InlineCheck"),label=(()=>{if(inlineLabel)return inlineLabel;if(tupleHasValue(SAVE_TYPES,params.type)){const saveName=game.i18n.localize(CONFIG.PF2E.saves[params.type]);return params.basic?localize("BasicWithSave",{save:saveName}):saveName}switch(params.type){case"flat":return game.i18n.localize("PF2E.FlatCheck");case"perception":return game.i18n.localize("PF2E.PerceptionLabel");default:{const shortForm=(()=>{if(objectHasKey(SKILL_EXPANDED,params.type))return SKILL_EXPANDED[params.type].shortForm;if(objectHasKey(SKILL_DICTIONARY,params.type))return params.type})();return shortForm?game.i18n.localize(CONFIG.PF2E.skills[shortForm]):params.type.split("-").map(word=>word.slice(0,1).toUpperCase()+word.slice(1)).join(" ")}}})(),createLabel=__name2(content=>createHTMLElement("span",{classes:["label"],innerHTML:content}),"createLabel"),anchor=createHTMLElement("a",{classes:["inline-check"],children:[icon,createLabel(label)],dataset:{pf2Traits:params.traits.toString()||null,pf2RollOptions:params.extraRollOptions.toString()||null,pf2RepostFlavor:name2,pf2ShowDc:params.showDC==="all"?null:params.showDC,pf2Label:localize("DCWithName",{name:name2}),pf2Adjustment:Number(params.adjustment)||null,pf2Roller:params.roller||null,pf2Check:sluggify(params.type)}});if(params.defense&¶ms.dc&&(anchor.dataset.tooltip=localize("Invalid",{message:localize("Errors.DCAndDefense")}),anchor.dataset.invalid="true"),!["flat","fortitude","reflex","will"].includes(params.type)&¶ms.defense&&(anchor.dataset.pf2Defense=params.defense),params.type&¶ms.dc){const checkDC=params.dc==="@self.level"?params.dc:getCheckDC({name:name2,params,item,actor});if(anchor.dataset.pf2Dc=checkDC,checkDC!=="@self.level"){const dc=params.dc===""?NaN:Number(checkDC),displayedDC=isNaN(dc)?checkDC:`${dc+Number(params.adjustment)}`,text=anchor.innerText;anchor.querySelector("span.label")?.replaceWith(createLabel(game.i18n.format("PF2E.DCWithValueAndVisibility",{role:params.showDC,dc:displayedDC,text})))}}return params.roller==="self"&&actor&&!actor.canUserModify(game.user,"update")?createHTMLElement("span",{children:[anchor.innerText]}):anchor},"#createSingleCheck"),_createDamageRoll=new WeakSet,createDamageRoll_fn=__name2(async function(args){const params=__privateMethod(this,_parseInlineParams,parseInlineParams_fn).call(this,args.paramString,{first:"formula"});if(!params||!params.formula)return ui.notifications.warn(game.i18n.localize("PF2E.InlineCheck.Errors.TypeMissing")),null;const item=args.rollData?.item instanceof ItemPF2e?args.rollData?.item:null,actor=(args.rollData?.actor instanceof ActorPF2e?args.rollData?.actor:null)??item?.actor??null,domains=params.domains?.split(",");if(domains?.some(d=>!/^[a-z][-a-z0-9]+-damage$/.test(d)))return ui.notifications.warn(game.i18n.format("PF2E.InlineCheck.Errors.InvalidDomains",{type:"@Damage"})),null;const traits=(()=>{const fromParams=params.traits?.split(",").flatMap(t=>t.trim()||[])??[],fromItem=item?.system.traits?.value??[];return params.overrideTraits==="true"?fromParams:uniq([...fromParams,...fromItem])})().sort(),extraRollOptions=compact([...params.options?.split(",").map(t=>t.trim())??[],...__privateMethod(this,_createActionOptions,createActionOptions_fn).call(this,item)]).sort(),result=await augmentInlineDamageRoll(params.formula,{skipDialog:!0,actor,item,domains,traits,extraRollOptions}),baseFormula=(()=>{const baseRollData={...item?.getRollData()??{},actor:{level:(item&&"level"in item?item.level:null)??1}};return new DamageRoll(params.formula,baseRollData).formula})(),roll=result?.template.damage.roll??new DamageRoll(params.formula,args.rollData),formula=roll.formula;return createHTMLElement("a",{classes:compact(["inline-roll","roll",baseFormula!==formula?"altered":null]),children:[damageDiceIcon(roll),args.inlineLabel??formula],dataset:{formula:roll._formula,tooltip:args.inlineLabel?formula:baseFormula!==formula?game.i18n.format("PF2E.InlineDamage.Base",{formula:baseFormula}):null,damageRoll:params.formula,pf2Domains:domains?.join(",")||null,pf2BaseFormula:result?params.formula:null,pf2Traits:traits.toString()||null,pf2RollOptions:extraRollOptions.toString()||null,pf2ItemId:item?.id}})},"#createDamageRoll"),_createActionOptions=new WeakSet,createActionOptions_fn=__name2(function(item){return!item?.isOfType("action","feat")||!item.actionCost?[]:compact([`action:${item.slug??sluggify(item.name)}`,item.actionCost.value?`action:cost:${item.actionCost.value}`:null])},"#createActionOptions"),__privateAdd(_TextEditorPF2e,_localize),__privateAdd(_TextEditorPF2e,_createTemplate),__privateAdd(_TextEditorPF2e,_parseInlineParams),__privateAdd(_TextEditorPF2e,_createCheck),__privateAdd(_TextEditorPF2e,_createSingleCheck),__privateAdd(_TextEditorPF2e,_createDamageRoll),__privateAdd(_TextEditorPF2e,_createActionOptions),__name2(_TextEditorPF2e,"TextEditorPF2e");let TextEditorPF2e=_TextEditorPF2e;function getCheckDC({name:name2,params,item=null,actor=item?.actor??null}){const{type}=params,dc=params.dc,base=(()=>{if(dc?.startsWith("resolve")&&actor){params.immutable||="true";const resolve=dc.match(/resolve\((.+?)\)$/),value=resolve&&resolve?.length>0?resolve[1]:"";return Number(__name2(resolveString=>{try{const rollData=item?.getRollData()??actor?.getRollData();return Roll.safeEval(Roll.replaceFormulaData(resolveString,rollData))}catch{return 0}},"saferEval")(value))}return Number(dc)||void 0})();if(base){const getStatisticValue=__name2(selectors=>{if(item?.actor&¶ms.immutable!=="true"){const{actor:actor2}=item,{synthetics}=actor2,modifier=new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:base-10,adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,selectors,"base")}),stat=new Statistic(actor2,{slug:type,label:name2,domains:selectors,modifiers:[modifier]});return String(stat.dc.value)}return base.toString()},"getStatisticValue"),slugName=sluggify(name2);if(type==="flat")return params.immutable==="false"?getStatisticValue(["inline-dc",`${slugName}-inline-dc`]):base.toString();{const selectors=["all","inline-dc",`${slugName}-inline-dc`];return getStatisticValue(selectors)}}return"0"}__name(getCheckDC,"getCheckDC"),__name2(getCheckDC,"getCheckDC");async function augmentInlineDamageRoll(baseFormula,args){const{name:name2,actor,item,traits,extraRollOptions}=args;try{const rollData=item?.getRollData()??actor?.getRollData()??{};rollData.actor??={level:(item&&"level"in item?item.level:null)??1};const base=extractBaseDamage(new DamageRoll(baseFormula,rollData)),domains=compact(["damage","inline-damage",item?`${item.id}-inline-damage`:null,item?`${sluggify(item.slug??item.name)}-inline-damage`:null,args.domains]).flat(),options=new Set([...actor?.getRollOptions(domains)??[],...item?.getRollOptions("item")??[],...traits??[],...extraRollOptions??[]]),firstBase=base.at(0);if(firstBase&&actor?.isOfType("npc")&&(actor.isElite||actor.isWeak)){const value=options.has("item:frequency:limited")?4:2;firstBase.terms?.push({dice:null,modifier:actor.isElite?value:-value})}const{modifiers,dice}=(()=>{if(!(actor instanceof ActorPF2e))return{modifiers:[],dice:[]};const extractOptions={resolvables:rollData??{},test:options};return processDamageCategoryStacking(base,{modifiers:extractModifiers(actor.synthetics,domains,extractOptions),dice:extractDamageDice(actor.synthetics.damageDice,domains,extractOptions),test:options})})(),formulaData={base,modifiers,dice,ignoredResistances:[]},isAttack=!!traits?.includes("attack"),context={type:"damage-roll",sourceType:isAttack?"attack":"save",outcome:isAttack?"success":null,domains,options,self:(()=>actor?{actor,token:actor.token,item:item||null,statistic:null,modifiers}:null)()};applyDamageDiceOverrides(base,dice);const{formula,breakdown}=createDamageFormula(formulaData),roll=new DamageRoll(formula);return{template:{name:name2??item?.name??actor?.name??"",damage:{roll,breakdown},modifiers:[...modifiers,...dice],traits:traits?.filter(t=>t in CONFIG.PF2E.actionTraits)??[],materials:[]},context}}catch(ex){return console.error(`Failed to parse inline @Damage ${baseFormula}:`,ex),null}}__name(augmentInlineDamageRoll,"augmentInlineDamageRoll"),__name2(augmentInlineDamageRoll,"augmentInlineDamageRoll");const _CheckModifiersDialog=class extends Application{static{__name(this,"_CheckModifiersDialog")}constructor(check,resolve,context={options:new Set}){const title=(()=>{const maybeWithHTML=context.title?.trim()||check.slug;if(!maybeWithHTML.includes("<"))return maybeWithHTML.trim();const div=document.createElement("div");return div.innerHTML=maybeWithHTML,div.querySelector(".action-glyph, .pf2-icon")?.remove(),div.innerText.trim()})();super({title}),__privateAdd(this,_resolveSubstitutions),__publicField(this,"check"),__publicField(this,"context"),__publicField(this,"resolve"),__publicField(this,"isResolved",!1),__privateAdd(this,_originallyEnabled2,void 0),this.check=check,this.resolve=resolve,this.context=context,__privateSet(this,_originallyEnabled2,new Set(check.modifiers.filter(m=>m.enabled)))}static get defaultOptions(){return{...super.defaultOptions,template:"systems/pf2e/templates/chat/check-modifiers-dialog.hbs",classes:["roll-modifiers-dialog","dice-checks","dialog"],popOut:!0,width:380,height:"auto"}}async getData(){const fortune=this.context.rollTwice==="keep-higher",misfortune=this.context.rollTwice==="keep-lower",none=fortune===misfortune,rollMode=this.context.rollMode==="roll"?game.settings.get("core","rollMode"):this.context.rollMode;return{appId:this.id,modifiers:this.check.modifiers.map(m=>({...m,hideIfDisabled:!__privateGet(this,_originallyEnabled2).has(m)&&m.hideIfDisabled})),totalModifier:this.check.totalModifier,rollModes:CONFIG.Dice.rollModes,rollMode,showRollDialogs:game.user.settings.showRollDialogs,substitutions:__privateMethod(this,_resolveSubstitutions,resolveSubstitutions_fn).call(this),fortune,none,misfortune}}activateListeners($html){const html=$html[0];htmlQuery(html,"button.roll")?.addEventListener("click",()=>{this.resolve(!0),this.isResolved=!0,this.close()});for(const checkbox of htmlQueryAll(html,".substitutions input[type=checkbox]"))checkbox.addEventListener("click",()=>{const substitutions=this.context.substitutions??[],index=Number(checkbox.dataset.subIndex),toggledSub=substitutions.at(index);if(!toggledSub)return;toggledSub.selected=toggledSub.required||checkbox.checked;const options=this.context.options??=new Set;for(const substitution of substitutions){const option=`substitute:${substitution.slug}`;substitution.selected?options.add(option):options.delete(option)}this.context.substitutions=__privateMethod(this,_resolveSubstitutions,resolveSubstitutions_fn).call(this).map(s=>omit(s,["toggleable"])),this.check.calculateTotal(this.context.options),this.render()});for(const checkbox of htmlQueryAll(html,".modifier-container input[type=checkbox]"))checkbox.addEventListener("click",()=>{const index=Number(checkbox.dataset.modifierIndex);this.check.modifiers[index].ignored=!checkbox.checked,this.check.calculateTotal(),this.render()});const addModifierButton=htmlQuery(html,"button.add-modifier");addModifierButton?.addEventListener("click",()=>{const parent=addModifierButton.parentElement,value=Number(parent.querySelector(".add-modifier-value")?.value||1),type=String(parent.querySelector(".add-modifier-type")?.value);let name2=String(parent.querySelector(".add-modifier-name")?.value);const errors=[];if(Number.isNaN(value)?errors.push("Modifier value must be a number."):value===0&&errors.push("Modifier value must not be zero."),!setHasElement(MODIFIER_TYPES,type))throw ErrorPF2e("Unexpected invalid modifier type");(!name2||!name2.trim())&&(name2=game.i18n.localize(value<0?`PF2E.PenaltyLabel.${type}`:`PF2E.BonusLabel.${type}`)),errors.length>0?ui.notifications.error(errors.join(" ")):(this.check.push(new ModifierPF2e(name2,value,type)),this.render())});for(const rollTwice of htmlQueryAll(html,".fate input[type=radio]"))rollTwice.addEventListener("click",()=>{this.context.rollTwice=rollTwice.value||!1});const rollModeInput=htmlQuery(html,"select[name=rollmode]");rollModeInput?.addEventListener("change",()=>{const rollMode=rollModeInput.value;if(!tupleHasValue(Object.values(CONST.DICE_ROLL_MODES),rollMode))throw ErrorPF2e("Unexpected roll mode");this.context.rollMode=rollMode});const settingsButton=htmlQuery(htmlClosest(html,".app"),"a.header-button.settings");if(settingsButton&&!settingsButton?.dataset.tooltipContent){settingsButton.dataset.tooltipContent=`#${this.id}-settings`;const $tooltip=$(settingsButton).tooltipster({animation:"fade",trigger:"click",arrow:!1,contentAsHTML:!0,debug:!1,interactive:!0,side:["top"],theme:"crb-hover",minWidth:165}),toggle=htmlQuery(html,".settings-list input.quick-rolls-submit");toggle?.addEventListener("click",async()=>{await game.user.setFlag("pf2e","settings.showRollDialogs",toggle.checked),$tooltip.tooltipster("close")})}}async close(options){this.isResolved||this.resolve(!1),super.close(options)}_getHeaderButtons(){const buttons=super._getHeaderButtons();return[{label:game.i18n.localize("PF2E.SETTINGS.Settings"),class:"settings",icon:"fa-solid fa-cog",onclick:()=>null},...buttons]}_injectHTML($html){super._injectHTML($html),$html[0]?.querySelector("button.roll")?.focus()}};_originallyEnabled2=new WeakMap,_resolveSubstitutions=new WeakSet,resolveSubstitutions_fn=__name2(function(){this.context.substitutions??=[];const hasRequired={fortune:this.context.substitutions.some(s=>s.required&&s.effectType==="fortune"),misfortune:this.context.substitutions.some(s=>s.required&&s.effectType==="misfortune")};return this.context.substitutions.map(substitution=>{const toggleable=!hasRequired[substitution.effectType],selected=substitution.required?!0:substitution.selected&&toggleable;return{...substitution,selected,toggleable}})},"#resolveSubstitutions"),__name2(_CheckModifiersDialog,"CheckModifiersDialog");let CheckModifiersDialog=_CheckModifiersDialog;const _CheckRoll=class _CheckRoll2 extends Roll{static{__name(this,"_CheckRoll")}get roller(){return game.users.get(this.options.rollerId??"")??null}get type(){return this.options.type??"check"}get degreeOfSuccess(){return this.options.degreeOfSuccess??null}get isReroll(){return this.options.isReroll??!1}get isRerollable(){return!this.isReroll&&!this.dice.some(d=>d.modifiers.includes("kh")||d.modifiers.includes("kl"))}async render(options={}){this._evaluated||await this.evaluate({async:!0});const{isPrivate,flavor,template}=options,{type,identifier,action:action2,damaging}=this.options,canRollDamage=!!(damaging&&identifier&&(this.roller===game.user||game.user.isGM)),limitCueVisibility=!game.settings.get("pf2e","metagame_showResults"),chatData={formula:isPrivate?"???":this._formula,flavor:isPrivate?null:flavor,user:game.user.id,tooltip:isPrivate?"":await this.getTooltip(),total:isPrivate?"?":Math.round(this.total*100)/100,type,identifier,action:action2,degree:this.degreeOfSuccess,canRollDamage,limitCueVisibility};return renderTemplate(template??_CheckRoll2.CHAT_TEMPLATE,chatData)}};__name2(_CheckRoll,"CheckRoll"),__publicField(_CheckRoll,"CHAT_TEMPLATE","systems/pf2e/templates/chat/check/roll.hbs");let CheckRoll=_CheckRoll;const _StrikeAttackRoll=class extends CheckRoll{static{__name(this,"_StrikeAttackRoll")}};__name2(_StrikeAttackRoll,"StrikeAttackRoll");let StrikeAttackRoll=_StrikeAttackRoll;const _CheckPF2e=class _CheckPF2e2{static{__name(this,"_CheckPF2e")}static async roll(check,context={},event=null,callback){event&&mergeObject(context,eventToRollParams(event)),context.skipDialog??=!game.user.settings.showRollDialogs,context.createMessage??=!0,Array.isArray(context.options)&&(context.options=new Set(context.options));const rollOptions=context.options??new Set;typeof context.mapIncreases=="number"&&rollOptions.add(`map:increases:${context.mapIncreases}`),rollOptions.has("secret")&&(context.rollMode??=game.user.isGM?"gmroll":"blindroll"),context.rollMode??="roll",rollOptions.size>0&&!context.isReroll&&check.calculateTotal(rollOptions);const substitutions=context.substitutions??=[],requiredSubstitution=context.substitutions.find(s=>s.required&&s.selected);if(requiredSubstitution)for(const substitution of context.substitutions)substitution.required=substitution===requiredSubstitution,substitution.selected=substitution===requiredSubstitution;if(!context.skipDialog&&context.type!=="flat-check"&&!await new Promise(resolve=>{new CheckModifiersDialog(check,resolve,context).render(!0)}))return null;const extraTags=[],isReroll=context.isReroll??!1;isReroll&&(context.rollTwice=!1);const[dice,tagsFromDice]=(()=>{const substitution=substitutions.find(s=>s.selected),rollTwice=context.rollTwice??!1,fortuneMisfortune=new Set(compact([substitution?.effectType,rollTwice==="keep-higher"?"fortune":rollTwice==="keep-lower"?"misfortune":null]));for(const trait of fortuneMisfortune)rollOptions.add(trait);if(rollOptions.has("fortune")&&rollOptions.has("misfortune")){for(const sub of substitutions)rollOptions.delete(`substitute:${sub.slug}`),check.calculateTotal(rollOptions);return["1d20",["PF2E.TraitFortune","PF2E.TraitMisfortune"]]}else if(substitution){const effectType={fortune:"PF2E.TraitFortune",misfortune:"PF2E.TraitMisfortune"}[substitution.effectType],extraTag=game.i18n.format("PF2E.SpecificRule.SubstituteRoll.EffectType",{type:game.i18n.localize(effectType),substitution:reduceItemName(game.i18n.localize(substitution.label))});return[substitution.value.toString(),[extraTag]]}else return context.rollTwice==="keep-lower"?["2d20kl",["PF2E.TraitMisfortune"]]:context.rollTwice==="keep-higher"?["2d20kh",["PF2E.TraitFortune"]]:["1d20",[]]})();extraTags.push(...tagsFromDice);const options={type:context.type,identifier:context.identifier,action:context.action&&sluggify(context.action)||null,rollerId:game.userId,isReroll,totalModifier:check.totalModifier,damaging:!!context.damaging,domains:context.domains},totalModifierPart=signedInteger(check.totalModifier,{emptyStringZero:!0}),roll=await new CheckRoll(`${dice}${totalModifierPart}`,{},options).evaluate({async:!0}),dosAdjustments=context.dosAdjustments?.filter(a=>a.predicate?.test(rollOptions)??!0).reduce((record,data)=>{for(const outcome of["all",...DEGREE_OF_SUCCESS_STRINGS])data.adjustments[outcome]&&(record[outcome]=deepClone(data.adjustments[outcome]));return record},{})??{},degree=context.dc?new DegreeOfSuccess(roll,context.dc,dosAdjustments):null;degree&&(context.outcome=DEGREE_OF_SUCCESS_STRINGS[degree.value],context.unadjustedOutcome=DEGREE_OF_SUCCESS_STRINGS[degree.unadjusted],roll.options.degreeOfSuccess=degree.value);const notes=context.notes?.map(n=>n instanceof RollNotePF2e?n:new RollNotePF2e(n)).filter(note=>{if(!note.predicate.test([...rollOptions,...note.rule?.item.getRollOptions("parent")??[]]))return!1;if(!context.dc||note.outcome.length===0)return!0;const outcome=context.outcome??context.unadjustedOutcome;return!!(outcome&¬e.outcome.includes(outcome))})??[],notesList=RollNotePF2e.notesToHTML(notes),item=context.item??null,flavor=await(async()=>{const result=await __privateMethod(this,_createResultFlavor,createResultFlavor_fn).call(this,{degree,target:context.target??null}),tags=__privateMethod(this,_createTagFlavor,createTagFlavor_fn).call(this,{check,context,extraTags}),title=(context.title??check.slug).trim();return[title.startsWith("{const strong=document.createElement("strong");return strong.innerHTML=title,createHTMLElement("h4",{classes:["action"],children:[strong]})})(),result??[],tags,notesList].flat().map(e=>typeof e=="string"?e:e.outerHTML).join("")})(),contextFlag={...context,type:context.type??"check",identifier:context.identifier??null,item:void 0,dosAdjustments,actor:context.actor?.id??null,token:context.token?.id??null,domains:context.domains??[],target:context.target?{actor:context.target.actor.uuid,token:context.target.token.uuid}:null,options:Array.from(rollOptions).sort(),notes:notes.map(n=>n.toObject()),rollMode:context.rollMode,rollTwice:context.rollTwice??!1,title:context.title??"PF2E.Check.Label",traits:context.traits??[],substitutions,dc:context.dc?omit(context.dc,["statistic"]):null,skipDialog:context.skipDialog,isReroll:context.isReroll??!1,outcome:context.outcome??null,unadjustedOutcome:context.unadjustedOutcome??null};delete contextFlag.item;const message=await(()=>{const flags={core:context.type==="initiative"?{initiativeRoll:!0}:{},pf2e:{context:contextFlag,modifierName:check.slug,modifiers:check.modifiers.map(m=>m.toObject()),origin:item?.getOriginData()}},speaker=ChatMessagePF2e.getSpeaker({actor:context.actor,token:context.token}),{rollMode}=contextFlag,create=context.createMessage;return roll.toMessage({speaker,flavor,flags},{rollMode,create})})();if(callback){const msg=message instanceof ChatMessagePF2e?message:new ChatMessagePF2e(message),evt=event&&event instanceof Event?event:event?.originalEvent??null;await callback(roll,context.outcome,msg,evt)}return item?.isOfType("weapon")&&item.traits.has("consumable")&&item.actor.items.has(item.id)&&item.quantity>0&&await item.update({system:{quantity:item.quantity-1}}),roll}static async rerollFromMessage(message,{heroPoint=!1,keep="new"}={}){if(!(message.isAuthor||game.user.isGM)){ui.notifications.error(game.i18n.localize("PF2E.RerollMenu.ErrorCantDelete"));return}const actor=game.actors.get(message.speaker.actor??"");let rerollFlavor=game.i18n.localize(`PF2E.RerollMenu.MessageKeep.${keep}`);if(heroPoint)if(actor?.isOfType("character")){const heroPointCount=actor.heroPoints.value;if(heroPointCount)await actor.update({"system.resources.heroPoints.value":Math.clamped(heroPointCount-1,0,actor.heroPoints.max)}),rerollFlavor=game.i18n.format("PF2E.RerollMenu.MessageHeroPoint",{name:actor.name});else{ui.notifications.warn(game.i18n.format("PF2E.RerollMenu.WarnNoHeroPoint",{name:actor.name}));return}}else{ui.notifications.error("PF2E.RerollMenu.ErrorNoActor",{localize:!0});return}const systemFlags=deepClone(message.flags.pf2e),context=systemFlags.context;if(!isCheckContextFlag(context))return;context.skipDialog=!0,context.isReroll=!0;const oldRoll=message.rolls.at(0);if(!(oldRoll instanceof CheckRoll))throw ErrorPF2e("Unexpected error retrieving prior roll");const unevaluatedNewRoll=oldRoll.clone();unevaluatedNewRoll.options.isReroll=!0,Hooks.callAll("pf2e.preReroll",Roll.fromJSON(JSON.stringify(oldRoll.toJSON())),unevaluatedNewRoll,heroPoint,keep);const newRoll=await unevaluatedNewRoll.evaluate({async:!0});Hooks.callAll("pf2e.reroll",Roll.fromJSON(JSON.stringify(oldRoll.toJSON())),newRoll,heroPoint,keep);let keptRoll=newRoll,[oldRollClass,newRollClass]=["pf2e-reroll-discard",""];(keep==="higher"&&oldRoll.total>newRoll.total||keep==="lower"&&oldRoll.total{const{dc}=context;if(!dc)return null;if(dc.slug==="armor"){const targetActor=(()=>{const{target}=context;if(!target?.actor)return null;const maybeActor=fromUuidSync(target.actor);return maybeActor instanceof ActorPF2e?maybeActor:maybeActor instanceof TokenDocumentPF2e?maybeActor.actor:null})();dc.statistic=targetActor?.armorClass}return new DegreeOfSuccess(newRoll,dc,context.dosAdjustments)})(),useNewRoll=keptRoll===newRoll&&!!degree;useNewRoll&°ree&&(newRoll.options.degreeOfSuccess=degree.value);const renders={old:await _CheckPF2e2.renderReroll(oldRoll,{isOld:!0}),new:await _CheckPF2e2.renderReroll(newRoll,{isOld:!1})},rerollIcon=fontAwesomeIcon(heroPoint?"hospital-symbol":"dice");rerollIcon.classList.add("pf2e-reroll-indicator"),rerollIcon.setAttribute("title",rerollFlavor);const oldFlavor=message.flavor??"";context.outcome=useNewRoll?DEGREE_OF_SUCCESS_STRINGS[degree.value]:context.outcome;const newFlavor=useNewRoll?await(async()=>{const parsedFlavor=document.createElement("div");parsedFlavor.innerHTML=oldFlavor;const target=context.target??null,targetFlavor=await __privateMethod(this,_createResultFlavor,createResultFlavor_fn).call(this,{degree,target});targetFlavor&&htmlQuery(parsedFlavor,".target-dc-result")?.replaceWith(targetFlavor);for(const element of htmlQueryAll(parsedFlavor,".roll-note"))element.remove();const notesText=(context.notes?.map(n=>new RollNotePF2e(n))??[]).filter(note=>{if(!context.dc||note.outcome.length===0)return!0;const outcome=context.outcome??context.unadjustedOutcome;return!!(outcome&¬e.outcome.includes(outcome))}).map(n=>n.text).join(` -`)??"";return parsedFlavor.innerHTML+notesText})():oldFlavor,{initiativeRoll}=message.flags.core;if(initiativeRoll){const combatant=message.token?.combatant;await combatant?.parent.setInitiative(combatant.id,newRoll.total)}await message.delete({render:!1}),await keptRoll.toMessage({content:`

${renders.old}
${renders.new}
`,flavor:`${rerollIcon.outerHTML}${newFlavor}`,speaker:message.speaker,flags:{core:{initiativeRoll},pf2e:systemFlags}},{rollMode:context.rollMode})}static async renderReroll(roll,{isOld}){const die=roll.dice.find(d=>d instanceof Die&&d.faces===20);if(typeof die?.total!="number")throw ErrorPF2e("Unexpected error inspecting d20 term");const html=await roll.render(),element=parseHTML(`
${html}
`);return isOld&&element.querySelector(".message-buttons")?.remove(),[1,20].includes(die.total)&&element.querySelector(".dice-total")?.classList.add(die.total===20?"success":"failure"),element.innerHTML}};_createTagFlavor=new WeakSet,createTagFlavor_fn=__name2(function({check,context,extraTags}){const toTagElement=__name2((tag,cssClass=null)=>{const span=document.createElement("span");return span.classList.add("tag"),cssClass&&span.classList.add(`tag_${cssClass}`),span.innerText=tag.label,tag.name&&(span.dataset.slug=tag.name),tag.description&&(span.dataset.description=tag.description),span},"toTagElement"),traits=uniqBy(context.traits?.map(trait=>(trait.label=game.i18n.localize(trait.label),trait))??[],t=>t.name).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang)).map(t=>toTagElement(t))??[],{item}=context,itemTraits=item?.isOfType("weapon","melee")&&context.type!=="saving-throw"?Array.from(item.traits).map(t=>{const obj=traitSlugToObject(t,CONFIG.PF2E.npcAttackTraits);return obj.label=game.i18n.localize(obj.label),obj}).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang)).map(t=>toTagElement(t,"alt")):[],properties=(()=>{const range=item?.isOfType("action","weapon")?item.range:null,label=createActionRangeLabel(range);if(label&&(range?.increment||range?.max)){const slug=range.increment?`range-increment-${range.increment}`:`range-${range.max}`;return[toTagElement({name:slug,label,description:"PF2E.Item.Weapon.RangeIncrementN.Hint"},"secondary")]}else return[]})(),traitsAndProperties=createHTMLElement("div",{classes:["tags","traits"]});if(itemTraits.length===0&&properties.length===0)traitsAndProperties.append(...traits);else{const verticalBar=document.createElement("hr");verticalBar.className="vr",traitsAndProperties.append(...[traits,verticalBar,itemTraits,properties].flat())}const modifiers=check.modifiers.filter(m=>m.enabled).map(modifier=>{const sign=modifier.modifier<0?"":"+",label=`${modifier.label} ${sign}${modifier.modifier}`;return toTagElement({name:modifier.slug,label},"transparent")}),tagsFromOptions=extraTags.map(t=>toTagElement({label:game.i18n.localize(t)},"transparent")),modifiersAndExtras=createHTMLElement("div",{classes:["tags","modifiers"],children:[...modifiers,...tagsFromOptions]});return compact([traitsAndProperties.childElementCount>0?traitsAndProperties:null,document.createElement("hr"),modifiersAndExtras])},"#createTagFlavor"),_createResultFlavor=new WeakSet,createResultFlavor_fn=__name2(async function({degree,target}){if(!degree)return null;const{dc}=degree,customLabel=!!dc.label&&Number.isInteger(dc.value)&&!dc.label.includes("{dc}")&&dc.label?`${game.i18n.localize(dc.label)}: {dc}`:dc.label??null,targetActor=await(async()=>{if(!target?.actor)return null;if(target.actor instanceof ActorPF2e)return target.actor;const maybeActor=await fromUuid(target.actor);return maybeActor instanceof ActorPF2e?maybeActor:maybeActor instanceof TokenDocumentPF2e?maybeActor.actor:null})(),targetData=await(async()=>{if(!target)return null;const token=await(async()=>target.token?target.token instanceof TokenDocumentPF2e?target.token:targetActor?.token?targetActor.token:fromUuid(target.token):null)(),canSeeName=(token??new TokenDocumentPF2e(targetActor?.prototypeToken.toObject()??{})).playersCanSeeName||!game.settings.get("pf2e","metagame_tokenSetsNameVisibility");return{name:token?.name??targetActor?.name??"",visible:!!canSeeName}})(),{checkDCs}=CONFIG.PF2E,dcData=(()=>{const dcSlug=dc.slug??(dc.statistic instanceof StatisticDifficultyClass?dc.statistic.parent.slug:null),dcType=game.i18n.localize(dc.label?.trim()||game.i18n.localize(objectHasKey(checkDCs.Specific,dcSlug)?checkDCs.Specific[dcSlug]:checkDCs.Unspecific)),circumstances=dc.statistic instanceof StatisticDifficultyClass?dc.statistic.modifiers.filter(m=>m.enabled&&m.type==="circumstance"):[],preadjustedDC=circumstances.length>0&&dc.statistic?dc.value-circumstances.reduce((total,c)=>total+c.modifier,0):dc.value??null,visible=targetActor?.hasPlayerOwner||dc.visible||game.settings.get("pf2e","metagame_showDC");if(typeof preadjustedDC!="number"||circumstances.length===0){const labelKey=game.i18n.localize(targetData?checkDCs.Label.WithTarget:customLabel??checkDCs.Label.NoTarget);return{markup:game.i18n.format(labelKey,{dcType,dc:dc.value,target:targetData?.name??null}),visible}}const adjustment={preadjusted:preadjustedDC,direction:preadjustedDCdc.value?"decreased":"no-change",circumstances:circumstances.map(c=>({label:c.label,value:c.modifier}))},translation=adjustment.direction==="no-change"?checkDCs.Label.NoChangeTarget:checkDCs.Label.AdjustedTarget;return{markup:game.i18n.format(translation,{target:targetData?.name??game.user.name,dcType,preadjusted:preadjustedDC,adjusted:dc.value}),visible,adjustment}})(),resultData=(()=>{const offset={value:new Intl.NumberFormat(game.i18n.lang,{maximumFractionDigits:0,signDisplay:"always",useGrouping:!1}).format(degree.rollTotal-dc.value),visible:dc.visible},checkOrAttack=sluggify(dc.scope??"Check",{camel:"bactrian"}),locPath=__name2((checkOrAttack2,dosKey)=>`PF2E.Check.Result.Degree.${checkOrAttack2}.${dosKey}`,"locPath"),unadjusted=game.i18n.localize(locPath(checkOrAttack,DEGREE_OF_SUCCESS_STRINGS[degree.unadjusted])),[adjusted,locKey]=degree.adjustment?[game.i18n.localize(locPath(checkOrAttack,DEGREE_OF_SUCCESS_STRINGS[degree.value])),"AdjustedLabel"]:[unadjusted,"Label"],markup=game.i18n.format(`PF2E.Check.Result.${locKey}`,{adjusted,unadjusted,offset:offset.value}),visible=game.settings.get("pf2e","metagame_showResults");return{markup,visible}})(),rendered=await renderTemplate("systems/pf2e/templates/chat/check/target-dc-result.hbs",{target:targetData,dc:dcData,result:resultData}),html=parseHTML(rendered),{convertXMLNode}=TextEditorPF2e;if(targetData&&convertXMLNode(html,"target",{visible:targetData.visible,whose:"target"}),convertXMLNode(html,"dc",{visible:dcData.visible,whose:"target"}),dcData.adjustment){const{adjustment}=dcData;convertXMLNode(html,"preadjusted",{classes:["unadjusted"]});const adjustedNode=convertXMLNode(html,"adjusted",{classes:["adjusted",adjustment.direction]});if(!adjustedNode)throw ErrorPF2e("Unexpected error processing roll template");adjustedNode.dataset.circumstances=JSON.stringify(adjustment.circumstances)}if(convertXMLNode(html,"unadjusted",{visible:resultData.visible,classes:degree.adjustment?["unadjusted"]:[DEGREE_OF_SUCCESS_STRINGS[degree.value]]}),degree.adjustment){const adjustedNode=convertXMLNode(html,"adjusted",{visible:resultData.visible,classes:[DEGREE_OF_SUCCESS_STRINGS[degree.value],"adjusted"]});if(!adjustedNode)throw ErrorPF2e("Unexpected error processing roll template");adjustedNode.dataset.adjustment=game.i18n.localize(degree.adjustment.label)}if(convertXMLNode(html,"offset",{visible:dcData.visible,whose:"target"}),!targetData?.visible&&!dcData.visible){const targetDC=html.querySelector(".target-dc");targetDC&&(targetDC.dataset.visibility="gm"),resultData.visible||(html.dataset.visibility="gm")}return html},"#createResultFlavor"),__privateAdd(_CheckPF2e,_createTagFlavor),__privateAdd(_CheckPF2e,_createResultFlavor),__name2(_CheckPF2e,"CheckPF2e");let CheckPF2e=_CheckPF2e;const _CheckContextError=class extends Error{static{__name(this,"_CheckContextError")}constructor(message,actor,slug){super(message),this.actor=actor,this.slug=slug}};__name2(_CheckContextError,"CheckContextError");let CheckContextError=_CheckContextError;const _ActionMacroHelpers=class{static{__name(this,"_ActionMacroHelpers")}static resolveStat(stat){switch(stat){case"perception":return{checkType:"perception-check",property:"perception",stat,subtitle:"PF2E.ActionsCheck.perception"};case"unarmed":return{checkType:"attack-roll",property:"unarmed",stat,subtitle:"PF2E.ActionsCheck.unarmed"};default:return{checkType:"skill-check",property:`skills.${sluggify(stat)}`,stat,subtitle:`PF2E.ActionsCheck.${stat}`}}}static defaultCheckContext(options,data){const{checkType:type,property,stat:slug,subtitle}=this.resolveStat(data.slug),statistic=options.actor.getStatistic(data.slug)??getProperty(options.actor,property);if(!statistic){const{actor}=options,message=`Actor ${actor.name} (${actor.id}) does not have a statistic for ${slug}.`;throw new CheckContextError(message,actor,slug)}const{item,rollOptions:contextualRollOptions}=options.buildContext({actor:options.actor,item:data.item,rollOptions:[...data.rollOptions],target:options.target});return{item,modifiers:data.modifiers??[],rollOptions:contextualRollOptions,slug,statistic,subtitle,type}}static note(selector,translationPrefix,outcome,translationKey){const outcomes=game.settings.get("pf2e","metagame_showResults")?[outcome]:[];return new RollNotePF2e({selector,text:game.i18n.localize(translationKey??`${translationPrefix}.Notes.${outcome}`),outcome:outcomes})}static outcomesNote(selector,translationKey,outcomes){const visibleOutcomes=game.settings.get("pf2e","metagame_showResults")?outcomes:[];return new RollNotePF2e({selector,text:game.i18n.localize(translationKey),outcome:visibleOutcomes})}static async simpleRollActionCheck(options){const rollers=[];if(Array.isArray(options.actors)?rollers.push(...options.actors):options.actors?rollers.push(options.actors):rollers.push(...getSelectedOrOwnActors()),rollers.length===0)throw new Error(game.i18n.localize("PF2E.ActionsWarning.NoActor"));const targetData=options.target?.()??this.target();for(const actor of rollers)try{const selfToken=actor.getActiveTokens(!1,!0).shift(),{item:weapon,modifiers=[],rollOptions:combinedOptions,statistic,subtitle,type}=await options.checkContext({actor,buildContext:args=>{const combinedOptions2=compact([args.rollOptions,options.traits].flat());return combinedOptions2.push(...args.item?.getRollOptions("item")??[]),{item:args.item,rollOptions:combinedOptions2.sort(),target:args.target}},target:targetData.actor}),header=await renderTemplate("systems/pf2e/templates/chat/action/header.hbs",{glyph:options.actionGlyph,subtitle,title:options.title}),actionTraits2=CONFIG.PF2E.actionTraits,traitDescriptions2=CONFIG.PF2E.traitsDescriptions,traitObjects=options.traits.map(trait=>({description:traitDescriptions2[trait],name:trait,label:actionTraits2[trait]??trait})),notes=options.extraNotes?.(statistic.slug)??[],label=await options.content?.(header)??header,title=`${game.i18n.localize(options.title)} - ${game.i18n.localize(subtitle)}`;if(statistic instanceof Statistic){const dc=__privateMethod(this,_resolveCheckDC,resolveCheckDC_fn).call(this,{unresolvedDC:options.difficultyClass});await statistic.roll({...eventToRollParams(options.event),token:selfToken,label,title,dc,extraRollNotes:notes,extraRollOptions:combinedOptions,modifiers,target:targetData.actor,traits:traitObjects,createMessage:options.createMessage,callback:(roll,outcome,message)=>{options.callback?.({actor,message,outcome,roll})}})}else{const check=new CheckModifier(label,statistic,modifiers),dc=__privateMethod(this,_resolveCheckDC,resolveCheckDC_fn).call(this,{target:targetData.actor,unresolvedDC:options.difficultyClass,fully:!0}),finalOptions=new Set(combinedOptions);ensureProficiencyOption(finalOptions,statistic.rank??-1),check.calculateTotal(finalOptions);const selfActor=actor.getContextualClone(combinedOptions.filter(o=>o.startsWith("self:"))),distance=(()=>{const reach=selfActor.isOfType("creature")&&weapon?.isOfType("weapon")?selfActor.getReach({action:"attack",weapon})??null:null;return selfToken?.object&&targetData?.token?.object?selfToken.object.distanceTo(targetData.token.object,{reach}):null})(),rangeIncrement=weapon?.isOfType("weapon")&&typeof distance=="number"?getRangeIncrement(weapon,distance):null,domains=["all",type,statistic.slug],targetInfo=targetData.token&&targetData.actor&&typeof distance=="number"?{token:targetData.token,actor:targetData.actor,distance,rangeIncrement}:null,substitutions=extractRollSubstitutions(actor.synthetics.rollSubstitutions,domains,finalOptions),dosAdjustments=extractDegreeOfSuccessAdjustments(actor.synthetics,domains);await CheckPF2e.roll(check,{actor:selfActor,token:selfToken,item:weapon,createMessage:options.createMessage,target:targetInfo,dc,type,options:finalOptions,notes:[...notes,...statistic.notes??[]],dosAdjustments,substitutions,traits:traitObjects,title},options.event,(roll,outcome,message)=>{options.callback?.({actor,message,outcome,roll})})}}catch(cce){if(cce instanceof CheckContextError){const message=game.i18n.format("PF2E.ActionsWarning.NoStatistic",{id:cce.actor.id,name:cce.actor.name,statistic:cce.slug});ui.notifications.error(message);continue}throw cce}}static target(){const target=Array.from(game.user.targets).filter(t=>t.actor?.isOfType("creature")).shift()?.document??null,targetActor=target?.actor??null;return{token:target,actor:targetActor}}static getWeaponPotencyModifier(item,selector){const slug="potency";return AutomaticBonusProgression.isEnabled(item.actor)?new ModifierPF2e({slug,type:"potency",label:"PF2E.AutomaticBonusProgression.attackPotency",modifier:item.actor.synthetics.weaponPotency["strike-attack-roll"]?.[0]?.bonus??0,adjustments:extractModifierAdjustments(item.actor.synthetics.modifierAdjustments,[selector],slug)}):item.system.runes.potency>0?new ModifierPF2e({slug,type:"item",label:"PF2E.Item.Weapon.Rune.Potency",modifier:item.system.runes.potency,adjustments:extractModifierAdjustments(item.actor.synthetics.modifierAdjustments,[selector],slug)}):null}static getApplicableEquippedWeapons(actor,trait){return actor.isOfType("character")?actor.system.actions.flatMap(s=>s.ready&&s.item.traits.has(trait)?s.item:[]):actor.itemTypes.weapon.filter(w=>w.isEquipped&&w.traits.has(trait))}};_resolveCheckDC=new WeakSet,resolveCheckDC_fn=__name2(function({unresolvedDC=null,target=null,fully=!1}){return typeof unresolvedDC=="string"?fully?target?.getStatistic(unresolvedDC)?.dc??null:{slug:unresolvedDC}:typeof unresolvedDC=="function"?unresolvedDC(target):unresolvedDC},"#resolveCheckDC"),__privateAdd(_ActionMacroHelpers,_resolveCheckDC),__name2(_ActionMacroHelpers,"ActionMacroHelpers");let ActionMacroHelpers=_ActionMacroHelpers;const _SelectItemDialog=class extends Application{static{__name(this,"_SelectItemDialog")}constructor(action2,resolve){super(),__privateAdd(this,_item,null),__privateAdd(this,_resolve2,void 0),__privateAdd(this,_action,void 0),__privateSet(this,_action,action2),__privateSet(this,_resolve2,resolve)}static get defaultOptions(){return{...super.defaultOptions,width:270}}get template(){return __privateGet(this,_action)==="craft"?"systems/pf2e/templates/system/actions/craft-target-item.hbs":"systems/pf2e/templates/system/actions/repair/select-item-dialog.hbs"}get title(){const key=sluggify(__privateGet(this,_action),{camel:"bactrian"});return game.i18n.localize(`PF2E.Actions.${key}.SelectItemDialog.Title`)}async getData(options={}){return options.classes=[`select-${__privateGet(this,_action)}-item-dialog`],{...await super.getData(options),item:__privateGet(this,_item)}}activateListeners($html){super.activateListeners($html);const html=$html[0];html.addEventListener("drop",async event=>{const json2=event.dataTransfer?.getData("text/plain");if(!json2?.startsWith("{")||!json2.endsWith("}"))return;const data=JSON.parse(json2),uuid=data.uuid??data.pf2e?.itemUuid,item=uuid?await fromUuid(uuid):null;if(__privateGet(this,_action)==="repair"&&item&&!(item?.isEmbedded&&item.isOwner))ui.notifications.error("DOCUMENT.UsePermissionWarn",{localize:!0});else if(item instanceof PhysicalItemPF2e)__privateSet(this,_item,item),this.render();else{const key=sluggify(__privateGet(this,_action),{camel:"bactrian"});ui.notifications.error(game.i18n.localize(`PF2E.Actions.${key}.Error.ItemReferenceMismatch`))}}),htmlQuery(html,`[data-event-handler=${__privateGet(this,_action)}]`)?.addEventListener("click",()=>{this.close()}),htmlQuery(html,"[data-event-handler=cancel]")?.addEventListener("click",()=>{__privateSet(this,_item,null),this.close()})}close(options){return __privateGet(this,_resolve2).call(this,__privateGet(this,_item)),super.close(options)}static async getItem(action2){return new Promise(resolve=>{new this(action2,resolve).render(!0)})}};_item=new WeakMap,_resolve2=new WeakMap,_action=new WeakMap,__name2(_SelectItemDialog,"SelectItemDialog");let SelectItemDialog=_SelectItemDialog;async function craft(options){const item=options.item??(options.uuid?await fromUuid(options.uuid):await SelectItemDialog.getItem("craft"));if(item){if(!(item instanceof PhysicalItemPF2e)){ui.notifications.warn(game.i18n.format("PF2E.Actions.Craft.Warning.NotPhysicalItem",{item:item.name??""}));return}}else{console.warn("PF2e System | No item selected to craft: aborting");return}const quantity=options.quantity??1,proficiencyWithoutLevel=game.settings.get("pf2e","proficiencyVariant"),dc=options.difficultyClass??{value:calculateDC(item.level,{proficiencyWithoutLevel}),visible:!0},free=!!options.free,slug=options?.skill??"crafting",rollOptions=["action:craft"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.Craft.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["downtime","manipulate"],event:options.event,difficultyClass:dc,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Craft","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Craft","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Craft","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Craft","criticalFailure")],createMessage:!1,callback:async result=>{if(result.message instanceof ChatMessagePF2e){const message=result.message,flavor=await(async()=>["criticalSuccess","success","criticalFailure"].includes(result.outcome??"")?await renderCraftingInline(item,result.roll,quantity,result.actor,free):"")();flavor&&message.updateSource({flavor:message.flavor+flavor}),ChatMessage.create(message.toObject())}else console.error("PF2E | Unable to amend chat message with craft result.",result.message);options.callback?.(result)}}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(craft,"craft"),__name2(craft,"craft");function createEmptySpellcastingEntry(actor){return new SpellcastingEntryPF2e({name:"Untitled",type:"spellcastingEntry",system:{ability:{value:"cha"},spelldc:{value:0,dc:0},tradition:{value:"arcane"},prepared:{value:"innate"}}},{actor})}__name(createEmptySpellcastingEntry,"createEmptySpellcastingEntry"),__name2(createEmptySpellcastingEntry,"createEmptySpellcastingEntry");const _SpellcastingCreateAndEditDialog=class extends FormApplication{static{__name(this,"_SpellcastingCreateAndEditDialog")}constructor(object,options){super(object instanceof ActorPF2e?createEmptySpellcastingEntry(object):object.clone({},{keepId:!0}),options),__privateAdd(this,_canSetAttribute),__publicField(this,"actor"),this.actor=object instanceof ActorPF2e?object:object.actor}static get defaultOptions(){const options=super.defaultOptions;return options.id="spellcasting-dialog",options.classes=[],options.title=game.i18n.localize("PF2E.SpellcastingSettings.Title"),options.template="systems/pf2e/templates/actors/spellcasting-dialog.hbs",options.width=350,options.submitOnChange=!0,options.closeOnSubmit=!1,options}async getData(){const{actor}=this,extraStatistics=actor.synthetics.statistics.values(),classDCs=actor.isOfType("character")?Object.values(actor.system.proficiencies.classDCs).filter(cdc=>cdc.rank>0):[],selectedStatistic=actor.getStatistic(this.object.system.proficiency.slug);return{...await super.getData(),actor,system:this.object.toObject().system,statistics:[...extraStatistics,...classDCs.map(c=>({slug:c.slug,label:game.i18n.format("PF2E.Actor.Character.ClassDC.LabelSpecific",{class:c.label})}))],magicTraditions:CONFIG.PF2E.magicTraditions,spellcastingTypes:omit(CONFIG.PF2E.preparationType,["ritual"]),attributes:CONFIG.PF2E.abilities,isAttributeConfigurable:__privateMethod(this,_canSetAttribute,canSetAttribute_fn).call(this),selectedAttribute:selectedStatistic?.attribute??this.object.attribute}}async _updateObject(event,formData){const wasInnate=this.object.isInnate,inputData=expandObject(formData),system=mergeObject(inputData.system??{},{prepared:{value:this.object.system.prepared.value},ability:{value:"cha"}},{overwrite:!1});if(inputData.system=system,system.prepared.value==="innate"&&!wasInnate&&(system.ability.value="cha"),system.proficiency?.slug&&(system.ability.value=""),system?.autoHeightenLevel&&(system.autoHeightenLevel.value||=null),this.object.updateSource(inputData),this.object.reset(),event.type!=="submit"){await this.render();return}return this.updateAndClose()}async updateAndClose(){const updateData=this.object.toObject();if(this.object.isRitual&&(updateData.system.tradition.value="",updateData.system.ability.value=""),this.object.isPrepared||delete updateData.system.prepared.flexible,this.object.id===null)updateData.name=(()=>{const preparationType=game.i18n.localize(CONFIG.PF2E.preparationType[updateData.system.prepared.value])??"",magicTraditions2=CONFIG.PF2E.magicTraditions,traditionSpells=game.i18n.localize(magicTraditions2[this.object.tradition??""]);return this.object.isRitual||!traditionSpells?preparationType:game.i18n.format("PF2E.SpellCastingFormat",{preparationType,traditionSpells})})(),await this.actor.createEmbeddedDocuments("Item",[updateData]);else{const actualEntry=this.actor.spellcasting.get(this.object.id);if(!(actualEntry instanceof SpellcastingEntryPF2e))return;const system=pick(updateData.system,["prepared","tradition","ability","proficiency","autoHeightenLevel"]);await actualEntry.update({system})}this.close()}};_canSetAttribute=new WeakSet,canSetAttribute_fn=__name2(function(){const slug=this.object._source.system.proficiency.slug,baseStat=this.actor.isOfType("character")?this.actor.getStatistic(slug):null;return!slug||!!baseStat&&!baseStat.attribute},"#canSetAttribute"),__name2(_SpellcastingCreateAndEditDialog,"SpellcastingCreateAndEditDialog");let SpellcastingCreateAndEditDialog=_SpellcastingCreateAndEditDialog;async function createSpellcastingDialog(event,object){return new SpellcastingCreateAndEditDialog(object,{top:event.clientY-80,left:window.innerWidth-710,height:"auto"}).render(!0)}__name(createSpellcastingDialog,"createSpellcastingDialog"),__name2(createSpellcastingDialog,"createSpellcastingDialog");const _SpellPreparationSheet=class extends ActorSheet{static{__name(this,"_SpellPreparationSheet")}constructor(item,options){super(item.actor,options),this.item=item}itemRenderer=new ItemSummaryRenderer(this);static get defaultOptions(){const options=super.defaultOptions;return options.classes=["default","sheet","spellcasting-entry","preparation"],options.width=480,options.height=600,options.template="systems/pf2e/templates/actors/spellcasting-prep-sheet.hbs",options.scrollY=[".sheet-content"],options.sheetConfig=!1,options}get id(){return`${super.id}-spellprep-${this.item.id}`}get title(){return game.i18n.format("PF2E.Actor.Creature.SpellPreparation.Title",{actor:this.actor.name})}_getHeaderButtons(){return super._getHeaderButtons().filter(b=>b.class==="close")}async getData(){return{...await super.getData(),owner:this.actor.isOwner,entry:await this.item.getSheetData()}}activateListeners($html){super.activateListeners($html);const html=$html[0];this.itemRenderer.activateListeners(html),$html.find(".item-edit").on("click",event=>{const item=this.getItemFromEvent(event);item&&item.sheet.render(!0)}),$html.find(".item-delete").on("click",event=>{this.getItemFromEvent(event)?.delete()}),$html.find(".item[data-item-id] .item-image").on("click",event=>{this.getItemFromEvent(event)?.toChat(event)}),$html.find(".toggle-signature-spell").on("click",event=>{const item=this.getItemFromEvent(event);item instanceof SpellPF2e&&item.update({"system.location.signature":!item.system.location.signature})});for(const link of htmlQueryAll(html,".spell-create"))link.addEventListener("click",()=>{onClickCreateSpell(this.actor,{...link.dataset,location:this.item.id})});$html.find(".spell-browse").on("click",event=>{const level=Number($(event.currentTarget).attr("data-level"))??null;game.pf2e.compendiumBrowser.openSpellTab(this.item,level)})}getItemFromEvent(event){const itemId=$(event.currentTarget).closest("li[data-item-id]").attr("data-item-id")??"";return this.actor.items.get(itemId,{strict:!0})}async _onDropItemCreate(itemSource){const spellSources=(Array.isArray(itemSource)?itemSource:[itemSource]).filter(source=>source.type==="spell");for(const spellSource of spellSources)spellSource.system.location.value=this.item.id;return super._onDropItemCreate(spellSources)}async _onSortItem(event,itemData){if(itemData.type!=="spell")return[];const spell=this.actor.items.get(itemData._id);return itemData.system.location.value!==this.item.id&&spell?.isOfType("spell")?[await this.item.spells?.addSpell(spell)??[]].flat():super._onSortItem(event,itemData)}async _renderInner(data,options){return this.itemRenderer.saveAndRestoreState(()=>super._renderInner(data,options))}};__name2(_SpellPreparationSheet,"SpellPreparationSheet");let SpellPreparationSheet=_SpellPreparationSheet;const _CreatureSheetPF2e=class extends ActorSheetPF2e{static{__name(this,"_CreatureSheetPF2e")}constructor(){super(...arguments),__privateAdd(this,_onConfigureActor),__privateAdd(this,_onToggleSignatureSpell),__privateAdd(this,_onClickBrowseActions),__privateAdd(this,_onClickBrowseSpellCompendia)}async getData(options){const sheetData=await super.getData(options),{actor}=this;if(sheetData.data.saves)for(const key of["fortitude","reflex","will"]){const save=sheetData.data.saves[key];save.icon=this.getProficiencyIcon(save.rank),save.hover=CONFIG.PF2E.proficiencyLevels[save.rank],save.label=CONFIG.PF2E.saves[key]}if(sheetData.data.attributes!==void 0&&(sheetData.data.attributes.perception.icon=this.getProficiencyIcon(sheetData.data.attributes.perception.rank),sheetData.data.attributes.perception.hover=CONFIG.PF2E.proficiencyLevels[sheetData.data.attributes.perception.rank]),sheetData.data.abilities)for(const key of ATTRIBUTE_ABBREVIATIONS)sheetData.data.abilities[key].label=CONFIG.PF2E.abilities[key];if(sheetData.data.skills){const skills=sheetData.data.skills;for(const[key,skill]of Object.entries(skills)){const label=objectHasKey(CONFIG.PF2E.skills,key)?CONFIG.PF2E.skills[key]:null;skill.icon=this.getProficiencyIcon(skill.rank??0),skill.hover=CONFIG.PF2E.proficiencyLevels[skill.rank??0],skill.label=skill.label??label??""}}return{...sheetData,languages:createSheetTags(CONFIG.PF2E.languages,actor.system.traits.languages),abilities:CONFIG.PF2E.abilities,actorSizes:CONFIG.PF2E.actorSizes,alignments:deepClone(CONFIG.PF2E.alignments),rarity:CONFIG.PF2E.rarityTraits,frequencies:CONFIG.PF2E.frequencies,attitude:CONFIG.PF2E.attitude,pfsFactions:CONFIG.PF2E.pfsFactions,dying:{maxed:actor.attributes.dying.value>=actor.attributes.dying.max,remainingDying:Math.max(actor.attributes.dying.max-actor.attributes.dying.value),remainingWounded:Math.max(actor.attributes.wounded.max-actor.attributes.wounded.value)}}}openSpellPreparationSheet(entryId){const entry=this.actor.items.get(entryId);if(entry?.isOfType("spellcastingEntry")&&entry.isPrepared){const offset=this.element.find(`.item-container[data-container-id="${entry.id}"] .prepared-toggle`).offset()??{left:0,top:0};new SpellPreparationSheet(entry,{top:offset.top-60,left:offset.left+200}).render(!0)}}async prepareSpellcasting(){return(await Promise.all(this.actor.spellcasting.map(async entry=>entry.getSheetData()))).sort((a,b)=>a.sort-b.sort)}getProficiencyIcon(level){return[...Array(level)].map(()=>fontAwesomeIcon("check-circle").outerHTML).join("")}activateListeners($html){super.activateListeners($html);const html=$html[0],carryMenuListener=__name2(event=>{if(!(event.currentTarget instanceof HTMLElement))throw ErrorPF2e("Unexpected error retrieving carry-type link");const menu=event.currentTarget,toggle=menu.nextElementSibling;toggle?.classList.contains("carry-type-hover")&&$(toggle).tooltipster("close");const carryType=menu.dataset.carryType;if(!setHasElement(ITEM_CARRY_TYPES,carryType))throw ErrorPF2e("Unexpected error retrieving requested carry type");const itemId=htmlClosest(menu,"[data-item-id]")?.dataset.itemId,item=this.actor.inventory.get(itemId,{strict:!0}),handsHeld=Number(menu.dataset.handsHeld)||0,inSlot=menu.dataset.inSlot==="true",current=item.system.equipped;(carryType!==current.carryType||inSlot!==current.inSlot||carryType==="held"&&handsHeld!==current.handsHeld)&&this.actor.adjustCarryType(item,{carryType,handsHeld,inSlot})},"carryMenuListener");for(const carryTypeMenu of htmlQueryAll(html,".tab.inventory a[data-carry-type]"))carryTypeMenu.addEventListener("click",carryMenuListener);const selectors="input[data-item-id][data-item-property], select[data-item-id][data-item-property]";$html.find(selectors).on("change",event=>{const $target=$(event.target),{itemId,itemProperty}=event.target.dataset;if(!itemId||!itemProperty)return;const value=(()=>{const value2=$(event.target).val();if(typeof value2>"u"||value2===null)return value2;switch($target.attr("data-dtype")??($target.attr("type")==="checkbox"?"Boolean":["number","range"].includes($target.attr("type")??"")?"Number":"String")){case"Boolean":return typeof value2=="boolean"?value2:value2==="true";case"Number":return Number(value2);case"String":return String(value2);default:return value2}})();this.actor.updateEmbeddedDocuments("Item",[{_id:itemId,[itemProperty]:value}])}),$html.find(".dots.dying, .dots.wounded").on("click contextmenu",event=>{const condition=Array.from(event.delegateTarget.classList).find(className=>["dying","wounded"].includes(className));if(condition){const currentMax=this.actor.system.attributes[condition]?.max;event.type==="click"&¤tMax?this.actor.increaseCondition(condition,{max:currentMax}):event.type==="contextmenu"&&this.actor.decreaseCondition(condition)}}),$html.find("[data-action=recovery-check]").tooltipster({theme:"crb-hover"}).filter(":not(.disabled)").on("click",event=>{this.actor.rollRecovery(event)}),$html.find(".skill-name.rollable, .skill-score.rollable").on("click",event=>{const skill=event.currentTarget.closest("[data-skill]")?.dataset.skill??"",key=objectHasKey(SKILL_DICTIONARY,skill)?SKILL_DICTIONARY[skill]:skill,rollParams=eventToRollParams(event);this.actor.skills[key]?.check.roll(rollParams)});for(const element of htmlQueryAll(html,"a[data-action=perception-check]"))element.addEventListener("click",event=>{const extraRollOptions=element.dataset.secret?["secret"]:[];this.actor.perception.roll({...eventToRollParams(event),extraRollOptions})});for(const section of htmlQueryAll(html,".tab.spellcasting, .tab.spells")??[]){for(const element of htmlQueryAll(section,"[data-action=spellcasting-create]")??[])element.addEventListener("click",event=>{createSpellcastingDialog(event,this.actor)});for(const element of htmlQueryAll(section,"[data-action=spellcasting-edit]")??[])element.addEventListener("click",event=>{const containerId=htmlClosest(event.target,"[data-item-id]")?.dataset.itemId,entry=this.actor.items.get(containerId,{strict:!0});entry.isOfType("spellcastingEntry")&&createSpellcastingDialog(event,entry)});for(const element of htmlQueryAll(section,"[data-action=spellcasting-remove]")??[])element.addEventListener("click",async event=>{const itemId=htmlClosest(event.currentTarget,"[data-item-id]")?.dataset.itemId,item=this.actor.items.get(itemId,{strict:!0}),title=game.i18n.localize("PF2E.DeleteSpellcastEntryTitle"),content=await renderTemplate("systems/pf2e/templates/actors/delete-spellcasting-dialog.hbs");await Dialog.confirm({title,content})&&item.delete()})}$html.find(".prepared-toggle").on("click",async event=>{event.preventDefault();const itemId=$(event.currentTarget).parents(".item-container").attr("data-container-id")??"";this.openSpellPreparationSheet(itemId)});for(const toggle of htmlQueryAll(html,".slotless-level-toggle"))toggle.addEventListener("click",async()=>{const itemId=htmlClosest(toggle,".item-container")?.dataset.containerId??"",spellcastingEntry=this.actor.items.get(itemId);if(!spellcastingEntry?.isOfType("spellcastingEntry"))throw ErrorPF2e("Tried to toggle visibility of slotless levels on a non-spellcasting entry");await spellcastingEntry.update({"system.showSlotlessLevels.value":!spellcastingEntry.showSlotlessLevels})});for(const button of htmlQueryAll(html,"button[data-action=cast-spell]"))button.addEventListener("click",()=>{const spellEl=htmlClosest(button,".item"),{itemId,slotLevel,slotId,entryId}=spellEl?.dataset??{},collection=this.actor.spellcasting.collections.get(entryId,{strict:!0}),spell=collection.get(itemId,{strict:!0});collection.entry.cast(spell,{slot:Number(slotId??NaN),level:Number(slotLevel??NaN)})});$html.find(".spell-slots-increment-reset").on("click",event=>{const target=$(event.currentTarget),itemId=target.data().itemId,itemLevel=target.data().level,item=this.actor.items.get(itemId);if(item?.isOfType("spellcastingEntry")){const{system}=item.toObject();if(!system.slots)return;const slotLevel=goesToEleven(itemLevel)?`slot${itemLevel}`:"slot0";system.slots[slotLevel].value=system.slots[slotLevel].max,item.update({system})}else if(item?.isOfType("spell")){const max=item.system.location.uses?.max;if(!max)return;item.update({"system.location.uses.value":max})}}),$html.find(".focus-pool").on("change",event=>{this.actor.update({"system.resources.focus.max":$(event.target).val()})}),$html.find(".toggle-signature-spell").on("click",event=>{__privateMethod(this,_onToggleSignatureSpell,onToggleSignatureSpell_fn).call(this,event)});for(const button of htmlQueryAll(html,".action-browse"))button.addEventListener("click",()=>__privateMethod(this,_onClickBrowseActions,onClickBrowseActions_fn).call(this,button));for(const button of htmlQueryAll(html,".spell-browse"))button.addEventListener("click",()=>__privateMethod(this,_onClickBrowseSpellCompendia,onClickBrowseSpellCompendia_fn).call(this,button))}async _onSortItem(event,itemSource){const dropItemEl=htmlClosest(event.target,".item"),dropContainerEl=htmlClosest(event.target,".item-container"),dropSlotType=dropItemEl?.dataset.itemType,dropContainerType=dropContainerEl?.dataset.containerType,item=this.actor.items.get(itemSource._id);if(!item)return[];if(item.isOfType("spell")){if(!(dropItemEl&&dropContainerEl))return[];const entryId=dropContainerEl.dataset.containerId,collection=this.actor.spellcasting.collections.get(entryId,{strict:!0});if(dropSlotType==="spellLevel"){const{level}=dropItemEl.dataset,spell=await collection.addSpell(item,{slotLevel:Number(level)});return this.openSpellPreparationSheet(collection.id),[spell??[]].flat()}else if(dropItemEl.dataset.slotId){const dropId=Number(dropItemEl.dataset.slotId),slotRank=Number(dropItemEl.dataset.slotLevel);if(Number.isInteger(dropId)&&Number.isInteger(slotRank)){const allocated=await collection.prepareSpell(item,slotRank,dropId);if(allocated instanceof SpellcastingEntryPF2e)return[allocated]}}else if(dropSlotType==="spell"){const dropId=dropItemEl.dataset.itemId??"",target=this.actor.items.get(dropId);if(target?.isOfType("spell")&&item.id!==dropId){const sourceLocation=item.system.location.value,testSibling=__name2((item2,test)=>item2.isCantrip!==test.isCantrip?!1:!!(item2.isCantrip&&test.isCantrip||item2.isFocusSpell&&test.isFocusSpell||item2.rank===test.rank),"testSibling");if(sourceLocation===entryId&&testSibling(item,target)){const siblings=collection.filter(s=>testSibling(item,s));return await item.sortRelative({target,siblings}),[target]}else{const spell=await collection.addSpell(item,{slotLevel:target.rank});return this.openSpellPreparationSheet(collection.id),[spell??[]].flat()}}}else if(dropContainerType==="spellcastingEntry"){CONFIG.debug.hooks&&console.debug("PF2e System | ***** spell from same actor dropped on a spellcasting entry *****");const dropId=htmlClosest(event.target,".item-container")?.dataset.containerId;return dropId?[await item.update({"system.location.value":dropId})]:[]}}else if(item.isOfType("spellcastingEntry")&&dropContainerType==="spellcastingEntry"){const sourceId=item.id,dropId=dropContainerEl?.dataset.containerId??"",source=this.actor.items.get(sourceId),target=this.actor.items.get(dropId);if(source?.isOfType("spellcastingEntry")&&target?.isOfType("spellcastingEntry")&&source.id!==target.id){const siblings=this.actor.itemTypes.spellcastingEntry;return await source.sortRelative({target,siblings}),[source]}}return super._onSortItem(event,itemSource)}async _handleDroppedItem(event,item,data){const containerEl=htmlClosest(event.target,".item-container[data-container-type=spellcastingEntry]");if(containerEl&&item.isOfType("spell")&&!item.isRitual){const entryId=containerEl.dataset.containerId,collection=this.actor.spellcasting.collections.get(entryId,{strict:!0}),slotLevel=Number(htmlClosest(event.target,"[data-slot-level]")?.dataset.slotLevel??0);return this.openSpellPreparationSheet(collection.id),[await collection.addSpell(item,{slotLevel:Math.max(slotLevel,item.baseRank)})??[]].flat()}return super._handleDroppedItem(event,item,data)}_getHeaderButtons(){const buttons=super._getHeaderButtons();if(!this.actor.isOfType("character","npc"))return buttons;if(this.isEditable){const index=buttons.findIndex(b=>b.class==="close");buttons.splice(index,0,{label:"Configure",class:"configure-creature",icon:"fa-solid fa-user-gear",onclick:()=>__privateMethod(this,_onConfigureActor,onConfigureActor_fn).call(this)})}return buttons}async _updateObject(event,formData){const heldShield=this.actor.heldShield;return heldShield&&typeof formData["system.attributes.shield.hp.value"]=="number"&&await heldShield.update({"system.hp.value":formData["system.attributes.shield.hp.value"]}),delete formData["system.attributes.shield.hp.value"],super._updateObject(event,formData)}};_onConfigureActor=new WeakSet,onConfigureActor_fn=__name2(function(){this.actorConfigClass&&new this.actorConfigClass(this.actor).render(!0)},"#onConfigureActor"),_onToggleSignatureSpell=new WeakSet,onToggleSignatureSpell_fn=__name2(function(event){const{itemId}=event.target.closest(".item").dataset,spell=this.actor.items.get(itemId);spell instanceof SpellPF2e&&spell.update({"system.location.signature":!spell.system.location.signature})},"#onToggleSignatureSpell"),_onClickBrowseActions=new WeakSet,onClickBrowseActions_fn=__name2(function(button){const types=(button.dataset.actionType||"").split(","),traits=(button.dataset.actionTrait||"").split(","),categories=(button.dataset.actionCategory||"").split(",");game.pf2e.compendiumBrowser.openActionTab({types,traits,categories})},"#onClickBrowseActions"),_onClickBrowseSpellCompendia=new WeakSet,onClickBrowseSpellCompendia_fn=__name2(function(button){const level=Number(button.dataset.level??null),spellcastingIndex=htmlClosest(button,"[data-container-id]")?.dataset.containerId??"",entry=this.actor.spellcasting.get(spellcastingIndex);entry&&game.pf2e.compendiumBrowser.openSpellTab(entry,level)},"#onClickBrowseSpellCompendia"),__name2(_CreatureSheetPF2e,"CreatureSheetPF2e");let CreatureSheetPF2e=_CreatureSheetPF2e;async function add(actor,event){const weaponGroups2=CONFIG.PF2E.weaponGroups,baseWeapons=CONFIG.PF2E.baseWeaponTypes,template=await renderTemplate("systems/pf2e/templates/actors/add-combat-proficiency-dialog.hbs",{message:game.i18n.localize("PF2E.AddCombatProficiency.Message"),weaponGroups:weaponGroups2,baseWeapons});new Dialog({title:game.i18n.localize("PF2E.AddCombatProficiency.Title"),content:template,buttons:{add:{icon:fontAwesomeIcon("check").outerHTML,label:game.i18n.localize("PF2E.AddShortLabel"),callback:async $dialog=>{const selection=$dialog.find("select[name=proficiency]").val();if(typeof selection=="string"&&selection){const proficiencyKey=selection in weaponGroups2?`weapon-group-${selection}`:`weapon-base-${selection}`;await actor.addAttackProficiency(proficiencyKey);const tab=htmlClosest(event.currentTarget,".tab.skills");if(tab){const $tab=$(tab);$tab.animate({scrollTop:$tab.height()},"slow")}}}},cancel:{icon:fontAwesomeIcon("times").outerHTML,label:game.i18n.localize("Cancel")}},default:"cancel"}).render(!0)}__name(add,"add"),__name2(add,"add");function remove(actor,event){const weaponGroups2=CONFIG.PF2E.weaponGroups,baseWeapons=CONFIG.PF2E.baseWeaponTypes,key=htmlClosest(event.currentTarget,"li.skill.custom")?.dataset.skill??"",translationKey=key?.replace(/^weapon-(?:base|group)-/,"")??"",name2=objectHasKey(weaponGroups2,translationKey)?game.i18n.localize(weaponGroups2[translationKey]):baseWeapons[translationKey],localize=localizer("PF2E.RemoveCombatProficiency"),message=localize("Message",{proficiency:name2});Dialog.confirm({title:localize("Title"),content:`

${message}

`,defaultYes:!1,yes:()=>{key in(actor._source.system.proficiencies?.attacks??{})&&actor.update({[`system.proficiencies.attacks.-=${key}`]:null})}})}__name(remove,"remove"),__name2(remove,"remove");const ManageAttackProficiencies={add,remove},_AttributeBuilder=class extends Application{static{__name(this,"_AttributeBuilder")}constructor(actor){super(),__privateAdd(this,_createButtons),__privateAdd(this,_calculateAncestryBoosts),__privateAdd(this,_calculateBackgroundBoosts),__privateAdd(this,_calculateLeveledBoosts),__privateAdd(this,_getBoostFlawLabels),__publicField(this,"actor"),__privateAdd(this,_abpEnabled,void 0),this.actor=actor,__privateSet(this,_abpEnabled,game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(actor)),actor.apps[this.appId]=this}static get defaultOptions(){return{...super.defaultOptions,classes:["attribute-builder"],title:game.i18n.localize("PF2E.Actor.Character.Attribute.Boosts"),template:"systems/pf2e/templates/actors/character/attribute-builder.hbs",width:"auto",height:"auto"}}get id(){return`attribute-builder-${this.actor.uuid}`}async getData(options={}){const{actor}=this,build=actor.system.build.attributes;return{...await super.getData(options),actor,attributes:CONFIG.PF2E.abilities,manual:build.manual,ancestry:actor.ancestry,background:actor.background,class:actor.class,attributeModifiers:mapValues$1(actor.abilities,(value,attribute)=>{const mod=build.manual?actor._source.system.abilities?.[attribute].mod??0:value.base;return{mod:addSign(Number(mod.toFixed(1))),label:CONFIG.PF2E.abilities[attribute]}}),manualKeyAttribute:actor.keyAttribute,keyOptions:build.keyOptions,...__privateMethod(this,_calculateAncestryBoosts,calculateAncestryBoosts_fn).call(this),backgroundBoosts:__privateMethod(this,_calculateBackgroundBoosts,calculateBackgroundBoosts_fn).call(this),legacyFlaws:actor.ancestry?.system.voluntary?.boost!==void 0,levelBoosts:__privateMethod(this,_calculateLeveledBoosts,calculateLeveledBoosts_fn).call(this)}}async _render(force,options){return maintainFocusInRender(this,()=>super._render(force,options))}async close(options={}){return delete this.actor.apps[this.appId],super.close(options)}activateListeners($html){super.activateListeners($html);const html=$html[0],{actor}=this;$html.find("[data-tooltip-content]").tooltipster({contentAsHTML:!0,arrow:!1,debug:!1,interactive:!0,maxWidth:350,side:["bottom"],theme:"crb-hover"}),$html.find("div.tooltip").tooltipster();for(const input of htmlQueryAll(html,"input[type=text], input[type=number]"))input.addEventListener("focus",()=>{input.type==="text"&&input.dataset.dtype==="Number"&&(input.value=input.value.replace(/[^-.0-9]/g,""),input.type="number"),input.select()}),input.addEventListener("blur",()=>{if(input.type==="number"&&input.dataset.dtype==="Number"){input.type="text";const newValue=Math.clamped(Number(input.value)||0,-5,10);input.value=addSign(newValue);const propertyPath=input.dataset.property;if(!propertyPath)throw ErrorPF2e("Empty property path");actor.update({[propertyPath]:newValue})}});htmlQuery(html,"[data-action=toggle-alternate-ancestry-boosts]")?.addEventListener("click",()=>{actor.ancestry&&(actor.ancestry.system.alternateAncestryBoosts?actor.ancestry.update({"system.-=alternateAncestryBoosts":null}):actor.ancestry.update({"system.alternateAncestryBoosts":[]}))}),htmlQuery(html,"[data-action=toggle-legacy-voluntary-flaw]")?.addEventListener("click",async()=>{const ancestry=actor.ancestry;if(!ancestry)return;const voluntary=ancestry.system.voluntary;if(voluntary?.boost!==void 0){const flaws=uniq(voluntary.flaws);ancestry.update({system:{voluntary:{"-=boost":null,flaws}}})}else{const flaws=voluntary?.flaws.slice(0,2)??[];ancestry.update({system:{voluntary:{boost:null,flaws}}})}});for(const button of htmlQueryAll(html,"[data-section=ancestry] .boost"))button.addEventListener("click",async()=>{const ancestry=actor.ancestry,attribute=button.dataset.attribute;if(!ancestry||!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute))return;if(ancestry.system.alternateAncestryBoosts){const existingBoosts=ancestry.system.alternateAncestryBoosts,boosts=existingBoosts.includes(attribute)?existingBoosts.filter(b=>b!==attribute):[...existingBoosts,attribute].slice(0,2);ancestry.update({"system.alternateAncestryBoosts":boosts});return}const boostToRemove=Object.entries(ancestry.system.boosts??{}).find(([,b])=>b.selected===attribute);if(boostToRemove){await ancestry.update({[`system.boosts.${boostToRemove[0]}.selected`]:null});return}const freeBoost=Object.entries(ancestry.system.boosts??{}).find(([,b])=>!b.selected&&b.value.length>0);freeBoost&&await ancestry.update({[`system.boosts.${freeBoost[0]}.selected`]:attribute})});for(const button of htmlQueryAll(html,"[data-section=voluntary] .boost-button"))button.addEventListener("click",()=>{const ancestry=actor.ancestry,attribute=button.dataset.attribute;if(!ancestry||!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute))return;const removing=button.classList.contains("selected");if(button.dataset.action==="flaw"){const{flaws,boost}=ancestry.system.voluntary??{flaws:[]},alreadyHasFlaw=flaws.includes(attribute),isLegacy=boost!==void 0;if(removing&&alreadyHasFlaw&&!boost){flaws.splice(flaws.indexOf(attribute),1),ancestry.update({system:{voluntary:{flaws}}});return}const canDoubleFlaw=ancestry.lockedBoosts.includes(attribute)&&isLegacy,maxFlaws=isLegacy?2:6;flaws.length{const attribute=button.dataset.attribute;if(!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute))return;const boostToRemove=Object.entries(actor.background?.system.boosts??{}).find(([,b])=>b.selected===attribute);if(boostToRemove){actor.background?.update({[`system.boosts.${boostToRemove[0]}.selected`]:null});return}const freeBoost=Object.entries(actor.background?.system.boosts??{}).find(([,b])=>!b.selected&&b.value.length>0);freeBoost&&actor.background?.update({[`system.boosts.${freeBoost[0]}.selected`]:attribute})});for(const button of htmlQueryAll(html,"button[data-action=class-key-attribute]"))button.addEventListener("click",()=>{const attribute=button.dataset.attribute;if(!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute))throw ErrorPF2e(`Unrecognized attribute abbreviation: ${attribute}`);actor.system.build.attributes.manual?actor.update({"system.details.keyability.value":attribute}):actor.class?.update({"system.keyAbility.selected":attribute})});for(const button of htmlQueryAll(html,"[data-level] .boost"))button.addEventListener("click",()=>{const level=Number(htmlClosest(button,"[data-level]")?.dataset.level),attribute=button.dataset.attribute;if(!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute)||!tupleHasValue([1,5,10,15,20],level))return;const buildSource=mergeObject(actor.toObject().system.build??{},{attributes:{boosts:{}}}),boosts=buildSource.attributes.boosts[level]??=[];boosts.includes(attribute)?boosts.splice(boosts.indexOf(attribute),1):boosts.push(attribute),actor.update({"system.build":buildSource})});for(const button of htmlQueryAll(html,"button[data-action=apex]"))button.addEventListener("click",()=>{const attribute=button.dataset.attribute;if(!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute))throw ErrorPF2e(`Unrecognized attribute abbreviation: ${attribute}`);const current=this.actor.system.build.attributes.apex;actor.update({"system.build.attributes.apex":__privateGet(this,_abpEnabled)&&attribute!==current?attribute:null})});htmlQuery(html,"input[name=toggle-manual-mode]")?.addEventListener("click",()=>{actor.toggleAttributeManagement()}),htmlQuery(html,"button[data-action=close]")?.addEventListener("click",()=>this.close())}};_abpEnabled=new WeakMap,_createButtons=new WeakSet,createButtons_fn=__name2(function(){return Array.from(ATTRIBUTE_ABBREVIATIONS).reduce((accumulated,attribute)=>(accumulated[attribute]={ability:attribute},accumulated),{})},"#createButtons"),_calculateAncestryBoosts=new WeakSet,calculateAncestryBoosts_fn=__name2(function(){const{actor}=this,ancestry=actor.ancestry;if(!ancestry)return{ancestryBoosts:null,voluntaryFlaws:null};const buttons=__privateMethod(this,_createButtons,createButtons_fn).call(this),[maxBoosts,selectedBoosts]=(()=>{const alternateAncestryBoosts=ancestry.system.alternateAncestryBoosts;if(alternateAncestryBoosts)return[2,alternateAncestryBoosts];const baseBoosts=Object.values(ancestry.system.boosts),selectedBoosts2=baseBoosts.map(b=>b.selected).filter(b=>!!b);return[baseBoosts.filter(b=>b.value.length>0||b.selected).length,selectedBoosts2]})(),build=actor.system.build.attributes,netBoosted=difference(build.boosts.ancestry,build.flaws.ancestry),remaining=maxBoosts-selectedBoosts.length,lockedBoosts=ancestry.system.alternateAncestryBoosts?null:ancestry.lockedBoosts,lockedFlaws=ancestry.system.alternateAncestryBoosts?null:ancestry.lockedFlaws;for(const attribute of ATTRIBUTE_ABBREVIATIONS){const state=buttons[attribute],selected=selectedBoosts.includes(attribute);state.boost={selected,locked:lockedBoosts?.includes(attribute),disabled:selected?!1:!remaining||netBoosted.includes(attribute)},lockedFlaws?.includes(attribute)&&(state.flaw={selected:!0,locked:!0})}const voluntaryFlaws=(()=>{const voluntary=ancestry.system.voluntary??{flaws:[]},legacyFlaws=voluntary.boost!==void 0,flawsComplete=legacyFlaws&&voluntary.flaws.length>=2,buttons2=__privateMethod(this,_createButtons,createButtons_fn).call(this);for(const attribute of ATTRIBUTE_ABBREVIATIONS){const state=buttons2[attribute],numFlaws=voluntary.flaws.filter(f=>f===attribute).length;if(state.flaw={selected:numFlaws>0,disabled:!numFlaws&&flawsComplete},legacyFlaws){lockedBoosts?.includes(attribute)&&(state.flaw.second={selected:numFlaws>1,disabled:!numFlaws||numFlaws<2&&flawsComplete});const boosted=voluntary.boost===attribute;state.boost={selected:boosted,disabled:boosted?!1:!flawsComplete||!!voluntary.boost||netBoosted.includes(attribute)}}}return{remaining:voluntary&&legacyFlaws&&!voluntary.boost?1:0,buttons:buttons2,voluntaryBoostsRemaining:0,labels:__privateMethod(this,_getBoostFlawLabels,getBoostFlawLabels_fn).call(this,ancestry.system.flaws)}})();return{ancestryBoosts:{buttons,remaining,labels:__privateMethod(this,_getBoostFlawLabels,getBoostFlawLabels_fn).call(this,ancestry.system.boosts),alternate:!!ancestry.system.alternateAncestryBoosts},voluntaryFlaws}},"#calculateAncestryBoosts"),_calculateBackgroundBoosts=new WeakSet,calculateBackgroundBoosts_fn=__name2(function(){const{actor}=this;if(!actor.background)return null;const buttons=__privateMethod(this,_createButtons,createButtons_fn).call(this),boosts=Object.values(actor.background.system.boosts).filter(b=>b.value.length>0),selectedBoosts=boosts.map(b=>b.selected).filter(b=>!!b),unselectedRestricted=boosts.filter(b=>b.value.length<6&&!b.selected).flatMap(b=>b.value),remaining=boosts.length-selectedBoosts.length;for(const attribute of ATTRIBUTE_ABBREVIATIONS){const selected=selectedBoosts.includes(attribute),mightBeForced=unselectedRestricted.includes(attribute);buttons[attribute].boost={selected,disabled:!(selected||remaining)||!!unselectedRestricted.length&&!mightBeForced}}const labels=__privateMethod(this,_getBoostFlawLabels,getBoostFlawLabels_fn).call(this,actor.background.system.boosts),tooltip=(()=>{const boosts2=actor.background?.system.boosts??{};if(Object.values(boosts2).length===2&&Object.values(boosts2)[0].value.length===2&&Object.values(boosts2)[1].value.length===6){const choices=Object.values(boosts2)[0].value.map(b=>game.i18n.localize(CONFIG.PF2E.abilities[b]));return game.i18n.format("PF2E.Actor.Character.AttributeBuilder.BackgroundBoostDescription",{a:choices[0],b:choices[1]})}else return null})();return{buttons,remaining,labels,tooltip}},"#calculateBackgroundBoosts"),_calculateLeveledBoosts=new WeakSet,calculateLeveledBoosts_fn=__name2(function(){const build=this.actor.system.build.attributes,isGradual=game.settings.get("pf2e","gradualBoostsVariant"),boostIsPartial=__name2((attribute,level,isApex)=>{if(level<5||build.manual||isApex)return!1;const boosts=compact([build.boosts.ancestry.find(a=>a===attribute),build.boosts.background.find(a=>a===attribute),build.boosts.class===attribute?attribute:null,build.boosts[1].find(a=>a===attribute),level===20?build.boosts[20].find(a=>a===attribute):null,level>=15?build.boosts[15].find(a=>a===attribute):null,level>=10?build.boosts[10].find(a=>a===attribute):null,level>=5?build.boosts[5].find(a=>a===attribute):null]).length,flaws=Number(build.flaws.ancestry.some(a=>a===attribute)),netBoosts=boosts-flaws,cssClasses={0:!1,1:!0};return netBoosts>=5?cssClasses[netBoosts%2]:!1},"boostIsPartial");return[1,5,10,15,17,20].flatMap(level=>{const isApex=level===17;if(isApex&&!__privateGet(this,_abpEnabled))return[];const remaining=isApex?+!build.apex:build.allowedBoosts[level]-build.boosts[level].length,buttons=__privateMethod(this,_createButtons,createButtons_fn).call(this);for(const attribute of ATTRIBUTE_ABBREVIATIONS){const selected=isApex?build.apex===attribute:build.boosts[level].includes(attribute),partial=selected&&boostIsPartial(attribute,level,isApex);buttons[attribute].boost={selected,partial,disabled:!remaining}}const eligible=isApex?this.actor.level>=17:build.allowedBoosts[level]>0,minLevel=isGradual&&!isApex?Math.max(1,level-3):level;return{buttons,remaining,level,eligible,minLevel,isApex}})},"#calculateLeveledBoosts"),_getBoostFlawLabels=new WeakSet,getBoostFlawLabels_fn=__name2(function(boostData){return Object.values(boostData).flatMap(boosts=>boosts.value.length===6?game.i18n.localize("PF2E.AbilityFree"):boosts.value.length>0?boosts.value.map(b=>game.i18n.localize(CONFIG.PF2E.abilities[b])).join(" or "):[])},"#getBoostFlawLabels"),__name2(_AttributeBuilder,"AttributeBuilder");let AttributeBuilder=_AttributeBuilder;const _CreatureConfig=class extends DocumentSheet{static{__name(this,"_CreatureConfig")}get title(){const namespace=this.actor.isOfType("character")?"Character":"NPC";return game.i18n.localize(`PF2E.Actor.${namespace}.Configure.Title`)}get template(){return`systems/pf2e/templates/actors/${this.actor.type}/config.hbs`}get actor(){return this.object}static get defaultOptions(){const options=super.defaultOptions;return options.width=450,options}async getData(options={}){const source=this.actor._source,alliance=source.system.details?.alliance===null?"neutral":source.system.details?.alliance??"default",defaultValue=game.i18n.localize(this.actor.hasPlayerOwner?"PF2E.Actor.Creature.Alliance.Party":"PF2E.Actor.Creature.Alliance.Opposition"),allianceOptions={default:game.i18n.format("PF2E.Actor.Creature.Alliance.Default",{alliance:defaultValue}),opposition:"PF2E.Actor.Creature.Alliance.Opposition",party:"PF2E.Actor.Creature.Alliance.Party",neutral:"PF2E.Actor.Creature.Alliance.Neutral"};return{...await super.getData(options),alliances:createSheetOptions(allianceOptions,{value:[alliance]})}}async _updateObject(event,formData){const key="system.details.alliance",alliance=formData[key];if(alliance==="default")delete formData[key],formData["system.details.-=alliance"]=null;else if(alliance==="neutral")formData[key]=null;else if(!setHasElement(ALLIANCES,alliance))throw ErrorPF2e("Unrecognized alliance");return super._updateObject(event,formData)}};__name2(_CreatureConfig,"CreatureConfig");let CreatureConfig=_CreatureConfig;const _CharacterConfig=class extends CreatureConfig{static{__name(this,"_CharacterConfig")}async getData(options={}){const{showBasicUnarmed}=this.actor.flags.pf2e;return{...await super.getData(options),showBasicUnarmed}}};__name2(_CharacterConfig,"CharacterConfig");let CharacterConfig=_CharacterConfig;const _CraftingFormula=class{static{__name(this,"_CraftingFormula")}constructor(item,{dc,batchSize,deletable=!1}={}){this.item=item,this.dc=dc??calculateDC(item.level,{rarity:item.rarity,proficiencyWithoutLevel:game.settings.get("pf2e","proficiencyVariant")}),this.batchSize=Math.max(batchSize??1,this.defaultBatchSize),this.deletable=deletable}dc;batchSize;deletable;get uuid(){return this.item.uuid}get img(){return this.item.img}get name(){return this.item.name}get level(){return this.item.level}get rarity(){return this.item.rarity}get price(){return this.item.price}get cost(){return CoinsPF2e.fromPrice(this.price,this.batchSize)}get minimumBatchSize(){return STACK_DEFINITIONS[this.item.system.stackGroup??""]?.size??1}get defaultBatchSize(){const{item}=this,isMundaneAmmo=item instanceof ConsumablePF2e&&item.isAmmunition&&!item.isMagical,isConsumable=item instanceof ConsumablePF2e&&item.category!=="wand"||item instanceof WeaponPF2e&&item.baseType==="alchemical-bomb";return Math.max(this.minimumBatchSize,isMundaneAmmo?10:isConsumable?4:1)}get description(){return this.item.description}};__name2(_CraftingFormula,"CraftingFormula");let CraftingFormula=_CraftingFormula;const _CraftingEntry=class{static{__name(this,"_CraftingEntry")}constructor(actor,knownFormulas,data){__privateAdd(this,_updateRE),__publicField(this,"preparedCraftingFormulas"),__publicField(this,"preparedFormulaData"),__publicField(this,"name"),__publicField(this,"selector"),__publicField(this,"isAlchemical"),__publicField(this,"isDailyPrep"),__publicField(this,"isPrepared"),__publicField(this,"craftableItems"),__publicField(this,"maxSlots"),__publicField(this,"fieldDiscovery"),__publicField(this,"batchSize"),__publicField(this,"fieldDiscoveryBatchSize"),__publicField(this,"maxItemLevel"),__publicField(this,"parentItem"),this.selector=data.selector,this.name=data.name,this.isAlchemical=!!data.isAlchemical,this.isDailyPrep=!!data.isDailyPrep,this.isPrepared=!!data.isPrepared,this.maxSlots=data.maxSlots??0,this.maxItemLevel=data.maxItemLevel||actor.level,this.fieldDiscovery=data.fieldDiscovery?new PredicatePF2e(data.fieldDiscovery):null,this.batchSize=data.batchSize,this.fieldDiscoveryBatchSize=data.fieldDiscoveryBatchSize,this.craftableItems=new PredicatePF2e(data.craftableItems),this.preparedFormulaData=(data.preparedFormulaData||[]).map(prepData=>knownFormulas.find(formula2=>formula2.uuid===prepData.itemUUID)?prepData:null).filter(prepData=>!!prepData),this.parentItem=actor.items.get(data.parentItem,{strict:!0}),this.preparedCraftingFormulas=this.preparedFormulaData.sort((prepDataA,prepDataB)=>(prepDataA.sort??0)-(prepDataB.sort??0)).map(prepData=>{const formula=knownFormulas.find(formula2=>formula2.uuid===prepData.itemUUID);return formula?Object.assign(new CraftingFormula(formula.item),{quantity:prepData.quantity||1,expended:!!prepData.expended,isSignatureItem:!!prepData.isSignatureItem,sort:prepData.sort??0}):null}).filter(prepData=>!!prepData)}get actor(){return this.parentItem.actor}get formulas(){const formulas=this.preparedCraftingFormulas.map(formula=>({uuid:formula.uuid,img:formula.img,name:formula.name,expended:formula.expended,quantity:formula.quantity,isSignatureItem:formula.isSignatureItem}));if(this.maxSlots>0){const fill=this.maxSlots-formulas.length;if(fill>0){const nulls=new Array(fill).fill(null);return formulas.concat(nulls)}}return formulas}get reagentCost(){if(!this.isAlchemical)return 0;const fieldDiscoveryQuantity=this.preparedCraftingFormulas.filter(f=>!!this.fieldDiscovery?.test(f.item.getRollOptions("item"))||f.isSignatureItem).reduce((sum2,current)=>sum2+current.quantity,0),otherQuantity=this.preparedCraftingFormulas.filter(f=>!this.fieldDiscovery?.test(f.item.getRollOptions("item"))&&!f.isSignatureItem).reduce((sum2,current)=>sum2+current.quantity,0),fieldDiscoveryBatchSize=this.fieldDiscoveryBatchSize||3,batchSize=this.batchSize||2;return Math.floor(fieldDiscoveryQuantity/fieldDiscoveryBatchSize)+Math.ceil((fieldDiscoveryQuantity%fieldDiscoveryBatchSize+otherQuantity)/batchSize)}static isValid(data){return!!data&&!!data.name&&!!data.selector}async prepareFormula(formula){this.checkEntryRequirements(formula);const index=this.preparedFormulaData.findIndex(f=>f.itemUUID===formula.uuid);if(this.isAlchemical&&index!==-1){const formula2=this.preparedFormulaData[index];formula2.quantity?formula2.quantity+=1:formula2.quantity=2}else this.preparedFormulaData.push({itemUUID:formula.uuid,quantity:1});return __privateMethod(this,_updateRE,updateRE_fn).call(this)}checkEntryRequirements(formula,{warn=!0}={}){return this.maxSlots&&this.formulas.filter(f=>f!==null).length>=this.maxSlots?(warn&&ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.MaxSlots")),!1):this.actor.levelthis.maxItemLevel?(warn&&ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.MaxItemLevel")),!1):this.craftableItems.test(formula.item.getRollOptions("item"))?!0:(warn&&ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.ItemMissingTraits")),!1)}async unprepareFormula(index,itemUUID){const formula=this.preparedFormulaData[index];if(!(!formula||formula.itemUUID!==itemUUID))return this.preparedFormulaData.splice(index,1),__privateMethod(this,_updateRE,updateRE_fn).call(this)}async increaseFormulaQuantity(index,itemUUID){const formula=this.preparedFormulaData[index];if(!(!formula||formula.itemUUID!==itemUUID))return formula.quantity?formula.quantity+=1:formula.quantity=2,__privateMethod(this,_updateRE,updateRE_fn).call(this)}async decreaseFormulaQuantity(index,itemUUID){const formula=this.preparedFormulaData[index];if(!(!formula||formula.itemUUID!==itemUUID)){if(formula.quantity?formula.quantity-=1:formula.quantity=0,formula.quantity<=0){await this.unprepareFormula(index,itemUUID);return}return __privateMethod(this,_updateRE,updateRE_fn).call(this)}}async setFormulaQuantity(index,itemUUID,quantity){if(quantity<=0){await this.unprepareFormula(index,itemUUID);return}const formula=this.preparedFormulaData[index];if(!(!formula||formula.itemUUID!==itemUUID))return formula.quantity=quantity,__privateMethod(this,_updateRE,updateRE_fn).call(this)}async toggleFormulaExpended(index,itemUUID){const formula=this.preparedFormulaData[index];if(!(!formula||formula.itemUUID!==itemUUID))return formula.expended=!formula.expended,__privateMethod(this,_updateRE,updateRE_fn).call(this)}async toggleSignatureItem(itemUUID){const formula=this.preparedFormulaData.find(f=>f.itemUUID===itemUUID);if(formula)return formula.isSignatureItem=!formula.isSignatureItem,__privateMethod(this,_updateRE,updateRE_fn).call(this)}async updateFormulas(formulas){return this.preparedFormulaData=formulas,__privateMethod(this,_updateRE,updateRE_fn).call(this)}};_updateRE=new WeakSet,updateRE_fn=__name2(async function(){const rules=this.parentItem.toObject().system.rules,thisRule=rules.find(r=>r.key==="CraftingEntry"&&r.selector===this.selector);thisRule&&(thisRule.preparedFormulas=this.preparedFormulaData,await this.parentItem.update({"system.rules":rules}))},"#updateRE"),__name2(_CraftingEntry,"CraftingEntry");let CraftingEntry=_CraftingEntry;const _ElementalBlast=class{static{__name(this,"_ElementalBlast")}constructor(actor){if(__privateAdd(this,_prepareBlastConfigs),__privateAdd(this,_prepareBlastInfusion),__privateAdd(this,_getBlastConfig),__privateAdd(this,_createModifiedItem),__privateAdd(this,_strengthModToDamage),__publicField(this,"actor"),__publicField(this,"statistic"),__publicField(this,"item"),__publicField(this,"configs"),__publicField(this,"infusion"),!actor.isOfType("character"))throw ErrorPF2e("Must construct with a PC");this.actor=actor,this.statistic=this.actor.getStatistic("impulse"),this.item=this.actor.itemTypes.action.find(a=>a.slug==="elemental-blast")??null,this.infusion=__privateMethod(this,_prepareBlastInfusion,prepareBlastInfusion_fn).call(this),this.configs=__privateMethod(this,_prepareBlastConfigs,prepareBlastConfigs_fn).call(this)}get actionCost(){const cost=this.item?.flags.pf2e.rulesSelections.actionCost??1;if(cost!==1&&cost!==2)throw ErrorPF2e("Action cost must be 1 or 2");return cost}async attack(params){const{statistic,actionCost}=this;if(!(statistic&&this.item))throw ErrorPF2e("Unable to blast");if(!this.actor.rollOptions.all["self:effect:kinetic-aura"])throw ErrorPF2e("No kinetic gate");const{element,damageType}=params;if(!element)throw ErrorPF2e("No element provided");if(!objectHasKey(elementTraits,element))throw ErrorPF2e(`Unrecognized element: ${element}`);if(!damageType)throw ErrorPF2e("No damage type provided");if(!objectHasKey(CONFIG.PF2E.damageTypes,damageType))throw ErrorPF2e(`Unrecognized damage type: ${damageType}`);const blastConfig=__privateMethod(this,_getBlastConfig,getBlastConfig_fn).call(this,element,damageType),melee=!!(params.melee??=!0),item=__privateMethod(this,_createModifiedItem,createModifiedItem_fn).call(this,{config:blastConfig,damageType,melee});if(!item)return null;const thisToken=this.actor.getActiveTokens(!0,!1).shift()??null,targetToken=game.user.targets.first()??null;if(!params.melee&&thisToken&&targetToken&&thisToken.distanceTo(targetToken)>blastConfig.range.max)return ui.notifications.warn("PF2E.Action.Strike.OutOfRange",{localize:!0}),null;const actionSlug="elemental-blast",blastStatistic=statistic.extend({check:{domains:[`${actionSlug}-attack-roll`],modifiers:AttackTraitHelpers.createAttackModifiers({item})}}),label=await renderTemplate("systems/pf2e/templates/chat/action/header.hbs",{title:item.name,glyph:actionCost.toString(),subtitle:game.i18n.format("PF2E.ActionsCheck.x-attack-roll",{type:statistic.label})}),meleeOrRanged=params.melee?"melee":"ranged",mapIncreases=Math.clamped(params.mapIncreases??0,0,2)||0;return blastStatistic.roll({identifier:`${blastConfig.element}.${params.damageType}.${meleeOrRanged}.${actionCost}`,action:actionSlug,attackNumber:mapIncreases+1,target:targetToken?.actor??null,token:thisToken?.document??null,item,label,traits:item.system.traits.value,melee,damaging:!0,dc:{slug:"ac"},extraRollOptions:[`action:${actionSlug}`,`action:cost:${actionCost}`],...eventToRollParams(params.event)})}async damage(params){if(!this.statistic)return null;const melee=!!(params.melee??!0),blastConfig=__privateMethod(this,_getBlastConfig,getBlastConfig_fn).call(this,params.element,params.damageType);if(!blastConfig)return null;const item=__privateMethod(this,_createModifiedItem,createModifiedItem_fn).call(this,{config:blastConfig,damageType:params.damageType,melee});if(!item)return null;const outcome=params.outcome??"success",meleeOrRanged=melee?"melee":"ranged",actionCost=Math.clamped(Number(params.actionCost??this.actionCost),1,2)||1,actionSlug="elemental-blast",domains=["damage","attack-damage","impulse-damage",`${actionSlug}-damage`],targetToken=game.user.targets.first()??null,context=await this.actor.getDamageRollContext({viewOnly:params.getFormula??!1,statistic:this.statistic.check,item,target:{token:targetToken},domains,outcome,melee,checkContext:params.checkContext,options:new Set([`action:${actionSlug}`,`action:cost:${actionCost}`,meleeOrRanged,...item.traits])}),baseDamage={category:null,damageType:params.damageType,terms:[{dice:{number:1,faces:blastConfig.dieFaces},modifier:0}]},damageSynthetics=processDamageCategoryStacking([baseDamage],{modifiers:extractModifiers(this.actor.synthetics,domains,{test:context.options}),dice:extractDamageDice(this.actor.synthetics.damageDice,domains,{test:context.options}),test:context.options}),extraModifiers=compact([...damageSynthetics.modifiers,__privateMethod(this,_strengthModToDamage,strengthModToDamage_fn).call(this,item,domains)]),modifiers=new StatisticModifier("",extraModifiers).modifiers;applyDamageDiceOverrides([baseDamage],damageSynthetics.dice);const formulaData={dice:damageSynthetics.dice,modifiers,base:[baseDamage],ignoredResistances:[]},damageContext={type:"damage-roll",sourceType:"attack",self:context.self,target:context.target,outcome,options:context.options,domains,...eventToRollParams(params.event)},damageData=createDamageFormula(formulaData,outcome==="success"?DEGREE_OF_SUCCESS.SUCCESS:DEGREE_OF_SUCCESS.CRITICAL_SUCCESS),roll=new DamageRoll(damageData.formula);if(params.getFormula)return roll.formula;const damageTemplate={name:`${game.i18n.localize("PF2E.DamageRoll")}: ${item.name}`,traits:item.system.traits.value,materials:[],modifiers,damage:{roll,breakdown:damageData.breakdown}};return DamagePF2e.roll(damageTemplate,damageContext)}async setDamageType({element,damageType}){if(!this.configs.some(c=>c.element===element&&c.damageTypes.some(dt=>dt.value===damageType)))throw ErrorPF2e(`Damage type "${damageType}" not available for ${element}`);await this.item?.update({[`flags.pf2e.damageSelections.${element}`]:damageType})}};_blastConfigSchema=new WeakMap,_blastInfusionSchema=new WeakMap,_prepareBlastConfigs=new WeakSet,prepareBlastConfigs_fn=__name2(function(){const{item,statistic,actionCost,infusion}=this;if(!item||!statistic)return[];const{kineticist}=this.actor.flags.pf2e;if(!isObject(kineticist)||!("elementalBlast"in kineticist)||!isObject(kineticist.elementalBlast))return[];const schema=__privateGet(_ElementalBlast,_blastConfigSchema),damageTypeSelections=(()=>{const flag=item.flags.pf2e.damageSelections;return isObject(flag)?flag:{}})(),blasts=Object.values(kineticist.elementalBlast).filter(b=>isObject(b)&&"element"in b).map(b=>schema.clean(b)),validationFailures=blasts.flatMap(b=>schema.validate(b)??[]);for(const failure of validationFailures)throw failure.asError();const maps=(()=>{const domains=[...statistic.check.domains,"elemental-blast-attack-roll"],options=this.actor.getRollOptions(domains),modifier=statistic.check.mod,mapsFor=__name2(melee=>{const penalties=calculateMAPs(__privateMethod(this,_createModifiedItem,createModifiedItem_fn).call(this,{melee})??item,{domains,options});return{map1:game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(modifier+penalties.map1),penalty:penalties.map1}),map2:game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(modifier+penalties.map2),penalty:penalties.map2})}},"mapsFor");return{melee:mapsFor(!0),ranged:mapsFor(!1)}})();return blasts.map(blast=>{const damageTypes2=uniq(compact([blast.damageTypes,this.infusion?.damageTypes].flat())).map(dt=>({value:dt,label:game.i18n.localize(CONFIG.PF2E.damageTypes[dt]),icon:DAMAGE_TYPE_ICONS[dt]??"",selected:damageTypeSelections[blast.element]===dt})).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang)),firstDamageType=damageTypes2.at(0);firstDamageType&&!damageTypes2.some(dt=>dt.selected)&&(firstDamageType.selected=!0);const maxRange=infusion?.range?.max??blast.range,range=infusion?.range?.increment?{increment:infusion.range.increment,max:infusion.range.increment*6,label:game.i18n.format("PF2E.Action.Range.IncrementN",{n:infusion.range.increment})}:{increment:null,max:maxRange,label:game.i18n.format("PF2E.Action.Range.MaxN",{n:maxRange})};return{...blast,statistic,maps,item,actionCost,damageTypes:damageTypes2,range}})},"#prepareBlastConfigs"),_prepareBlastInfusion=new WeakSet,prepareBlastInfusion_fn=__name2(function(){const schema=__privateGet(_ElementalBlast,_blastInfusionSchema),flag=this.actor.flags.pf2e.kineticist,infusionData=isObject(flag)&&isObject(flag.elementalBlast)?flag.elementalBlast.infusion:null;return isObject(infusionData)?schema.clean(infusionData):null},"#prepareBlastInfusion"),_getBlastConfig=new WeakSet,getBlastConfig_fn=__name2(function(element,damageType){const config=this.configs.find(c=>c.element===element&&c.damageTypes.some(t=>t.value===damageType));if(!config)throw ErrorPF2e(`Elemental blast configuration of element ${element} and damage type ${damageType} not found.`);return config},"#getBlastConfig"),_createModifiedItem=new WeakSet,createModifiedItem_fn=__name2(function({melee,config,damageType}){const{item}=this;if(!item)return null;const traits=(()=>{const baseTraits=this.item?.system.traits.value??[],infusionTraits=melee?this.infusion?.traits.melee:this.infusion?.traits.ranged;return uniq(compact([baseTraits,infusionTraits,config?.element,damageType].flat()).filter(t=>t in CONFIG.PF2E.actionTraits)).sort()})(),clone=item.clone({system:{traits:{value:traits}}},{keepId:!0});return clone.range=melee?null:config?.range??null,clone},"#createModifiedItem"),_strengthModToDamage=new WeakSet,strengthModToDamage_fn=__name2(function(item,domains){if(!item.range)return null;const strengthModValue=this.actor.abilities.str.mod,{traits}=item,modifierValue=traits.has("thrown")?strengthModValue:traits.has("propulsive")?strengthModValue<0?strengthModValue:Math.floor(strengthModValue/2):null;return typeof modifierValue=="number"?new ModifierPF2e({slug:"str",label:CONFIG.PF2E.abilities.str,ability:"str",modifier:modifierValue,type:"ability",adjustments:extractModifierAdjustments(this.actor.synthetics.modifierAdjustments,domains,"str")}):null},"#strengthModToDamage"),__name2(_ElementalBlast,"ElementalBlast"),__privateAdd(_ElementalBlast,_blastConfigSchema,(()=>{const{fields:fields2}=foundry.data;return new fields2.SchemaField({element:new fields2.StringField({required:!0,choices:()=>CONFIG.PF2E.elementTraits,initial:void 0}),label:new fields2.StringField({required:!0,blank:!1,initial:void 0}),img:new fields2.FilePathField({required:!0,categories:["IMAGE"],nullable:!1,initial:"systems/pf2e/icons/default-icons/spell.svg"}),damageTypes:new fields2.ArrayField(new fields2.StringField({required:!0,choices:()=>CONFIG.PF2E.damageTypes,initial:void 0})),dieFaces:new fields2.NumberField({required:!0,nullable:!1,integer:!0,choices:[6,8],initial:void 0}),range:new fields2.NumberField({required:!0,nullable:!1,integer:!0,positive:!0,initial:void 0})})})()),__privateAdd(_ElementalBlast,_blastInfusionSchema,(()=>{const{fields:fields2}=foundry.data;return new fields2.SchemaField({damageTypes:new fields2.ArrayField(new fields2.StringField({required:!0,choices:()=>CONFIG.PF2E.damageTypes,initial:void 0})),range:new fields2.SchemaField({increment:new fields2.NumberField({required:!0,integer:!0,positive:!0,nullable:!1}),max:new fields2.NumberField({required:!0,integer:!0,positive:!0,nullable:!1})},{required:!1,nullable:!0,initial:null}),traits:new fields2.SchemaField({melee:new fields2.ArrayField(new fields2.StringField({required:!0,nullable:!1,choices:()=>CONFIG.PF2E.weaponTraits,initial:void 0})),ranged:new fields2.ArrayField(new fields2.StringField({required:!0,nullable:!1,choices:()=>CONFIG.PF2E.weaponTraits,initial:void 0}))})})})());let ElementalBlast=_ElementalBlast;const _PCSheetTabManager=class{static{__name(this,"_PCSheetTabManager")}constructor(actor,link){this.actor=actor,this.link=link,renderTemplate("systems/pf2e/templates/actors/character/manage-tabs.hbs").then(template=>{$(this.link).tooltipster({content:template,contentAsHTML:!0,delay:250,interactive:!0,theme:"crb-hover",title:game.i18n.localize("PF2E.TabManageTabsLabel"),trigger:"custom",triggerOpen:{click:!0},triggerClose:{originClick:!0,mouseleave:!0},functionReady:(_origin,helper)=>this.onReady(helper.tooltip),functionAfter:()=>this.onClose()})})}static initialize(actor,link){new this(actor,link)}onReady(tooltip){const tabVisibility=this.actor.flags.pf2e.sheetTabs,tabs=this.link.closest("nav")?.querySelectorAll("a.item[data-tab]")??[];for(const tab of Array.from(tabs)){const tabName=tab.dataset.tab??"",selector=`input[data-tab-name="${tabName}"]`;tooltip.querySelector(selector).checked=tabVisibility[tabName],tab.classList.contains("hidden")&&(tab.classList.remove("hidden"),tab.classList.add("to-hide"))}const checkboxes=Array.from(tooltip.querySelectorAll('input[type="checkbox"]'));for(const checkbox of checkboxes)this.handleOnChange(checkbox,checkboxes)}handleOnChange(checkbox,checkboxes){checkbox.addEventListener("change",async()=>{const nav=this.link.closest("nav"),tabName=checkbox?.dataset.tabName??"",tab=nav?.querySelector(`a.item[data-tab="${tabName}"]`);for(const c of checkboxes)c.readOnly=!0;checkbox.checked?(tab?.classList.remove("to-hide"),await this.actor.update({[`flags.pf2e.sheetTabs.-=${tabName}`]:null},{render:!1})):(tab?.classList.add("to-hide"),await this.actor.update({[`flags.pf2e.sheetTabs.${tabName}`]:!1},{render:!1}));for(const c of checkboxes)c.readOnly=!1})}onClose(){const tabs=Array.from(this.link.closest("nav")?.querySelectorAll("a.item[data-tab]")??[]);for(const tab of tabs)tab.classList.contains("to-hide")&&(tab.classList.remove("to-hide"),tab.classList.add("hidden"))}};__name2(_PCSheetTabManager,"PCSheetTabManager");let PCSheetTabManager=_PCSheetTabManager;const _CharacterSheetPF2e=class extends CreatureSheetPF2e{static{__name(this,"_CharacterSheetPF2e")}constructor(){super(...arguments),__privateAdd(this,_prepareAbilities),__privateAdd(this,_prepareCraftingEntries),__privateAdd(this,_getBlastData),__privateAdd(this,_activateBlastListeners),__privateAdd(this,_onClickBrowseFeats),__privateAdd(this,_onChangeAdjustStat),__privateAdd(this,_onChangeAdjustItemStat),__privateAdd(this,_onClickAdjustItemStat),__privateAdd(this,_getFeatSlotData),__privateAdd(this,_sortFormulas),__publicField(this,"actorConfigClass",CharacterConfig),__privateAdd(this,_knownFormulas,{}),__privateAdd(this,_formulaQuantities,{})}static get defaultOptions(){const options=super.defaultOptions;return options.classes=[...options.classes,"character"],options.width=750,options.height=800,options.scrollY.push(".tab.active .tab-content"),options.tabs=[{navSelector:".sheet-navigation",contentSelector:".sheet-content",initial:"character"},{navSelector:".actions-nav",contentSelector:".actions-panels",initial:"encounter"}],options}get template(){return`systems/pf2e/templates/actors/character/${this.actor.limited&&!game.user.isGM?"limited":"sheet"}.hbs`}async getData(options){const sheetData=await super.getData(options),{actor}=this;if(this.actor.limited){const tab=options?.tabs.find(t=>t.navSelector===".sheet-navigation");tab&&(tab.initial="biography")}sheetData.martialProficiencies={attacks:sortLabeledRecord(mapValues$1(sheetData.data.proficiencies.attacks,(data,key)=>{const groupMatch=/^weapon-group-([-\w]+)$/.exec(key),baseWeaponMatch=/^weapon-base-([-\w]+)$/.exec(key);if(objectHasKey(CONFIG.PF2E.weaponCategories,key)){const locKey=sluggify(key,{camel:"bactrian"});data.label=setHasElement(WEAPON_CATEGORIES,key)?`PF2E.Actor.Character.Proficiency.Attack.${locKey}`:CONFIG.PF2E.weaponCategories[key]}else if(Array.isArray(groupMatch)){const weaponGroup=groupMatch[1];data.label=CONFIG.PF2E.weaponGroups[weaponGroup]??weaponGroup}else if(Array.isArray(baseWeaponMatch)){const baseWeapon=baseWeaponMatch[1];data.label=CONFIG.PF2E.baseWeaponTypes[baseWeapon]??baseWeapon}else data.label??=key;const rank=data.rank??0;return data.value=createProficiencyModifier({actor,rank,domains:[]}).value,data})),defenses:sortLabeledRecord(mapValues$1(sheetData.data.proficiencies.defenses,(data,key)=>{if(key in CONFIG.PF2E.armorCategories){const locKey=sluggify(key,{camel:"bactrian"});data.label=`PF2E.Actor.Character.Proficiency.Defense.${locKey}`}const rank=data.rank??0;return data.value=createProficiencyModifier({actor,rank,domains:[]}).value,data}))};for(const key of["light-barding","heavy-barding"])sheetData.martialProficiencies.defenses[key]?.rank===0&&delete sheetData.martialProficiencies.defenses[key];sheetData.ancestry=actor.ancestry,sheetData.heritage=actor.heritage,sheetData.background=actor.background,sheetData.class=actor.class,sheetData.deity=actor.deity,sheetData.data.resources.heroPoints.hover=game.i18n.format(actor.heroPoints.value===1?"PF2E.HeroPointRatio.One":"PF2E.HeroPointRatio.Many",actor.heroPoints),sheetData.attributeBoostsAllocated=(()=>{const{build}=sheetData.data;if(build.attributes.manual||!isReallyPC(actor))return!0;const keyAttributeSelected=!sheetData.class||build.attributes.keyOptions.includes(sheetData.data.details.keyability.value),ancestryBoostsSelected=(sheetData.ancestry?.system.alternateAncestryBoosts?.length===2||Object.values(sheetData.ancestry?.system.boosts??{}).every(b=>b.value.length===0||!!b.selected))&&sheetData.ancestry?.system.voluntary?.boost!==null,backgroundBoostsSelected=Object.values(sheetData.background?.system.boosts??{}).every(b=>b.value.length===0||!!b.selected);return ancestryBoostsSelected&&backgroundBoostsSelected&&keyAttributeSelected&&[1,5,10,15,20].filter(l=>build.attributes.allowedBoosts[l]>build.attributes.boosts[l].length).length===0})();const allClassDCs=Object.values(sheetData.data.proficiencies.classDCs),classDCs=allClassDCs.filter(cdc=>cdc.rank>0||allClassDCs.length>1).map(classDC=>({...classDC,icon:this.getProficiencyIcon(classDC.rank),hover:CONFIG.PF2E.proficiencyLevels[classDC.rank],rankSlug:PROFICIENCY_RANKS[classDC.rank],rankName:game.i18n.format(`PF2E.ProficiencyLevel${classDC.rank}`)})).sort((a,b)=>a.primary?-1:b.primary?1:a.slug.localeCompare(b.slug)),primaryClassDC=sheetData.data.attributes.classDC?.slug??null;sheetData.classDCs={dcs:classDCs,primary:primaryClassDC,perDCDetails:classDCs.length>1||!primaryClassDC};const abpEnabled=game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(actor);sheetData.apexAttributeOptions=abpEnabled?[]:this.actor.itemTypes.equipment.flatMap(e=>e.system.apex?.selected===!1&&e.isInvested&&e.system.apex.attribute!==actor.system.build.attributes.apex?e.system.apex.attribute:[]),sheetData.magicTraditions=CONFIG.PF2E.magicTraditions,sheetData.preparationType=CONFIG.PF2E.preparationType,sheetData.data.attributes.perception.rankName=game.i18n.format(`PF2E.ProficiencyLevel${sheetData.data.attributes.perception.rank}`),sheetData.data.saves={fortitude:sheetData.data.saves.fortitude,reflex:sheetData.data.saves.reflex,will:sheetData.data.saves.will};for(const save of Object.values(sheetData.data.saves))save.rankName=game.i18n.format(`PF2E.ProficiencyLevel${save.rank}`);for(const save of Object.values(sheetData.data.saves))save.short=game.i18n.format(`PF2E.Saves${save.label}Short`);sheetData.data.details.keyability.singleOption=actor.class?.system.keyAbility.value.length===1,sheetData.hasStamina=game.settings.get("pf2e","staminaVariant"),sheetData.spellcastingEntries=await this.prepareSpellcasting(),sheetData.actions=__privateMethod(this,_prepareAbilities,prepareAbilities_fn).call(this),sheetData.feats=[...actor.feats,actor.feats.bonus];const craftingFormulas=await actor.getCraftingFormulas(),formulasByLevel=groupBy$1(craftingFormulas,f=>f.level),flags=actor.flags.pf2e,hasQuickAlchemy=!!(actor.rollOptions.all["feature:quick-alchemy"]||actor.rollOptions.all["feat:quick-alchemy"]);sheetData.crafting={noCost:flags.freeCrafting,hasQuickAlchemy,knownFormulas:formulasByLevel,entries:await __privateMethod(this,_prepareCraftingEntries,prepareCraftingEntries_fn).call(this,craftingFormulas)},__privateSet(this,_knownFormulas,Object.values(formulasByLevel).flat().reduce((result,entry)=>(entry.batchSize=__privateGet(this,_formulaQuantities)[entry.uuid]??entry.batchSize,result[entry.uuid]=entry,result),{})),sheetData.abpEnabled=AutomaticBonusProgression.isEnabled(actor),sheetData.data.skills=Object.fromEntries(Object.entries(sheetData.data.skills).sort(([_keyA,skillA],[_keyB,skillB])=>game.i18n.localize(skillA.label??"").localeCompare(game.i18n.localize(skillB.label??""),game.i18n.lang))),sheetData.tabVisibility=deepClone(actor.flags.pf2e.sheetTabs);const rollData=actor.getRollData(),biography=sheetData.biography=actor.system.details.biography,enrichPromises={appearance:TextEditor.enrichHTML(biography.appearance,{rollData,async:!0}),backstory:TextEditor.enrichHTML(biography.backstory,{rollData,async:!0}),campaignNotes:TextEditor.enrichHTML(biography.campaignNotes,{rollData,async:!0}),allies:TextEditor.enrichHTML(biography.allies,{rollData,async:!0}),enemies:TextEditor.enrichHTML(biography.enemies,{rollData,async:!0}),organizations:TextEditor.enrichHTML(biography.organizations,{rollData,async:!0})};await Promise.all(Object.values(enrichPromises));for(const[key,content]of Object.entries(enrichPromises))sheetData.enrichedContent[key]=await content;try{const action2=new ElementalBlast(this.actor),blastData=(await Promise.all(action2.configs.map(c=>__privateMethod(this,_getBlastData,getBlastData_fn).call(this,action2,c)))).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang));sheetData.elementalBlasts=blastData}catch{sheetData.elementalBlasts=[]}return sheetData}async prepareItems(sheetData){const actorData=sheetData.actor,lores=[];for(const itemData of sheetData.items)if(itemData.type==="lore"){itemData.system.icon=this.getProficiencyIcon((itemData.system.proficient||{}).value),itemData.system.hover=CONFIG.PF2E.proficiencyLevels[(itemData.system.proficient||{}).value];const rank=itemData.system.proficient?.value||0,proficiency=createProficiencyModifier({actor:this.actor,rank,domains:[]}).modifier,modifier=actorData.system.abilities.int.mod,itemBonus=Number((itemData.system.item||{}).value||0);itemData.system.itemBonus=itemBonus,itemData.system.value=modifier+proficiency+itemBonus,itemData.system.breakdown=`int modifier(${modifier}) + proficiency(${proficiency}) + item bonus(${itemBonus})`,lores.push(itemData)}actorData.pfsBoons=this.actor.pfsBoons,actorData.deityBoonsCurses=this.actor.deityBoonsCurses,actorData.lores=lores}prepareInventoryItem(item){const data=super.prepareInventoryItem(item);data.isInvestable=!item.isInContainer&&item.isIdentified&&item.isInvested!==null;const invested=this.actor.inventory.invested,canInvest=invested&&invested.value{this.toggleInitiativeLink()});const heroPointsPips=htmlQuery(html,"[data-action=adjust-hero-points]");heroPointsPips?.addEventListener("click",async()=>{const newValue=Math.min(this.actor.heroPoints.value+1,this.actor.heroPoints.max);await this.actor.update({"system.resources.heroPoints.value":newValue})}),heroPointsPips?.addEventListener("contextmenu",async event=>{event.preventDefault();const newValue=Math.max(this.actor.heroPoints.value-1,0);await this.actor.update({"system.resources.heroPoints.value":newValue})});for(const selectElem of htmlQueryAll(html,"select.adjust-stat-select"))selectElem.addEventListener("change",()=>__privateMethod(this,_onChangeAdjustStat,onChangeAdjustStat_fn).call(this,selectElem));$html.find(".adjust-item-stat").on("click contextmenu",event=>__privateMethod(this,_onClickAdjustItemStat,onClickAdjustItemStat_fn).call(this,event)),$html.find(".adjust-item-stat-select").on("change",event=>__privateMethod(this,_onChangeAdjustItemStat,onChangeAdjustItemStat_fn).call(this,event));{const title=$(".sheet-navigation .active").attr("title");title&&$html.find(".navigation-title").text(title)}$html.find(".sheet-navigation").on("mouseover",".item,.manage-tabs",event=>{const title=event.currentTarget.title;title&&$(event.currentTarget).parents(".sheet-navigation").find(".navigation-title").text(title)}),$html.find(".sheet-navigation").on("mouseout",".item,.manage-tabs",event=>{const parent=$(event.currentTarget).parents(".sheet-navigation"),title=parent.find(".item.active").attr("title");title&&parent.find(".navigation-title").text(title)}),$html.find(".open-compendium").on("click",event=>{if(event.currentTarget.dataset.compendium){const compendium=game.packs.get(event.currentTarget.dataset.compendium);compendium&&compendium.render(!0)}});const mainPanel=htmlQuery(html,".tab[data-tab=character]");if(mainPanel&&this.isEditable){new ContextMenu(mainPanel,".detail-item-control",[{name:"PF2E.EditItemTitle",icon:fontAwesomeIcon("edit").outerHTML,callback:target=>{const itemId=$(target).closest("[data-item-id]").attr("data-item-id");this.actor.items.get(itemId??"")?.sheet.render(!0,{focus:!0})}},{name:"PF2E.DeleteItemTitle",icon:fontAwesomeIcon("trash").outerHTML,callback:target=>{const row=htmlClosest(target[0],"[data-item-id]"),itemId=row?.dataset.itemId,item=this.actor.items.get(itemId??"");if(row&&item)this.deleteItem(row,item);else throw ErrorPF2e("Item not found")}}],{eventName:"click"});for(const link of htmlQueryAll(html,".crb-tag-selector"))link.addEventListener("click",()=>this.openTagSelector(link,{allowCustom:!1}));htmlQuery(mainPanel,"button[data-action=edit-attribute-boosts]")?.addEventListener("click",()=>{(Object.values(this.actor.apps).find(a=>a instanceof AttributeBuilder)??new AttributeBuilder(this.actor)).render(!0)});for(const link of htmlQueryAll(mainPanel,"a[data-action=apex-attribute]"))link.addEventListener("click",()=>{if(game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(this.actor))return;const attribute=htmlClosest(link,"[data-attribute]")?.dataset.attribute;if(setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute)){const apexItems=this.actor.itemTypes.equipment.filter(e=>e.system.apex),selection=apexItems.find(e=>e.isInvested&&e.system.apex?.attribute===attribute);this.actor.updateEmbeddedDocuments("Item",apexItems.map(e=>({_id:e.id,"system.apex.selected":e===selection})))}})}const actionsPanel=htmlQuery(html,".tab.actions");htmlQuery(actionsPanel,".toggle-unready-strikes")?.addEventListener("click",()=>{this.actor.setFlag("pf2e","showUnreadyStrikes",!this.actor.flags.pf2e.showUnreadyStrikes)});for(const strikeElem of htmlQueryAll(actionsPanel,".strikes-list li")){for(const tagElem of htmlQueryAll(strikeElem,".item-summary .item-properties.tags .tag"))tagElem.dataset.description&&$(tagElem).tooltipster({content:game.i18n.localize(tagElem.dataset.description),maxWidth:400,theme:"crb-hover"});const versatileToggleButtons=htmlQueryAll(strikeElem,"button[data-action=toggle-versatile]");for(const button of versatileToggleButtons)button.addEventListener("click",()=>{const weapon=this.getStrikeFromDOM(button)?.item,baseType=weapon?.system.damage.damageType??null,selection=button.classList.contains("selected")||button.value===baseType?null:button.value,selectionIsValid=objectHasKey(CONFIG.PF2E.damageTypes,selection)||selection===null;weapon&&selectionIsValid&&toggleWeaponTrait({trait:"versatile",weapon,selection})});const auxActionButtons=htmlQueryAll(strikeElem,"button[data-action=auxiliary-action]");for(const button of auxActionButtons){const modularSelect=htmlQuery(button,"select");button.addEventListener("click",()=>{const auxiliaryActionIndex=Number(button.dataset.auxiliaryActionIndex??NaN),strike=this.getStrikeFromDOM(button),selection=modularSelect?.value??null;strike?.auxiliaryActions?.at(auxiliaryActionIndex)?.execute({selection})});for(const eventType of["change","click","dragenter","input"])modularSelect?.addEventListener(eventType,event=>{event.stopImmediatePropagation()})}const meleeIcon=htmlQuery(strikeElem,".melee-icon");meleeIcon&&$(meleeIcon).tooltipster({content:game.i18n.localize("PF2E.Item.Weapon.MeleeUsage.Label"),position:"left",theme:"crb-hover"});const ammoSelect=htmlQuery(strikeElem,"select[data-action=link-ammo]");ammoSelect?.addEventListener("change",event=>{event.stopPropagation();const weapon=this.getStrikeFromDOM(ammoSelect)?.item,ammo=this.actor.items.get(ammoSelect.value);weapon?.update({system:{selectedAmmoId:ammo?.id??null}})})}for(const activeToggle of htmlQueryAll(actionsPanel,"[data-action=toggle-exploration]"))activeToggle.addEventListener("click",()=>{const actionId=htmlClosest(activeToggle,"[data-item-id]")?.dataset.itemId;if(!actionId)return;const exploration=this.actor.system.exploration.filter(id=>this.actor.items.has(id));exploration.findSplice(id=>id===actionId)||exploration.push(actionId),this.actor.update({"system.exploration":exploration})});htmlQuery(actionsPanel,"[data-action=clear-exploration]")?.addEventListener("click",()=>{this.actor.update({"system.exploration":[]})});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.actor.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.actor.addCustomModifier(stat,label,modifier,type)})}$html.find("i.fa-info-circle.small[title]").tooltipster({maxWidth:275,position:"right",theme:"crb-hover",contentAsHTML:!0}),__privateMethod(this,_activateBlastListeners,activateBlastListeners_fn).call(this,actionsPanel);{const tab=html.querySelector(".tab.proficiencies");tab?.querySelector("h3.attacks-defenses")?.querySelector("button[data-action=add-attack-proficiency]")?.addEventListener("click",event=>{ManageAttackProficiencies.add(this.actor,event)});const list=tab?.querySelector("ol.combat-list")??null,links=htmlQueryAll(list,"li.custom a[data-action=remove-attack-proficiency]");for(const link of links)link.addEventListener("click",event=>{ManageAttackProficiencies.remove(this.actor,event)})}$html.find(".hover").tooltipster({trigger:"click",arrow:!1,contentAsHTML:!0,debug:!1,interactive:!0,side:["right","bottom"],theme:"crb-hover",minWidth:120}),$html.find("a[data-action=rest]").tooltipster({theme:"crb-hover"}).on("click",event=>{game.pf2e.actions.restForTheNight({event,actors:[this.actor]})}),$html.find("a[data-action=perception-check]").tooltipster({theme:"crb-hover"});const castingPanel=htmlQuery(html,".tab[data-tab=spellcasting]"),focusPips=htmlQueryAll(castingPanel,".focus-pool");if(focusPips.length>0){const listener=__name2(event=>{const change=event.type==="click"?1:-1,points=this.actor.system.resources.focus.value+change;this.actor.update({"system.resources.focus.value":points})},"listener");for(const pips of focusPips)pips.addEventListener("click",listener),pips.addEventListener("contextmenu",listener)}const craftingTab=htmlQuery(html,".tab.crafting");for(const element of htmlQueryAll(craftingTab,"li.formula-item")){const quantity=htmlQuery(element,"input[data-action=enter-quantity]");quantity?.addEventListener("change",async()=>{const itemUUID=element.dataset.itemId??"",formula=__privateGet(this,_knownFormulas)[itemUUID],minBatchSize=formula.minimumBatchSize,newValue=Number(quantity.value)||minBatchSize;if(newValue<1)return;const entrySelector=htmlClosest(element,"li.crafting-entry")?.dataset.entrySelector;if(entrySelector){const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");const index=element.dataset.itemIndex;await craftingEntry.setFormulaQuantity(Number(index),itemUUID??"",newValue);return}__privateGet(this,_formulaQuantities)[formula.uuid]=Math.max(newValue,minBatchSize),this.render()});for(const button of htmlQueryAll(element,"[data-action=increase-quantity], [data-action=decrease-quantity]"))button.addEventListener("click",async()=>{if(!quantity)return;const itemUUID=element.dataset.itemId??"",formula=__privateGet(this,_knownFormulas)[itemUUID],minBatchSize=formula.minimumBatchSize,step2=button.dataset.action==="increase-quantity"?minBatchSize:-minBatchSize,newValue=(Number(quantity.value)||step2)+step2;if(newValue<1)return;const entrySelector=htmlClosest(element,"li.crafting-entry")?.dataset.entrySelector;if(entrySelector){const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");const index=element.dataset.itemIndex;await craftingEntry.setFormulaQuantity(Number(index),itemUUID??"",newValue);return}__privateGet(this,_formulaQuantities)[formula.uuid]=Math.max(newValue,minBatchSize),this.render()});const craftButton=htmlQuery(element,"a[data-action=craft-item]");craftButton?.addEventListener("click",async event=>{const{itemUuid,free,prepared}=craftButton.dataset,itemQuantity=Number(quantity?.value)||1,formula=__privateGet(this,_knownFormulas)[itemUuid??""];if(!formula)return;if(prepared==="true"){if(element.dataset.expendedState==="true"){ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.FormulaExpended"));return}const index=element.dataset.itemIndex,entrySelector=htmlClosest(craftButton,"li.crafting-entry")?.dataset.entrySelector;if(!itemUuid||!index||!entrySelector)return;const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");await craftingEntry.toggleFormulaExpended(Number(index),itemUuid)}if(this.actor.flags.pf2e.quickAlchemy){const reagentValue=this.actor.system.resources.crafting.infusedReagents.value-1;if(reagentValue<0){ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.MissingReagents"));return}return await this.actor.update({"system.resources.crafting.infusedReagents.value":reagentValue},{render:!1}),craftItem(formula.item,1,this.actor,!0)}if(this.actor.flags.pf2e.freeCrafting){const itemId=itemUuid?.split(".").pop()??"";return isSpellConsumable(itemId)&&formula.item.isOfType("consumable")?craftSpellConsumable(formula.item,itemQuantity,this.actor):craftItem(formula.item,itemQuantity,this.actor)}const difficultyClass={value:formula.dc,visible:!0,scope:"check"};craft({difficultyClass,item:formula.item,quantity:itemQuantity,actors:this.actor,event,free:free==="true"})}),htmlQuery(element,"a.formula-delete")?.addEventListener("click",async()=>{const itemUuid=element.dataset.itemId;if(!itemUuid)return;const name2=__privateGet(this,_knownFormulas)[itemUuid]?.name,content=`

${game.i18n.format("PF2E.CraftingTab.RemoveFormulaDialogQuestion",{name:name2})}

`,title=game.i18n.localize("PF2E.CraftingTab.RemoveFormulaDialogTitle");if(await Dialog.confirm({title,content})){const actorFormulas=this.actor.toObject().system.crafting?.formulas??[];actorFormulas.findSplice(f=>f.uuid===itemUuid),this.actor.update({"system.crafting.formulas":actorFormulas})}}),htmlQuery(element,"a.formula-unprepare")?.addEventListener("click",async()=>{const itemUuid=element.dataset.itemId,index=element.dataset.itemIndex,entrySelector=element.dataset.entrySelector;if(!itemUuid||!index||!entrySelector)return;const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");const name2=__privateGet(this,_knownFormulas)[itemUuid]?.name,content=`

${game.i18n.format("PF2E.CraftingTab.UnprepareFormulaDialogQuestion",{name:name2})}

`,title=game.i18n.localize("PF2E.CraftingTab.UnprepareFormulaDialogTitle");await Dialog.confirm({title,content})&&await craftingEntry.unprepareFormula(Number(index),itemUuid)})}const $craftingTab=$html.find(".tab.crafting"),$craftingOptions=$craftingTab.find(".crafting-options input:checkbox");$craftingOptions.on("click",async event=>{const flags=[];$craftingOptions.each((_index,element)=>{element!==event.target&&flags.push($(element).attr("flag"))}),flags.forEach(async flag=>{await this.actor.setFlag("pf2e",flag,!1)})}),$craftingTab.find("a[data-action=quick-add]").on("click",async event=>{const{itemUuid}=event.currentTarget.dataset,formula=(await this.actor.getCraftingFormulas()).find(f=>f.uuid===itemUuid);if(!formula)return;const entries=(await this.actor.getCraftingEntries()).filter(e=>!!e.selector&&e.checkEntryRequirements(formula,{warn:!1}));for(const entry of entries)await entry.prepareFormula(formula);entries.length===0&&ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.NoEligibleEntry"))});const $formulas=$craftingTab.find(".craftingEntry-list");$formulas.find(".toggle-formula-expended").on("click",async event=>{const $target=$(event.currentTarget),itemUUID=$target.closest("li.formula-item").attr("data-item-id"),index=$target.closest("li.formula-item").attr("data-item-index"),entrySelector=$target.closest("li.crafting-entry").attr("data-entry-selector");if(!itemUUID||!index||!entrySelector)return;const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");await craftingEntry.toggleFormulaExpended(Number(index),itemUUID)}),$formulas.find(".toggle-signature-item").on("click",async event=>{const $target=$(event.currentTarget),itemUUID=$target.closest("li.formula-item").attr("data-item-id"),entrySelector=$target.closest("li.crafting-entry").attr("data-entry-selector");if(!itemUUID||!entrySelector)return;const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");await craftingEntry.toggleSignatureItem(itemUUID)}),$formulas.find(".infused-reagents").on("change",event=>{const change=Number($(event.target).val()),infusedReagents=this.actor.system.resources.crafting.infusedReagents,value=Math.clamped(change,0,infusedReagents?.max??0);this.actor.update({"system.resources.crafting.infusedReagents.value":value})}),$formulas.find(".daily-crafting").on("click",async()=>await this.actor.performDailyCrafting());for(const spellcastingCollectionEl of htmlQueryAll(html,".spellcasting-entry[data-item-id]")){const entry=this.actor.spellcasting.get(spellcastingCollectionEl.dataset.itemId??"");htmlQuery(spellcastingCollectionEl,"[data-action=spell-attack]")?.addEventListener("click",event=>{entry?.statistic?.check.roll(eventToRollParams(event))})}PCSheetTabManager.initialize(this.actor,$html.find("a[data-action=manage-tabs]")[0]);for(const link of htmlQueryAll(html,"[data-action=browse-feats]"))link.addEventListener("click",()=>__privateMethod(this,_onClickBrowseFeats,onClickBrowseFeats_fn).call(this,link));htmlQuery(html,".tab[data-tab=biography]")?.addEventListener("click",event=>{const section=htmlClosest(event.target,"a[data-action=toggle-bio-visibility")?.dataset.section;if(tupleHasValue(["appearance","backstory","personality","campaign"],section)){event.stopPropagation();const{biography}=this.actor.system.details,path=`system.details.biography.visibility.${section}`;this.actor.update({[path]:!biography.visibility[section]})}})}activateInventoryListeners(panel){super.activateInventoryListeners(panel),(this.isEditable?htmlQuery(panel,".inventory-pane"):null)?.addEventListener("click",event=>{const link=htmlClosest(event.target,"a[data-action=toggle-invested]"),itemId=htmlClosest(link,".item")?.dataset.itemId;itemId&&this.actor.toggleInvested(itemId)})}toggleInitiativeLink(link){if(link??=htmlQuery(this.element.get(0),"aside a[data-action=roll-initiative]"),!link)return;const alreadyRolled=game.combat&&typeof game.combat.combatants.find(c=>c.actor===this.actor)?.initiative=="number";if(!!(this.isEditable&&game.combat&&!alreadyRolled))link.classList.remove("disabled"),link.removeAttribute("title");else{link.classList.add("disabled");const reason=game.combat?alreadyRolled?"AlreadyRolled":null:"NoActiveEncounter";reason&&(link.title=game.i18n.format(`PF2E.Encounter.${reason}`,{actor:this.actor.name}))}}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("feat")){const slotData=__privateMethod(this,_getFeatSlotData,getFeatSlotData_fn).call(this,event);return this.actor.feats.insertFeat(item,slotData)}return super._onDropItem(event,data)}async _onDrop(event){const dataString=event.dataTransfer?.getData("text/plain"),dropData=(()=>{try{return JSON.parse(dataString??"")}catch{return null}})();if(dropData)if(isObject(dropData.pf2e)&&dropData.pf2e.type==="CraftingFormula"){const dropEntrySelector=typeof dropData.entrySelector=="string"?dropData.entrySelector:null;if(!dropEntrySelector){const containerEl=htmlClosest(event.target,".item-container");if(containerEl?.dataset.containerType==="craftingEntry"){const entrySelector=containerEl.dataset.entrySelector??"",craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)return;const craftingFormulas=await this.actor.getCraftingFormulas(),uuid2=dropData.pf2e.itemUuid,formula=craftingFormulas.find(f=>f.uuid===uuid2);formula&&craftingEntry.prepareFormula(formula);return}}const uuid=dropData.pf2e.itemUuid;if(typeof uuid=="string"){const formula=__privateGet(this,_knownFormulas)[uuid];if(formula){const targetUuid=htmlClosest(event.target,"li.formula-item")?.dataset.itemId??"";return __privateMethod(this,_sortFormulas,sortFormulas_fn).call(this,formula,targetUuid,dropEntrySelector)}}}else return super._onDrop(event)}async _onSortItem(event,itemSource){const item=this.actor.items.get(itemSource._id);if(item?.isOfType("feat")){const featSlot=__privateMethod(this,_getFeatSlotData,getFeatSlotData_fn).call(this,event);if(featSlot){const group=this.actor.feats.get(featSlot.groupId)??null,resorting=item.group===group&&!group?.slotted;if(group?.slotted&&!featSlot.slotId)return[];if(!resorting)return this.actor.feats.insertFeat(item,featSlot)}}return super._onSortItem(event,itemSource)}openTab(name2){["encounter","exploration","downtime"].includes(name2)?(super.openTab("actions"),this._tabs[1].activate(name2)):super.openTab(name2)}};_knownFormulas=new WeakMap,_formulaQuantities=new WeakMap,_prepareAbilities=new WeakSet,prepareAbilities_fn=__name2(function(){const{actor}=this,result={encounter:{action:{label:game.i18n.localize("PF2E.ActionsActionsHeader"),actions:[]},reaction:{label:game.i18n.localize("PF2E.ActionsReactionsHeader"),actions:[]},free:{label:game.i18n.localize("PF2E.ActionsFreeActionsHeader"),actions:[]}},exploration:{active:[],other:[]},downtime:[]};for(const item of actor.items){if(!item.isOfType("action")&&!(item.isOfType("feat")&&item.actionCost)||item.slug==="elemental-blast"&&this.actor.flags.pf2e.kineticist)continue;const 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})(),traits=item.system.traits.value,traitDescriptions2=item.isOfType("feat")?CONFIG.PF2E.featTraits:CONFIG.PF2E.actionTraits,action2={...pick$1(item,["id","name","actionCost","frequency"]),img,glyph:getActionGlyph(item.actionCost),traits:createSheetTags(traitDescriptions2,traits),feat:item.isOfType("feat")?item:null,hasEffect:!!item.system.selfEffect};if(traits.includes("exploration")){const active=actor.system.exploration.includes(item.id);action2.exploration={active},(active?result.exploration.active:result.exploration.other).push(action2)}else traits.includes("downtime")?result.downtime.push(action2):result.encounter[item.actionCost?.type??"free"]?.actions.push(action2)}for(const list of["action","reaction","free"])result.encounter[list].actions.sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang));return result.exploration.active.sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang)),result.exploration.other.sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang)),result.downtime.sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang)),result},"#prepareAbilities"),_prepareCraftingEntries=new WeakSet,prepareCraftingEntries_fn=__name2(async function(formulas){const craftingEntries={dailyCrafting:!1,other:[],alchemical:{entries:[],totalReagentCost:0,infusedReagents:this.actor.system.resources.crafting.infusedReagents}};for(const entry of await this.actor.getCraftingEntries(formulas))entry.isAlchemical?(craftingEntries.alchemical.entries.push(entry),craftingEntries.alchemical.totalReagentCost+=entry.reagentCost||0,craftingEntries.dailyCrafting=!0):(craftingEntries.other.push(entry),entry.isDailyPrep&&(craftingEntries.dailyCrafting=!0));return craftingEntries},"#prepareCraftingEntries"),_getBlastData=new WeakSet,getBlastData_fn=__name2(async function(blast,config){const damageType=config.damageTypes.find(dt=>dt.selected)?.value??"untyped",formulaFor=__name2((outcome,melee=!0)=>blast.damage({element:config.element,damageType,melee,outcome,getFormula:!0}),"formulaFor");return{...config,damageType,formula:{melee:{damage:await formulaFor("success"),critical:await formulaFor("criticalSuccess")},ranged:{damage:await formulaFor("success",!1),critical:await formulaFor("criticalSuccess",!1)}}}},"#getBlastData"),_activateBlastListeners=new WeakSet,activateBlastListeners_fn=__name2(function(panel){const blastList=htmlQuery(panel,"ol.elemental-blasts"),{elementTraits:elementTraits2,damageTypes:damageTypes2}=CONFIG.PF2E,selectors=["roll-attack","roll-damage","set-damage-type"].map(s=>`button[data-action=${s}]`).join(",");blastList?.addEventListener("click",async event=>{const button=htmlClosest(event.target,selectors),blastRow=htmlClosest(button,"li");if(!(button&&blastRow))return;event.stopPropagation();const blast=new ElementalBlast(this.actor),{element}=blastRow.dataset,damageType=button.value||blastRow.dataset.damageType;if(!objectHasKey(elementTraits2,element))throw ErrorPF2e("Unexpected error retrieve element");if(!objectHasKey(damageTypes2,damageType))throw ErrorPF2e("Unexpected error retrieving damage type");const melee=button.dataset.melee==="true";switch(button.dataset.action){case"roll-attack":{const mapIncreases=Math.clamped(Number(button.dataset.mapIncreases)||0,0,2);await blast.attack({mapIncreases,element,damageType,melee,event});break}case"roll-damage":{const outcome=button.dataset.outcome==="success"?"success":"criticalSuccess";await blast.damage({element,damageType,melee,outcome,event});break}case"set-damage-type":blast.setDamageType({element,damageType})}});for(const damageButton of htmlQueryAll(blastList,"button[data-action=roll-damage]")){const formula=damageButton.dataset.formula??"";$(damageButton).tooltipster({position:"top",theme:"crb-hover",content:formula})}},"#activateBlastListeners"),_onClickBrowseFeats=new WeakSet,onClickBrowseFeats_fn=__name2(async function(element){const maxLevel=Number(element.dataset.level)||this.actor.level,checkboxesFilterCodes=(element.dataset.filter??"").split(",").filter(s=>!!s).map(s=>s.trim()),featTab=game.pf2e.compendiumBrowser.tabs.feat,filter2=await featTab.getFilterData(),level=filter2.sliders.level;level.values.max=Math.min(maxLevel,level.values.upperLimit),level.isExpanded=level.values.max!==level.values.upperLimit;const{category}=filter2.checkboxes,{traits}=filter2.multiselects;for(const filterCode of checkboxesFilterCodes){const[filterType,...rest]=filterCode.split("-"),value=rest.join("-");if(!(filterType&&value))throw ErrorPF2e(`Invalid filter value for opening the compendium browser: "${filterCode}"`);if(filterType==="category"&&value in category.options)category.isExpanded=!0,category.options[value].selected=!0,category.selected.push(value);else if(filterType==="traits"){const trait=traits.options.find(t=>t.value===value);trait&&traits.selected.push(deepClone(trait))}else filterType==="conjunction"&&(value==="and"||value==="or")&&(filter2.multiselects.traits.conjunction=value)}return featTab.open(filter2)},"#onClickBrowseFeats"),_onChangeAdjustStat=new WeakSet,onChangeAdjustStat_fn=__name2(function(selectElem){const propertyKey=selectElem.dataset.property??"",currentValue=getProperty(this.actor,propertyKey),selectedValue=Number(selectElem.value);if(typeof currentValue!="number"||Number.isNaN(selectedValue))throw ErrorPF2e("Actor property not found");const newValue=Math.clamped(selectedValue,0,4),clone=this.actor.clone({[propertyKey]:newValue},{keepId:!0});newValue!==getProperty(clone,propertyKey)&&(ui.notifications.warn("PF2E.ErrorMessage.MinimumProfLevelSetByFeatures",{localize:!0}),selectElem.value=currentValue.toString())},"#onChangeAdjustStat"),_onChangeAdjustItemStat=new WeakSet,onChangeAdjustItemStat_fn=__name2(async function(event){const $select=$(event.delegateTarget),propertyKey=$select.attr("data-item-property")??"",selectedValue=Number($select.val()),itemId=$select.closest(".item").attr("data-item-id")??"",item=this.actor.items.get(itemId);if(!item)throw ErrorPF2e("Item not found");const newValue=(()=>{if(item.isOfType("spellcastingEntry"))return{"system.proficiency.value":()=>Math.clamped(selectedValue,0,4)}[propertyKey]?.();if(item.isOfType("lore"))return Math.clamped(selectedValue,0,4);throw ErrorPF2e("Item not recognized")})();typeof newValue=="number"&&await item.update({[propertyKey]:newValue}),newValue!==getProperty(item,propertyKey)&&ui.notifications.warn(game.i18n.localize("PF2E.ErrorMessage.MinimumProfLevelSetByFeatures"))},"#onChangeAdjustItemStat"),_onClickAdjustItemStat=new WeakSet,onClickAdjustItemStat_fn=__name2(async function(event){const $button=$(event.delegateTarget),itemId=$button.closest(".item").attr("data-item-id")??"",item=this.actor.items.get(itemId);if(!item)throw ErrorPF2e("Item not found");const propertyKey=$button.attr("data-item-property")??"",change=event.type==="click"?1:-1,newValue=(()=>{if(item.isOfType("spellcastingEntry")){const proficiencyRank=item.system.proficiency.value;return{"system.proficiency.value":()=>Math.clamped(proficiencyRank+change,0,4)}[propertyKey]?.()}else if(item.isOfType("lore")){const currentRank=item.system.proficient.value;return Math.clamped(currentRank+change,0,4)}else throw ErrorPF2e("Item not recognized")})();typeof newValue=="number"&&await item.update({[propertyKey]:newValue})},"#onClickAdjustItemStat"),_getFeatSlotData=new WeakSet,getFeatSlotData_fn=__name2(function(event){const groupId=htmlClosest(event.target,"[data-group-id]")?.dataset.groupId,slotId=htmlClosest(event.target,"[data-slot-id]")?.dataset.slotId||null;return groupId?{groupId,slotId}:null},"#getFeatSlotData"),_sortFormulas=new WeakSet,sortFormulas_fn=__name2(async function(sourceFormula,targetUuid,entrySelector){if(!UUIDUtils.isItemUUID(targetUuid)||sourceFormula.uuid===targetUuid)return;const sourceLevel=sourceFormula.level,targetLevel=__privateGet(this,_knownFormulas)[targetUuid].level;if(!entrySelector&&sourceLevel!==targetLevel)return;const performSort=__name2(async(formulas2,source2,target2,siblings)=>{const results=SortingHelpers.performIntegerSort(source2,{target:target2,siblings});if(results.length){for(const result of results){const formula=formulas2.find(f=>f===result.target);formula&&(formula.sort=result.update.sort)}entrySelector?await(await this.actor.getCraftingEntry(entrySelector))?.updateFormulas(formulas2):await this.actor.update({"system.crafting.formulas":formulas2})}},"performSort");if(entrySelector){const entry=await this.actor.getCraftingEntry(entrySelector);if(!entry)throw ErrorPF2e(`Crafting entry "${entrySelector}" doesn't exist!`);const formulas2=deepClone(entry.preparedFormulaData),source2=formulas2.find(f=>f.itemUUID===sourceFormula.uuid),target2=formulas2.find(f=>f.itemUUID===targetUuid);if(source2&&target2){const siblings=formulas2.filter(f=>f.itemUUID!==source2.itemUUID);return performSort(formulas2,source2,target2,siblings)}}const formulas=this.actor.toObject().system.crafting?.formulas??[],source=formulas.find(f=>f.uuid===sourceFormula.uuid),target=formulas.find(f=>f.uuid===targetUuid);if(source&&target){const siblings=formulas.filter(f=>f.uuid!==source.uuid);return performSort(formulas,source,target,siblings)}},"#sortFormulas"),__name2(_CharacterSheetPF2e,"CharacterSheetPF2e");let CharacterSheetPF2e=_CharacterSheetPF2e;const _AttackPopout=class extends CharacterSheetPF2e{static{__name(this,"_AttackPopout")}constructor(object,options){if(super(object,options),__publicField(this,"type","strike"),__privateAdd(this,_strikeItemId,""),__privateAdd(this,_strikeSlug,""),__privateAdd(this,_strike,void 0),__privateAdd(this,_elementTrait,void 0),__privateAdd(this,_blasts,[]),!options.type)throw ErrorPF2e('AttackPopout is missing mandatory "type" option.');if(options.type==="blast"){if(!options.elementTrait)throw ErrorPF2e('AttackPopout of type "blast" is missing mandatory "elementalTrait" option.');__privateSet(this,_elementTrait,options.elementTrait)}else{if(!options.strikeSlug)throw ErrorPF2e('AttackPopout of type "strike" is missing mandatory "strikeSlug" option.');if(!options.strikeItemId)throw ErrorPF2e('AttackPopout of type "strike" is missing mandatory "strikeItemId" option.');__privateSet(this,_strikeSlug,options.strikeSlug),__privateSet(this,_strikeItemId,options.strikeItemId)}this.type=options.type}get template(){return"systems/pf2e/templates/actors/character/attack-popout.hbs"}get id(){const id=super.id;return this.type==="strike"?`${id}-strike-${__privateGet(this,_strikeItemId)}-${__privateGet(this,_strikeSlug)}`:`${id}-blast-${__privateGet(this,_elementTrait)}`}static get defaultOptions(){return{...super.defaultOptions,submitOnChange:!1,submitOnClose:!1,width:480,height:"auto",resizable:!1}}get label(){return this.type==="blast"?__privateGet(this,_blasts).at(0)?.label??null:__privateGet(this,_strike)?.label??null}async getData(options){const base=await super.getData(options);return this.type==="blast"?(base.elementalBlasts=__privateSet(this,_blasts,base.elementalBlasts.filter(b=>b.element===__privateGet(this,_elementTrait))),base.data.actions=[],base.toggles=base.toggles.filter(t=>t.domain==="elemental-blast")):(base.elementalBlasts=[],__privateGet(this,_strikeSlug)&&__privateGet(this,_strikeItemId)&&__privateSet(this,_strike,base.data.actions.find(a=>a.item.id===__privateGet(this,_strikeItemId)&&a.slug===__privateGet(this,_strikeSlug)))),{...base,strike:__privateGet(this,_strike),strikeIndex:base.data.actions.findIndex(a=>a===__privateGet(this,_strike)),popoutType:this.type}}activateListeners($html){super.activateListeners($html);const html=$html[0],{label}=this;if(label){const title=htmlQuery(htmlClosest(html,"div.window-app"),"h4.window-title");title&&(title.innerHTML=game.i18n.localize(label))}}_getHeaderButtons(){return super._getHeaderButtons().filter(b=>b.label==="Close")}};_strikeItemId=new WeakMap,_strikeSlug=new WeakMap,_strike=new WeakMap,_elementTrait=new WeakMap,_blasts=new WeakMap,__name2(_AttackPopout,"AttackPopout");let AttackPopout=_AttackPopout;const _MacroPF2e=class extends Macro{static{__name(this,"_MacroPF2e")}get visible(){return this.permission>=CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER}};__name2(_MacroPF2e,"MacroPF2e");let MacroPF2e=_MacroPF2e;async function rollItemMacro(itemId){const speaker=ChatMessage.getSpeaker(),item=(canvas.tokens.get(speaker.token??"")?.actor??game.actors.get(speaker.actor??""))?.items?.get(itemId);if(!item){ui.notifications.warn(`Your controlled Actor does not have an item with ID ${itemId}`);return}return item.isOfType("action","feat")&&item.system.selfEffect?createSelfEffectMessage(item):item.toChat()}__name(rollItemMacro,"rollItemMacro"),__name2(rollItemMacro,"rollItemMacro");async function createActionMacro({actorUUID,actionIndex,elementTrait,slot}){const actor=resolveMacroActor(actorUUID);if(!actor?.isOfType("character","npc"))return;const data=(()=>{if(actor.isOfType("character")&&objectHasKey(CONFIG.PF2E.elementTraits,elementTrait)){const config=new ElementalBlast(actor).configs.find(c=>c.element===elementTrait);return config?{name:game.i18n.localize(config.label),command:`game.pf2e.rollActionMacro({ actorUUID: "${actorUUID}", type: "blast", elementTrait: "${elementTrait}" })`,img:config.img}:null}else if(actionIndex!==void 0){const action2=actor.system.actions[actionIndex];return action2?{name:`${game.i18n.localize("PF2E.WeaponStrikeLabel")}: ${action2.label}`,command:`game.pf2e.rollActionMacro({ actorUUID: "${actorUUID}", type: "strike", itemId: "${action2.item.id}", slug: "${action2.slug}" })`,img:action2.imageUrl}:null}return null})();if(!data)return;const actionMacro=game.macros.find(macro=>macro.name===data.name&¯o.command===data.command)??await MacroPF2e.create({command:data.command,name:data.name,type:"script",img:data.img,flags:{pf2e:{actionMacro:!0}}},{renderSheet:!1});game.user.assignHotbarMacro(actionMacro??null,slot)}__name(createActionMacro,"createActionMacro"),__name2(createActionMacro,"createActionMacro");async function rollActionMacro({actorUUID,itemId,elementTrait,slug,type}){const actor=resolveMacroActor(actorUUID);if(!actor?.isOfType("character","npc")){ui.notifications.error("PF2E.MacroActionNoActorError",{localize:!0});return}const strikes=actor.system.actions,strike=strikes.find(s=>s.item.id===itemId&&s.slug===slug)??strikes.find(s=>s.slug===slug);if(actor.isOfType("character")){const closedExisting=__name2(partialId=>{const appId=`AttackPopout-Actor-${actor.id}-${partialId}`,existing=Object.values(actor.apps).find(a=>a?.id===appId);return existing?(existing.close({force:!0}),!0):!1},"closedExisting");switch(type){case"blast":{if(closedExisting(`blast-${elementTrait}`))return;if(!actor.itemTypes.effect.find(e=>e.slug==="effect-kinetic-aura")){ui.notifications.error("PF2E.MacroActionNoActionError",{localize:!0});return}new AttackPopout(actor,{type,elementTrait}).render(!0);return}case"strike":{if(closedExisting(`strike-${itemId}-${slug}`))return;if(!strike){ui.notifications.error("PF2E.MacroActionNoActionError",{localize:!0});return}new AttackPopout(actor,{type,strikeItemId:itemId,strikeSlug:slug}).render(!0);return}}}if(!strike){ui.notifications.error("PF2E.MacroActionNoActionError",{localize:!0});return}const meleeOrRanged=strike.item.isMelee?"melee":"ranged",identifier=`${strike.item.id}.${strike.slug}.${meleeOrRanged}`,description=await TextEditor.enrichHTML(game.i18n.localize(strike.description),{async:!0}),templateData={actor,strike,identifier,description},content=await renderTemplate("systems/pf2e/templates/chat/strike-card.hbs",templateData),token=actor.token??actor.getActiveTokens(!0,!0).shift()??null,chatData={speaker:ChatMessagePF2e.getSpeaker({actor,token}),content,type:CONST.CHAT_MESSAGE_TYPES.OTHER},rollMode=game.settings.get("core","rollMode");return["gmroll","blindroll"].includes(rollMode)&&(chatData.whisper=ChatMessage.getWhisperRecipients("GM").map(u=>u.id)),rollMode==="blindroll"&&(chatData.blind=!0),ChatMessagePF2e.create(chatData)}__name(rollActionMacro,"rollActionMacro"),__name2(rollActionMacro,"rollActionMacro");async function createSkillMacro(skill,skillName,actorId,slot){const dictName=SKILL_DICTIONARY[skill]??skill,command=` +`,n.toHTML()]).slice(1)})}toHTML(){const element=createHTMLElement("li",{classes:["roll-note"],dataset:{itemId:this.rule?.item.id,visibility:this.visibility},innerHTML:game.i18n.localize(this.text)});if(element.childNodes.length===1&&element.firstChild instanceof HTMLElement&&(element.innerHTML=element.firstChild.innerHTML),this.title){const strong=createHTMLElement("strong",{innerHTML:game.i18n.localize(this.title)});element.prepend(strong," ")}return element}clone(){return new _RollNotePF2e2({...this.toObject(),rule:this.rule})}toObject(){return{selector:this.selector,title:this.title,text:this.text,predicate:this.predicate.toObject(),outcome:this.outcome,visibility:this.visibility}}};__name2(_RollNotePF2e,"RollNotePF2e");let RollNotePF2e=_RollNotePF2e;function normalizeActionChangeData(document2,changed){if(changed.system&&("actionType"in changed.system||"actions"in changed.system)){const actionType=changed.system?.actionType?.value??document2.system.actionType.value,actionCount=Number(changed.system?.actions?.value??document2.system.actions.value);changed.system=mergeObject(changed.system,{actionType:{value:actionType},actions:{value:actionType!=="action"?null:Math.clamped(actionCount,1,3)}})}}__name(normalizeActionChangeData,"normalizeActionChangeData"),__name2(normalizeActionChangeData,"normalizeActionChangeData");function activateActionSheetListeners(item,html){htmlQuery(html,"a[data-action=frequency-add]")?.addEventListener("click",()=>{const frequency={max:1,per:"day"};item.update({system:{frequency}})}),htmlQuery(html,"a[data-action=frequency-delete]")?.addEventListener("click",()=>{item.update({"system.-=frequency":null})}),item.isOfType("action","feat")&&htmlQuery(html,"a[data-action=delete-effect]")?.addEventListener("click",()=>{item._source.system.selfEffect&&item.update({"system.-=selfEffect":null})})}__name(activateActionSheetListeners,"activateActionSheetListeners"),__name2(activateActionSheetListeners,"activateActionSheetListeners");function createSelfEffectSheetData(data){if(!data)return null;const indexEntry=fromUuidSync(data.uuid);indexEntry?.name&&isImageFilePath(indexEntry.img)&&(data.name=indexEntry.name,data.img=indexEntry.img);const parsedUUID=foundry.utils.parseUuid(data.uuid),linkData={id:parsedUUID.documentId??null,type:parsedUUID.documentType??null,pack:parsedUUID.collection instanceof CompendiumCollection?parsedUUID.collection.metadata.id:null};return{...data,...linkData}}__name(createSelfEffectSheetData,"createSelfEffectSheetData"),__name2(createSelfEffectSheetData,"createSelfEffectSheetData");async function handleSelfEffectDrop(sheet,event){if(!sheet.isEditable||sheet.item.system.actionType.value==="passive")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))throw ErrorPF2e("Invalid item drop");await sheet.item.update({"system.selfEffect":{uuid:item.uuid,name:item.name}})}__name(handleSelfEffectDrop,"handleSelfEffectDrop"),__name2(handleSelfEffectDrop,"handleSelfEffectDrop");function createActionRangeLabel(range){if(!range?.max)return null;const[key,value]=range.increment?["PF2E.Action.Range.IncrementN",range.increment]:["PF2E.Action.Range.MaxN",range.max];return game.i18n.format(key,{n:value})}__name(createActionRangeLabel,"createActionRangeLabel"),__name2(createActionRangeLabel,"createActionRangeLabel");var LightLevels=(LightLevels2=>(LightLevels2[LightLevels2.DARKNESS=.25]="DARKNESS",LightLevels2[LightLevels2.BRIGHT_LIGHT=.75]="BRIGHT_LIGHT",LightLevels2))(LightLevels||{});let auraCheckLock=Promise.resolve();const checkAuras=foundry.utils.debounce(async function(){if(!(canvas.ready&&this.isInFocus&&this.grid.type===CONST.GRID_TYPES.SQUARE))return;await auraCheckLock;const lock={release:()=>{}};auraCheckLock=new Promise(resolve=>{lock.release=resolve});try{const tokens=this.tokens.reduce((list,token)=>(token.isLinked&&list.some(t=>t.actor===token.actor)||list.push(token),list),[]);for(const token of tokens)await token.object?._animation;for(const aura of tokens.flatMap(t=>Array.from(t.auras.values())))await aura.notifyActors();const sceneActors=new Set(tokens.flatMap(t=>t.actor?.primaryUpdater===game.user?t.actor:[]));for(const actor of sceneActors)actor.checkAreaEffects()}finally{lock.release()}},100),_ScenePF2e=class extends Scene{static{__name(this,"_ScenePF2e")}get rulesBasedVision(){return this.tokenVision?this.flags.pf2e.rulesBasedVision??game.settings.get("pf2e","automation.rulesBasedVision"):!1}get hearingRange(){return this.flags.pf2e.hearingRange}get darknessSyncedToTime(){return this.flags.pf2e.syncDarkness==="enabled"||this.flags.pf2e.syncDarkness==="default"&&game.settings.get("pf2e","worldClock.syncDarkness")}get lightLevel(){return 1-this.darkness}get isBright(){return this.lightLevel>=LightLevels.BRIGHT_LIGHT}get isDimlyLit(){return!this.isBright&&!this.isDark}get isDark(){return this.lightLevel<=LightLevels.DARKNESS}get hasHexGrid(){return![CONST.GRID_TYPES.GRIDLESS,CONST.GRID_TYPES.SQUARE].includes(this.grid.type)}get isInFocus(){const soleUserIsGM=game.user.isGM&&game.users.filter(u=>u.active).length===1;return this.active&&!soleUserIsGM||this.isView&&soleUserIsGM}prepareData(){super.prepareData(),Promise.resolve().then(()=>{this.checkAuras()})}prepareBaseData(){super.prepareBaseData(),this.flags.pf2e=mergeObject({hearingRange:null,rulesBasedVision:null,syncDarkness:"default"},this.flags.pf2e??{}),this.rulesBasedVision&&(this.globalLight=!0,this.globalLightThreshold=1-(LightLevels.DARKNESS+.001))}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId);const flagChanges=changed.flags?.pf2e??{};if(this.isView&&["rulesBasedVision","hearingRange"].some(k=>flagChanges[k]!==void 0)&&canvas.perception.update({initializeLighting:!0,initializeVision:!0}),changed.active&&canvas.scene===this)for(const token of canvas.tokens.placeables)token.auras.reset()}_onDeleteDescendantDocuments(parent,collection,documents,ids,options,userId){super._onDeleteDescendantDocuments(parent,collection,documents,ids,options,userId),documents.some(d=>d instanceof TokenDocumentPF2e&&!(d._source.light.dim||d._source.light.bright)&&d.actor?.synthetics.tokenOverrides.light)&&canvas.perception.update({initializeLighting:!0,initializeVision:!0})}};__name2(_ScenePF2e,"ScenePF2e");let ScenePF2e=_ScenePF2e;Object.defineProperty(ScenePF2e.prototype,"checkAuras",{configurable:!1,enumerable:!1,writable:!1,value:checkAuras});const _AmbientLightDocumentPF2e=class extends AmbientLightDocument{static{__name(this,"_AmbientLightDocumentPF2e")}get isDarkness(){return this.object?.source.isDarkness??!1}};__name2(_AmbientLightDocumentPF2e,"AmbientLightDocumentPF2e");let AmbientLightDocumentPF2e=_AmbientLightDocumentPF2e;const _MeasuredTemplateDocumentPF2e=class extends MeasuredTemplateDocument{static{__name(this,"_MeasuredTemplateDocumentPF2e")}get item(){const origin=this.flags.pf2e?.origin,uuid=origin?.uuid;if(!uuid)return null;const item=fromUuidSync(uuid);if(!(item instanceof ItemPF2e))return null;if(item?.isOfType("spell")){const overlayIds=origin?.variant?.overlays,castRank=origin?.castLevel??item.rank;return item.loadVariant({overlayIds,castLevel:castRank})??item}return item}get message(){return game.messages.get(this.flags.pf2e?.messageId??"")??null}_onCreate(data,options,userId){super._onCreate(data,options,userId),toggleClearTemplatesButton(this.message)}_onDelete(options,userId){super._onDelete(options,userId),toggleClearTemplatesButton(this.message)}};__name2(_MeasuredTemplateDocumentPF2e,"MeasuredTemplateDocumentPF2e");let MeasuredTemplateDocumentPF2e=_MeasuredTemplateDocumentPF2e;const _TileDocumentPF2e=class extends TileDocument{static{__name(this,"_TileDocumentPF2e")}};__name2(_TileDocumentPF2e,"TileDocumentPF2e");let TileDocumentPF2e=_TileDocumentPF2e;const _TokenConfigPF2e=class extends TokenConfig{static{__name(this,"_TokenConfigPF2e")}constructor(){super(...arguments),__privateAdd(this,_disableScale),__privateAdd(this,_reestablishPrototype),__privateAdd(this,_disableVisionInputs)}static get defaultOptions(){return{...super.defaultOptions,template:"systems/pf2e/templates/scene/token/sheet.hbs",sheetConfig:!1}}get dimensionsFromActorSize(){const actorSize=this.actor?.size??"med";return{tiny:.5,sm:1,med:1,lg:2,huge:3,grg:4}[actorSize]}async getData(options){return{...await super.getData(options),sizeLinkable:!!this.actor&&SIZE_LINKABLE_ACTOR_TYPES.has(this.actor.type),linkToSizeTitle:this.token.flags.pf2e.linkToActorSize?"Unlink":"Link",autoscaleTitle:this.token.flags.pf2e.autoscale?"Unlink":"Link"}}_getFilePickerOptions(event){return{...super._getFilePickerOptions(event),redirectToRoot:this.actor?[ActorPF2e.getDefaultArtwork(this.actor.toObject()).texture.src]:[]}}activateListeners($html){super.activateListeners($html);const html=$html[0];__privateMethod(this,_disableVisionInputs,disableVisionInputs_fn).call(this,html),this.token.flags.pf2e.autoscale&&__privateMethod(this,_disableScale,disableScale_fn).call(this,html),htmlQuery(html,"a[data-action=toggle-link-to-size]")?.addEventListener("click",async()=>{await this.token.update({"flags.pf2e.linkToActorSize":!this.token.flags.pf2e.linkToActorSize}),__privateMethod(this,_reestablishPrototype,reestablishPrototype_fn).call(this),await this.render()}),htmlQuery(html,"a[data-action=toggle-autoscale]")?.addEventListener("click",async()=>{await this.token.update({"flags.pf2e.autoscale":!this.token.flags.pf2e.autoscale}),__privateMethod(this,_reestablishPrototype,reestablishPrototype_fn).call(this),await this.render()})}_getSubmitData(updateData={}){const changes=updateData??{};return this.form.querySelector("input[name=scale]")?.disabled&&(changes.scale=Math.abs(this.token._source.texture.scaleX)),super._getSubmitData(changes)}async _updateObject(event,formData){if(formData["flags.pf2e.linkToActorSize"]===!0)if(this.actor?.isOfType("vehicle")){const{dimensions}=this.actor,width=Math.max(Math.round(dimensions.width/5),1),length=Math.max(Math.round(dimensions.length/5),1);formData.width=width,formData.height=length}else formData.width=formData.height=this.dimensionsFromActorSize;return super._updateObject(event,formData)}};_disableScale=new WeakSet,disableScale_fn=__name2(function(html){if(!game.settings.get("pf2e","tokens.autoscale"))return;const scale=html.querySelector(".form-group.scale");if(!scale)throw ErrorPF2e("Scale form group missing");scale.classList.add("children-disabled");const constrainedScale=String(this.actor?.size==="sm"?.8:1),rangeInput=scale.querySelector("input[type=range]");if(rangeInput){rangeInput.disabled=!0,rangeInput.value=constrainedScale;const rangeDisplayValue=scale.querySelector(".range-value");rangeDisplayValue&&(rangeDisplayValue.innerHTML=constrainedScale)}},"#disableScale"),_reestablishPrototype=new WeakSet,reestablishPrototype_fn=__name2(function(){if(this.isPrototype&&this.actor){const realPrototype=this.actor.prototypeToken;this.object=this.token=realPrototype}},"#reestablishPrototype"),_disableVisionInputs=new WeakSet,disableVisionInputs_fn=__name2(function(html){if(!(["character","familiar"].includes(this.actor?.type??"")&&(this.token.rulesBasedVision||this.isPrototype&&game.settings.get("pf2e","automation.rulesBasedVision"))))return;const sightInputNames=["angle","brightness","range","saturation","visionMode"].map(n=>`sight.${n}`),sightInputs=Array.from(html.querySelectorAll(sightInputNames.map(n=>`[name="${n}"]`).join(", "))),sightEnabledInput=html.querySelector('input[name="sight.enabled"]');if(!sightEnabledInput)throw ErrorPF2e("sight.enabled input not found");sightEnabledInput.addEventListener("change",()=>{for(const input of sightInputs)if(input.disabled=!sightEnabledInput.checked,input.type==="range")sightEnabledInput.checked?input.closest(".form-group")?.classList.remove("children-disabled"):input.closest(".form-group")?.classList.add("children-disabled");else if(input.name==="sight.color"){const colorInput=input.parentElement?.querySelector("input[type=color]");colorInput&&(colorInput.disabled=!sightEnabledInput.checked)}});for(const input of sightInputs)input.disabled=!0,input.type==="range"&&input.closest(".form-group")?.classList.add("children-disabled");html.querySelector("a.item[data-tab=detection]")?.classList.add("disabled");const managedBy=document.createElement("a");managedBy.className="managed-by-rbv",managedBy.append(fontAwesomeIcon("robot")),managedBy.title=game.i18n.localize("PF2E.SETTINGS.Automation.RulesBasedVision.ManagedBy").replace(/<\/?rbv>/g,"");for(const sightInput of sightInputs){const anchor=managedBy.cloneNode(!0);anchor.addEventListener("click",()=>{const menu=game.settings.menus.get("pf2e.automation");if(!menu)throw ErrorPF2e("Automation Settings application not found");new menu.type().render(!0)}),sightInput.closest(".form-group")?.querySelector("label")?.append(anchor)}},"#disableVisionInputs"),__name2(_TokenConfigPF2e,"TokenConfigPF2e");let TokenConfigPF2e=_TokenConfigPF2e;const _AmbientLightPF2e=class extends AmbientLight{static{__name(this,"_AmbientLightPF2e")}get isDarkness(){return this.source.isDarkness}};__name2(_AmbientLightPF2e,"AmbientLightPF2e");let AmbientLightPF2e=_AmbientLightPF2e;const _EffectsCanvasGroupPF2e=class extends EffectsCanvasGroup{static{__name(this,"_EffectsCanvasGroupPF2e")}get rulesBasedVision(){return game.settings.get("pf2e","automation.rulesBasedVision")&&canvas.ready&&!!canvas.scene?.tokenVision}};__name2(_EffectsCanvasGroupPF2e,"EffectsCanvasGroupPF2e");let EffectsCanvasGroupPF2e=_EffectsCanvasGroupPF2e;const _LightingLayerPF2e=class extends LightingLayer{static{__name(this,"_LightingLayerPF2e")}get lightingLevel(){return 1-canvas.darknessLevel}};__name2(_LightingLayerPF2e,"LightingLayerPF2e");let LightingLayerPF2e=_LightingLayerPF2e;const _TemplateLayerPF2e=class extends TemplateLayer{static{__name(this,"_TemplateLayerPF2e")}_onDragLeftMove(event){if(!canvas.scene||!canvas.dimensions)return;const interaction=event.interactionData,{destination,layerDragState,preview:template,origin}=interaction;if(!template||template.destroyed)return;if(template.parent===null&&this.preview.addChild(template),(layerDragState??0)>=1){const{x,y}=canvas.grid.getSnappedPosition(destination.x,destination.y,2);if(destination.x=x,destination.y=y,!template)return;const ray=new Ray(origin,destination),ratio=canvas.dimensions.size/canvas.dimensions.distance;if(["cone","circle"].includes(template.type)){const direction=ray.angle,snapAngle=Math.PI/(canvas.scene.hasHexGrid?6:4);template.document.direction=Math.toDegrees(Math.floor((direction+Math.PI*.125)/snapAngle)*snapAngle);const distance=Math.max(ray.distance/ratio,canvas.dimensions.distance);template.document.distance=Math.floor(distance/canvas.dimensions.distance)*canvas.dimensions.distance}else template.document.direction=Math.toDegrees(ray.angle),template.document.distance=ray.distance/ratio;template.refresh(),event.interactionData.layerDragState=2}}_onMouseWheel(event){const template=this.hover;if(!(template&&canvas.scene))return;const increment=event.shiftKey?15:5,coneMultiplier=template.type==="cone"?canvas.scene.hasHexGrid?2:3:1,snap=increment*coneMultiplier,delta=snap*Math.sign(event.deltaY);return template.rotate(template.document.direction+delta,snap)}};__name2(_TemplateLayerPF2e,"TemplateLayerPF2e");let TemplateLayerPF2e=_TemplateLayerPF2e;const _TokenLayerPF2e=class extends TokenLayer{static{__name(this,"_TokenLayerPF2e")}cycleStack(){const hovered=this.hover;if(!hovered)return!1;const stack=this.placeables.filter(t=>hovered.distanceTo(t)===0&&hovered.document.elevation===t.document.elevation).sort((a,b)=>a.mesh.sort-b.mesh.sort);if(stack.length<2)return!1;const first=stack.shift();stack.push(first);for(let sort=stack.length-1;sort>=0;sort--){const token=stack[sort];token.document.sort=sort,token.mesh.initialize({sort}),sort===stack.length-1&&(token.emitHoverIn(new PointerEvent("pointerenter")),this.hover=token)}return!0}};__name2(_TokenLayerPF2e,"TokenLayerPF2e");let TokenLayerPF2e=_TokenLayerPF2e;const _HearingSource=class extends SoundSource{static{__name(this,"_HearingSource")}_initialize(data){super._initialize(data),this.data.x=this.object.center.x,this.data.y=this.object.center.y,this.data.elevation=this.object.document.elevation,this.data.radius=canvas.dimensions?.maxR??1e3,this.data.walls=!0}};__name2(_HearingSource,"HearingSource");let HearingSource=_HearingSource;const _EffectAreaSquare=class extends PIXI.Rectangle{static{__name(this,"_EffectAreaSquare")}active;constructor(x,y,width,height,active=!0){super(x,y,width,height),this.active=active}get center(){return{x:this.x+this.width/2,y:this.y+this.height/2}}highlight(layer,{border,highlight}){this.x<0||this.y<0||(this.active?canvas.grid.grid.highlightGridPosition(layer,{x:this.x,y:this.y,border:border?.color,color:highlight.color,alpha:highlight.alpha}):(canvas.grid.grid.highlightGridPosition(layer,{x:this.x,y:this.y,border:0,color:0}),layer.beginFill(0,.5).moveTo(this.x,this.y).lineTo(this.x+this.width,this.y+this.height).endFill()))}};__name2(_EffectAreaSquare,"EffectAreaSquare");let EffectAreaSquare=_EffectAreaSquare;function getAreaSquares(data){if(!canvas.dimensions)return[];const squareWidth=canvas.dimensions.size,rowCount=Math.ceil(data.bounds.width/squareWidth),emptyVector=Array(rowCount-1).fill(null),genColumn=__name2(square=>emptyVector.reduce(colSquares=>{const squareAbove=colSquares.at(-1),squareBelow=new EffectAreaSquare(square.x,squareAbove.y+squareWidth,squareWidth,squareWidth);return colSquares.push(squareBelow),colSquares},[square]),"genColumn"),topLeftSquare=new EffectAreaSquare(data.bounds.x,data.bounds.y,squareWidth,squareWidth),collisionType=data.traits?.includes("visual")&&!data.traits.includes("auditory")?"sight":data.traits?.includes("auditory")&&!data.traits.includes("visual")?"sound":"move",tokenBounds=data.token.mechanicalBounds,tokenCenter=data.token.center,tokenCenters=[tokenCenter,...[{x:0,y:1},{x:1,y:0},{x:0,y:-1},{x:-1,y:0}].map(c=>({x:tokenCenter.x+c.x*Math.round(tokenBounds.width/8),y:tokenCenter.y+c.y*Math.round(tokenBounds.height/8)}))];return emptyVector.reduce(squares=>{const lastSquare=squares.at(-1).at(-1),column=genColumn(new EffectAreaSquare(lastSquare.x+squareWidth,topLeftSquare.y,squareWidth,squareWidth));return squares.push(column),squares},[genColumn(topLeftSquare)]).flat().filter(s=>measureDistanceCuboid(tokenBounds,s)<=data.radius).map(square=>(square.active=tokenCenters.some(c=>!CONFIG.Canvas.polygonBackends[collisionType].testCollision(c,square.center,{type:collisionType,mode:"any"})),square))}__name(getAreaSquares,"getAreaSquares"),__name2(getAreaSquares,"getAreaSquares");const _AuraRenderer=class extends PIXI.Graphics{static{__name(this,"_AuraRenderer")}constructor(params){super(),__privateAdd(this,_drawBorder),__privateAdd(this,_drawTexture),__privateAdd(this,_drawLabel),__publicField(this,"slug"),__publicField(this,"token"),__publicField(this,"radius"),__publicField(this,"radiusPixels"),__publicField(this,"traits"),__publicField(this,"appearance"),__publicField(this,"border",new PIXI.Graphics),__publicField(this,"texture",null),this.slug=params.slug,this.token=params.token,this.appearance=params.appearance,this.radius=params.radius,this.radiusPixels=.5*this.token.mechanicalBounds.width+this.radius/(canvas.dimensions?.distance??0)*canvas.grid.size,this.traits=params.traits,this.addChild(this.border)}get bounds(){const{token,radiusPixels}=this,bounds=token.mechanicalBounds;return new PIXI.Rectangle(bounds.x-(radiusPixels-bounds.width/2),bounds.y-(radiusPixels-bounds.width/2),radiusPixels*2,radiusPixels*2)}get highlightLayer(){return canvas.grid?.getHighlightLayer(this.token.highlightId)??null}get squares(){return getAreaSquares(this)}async draw(showBorder){const{mechanicalBounds}=this.token;return this.x=mechanicalBounds.width/2,this.y=mechanicalBounds.height/2,this.token.document.width<1&&(this.x+=mechanicalBounds.x-this.token.x,this.y+=mechanicalBounds.y-this.token.y),__privateMethod(this,_drawBorder,drawBorder_fn).call(this),this.border.visible=showBorder,__privateMethod(this,_drawTexture,drawTexture_fn).call(this)}highlight(){const{dimensions}=canvas;if(!dimensions)return;if(__privateMethod(this,_drawLabel,drawLabel_fn).call(this),!!(this.token.actor?.isOfType("familiar")?this.token.actor.master?.combatant?.encounter.active:this.token.combatant?.encounter.active)){const{highlightLayer}=this;if(!highlightLayer)return;for(const square of this.squares)square.highlight(highlightLayer,this.appearance)}}};_drawBorder=new WeakSet,drawBorder_fn=__name2(function(){const data=this.appearance.border;!data||this.border.geometry.graphicsData.length>0||this.border.lineStyle(_AuraRenderer.LINE_THICKNESS,data.color,data.alpha).drawCircle(0,0,this.radiusPixels)},"#drawBorder"),_drawTexture=new WeakSet,drawTexture_fn=__name2(async function(){const data=this.appearance.texture;if(!data||this.token.isPreview||this.texture)return;const maybeTexture=await loadTexture(data.src,{fallback:"icons/svg/hazard.svg"});if(this.texture=maybeTexture instanceof PIXI.Texture?maybeTexture:null,!this.texture)return;const globalVideo=isVideoFilePath(data.src)?game.video.getVideoSource(this.texture):null;if(globalVideo){this.texture.destroy(),this.texture=await game.video.cloneTexture(globalVideo);const video=game.video.getVideoSource(this.texture)??globalVideo;video.playbackRate=data.playbackRate;const offset=data.loop?Math.random()*video.duration:0;game.video.play(video,{volume:0,offset,loop:data.loop})}const radius=data.scale*this.radiusPixels,diameter=radius*2,scale={x:diameter/this.texture.width,y:diameter/this.texture.height},matrix=new PIXI.Matrix(scale.x,void 0,void 0,scale.y,radius,radius);this.beginTextureFill({texture:this.texture,alpha:data.alpha,matrix}).drawCircle(0,0,radius).endFill()},"#drawTexture"),_drawLabel=new WeakSet,drawLabel_fn=__name2(function(){const style=CONFIG.canvasTextStyle.clone(),gridSize=canvas.dimensions?.size??100;style.fontSize=Math.max(Math.round(gridSize*.36*12)/12,36),style.align="center";const bounds=this.token.mechanicalBounds,gridUnits=canvas.scene?.grid.units.trim()||game.system.gridUnits,label=[this.radius,gridUnits].join(""),text=new PreciseText(label,style),center={x:bounds.x+bounds.width/2,y:bounds.y+bounds.height/2},textOffset=Math.sqrt(style.fontSize);text.position.set(center.x+textOffset,center.y-this.radiusPixels-style.fontSize-textOffset),this.highlightLayer?.beginFill(0,.5).lineStyle(_AuraRenderer.LINE_THICKNESS,0).drawCircle(center.x,center.y-this.radiusPixels,6).endFill().addChild(text)},"#drawLabel"),__name2(_AuraRenderer,"AuraRenderer"),__publicField(_AuraRenderer,"LINE_THICKNESS",3);let AuraRenderer=_AuraRenderer;const _AuraRenderers=class extends Map{static{__name(this,"_AuraRenderers")}constructor(token){super(),__privateAdd(this,_showBordersHighlights),__publicField(this,"token"),this.token=token}get highlightId(){return this.token.highlightId}async reset(slugs){if(!slugs)this.clear();else for(const slug of slugs)this.delete(slug);if(!this.token.actor)return;const data=Array.from(this.token.document.auras.values()).filter(a=>slugs?.includes(a.slug)??!0);for(const datum of data){const renderer=new AuraRenderer({...datum,token:this.token});this.set(datum.slug,this.token.addChild(renderer))}return this.draw()}async draw(){if(this.size===0||(this.clearHighlights(),this.token.isAnimating))return;const showBordersHighlights=__privateGet(this,_showBordersHighlights,showBordersHighlights_get);for(const aura of this.values())await aura.draw(showBordersHighlights);if(showBordersHighlights&&(this.token.hover||this.token.layer.highlightObjects)){const{highlightId}=this;(canvas.grid.highlightLayers[highlightId]??canvas.grid.addHighlightLayer(highlightId)).clear();for(const aura of this.values())aura.highlight()}}delete(key){const aura=this.get(key);return aura?(aura.destroyed||aura.destroy(!0),this.token.removeChild(aura),super.delete(key)):!1}clear(){this.clearHighlights();for(const aura of this.values())aura.destroyed||aura.destroy(!0),this.token.removeChild(aura);return super.clear()}destroy(){this.clear()}clearHighlights(){canvas.grid.destroyHighlightLayer(this.highlightId)}};_showBordersHighlights=new WeakSet,showBordersHighlights_get=__name2(function(){const inEncounter=__name2(()=>!!(this.token.actor?.isOfType("familiar")?this.token.actor.master?.combatant?.encounter.active:this.token.combatant?.encounter.active),"inEncounter");return canvas.scene?.grid.type===CONST.GRID_TYPES.SQUARE&&canvas.scene.tokenVision&&canvas.scene.isInFocus&&(game.user.isGM||this.token.actor?.alliance==="party")&&(this.token.controlled||this.token.hover||this.token.layer.highlightObjects||inEncounter())},"#showBordersHighlights"),__name2(_AuraRenderers,"AuraRenderers");let AuraRenderers=_AuraRenderers;const _FlankingHighlightRenderer=class{static{__name(this,"_FlankingHighlightRenderer")}_layer;token;labelText;lineColor;constructor(token){this._layer=null,this.token=token,this.labelText=game.i18n.localize("PF2E.Token.Flanking"),this.lineColor=CONFIG.Canvas.dispositionColors.CONTROLLED}get layer(){return this._layer??this.addLayer()}get shouldRender(){return canvas.ready&&!!canvas.scene?.isInFocus&&this.tokenIsSelectedOrOwn&&this.tokenIsReady}get tokenIsSelectedOrOwn(){return this.token.controlled&&this.token.isOwner||!!this.token.actor&&this.token.actor?.id===game.user.character?.id}get tokenIsReady(){return!this.token.isPreview&&!this.token.isAnimating}draw(){this.clear(),canvas.tokens.highlightObjects&&game.user.targets.size&&this.shouldRender&&game.user.targets.forEach(target=>this.drawForTarget(target))}drawForTarget(target){const buddies=this.token.buddiesFlanking(target,{ignoreFlankable:!0});this.drawBuddyLines(buddies)}drawBuddyLines(buddies){buddies.forEach(b=>this.drawBuddyLine(b))}drawBuddyLine(buddy){const t=CONFIG.Canvas.objectBorderThickness,o=Math.round(t*1.5),c=Math.round(t*2);this.layer.lineStyle(o,0,.5).moveTo(this.token.center.x,this.token.center.y).lineTo(buddy.center.x,buddy.center.y),this.layer.lineStyle(t,this.lineColor,.5).moveTo(this.token.center.x,this.token.center.y).lineTo(buddy.center.x,buddy.center.y),this.layer.beginFill(this.lineColor).lineStyle(1,0).drawCircle(this.token.center.x,this.token.center.y,c),this.layer.beginFill(this.lineColor).lineStyle(1,0).drawCircle(buddy.center.x,buddy.center.y,c),this.drawLabel(buddy)}drawLabel(buddy){const mid_x=Math.round((this.token.center.x+buddy.center.x)/2),mid_y=Math.round((this.token.center.y+buddy.center.y)/2),vect_x=buddy.center.x-this.token.center.x,vect_y=buddy.center.y-this.token.center.y,perp_vect_x=vect_x<=-vect_x?-vect_y:vect_y,perp_vect_y=vect_x<=-vect_x?vect_x:-vect_x,offsetScale=20/Math.sqrt(perp_vect_x**2+perp_vect_y**2),perp_x=mid_x+Math.round(perp_vect_x*offsetScale),perp_y=mid_y+Math.round(perp_vect_y*offsetScale),style=CONFIG.canvasTextStyle.clone();style.fontSize=24,canvas.dimensions?.size&&canvas.dimensions.size>=200?style.fontSize=28:canvas.dimensions?.size&&canvas.dimensions.size<50&&(style.fontSize=20),style.fill=this.lineColor,style.stroke=0;const text=new PreciseText(this.labelText,style);text.anchor.set(.5,.5);let rotation=Math.atan2(vect_y,vect_x);rotation>Math.PI/2?rotation=rotation-Math.PI:rotation<-Math.PI/2&&(rotation=rotation+Math.PI),text.rotation=rotation,text.position.set(perp_x,perp_y),this.layer.addChild(text)}clear(){this._layer?.destroy({children:!0}),this._layer=null}destroy(){this.clear()}addLayer(){return this._layer=new PIXI.Graphics,this.token.layer.addChild(this._layer)}};__name2(_FlankingHighlightRenderer,"FlankingHighlightRenderer");let FlankingHighlightRenderer=_FlankingHighlightRenderer;const _TokenPF2e=class extends Token{static{__name(this,"_TokenPF2e")}auras;flankingHighlight;hearing;constructor(document2){super(document2),this.hearing=new HearingSource({object:this}),this.auras=new AuraRenderers(this),Object.defineProperty(this,"auras",{configurable:!1,writable:!1}),this.flankingHighlight=new FlankingHighlightRenderer(this),Object.defineProperty(this,"flankingHighlight",{configurable:!1,writable:!1})}get isVisible(){if(this.detectionFilter=null,this.document.hidden&&!game.user.isGM)return!1;if(!canvas.effects.visibility.tokenVision||this.controlled||canvas.effects.visionSources.get(this.sourceId)?.active)return!0;const tolerance=Math.floor(.35*Math.min(this.w,this.h));return canvas.effects.visibility.testVisibility(this.center,{tolerance,object:this})}get isAnimating(){return!!this._animation}get emitsDarkness(){return this.document.emitsDarkness}get hasLowLightVision(){return this.document.hasLowLightVision}get hasDarkvision(){return this.document.hasDarkvision}get linkToActorSize(){return this.document.linkToActorSize}get highlightId(){return`Token.${this.id}`}get mechanicalBounds(){const bounds=super.bounds;if(this.document.width<1){const position=canvas.grid.getTopLeft(bounds.x+bounds.width/2,bounds.y+bounds.height/2);return new PIXI.Rectangle(position[0],position[1],Math.max(canvas.grid.size,bounds.width),Math.max(canvas.grid.size,bounds.height))}return bounds}get sightRange(){return this.document.sight.range>=canvas.dimensions.maxR?canvas.dimensions.maxR:super.sightRange}isAdjacentTo(token){return this.distanceTo(token)===5}canFlank(flankee,context={}){if(this===flankee||!game.settings.get("pf2e","automation.flankingDetection"))return!1;const flankable=context.ignoreFlankable||flankee.actor?.attributes.flanking.flankable;if(!(this.actor?.attributes.flanking.canFlank&&flankable)||!this.actor.isOfType("character","npc")||!flankee.actor?.isOfType("creature")||this.actor.isAllyOf(flankee.actor))return!1;const reach=context.reach??this.actor.getReach({action:"attack"});return this.actor.canAttack&&reach>=this.distanceTo(flankee,{reach})}onOppositeSides(flankerA,flankerB,flankee){const{lineSegmentIntersects}=foundry.utils,[centerA,centerB]=[flankerA.center,flankerB.center],{bounds}=flankee,left=new Ray({x:bounds.left,y:bounds.top},{x:bounds.left,y:bounds.bottom}),right=new Ray({x:bounds.right,y:bounds.top},{x:bounds.right,y:bounds.bottom}),top=new Ray({x:bounds.left,y:bounds.top},{x:bounds.right,y:bounds.top}),bottom=new Ray({x:bounds.left,y:bounds.bottom},{x:bounds.right,y:bounds.bottom}),intersectsSide=__name2(side=>lineSegmentIntersects(centerA,centerB,side.A,side.B),"intersectsSide");return intersectsSide(left)&&intersectsSide(right)||intersectsSide(top)&&intersectsSide(bottom)}isFlanking(flankee,context={}){if(!(this.actor&&this.canFlank(flankee,context)))return!1;const{flanking}=this.actor.attributes,flankingBuddies=canvas.tokens.placeables.filter(t=>t!==this&&t.canFlank(flankee,pick$1(context,["ignoreFlankable"])));return flankingBuddies.length===0?!1:flanking.canGangUp.some(g=>typeof g=="number"&&g<=flankingBuddies.length)||this.isAdjacentTo(flankee)&&flanking.canGangUp.includes("animal-companion")&&flankingBuddies.some(b=>{if(!b.actor?.isOfType("character"))return!1;const traits=b.actor.traits;return traits.has("minion")&&!traits.has("construct")&&b.isAdjacentTo(flankee)})?!0:flankingBuddies.some(b=>this.onOppositeSides(this,b,flankee))}buddiesFlanking(flankee,context={}){return!this.actor||!this.canFlank(flankee,context)?[]:canvas.tokens.placeables.filter(t=>t!==this&&t.canFlank(flankee,pick$1(context,["ignoreFlankable"]))).filter(b=>this.onOppositeSides(this,b,flankee))}_refreshVisibility(){super._refreshVisibility(),this.auras.draw(),this.flankingHighlight.draw()}_getBorderColor(options){const isHovered=options?.hover??(this.hover||this.layer.highlightObjects),isControlled=this.controlled||!game.user.isGM&&this.isOwner,isFriendly=this.document.disposition===CONST.TOKEN_DISPOSITIONS.FRIENDLY;if(!isHovered||isControlled||isFriendly||!this.actor?.hasPlayerOwner)return super._getBorderColor();const colors=CONFIG.Canvas.dispositionColors;switch(this.document.disposition){case CONST.TOKEN_DISPOSITIONS.NEUTRAL:return colors.NEUTRAL;case CONST.TOKEN_DISPOSITIONS.HOSTILE:return colors.HOSTILE;case CONST.TOKEN_DISPOSITIONS.SECRET:return this.isOwner?colors.SECRET:null;default:return super._getBorderColor(options)}}_drawBar(number,bar,data){if(!canvas.dimensions)return;const actor=this.document.actor;if(!(data.attribute==="attributes.hp"&&actor?.attributes.hp))return super._drawBar(number,bar,data);const{value,max,temp}=actor.attributes.hp??{},healthPercent=Math.clamped(value,0,max)/max,black=0,color=Number(number?Color.fromRGB([.5*healthPercent,.7*healthPercent,.5+healthPercent/2]):Color.fromRGB([1-healthPercent/2,healthPercent,0]));let h=Math.max(canvas.dimensions.size/12,8);const bs=Math.clamped(h/8,1,2);this.document.height>=2&&(h*=1.6);const numBars=temp>0?2:1,barHeight=h/numBars;if(bar.clear(),bar.lineStyle(0).beginFill(black,.5).drawRoundedRect(0,0,this.w,h,3),bar.lineStyle(bs/2,black,1),temp>0){const tempWidth=Math.clamped(temp,0,max)/max*this.w-2*(bs-1);bar.beginFill(6737151,1).drawRoundedRect(0,0,tempWidth,barHeight,2)}const healthBarY=(numBars-1)*barHeight;bar.beginFill(color,1).drawRoundedRect(0,healthBarY,healthPercent*this.w,barHeight,2),bar.beginFill(black,0).lineStyle(bs,black,1).drawRoundedRect(0,0,this.w,h,3),bar.position.set(0,number===0?this.h-h:0)}async drawEffects(){if(await super.drawEffects(),await this._animation,this.auras.size===0)return this.auras.reset();const changedAndDeletedAuraSlugs=Array.from(this.auras.entries()).filter(([slug,aura])=>{const properties=["radius","appearance"],sceneData=pick$1(this.document.auras.get(slug)??{radius:null,appearance:null},properties),canvasData=pick$1(aura,properties);return sceneData.radius===null?!0:Object.keys(diffObject(canvasData,sceneData)).length+Object.keys(diffObject(sceneData,canvasData)).length>0}).map(([slug])=>slug),newAuraSlugs=Array.from(this.document.auras.keys()).filter(s=>!this.auras.has(s));return this.auras.reset([changedAndDeletedAuraSlugs,newAuraSlugs].flat())}emitHoverIn(nativeEvent){const event=new PIXI.FederatedPointerEvent(new PIXI.EventBoundary(this));event.type="pointerover",event.nativeEvent=nativeEvent,this._onHoverIn(event,{hoverOutOthers:!0})}emitHoverOut(nativeEvent){const event=new PIXI.FederatedPointerEvent(new PIXI.EventBoundary(this));event.type="pointerout",event.nativeEvent=nativeEvent,this._onHoverOut(event)}_isVisionSource(){return!!this.actor?.hasPlayerOwner&&!game.user.isGM&&game.settings.get("pf2e","metagame_partyVision")||super._isVisionSource()}clone(){const clone=super.clone();return clone.isPreview&&(clone.document.height=this.document.height,clone.document.width=this.document.width,clone.document.texture.scaleX=this.document.texture.scaleX,clone.document.texture.scaleY=this.document.texture.scaleY,clone.document.texture.src=this.document.texture.src),clone}async showFloatyText(params){if(!this.isVisible)return;if(!game.user.isGM&&typeof params!="number"){const[_,document2]=Object.entries(params)[0];if(document2 instanceof EffectPF2e&&document2.system.unidentified)return}const scrollingTextArgs=(()=>{if(typeof params=="number"){const quantity=params,maxHP=this.actor?.hitPoints?.max;if(!(quantity&&typeof maxHP=="number"))return null;const percent=Math.clamped(Math.abs(quantity)/maxHP,0,1),textColors={damage:16711680,healing:65280};return[this.center,params.signedString(),{anchor:CONST.TEXT_ANCHOR_POINTS.TOP,jitter:.25,fill:textColors[quantity<0?"damage":"healing"],fontSize:16+32*percent,stroke:0,strokeThickness:4}]}else{const[change,details]=Object.entries(params)[0],isAdded=change==="create",sign=isAdded?"+ ":"- ",appendedNumber=!/ \d+$/.test(details.name)&&details.value?` ${details.value}`:"",content=`${sign}${details.name}${appendedNumber}`,anchorDirection=isAdded?CONST.TEXT_ANCHOR_POINTS.TOP:CONST.TEXT_ANCHOR_POINTS.BOTTOM,textStyle=pick$1(this._getTextStyle(),["fill","fontSize","stroke","strokeThickness"]);return[this.center,content,{...textStyle,anchor:anchorDirection,direction:anchorDirection,jitter:.25}]}})();scrollingTextArgs&&(await this._animation,await canvas.interface?.createScrollingText(...scrollingTextArgs))}distanceTo(target,{reach=null}={}){if(!canvas.dimensions)return NaN;if(this===target)return 0;if(canvas.grid.type!==CONST.GRID_TYPES.SQUARE)return canvas.grid.measureDistance(this.position,target.position);const selfElevation=this.document.elevation,targetElevation=target.document.elevation;return selfElevation===targetElevation||!this.actor||!target.actor?measureDistanceCuboid(this.bounds,target.bounds,{reach}):measureDistanceCuboid(this.bounds,target.bounds,{reach,token:this,target})}async animate(updateData,options){if(options?.spin){let attributeAdded=!1;const currentRotation=this.document.rotation,rotationAngle=this.x<=this.document.x?360:-360;options.ontick=(_frame,data)=>{if(this.document.lockRotation=!1,!attributeAdded&&data.attributes.length>0){const duration=(data.duration??1e3)/1e3;data.attributes.push({attribute:"rotation",parent:data.attributes[0].parent,from:currentRotation,to:currentRotation+duration*rotationAngle,delta:data.attributes[0].delta}),attributeAdded=!0}}}await super.animate(updateData,options),this.document.lockRotation=this.document._source.lockRotation}updateVisionSource({defer=!1,deleted=!1}={}){super.updateVisionSource({defer,deleted}),this._isVisionSource()&&!deleted&&this.hearing.initialize()}render(renderer){if(super.render(renderer),!this.mesh)return;const configuredTint=this.document.texture.tint??"#FFFFFF";this.mesh.tint!==0&&this.detectionFilter instanceof OutlineOverlayFilter?this.mesh.tint=0:this.mesh.tint===0&&configuredTint!=="#000000"&&!this.detectionFilter&&(this.mesh.tint=Number(Color.fromString(configuredTint)))}_destroy(){super._destroy(),this.auras.destroy(),this.hearing.destroy(),this.flankingHighlight.destroy()}_canView(user,event){return super._canView(user,event)||!!(this.actor?.isOfType("npc")&&this.actor.isLootable)}_onControl(options={}){return game.ready&&game.pf2e.effectPanel.refresh(),super._onControl(options)}_onRelease(options){return game.pf2e.effectPanel.refresh(),super._onRelease(options)}_onApplyStatusEffect(statusId,active){super._onApplyStatusEffect(statusId,active),["undetected","unnoticed"].includes(statusId)&&(canvas.perception.update({refreshVision:!0,refreshLighting:!0},!0),this.mesh.refresh())}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId),changed.width&&(this._animation?this._animation.then(()=>{this.auras.reset()}):this.auras.reset())}};__name2(_TokenPF2e,"TokenPF2e");let TokenPF2e=_TokenPF2e;function measureDistanceCuboid(r0,r1,{reach=null,token=null,target=null}={}){if(!canvas.dimensions)return NaN;if(canvas.grid.type!==CONST.GRID_TYPES.SQUARE)return canvas.grid.measureDistance(r0,r1);const gridWidth=canvas.grid.grid.w,distance={dx:0,dy:0,dz:0};if([[r0,r1],[r1,r0]].some(([rA,rB])=>rB.right>rA.left&&rB.leftrA.top&&rB.top{const roundLeft=rectangle.leftrB.bottom>rA.top&&rB.top{const roundLeft=rectangle.lefta-b),squares={doubleDiagonal:sortedDistance[0],diagonal:sortedDistance[1]-sortedDistance[0],straight:sortedDistance[2]-sortedDistance[1]},reduction=squares.diagonal+squares.doubleDiagonal>1&&reach===10?1:0;return(Math.floor(squares.doubleDiagonal*1.75+squares.diagonal*1.5+squares.straight)-reduction)*gridDistance}__name(measureDistanceOnGrid,"measureDistanceOnGrid"),__name2(measureDistanceOnGrid,"measureDistanceOnGrid");function highlightGrid({areaType,object,colors,document:document2,collisionType="move",preview=!1}){if(!object.id&&!preview)return;const{grid,dimensions}=canvas;if(!(grid&&dimensions))return;const angle=document2.angle??0,direction=document2.direction??45,highlightLayer=grid.getHighlightLayer(object.highlightId)?.clear();if(!highlightLayer)return;const[cx,cy]=grid.getCenter(document2.x,document2.y),[col0,row0]=grid.grid.getGridPositionFromPixels(cx,cy),minAngle=(360+(direction-angle*.5)%360)%360,maxAngle=(360+(direction+angle*.5)%360)%360,snappedOrigin=canvas.grid.getSnappedPosition(document2.x,document2.y,object.layer.gridPrecision),withinAngle=__name2((min,max,value)=>(min=(360+min%360)%360,max=(360+max%360)%360,value=(360+value%360)%360,min=min&&value<=max:value>=min||value<=max),"withinAngle"),coneOriginOffset=(()=>{if(areaType!=="cone")return{x:0,y:0};const dir=(direction>=0?360-direction:-direction)%360,xOffset=snappedOrigin.x%dimensions.size!==0?Math.sign(1*Math.round(Math.cos(Math.toRadians(dir))*100)/100)/2:0,yOffset=snappedOrigin.y%dimensions.size!==0?-Math.sign(1*Math.round(Math.sin(Math.toRadians(dir))*100)/100)/2:0;return{x:xOffset*dimensions.size,y:yOffset*dimensions.size}})(),padding=Math.clamped(document2.width??0,1.5,2),docDistance=document2.distance??0,padded=docDistance*padding/dimensions.distance,rowCount=Math.ceil(padded/(dimensions.size/grid.h)),columnCount=Math.ceil(padded/(dimensions.size/grid.w)),offsetEmanationOrigin=__name2(destination=>{if(!(areaType==="emanation"&&object instanceof TokenPF2e))return{x:0,y:0};if(object.w<=dimensions.size)return{x:0,y:0};const offset=(object.w-dimensions.size)/2,getCoordinate=__name2((centerCoord,destCoord)=>destCoord===centerCoord?0:destCoord>centerCoord?offset:-offset,"getCoordinate");return{x:getCoordinate(object.center.x,destination.x),y:getCoordinate(object.center.y,destination.y)}},"offsetEmanationOrigin");for(let a=-columnCount;a0&&!withinAngle(minAngle,maxAngle,rayAngle))continue}if(measureDistance(destination,origin)>docDistance)continue;canvas.ready&&CONFIG.Canvas.polygonBackends[collisionType].testCollision(origin,destination,{type:collisionType,mode:"any"})?(grid.grid.highlightGridPosition(highlightLayer,{x:gx,y:gy,border:1,color:0}),highlightLayer.beginFill(0,.5).moveTo(gx,gy).lineTo(gx+dimensions.size,gy+dimensions.size).endFill()):grid.grid.highlightGridPosition(highlightLayer,{x:gx,y:gy,border:colors.border,color:colors.fill})}}__name(highlightGrid,"highlightGrid"),__name2(highlightGrid,"highlightGrid");const _MeasuredTemplatePF2e=class _MeasuredTemplatePF2e2 extends MeasuredTemplate{static{__name(this,"_MeasuredTemplatePF2e")}constructor(){super(...arguments),__privateAdd(this,_moveTime,0),__privateAdd(this,_wheelListenerOptions,{passive:!1}),__privateAdd(this,_onPreviewMouseMove,__name2(event=>{event.stopPropagation();const now=Date.now();if(now-__privateGet(this,_moveTime)<=20)return;const center=event.getLocalPosition(this.layer),snapped=canvas.grid.getSnappedPosition(center.x,center.y,2),hexTypes=[CONST.GRID_TYPES.HEXODDR,CONST.GRID_TYPES.HEXEVENR],direction=__privateGet(this,_moveTime)===0&&hexTypes.includes(canvas.grid.type)?this.document.direction+30:this.document.direction;this.document.updateSource({...snapped,direction}),this.refresh(),__privateSet(this,_moveTime,now)},"#onPreviewMouseMove")),__privateAdd(this,_onPreviewLeftClick,__name2(()=>{canvas.scene&&canvas.scene.createEmbeddedDocuments("MeasuredTemplate",[this.document.toObject()]).then(()=>{_MeasuredTemplatePF2e2.currentPreview&&(_MeasuredTemplatePF2e2.currentPreview.placed=!0)}),canvas.tokens.activate(),this.destroy()},"#onPreviewLeftClick")),__privateAdd(this,_onPreviewRightClick,__name2(()=>{canvas.tokens.activate(),this.destroy(),_MeasuredTemplatePF2e2.currentPreview?.resolve(null)},"#onPreviewRightClick")),__privateAdd(this,_onPreviewMouseWheel,__name2(event=>{if(event instanceof WheelEvent){if(event.ctrlKey){event.preventDefault(),event.stopPropagation();const snap=event.shiftKey?15:5;this.document.updateSource({direction:this.document.direction+snap*Math.sign(event.deltaY)}),this.refresh()}else if(event.shiftKey){event.stopPropagation();const snap=canvas.grid.type>=CONST.GRID_TYPES.HEXODDR&&canvas.grid.type<=CONST.GRID_TYPES.HEXEVENQ?60:45;this.document.updateSource({direction:this.document.direction+snap*Math.sign(event.deltaY)}),this.refresh()}}},"#onPreviewMouseWheel"))}get type(){return this.document.t}highlightGrid(){if(!["circle","cone"].includes(this.type)||canvas.grid.type!==CONST.GRID_TYPES.SQUARE)return super.highlightGrid();if(!this.isVisible){canvas.grid.getHighlightLayer(this.highlightId)?.clear();return}highlightGrid({areaType:this.type==="circle"?"burst":"cone",object:this,document:this.document,colors:{border:this.borderColor,fill:this.fillColor},preview:!0})}async drawPreview(){return this.layer.activate(),await this.draw(),this.layer.preview.addChild(this),canvas.stage.on("mousemove",__privateGet(this,_onPreviewMouseMove)),canvas.stage.on("mousedown",__privateGet(this,_onPreviewLeftClick)),canvas.stage.on("rightdown",__privateGet(this,_onPreviewRightClick)),canvas.app.view.addEventListener?.("wheel",__privateGet(this,_onPreviewMouseWheel),__privateGet(this,_wheelListenerOptions)),_MeasuredTemplatePF2e2.currentPreview?.resolve(null),new Promise(res=>{_MeasuredTemplatePF2e2.currentPreview={resolve:value=>{res(value),_MeasuredTemplatePF2e2.currentPreview=null},placed:!1}})}destroy(options){canvas.stage.off("mousemove",__privateGet(this,_onPreviewMouseMove)),canvas.stage.off("mousedown",__privateGet(this,_onPreviewLeftClick)),canvas.stage.off("rightdown",__privateGet(this,_onPreviewRightClick)),canvas.app.view.removeEventListener?.("wheel",__privateGet(this,_onPreviewMouseWheel),__privateGet(this,_wheelListenerOptions)),super.destroy(options)}applyRenderFlags(){super.applyRenderFlags(),_MeasuredTemplatePF2e2.currentPreview?.placed&&_MeasuredTemplatePF2e2.currentPreview.resolve(this)}get item(){return this.document.item}};_moveTime=new WeakMap,_wheelListenerOptions=new WeakMap,_onPreviewMouseMove=new WeakMap,_onPreviewLeftClick=new WeakMap,_onPreviewRightClick=new WeakMap,_onPreviewMouseWheel=new WeakMap,__name2(_MeasuredTemplatePF2e,"MeasuredTemplatePF2e"),__publicField(_MeasuredTemplatePF2e,"currentPreview",null);let MeasuredTemplatePF2e=_MeasuredTemplatePF2e;const _TokenAura=class{static{__name(this,"_TokenAura")}constructor(params){__publicField(this,"slug"),__publicField(this,"token"),__publicField(this,"level"),__publicField(this,"radius"),__publicField(this,"traits"),__publicField(this,"effects"),__publicField(this,"appearance"),__privateAdd(this,_squares,void 0),this.slug=params.slug,this.token=params.token,this.level=params.level,this.radius=params.radius,this.traits=params.traits,this.effects=params.effects,this.appearance=params.appearance}get radiusPixels(){const gridSize=this.scene.grid.distance,gridSizePixels=this.scene.grid.size;return .5*this.token.mechanicalBounds.width+this.radius/gridSize*gridSizePixels}get scene(){return this.token.scene}get bounds(){const{token,radiusPixels}=this,bounds=token.mechanicalBounds;return new PIXI.Rectangle(bounds.x-(radiusPixels-bounds.width/2),bounds.y-(radiusPixels-bounds.width/2),radiusPixels*2,radiusPixels*2)}get center(){return this.token.center}get squares(){return __privateGet(this,_squares)??__privateSet(this,_squares,getAreaSquares(this))}containsToken(token){return token===this.token?!0:!this.token.object||!token.object||this.token.object.distanceTo(token.object)>this.radius?!1:this.squares.some(s=>s.active&&measureDistanceCuboid(s,token.mechanicalBounds)===0)}async notifyActors(){if(!this.scene.isInFocus)return;const auraActor=this.token.actor,auraData=auraActor?.auras.get(this.slug);if(!(auraActor&&auraData))return;const auradTokens=this.scene.tokens.filter(t=>t.actor?.primaryUpdater===game.user&&this.containsToken(t)),affectedActors=new Set(auradTokens.flatMap(t=>t.actor??[])),origin={actor:auraActor,token:this.token};for(const actor of affectedActors)await actor.applyAreaEffects(auraData,origin)}};_squares=new WeakMap,__name2(_TokenAura,"TokenAura");let TokenAura=_TokenAura;const _TokenDocumentPF2e=class _TokenDocumentPF2e2 extends TokenDocument{static{__name(this,"_TokenDocumentPF2e")}constructor(){super(...arguments),__privateAdd(this,_prepareDerivedPerception),__publicField(this,"constructed",!0)}get inCombat(){return this.actor?.isOfType("party")?this.actor.members.every(a=>game.combat?.getCombatantByActor(a.id)):super.inCombat}hasStatusEffect(statusId){if(statusId==="dead")return this.overlayEffect===CONFIG.controlIcons.defeated;const{actor}=this;return!actor||!game.settings.get("pf2e","automation.rulesBasedVision")?!1:objectHasKey(CONFIG.PF2E.conditionTypes,statusId)&&actor.hasCondition(statusId)||__name2(()=>actor.itemTypes.effect.some(e=>(e.slug??sluggify(e.name))===statusId),"hasEffect")()}static getTrackedAttributes(data={},_path=[]){if(_path.length===0&&Object.keys(data).length===0)for(const[type,model]of Object.entries(game.system.model.Actor))["character","npc"].includes(type)&&foundry.utils.mergeObject(data,model);if(_path.length>0)return super.getTrackedAttributes(data,_path);const patterns={positive:/^(?:attributes|resources)\./,negative:/\b(?:rank|_?modifiers|item|classdc|dexcap|familiar|\w+hp\b)|bonus/i},prunedData=expandObject(Object.fromEntries(Object.entries(flattenObject(data)).filter(([k,v])=>patterns.positive.test(k)&&!patterns.negative.test(k)&&!["boolean","string"].includes(typeof v))));return super.getTrackedAttributes(prunedData,_path)}get scene(){return this.parent}get emitsDarkness(){return this.light.bright<0}get rulesBasedVision(){return!!(this.sight.enabled&&this.actor?.isOfType("character","familiar")&&this.scene?.rulesBasedVision)}get hasLowLightVision(){return!!(this.rulesBasedVision&&this.actor?.isOfType("creature")&&this.actor.hasLowLightVision)}get hasDarkvision(){return!!(this.rulesBasedVision&&this.actor?.isOfType("creature")&&this.actor.hasDarkvision)}get linkToActorSize(){return this.flags.pf2e.linkToActorSize}get autoscale(){return this.flags.pf2e.autoscale}get playersCanSeeName(){const anyoneCanSee=[CONST.TOKEN_DISPLAY_MODES.ALWAYS,CONST.TOKEN_DISPLAY_MODES.HOVER],nameDisplayMode=this.displayName;return anyoneCanSee.includes(nameDisplayMode)||this.actor?.alliance==="party"}get bounds(){const gridSize=this.scene?.grid.size??100;return new PIXI.Rectangle(this._source.x,this._source.y,this.width*gridSize,this.height*gridSize)}get mechanicalBounds(){const bounds=this.bounds;if(this.width<1){const position=canvas.grid.getTopLeft(bounds.x+bounds.width/2,bounds.y+bounds.height/2);return new PIXI.Rectangle(position[0],position[1],Math.max(canvas.grid.size,bounds.width),Math.max(canvas.grid.size,bounds.height))}return bounds}get center(){const{bounds}=this;return{x:bounds.x+bounds.width/2,y:bounds.y+bounds.height/2}}_initialize(options){this.constructed??=!1,this.auras=new Map,super._initialize(options)}prepareData(){this.parent&&!this.parent.flags?.pf2e||super.prepareData()}prepareBaseData(){if(super.prepareBaseData(),this.flags=mergeObject(this.flags,{pf2e:{}}),this.auras.clear(),!this.actor||!this.isEmbedded)return;_TokenDocumentPF2e2.assignDefaultImage(this);for(const[key,data]of this.actor.auras.entries())this.auras.set(key,new TokenAura({token:this,...deepClone(data)}));if(!this.constructed)return;const linkDefault=SIZE_LINKABLE_ACTOR_TYPES.has(this.actor.type),linkToActorSize=this.flags.pf2e?.linkToActorSize??linkDefault,autoscaleDefault=game.settings.get("pf2e","tokens.autoscale"),autoscale=linkToActorSize?this.flags.pf2e.autoscale??autoscaleDefault:!1;this.flags.pf2e=mergeObject(this.flags.pf2e??{},{linkToActorSize,autoscale});const{alliance}=this.actor.system.details;this.disposition=this.disposition===CONST.TOKEN_DISPOSITIONS.SECRET?CONST.TOKEN_DISPOSITIONS.SECRET:alliance?{party:CONST.TOKEN_DISPOSITIONS.FRIENDLY,opposition:CONST.TOKEN_DISPOSITIONS.HOSTILE}[alliance]:CONST.TOKEN_DISPOSITIONS.NEUTRAL}_prepareDetectionModes(){if(!(this.constructed&&this.actor&&this.rulesBasedVision))return super._prepareDetectionModes();this.detectionModes=[{id:"basicSight",enabled:!0,range:0}],["character","familiar"].includes(this.actor.type)&&(this.sight.attenuation=.1,this.sight.brightness=0,this.sight.contrast=0,this.sight.range=0,this.sight.saturation=0,this.sight.visionMode="basic")}prepareDerivedData(){if(super.prepareDerivedData(),!(this.constructed&&this.actor&&this.scene))return;const{tokenOverrides}=this.actor.synthetics;this.name=tokenOverrides.name??this.name,tokenOverrides.texture&&(this.texture.src=tokenOverrides.texture.src,"scaleX"in tokenOverrides.texture&&(this.texture.scaleX=tokenOverrides.texture.scaleX,this.texture.scaleY=tokenOverrides.texture.scaleY,this.flags.pf2e.autoscale=!1),this.texture.tint=tokenOverrides.texture.tint??this.texture.tint),this.alpha=tokenOverrides.alpha??this.alpha,tokenOverrides.light&&(this.light=new foundry.data.LightData(tokenOverrides.light,{parent:this})),_TokenDocumentPF2e2.prepareSize(this),__privateMethod(this,_prepareDerivedPerception,prepareDerivedPerception_fn).call(this)}static assignDefaultImage(token){const{actor}=token;if(!actor)return;const defaultIcons=[ActorPF2e.DEFAULT_ICON,`systems/pf2e/icons/default-icons/${actor.type}.svg`];game.settings.get("pf2e","nathMode")&&defaultIcons.includes(token.texture.src)?token.texture.src=(()=>{switch(actor.alliance){case"party":return"systems/pf2e/icons/default-icons/alternatives/nath/ally.webp";case"opposition":return"systems/pf2e/icons/default-icons/alternatives/nath/enemy.webp";default:return token.texture.src}})():defaultIcons.some(path=>token.texture.src?.endsWith(path))&&(token.texture.src=actor._source.img)}static prepareSize(token){const{actor}=token;if(!(actor&&token.flags.pf2e.linkToActorSize))return;const size={tiny:.5,sm:1,med:1,lg:2,huge:3,grg:Math.max(token.width,4)}[actor.size];if(actor.isOfType("vehicle")){const{width,height}=actor.getTokenDimensions();token.width=width,token.height=height}else if(token.width=size,token.height=size,game.settings.get("pf2e","tokens.autoscale")&&token.flags.pf2e.autoscale!==!1){const absoluteScale=actor.size==="sm"?.8:1,mirrorX=token.texture.scaleX<0?-1:1;token.texture.scaleX=mirrorX*absoluteScale;const mirrorY=token.texture.scaleY<0?-1:1;token.texture.scaleY=mirrorY*absoluteScale}}async setInitiative({initiative,sendMessage=!0}){if(!game.combat){ui.notifications.error("PF2E.Encounter.NoActiveEncounter");return}const currentId=game.combat.combatant?.id;this.combatant&&game.combat.combatants.has(this.combatant.id)?await game.combat.setInitiative(this.combatant.id,initiative):await game.combat.createEmbeddedDocuments("Combatant",[{tokenId:this.id,initiative}]),await this.update({turn:game.combat.turns.findIndex(c=>c.id===currentId)}),sendMessage&&await ChatMessagePF2e.createDocuments([{speaker:{scene:this.scene?.id,token:this.id},whisper:this.actor?.hasPlayerOwner?[]:game.users.contents.flatMap(user=>user.isGM?user.id:[]),content:game.i18n.format("PF2E.InitiativeIsNow",{name:this.name,value:initiative})}])}_onCreate(data,options,userId){super._onCreate(data,options,userId),game.user.id===userId&&this.actor?.isOfType("loot")&&this.actor.toggleTokenHiding()}_onUpdate(changed,options,userId){const tokenSetsNameVisibility=game.settings.get("pf2e","metagame_tokenSetsNameVisibility");return"displayName"in changed&&tokenSetsNameVisibility&&this.combatant&&ui.combat.render(),changed.actorLink===!1&&this.rendered&&this.object?.controlled&&this.object.release(),super._onUpdate(changed,options,userId)}_onRelatedUpdate(update={},options={}){super._onRelatedUpdate(update,options);const initializeVision=!!this.scene?.isView&&this.sight.enabled&&Object.keys(flattenObject(update)).some(k=>k.startsWith("system.traits.senses"));initializeVision&&canvas.perception.update({initializeVision},!0);const preUpdate=this.toObject(!1),preUpdateAuras=Array.from(this.auras.values()).map(a=>omit(a,["appearance","token"]));this.reset();const postUpdate=this.toObject(!1),postUpdateAuras=Array.from(this.auras.values()).map(a=>omit(a,["appearance","token"])),tokenChanges=diffObject(preUpdate,postUpdate);this.scene?.isView&&Object.keys(tokenChanges).length>0&&this.object?._onUpdate(tokenChanges,{},game.user.id);const aurasChanged=__name2(()=>!!this.scene?.isInFocus&&!equals(preUpdateAuras,postUpdateAuras),"aurasChanged");("disposition"in tokenChanges||"width"in tokenChanges||"height"in tokenChanges||aurasChanged())&&this.scene?.checkAuras?.()}_onDelete(options,userId){if(super._onDelete(options,userId),!!this.actor)if(this.isLinked)this.scene?.tokens.some(t=>t.actor===this.actor)||this.actor.checkAreaEffects();else for(const effect of this.actor.itemTypes.effect)game.pf2e.effectTracker.unregister(effect)}};_prepareDerivedPerception=new WeakSet,prepareDerivedPerception_fn=__name2(function(){if(!(this.rulesBasedVision&&this.actor&&this.scene&&this.sight.enabled))return;const visionMode=this.hasDarkvision?"darkvision":"basic";this.sight.visionMode=visionMode;const{defaults}=CONFIG.Canvas.visionModes[visionMode].vision;if(this.sight.brightness=defaults.brightness??0,this.sight.saturation=defaults.saturation??0,visionMode==="darkvision"||this.scene.lightLevel>LightLevels.DARKNESS){const basicDetection=this.detectionModes.at(0);if(!basicDetection)return;this.sight.range=basicDetection.range=defaults.range??0,this.actor.isOfType("character")&&this.actor.flags.pf2e.colorDarkvision?this.sight.saturation=1:game.user.settings.monochromeDarkvision||(this.sight.saturation=0)}this.actor.isOfType("character","familiar")&&this.actor.system.traits.senses.some(s=>s.type==="seeInvisibility")&&this.detectionModes.push({id:"seeInvisibility",enabled:!0,range:1e3});const tremorsense=this.actor.isOfType("character")?this.actor.system.traits.senses.find(s=>s.type==="tremorsense"&&s.acuity!=="vague"):null;if(tremorsense&&this.detectionModes.push({id:"feelTremor",enabled:!0,range:tremorsense.range}),!this.actor.hasCondition("deafened")){const range=this.scene.flags.pf2e.hearingRange??canvas.dimensions?.maxR??1/0;this.detectionModes.push({id:"hearing",enabled:!0,range})}},"#prepareDerivedPerception"),__name2(_TokenDocumentPF2e,"TokenDocumentPF2e");let TokenDocumentPF2e=_TokenDocumentPF2e;const _BaseTagSelector=class extends DocumentSheet{static{__name(this,"_BaseTagSelector")}constructor(document2,options={}){super(document2,options),__privateAdd(this,_getChoices),__publicField(this,"choices"),__publicField(this,"flat"),this.flat=options.flat??!1,this.choices=__privateMethod(this,_getChoices,getChoices_fn).call(this)}static get defaultOptions(){return mergeObject(super.defaultOptions,{id:"tag-selector",classes:["pf2e","tag-selector"],width:"auto"})}get id(){return`${this.options.id}-${this.document.uuid}`}get title(){return game.i18n.localize(this.options.title||"PF2E.TraitsLabel")}async getData(options){return{...await super.getData(options),documentType:this.document.constructor.metadata.label}}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const input of htmlQueryAll(html,"input:not([type=checkbox])"))input.addEventListener("focusin",()=>{input.select()})}sortChoices(choices){return Object.entries(choices).map(([key,value])=>[key,game.i18n.localize(value)]).sort(([_keyA,valueA],[_keyB,valueB])=>valueA.localeCompare(valueB)).reduce((accumulated,[key,value])=>mergeObject(accumulated,{[key]:value}),{})}};_getChoices=new WeakSet,getChoices_fn=__name2(function(){const choices=this.configTypes.reduce((types,key)=>mergeObject(types,CONFIG.PF2E[key]),{});return this.sortChoices(choices)},"#getChoices"),__name2(_BaseTagSelector,"BaseTagSelector");let BaseTagSelector=_BaseTagSelector;function isValuesList(value){return!!(value&&typeof value=="object"&&"value"in value)}__name(isValuesList,"isValuesList"),__name2(isValuesList,"isValuesList");const _TagSelectorBasic=class extends BaseTagSelector{static{__name(this,"_TagSelectorBasic")}constructor(document2,options){super(document2,options),__privateAdd(this,_getUpdateData),__privateAdd(this,_search),__privateAdd(this,_onFilterResults),__publicField(this,"allowCustom"),__privateAdd(this,_filterTimeout,null),__publicField(this,"objectProperty"),this.objectProperty=options.objectProperty,this.allowCustom=options.allowCustom??!0,options.customChoices&&(mergeObject(this.choices,options.customChoices),this.choices=this.sortChoices(this.choices))}static get defaultOptions(){return mergeObject(super.defaultOptions,{template:"systems/pf2e/templates/system/tag-selector/basic.hbs"})}get configTypes(){return this.options.configTypes??[]}async getData(options){const{chosen,custom,flat,disabled}=(()=>{const document2=this.document,sourceProperty=getProperty(document2.toObject(),this.objectProperty),preparedProperty=getProperty(document2,this.objectProperty);if(Array.isArray(preparedProperty)){const manuallyChosen=Array.isArray(sourceProperty)?sourceProperty.map(prop=>String(prop)):[],automaticallyChosen=preparedProperty.filter(tag=>!manuallyChosen.includes(tag));return{chosen:Array.from(new Set([...manuallyChosen,...automaticallyChosen])),custom:null,flat:!0,disabled:automaticallyChosen}}else if(isValuesList(preparedProperty)&&isValuesList(sourceProperty)){const manuallyChosen=sourceProperty.value.map(prop=>prop.toString()),custom2=this.allowCustom?sourceProperty.custom:null,automaticallyChosen=preparedProperty.value.filter(tag=>!manuallyChosen.includes(tag));return{chosen:Array.from(new Set([...manuallyChosen,...automaticallyChosen])),custom:custom2,flat:!1,disabled:automaticallyChosen}}else return{chosen:[],custom:null,flat:this.flat,disabled:[]}})(),choices=Object.keys(this.choices).reduce((accumulated,type)=>(accumulated[type]={label:this.choices[type],selected:chosen.includes(type),disabled:disabled.includes(type)},accumulated),{});return{...await super.getData(options),choices,allowCustom:this.allowCustom&&!flat,custom,flat}}activateListeners($html){super.activateListeners($html);const html=$html[0],searchInput=htmlQuery(html,"input[type=search]");searchInput?.addEventListener("input",()=>{__privateMethod(this,_onFilterResults,onFilterResults_fn).call(this,searchInput)})}async _updateObject(event,formData){const{flat}=event.target?$(event.target).data():{flat:!1},value=__privateMethod(this,_getUpdateData,getUpdateData_fn).call(this,formData);return this.allowCustom&&typeof formData.custom=="string"?super._updateObject(event,{[this.objectProperty]:{value,custom:formData.custom}}):flat?super._updateObject(event,{[this.objectProperty]:value}):super._updateObject(event,{[`${this.objectProperty}.value`]:value})}};_filterTimeout=new WeakMap,_getUpdateData=new WeakSet,getUpdateData_fn=__name2(function(formData){const optionsAreNumeric=Object.keys(formData).every(tag=>Number.isInteger(Number(tag))),selections=Object.entries(formData).flatMap(([tag,selected])=>selected?tag:[]).filter(tag=>tag!=="custom");return optionsAreNumeric?selections.map(tag=>Number(tag)):selections},"#getUpdateData"),_search=new WeakSet,search_fn=__name2(function(searchString){const query=new RegExp(RegExp.escape(searchString),"i"),html=this.element[0];for(const row of htmlQueryAll(html,"li.trait-item")){const name2=row.getElementsByClassName("trait-label")[0]?.textContent??"";row.style.display=query.test(name2)?"flex":"none"}},"#search"),_onFilterResults=new WeakSet,onFilterResults_fn=__name2(function(input){__privateGet(this,_filterTimeout)&&(clearTimeout(__privateGet(this,_filterTimeout)),__privateSet(this,_filterTimeout,null)),__privateSet(this,_filterTimeout,window.setTimeout(()=>__privateMethod(this,_search,search_fn).call(this,input.value),100))},"#onFilterResults"),__name2(_TagSelectorBasic,"TagSelectorBasic");let TagSelectorBasic=_TagSelectorBasic;const _SenseSelector=class extends BaseTagSelector{static{__name(this,"_SenseSelector")}objectProperty="system.traits.senses";static get defaultOptions(){return mergeObject(super.defaultOptions,{height:"auto",template:"systems/pf2e/templates/system/tag-selector/senses.hbs",id:"sense-selector",title:"PF2E.Actor.Creature.Sense.Label"})}get configTypes(){return["senses"]}async getData(options){if(!this.document.isOfType("character"))throw ErrorPF2e("The Sense selector is usable only with PCs");const senses2=this.document.system.traits.senses,choices=Object.entries(this.choices).reduce((accum,[type,label])=>{const sense=senses2.find(sense2=>sense2.type===type),mandatoryAcuity=objectHasKey(SENSES_WITH_MANDATORY_ACUITIES,type),acuity=mandatoryAcuity?SENSES_WITH_MANDATORY_ACUITIES[type]:sense?.acuity??"precise";return{...accum,[type]:{acuity,mandatoryAcuity,disabled:!!sense?.source,label,selected:!!sense,value:sense?.value??""}}},{});return{...await super.getData(options),hasExceptions:!1,choices,senseAcuity:CONFIG.PF2E.senseAcuity}}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const input of htmlQueryAll(html,"input[type=number]")){const checkbox=htmlQuery(htmlClosest(input,"tr"),"input[type=checkbox]");checkbox&&input.addEventListener("input",()=>{checkbox.checked=!!Number(input.value)})}}_onSubmit(event,options){for(const input of htmlQueryAll(this.element[0],"input[type=number]")){const checkbox=htmlQuery(htmlClosest(input,"tr"),"input[type=checkbox]");checkbox&&!Number(input.value)&&(checkbox.checked=!1)}return super._onSubmit(event,options)}async _updateObject(event,formData){const update=Object.entries(formData).filter(e=>e[1]===!0||Array.isArray(e[1])&&e[1][0]).map(([type,values])=>{if(values===!0)return{type};if(Number(values[2])){const acuity=values[1],range=Number(values[2]);return{type,acuity,value:range}}else{const acuity=values[1];return{type,acuity}}});return super._updateObject(event,{[this.objectProperty]:update})}};__name2(_SenseSelector,"SenseSelector");let SenseSelector=_SenseSelector;const _SpeedSelector=class extends BaseTagSelector{static{__name(this,"_SpeedSelector")}objectProperty="system.attributes.speed.otherSpeeds";static get defaultOptions(){return mergeObject(super.defaultOptions,{id:"speed-selector",template:"systems/pf2e/templates/system/tag-selector/speeds.hbs",title:"PF2E.SpeedTypes"})}get configTypes(){return["speedTypes"]}async getData(options){if(!this.document.isOfType("creature"))throw ErrorPF2e("The Speed selector is usable only with creature-type actors");const speeds=this.document.system.attributes.speed.otherSpeeds,speedLabels=CONFIG.PF2E.speedTypes,choices=Object.keys(this.choices).reduce((accum,type)=>{const speed=speeds.find(s=>s.type===type);return{...accum,[type]:{selected:!!speed,disabled:!!speed?.source,label:game.i18n.localize(speedLabels[type]),value:Number(speed?.value)||""}}},{});return{...await super.getData(options),hasExceptions:this.document.isOfType("npc"),choices}}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const input of htmlQueryAll(html,"input[type=number]"))input.addEventListener("input",()=>{const checkbox=input.closest("li")?.querySelector("input[type=checkbox]");checkbox&&(checkbox.checked=!!Number(input.value))})}async _updateObject(event,formData){const update=Object.entries(formData).flatMap(([key,value])=>{if(!(Array.isArray(value)&&value.length===2))return[];const selected=!!value[0],distance=Math.trunc(Math.abs(value[1]));return selected&&distance?{type:key,value:Math.max(distance,5)}:[]});return super._updateObject(event,{[this.objectProperty]:update})}};__name2(_SpeedSelector,"SpeedSelector");let SpeedSelector=_SpeedSelector;const TAG_SELECTOR_TYPES=["basic","senses","speed-types"],SELECTABLE_TAG_FIELDS=["abilities","actionTraits","attackEffects","creatureTraits","damageCategories","languages","levels","materialDamageEffects","otherArmorTags","otherConsumableTags","otherWeaponTags","senses","skills","speedTypes","vehicleTraits","weaponTraits"],_UUIDUtils=class{static{__name(this,"_UUIDUtils")}static async fromUUIDs(uuids,options){const resolvedUUIDs=uniq(uuids).flatMap(u=>foundry.utils.parseUuid(u,options).uuid??[]),packEmbeddedLinks=resolvedUUIDs.filter(u=>{const parsed=foundry.utils.parseUuid(u,options);return parsed.collection instanceof CompendiumCollection&&parsed.embedded.length>0}),packEmbeddedDocs=compact(await Promise.all(packEmbeddedLinks.map(u=>fromUuid(u)))),documentsAndIndexData=compact(resolvedUUIDs.filter(u=>!packEmbeddedLinks.includes(u)).map(u=>fromUuidSync(u))),worldDocsAndCacheHits=documentsAndIndexData.filter(d=>d instanceof foundry.abstract.Document),indexEntries=documentsAndIndexData.filter(d=>!(d instanceof foundry.abstract.Document)),packs=uniq(indexEntries.flatMap(e=>game.packs.get(e.pack??"")??[])),packDocs=(await Promise.all(packs.map(async pack=>{const ids=indexEntries.filter(e=>e.pack===pack.metadata.id).map(e=>e._id);return pack.getDocuments({_id__in:ids})}))).flat();return sortBy$1([...packEmbeddedDocs,...worldDocsAndCacheHits,...packDocs],d=>uuids.indexOf(d.uuid))}static isItemUUID(uuid){return typeof uuid=="string"&&foundry.utils.parseUuid(uuid).documentType==="Item"}static isCompendiumUUID(uuid){return typeof uuid=="string"&&foundry.utils.parseUuid(uuid).collection instanceof CompendiumCollection}static isTokenUUID(uuid){if(typeof uuid!="string")return!1;const parsed=foundry.utils.parseUuid(uuid);return parsed.documentType==="Scene"&&parsed.embedded[0]==="Token"}};__name2(_UUIDUtils,"UUIDUtils");let UUIDUtils=_UUIDUtils;const _ActorSizePF2e=class _ActorSizePF2e2{static{__name(this,"_ActorSizePF2e")}value;length;width;constructor(params){(typeof params.value!="string"||params.smallIsMedium&¶ms.value==="sm")&&(params.value="med"),this.value=params.value;const spaces=_ActorSizePF2e2.defaultSpaces[params.value]??_ActorSizePF2e2.defaultSpaces.med;this.length=params.length??spaces.length,this.width=params.width??spaces.width}equals(size,{smallIsMedium=!1}={}){const thisSize=this.getEffectiveSize(this.value,{smallIsMedium}),otherSize=this.getEffectiveSize(size.value,{smallIsMedium});return thisSize===otherSize}isLargerThan(size,{smallIsMedium=!1}={}){const other=size instanceof _ActorSizePF2e2?size:new _ActorSizePF2e2({value:size}),thisSize=this.getEffectiveSize(this.value,{smallIsMedium}),otherSize=this.getEffectiveSize(other.value,{smallIsMedium});return _ActorSizePF2e2.sizeRanks[thisSize]>_ActorSizePF2e2.sizeRanks[otherSize]}isSmallerThan(size,{smallIsMedium=!1}={}){const other=size instanceof _ActorSizePF2e2?size:new _ActorSizePF2e2({value:size}),thisSize=this.getEffectiveSize(this.value,{smallIsMedium}),otherSize=this.getEffectiveSize(other.value,{smallIsMedium});return _ActorSizePF2e2.sizeRanks[thisSize]<_ActorSizePF2e2.sizeRanks[otherSize]}difference(size,{smallIsMedium=!1}={}){const thisSize=this.getEffectiveSize(this.value,{smallIsMedium}),otherSize=this.getEffectiveSize(size.value,{smallIsMedium});return _ActorSizePF2e2.sizeRanks[thisSize]-_ActorSizePF2e2.sizeRanks[otherSize]}getEffectiveSize(size,{smallIsMedium}){return smallIsMedium&&size==="sm"?"med":size}increment({skipSmall=!1}={}){this.value=this.value==="tiny"&&skipSmall?"med":this.value==="sm"&&skipSmall?"lg":this.value==="grg"?"grg":SIZES[SIZES.indexOf(this.value)+1];const newSpace=_ActorSizePF2e2.defaultSpaces[this.value];this.length=newSpace.length,this.width=newSpace.width}decrement({skipSmall=!1}={}){const toTiny=this.value==="med"&&skipSmall||this.value==="tiny";this.value=toTiny?"tiny":SIZES[SIZES.indexOf(this.value)-1];const newSpace=_ActorSizePF2e2.defaultSpaces[this.value];this.length=newSpace.length,this.width=newSpace.width}toString(){return game.i18n.localize(CONFIG.PF2E.actorSizes[this.value])}};__name2(_ActorSizePF2e,"ActorSizePF2e"),__publicField(_ActorSizePF2e,"defaultSpaces",{tiny:{length:2.5,width:2.5},sm:{length:5,width:5},med:{length:5,width:5},lg:{length:10,width:10},huge:{length:15,width:15},grg:{length:20,width:20}}),__publicField(_ActorSizePF2e,"sizeRanks",{grg:5,huge:4,lg:3,med:2,sm:1,tiny:0});let ActorSizePF2e=_ActorSizePF2e;function onClickCreateSpell(actor,data){if(!data.location)throw ErrorPF2e("Unexpected missing spellcasting-entry location");const rank=Number(data.level??1),newLabel=game.i18n.localize("PF2E.NewLabel"),[rankLabel,spellLabel]=rank>0?[game.i18n.localize(`PF2E.SpellLevel${rank}`),game.i18n.localize(data.location==="rituals"?"PF2E.SpellCategoryRitual":"PF2E.SpellLabel")]:[null,game.i18n.localize("PF2E.TraitCantrip")],source={type:"spell",name:compact([newLabel,rankLabel,spellLabel]).join(" "),system:{level:{value:rank||1},location:{value:String(data.location)},traits:{value:rank===0?["cantrip"]:[]}}};data.location==="rituals"&&(source.system=mergeObject(source.system,{category:{value:"ritual"}})),actor.createEmbeddedDocuments("Item",[source])}__name(onClickCreateSpell,"onClickCreateSpell"),__name2(onClickCreateSpell,"onClickCreateSpell");function getSelectedOrOwnActors(types,useOwnCharacter=!0){const actors=canvas.tokens.controlled.flatMap(token=>token.actor?token.actor:[]).filter(actor=>actor.isOwner).filter(actor=>!types||actor.isOfType(...types));return actors.length===0&&game.user.character&&useOwnCharacter&&actors.push(game.user.character),actors}__name(getSelectedOrOwnActors,"getSelectedOrOwnActors"),__name2(getSelectedOrOwnActors,"getSelectedOrOwnActors");const inlineSelector=["action","check","effect-area"].map(keyword=>`[data-pf2-${keyword}]`).join(","),InlineRollLinks={injectRepostElement:(links,foundryDoc)=>{for(const link of links){(!foundryDoc||foundryDoc.isOwner)&&link.classList.add("with-repost");const repostButtons=htmlQueryAll(link,"i[data-pf2-repost]");if(repostButtons.length>0){if(foundryDoc&&!foundryDoc.isOwner){for(const button of repostButtons)button.remove();link.classList.remove("with-repost")}continue}if(foundryDoc&&!foundryDoc.isOwner)continue;const newButton=document.createElement("i"),icon=link.parentElement?.dataset?.pf2Checkgroup!==void 0?"fa-comment-alt-dots":"fa-comment-alt";newButton.classList.add("fa-solid",icon),newButton.dataset.pf2Repost="",newButton.title=game.i18n.localize("PF2E.Repost"),link.appendChild(newButton),newButton.addEventListener("click",event=>{event.stopPropagation();const target=event.target;if(!(target instanceof HTMLElement))return;const parent=target?.parentElement;if(!parent)return;const document2=resolveDocument(target,foundryDoc);InlineRollLinks.repostAction(parent,document2)})}},listen:(html,foundryDoc=null)=>{foundryDoc??=resolveDocument(html,foundryDoc);const links=htmlQueryAll(html,inlineSelector).filter(l=>["A","SPAN"].includes(l.nodeName));InlineRollLinks.injectRepostElement(links,foundryDoc),InlineRollLinks.flavorDamageRolls(html,foundryDoc instanceof ActorPF2e?foundryDoc:null);for(const link of links.filter(l=>l.dataset.pf2Action)){const{pf2Action,pf2Glyph,pf2Variant,pf2Dc,pf2ShowDc,pf2Skill}=link.dataset;link.addEventListener("click",event=>{const action2=game.pf2e.actions[pf2Action?sluggify(pf2Action,{camel:"dromedary"}):""],visibility=pf2ShowDc??"all";pf2Action&&action2?action2({event,glyph:pf2Glyph,variant:pf2Variant,difficultyClass:pf2Dc?{scope:"check",value:Number(pf2Dc)||0,visibility}:void 0,skill:pf2Skill}):console.warn(`PF2e System | Skip executing unknown action '${pf2Action}'`)})}for(const link of links.filter(l=>l.dataset.pf2Check&&!l.dataset.invalid)){const{pf2Check,pf2Dc,pf2Traits,pf2Label,pf2Defense,pf2Adjustment,pf2Roller,pf2RollOptions}=link.dataset;if(!pf2Check)return;link.addEventListener("click",async event=>{const parent=resolveActor(foundryDoc,link),actors=(()=>{switch(pf2Roller){case"self":return parent?.canUserModify(game.user,"update")?[parent]:[];case"party":return parent?.isOfType("party")?[parent]:compact([game.actors.party])}const actors2=getSelectedOrOwnActors(),isSave=tupleHasValue(SAVE_TYPES,pf2Check);return parent?.isOfType("party")||actors2.length===0&&parent&&!isSave?[parent]:actors2})();if(actors.length===0){ui.notifications.warn(game.i18n.localize("PF2E.UI.errorTargetToken"));return}const extraRollOptions=[...pf2Traits?.split(",").map(o=>o.trim())??[],...pf2RollOptions?.split(",").map(o=>o.trim())??[]],eventRollParams=eventToRollParams(event);switch(pf2Check){case"flat":{for(const actor of actors){const flatCheck=new Statistic(actor,{label:"",slug:"flat",modifiers:[],check:{type:"flat-check"}}),dc=Number.isInteger(Number(pf2Dc))?{label:pf2Label,value:Number(pf2Dc)}:null;flatCheck.roll({...eventRollParams,extraRollOptions,dc})}break}default:{const isSavingThrow=tupleHasValue(SAVE_TYPES,pf2Check),traits=isSavingThrow?[]:extraRollOptions.filter(t=>t in CONFIG.PF2E.actionTraits)??[];for(const actor of actors){const statistic=(()=>{if(pf2Check in CONFIG.PF2E.magicTraditions){const bestSpellcasting=actor.spellcasting.filter(c=>c.tradition===pf2Check).flatMap(s=>s.statistic??[]).sort((a,b)=>b.check.mod-a.check.mod).shift()??null;if(bestSpellcasting)return bestSpellcasting}return actor.getStatistic(pf2Check)})();if(!statistic){console.warn(ErrorPF2e(`Skip rolling unknown statistic ${pf2Check}`).message);continue}const targetActor=pf2Defense?game.user.targets.first()?.actor:null,dcValue=(()=>{const adjustment=Number(pf2Adjustment)||0;return pf2Dc==="@self.level"?calculateDC(actor.level)+adjustment:Number(pf2Dc??"NaN")+adjustment})(),dc=(()=>{if(Number.isInteger(dcValue))return{label:pf2Label,value:dcValue};if(pf2Defense){const defenseStat=targetActor?.getStatistic(pf2Defense);return defenseStat?{statistic:defenseStat.dc,scope:"check",value:defenseStat.dc.value}:null}return null})(),item=(()=>{const itemFromDoc=foundryDoc instanceof ItemPF2e?foundryDoc:foundryDoc instanceof ChatMessagePF2e?foundryDoc.item:null;return itemFromDoc?.isOfType("action","feat","campaignFeature")||isSavingThrow&&!itemFromDoc?.isOfType("weapon")?itemFromDoc:null})(),args={...eventRollParams,extraRollOptions,origin:isSavingThrow&&parent instanceof ActorPF2e?parent:null,dc,target:!isSavingThrow&&dc?.statistic?targetActor:null,item,traits};if(!!(item?.isOfType("action","feat")&&item.actionCost)&&pf2Defense){const subtitleLocKey=pf2Check in CONFIG.PF2E.magicTraditions?"PF2E.ActionsCheck.spell":statistic.check.type==="attack-roll"?"PF2E.ActionsCheck.x-attack-roll":"PF2E.ActionsCheck.x";args.label=await renderTemplate("systems/pf2e/templates/chat/action/header.hbs",{glyph:getActionGlyph(item.actionCost),subtitle:game.i18n.format(subtitleLocKey,{type:statistic.label}),title:item.name})}statistic.roll(args)}}}})}const templateConversion={burst:"circle",cone:"cone",cube:"rect",emanation:"circle",line:"ray",rect:"rect",square:"rect"};for(const link of links.filter(l=>l.hasAttribute("data-pf2-effect-area"))){const{pf2EffectArea,pf2Distance,pf2TemplateData,pf2Traits,pf2Width}=link.dataset;link.addEventListener("click",()=>{if(typeof pf2EffectArea!="string"){console.warn("PF2e System | Could not create template'");return}const templateData=JSON.parse(pf2TemplateData??"{}");switch(templateData.distance||=Number(pf2Distance),templateData.fillColor||=game.user.color,templateData.t=templateConversion[pf2EffectArea],templateData.t){case"ray":templateData.width=Number(pf2Width)||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}}pf2Traits&&(templateData.flags={pf2e:{origin:{traits:pf2Traits.split(",")}}});const templateDoc=new MeasuredTemplateDocumentPF2e(templateData,{parent:canvas.scene});new MeasuredTemplatePF2e(templateDoc).drawPreview()})}},makeRepostHtml:(target,defaultVisibility)=>{const flavor=target.attributes.getNamedItem("data-pf2-repost-flavor")?.value??"";return`${flavor} ${target.outerHTML}`.trim()},repostAction:(target,foundryDoc=null)=>{if(!["pf2Action","pf2Check","pf2EffectArea"].some(d=>d in target.dataset))return;const actor=resolveActor(foundryDoc,target),defaultVisibility=(actor??foundryDoc)?.hasPlayerOwner?"all":"gm",content=(()=>target.parentElement?.dataset?.pf2Checkgroup!==void 0?`
${htmlQueryAll(target.parentElement,inlineSelector).map(target2=>InlineRollLinks.makeRepostHtml(target2,defaultVisibility)).join("
")}
`:InlineRollLinks.makeRepostHtml(target,defaultVisibility))(),speaker=actor?ChatMessagePF2e.getSpeaker({actor,token:actor.getActiveTokens(!1,!0).shift()}):ChatMessagePF2e.getSpeaker(),message=game.messages.get(htmlClosest(target,"[data-message-id]")?.dataset.messageId??""),flags=foundryDoc instanceof JournalEntry?{pf2e:{journalEntry:foundryDoc.uuid}}:message?.flags.pf2e.origin?{pf2e:{origin:deepClone(message.flags.pf2e.origin)}}:{};ChatMessagePF2e.create({speaker,content,flags})},flavorDamageRolls(html,actor=null){for(const rollLink of htmlQueryAll(html,"a.inline-roll[data-damage-roll]")){const itemId=htmlClosest(rollLink,"[data-item-id]")?.dataset.itemId,item=actor?.items.get(itemId??"");item&&(rollLink.dataset.flavor||=item.name)}}};function resolveDocument(html,foundryDoc){if(foundryDoc)return foundryDoc;const document2=(ui.windows[Number(html.closest(".app.sheet")?.dataset.appid)]??null)?.document;return document2 instanceof ActorPF2e||document2 instanceof JournalEntry?document2:null}__name(resolveDocument,"resolveDocument"),__name2(resolveDocument,"resolveDocument");function resolveActor(foundryDoc,anchor){if(foundryDoc instanceof ActorPF2e)return foundryDoc;if(foundryDoc instanceof ItemPF2e||foundryDoc instanceof ChatMessagePF2e)return foundryDoc.actor;const itemUuid=anchor.dataset.itemUuid,itemByUUID=itemUuid&&!itemUuid.startsWith("Compendium.")?fromUuidSync(itemUuid):null;return itemByUUID instanceof ItemPF2e?itemByUUID.actor:null}__name(resolveActor,"resolveActor"),__name2(resolveActor,"resolveActor");const _UserVisibilityPF2e=class{static{__name(this,"_UserVisibilityPF2e")}static process(html,options={}){const visibilityElements=htmlQueryAll(html,"[data-visibility]");for(const element of visibilityElements.filter(e=>e.dataset.visibility==="none"))element.remove();const{message}=options,document2=options.document??message?.actor??message?.journalEntry??message??null;if(document2){const ownerElements=visibilityElements.filter(e=>e.dataset.visibility==="owner");for(const element of ownerElements){if(element.dataset.action){document2.isOwner||element.remove(),delete element.dataset.visibility;continue}const whoseData=element.dataset.whose??"self";if(whoseData==="self"){element.dataset.visibility=document2.hasPlayerOwner?"all":"gm";continue}message?.target&&whoseData==="target"&&(element.dataset.visibility=message.target.actor.hasPlayerOwner?"all":"gm")}}const hasOwnership=document2?.isOwner??game.user.isGM,dcSetting=game.settings.get("pf2e","metagame_showDC"),saveButtons=htmlQueryAll(html,"button[data-action=save]");if(!document2?.hasPlayerOwner&&!hasOwnership&&!dcSetting)for(const button of saveButtons){const saveType=button.dataset.save;if(objectHasKey(CONFIG.PF2E.saves,saveType)){const saveName=game.i18n.localize(CONFIG.PF2E.saves[saveType]);button.innerText=game.i18n.format("PF2E.SavingThrowWithName",{saveName})}}else if(!document2?.hasPlayerOwner&&!dcSetting)for(const button of saveButtons)button.classList.add("hidden-to-others");for(const element of htmlQueryAll(html,"[data-owner-title]"))if(hasOwnership){const value=element.dataset.ownerTitle??"";element.title=value}else element.removeAttribute("data-owner-title");if(!game.user.isGM)for(const element of visibilityElements.filter(e=>e.dataset.visibility==="gm"))element.remove()}static processMessageSender(message,html){if(!game.settings.get("pf2e","metagame_tokenSetsNameVisibility"))return;const token=message.token??(message.actor?new TokenDocumentPF2e(message.actor.prototypeToken.toObject()):null);if(token){const sender=html.querySelector("h4.message-sender"),nameToHide=token.name.trim(),shouldHideName=!token.playersCanSeeName&&sender?.innerText.trim()===nameToHide;sender&&shouldHideName&&(game.user.isGM?sender.dataset.visibility="gm":sender.innerText=message.user?.name??"Gamemaster")}}};__name2(_UserVisibilityPF2e,"UserVisibilityPF2e");let UserVisibilityPF2e=_UserVisibilityPF2e;const USER_VISIBILITIES=new Set(["all","owner","gm","none"]),_ItemSummaryRenderer=class{static{__name(this,"_ItemSummaryRenderer")}constructor(sheet){this.sheet=sheet}activateListeners(html){const selectors=[".item .item-name h4",".item .melee-name h4",".item .action-name h4","a[data-action=toggle-summary]"].join(",");for(const link of htmlQueryAll(html,selectors))link.addEventListener("click",async()=>{const element=htmlClosest(link,"[data-item-id], .expandable");element&&await this.toggleSummary(element)})}async toggleSummary(element,options={}){const actor=this.sheet.actor,{itemId,itemType,actionIndex}=element.dataset,isFormula=!!element.dataset.isFormula,duration=.4;if(itemType==="spellSlot")return;const item=isFormula?await fromUuid(itemId??""):itemType==="condition"?actor.conditions.get(itemId,{strict:!0}):actionIndex?actor.system.actions?.[Number(actionIndex)].item??null:actor.items.get(itemId??"")??null,summary=await(async()=>{const existing=htmlQuery(element,":scope > .item-summary");if(existing?.hasChildNodes()||options.visible)return existing;if(item instanceof ItemPF2e&&!item.isOfType("spellcastingEntry")){const insertLocation=htmlQueryAll(element,":scope > .item-name, :scope > .item-controls, :scope > .action-header").at(-1)?.parentNode?.lastChild;if(!insertLocation&&!existing)return null;const summary2=existing??createHTMLElement("div",{classes:["item-summary"]});summary2.hidden=!0,insertLocation?.after(summary2);const chatData=await item.getChatData({secrets:actor.isOwner},element.dataset);return await this.renderItemSummary(summary2,item,chatData),InlineRollLinks.listen(summary2,item),summary2}return null})();if(!summary)return;const showSummary=typeof options.visible=="boolean"?options.visible:!element.classList.contains("expanded")||summary.hidden;options.instant?(summary.hidden=!showSummary,element.classList.toggle("expanded",showSummary)):showSummary?(element.classList.add("expanded"),await gsap.fromTo(summary,{height:0,opacity:0,hidden:!1},{height:"auto",opacity:1,duration})):await gsap.to(summary,{height:0,duration,opacity:0,paddingTop:0,paddingBottom:0,margin:0,clearProps:"all",onComplete:()=>{summary.hidden=!0,element.classList.remove("expanded")}})}async renderItemSummary(div,item,chatData){const description=isItemSystemData(chatData)?chatData.description.value:await TextEditor.enrichHTML(item.description,{rollData:item.getRollData(),async:!0}),rarity=item.system.traits?.rarity,isEffect=item instanceof AbstractEffectPF2e,selfEffect=item.isOfType("action","feat")&&item.system.selfEffect?await TextEditor.enrichHTML(`@UUID[${item.system.selfEffect.uuid}]{${item.system.selfEffect.name}}`,{async:!0}):null,summary=await renderTemplate("systems/pf2e/templates/actors/partials/item-summary.hbs",{item,description,identified:game.user.isGM||!(item.isOfType("physical")||isEffect)||item.isIdentified,rarityLabel:rarity&&item.isOfType("physical")?CONFIG.PF2E.rarityTraits[rarity]:null,isCreature:item.actor?.isOfType("creature"),chatData,selfEffect});if(div.innerHTML=summary,UserVisibilityPF2e.process(div,{document:item}),item.actor?.isOfType("creature"))for(const button of htmlQueryAll(div,"button"))button.addEventListener("click",event=>{event.preventDefault(),event.stopPropagation();const spell=item.isOfType("spell")?item:item.isOfType("consumable")?item.embeddedSpell:null;switch(button.dataset.action){case"spellAttack":spell?.rollAttack(event);break;case"spellDamage":spell?.rollDamage(event);break;case"consume":item.isOfType("consumable")&&item.consume();break}})}async saveAndRestoreState(callback){const element=this.sheet.element[0],expandedSummaryElements=htmlQueryAll(element,".item.expanded[data-item-summary-id]"),expandedItemElements=htmlQueryAll(element,".item.expanded[data-item-id]:not([data-item-summary-id])"),expandedActionElements=htmlQueryAll(element,".item.expanded[data-action-index]"),openActionIdxs=new Set(expandedActionElements.map(el=>el.dataset.actionIndex)),openItemsIds=expandedItemElements.map(el=>el.dataset.itemId),openSummaryIds=expandedSummaryElements.map(el=>el.dataset.itemSummaryId),$result=await callback.apply(null),result=$result[0];InlineRollLinks.listen(result,this.sheet.actor);for(const itemId of openItemsIds){const item=htmlQuery(result,`.item[data-item-id="${itemId}"]:not([data-item-summary-id])`);item&&await this.toggleSummary(item,{instant:!0})}for(const summaryId of openSummaryIds){const item=htmlQuery(result,`.item[data-item-summary-id="${summaryId}"]`);item&&await this.toggleSummary(item,{instant:!0})}for(const elementIdx of openActionIdxs)$result.find(`.item[data-action-index=${elementIdx}]`).toggleClass("expanded");return $result}};__name2(_ItemSummaryRenderer,"ItemSummaryRenderer");let ItemSummaryRenderer=_ItemSummaryRenderer;const _MoveLootPopup=class extends FormApplication{static{__name(this,"_MoveLootPopup")}onSubmitCallback;constructor(object,options,callback){super(object,options),this.onSubmitCallback=callback}async getData(){const[prompt,buttonLabel]=this.options.isPurchase?["PF2E.loot.PurchaseLootMessage","PF2E.loot.PurchaseLoot"]:["PF2E.loot.MoveLootMessage","PF2E.loot.MoveLoot"];return{...await super.getData(),quantity:{default:this.options.quantity.default,max:this.options.quantity.max},newStack:this.options.newStack,lockStack:this.options.lockStack,prompt,buttonLabel}}static get defaultOptions(){return{...super.defaultOptions,id:"MoveLootPopup",classes:[],title:game.i18n.localize("PF2E.loot.MoveLootPopupTitle"),template:"systems/pf2e/templates/popups/loot/move-loot-popup.hbs",width:"auto",quantity:{default:1,max:1},newStack:!1,lockStack:!1,isPurchase:!1}}async _updateObject(_event,formData){this.onSubmitCallback(formData.quantity,formData.newStack)}};__name2(_MoveLootPopup,"MoveLootPopup");let MoveLootPopup=_MoveLootPopup;const _AddCoinsPopup=class extends FormApplication{static{__name(this,"_AddCoinsPopup")}static get defaultOptions(){return{...super.defaultOptions,id:"add-coins",title:"PF2E.AddCoinsTitle",template:"systems/pf2e/templates/actors/add-coins.hbs"}}async _updateObject(_event,formData){const combineStacks=!!formData.combineStacks,coins={pp:Number(formData.pp)||0,gp:Number(formData.gp)||0,sp:Number(formData.sp)||0,cp:Number(formData.cp)||0};return this.object.inventory.addCoins(coins,{combineStacks})}};__name2(_AddCoinsPopup,"AddCoinsPopup");let AddCoinsPopup=_AddCoinsPopup;const itemTypeOptions=Object.fromEntries(new Map([["scroll","PF2E.CastingItemCreateDialog.scroll"],["wand","PF2E.CastingItemCreateDialog.wand"],["cantripDeck5","PF2E.CastingItemCreateDialog.cantripDeck5"]])),_CastingItemCreateDialog=class extends FormApplication{static{__name(this,"_CastingItemCreateDialog")}onSubmitCallback;spell;formDataCache;constructor(object,options,callback,spell){super(object,options),this.spell=spell,this.formDataCache={itemType:this.spell.isCantrip?"cantripDeck5":"scroll",level:spell.baseRank},this.onSubmitCallback=callback}static get defaultOptions(){const options=super.defaultOptions;return options.classes=[],options.title=game.i18n.localize("PF2E.CastingItemCreateDialog.title"),options.template="systems/pf2e/templates/popups/casting-item-create-dialog.hbs",options.width="auto",options.submitOnChange=!0,options.closeOnSubmit=!1,options}async getData(){if(!this.spell)throw ErrorPF2e("CastingItemCreateDialog | Could not read spelldata");const{cantripDeck5,...nonCantripOptions}=itemTypeOptions,minimumRank=this.spell.baseRank,ranks=Array.from(Array(11-minimumRank).keys()).map(index=>minimumRank+index);return{...await super.getData(),validLevels:ranks,itemTypeOptions:this.spell.isCantrip?{cantripDeck5}:nonCantripOptions,itemType:this.formDataCache.itemType,level:this.formDataCache.level}}async _updateObject(event,formData){if(Object.assign(this.formDataCache,formData),event.type!=="submit"){await this.render();return}this.formDataCache.itemType==="wand"&&this.formDataCache.level===10?ui.notifications.warn(game.i18n.localize("PF2E.CastingItemCreateDialog.10thLevelWand")):this.onSubmitCallback&&this.spell&&this.onSubmitCallback(this.formDataCache.level,this.formDataCache.itemType,this.spell),this.close()}};__name2(_CastingItemCreateDialog,"CastingItemCreateDialog");let CastingItemCreateDialog=_CastingItemCreateDialog;function getMagicTraditions(item){const traits=item.system.traits.value;return new Set(traits.filter(t=>setHasElement(MAGIC_TRADITIONS,t)))}__name(getMagicTraditions,"getMagicTraditions"),__name2(getMagicTraditions,"getMagicTraditions");function getDcRarity(item){return item.traits.has("cursed")?"unique":item.rarity}__name(getDcRarity,"getDcRarity"),__name2(getDcRarity,"getDcRarity");function getIdentifyMagicDCs(item,baseDC,notMatchingTraditionModifier){const result={occult:baseDC,primal:baseDC,divine:baseDC,arcane:baseDC},traditions=getMagicTraditions(item);for(const key of MAGIC_TRADITIONS)traditions.size>0&&!traditions.has(key)&&(result[key]=baseDC+notMatchingTraditionModifier);return{arcana:result.arcane,nature:result.primal,religion:result.divine,occultism:result.occult}}__name(getIdentifyMagicDCs,"getIdentifyMagicDCs"),__name2(getIdentifyMagicDCs,"getIdentifyMagicDCs");function getItemIdentificationDCs(item,{proficiencyWithoutLevel=!1,notMatchingTraditionModifier}){const baseDC=calculateDC(item.level,{proficiencyWithoutLevel}),rarity=getDcRarity(item),dc=adjustDCByRarity(baseDC,rarity);return item.isMagical?getIdentifyMagicDCs(item,dc,notMatchingTraditionModifier):item.isAlchemical?{crafting:dc}:{dc}}__name(getItemIdentificationDCs,"getItemIdentificationDCs"),__name2(getItemIdentificationDCs,"getItemIdentificationDCs");function getUnidentifiedPlaceholderImage(item){return`systems/pf2e/icons/unidentified_item_icons/${(()=>{if(item.isOfType("weapon")){const{traits}=item;return traits.has("bomb")?"alchemical_bomb":traits.has("staff")?"staves":traits.has("artifact")?"artifact":"weapon"}else{if(item.isOfType("armor"))return item.category==="shield"?"shields":"armor";if(item.isOfType("consumable"))switch(item.category){case"ammo":return"ammunition";case"oil":return"oils";case"scroll":return"infernal-contracts";case"talisman":return"talisman";case"elixir":case"mutagen":return"alchemical_elixir";case"poison":return"alchemical_poison";case"tool":return"alchemical_tool";case"wand":return"wands";case"potion":return"potions";case"snare":case"other":default:return item.traits.has("drug")?"drugs":"other-consumables"}else if(item.isOfType("equipment")&&item.traits.has("precious"))return"material-chunk"}return"adventuring_gear"})()}.webp`}__name(getUnidentifiedPlaceholderImage,"getUnidentifiedPlaceholderImage"),__name2(getUnidentifiedPlaceholderImage,"getUnidentifiedPlaceholderImage");const _IdentifyItemPopup=class extends FormApplication{static{__name(this,"_IdentifyItemPopup")}static get defaultOptions(){return{...super.defaultOptions,id:"identify-item",title:game.i18n.localize("PF2E.identification.Identify"),template:"systems/pf2e/templates/actors/identify-item.hbs",width:"auto",classes:["identify-popup"]}}get item(){return this.object}async getData(){const item=this.object,notMatchingTraditionModifier=game.settings.get("pf2e","identifyMagicNotMatchingTraditionModifier"),proficiencyWithoutLevel=game.settings.get("pf2e","proficiencyVariant"),dcs=getItemIdentificationDCs(item,{proficiencyWithoutLevel,notMatchingTraditionModifier});return{...await super.getData(),isMagic:item.isMagical,isAlchemical:item.isAlchemical,dcs}}activateListeners($form){$form.find("button.update-identification").on("click",event=>{const $button=$(event.delegateTarget);this.submit({updateData:{status:$button.val()}})}),$form.find("button.post-skill-checks").on("click",async()=>{const item=this.item,itemImg=item.system.identification.unidentified.img,itemName=item.system.identification.unidentified.name,identifiedName=item.system.identification.identified.name,skills=$("div#identify-item").find("tr").toArray().flatMap(row=>{const slug=row.dataset.skill,dc=Number(row.dataset.dc);if(!(Number.isInteger(dc)&&objectHasKey(CONFIG.PF2E.skillList,slug)))return[];const name2=game.i18n.localize(CONFIG.PF2E.skillList[slug]);return{slug,name:name2,dc}}),actionOption=item.isMagical?"action:identify-magic":item.isAlchemical?"action:identify-alchemy":null,content=await renderTemplate("systems/pf2e/templates/actors/identify-item-chat-skill-checks.hbs",{itemImg,itemName,identifiedName,rollOptions:compact(["concentrate","exploration","secret",actionOption]),skills});await ChatMessagePF2e.create({user:game.user.id,content})})}async _updateObject(_event,formData){const status=formData.status;status==="identified"&&await this.item.setIdentificationStatus(status)}};__name2(_IdentifyItemPopup,"IdentifyItemPopup");let IdentifyItemPopup=_IdentifyItemPopup;const _IWREditor=class extends DocumentSheet{static{__name(this,"_IWREditor")}constructor(actor,options){if(super(actor,options),__privateAdd(this,_updateIWR),__publicField(this,"category"),__publicField(this,"types"),this.actor.isOfType("familiar","loot"))throw ErrorPF2e(`Actor ${this.actor.name} (${this.actor.uuid}) may not have stored IWR data`);this.category=options.category,this.types={immunities:omit(CONFIG.PF2E.immunityTypes,["custom"]),weaknesses:omit(CONFIG.PF2E.weaknessTypes,["custom"]),resistances:omit(CONFIG.PF2E.resistanceTypes,["custom"])}[this.category]}static get defaultOptions(){return{...super.defaultOptions,closeOnSubmit:!1,classes:["iwr-editor"],template:"systems/pf2e/templates/actors/iwr-editor.hbs",sheetConfig:!1,width:500,height:"auto"}}get id(){return`${this.category}-editor-${this.actor.uuid}`}get title(){return game.i18n.format("PF2E.Actor.IWREditor.Title",{actor:this.actor.name,category:game.i18n.localize(this.categoryLabel)})}get actor(){return this.document}get categoryLabel(){return{immunities:"PF2E.ImmunitiesLabel",weaknesses:"PF2E.WeaknessesLabel",resistances:"PF2E.ResistancesLabel"}[this.category]}async getData(options={}){return this.options.id=this.id,{...await super.getData(options),category:this.category,header:this.categoryLabel,list:this.actor.attributes[this.category],sourceData:this.actor._source.system.attributes?.[this.category]??[],types:this.types}}getUpdatedData({includeNew=!1}={}){const entryElems=htmlQueryAll(this.element[0],".entry:not(.new,[data-synthetic])");return includeNew&&entryElems.push(...htmlQueryAll(this.element[0],".entry.new")),entryElems.flatMap(entryElem=>{const iwrType=htmlQuery(entryElem,"select")?.value;if(!iwrType)return[];const value=Math.trunc(Math.abs(Number(htmlQuery(entryElem,"input[data-property=value]")?.value??"NaN")))||5,exceptionsData=JSON.parse(htmlQuery(entryElem,"input[data-property=exceptions]")?.value||"[]");if(!(Array.isArray(exceptionsData)&&exceptionsData.every(o=>isObject(o))))throw ErrorPF2e("Unexpected data encountered while submitting form");const exceptions=exceptionsData.map(e=>e.id),doubleVsData=JSON.parse(htmlQuery(entryElem,"input[data-property=doubleVs]")?.value||"[]"),doubleVs=Array.isArray(doubleVsData)&&doubleVsData.every(o=>isObject(o)&&typeof o.id=="string"&&o.id in this.types)&&this.category==="resistances"?doubleVsData.map(d=>d.id):void 0;return exceptions.every(e=>typeof e=="string")?{type:iwrType,value:this.category==="immunities"?void 0:value||1,exceptions,doubleVs}:[]})}_getHeaderButtons(){return super._getHeaderButtons().filter(b=>b.class==="close")}activateListeners($html){const html=$html[0];for(const input of htmlQueryAll(html,"input[type=text]"))tagify$1(input,{whitelist:this.types,maxTags:4});htmlQuery(html,"a[data-action=add]")?.addEventListener("click",event=>{const entryElem=htmlClosest(event.target,".entry.new");htmlQuery(entryElem,"select[data-property=type]")?.value&&__privateMethod(this,_updateIWR,updateIWR_fn).call(this,{includeNew:!0})});for(const inputOrSelect of htmlQueryAll(html,"select, input")){const entryElem=htmlClosest(inputOrSelect,".entry");entryElem&&!entryElem.classList.contains("new")&&inputOrSelect.addEventListener("change",()=>{__privateMethod(this,_updateIWR,updateIWR_fn).call(this)})}for(const removeButton of htmlQueryAll(html,"a[data-action=remove]"))removeButton.addEventListener("click",async event=>{htmlClosest(event.target,".entry")?.remove(),__privateMethod(this,_updateIWR,updateIWR_fn).call(this)})}};_updateIWR=new WeakSet,updateIWR_fn=__name2(async function({includeNew=!1}={}){const data=this.getUpdatedData({includeNew}),formInput=htmlQuery(this.element[0],"input[name]");if(!formInput)throw ErrorPF2e("Unexpected error getting for input element");formInput.value=JSON.stringify(data),await this.submit({preventRender:!1})},"#updateIWR"),__name2(_IWREditor,"IWREditor");let IWREditor=_IWREditor;const _RemoveCoinsPopup=class extends FormApplication{static{__name(this,"_RemoveCoinsPopup")}static get defaultOptions(){return{...super.defaultOptions,id:"remove-coins",title:"PF2E.RemoveCoinsTitle",template:"systems/pf2e/templates/actors/remove-coins.hbs"}}async _updateObject(_event,formData){const actor=this.object,coinsToRemove={pp:Number(formData.pp)||0,gp:Number(formData.gp)||0,sp:Number(formData.sp)||0,cp:Number(formData.cp)||0};await actor.inventory.removeCoins(coinsToRemove,{byValue:!!formData.removeByValue})||ui.notifications.warn("PF2E.ErrorMessage.NotEnoughCoins",{localize:!0})}};__name2(_RemoveCoinsPopup,"RemoveCoinsPopup");let RemoveCoinsPopup=_RemoveCoinsPopup;const _ActorSheetPF2e=class _ActorSheetPF2e2 extends ActorSheet{static{__name(this,"_ActorSheetPF2e")}constructor(){super(...arguments),__privateAdd(this,_activateInventoryDragDrop),__privateAdd(this,_sortableOnMove),__privateAdd(this,_sortableOnEnd),__privateAdd(this,_onClickDeleteItem),__privateAdd(this,_onClickBrowseEquipment),__privateAdd(this,_onClickCreateItem),__privateAdd(this,_onClickSellAllTreasure),__publicField(this,"itemRenderer",new ItemSummaryRenderer(this)),__privateAdd(this,_sortableOnMoveData,{})}static get defaultOptions(){const options=super.defaultOptions;return options.dragDrop=[{dragSelector:"[data-foundry-list] .drag-handle"},{dragSelector:".item[draggable=true]"},{dragSelector:".item-list .item:not(.inventory-list *)"}],mergeObject(options,{classes:["default","sheet","actor"],scrollY:[".sheet-sidebar",".tab.active",".inventory-list"]})}get isLootSheet(){return!1}async getData(options=this.options){options.id||=this.id,options.editable=this.isEditable,options.sheetConfig&&=Object.values(CONFIG.Actor.sheetClasses[this.actor.type]).filter(c=>c.canConfigure).length>1;for(const item of[...this.actor.itemTypes.action,...this.actor.itemTypes.feat])item.system.selfEffect&&(item.system.selfEffect.img??=fromUuidSync(item.system.selfEffect.uuid)?.img??null);const actorData=this.actor.toObject(!1),iwrKeys=["immunities","weaknesses","resistances"],attributes=actorData.system.attributes;for(const key of iwrKeys)attributes[key]=[...attributes[key]].sort((a,b)=>a.label.localeCompare(b.label));const coins=this.actor.inventory.coins,totalCoinage=_ActorSheetPF2e2.coinsToSheetData(coins),totalCoinageGold=(coins.copperValue/100).toFixed(2),totalWealth=this.actor.inventory.totalWealth,totalWealthGold=(totalWealth.copperValue/100).toFixed(2),traitsMap=(()=>{switch(this.actor.type){case"hazard":return CONFIG.PF2E.hazardTraits;case"vehicle":return CONFIG.PF2E.vehicleTraits;default:return CONFIG.PF2E.creatureTraits}})(),sheetData={cssClass:this.actor.isOwner?"editable":"locked",editable:this.isEditable,document:this.actor,limited:this.actor.limited,options,owner:this.actor.isOwner,title:this.title,actor:actorData,data:actorData.system,effects:[],items:actorData.items,user:{isGM:game.user.isGM},traits:createSheetTags(traitsMap,{value:Array.from(this.actor.traits)}),toggles:this.actor.synthetics.toggles,isTargetFlatFooted:!!this.actor.rollOptions.all["target:condition:off-guard"],totalCoinage,totalCoinageGold,totalWealth,totalWealthGold,inventory:this.prepareInventory(),enrichedContent:{}};return await this.prepareItems?.(sheetData),sheetData}prepareInventory(){const sections={weapon:{label:game.i18n.localize("PF2E.InventoryWeaponsHeader"),type:"weapon",items:[]},armor:{label:game.i18n.localize("PF2E.InventoryArmorHeader"),type:"armor",items:[]},equipment:{label:game.i18n.localize("PF2E.InventoryEquipmentHeader"),type:"equipment",items:[]},consumable:{label:game.i18n.localize("PF2E.InventoryConsumablesHeader"),type:"consumable",items:[]},treasure:{label:game.i18n.localize("PF2E.InventoryTreasureHeader"),type:"treasure",items:[]},backpack:{label:game.i18n.localize("PF2E.InventoryBackpackHeader"),type:"backpack",items:[]}};for(const item of this.actor.inventory.contents.sort((a,b)=>(a.sort||0)-(b.sort||0))){if(!objectHasKey(sections,item.type)||item.isInContainer)continue;(item.isOfType("book")?sections.equipment:sections[item.type]).items.push(this.prepareInventoryItem(item))}return{sections,bulk:this.actor.inventory.bulk,showValueAlways:this.actor.isOfType("npc","loot","party"),showIndividualPricing:this.actor.isOfType("loot"),hasStowingContainers:this.actor.itemTypes.backpack.some(c=>c.system.stowing&&!c.isInContainer),invested:this.actor.inventory.invested}}prepareInventoryItem(item){const editable=game.user.isGM||item.isIdentified,heldItems=item.isOfType("backpack")?item.contents.map(i=>this.prepareInventoryItem(i)):void 0;heldItems?.sort((a,b)=>(a.item.sort||0)-(b.item.sort||0));const actorSize=new ActorSizePF2e({value:this.actor.size}),itemSize=new ActorSizePF2e({value:item.size}),sizeDifference=itemSize.difference(actorSize,{smallIsMedium:!0}),canBeEquipped=!item.isInContainer;return{item,itemSize:sizeDifference!==0?itemSize:null,editable,isContainer:item.isOfType("backpack"),canBeEquipped,isInvestable:!1,isSellable:editable&&item.isOfType("treasure")&&!item.isCoinage,hasCharges:item.isOfType("consumable")&&item.uses.max>0,heldItems}}static coinsToSheetData(coins){return DENOMINATIONS.reduce((accumulated,d)=>({...accumulated,[d]:{value:coins[d],label:CONFIG.PF2E.currencies[d]}}),{})}getStrikeFromDOM(button){const actionIndex=Number(htmlClosest(button,"[data-action-index]")?.dataset.actionIndex??"NaN"),rootAction=this.actor.system.actions?.at(actionIndex)??null,altUsage=tupleHasValue(["thrown","melee"],button?.dataset.altUsage)?button?.dataset.altUsage:null;return altUsage?rootAction?.altUsages?.find(s=>altUsage==="thrown"?s.item.isThrown:s.item.isMelee)??null:rootAction}activateListeners($html){super.activateListeners($html);const html=$html[0];this.itemRenderer.activateListeners(html),htmlQuery(html,"a[data-action=show-image]")?.addEventListener("click",()=>{const actor=this.actor,title=actor.token?.name??actor.prototypeToken?.name??actor.name;new ImagePopout(actor.img,{title,uuid:actor.uuid}).render(!0)});const inventoryPanel=(()=>{const selector=this.actor.isOfType("loot")?".sheet-body":".tab[data-tab=inventory]";return htmlQuery(html,selector)})();this.activateInventoryListeners(inventoryPanel);for(const element of htmlQueryAll(html,".item[data-item-id] .item-image, .item[data-item-id] .item-chat"))element.addEventListener("click",async event=>{const itemId=htmlClosest(element,"[data-item-id]")?.dataset.itemId??"",[item,fromFormula]=(()=>{if(UUIDUtils.isItemUUID(itemId)){if("knownFormulas"in this&&isObject(this.knownFormulas)){const formula=this.knownFormulas[itemId];if(formula)return[new ItemProxyPF2e(formula.item.toObject(),{parent:this.actor}),!0]}throw ErrorPF2e(`Invalid UUID [${itemId}]!`)}return[this.actor.items.get(itemId,{strict:!0}),!1]})();(!item.isOfType("physical")||item.isIdentified)&&await item.toMessage(event,{create:!0,data:{fromFormula}})});if(!this.options.editable)return;const manualPropertyInputs=htmlQueryAll(html,"select[data-property],input[data-property]");for(const input of manualPropertyInputs)input.addEventListener("focus",()=>{const propertyPath=input.dataset.property??"";if(input.name=propertyPath,input instanceof HTMLInputElement){const baseValue=Math.trunc(Number(getProperty(this.actor._source,propertyPath))||0);input.value=baseValue.toString(),input.type==="text"&&input.dataset.dtype==="Number"&&(input.type="number")}}),input.addEventListener("blur",()=>{input.removeAttribute("name");const propertyPath=input.dataset.property??"",preparedValue=Number(getProperty(this.actor,propertyPath))||0,baseValue=Math.trunc(Number(getProperty(this.actor._source,propertyPath))||0),newValue=Math.trunc(Number(input.value));input instanceof HTMLInputElement&&(input.type==="number"&&input.dataset.dtype==="Number"&&(input.type="text"),baseValue===newValue&&(input.value=input.classList.contains("modifier")?signedInteger(preparedValue):String(preparedValue)))});for(const link of htmlQueryAll(html,".item-delete"))link.addEventListener("click",event=>__privateMethod(this,_onClickDeleteItem,onClickDeleteItem_fn).call(this,event));for(const link of htmlQueryAll(html,".inventory-browse"))link.addEventListener("click",()=>__privateMethod(this,_onClickBrowseEquipment,onClickBrowseEquipment_fn).call(this,link));for(const link of htmlQueryAll(html,".save-name"))link.addEventListener("click",event=>{const saveType=htmlClosest(link,"[data-save]")?.dataset.save;if(!tupleHasValue(SAVE_TYPES,saveType))throw ErrorPF2e(`"${saveType}" is not a recognized save type`);this.actor.saves?.[saveType]?.check.roll(eventToRollParams(event))});const rollInitElem=htmlQuery(html,".roll-init");rollInitElem?.addEventListener("click",event=>{!rollInitElem.classList.contains("disabled")&&this.actor.initiative&&this.actor.initiative.roll(eventToRollParams(event))}),htmlQuery(html,".actions-options")?.addEventListener("change",event=>{const toggleRow=htmlClosest(event.target,"[data-item-id][data-domain][data-option]"),checkbox=htmlQuery(toggleRow,"input[data-action=toggle-roll-option]"),suboptionsSelect=htmlQuery(toggleRow,"select[data-action=set-suboption"),{domain,option,itemId}=toggleRow?.dataset??{},suboption=suboptionsSelect?.value??null;checkbox&&domain&&option&&this.actor.toggleRollOption(domain,option,itemId??null,checkbox.checked,suboption)});for(const listName of["immunities","weaknesses","resistances"])htmlQuery(html,`a[data-action=edit-${listName}]`)?.addEventListener("click",()=>{new IWREditor(this.actor,{category:listName}).render(!0)});for(const strikeElem of htmlQueryAll(html,"ol.strikes-list > li[data-strike]")){const attackSelectors=".item-image[data-action=strike-attack], button[data-action=strike-attack]";for(const button of htmlQueryAll(strikeElem,attackSelectors))button.addEventListener("click",async event=>{if(!Array.isArray(this.actor.system.actions))throw ErrorPF2e("Strikes are not supported on this actor");const altUsage=tupleHasValue(["thrown","melee"],button.dataset.altUsage)?button.dataset.altUsage:null,strike=this.getStrikeFromDOM(button),variantIndex=Number(button.dataset.variantIndex);await strike?.variants[variantIndex]?.roll({event,altUsage})});const damageSelectors="button[data-action=strike-damage], button[data-action=strike-critical]";for(const button of htmlQueryAll(strikeElem,damageSelectors)){const strike=this.getStrikeFromDOM(button),method=button.dataset.action==="strike-damage"?"damage":"critical";button.addEventListener("click",async event=>{await strike?.[method]?.({event})});const altUsage=tupleHasValue(["thrown","melee"],button.dataset.altUsage)?button.dataset.altUsage:null;strike?.[method]?.({getFormula:!0,altUsage}).then(formula=>{formula&&(button.title=formula.toString(),$(button).tooltipster({position:"top",theme:"crb-hover"}))})}}for(const button of htmlQueryAll(html,"button[data-action=use-action]"))button.addEventListener("click",()=>{const itemId=htmlClosest(button,"[data-item-id]")?.dataset.itemId,item=this.actor.items.get(itemId,{strict:!0});item.isOfType("action","feat")&&createSelfEffectMessage(item)});for(const anchor of htmlQueryAll(html,".item-unprepare"))anchor.addEventListener("click",()=>{const row=htmlClosest(anchor,".item"),slotLevel=Number(row?.dataset.slotLevel)||0,slotId=Number(row?.dataset.slotId)||0,entryId=row?.dataset.entryId??"";this.actor.spellcasting.collections.get(entryId)?.unprepareSpell(slotLevel,slotId)});for(const anchor of htmlQueryAll(html,".item-toggle-prepare"))anchor.addEventListener("click",()=>{const row=htmlClosest(anchor,".item"),slotLevel=Number(row?.dataset.slotLevel)||0,slotId=Number(row?.dataset.slotId)||0,entryId=row?.dataset.entryId??"",expendedState=row?.dataset.expendedState!=="true";this.actor.spellcasting.collections.get(entryId)?.setSlotExpendedState(slotLevel,slotId,expendedState)});for(const link of htmlQueryAll(html,".tag-selector"))link.addEventListener("click",()=>this.openTagSelector(link));for(const link of htmlQueryAll(html,".item-create, .item-control.spell-create"))link.addEventListener("click",()=>__privateMethod(this,_onClickCreateItem,onClickCreateItem_fn).call(this,link));for(const anchor of htmlQueryAll(html,".item-edit"))anchor.addEventListener("click",()=>{const itemId=htmlClosest(anchor,"[data-item-id]")?.dataset.itemId;this.actor.items.get(itemId??"")?.sheet.render(!0,{focus:!0})});for(const effectDecrement of htmlQueryAll(html,".effects-list .decrement"))effectDecrement.addEventListener("click",event=>{const parent=htmlClosest(event.currentTarget,".item"),effect=this.actor.items.get(parent?.dataset.itemId??"");effect instanceof AbstractEffectPF2e&&effect.decrease()});for(const effectIncrement of htmlQueryAll(html,".effects-list .increment"))effectIncrement.addEventListener("click",event=>{const parent=htmlClosest(event.currentTarget,".item"),effect=this.actor?.items.get(parent?.dataset.itemId??"");effect instanceof AbstractEffectPF2e&&effect.increase()});for(const element of htmlQueryAll(html,".effects-list [data-action=effect-toggle-unidentified]")??[])element.addEventListener("click",async event=>{const effectId=htmlClosest(event.currentTarget,"[data-item-id]")?.dataset.itemId,effect=this.actor.items.get(effectId,{strict:!0});if(effect.isOfType("effect")){const isUnidentified=effect.system.unidentified;await effect.update({"system.unidentified":!isUnidentified})}});for(const inputElem of htmlQueryAll(html,"input[type=text], input[type=number]"))inputElem.addEventListener("focus",()=>{inputElem.select()});for(const deltaInput of htmlQueryAll(html,"input[data-allow-delta]"))deltaInput.addEventListener("input",()=>{const match=/[+-]?\d*/.exec(deltaInput.value)?.at(0);deltaInput.value=match??deltaInput.value})}activateInventoryListeners(panel){if(this._canDragDrop(".item-list")&&__privateMethod(this,_activateInventoryDragDrop,activateInventoryDragDrop_fn).call(this,panel),!!this.isEditable){panel?.addEventListener("click",event=>{const link=htmlClosest(event.target,"a[data-action], button[data-action]");if(!link)return;const getItem=__name2(()=>{const itemId=htmlClosest(link,".item")?.dataset.itemId??"",item=this.actor.items.get(itemId);if(!item?.isOfType("physical"))throw ErrorPF2e("Item not found or isn't physical");return item},"getItem");switch(link.dataset.action){case"add-coins":{new AddCoinsPopup(this.actor).render(!0);return}case"remove-coins":{new RemoveCoinsPopup(this.actor).render(!0);return}case"increase-quantity":{const item=getItem(),addend=event.ctrlKey?10:event.shiftKey?5:1;item.update({"system.quantity":item.quantity+addend});return}case"decrease-quantity":{const item=getItem();if(item.quantity>0){const subtrahend=Math.min(item.quantity,event.ctrlKey?10:event.shiftKey?5:1);item.update({"system.quantity":item.quantity-subtrahend})}return}case"repair":{const item=getItem();game.pf2e.actions.repair({event,item});return}case"toggle-identified":{const item=getItem();item.isIdentified?item.setIdentificationStatus("unidentified"):new IdentifyItemPopup(item).render(!0);return}case"toggle-container":{const item=getItem();if(!item.isOfType("backpack"))return;const isCollapsed=item.system.collapsed??!1;item.update({"system.collapsed":!isCollapsed});return}case"sell-treasure":{const item=getItem(),sellItem=__name2(async()=>{item?.isOfType("treasure")&&!item.isCoinage&&(await item.delete(),await this.actor.inventory.addCoins(item.assetValue))},"sellItem");if(event.ctrlKey){sellItem();return}const content=document.createElement("p");content.innerText=game.i18n.format("PF2E.SellItemQuestion",{item:item.name}),new Dialog({title:game.i18n.localize("PF2E.SellItemConfirmHeader"),content:content.outerHTML,buttons:{Yes:{icon:fontAwesomeIcon("check").outerHTML,label:game.i18n.localize("Yes"),callback:sellItem},cancel:{icon:fontAwesomeIcon("times").outerHTML,label:game.i18n.localize("Cancel")}},default:"Yes"}).render(!0);return}case"sell-all-treasure":__privateMethod(this,_onClickSellAllTreasure,onClickSellAllTreasure_fn).call(this)}});for(const anchor of htmlQueryAll(panel,".carry-type-hover"))$(anchor).tooltipster({animation:"fade",delay:200,animationDuration:10,trigger:"click",arrow:!1,contentAsHTML:!0,debug:!1,interactive:!0,side:["bottom"],theme:"crb-hover",minWidth:120})}}async deleteItem(element,item,event){(event?.ctrlKey||await Dialog.confirm({title:game.i18n.localize("PF2E.DeleteItemTitle"),content:`

${game.i18n.format("PF2E.DeleteQuestion",{name:`"${item.name}"`})}

`}))&&(await item.delete(),$(element).slideUp(200,()=>this.render(!1)))}_canDragStart(selector){return this.isLootSheet?!0:super._canDragStart(selector)}_canDragDrop(selector){return this.isLootSheet?!0:super._canDragDrop(selector)}_onDragStart(event){if(!(event.target instanceof HTMLElement)||!event.dataTransfer)return;const isContentLink=event.target.classList.contains("content-link"),isPersistent="persistent"in event.target.dataset;if(event.target!==event.currentTarget&&(isContentLink||isPersistent))return;const targetElement=event.currentTarget,previewElement=htmlClosest(targetElement,".item");if(previewElement&&targetElement&&targetElement!==previewElement){const{x,y}=previewElement.getBoundingClientRect();event.dataTransfer.setDragImage(previewElement,event.pageX-x,event.pageY-y)}const itemId=previewElement?.dataset.itemId,item=this.actor.items.get(itemId??""),baseDragData={actorId:this.actor.id,actorUUID:this.actor.uuid,sceneId:canvas.scene?.id??null,tokenId:this.actor.token?.id??null,...item?.toDragData()};previewElement?.dataset.isFormula&&(baseDragData.isFormula=!0,baseDragData.entrySelector=previewElement.dataset.entrySelector);const supplementalData=(()=>{const actionIndex=previewElement?.dataset.actionIndex;if(actionIndex)return"itemType"in baseDragData&&baseDragData.itemType==="melee"?{index:Number(actionIndex)}:{type:"Action",index:Number(actionIndex)};const elementTrait=previewElement?.dataset.element;if(elementTrait)return{type:"Action",elementTrait};const label=previewElement?.innerText.trim(),rollOptionData=previewElement?.dataset??{};return item&&label&&rollOptionData.domain&&rollOptionData.option?{type:"RollOption",label,...rollOptionData}:baseDragData.isFormula?{pf2e:{type:"CraftingFormula",itemUuid:itemId}}:null})();event.dataTransfer.setData("text/plain",JSON.stringify({...baseDragData,...supplementalData}))}async emulateItemDrop(data){const event=new DragEvent("drop",{altKey:game.keyboard.isModifierActive("Alt")});return this._onDropItem(event,data)}async _onDropItem(event,data){event.preventDefault();const item=await ItemPF2e.fromDropData(data);return item?item.actor?.uuid===this.actor.uuid?data.fromInventory?[]:this._onSortItem(event,item.toObject()):item.actor&&item.isOfType("physical")?(await this.moveItemBetweenActors(event,item.actor.id,item.actor?.token?.id??null,this.actor.id,this.actor.token?.id??null,item.id),[item]):this._handleDroppedItem(event,item,data):[]}async _handleDroppedItem(event,item,data){const{actor}=this,itemSource=item.toObject(),mystified=game.user.isGM&&event.altKey;mystified&&itemSource.type==="effect"&&(itemSource.system.unidentified=!0),mystified&&item.isOfType("physical")&&isPhysicalData(itemSource)&&(itemSource.system.identification.unidentified=item.getMystifiedData("unidentified"),itemSource.system.identification.status="unidentified");const containerAttribute=htmlClosest(event.target,".item-container")?.dataset.containerType,dropContainerType=this._tabs[0]?.active==="inventory"&&!containerAttribute?"actorInventory":containerAttribute,craftingTab=this._tabs[0]?.active==="crafting";if(item.isOfType("spell")&&itemSource.type==="spell")return item.isRitual?this._onDropItemCreate(item.clone().toObject()):dropContainerType==="actorInventory"&&itemSource.system.level.value>0?(new CastingItemCreateDialog(actor,{},async(heightenedLevel,itemType,spell)=>{const createdItem=await createConsumableFromSpell(spell,{type:itemType,heightenedLevel,mystified});await this._onDropItemCreate(createdItem)},item).render(!0),[item]):[];if(itemSource.type==="spellcastingEntry")return[];if(itemSource.type==="condition"){const value=data.value;return typeof value=="number"&&itemSource.system.value.isValued&&(itemSource.system.value.value=value),actor.canUserModify(game.user,"update")?[await actor.increaseCondition(itemSource.system.slug,{value})??[]].flat():(ui.notifications.error("PF2E.ErrorMessage.NoUpdatePermission",{localize:!0}),[])}else if(itemIsOfType(itemSource,"affliction","effect")){const{level,value,context}=data;typeof level=="number"&&level>=0&&(itemSource.system.level.value=Math.floor(level)),itemSource.type==="effect"&&itemSource.system.badge?.type==="counter"&&typeof value=="number"&&(itemSource.system.badge.value=value),itemSource.system.context=context??null;const originItem=fromUuidSync(context?.origin.item??"");itemSource.system.traits?.value.length===0&&originItem instanceof SpellPF2e&&itemSource.system.traits.value.push(...originItem.traits)}else if(item.isOfType("physical")&&actor.isOfType("character")&&craftingTab){const actorFormulas=deepClone(actor.system.crafting.formulas);return actorFormulas.some(f=>f.uuid===item.uuid)||(actorFormulas.push({uuid:item.uuid}),await actor.update({"system.crafting.formulas":actorFormulas})),[item]}if(isPhysicalData(itemSource)){const containerId=htmlClosest(event.target,"[data-item-is-container=true]")?.dataset.itemId?.trim()||null;this.actor.itemTypes.backpack.find(container2=>container2.id===containerId)?(itemSource.system.containerId=containerId,itemSource.system.equipped.carryType="stowed"):itemSource.system.equipped.carryType="worn",data?.uuid?.startsWith("Compendium")&&itemSource.type!=="treasure"&&!["med","sm"].includes(actor.size)&&actor.isOfType("creature")&&(itemSource.system.size=actor.size)}return this._onDropItemCreate(new ItemProxyPF2e(itemSource).clone().toObject())}async _onDropFolder(_event,data){if(!(this.actor.isOwner&&data.documentName==="Item"))return[];const folder=await Folder.fromDropData(data);if(!folder)return[];const itemSources=[folder,...folder.getSubfolders()].flatMap(f=>f.contents).map(i=>i.toObject());return this._onDropItemCreate(itemSources)}async moveItemBetweenActors(event,sourceActorId,sourceTokenId,targetActorId,targetTokenId,itemId){const sourceActor=canvas.scene?.tokens.get(sourceTokenId??"")?.actor??game.actors.get(sourceActorId),targetActor=canvas.scene?.tokens.get(targetTokenId??"")?.actor??game.actors.get(targetActorId),item=sourceActor?.items.get(itemId);if(!sourceActor||!targetActor)throw ErrorPF2e("Unexpected missing actor(s)");if(!item?.isOfType("physical"))throw ErrorPF2e("Missing or invalid item");const containerId=htmlClosest(event.target,"[data-item-is-container=true]")?.dataset.containerId?.trim(),sourceItemQuantity=item.quantity,stackable=!!targetActor.inventory.findStackableItem(item._source),isPurchase=sourceActor.isOfType("loot")&&sourceActor.isMerchant&&!sourceActor.isOwner,isAmmunition=item.isOfType("consumable")&&item.isAmmunition;if(sourceItemQuantity>1){const defaultQuantity=isPurchase?isAmmunition?Math.min(10,sourceItemQuantity):1:sourceItemQuantity;new MoveLootPopup(sourceActor,{quantity:{max:sourceItemQuantity,default:defaultQuantity},lockStack:!stackable,isPurchase},(quantity,newStack)=>{sourceActor.transferItemToActor(targetActor,item,quantity,containerId,newStack)}).render(!0)}else sourceActor.transferItemToActor(targetActor,item,1,containerId)}openTagSelector(anchor,options={}){const selectorType=anchor.dataset.tagSelector;if(!tupleHasValue(TAG_SELECTOR_TYPES,selectorType))throw ErrorPF2e(`Unrecognized tag selector type "${selectorType}"`);if(selectorType==="basic"){const objectProperty=anchor.dataset.property??"",title=anchor.dataset.title??"",configTypes=(anchor.dataset.configTypes??"").split(",").map(type=>type.trim()).filter(tag=>tupleHasValue(SELECTABLE_TAG_FIELDS,tag));this.tagSelector("basic",{...options,objectProperty,configTypes,title})}else this.tagSelector(selectorType,options)}tagSelector(selectorType,options){if(selectorType==="basic"&&options&&"objectProperty"in options)new TagSelectorBasic(this.object,options).render(!0);else{if(selectorType==="basic")throw ErrorPF2e("Insufficient options provided to render basic tag selector");{const TagSelector={senses:SenseSelector,"speed-types":SpeedSelector}[selectorType];new TagSelector(this.object,options).render(!0)}}}openTab(name2){this._tabs[0].activate(name2)}async _renderInner(data,options){return this.itemRenderer.saveAndRestoreState(()=>super._renderInner(data,options))}async _render(force,options){await maintainFocusInRender(this,()=>super._render(force,options)),options?.tab&&this.openTab(options.tab)}async _onSubmit(event,{updateData=null,preventClose=!1,preventRender=!1}={}){for(const input of htmlQueryAll(this.form,"tags ~ input"))input.value===""&&(input.value="[]");return super._onSubmit(event,{updateData,preventClose,preventRender})}_getSubmitData(updateData){const data=super._getSubmitData(updateData);processTagifyInSubmitData(this.form,data);for(const el of this.form.elements)if(el instanceof HTMLInputElement&&el.dataset.allowDelta!==void 0){const strValue=el.value.trim(),value=Number(strValue);(strValue.startsWith("+")||strValue.startsWith("-"))&&!Number.isNaN(value)&&(data[el.name]=Number(getProperty(this.actor,el.name))+value)}return data}};_sortableOnMoveData=new WeakMap,_activateInventoryDragDrop=new WeakSet,activateInventoryDragDrop_fn=__name2(function(panel){const inventoryList=htmlQuery(panel,"section.inventory-list, ol[data-container-type=actorInventory]");if(!inventoryList)return;const sortableOptions={...SORTABLE_DEFAULTS,filter:"div.item-summary",preventOnFilter:!1,scroll:inventoryList,setData:(dataTransfer,dragEl)=>{const item=this.actor.inventory.get(htmlQuery(dragEl,"div[data-item-id]")?.dataset.itemId,{strict:!0});dataTransfer.setData("text/plain",JSON.stringify({...item.toDragData(),fromInventory:!0}))},onStart:()=>{__privateSet(this,_sortableOnMoveData,{})},onClone:event=>{for(const link of htmlQueryAll(htmlQuery(event.item,"div.item-summary"),"a.content-link"))link.draggable=!0},onMove:(event,originalEvent)=>__privateMethod(this,_sortableOnMove,sortableOnMove_fn).call(this,event,originalEvent),onEnd:event=>__privateMethod(this,_sortableOnEnd,sortableOnEnd_fn).call(this,event)};for(const list of htmlQueryAll(inventoryList,"ol.inventory-items, ol.item-list")){const itemType=list.dataset.itemType;if(!(list.dataset.containerId||!itemType)){if(itemType==="backpack"){Sortable.create(list,{...sortableOptions,group:{name:"container",put:(_to,_from,dragEl)=>dragEl.dataset.itemType==="backpack"},swapThreshold:.2});for(const subList of htmlQueryAll(list,"ol.container-held-items"))Sortable.create(subList,{...sortableOptions,group:{name:"nested-item",put:!0},swapThreshold:.2});continue}Sortable.create(list,{...sortableOptions,group:{name:itemType,put:(to,from,dragEl)=>from===to?!0:dragEl.dataset.itemType===to.el.dataset.itemType}})}}},"#activateInventoryDragDrop"),_sortableOnMove=new WeakSet,sortableOnMove_fn=__name2(function(event,originalEvent){if(!this.isEditable)return!1;__privateSet(this,_sortableOnMoveData,{related:event.related,willInsertAfter:event.willInsertAfter});const sourceItem=this.actor.inventory.get(htmlQuery(event.dragged,"div[data-item-id]")?.dataset.itemId??""),targetItem=this.actor.inventory.get(htmlClosest(originalEvent.target,"div[data-item-id]")?.dataset.itemId??"");if(sourceItem&&targetItem)return sourceItem.isOfType("backpack")&&targetItem.isOfType("backpack")&&targetItem.isCollapsed?!1:!sourceItem.isStackableWith(targetItem)},"#sortableOnMove"),_sortableOnEnd=new WeakSet,sortableOnEnd_fn=__name2(async function(event){const itemId=htmlQuery(event.item,"div[data-item-id]")?.dataset.itemId,sourceItem=this.actor.inventory.get(itemId,{strict:!0}),targetElement=event.originalEvent?.target instanceof HTMLElement?event.originalEvent.target:null,targetItemId=htmlClosest(targetElement,"div[data-item-id]")?.dataset.itemId??"",targetItem=this.actor.inventory.get(targetItemId);if(!targetItem&&!event.from.contains(targetElement)&&!event.to.contains(targetElement)){if(this.isEditable&&sourceItem.isInContainer&&htmlClosest(targetElement,".inventory-header"))return sourceItem.move({toContainer:null});const itemIsOnlyOneOfType=this.actor.itemTypes[sourceItem.type].length===1;(event.newIndex!==event.oldIndex||itemIsOnlyOneOfType)&&this.render();return}if(!this.isEditable)return;if(targetItem?.isOfType("backpack")&&(!!!htmlClosest(targetElement,"ol[data-container-id]")||targetItem.contents.size===0))return sourceItem.move({toContainer:targetItem});const{related,willInsertAfter}=__privateGet(this,_sortableOnMoveData),relativeItemId=htmlQuery(related,"div[data-item-id]")?.dataset.itemId??"",relativeItem=this.actor.inventory.get(relativeItemId);if(relativeItem||targetItem)return targetItem&&!targetItem.isOfType("backpack")?sourceItem.move({toStack:targetItem}):sourceItem.move({relativeTo:relativeItem,sortBefore:!willInsertAfter})},"#sortableOnEnd"),_onClickDeleteItem=new WeakSet,onClickDeleteItem_fn=__name2(async function(event){const row=htmlClosest(event.currentTarget,"[data-item-id]"),itemId=row?.dataset.itemId,item=this.actor.items.get(itemId??"");if(item?.isOfType("condition")){const references=htmlQuery(row,".condition-references"),deleteCondition=__name2(async()=>{this.actor.decreaseCondition(item,{forceRemove:!0})},"deleteCondition");if(event.ctrlKey){deleteCondition();return}const content=await renderTemplate("systems/pf2e/templates/actors/delete-condition-dialog.hbs",{question:game.i18n.format("PF2E.DeleteQuestion",{name:item.name}),ref:references?.innerHTML});new Dialog({title:game.i18n.localize("PF2E.DeleteConditionTitle"),content,buttons:{Yes:{icon:'',label:"Yes",callback:deleteCondition},cancel:{icon:'',label:"Cancel"}},default:"Yes"}).render(!0)}else if(row&&item)this.deleteItem(row,item,event);else throw ErrorPF2e("Item not found")},"#onClickDeleteItem"),_onClickBrowseEquipment=new WeakSet,onClickBrowseEquipment_fn=__name2(async function(element){const checkboxesFilterCodes=(element.dataset.filter??"").split(",").filter(s=>!!s).map(s=>s.trim()),tab=game.pf2e.compendiumBrowser.tabs.equipment,filter2=await tab.getFilterData(),{checkboxes}=filter2;for(const filterCode of checkboxesFilterCodes){const splitValues=filterCode.split("-");if(splitValues.length!==2)throw ErrorPF2e(`Invalid filter value for opening the compendium browser: "${filterCode}"`);const[filterType,value]=splitValues;if(objectHasKey(checkboxes,filterType)){const checkbox=checkboxes[filterType];objectHasKey(checkbox.options,value)&&(checkbox.options[value].selected=!0,checkbox.selected.push(value),checkbox.isExpanded=!0)}}tab.open(filter2)},"#onClickBrowseEquipment"),_onClickCreateItem=new WeakSet,onClickCreateItem_fn=__name2(function(link){const data=link.dataset;if(!objectHasKey(CONFIG.PF2E.Item.documentClasses,data.type))throw ErrorPF2e(`Unrecognized item type: "${data.type}"`);if(data.type==="spell")return onClickCreateSpell(this.actor,data);const img=`systems/pf2e/icons/default-icons/${data.type}.svg`,type=data.type,itemSource=(()=>{switch(type){case"action":{const name2=game.i18n.localize(`PF2E.ActionType${String(data.actionType).capitalize()}`),actionType=data.actionType;return{type,img,name:name2,system:{actionType:{value:actionType}}}}case"melee":{const name2=game.i18n.localize(`PF2E.NewPlaceholders.${type.capitalize()}`),weaponType=data.actionType;return{type,img,name:name2,system:{weaponType:{value:weaponType}}}}case"lore":{const name2=this.actor.type==="npc"?game.i18n.localize("PF2E.SkillLabel"):game.i18n.localize("PF2E.NewPlaceholders.Lore");return{type,img,name:name2}}default:{if(!setHasElement(PHYSICAL_ITEM_TYPES,type))throw ErrorPF2e(`Unsupported item type: ${type}`);return{name:game.i18n.localize(`PF2E.NewPlaceholders.${data.type.capitalize()}`),type}}}})();if(itemSource){if(data.traits){const traits=String(data.traits).split(",");itemSource.system=mergeObject(itemSource.system??{},{traits:{value:traits}})}this.actor.createEmbeddedDocuments("Item",[itemSource])}},"#onClickCreateItem"),_onClickSellAllTreasure=new WeakSet,onClickSellAllTreasure_fn=__name2(async function(){const content=await renderTemplate("systems/pf2e/templates/actors/sell-all-treasure-dialog.hbs");new Dialog({title:game.i18n.localize("PF2E.SellAllTreasureTitle"),content,buttons:{yes:{icon:fontAwesomeIcon("check").outerHTML,label:"Yes",callback:async()=>this.actor.inventory.sellAllTreasure()},cancel:{icon:fontAwesomeIcon("times").outerHTML,label:"Cancel"}},default:"cancel"}).render(!0)},"#onClickSellAllTreasure"),__name2(_ActorSheetPF2e,"ActorSheetPF2e");let ActorSheetPF2e=_ActorSheetPF2e;const _DamagePF2e=class{static{__name(this,"_DamagePF2e")}static async roll(data,context,callback){const outcome=context.outcome??null;context.rollMode??=(context.secret?"blindroll":void 0)??game.settings.get("core","rollMode"),context.createMessage??=!0,context.options.has("secret")&&(context.secret=!0);const subtitle=outcome?context.sourceType==="attack"?game.i18n.localize(`PF2E.Check.Result.Degree.Attack.${outcome}`):game.i18n.localize(`PF2E.Check.Result.Degree.Check.${outcome}`):null;let flavor=await renderTemplate("systems/pf2e/templates/chat/action/header.hbs",{title:data.name,subtitle});if(data.traits){const toTags=__name2((slugs,{labels={},descriptions={},cssClass,dataAttr})=>slugs.map(s=>({value:s,label:game.i18n.localize(labels[s]??"")})).sort((a,b)=>a.label.localeCompare(b.label)).map(tag=>{const description=descriptions[tag.value]??"",span=document.createElement("span");return span.className="tag",cssClass&&span.classList.add(cssClass),span.dataset[dataAttr]=tag.value,description&&(span.dataset.tooltip=description),span.innerText=tag.label,span.outerHTML}).join(""),"toTags"),traits=toTags(data.traits,{labels:CONFIG.PF2E.actionTraits,descriptions:CONFIG.PF2E.traitsDescriptions,cssClass:null,dataAttr:"trait"}),item2=context.self?.item,itemTraits=item2?.isOfType("weapon","melee","spell")?toTags(Array.from(item2.traits).filter(t=>!(t in CONFIG.PF2E.materialDamageEffects)),{labels:item2.isOfType("spell")?CONFIG.PF2E.spellTraits:CONFIG.PF2E.npcAttackTraits,descriptions:CONFIG.PF2E.traitsDescriptions,cssClass:"tag_alt",dataAttr:"trait"}):"",properties=(()=>{const range=item2?.isOfType("action","melee","weapon")?item2.range:null,label=createActionRangeLabel(range);if(label&&(range?.increment||range?.max)){const slug=range.increment?`range-increment-${range.increment}`:`range-${range.max}`;return toTags([slug],{labels:{[slug]:label},descriptions:{[slug]:"PF2E.Item.Weapon.RangeIncrementN.Hint"},cssClass:"tag_secondary",dataAttr:"slug"})}else return""})(),materialEffects=toTags(data.materials,{labels:CONFIG.PF2E.preciousMaterials,descriptions:CONFIG.PF2E.traitsDescriptions,cssClass:"tag_material",dataAttr:"material"}),otherTags=[itemTraits,properties,materialEffects].join(""),tagsElem=createHTMLElement("div",{classes:["tags"],dataset:{tooltipClass:"pf2e"}});tagsElem.innerHTML=otherTags.length>0?`${traits}
${otherTags}`:traits,flavor+=tagsElem.outerHTML,flavor+=` +
`}const breakdownTags=(Array.isArray(data.damage.breakdown)?data.damage.breakdown:data.damage.breakdown[outcome??"success"]).map(b=>`${b}`);flavor+=`
${breakdownTags.join("")}
`;const roll=await(()=>{const damage=data.damage;if("roll"in damage)return damage.roll.evaluate({async:!0});const formula=deepClone(damage.formula[outcome??"success"]);if(!formula)return ui.notifications.error(game.i18n.format("PF2E.UI.noDamageInfoForOutcome",{outcome})),null;const rollerId=game.userId,degreeOfSuccess=outcome?DEGREE_OF_SUCCESS_STRINGS.indexOf(outcome):null,critRule=game.settings.get("pf2e","critRule")==="doubledamage"?"double-damage":"double-dice",options={rollerId,damage:data,degreeOfSuccess,ignoredResistances:damage.ignoredResistances,critRule};return new DamageRoll(formula,{},options).evaluate({async:!0})})();if(roll===null)return null;const syntheticNotes=context.self?.actor?extractNotes(context.self?.actor.synthetics.rollNotes,context.domains??[]):[],contextNotes=context.notes?.map(n=>n instanceof RollNotePF2e?n:new RollNotePF2e(n))??[],notes=[...syntheticNotes,...contextNotes].filter(n=>(n.outcome.length===0||outcome&&n.outcome.includes(outcome))&&n.predicate.test(context.options)),notesList=RollNotePF2e.notesToHTML(notes);flavor+=notesList.outerHTML;const{self,target}=context,item=self?.item??null,targetFlag=target?{actor:target.actor.uuid,token:target.token.uuid}:null,strike=(()=>{if(item?.isOfType("melee","weapon")&&item&&self?.actor?.isOfType("character","npc")){const strikes=self.actor.system.actions,strike2=strikes.find(a=>a.item?.id===item.id&&a.item.slug===item.slug);if(strike2)return{actor:self.actor.uuid,index:strikes.indexOf(strike2),damaging:!0,name:strike2.item.name,altUsage:item.isOfType("weapon")?item.altUsageType:null}}return null})(),rollMode=context.rollMode??"roll",contextFlag={type:context.type,sourceType:context.sourceType,actor:context.self?.actor.id??null,token:context.self?.token?.id??null,target:targetFlag,domains:context.domains??[],options:Array.from(context.options).sort(),mapIncreases:context.mapIncreases,notes:notes.map(n=>n.toObject()),secret:context.secret??!1,rollMode,traits:context.traits??[],skipDialog:context.skipDialog??!game.user.settings.showRollDialogs,outcome,unadjustedOutcome:context.unadjustedOutcome??null},messageData=await roll.toMessage({speaker:ChatMessagePF2e.getSpeaker({actor:self?.actor,token:self?.token}),flavor,flags:{pf2e:{context:contextFlag,target:targetFlag,modifiers:data.modifiers?.map(m=>m.toObject())??[],origin:item?.getOriginData(),strike,preformatted:"both"}}},{create:!1}),splashRolls=await(async()=>{const splashInstances=roll.instances.map(i=>({damageType:i.type,total:i.componentTotal("splash")})).filter(s=>s.total>0),rolls=[];for(const splash of splashInstances){const formula=`(${splash.total}[splash])[${splash.damageType}]`,roll2=await new DamageRoll(formula).evaluate({async:!0});roll2.options.splashOnly=!0,rolls.push(roll2.toJSON())}return rolls})();return context.createMessage&&(messageData.rolls.push(...splashRolls),await ChatMessagePF2e.create(messageData,{rollMode})),Hooks.callAll("pf2e.damageRoll",roll),callback&&callback(roll),roll}};__name2(_DamagePF2e,"DamagePF2e");let DamagePF2e=_DamagePF2e;const _DamageModifierDialog=class extends Application{static{__name(this,"_DamageModifierDialog")}constructor(params){super(),__privateAdd(this,_getModifierIcon),__privateAdd(this,_getTypeLabel),__privateAdd(this,_applyStackingRules),__publicField(this,"formulaData"),__publicField(this,"context"),__publicField(this,"baseDamageType"),__publicField(this,"isCritical"),__privateAdd(this,_resolve,void 0),__publicField(this,"isRolled",!1),__privateAdd(this,_originallyEnabled,void 0),this.formulaData=params.formulaData,this.context=params.context,this.baseDamageType=params.formulaData.base.at(0)?.damageType??"untyped",this.isCritical=this.context.outcome==="criticalSuccess",__privateSet(this,_originallyEnabled,new Set(this.formulaData.modifiers.filter(m=>m.enabled)))}static get defaultOptions(){return{...super.defaultOptions,template:"systems/pf2e/templates/chat/damage/damage-modifier-dialog.hbs",classes:["roll-modifiers-dialog","damage-dialog","dialog"],popOut:!0,width:440,height:"auto"}}get title(){return this.isCritical?game.i18n.localize("PF2E.Damage.Dialog.CriticalDamageRoll"):game.i18n.localize("PF2E.Damage.Dialog.DamageRoll")}async getData(){const modifiers=this.formulaData.modifiers.map(m=>({label:m.label,category:m.category,type:m.type,modifier:m.modifier,hideIfDisabled:!__privateGet(this,_originallyEnabled).has(m)&&m.hideIfDisabled,damageType:m.damageType,typeLabel:__privateMethod(this,_getTypeLabel,getTypeLabel_fn).call(this,m.damageType,m.damageCategory),enabled:m.enabled,ignored:m.ignored,critical:m.critical,show:this.isCritical||!m.critical,icon:__privateMethod(this,_getModifierIcon,getModifierIcon_fn).call(this,m)})),dice=this.formulaData.dice.map(d=>({label:d.label,category:d.category,damageType:d.damageType,typeLabel:__privateMethod(this,_getTypeLabel,getTypeLabel_fn).call(this,d.damageType,d.category),diceLabel:d.diceNumber&&d.dieSize?`${d.diceNumber}${d.dieSize}`:d.diceNumber?game.i18n.format("PF2E.Damage.Dialog.BonusDice",{dice:addSign(d.diceNumber)}):"",enabled:d.enabled,ignored:d.ignored,critical:d.critical,show:!d.override&&(this.isCritical||!d.critical),icon:__privateMethod(this,_getModifierIcon,getModifierIcon_fn).call(this,d)})),hasVisibleModifiers=modifiers.filter(m=>m.show).length>0,hasVisibleDice=dice.filter(d=>d.show).length>0,baseResult=createDamageFormula({base:this.formulaData.base,modifiers:[],dice:[],ignoredResistances:[]}),baseRoll=new DamageRoll(baseResult.formula),baseFormulaTemplate=(await Promise.all(baseRoll.instances.map(i=>i.render()))).join(" + "),result=createDamageFormula(this.formulaData),roll=new DamageRoll(result.formula),formulaTemplate=(await Promise.all(roll.instances.map(i=>i.render()))).join(" + ");return{appId:this.id,baseFormula:baseFormulaTemplate,modifiers,dice,isCritical:this.isCritical,hasVisibleDice,hasVisibleModifiers,damageTypes:sortStringRecord(CONFIG.PF2E.damageTypes),damageSubtypes:sortStringRecord(pick(CONFIG.PF2E.damageCategories,DAMAGE_CATEGORIES_UNIQUE)),rollModes:CONFIG.Dice.rollModes,rollMode:this.context?.rollMode,showRollDialogs:game.user.settings.showRollDialogs,formula:formulaTemplate}}activateListeners($html){const html=$html[0];htmlQuery(html,"button.roll")?.addEventListener("click",()=>{this.isRolled=!0,this.close()});for(const checkbox of htmlQueryAll(html,".modifier-container input[type=checkbox]"))checkbox.addEventListener("click",()=>{const{dice,modifiers}=this.formulaData,modIndex=Number(checkbox.dataset.modifierIndex),dieIndex=Number(checkbox.dataset.diceIndex);Number.isNaN(modIndex)?Number.isNaN(dieIndex)||(dice[dieIndex].ignored=!checkbox.checked,dice[dieIndex].enabled=checkbox.checked):(modifiers[modIndex].ignored=!checkbox.checked,__privateMethod(this,_applyStackingRules,applyStackingRules_fn).call(this)),this.render()});const categorySelect=htmlQuery(html,"select.add-dice-category"),damageTypeSelect=htmlQuery(html,"select.add-dice-type");categorySelect?.addEventListener("change",()=>{damageTypeSelect&&(categorySelect.value==="precision"?(damageTypeSelect.value="",damageTypeSelect.disabled=!0):(damageTypeSelect.disabled=!1,damageTypeSelect.value=damageTypeSelect.firstElementChild?.value??"acid"))});const addModifierButton=htmlQuery(html,"button.add-modifier");addModifierButton?.addEventListener("click",()=>{const parent=addModifierButton.parentElement,value=Number(parent.querySelector(".add-modifier-value")?.value||1),type=String(parent.querySelector(".add-modifier-type")?.value),damageType=parent.querySelector(".add-modifier-damage-type")?.value??null,category=parent.querySelector(".add-modifier-category")?.value||null,errors=[];if(Number.isNaN(value)?errors.push("Modifier value must be a number."):value===0&&errors.push("Modifier value must not be zero."),!setHasElement(MODIFIER_TYPES,type))throw ErrorPF2e("Unexpected invalid modifier type");const label=String(parent.querySelector(".add-modifier-name")?.value).trim()||game.i18n.localize(value<0?`PF2E.PenaltyLabel.${type}`:`PF2E.BonusLabel.${type}`);errors.length>0?ui.notifications.error(errors.join(" ")):(this.formulaData.modifiers.push(new ModifierPF2e({label,modifier:value,type,damageType,damageCategory:category})),__privateMethod(this,_applyStackingRules,applyStackingRules_fn).call(this),this.render())});const addDiceButton=htmlQuery(html,"button.add-dice");addDiceButton?.addEventListener("click",()=>{const parent=addDiceButton.parentElement,count=Number(parent.querySelector(".add-dice-count")?.value||1),faces=parent.querySelector(".add-dice-faces")?.value??"d4",category=parent.querySelector(".add-dice-category")?.value||null,type=parent.querySelector(".add-dice-type")?.value||null;if(Number.isNaN(count)){ui.notifications.error("Damage dice count must be a number.");return}else if(count<1){ui.notifications.error("Damage dice count must be greater than zero.");return}if(!tupleHasValue(["persistent","precision","splash",null],category)){ui.notifications.error(`Unkown damage category: ${category}.`);return}const faceLabel=game.i18n.localize(`PF2E.DamageDie${faces.toUpperCase()}`),label=game.i18n.format("PF2E.Damage.Dialog.Bonus",{dice:`+${count}${faceLabel}`}),slug=sluggify(`${label}-${type}`);this.formulaData.dice.push(new DamageDicePF2e({label,category,diceNumber:count,dieSize:faces,damageType:type,slug,selector:"damage"})),this.render()});const rollModeInput=htmlQuery(html,"select[name=rollmode]");rollModeInput?.addEventListener("change",()=>{const rollMode=rollModeInput.value;if(!tupleHasValue(Object.values(CONST.DICE_ROLL_MODES),rollMode))throw ErrorPF2e("Unexpected roll mode");this.context.rollMode=rollMode});const settingsButton=htmlQuery(htmlClosest(html,".app"),"a.header-button.settings");if(settingsButton&&!settingsButton?.dataset.tooltipContent){settingsButton.dataset.tooltipContent=`#${this.id}-settings`;const $tooltip=$(settingsButton).tooltipster({animation:"fade",trigger:"click",arrow:!1,contentAsHTML:!0,debug:!1,interactive:!0,side:["top"],theme:"crb-hover",minWidth:165}),toggle=htmlQuery(html,".settings-list input.quick-rolls-submit");toggle?.addEventListener("click",async()=>{await game.user.setFlag("pf2e","settings.showRollDialogs",toggle.checked),$tooltip.tooltipster("close")})}}async resolve(){return this.render(!0),new Promise(resolve=>{__privateSet(this,_resolve,resolve)})}async close(options){var _a;(_a=__privateGet(this,_resolve))==null||_a.call(this,this.isRolled),super.close(options)}_getHeaderButtons(){const buttons=super._getHeaderButtons();return[{label:game.i18n.localize("PF2E.SETTINGS.Settings"),class:"settings",icon:"fa-solid fa-cog",onclick:()=>null},...buttons]}_injectHTML($html){super._injectHTML($html),$html[0]?.querySelector("button.roll")?.focus()}};_resolve=new WeakMap,_originallyEnabled=new WeakMap,_getModifierIcon=new WeakSet,getModifierIcon_fn=__name2(function(object){const damageTypeIconClass=object.damageType?DAMAGE_TYPE_ICONS[object.damageType]:null,damageTypeIcon=damageTypeIconClass?fontAwesomeIcon(damageTypeIconClass):null;return(()=>{switch(object.category){case"splash":return compact([fontAwesomeIcon("fa-burst"),damageTypeIcon]);case"persistent":return object.damageType!=="bleed"?[damageTypeIcon,fontAwesomeIcon("fa-hourglass",{style:"duotone"})]:[damageTypeIcon];case"precision":return[damageTypeIcon,fontAwesomeIcon("fa-crosshairs")];default:return[damageTypeIcon]}})().map(i=>i?.outerHTML??"").join("")},"#getModifierIcon"),_getTypeLabel=new WeakSet,getTypeLabel_fn=__name2(function(damageType,category){if(category==="precision")return game.i18n.localize("PF2E.Damage.Precision");if(!damageType)return null;const typeLabel=game.i18n.localize(CONFIG.PF2E.damageTypes[damageType]);switch(category){case"persistent":return game.i18n.format("PF2E.Damage.PersistentTooltip",{damageType:typeLabel});case"splash":return game.i18n.format("PF2E.Damage.Dialog.Splash",{damageType:typeLabel});default:return typeLabel}},"#getTypeLabel"),_applyStackingRules=new WeakSet,applyStackingRules_fn=__name2(function(){applyStackingRules(this.formulaData.modifiers.filter(m=>m.category!=="persistent")),applyStackingRules(this.formulaData.modifiers.filter(m=>m.category==="persistent"))},"#applyStackingRules"),__name2(_DamageModifierDialog,"DamageModifierDialog");let DamageModifierDialog=_DamageModifierDialog;const superEnrichHTML=TextEditor.enrichHTML,superEnrichContentLinks=TextEditor._enrichContentLinks,superCreateInlineRoll=TextEditor._createInlineRoll,superOnClickInlineRoll=TextEditor._onClickInlineRoll,_TextEditorPF2e=class _TextEditorPF2e2 extends TextEditor{static{__name(this,"_TextEditorPF2e")}static enrichHTML(content,options={}){content?.startsWith("

@Localize")&&(content=content.substring(3,content.length-4));const enriched=superEnrichHTML.apply(this,[content,options]);return typeof enriched=="string"&&(options.processVisibility??!0)?_TextEditorPF2e2.processUserVisibility(enriched,options):Promise.resolve().then(async()=>_TextEditorPF2e2.processUserVisibility(await enriched,options))}static _enrichContentLinks(text,options){if(options?.async){const documentTypes=[...CONST.DOCUMENT_LINK_TYPES,"Compendium","UUID"],pattern=new RegExp(`@(${documentTypes.join("|")})\\[([^#\\]]+)(?:#([^\\]]+))?](?:{([^}]+)})?`,"g"),uuids=text.map(t=>Array.from((t.textContent??"").matchAll(pattern))).flat(2).filter(m=>UUIDUtils.isCompendiumUUID(m));return UUIDUtils.fromUUIDs(uuids).then(()=>superEnrichContentLinks.apply(this,[text,options]))}return superEnrichContentLinks.apply(this,[text,options])}static async _createInlineRoll(match,rollData,options={}){const anchor=await superCreateInlineRoll.apply(this,[match,rollData,options]),formula=anchor?.dataset.formula;if(formula){const roll=(()=>{try{return new DamageRoll(formula)}catch{return null}})();if(!roll||!looksLikeDamageRoll(roll))return anchor;const icon=damageDiceIcon(roll),label=match[4]&&match[4].length>0?match[4]:roll.formula;anchor.innerHTML=`${icon.outerHTML}${label}`,anchor.dataset.tooltip=roll.formula,anchor.dataset.damageRoll="",roll.instances.length>0&&roll.instances.every(i=>i.persistent)&&(anchor.draggable=!0,anchor.dataset.persistent="")}return anchor}static async _onClickInlineRoll(event){const anchor=event.currentTarget??null;if(!(anchor instanceof HTMLAnchorElement&&anchor.dataset.formula&&"damageRoll"in anchor.dataset))return superOnClickInlineRoll.apply(this,[event]);const sheetElem=htmlClosest(anchor,".sheet"),messageElem=htmlClosest(anchor,"li.chat-message"),app=ui.windows[Number(sheetElem?.dataset.appid)],message=game.messages.get(messageElem?.dataset.messageId??""),[actor,rollData]=(()=>{if(message?.actor)return[message.actor,message.getRollData()];if(app instanceof ActorSheetPF2e){const itemId=anchor.dataset.pf2ItemId;return[app.actor,app.actor.items.get(itemId)?.getRollData()??app.actor.getRollData()]}if(app instanceof ItemSheetPF2e)return[app.actor,app.item.getRollData()];const itemUuid=anchor.dataset.itemUuid,itemByUUID=itemUuid&&!itemUuid.startsWith("Compendium.")?fromUuidSync(itemUuid):null;return itemByUUID instanceof ItemPF2e?[itemByUUID.actor,itemByUUID.getRollData()]:[null,{}]})(),options=anchor.dataset.flavor?{flavor:anchor.dataset.flavor}:{},speaker=ChatMessagePF2e.getSpeaker({actor}),rollMode=objectHasKey(CONFIG.Dice.rollModes,anchor.dataset.mode)?anchor.dataset.mode:"roll",baseFormula=anchor.dataset.pf2BaseFormula;if(baseFormula){const item=rollData.item instanceof ItemPF2e?rollData.item:null,traits=anchor.dataset.pf2Traits?.split(",")??[],domains=anchor.dataset.pf2Domains?.split(","),extraRollOptions=anchor.dataset.pf2RollOptions?.split(",")??[],result=await augmentInlineDamageRoll(baseFormula,{...eventToRollParams(event),actor,item,domains,traits,extraRollOptions});result&&await DamagePF2e.roll(result.template,result.context);return}const roll=new DamageRoll(anchor.dataset.formula,rollData,options);return roll.toMessage({speaker,flavor:roll.options.flavor},{rollMode})}static processUserVisibility(content,options){const html=createHTMLElement("div",{innerHTML:content}),document2=options.rollData?.actor??null;return UserVisibilityPF2e.process(html,{document:document2}),html.innerHTML}static async enrichString(data,options={}){if(data.length<4)return null;const item=options.rollData?.item??null,[_match,inlineType,paramString,inlineLabel]=data;switch(inlineType){case"Check":{const actor=options.rollData?.actor??item?.actor??null;return __privateMethod(this,_createCheck,createCheck_fn).call(this,{paramString,inlineLabel,item,actor})}case"Damage":return __privateMethod(this,_createDamageRoll,createDamageRoll_fn).call(this,{paramString,rollData:options.rollData,inlineLabel});case"Localize":return __privateMethod(this,_localize,localize_fn).call(this,paramString,options);case"Template":return __privateMethod(this,_createTemplate,createTemplate_fn).call(this,paramString,inlineLabel,item?.system);default:return null}}static convertXMLNode(html,name2,{visible,visibility,whose,tooltip,classes}){const node=html.querySelector(name2);if(!node)return null;const span=document.createElement("span"),{dataset,classList}=span;if(typeof visible=="boolean"&&(visibility=visible?"all":"gm"),visibility&&(dataset.visibility=visibility),whose&&(dataset.whose=whose),tooltip&&(dataset.tooltip=tooltip.trim()),classes)for(const cssClass of classes)classList.add(cssClass);return span.append(...Array.from(node.childNodes)),node.replaceWith(span),span}};_localize=new WeakSet,localize_fn=__name2(async function(paramString,options){const content=game.i18n.localize(paramString);if(content===paramString)return ui.notifications.error(`Failed to localize ${paramString}!`),null;const result=document.createElement("span");return result.innerHTML=await TextEditor.enrichHTML(content,{...options,async:!0}),result},"#localize"),_createTemplate=new WeakSet,createTemplate_fn=__name2(function(paramString,label,itemData){const params=__privateMethod(this,_parseInlineParams,parseInlineParams_fn).call(this,paramString,{first:"type"});if(!params)return null;if(!params.type)ui.notifications.error(game.i18n.localize("PF2E.InlineTemplateErrors.TypeMissing"));else if(params.distance)if(objectHasKey(CONFIG.PF2E.areaTypes,params.type)){if(isNaN(+params.distance))return ui.notifications.error(game.i18n.format("PF2E.InlineTemplateErrors.DistanceNoNumber",{distance:params.distance})),null;if(params.width&&isNaN(+params.width))return ui.notifications.error(game.i18n.format("PF2E.InlineTemplateErrors.WidthNoNumber",{width:params.width})),null;{params.traits||=itemData?.traits?.value?.toString()??"",label||(label=game.i18n.format("PF2E.TemplateLabel",{size:params.distance,unit:game.i18n.localize("PF2E.Foot"),shape:game.i18n.localize(CONFIG.PF2E.areaTypes[params.type])}));const html=document.createElement("span");return html.innerHTML=label,html.setAttribute("data-pf2-effect-area",params.type),html.setAttribute("data-pf2-distance",params.distance),params.traits!==""&&html.setAttribute("data-pf2-traits",params.traits),params.type==="line"&&html.setAttribute("data-pf2-width",params.width??"5"),html}}else return ui.notifications.error(game.i18n.format("PF2E.InlineTemplateErrors.TypeUnsupported",{type:params.type})),null;else return ui.notifications.error(game.i18n.localize("PF2E.InlineTemplateErrors.DistanceMissing")),null;return null},"#createTemplate"),_parseInlineParams=new WeakSet,parseInlineParams_fn=__name2(function(paramString,options={}){return paramString.split("|").reduce((result2,part,idx)=>{if(idx===0&&options.first&&!part.includes(":"))return result2[options.first]=part.trim(),result2;const colonIdx=part.indexOf(":"),portions=colonIdx>=0?[part.slice(0,colonIdx),part.slice(colonIdx+1)]:[part,""];return result2[portions[0]]=portions[1],result2},{})},"#parseInlineParams"),_createCheck=new WeakSet,createCheck_fn=__name2(function({paramString,inlineLabel,item=null,actor=item?.actor??null}){const rawParams=__privateMethod(this,_parseInlineParams,parseInlineParams_fn).call(this,paramString,{first:"type"});if(!rawParams)return null;if(!rawParams.type)return ui.notifications.warn(game.i18n.localize("PF2E.InlineCheck.Errors.TypeMissing")),null;const showDC=setHasElement(USER_VISIBILITIES,rawParams.showDC)?rawParams.showDC:actor?.hasPlayerOwner||actor?.isOfType("party")||game.settings.get("pf2e","metagame_showDC")?"all":"gm",params={...rawParams,type:rawParams.type,basic:rawParams.basic!==void 0&&["true",""].includes(rawParams.basic),showDC,traits:(()=>{const traits=[],itemTraits=item?.system.traits?.value??[];return rawParams.overrideTraits!=="true"&&traits.push(...itemTraits),rawParams.traits&&traits.push(...rawParams.traits.split(",").map(trait=>trait.trim())),Array.from(new Set(traits))})(),extraRollOptions:compact([...__privateMethod(this,_createActionOptions,createActionOptions_fn).call(this,item),...rawParams.basic==="true"?["damaging-effect"]:[],...rawParams.options?.split(",").map(t=>t.trim())??[]]).sort()};rawParams.dc&&(params.dc=rawParams.dc),rawParams.defense&&(params.defense=rawParams.defense);const types=params.type.split(",");let adjustments=params.adjustment?.split(",")??["0"];if(types.length!==adjustments.length&&adjustments.length>1)return ui.notifications.warn(game.i18n.localize("PF2E.InlineCheck.Errors.AdjustmentLengthMismatch")),null;if(types.length>adjustments.length&&(adjustments=new Array(types.length).fill(adjustments[0])),adjustments.some(adj=>adj!==""&&isNaN(parseInt(adj))))return ui.notifications.warn(game.i18n.localize("PF2E.InlineCheck.Errors.NonIntegerAdjustment")),null;const buttons=types.map((type,i)=>__privateMethod(this,_createSingleCheck,createSingleCheck_fn).call(this,{actor,item,inlineLabel,params:{...params,type,adjustment:adjustments[i]}}));if(buttons.length===1)return buttons[0];{const checkGroup=document.createElement("div");checkGroup.setAttribute("data-pf2-checkgroup","");for(const button of buttons){if(button===null)return null;checkGroup.hasChildNodes()&&checkGroup.appendChild(document.createElement("br")),checkGroup.appendChild(button)}return checkGroup}},"#createCheck"),_createSingleCheck=new WeakSet,createSingleCheck_fn=__name2(function({params,item,actor,inlineLabel}){const icon=(()=>{switch(params.type){case"fortitude":return fontAwesomeIcon("heart-pulse");case"reflex":return fontAwesomeIcon("person-running");case"will":return fontAwesomeIcon("brain");case"perception":return fontAwesomeIcon("eye");default:return fontAwesomeIcon("dice-d20")}})();icon.classList.add("icon");const name2=params.name??item?.name??params.type,localize=localizer("PF2E.InlineCheck"),label=(()=>{if(inlineLabel)return inlineLabel;if(tupleHasValue(SAVE_TYPES,params.type)){const saveName=game.i18n.localize(CONFIG.PF2E.saves[params.type]);return params.basic?localize("BasicWithSave",{save:saveName}):saveName}switch(params.type){case"flat":return game.i18n.localize("PF2E.FlatCheck");case"perception":return game.i18n.localize("PF2E.PerceptionLabel");default:{const shortForm=(()=>{if(objectHasKey(SKILL_EXPANDED,params.type))return SKILL_EXPANDED[params.type].shortForm;if(objectHasKey(SKILL_DICTIONARY,params.type))return params.type})();return shortForm?game.i18n.localize(CONFIG.PF2E.skills[shortForm]):params.type.split("-").map(word=>word.slice(0,1).toUpperCase()+word.slice(1)).join(" ")}}})(),createLabel=__name2(content=>createHTMLElement("span",{classes:["label"],innerHTML:content}),"createLabel"),anchor=createHTMLElement("a",{classes:["inline-check"],children:[icon,createLabel(label)],dataset:{pf2Traits:params.traits.toString()||null,pf2RollOptions:params.extraRollOptions.toString()||null,pf2RepostFlavor:name2,pf2ShowDc:params.showDC==="all"?null:params.showDC,pf2Label:localize("DCWithName",{name:name2}),pf2Adjustment:Number(params.adjustment)||null,pf2Roller:params.roller||null,pf2Check:sluggify(params.type)}});if(params.defense&¶ms.dc&&(anchor.dataset.tooltip=localize("Invalid",{message:localize("Errors.DCAndDefense")}),anchor.dataset.invalid="true"),!["flat","fortitude","reflex","will"].includes(params.type)&¶ms.defense&&(anchor.dataset.pf2Defense=params.defense),params.type&¶ms.dc){const checkDC=params.dc==="@self.level"?params.dc:getCheckDC({name:name2,params,item,actor});if(anchor.dataset.pf2Dc=checkDC,checkDC!=="@self.level"){const dc=params.dc===""?NaN:Number(checkDC),displayedDC=isNaN(dc)?checkDC:`${dc+Number(params.adjustment)}`,text=anchor.innerText;anchor.querySelector("span.label")?.replaceWith(createLabel(game.i18n.format("PF2E.DCWithValueAndVisibility",{role:params.showDC,dc:displayedDC,text})))}}return params.roller==="self"&&actor&&!actor.canUserModify(game.user,"update")?createHTMLElement("span",{children:[anchor.innerText]}):anchor},"#createSingleCheck"),_createDamageRoll=new WeakSet,createDamageRoll_fn=__name2(async function(args){const params=__privateMethod(this,_parseInlineParams,parseInlineParams_fn).call(this,args.paramString,{first:"formula"});if(!params||!params.formula)return ui.notifications.warn(game.i18n.localize("PF2E.InlineCheck.Errors.TypeMissing")),null;const item=args.rollData?.item instanceof ItemPF2e?args.rollData?.item:null,actor=(args.rollData?.actor instanceof ActorPF2e?args.rollData?.actor:null)??item?.actor??null,domains=params.domains?.split(",");if(domains?.some(d=>!/^[a-z][-a-z0-9]+-damage$/.test(d)))return ui.notifications.warn(game.i18n.format("PF2E.InlineCheck.Errors.InvalidDomains",{type:"@Damage"})),null;const traits=(()=>{const fromParams=params.traits?.split(",").flatMap(t=>t.trim()||[])??[],fromItem=item?.system.traits?.value??[];return params.overrideTraits==="true"?fromParams:uniq([...fromParams,...fromItem])})().sort(),extraRollOptions=compact([...params.options?.split(",").map(t=>t.trim())??[],...__privateMethod(this,_createActionOptions,createActionOptions_fn).call(this,item)]).sort(),result=await augmentInlineDamageRoll(params.formula,{skipDialog:!0,actor,item,domains,traits,extraRollOptions}),baseFormula=(()=>{const baseRollData={...item?.getRollData()??{},actor:{level:(item&&"level"in item?item.level:null)??1}};return new DamageRoll(params.formula,baseRollData).formula})(),roll=result?.template.damage.roll??new DamageRoll(params.formula,args.rollData),formula=roll.formula;return createHTMLElement("a",{classes:compact(["inline-roll","roll",baseFormula!==formula?"altered":null]),children:[damageDiceIcon(roll),args.inlineLabel??formula],dataset:{formula:roll._formula,tooltip:args.inlineLabel?formula:baseFormula!==formula?game.i18n.format("PF2E.InlineDamage.Base",{formula:baseFormula}):null,damageRoll:params.formula,pf2Domains:domains?.join(",")||null,pf2BaseFormula:result?params.formula:null,pf2Traits:traits.toString()||null,pf2RollOptions:extraRollOptions.toString()||null,pf2ItemId:item?.id}})},"#createDamageRoll"),_createActionOptions=new WeakSet,createActionOptions_fn=__name2(function(item){return!item?.isOfType("action","feat")||!item.actionCost?[]:compact([`action:${item.slug??sluggify(item.name)}`,item.actionCost.value?`action:cost:${item.actionCost.value}`:null])},"#createActionOptions"),__privateAdd(_TextEditorPF2e,_localize),__privateAdd(_TextEditorPF2e,_createTemplate),__privateAdd(_TextEditorPF2e,_parseInlineParams),__privateAdd(_TextEditorPF2e,_createCheck),__privateAdd(_TextEditorPF2e,_createSingleCheck),__privateAdd(_TextEditorPF2e,_createDamageRoll),__privateAdd(_TextEditorPF2e,_createActionOptions),__name2(_TextEditorPF2e,"TextEditorPF2e");let TextEditorPF2e=_TextEditorPF2e;function getCheckDC({name:name2,params,item=null,actor=item?.actor??null}){const{type}=params,dc=params.dc,base=(()=>{if(dc?.startsWith("resolve")&&actor){params.immutable||="true";const resolve=dc.match(/resolve\((.+?)\)$/),value=resolve&&resolve?.length>0?resolve[1]:"";return Number(__name2(resolveString=>{try{const rollData=item?.getRollData()??actor?.getRollData();return Roll.safeEval(Roll.replaceFormulaData(resolveString,rollData))}catch{return 0}},"saferEval")(value))}return Number(dc)||void 0})();if(base){const getStatisticValue=__name2(selectors=>{if(item?.actor&¶ms.immutable!=="true"){const{actor:actor2}=item,{synthetics}=actor2,modifier=new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:base-10,adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,selectors,"base")}),stat=new Statistic(actor2,{slug:type,label:name2,domains:selectors,modifiers:[modifier]});return String(stat.dc.value)}return base.toString()},"getStatisticValue"),slugName=sluggify(name2);if(type==="flat")return params.immutable==="false"?getStatisticValue(["inline-dc",`${slugName}-inline-dc`]):base.toString();{const selectors=["all","inline-dc",`${slugName}-inline-dc`];return getStatisticValue(selectors)}}return"0"}__name(getCheckDC,"getCheckDC"),__name2(getCheckDC,"getCheckDC");async function augmentInlineDamageRoll(baseFormula,args){const{name:name2,actor,item,traits,extraRollOptions}=args;try{const rollData=item?.getRollData()??actor?.getRollData()??{};rollData.actor??={level:(item&&"level"in item?item.level:null)??1};const base=extractBaseDamage(new DamageRoll(baseFormula,rollData)),domains=compact(["damage","inline-damage",item?`${item.id}-inline-damage`:null,item?`${sluggify(item.slug??item.name)}-inline-damage`:null,args.domains]).flat(),options=new Set([...actor?.getRollOptions(domains)??[],...item?.getRollOptions("item")??[],...traits??[],...extraRollOptions??[]]),firstBase=base.at(0);if(firstBase&&actor?.isOfType("npc")&&(actor.isElite||actor.isWeak)){const value=options.has("item:frequency:limited")?4:2;firstBase.terms?.push({dice:null,modifier:actor.isElite?value:-value})}const{modifiers,dice}=(()=>{if(!(actor instanceof ActorPF2e))return{modifiers:[],dice:[]};const extractOptions={resolvables:rollData??{},test:options};return processDamageCategoryStacking(base,{modifiers:extractModifiers(actor.synthetics,domains,extractOptions),dice:extractDamageDice(actor.synthetics.damageDice,domains,extractOptions),test:options})})(),formulaData={base,modifiers,dice,ignoredResistances:[]},isAttack=!!traits?.includes("attack"),context={type:"damage-roll",sourceType:isAttack?"attack":"save",outcome:isAttack?"success":null,domains,options,self:(()=>actor?{actor,token:actor.token,item:item||null,statistic:null,modifiers}:null)()};applyDamageDiceOverrides(base,dice);const{formula,breakdown}=createDamageFormula(formulaData),roll=new DamageRoll(formula);return{template:{name:name2??item?.name??actor?.name??"",damage:{roll,breakdown},modifiers:[...modifiers,...dice],traits:traits?.filter(t=>t in CONFIG.PF2E.actionTraits)??[],materials:[]},context}}catch(ex){return console.error(`Failed to parse inline @Damage ${baseFormula}:`,ex),null}}__name(augmentInlineDamageRoll,"augmentInlineDamageRoll"),__name2(augmentInlineDamageRoll,"augmentInlineDamageRoll");const _CheckModifiersDialog=class extends Application{static{__name(this,"_CheckModifiersDialog")}constructor(check,resolve,context={options:new Set}){const title=(()=>{const maybeWithHTML=context.title?.trim()||check.slug;if(!maybeWithHTML.includes("<"))return maybeWithHTML.trim();const div=document.createElement("div");return div.innerHTML=maybeWithHTML,div.querySelector(".action-glyph, .pf2-icon")?.remove(),div.innerText.trim()})();super({title}),__privateAdd(this,_resolveSubstitutions),__publicField(this,"check"),__publicField(this,"context"),__publicField(this,"resolve"),__publicField(this,"isResolved",!1),__privateAdd(this,_originallyEnabled2,void 0),this.check=check,this.resolve=resolve,this.context=context,__privateSet(this,_originallyEnabled2,new Set(check.modifiers.filter(m=>m.enabled)))}static get defaultOptions(){return{...super.defaultOptions,template:"systems/pf2e/templates/chat/check-modifiers-dialog.hbs",classes:["roll-modifiers-dialog","dice-checks","dialog"],popOut:!0,width:380,height:"auto"}}async getData(){const fortune=this.context.rollTwice==="keep-higher",misfortune=this.context.rollTwice==="keep-lower",none=fortune===misfortune,rollMode=this.context.rollMode==="roll"?game.settings.get("core","rollMode"):this.context.rollMode;return{appId:this.id,modifiers:this.check.modifiers.map(m=>({...m,hideIfDisabled:!__privateGet(this,_originallyEnabled2).has(m)&&m.hideIfDisabled})),totalModifier:this.check.totalModifier,rollModes:CONFIG.Dice.rollModes,rollMode,showRollDialogs:game.user.settings.showRollDialogs,substitutions:__privateMethod(this,_resolveSubstitutions,resolveSubstitutions_fn).call(this),fortune,none,misfortune}}activateListeners($html){const html=$html[0];htmlQuery(html,"button.roll")?.addEventListener("click",()=>{this.resolve(!0),this.isResolved=!0,this.close()});for(const checkbox of htmlQueryAll(html,".substitutions input[type=checkbox]"))checkbox.addEventListener("click",()=>{const substitutions=this.context.substitutions??[],index=Number(checkbox.dataset.subIndex),toggledSub=substitutions.at(index);if(!toggledSub)return;toggledSub.selected=toggledSub.required||checkbox.checked;const options=this.context.options??=new Set;for(const substitution of substitutions){const option=`substitute:${substitution.slug}`;substitution.selected?options.add(option):options.delete(option)}this.context.substitutions=__privateMethod(this,_resolveSubstitutions,resolveSubstitutions_fn).call(this).map(s=>omit(s,["toggleable"])),this.check.calculateTotal(this.context.options),this.render()});for(const checkbox of htmlQueryAll(html,".modifier-container input[type=checkbox]"))checkbox.addEventListener("click",()=>{const index=Number(checkbox.dataset.modifierIndex);this.check.modifiers[index].ignored=!checkbox.checked,this.check.calculateTotal(),this.render()});const addModifierButton=htmlQuery(html,"button.add-modifier");addModifierButton?.addEventListener("click",()=>{const parent=addModifierButton.parentElement,value=Number(parent.querySelector(".add-modifier-value")?.value||1),type=String(parent.querySelector(".add-modifier-type")?.value);let name2=String(parent.querySelector(".add-modifier-name")?.value);const errors=[];if(Number.isNaN(value)?errors.push("Modifier value must be a number."):value===0&&errors.push("Modifier value must not be zero."),!setHasElement(MODIFIER_TYPES,type))throw ErrorPF2e("Unexpected invalid modifier type");(!name2||!name2.trim())&&(name2=game.i18n.localize(value<0?`PF2E.PenaltyLabel.${type}`:`PF2E.BonusLabel.${type}`)),errors.length>0?ui.notifications.error(errors.join(" ")):(this.check.push(new ModifierPF2e(name2,value,type)),this.render())});for(const rollTwice of htmlQueryAll(html,".fate input[type=radio]"))rollTwice.addEventListener("click",()=>{this.context.rollTwice=rollTwice.value||!1});const rollModeInput=htmlQuery(html,"select[name=rollmode]");rollModeInput?.addEventListener("change",()=>{const rollMode=rollModeInput.value;if(!tupleHasValue(Object.values(CONST.DICE_ROLL_MODES),rollMode))throw ErrorPF2e("Unexpected roll mode");this.context.rollMode=rollMode});const settingsButton=htmlQuery(htmlClosest(html,".app"),"a.header-button.settings");if(settingsButton&&!settingsButton?.dataset.tooltipContent){settingsButton.dataset.tooltipContent=`#${this.id}-settings`;const $tooltip=$(settingsButton).tooltipster({animation:"fade",trigger:"click",arrow:!1,contentAsHTML:!0,debug:!1,interactive:!0,side:["top"],theme:"crb-hover",minWidth:165}),toggle=htmlQuery(html,".settings-list input.quick-rolls-submit");toggle?.addEventListener("click",async()=>{await game.user.setFlag("pf2e","settings.showRollDialogs",toggle.checked),$tooltip.tooltipster("close")})}}async close(options){this.isResolved||this.resolve(!1),super.close(options)}_getHeaderButtons(){const buttons=super._getHeaderButtons();return[{label:game.i18n.localize("PF2E.SETTINGS.Settings"),class:"settings",icon:"fa-solid fa-cog",onclick:()=>null},...buttons]}_injectHTML($html){super._injectHTML($html),$html[0]?.querySelector("button.roll")?.focus()}};_originallyEnabled2=new WeakMap,_resolveSubstitutions=new WeakSet,resolveSubstitutions_fn=__name2(function(){this.context.substitutions??=[];const hasRequired={fortune:this.context.substitutions.some(s=>s.required&&s.effectType==="fortune"),misfortune:this.context.substitutions.some(s=>s.required&&s.effectType==="misfortune")};return this.context.substitutions.map(substitution=>{const toggleable=!hasRequired[substitution.effectType],selected=substitution.required?!0:substitution.selected&&toggleable;return{...substitution,selected,toggleable}})},"#resolveSubstitutions"),__name2(_CheckModifiersDialog,"CheckModifiersDialog");let CheckModifiersDialog=_CheckModifiersDialog;const _CheckRoll=class _CheckRoll2 extends Roll{static{__name(this,"_CheckRoll")}get roller(){return game.users.get(this.options.rollerId??"")??null}get type(){return this.options.type??"check"}get degreeOfSuccess(){return this.options.degreeOfSuccess??null}get isReroll(){return this.options.isReroll??!1}get isRerollable(){return!this.isReroll&&!this.dice.some(d=>d.modifiers.includes("kh")||d.modifiers.includes("kl"))}async render(options={}){this._evaluated||await this.evaluate({async:!0});const{isPrivate,flavor,template}=options,{type,identifier,action:action2,damaging}=this.options,canRollDamage=!!(damaging&&identifier&&(this.roller===game.user||game.user.isGM)),limitCueVisibility=!game.settings.get("pf2e","metagame_showResults"),chatData={formula:isPrivate?"???":this._formula,flavor:isPrivate?null:flavor,user:game.user.id,tooltip:isPrivate?"":await this.getTooltip(),total:isPrivate?"?":Math.round(this.total*100)/100,type,identifier,action:action2,degree:this.degreeOfSuccess,canRollDamage,limitCueVisibility};return renderTemplate(template??_CheckRoll2.CHAT_TEMPLATE,chatData)}};__name2(_CheckRoll,"CheckRoll"),__publicField(_CheckRoll,"CHAT_TEMPLATE","systems/pf2e/templates/chat/check/roll.hbs");let CheckRoll=_CheckRoll;const _StrikeAttackRoll=class extends CheckRoll{static{__name(this,"_StrikeAttackRoll")}};__name2(_StrikeAttackRoll,"StrikeAttackRoll");let StrikeAttackRoll=_StrikeAttackRoll;const _CheckPF2e=class _CheckPF2e2{static{__name(this,"_CheckPF2e")}static async roll(check,context={},event=null,callback){event&&mergeObject(context,eventToRollParams(event)),context.skipDialog??=!game.user.settings.showRollDialogs,context.createMessage??=!0,Array.isArray(context.options)&&(context.options=new Set(context.options));const rollOptions=context.options??new Set;typeof context.mapIncreases=="number"&&rollOptions.add(`map:increases:${context.mapIncreases}`),rollOptions.has("secret")&&(context.rollMode??=game.user.isGM?"gmroll":"blindroll"),context.rollMode??="roll",rollOptions.size>0&&!context.isReroll&&check.calculateTotal(rollOptions);const substitutions=context.substitutions??=[],requiredSubstitution=context.substitutions.find(s=>s.required&&s.selected);if(requiredSubstitution)for(const substitution of context.substitutions)substitution.required=substitution===requiredSubstitution,substitution.selected=substitution===requiredSubstitution;if(!context.skipDialog&&context.type!=="flat-check"&&!await new Promise(resolve=>{new CheckModifiersDialog(check,resolve,context).render(!0)}))return null;const extraTags=[],isReroll=context.isReroll??!1;isReroll&&(context.rollTwice=!1);const[dice,tagsFromDice]=(()=>{const substitution=substitutions.find(s=>s.selected),rollTwice=context.rollTwice??!1,fortuneMisfortune=new Set(compact([substitution?.effectType,rollTwice==="keep-higher"?"fortune":rollTwice==="keep-lower"?"misfortune":null]));for(const trait of fortuneMisfortune)rollOptions.add(trait);if(rollOptions.has("fortune")&&rollOptions.has("misfortune")){for(const sub of substitutions)rollOptions.delete(`substitute:${sub.slug}`),check.calculateTotal(rollOptions);return["1d20",["PF2E.TraitFortune","PF2E.TraitMisfortune"]]}else if(substitution){const effectType={fortune:"PF2E.TraitFortune",misfortune:"PF2E.TraitMisfortune"}[substitution.effectType],extraTag=game.i18n.format("PF2E.SpecificRule.SubstituteRoll.EffectType",{type:game.i18n.localize(effectType),substitution:reduceItemName(game.i18n.localize(substitution.label))});return[substitution.value.toString(),[extraTag]]}else return context.rollTwice==="keep-lower"?["2d20kl",["PF2E.TraitMisfortune"]]:context.rollTwice==="keep-higher"?["2d20kh",["PF2E.TraitFortune"]]:["1d20",[]]})();extraTags.push(...tagsFromDice);const options={type:context.type,identifier:context.identifier,action:context.action&&sluggify(context.action)||null,rollerId:game.userId,isReroll,totalModifier:check.totalModifier,damaging:!!context.damaging,domains:context.domains},totalModifierPart=signedInteger(check.totalModifier,{emptyStringZero:!0}),roll=await new CheckRoll(`${dice}${totalModifierPart}`,{},options).evaluate({async:!0}),dosAdjustments=context.dosAdjustments?.filter(a=>a.predicate?.test(rollOptions)??!0).reduce((record,data)=>{for(const outcome of["all",...DEGREE_OF_SUCCESS_STRINGS])data.adjustments[outcome]&&(record[outcome]=deepClone(data.adjustments[outcome]));return record},{})??{},degree=context.dc?new DegreeOfSuccess(roll,context.dc,dosAdjustments):null;degree&&(context.outcome=DEGREE_OF_SUCCESS_STRINGS[degree.value],context.unadjustedOutcome=DEGREE_OF_SUCCESS_STRINGS[degree.unadjusted],roll.options.degreeOfSuccess=degree.value);const notes=context.notes?.map(n=>n instanceof RollNotePF2e?n:new RollNotePF2e(n)).filter(note=>{if(!note.predicate.test([...rollOptions,...note.rule?.item.getRollOptions("parent")??[]]))return!1;if(!context.dc||note.outcome.length===0)return!0;const outcome=context.outcome??context.unadjustedOutcome;return!!(outcome&¬e.outcome.includes(outcome))})??[],notesList=RollNotePF2e.notesToHTML(notes),item=context.item??null,flavor=await(async()=>{const result=await __privateMethod(this,_createResultFlavor,createResultFlavor_fn).call(this,{degree,target:context.target??null}),tags=__privateMethod(this,_createTagFlavor,createTagFlavor_fn).call(this,{check,context,extraTags}),title=(context.title??check.slug).trim();return[title.startsWith("{const strong=document.createElement("strong");return strong.innerHTML=title,createHTMLElement("h4",{classes:["action"],children:[strong]})})(),result??[],tags,notesList].flat().map(e=>typeof e=="string"?e:e.outerHTML).join("")})(),contextFlag={...context,type:context.type??"check",identifier:context.identifier??null,item:void 0,dosAdjustments,actor:context.actor?.id??null,token:context.token?.id??null,domains:context.domains??[],target:context.target?{actor:context.target.actor.uuid,token:context.target.token.uuid}:null,options:Array.from(rollOptions).sort(),notes:notes.map(n=>n.toObject()),rollMode:context.rollMode,rollTwice:context.rollTwice??!1,title:context.title??"PF2E.Check.Label",traits:context.traits??[],substitutions,dc:context.dc?omit(context.dc,["statistic"]):null,skipDialog:context.skipDialog,isReroll:context.isReroll??!1,outcome:context.outcome??null,unadjustedOutcome:context.unadjustedOutcome??null};delete contextFlag.item;const message=await(()=>{const flags={core:context.type==="initiative"?{initiativeRoll:!0}:{},pf2e:{context:contextFlag,modifierName:check.slug,modifiers:check.modifiers.map(m=>m.toObject()),origin:item?.getOriginData()}},speaker=ChatMessagePF2e.getSpeaker({actor:context.actor,token:context.token}),{rollMode}=contextFlag,create=context.createMessage;return roll.toMessage({speaker,flavor,flags},{rollMode,create})})();if(callback){const msg=message instanceof ChatMessagePF2e?message:new ChatMessagePF2e(message),evt=event&&event instanceof Event?event:event?.originalEvent??null;await callback(roll,context.outcome,msg,evt)}return item?.isOfType("weapon")&&item.traits.has("consumable")&&item.actor.items.has(item.id)&&item.quantity>0&&await item.update({system:{quantity:item.quantity-1}}),roll}static async rerollFromMessage(message,{heroPoint=!1,keep="new"}={}){if(!(message.isAuthor||game.user.isGM)){ui.notifications.error(game.i18n.localize("PF2E.RerollMenu.ErrorCantDelete"));return}const actor=game.actors.get(message.speaker.actor??"");let rerollFlavor=game.i18n.localize(`PF2E.RerollMenu.MessageKeep.${keep}`);if(heroPoint)if(actor?.isOfType("character")){const heroPointCount=actor.heroPoints.value;if(heroPointCount)await actor.update({"system.resources.heroPoints.value":Math.clamped(heroPointCount-1,0,actor.heroPoints.max)}),rerollFlavor=game.i18n.format("PF2E.RerollMenu.MessageHeroPoint",{name:actor.name});else{ui.notifications.warn(game.i18n.format("PF2E.RerollMenu.WarnNoHeroPoint",{name:actor.name}));return}}else{ui.notifications.error("PF2E.RerollMenu.ErrorNoActor",{localize:!0});return}const systemFlags=deepClone(message.flags.pf2e),context=systemFlags.context;if(!isCheckContextFlag(context))return;context.skipDialog=!0,context.isReroll=!0;const oldRoll=message.rolls.at(0);if(!(oldRoll instanceof CheckRoll))throw ErrorPF2e("Unexpected error retrieving prior roll");const unevaluatedNewRoll=oldRoll.clone();unevaluatedNewRoll.options.isReroll=!0,Hooks.callAll("pf2e.preReroll",Roll.fromJSON(JSON.stringify(oldRoll.toJSON())),unevaluatedNewRoll,heroPoint,keep);const newRoll=await unevaluatedNewRoll.evaluate({async:!0});Hooks.callAll("pf2e.reroll",Roll.fromJSON(JSON.stringify(oldRoll.toJSON())),newRoll,heroPoint,keep);let keptRoll=newRoll,[oldRollClass,newRollClass]=["pf2e-reroll-discard",""];(keep==="higher"&&oldRoll.total>newRoll.total||keep==="lower"&&oldRoll.total{const{dc}=context;if(!dc)return null;if(dc.slug==="armor"){const targetActor=(()=>{const{target}=context;if(!target?.actor)return null;const maybeActor=fromUuidSync(target.actor);return maybeActor instanceof ActorPF2e?maybeActor:maybeActor instanceof TokenDocumentPF2e?maybeActor.actor:null})();dc.statistic=targetActor?.armorClass}return new DegreeOfSuccess(newRoll,dc,context.dosAdjustments)})(),useNewRoll=keptRoll===newRoll&&!!degree;useNewRoll&°ree&&(newRoll.options.degreeOfSuccess=degree.value);const renders={old:await _CheckPF2e2.renderReroll(oldRoll,{isOld:!0}),new:await _CheckPF2e2.renderReroll(newRoll,{isOld:!1})},rerollIcon=fontAwesomeIcon(heroPoint?"hospital-symbol":"dice");rerollIcon.classList.add("pf2e-reroll-indicator"),rerollIcon.setAttribute("title",rerollFlavor);const oldFlavor=message.flavor??"";context.outcome=useNewRoll?DEGREE_OF_SUCCESS_STRINGS[degree.value]:context.outcome;const newFlavor=useNewRoll?await(async()=>{const parsedFlavor=document.createElement("div");parsedFlavor.innerHTML=oldFlavor;const target=context.target??null,targetFlavor=await __privateMethod(this,_createResultFlavor,createResultFlavor_fn).call(this,{degree,target});targetFlavor&&htmlQuery(parsedFlavor,".target-dc-result")?.replaceWith(targetFlavor);for(const element of htmlQueryAll(parsedFlavor,".roll-note"))element.remove();const notesText=(context.notes?.map(n=>new RollNotePF2e(n))??[]).filter(note=>{if(!context.dc||note.outcome.length===0)return!0;const outcome=context.outcome??context.unadjustedOutcome;return!!(outcome&¬e.outcome.includes(outcome))}).map(n=>n.text).join(` +`)??"";return parsedFlavor.innerHTML+notesText})():oldFlavor,{initiativeRoll}=message.flags.core;if(initiativeRoll){const combatant=message.token?.combatant;await combatant?.parent.setInitiative(combatant.id,newRoll.total)}await message.delete({render:!1}),await keptRoll.toMessage({content:`

${renders.old}
${renders.new}
`,flavor:`${rerollIcon.outerHTML}${newFlavor}`,speaker:message.speaker,flags:{core:{initiativeRoll},pf2e:systemFlags}},{rollMode:context.rollMode})}static async renderReroll(roll,{isOld}){const die=roll.dice.find(d=>d instanceof Die&&d.faces===20);if(typeof die?.total!="number")throw ErrorPF2e("Unexpected error inspecting d20 term");const html=await roll.render(),element=parseHTML(`
${html}
`);return isOld&&element.querySelector(".message-buttons")?.remove(),[1,20].includes(die.total)&&element.querySelector(".dice-total")?.classList.add(die.total===20?"success":"failure"),element.innerHTML}};_createTagFlavor=new WeakSet,createTagFlavor_fn=__name2(function({check,context,extraTags}){const toTagElement=__name2((tag,cssClass=null)=>{const span=document.createElement("span");return span.classList.add("tag"),cssClass&&span.classList.add(`tag_${cssClass}`),span.innerText=tag.label,tag.name&&(span.dataset.slug=tag.name),tag.description&&(span.dataset.tooltip=tag.description),span},"toTagElement"),traits=uniqBy(context.traits?.map(trait=>(trait.label=game.i18n.localize(trait.label),trait))??[],t=>t.name).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang)).map(t=>toTagElement(t))??[],{item}=context,itemTraits=item?.isOfType("weapon","melee")&&context.type!=="saving-throw"?Array.from(item.traits).map(t=>{const obj=traitSlugToObject(t,CONFIG.PF2E.npcAttackTraits);return obj.label=game.i18n.localize(obj.label),obj}).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang)).map(t=>toTagElement(t,"alt")):[],properties=(()=>{const range=item?.isOfType("action","weapon")?item.range:null,label=createActionRangeLabel(range);if(label&&(range?.increment||range?.max)){const slug=range.increment?`range-increment-${range.increment}`:`range-${range.max}`;return[toTagElement({name:slug,label,description:"PF2E.Item.Weapon.RangeIncrementN.Hint"},"secondary")]}else return[]})(),traitsAndProperties=createHTMLElement("div",{classes:["tags","traits"],dataset:{tooltipClass:"pf2e"}});if(itemTraits.length===0&&properties.length===0)traitsAndProperties.append(...traits);else{const verticalBar=document.createElement("hr");verticalBar.className="vr",traitsAndProperties.append(...[traits,verticalBar,itemTraits,properties].flat())}const modifiers=check.modifiers.filter(m=>m.enabled).map(modifier=>{const sign=modifier.modifier<0?"":"+",label=`${modifier.label} ${sign}${modifier.modifier}`;return toTagElement({name:modifier.slug,label},"transparent")}),tagsFromOptions=extraTags.map(t=>toTagElement({label:game.i18n.localize(t)},"transparent")),modifiersAndExtras=createHTMLElement("div",{classes:["tags","modifiers"],children:[...modifiers,...tagsFromOptions]});return compact([traitsAndProperties.childElementCount>0?traitsAndProperties:null,document.createElement("hr"),modifiersAndExtras])},"#createTagFlavor"),_createResultFlavor=new WeakSet,createResultFlavor_fn=__name2(async function({degree,target}){if(!degree)return null;const{dc}=degree,customLabel=!!dc.label&&Number.isInteger(dc.value)&&!dc.label.includes("{dc}")&&dc.label?`${game.i18n.localize(dc.label)}: {dc}`:dc.label??null,targetActor=await(async()=>{if(!target?.actor)return null;if(target.actor instanceof ActorPF2e)return target.actor;const maybeActor=await fromUuid(target.actor);return maybeActor instanceof ActorPF2e?maybeActor:maybeActor instanceof TokenDocumentPF2e?maybeActor.actor:null})(),targetData=await(async()=>{if(!target)return null;const token=await(async()=>target.token?target.token instanceof TokenDocumentPF2e?target.token:targetActor?.token?targetActor.token:fromUuid(target.token):null)(),canSeeName=(token??new TokenDocumentPF2e(targetActor?.prototypeToken.toObject()??{})).playersCanSeeName||!game.settings.get("pf2e","metagame_tokenSetsNameVisibility");return{name:token?.name??targetActor?.name??"",visible:!!canSeeName}})(),{checkDCs}=CONFIG.PF2E,dcData=(()=>{const dcSlug=dc.slug??(dc.statistic instanceof StatisticDifficultyClass?dc.statistic.parent.slug:null),dcType=game.i18n.localize(dc.label?.trim()||game.i18n.localize(objectHasKey(checkDCs.Specific,dcSlug)?checkDCs.Specific[dcSlug]:checkDCs.Unspecific)),circumstances=dc.statistic instanceof StatisticDifficultyClass?dc.statistic.modifiers.filter(m=>m.enabled&&m.type==="circumstance"):[],preadjustedDC=circumstances.length>0&&dc.statistic?dc.value-circumstances.reduce((total,c)=>total+c.modifier,0):dc.value??null,visible=targetActor?.hasPlayerOwner||dc.visible||game.settings.get("pf2e","metagame_showDC");if(typeof preadjustedDC!="number"||circumstances.length===0){const labelKey=game.i18n.localize(targetData?checkDCs.Label.WithTarget:customLabel??checkDCs.Label.NoTarget);return{markup:game.i18n.format(labelKey,{dcType,dc:dc.value,target:targetData?.name??null}),visible}}const adjustment={preadjusted:preadjustedDC,direction:preadjustedDCdc.value?"decreased":"no-change",circumstances:circumstances.map(c=>({label:c.label,value:c.modifier}))},translation=adjustment.direction==="no-change"?checkDCs.Label.NoChangeTarget:checkDCs.Label.AdjustedTarget;return{markup:game.i18n.format(translation,{target:targetData?.name??game.user.name,dcType,preadjusted:preadjustedDC,adjusted:dc.value}),visible,adjustment}})(),resultData=(()=>{const offset={value:new Intl.NumberFormat(game.i18n.lang,{maximumFractionDigits:0,signDisplay:"always",useGrouping:!1}).format(degree.rollTotal-dc.value),visible:dc.visible},checkOrAttack=sluggify(dc.scope??"Check",{camel:"bactrian"}),locPath=__name2((checkOrAttack2,dosKey)=>`PF2E.Check.Result.Degree.${checkOrAttack2}.${dosKey}`,"locPath"),unadjusted=game.i18n.localize(locPath(checkOrAttack,DEGREE_OF_SUCCESS_STRINGS[degree.unadjusted])),[adjusted,locKey]=degree.adjustment?[game.i18n.localize(locPath(checkOrAttack,DEGREE_OF_SUCCESS_STRINGS[degree.value])),"AdjustedLabel"]:[unadjusted,"Label"],markup=game.i18n.format(`PF2E.Check.Result.${locKey}`,{adjusted,unadjusted,offset:offset.value}),visible=game.settings.get("pf2e","metagame_showResults");return{markup,visible}})(),rendered=await renderTemplate("systems/pf2e/templates/chat/check/target-dc-result.hbs",{dc:dcData,result:resultData}),html=parseHTML(rendered),{convertXMLNode}=TextEditorPF2e;if(targetData&&convertXMLNode(html,"target",{visible:targetData.visible,whose:"target"}),convertXMLNode(html,"dc",{visible:dcData.visible,whose:"target"}),dcData.adjustment){const{adjustment}=dcData;convertXMLNode(html,"preadjusted",{classes:["unadjusted"]});const adjustedNode=convertXMLNode(html,"adjusted",{classes:["adjusted",adjustment.direction]});if(!adjustedNode)throw ErrorPF2e("Unexpected error processing roll template");adjustment.circumstances.length>0&&(adjustedNode.dataset.tooltip=adjustment.circumstances.map(a=>createHTMLElement("div",{children:[`${a.label}: ${signedInteger(a.value)}`]}).outerHTML).join(` +`))}if(convertXMLNode(html,"unadjusted",{visible:resultData.visible,classes:degree.adjustment?["unadjusted"]:[DEGREE_OF_SUCCESS_STRINGS[degree.value]]}),degree.adjustment){const adjustedNode=convertXMLNode(html,"adjusted",{visible:resultData.visible,classes:[DEGREE_OF_SUCCESS_STRINGS[degree.value],"adjusted"]});if(!adjustedNode)throw ErrorPF2e("Unexpected error processing roll template");adjustedNode.dataset.tooltip=degree.adjustment.label}if(convertXMLNode(html,"offset",{visible:dcData.visible,whose:"target"}),!targetData?.visible&&!dcData.visible){const targetDC=html.querySelector(".target-dc");targetDC&&(targetDC.dataset.visibility="gm"),resultData.visible||(html.dataset.visibility="gm")}return html},"#createResultFlavor"),__privateAdd(_CheckPF2e,_createTagFlavor),__privateAdd(_CheckPF2e,_createResultFlavor),__name2(_CheckPF2e,"CheckPF2e");let CheckPF2e=_CheckPF2e;const _CheckContextError=class extends Error{static{__name(this,"_CheckContextError")}constructor(message,actor,slug){super(message),this.actor=actor,this.slug=slug}};__name2(_CheckContextError,"CheckContextError");let CheckContextError=_CheckContextError;const _ActionMacroHelpers=class{static{__name(this,"_ActionMacroHelpers")}static resolveStat(stat){switch(stat){case"perception":return{checkType:"perception-check",property:"perception",stat,subtitle:"PF2E.ActionsCheck.perception"};case"unarmed":return{checkType:"attack-roll",property:"unarmed",stat,subtitle:"PF2E.ActionsCheck.unarmed"};default:return{checkType:"skill-check",property:`skills.${sluggify(stat)}`,stat,subtitle:`PF2E.ActionsCheck.${stat}`}}}static defaultCheckContext(options,data){const{checkType:type,property,stat:slug,subtitle}=this.resolveStat(data.slug),statistic=options.actor.getStatistic(data.slug)??getProperty(options.actor,property);if(!statistic){const{actor}=options,message=`Actor ${actor.name} (${actor.id}) does not have a statistic for ${slug}.`;throw new CheckContextError(message,actor,slug)}const{item,rollOptions:contextualRollOptions}=options.buildContext({actor:options.actor,item:data.item,rollOptions:[...data.rollOptions],target:options.target});return{item,modifiers:data.modifiers??[],rollOptions:contextualRollOptions,slug,statistic,subtitle,type}}static note(selector,translationPrefix,outcome,translationKey){const outcomes=game.settings.get("pf2e","metagame_showResults")?[outcome]:[];return new RollNotePF2e({selector,text:game.i18n.localize(translationKey??`${translationPrefix}.Notes.${outcome}`),outcome:outcomes})}static outcomesNote(selector,translationKey,outcomes){const visibleOutcomes=game.settings.get("pf2e","metagame_showResults")?outcomes:[];return new RollNotePF2e({selector,text:game.i18n.localize(translationKey),outcome:visibleOutcomes})}static async simpleRollActionCheck(options){const rollers=[];if(Array.isArray(options.actors)?rollers.push(...options.actors):options.actors?rollers.push(options.actors):rollers.push(...getSelectedOrOwnActors()),rollers.length===0)throw new Error(game.i18n.localize("PF2E.ActionsWarning.NoActor"));const targetData=options.target?.()??this.target();for(const actor of rollers)try{const selfToken=actor.getActiveTokens(!1,!0).shift(),{item:weapon,modifiers=[],rollOptions:combinedOptions,statistic,subtitle,type}=await options.checkContext({actor,buildContext:args=>{const combinedOptions2=compact([args.rollOptions,options.traits].flat());return combinedOptions2.push(...args.item?.getRollOptions("item")??[]),{item:args.item,rollOptions:combinedOptions2.sort(),target:args.target}},target:targetData.actor}),header=await renderTemplate("systems/pf2e/templates/chat/action/header.hbs",{glyph:options.actionGlyph,subtitle,title:options.title}),actionTraits2=CONFIG.PF2E.actionTraits,traitDescriptions2=CONFIG.PF2E.traitsDescriptions,traitObjects=options.traits.map(trait=>({description:traitDescriptions2[trait],name:trait,label:actionTraits2[trait]??trait})),notes=options.extraNotes?.(statistic.slug)??[],label=await options.content?.(header)??header,title=`${game.i18n.localize(options.title)} - ${game.i18n.localize(subtitle)}`;if(statistic instanceof Statistic){const dc=__privateMethod(this,_resolveCheckDC,resolveCheckDC_fn).call(this,{unresolvedDC:options.difficultyClass});await statistic.roll({...eventToRollParams(options.event),token:selfToken,label,title,dc,extraRollNotes:notes,extraRollOptions:combinedOptions,modifiers,target:targetData.actor,traits:traitObjects,createMessage:options.createMessage,callback:(roll,outcome,message)=>{options.callback?.({actor,message,outcome,roll})}})}else{const check=new CheckModifier(label,statistic,modifiers),dc=__privateMethod(this,_resolveCheckDC,resolveCheckDC_fn).call(this,{target:targetData.actor,unresolvedDC:options.difficultyClass,fully:!0}),finalOptions=new Set(combinedOptions);ensureProficiencyOption(finalOptions,statistic.rank??-1),check.calculateTotal(finalOptions);const selfActor=actor.getContextualClone(combinedOptions.filter(o=>o.startsWith("self:"))),distance=(()=>{const reach=selfActor.isOfType("creature")&&weapon?.isOfType("weapon")?selfActor.getReach({action:"attack",weapon})??null:null;return selfToken?.object&&targetData?.token?.object?selfToken.object.distanceTo(targetData.token.object,{reach}):null})(),rangeIncrement=weapon?.isOfType("weapon")&&typeof distance=="number"?getRangeIncrement(weapon,distance):null,domains=["all",type,statistic.slug],targetInfo=targetData.token&&targetData.actor&&typeof distance=="number"?{token:targetData.token,actor:targetData.actor,distance,rangeIncrement}:null,substitutions=extractRollSubstitutions(actor.synthetics.rollSubstitutions,domains,finalOptions),dosAdjustments=extractDegreeOfSuccessAdjustments(actor.synthetics,domains);await CheckPF2e.roll(check,{actor:selfActor,token:selfToken,item:weapon,createMessage:options.createMessage,target:targetInfo,dc,type,options:finalOptions,notes:[...notes,...statistic.notes??[]],dosAdjustments,substitutions,traits:traitObjects,title},options.event,(roll,outcome,message)=>{options.callback?.({actor,message,outcome,roll})})}}catch(cce){if(cce instanceof CheckContextError){const message=game.i18n.format("PF2E.ActionsWarning.NoStatistic",{id:cce.actor.id,name:cce.actor.name,statistic:cce.slug});ui.notifications.error(message);continue}throw cce}}static target(){const target=Array.from(game.user.targets).filter(t=>t.actor?.isOfType("creature")).shift()?.document??null,targetActor=target?.actor??null;return{token:target,actor:targetActor}}static getWeaponPotencyModifier(item,selector){const slug="potency";return AutomaticBonusProgression.isEnabled(item.actor)?new ModifierPF2e({slug,type:"potency",label:"PF2E.AutomaticBonusProgression.attackPotency",modifier:item.actor.synthetics.weaponPotency["strike-attack-roll"]?.[0]?.bonus??0,adjustments:extractModifierAdjustments(item.actor.synthetics.modifierAdjustments,[selector],slug)}):item.system.runes.potency>0?new ModifierPF2e({slug,type:"item",label:"PF2E.Item.Weapon.Rune.Potency",modifier:item.system.runes.potency,adjustments:extractModifierAdjustments(item.actor.synthetics.modifierAdjustments,[selector],slug)}):null}static getApplicableEquippedWeapons(actor,trait){return actor.isOfType("character")?actor.system.actions.flatMap(s=>s.ready&&s.item.traits.has(trait)?s.item:[]):actor.itemTypes.weapon.filter(w=>w.isEquipped&&w.traits.has(trait))}};_resolveCheckDC=new WeakSet,resolveCheckDC_fn=__name2(function({unresolvedDC=null,target=null,fully=!1}){return typeof unresolvedDC=="string"?fully?target?.getStatistic(unresolvedDC)?.dc??null:{slug:unresolvedDC}:typeof unresolvedDC=="function"?unresolvedDC(target):unresolvedDC},"#resolveCheckDC"),__privateAdd(_ActionMacroHelpers,_resolveCheckDC),__name2(_ActionMacroHelpers,"ActionMacroHelpers");let ActionMacroHelpers=_ActionMacroHelpers;const _SelectItemDialog=class extends Application{static{__name(this,"_SelectItemDialog")}constructor(action2,resolve){super(),__privateAdd(this,_item,null),__privateAdd(this,_resolve2,void 0),__privateAdd(this,_action,void 0),__privateSet(this,_action,action2),__privateSet(this,_resolve2,resolve)}static get defaultOptions(){return{...super.defaultOptions,width:270}}get template(){return __privateGet(this,_action)==="craft"?"systems/pf2e/templates/system/actions/craft-target-item.hbs":"systems/pf2e/templates/system/actions/repair/select-item-dialog.hbs"}get title(){const key=sluggify(__privateGet(this,_action),{camel:"bactrian"});return game.i18n.localize(`PF2E.Actions.${key}.SelectItemDialog.Title`)}async getData(options={}){return options.classes=[`select-${__privateGet(this,_action)}-item-dialog`],{...await super.getData(options),item:__privateGet(this,_item)}}activateListeners($html){super.activateListeners($html);const html=$html[0];html.addEventListener("drop",async event=>{const json2=event.dataTransfer?.getData("text/plain");if(!json2?.startsWith("{")||!json2.endsWith("}"))return;const data=JSON.parse(json2),uuid=data.uuid??data.pf2e?.itemUuid,item=uuid?await fromUuid(uuid):null;if(__privateGet(this,_action)==="repair"&&item&&!(item?.isEmbedded&&item.isOwner))ui.notifications.error("DOCUMENT.UsePermissionWarn",{localize:!0});else if(item instanceof PhysicalItemPF2e)__privateSet(this,_item,item),this.render();else{const key=sluggify(__privateGet(this,_action),{camel:"bactrian"});ui.notifications.error(game.i18n.localize(`PF2E.Actions.${key}.Error.ItemReferenceMismatch`))}}),htmlQuery(html,`[data-event-handler=${__privateGet(this,_action)}]`)?.addEventListener("click",()=>{this.close()}),htmlQuery(html,"[data-event-handler=cancel]")?.addEventListener("click",()=>{__privateSet(this,_item,null),this.close()})}close(options){return __privateGet(this,_resolve2).call(this,__privateGet(this,_item)),super.close(options)}static async getItem(action2){return new Promise(resolve=>{new this(action2,resolve).render(!0)})}};_item=new WeakMap,_resolve2=new WeakMap,_action=new WeakMap,__name2(_SelectItemDialog,"SelectItemDialog");let SelectItemDialog=_SelectItemDialog;async function craft(options){const item=options.item??(options.uuid?await fromUuid(options.uuid):await SelectItemDialog.getItem("craft"));if(item){if(!(item instanceof PhysicalItemPF2e)){ui.notifications.warn(game.i18n.format("PF2E.Actions.Craft.Warning.NotPhysicalItem",{item:item.name??""}));return}}else{console.warn("PF2e System | No item selected to craft: aborting");return}const quantity=options.quantity??1,proficiencyWithoutLevel=game.settings.get("pf2e","proficiencyVariant"),dc=options.difficultyClass??{value:calculateDC(item.level,{proficiencyWithoutLevel}),visible:!0},free=!!options.free,slug=options?.skill??"crafting",rollOptions=["action:craft"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.Craft.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["downtime","manipulate"],event:options.event,difficultyClass:dc,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Craft","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Craft","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Craft","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Craft","criticalFailure")],createMessage:!1,callback:async result=>{if(result.message instanceof ChatMessagePF2e){const message=result.message,flavor=await(async()=>["criticalSuccess","success","criticalFailure"].includes(result.outcome??"")?await renderCraftingInline(item,result.roll,quantity,result.actor,free):"")();flavor&&message.updateSource({flavor:message.flavor+flavor}),ChatMessage.create(message.toObject())}else console.error("PF2E | Unable to amend chat message with craft result.",result.message);options.callback?.(result)}}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(craft,"craft"),__name2(craft,"craft");function createEmptySpellcastingEntry(actor){return new SpellcastingEntryPF2e({name:"Untitled",type:"spellcastingEntry",system:{ability:{value:"cha"},spelldc:{value:0,dc:0},tradition:{value:"arcane"},prepared:{value:"innate"}}},{actor})}__name(createEmptySpellcastingEntry,"createEmptySpellcastingEntry"),__name2(createEmptySpellcastingEntry,"createEmptySpellcastingEntry");const _SpellcastingCreateAndEditDialog=class extends FormApplication{static{__name(this,"_SpellcastingCreateAndEditDialog")}constructor(object,options){super(object instanceof ActorPF2e?createEmptySpellcastingEntry(object):object.clone({},{keepId:!0}),options),__privateAdd(this,_canSetAttribute),__publicField(this,"actor"),this.actor=object instanceof ActorPF2e?object:object.actor}static get defaultOptions(){const options=super.defaultOptions;return options.id="spellcasting-dialog",options.classes=[],options.title=game.i18n.localize("PF2E.SpellcastingSettings.Title"),options.template="systems/pf2e/templates/actors/spellcasting-dialog.hbs",options.width=350,options.submitOnChange=!0,options.closeOnSubmit=!1,options}async getData(){const{actor}=this,extraStatistics=actor.synthetics.statistics.values(),classDCs=actor.isOfType("character")?Object.values(actor.system.proficiencies.classDCs).filter(cdc=>cdc.rank>0):[],selectedStatistic=actor.getStatistic(this.object.system.proficiency.slug);return{...await super.getData(),actor,system:this.object.toObject().system,statistics:[...extraStatistics,...classDCs.map(c=>({slug:c.slug,label:game.i18n.format("PF2E.Actor.Character.ClassDC.LabelSpecific",{class:c.label})}))],magicTraditions:CONFIG.PF2E.magicTraditions,spellcastingTypes:omit(CONFIG.PF2E.preparationType,["ritual"]),attributes:CONFIG.PF2E.abilities,isAttributeConfigurable:__privateMethod(this,_canSetAttribute,canSetAttribute_fn).call(this),selectedAttribute:selectedStatistic?.attribute??this.object.attribute}}async _updateObject(event,formData){const wasInnate=this.object.isInnate,inputData=expandObject(formData),system=mergeObject(inputData.system??{},{prepared:{value:this.object.system.prepared.value},ability:{value:"cha"}},{overwrite:!1});if(inputData.system=system,system.prepared.value==="innate"&&!wasInnate&&(system.ability.value="cha"),system.proficiency?.slug&&(system.ability.value=""),system?.autoHeightenLevel&&(system.autoHeightenLevel.value||=null),this.object.updateSource(inputData),this.object.reset(),event.type!=="submit"){await this.render();return}return this.updateAndClose()}async updateAndClose(){const updateData=this.object.toObject();if(this.object.isRitual&&(updateData.system.tradition.value="",updateData.system.ability.value=""),this.object.isPrepared||delete updateData.system.prepared.flexible,this.object.id===null)updateData.name=(()=>{const preparationType=game.i18n.localize(CONFIG.PF2E.preparationType[updateData.system.prepared.value])??"",magicTraditions2=CONFIG.PF2E.magicTraditions,traditionSpells=game.i18n.localize(magicTraditions2[this.object.tradition??""]);return this.object.isRitual||!traditionSpells?preparationType:game.i18n.format("PF2E.SpellCastingFormat",{preparationType,traditionSpells})})(),await this.actor.createEmbeddedDocuments("Item",[updateData]);else{const actualEntry=this.actor.spellcasting.get(this.object.id);if(!(actualEntry instanceof SpellcastingEntryPF2e))return;const system=pick(updateData.system,["prepared","tradition","ability","proficiency","autoHeightenLevel"]);await actualEntry.update({system})}this.close()}};_canSetAttribute=new WeakSet,canSetAttribute_fn=__name2(function(){const slug=this.object._source.system.proficiency.slug,baseStat=this.actor.isOfType("character")?this.actor.getStatistic(slug):null;return!slug||!!baseStat&&!baseStat.attribute},"#canSetAttribute"),__name2(_SpellcastingCreateAndEditDialog,"SpellcastingCreateAndEditDialog");let SpellcastingCreateAndEditDialog=_SpellcastingCreateAndEditDialog;async function createSpellcastingDialog(event,object){return new SpellcastingCreateAndEditDialog(object,{top:event.clientY-80,left:window.innerWidth-710,height:"auto"}).render(!0)}__name(createSpellcastingDialog,"createSpellcastingDialog"),__name2(createSpellcastingDialog,"createSpellcastingDialog");const _SpellPreparationSheet=class extends ActorSheet{static{__name(this,"_SpellPreparationSheet")}constructor(item,options){super(item.actor,options),__privateAdd(this,_getSpellFromEvent),__publicField(this,"itemRenderer",new ItemSummaryRenderer(this)),__privateAdd(this,_searchEngine,new MiniSearch({fields:["name"],idField:"id",processTerm:t=>t.length>1?t.toLocaleLowerCase(game.i18n.lang):null,searchOptions:{combineWith:"AND",prefix:!0}})),this.item=item}static get defaultOptions(){return{...super.defaultOptions,classes:["default","sheet","spellcasting-entry","preparation"],width:480,height:600,template:"systems/pf2e/templates/actors/spellcasting-prep-sheet.hbs",scrollY:[".sheet-content"],filters:[{inputSelector:"input[type=search]",contentSelector:"ol.directory-list"}],sheetConfig:!1}}get id(){return`${super.id}-spellprep-${this.item.id}`}get title(){return game.i18n.format("PF2E.Actor.Creature.SpellPreparation.Title",{actor:this.actor.name})}_getHeaderButtons(){return super._getHeaderButtons().filter(b=>b.class==="close")}async getData(){__privateGet(this,_searchEngine).removeAll();const entry=await this.item.getSheetData(),spells=Object.values(entry.spellPrepList??{}).flat().map(s=>pick$1(s.spell,["id","name"]));return __privateGet(this,_searchEngine).addAll(spells),{...await super.getData(),owner:this.actor.isOwner,entry}}activateListeners($html){super.activateListeners($html);const html=$html[0];this.itemRenderer.activateListeners(html),html.addEventListener("click",event=>{const anchor=htmlClosest(event.target,"[data-action]"),action2=anchor?.dataset.action;if(anchor&&action2)switch(action2){case"edit-spell":{__privateMethod(this,_getSpellFromEvent,getSpellFromEvent_fn).call(this,event).sheet.render(!0);return}case"delete-spell":{__privateMethod(this,_getSpellFromEvent,getSpellFromEvent_fn).call(this,event).delete();return}case"spell-to-chat":{__privateMethod(this,_getSpellFromEvent,getSpellFromEvent_fn).call(this,event).toMessage(event);return}case"toggle-flexible-collection":{const spell=__privateMethod(this,_getSpellFromEvent,getSpellFromEvent_fn).call(this,event);spell.update({"system.location.signature":!spell.system.location.signature});return}case"create-spell":{onClickCreateSpell(this.actor,{...anchor?.dataset,location:this.item.id});return}case"browse-spells":{const level=Number(anchor.dataset.level)||0;game.pf2e.compendiumBrowser.openSpellTab(this.item,level)}}})}_onSearchFilter(_event,query,_rgx,html){const matches=query.length>1?new Set(__privateGet(this,_searchEngine).search(query).map(s=>s.id)):new Set;for(const row of htmlQueryAll(html,"li[data-item-id]"))row.hidden=query.length>1&&!matches.has(row.dataset.itemId??"")}async _onDropItemCreate(itemSource){const spellSources=(Array.isArray(itemSource)?itemSource:[itemSource]).filter(source=>source.type==="spell");for(const spellSource of spellSources)spellSource.system.location.value=this.item.id;return super._onDropItemCreate(spellSources)}async _onSortItem(event,itemData){if(itemData.type!=="spell")return[];const spell=this.actor.items.get(itemData._id);return itemData.system.location.value!==this.item.id&&spell?.isOfType("spell")?[await this.item.spells?.addSpell(spell)??[]].flat():super._onSortItem(event,itemData)}async _renderInner(data,options){return this.itemRenderer.saveAndRestoreState(()=>super._renderInner(data,options))}};_searchEngine=new WeakMap,_getSpellFromEvent=new WeakSet,getSpellFromEvent_fn=__name2(function(event){const itemId=htmlClosest(event.target,"li[data-item-id]")?.dataset.itemId,item=this.actor.items.get(itemId,{strict:!0});if(!item.isOfType("spell"))throw ErrorPF2e("Unexpected item type");return item},"#getSpellFromEvent"),__name2(_SpellPreparationSheet,"SpellPreparationSheet");let SpellPreparationSheet=_SpellPreparationSheet;const _CreatureSheetPF2e=class extends ActorSheetPF2e{static{__name(this,"_CreatureSheetPF2e")}constructor(){super(...arguments),__privateAdd(this,_onConfigureActor),__privateAdd(this,_onToggleSignatureSpell),__privateAdd(this,_onClickBrowseActions),__privateAdd(this,_onClickBrowseSpellCompendia)}async getData(options){const sheetData=await super.getData(options),{actor}=this;if(sheetData.data.saves)for(const key of["fortitude","reflex","will"]){const save=sheetData.data.saves[key];save.icon=this.getProficiencyIcon(save.rank),save.hover=CONFIG.PF2E.proficiencyLevels[save.rank],save.label=CONFIG.PF2E.saves[key]}if(sheetData.data.attributes!==void 0&&(sheetData.data.attributes.perception.icon=this.getProficiencyIcon(sheetData.data.attributes.perception.rank),sheetData.data.attributes.perception.hover=CONFIG.PF2E.proficiencyLevels[sheetData.data.attributes.perception.rank]),sheetData.data.abilities)for(const key of ATTRIBUTE_ABBREVIATIONS)sheetData.data.abilities[key].label=CONFIG.PF2E.abilities[key];if(sheetData.data.skills){const skills=sheetData.data.skills;for(const[key,skill]of Object.entries(skills)){const label=objectHasKey(CONFIG.PF2E.skills,key)?CONFIG.PF2E.skills[key]:null;skill.icon=this.getProficiencyIcon(skill.rank??0),skill.hover=CONFIG.PF2E.proficiencyLevels[skill.rank??0],skill.label=skill.label??label??""}}return{...sheetData,languages:createSheetTags(CONFIG.PF2E.languages,actor.system.traits.languages),abilities:CONFIG.PF2E.abilities,actorSizes:CONFIG.PF2E.actorSizes,alignments:deepClone(CONFIG.PF2E.alignments),rarity:CONFIG.PF2E.rarityTraits,frequencies:CONFIG.PF2E.frequencies,attitude:CONFIG.PF2E.attitude,pfsFactions:CONFIG.PF2E.pfsFactions,dying:{maxed:actor.attributes.dying.value>=actor.attributes.dying.max,remainingDying:Math.max(actor.attributes.dying.max-actor.attributes.dying.value),remainingWounded:Math.max(actor.attributes.wounded.max-actor.attributes.wounded.value)}}}openSpellPreparationSheet(entryId){const entry=this.actor.items.get(entryId);if(entry?.isOfType("spellcastingEntry")&&entry.isPrepared){const offset=this.element.find(`.item-container[data-container-id="${entry.id}"] .prepared-toggle`).offset()??{left:0,top:0};new SpellPreparationSheet(entry,{top:offset.top-60,left:offset.left+200}).render(!0)}}async prepareSpellcasting(){return(await Promise.all(this.actor.spellcasting.map(async entry=>entry.getSheetData()))).sort((a,b)=>a.sort-b.sort)}getProficiencyIcon(level){return[...Array(level)].map(()=>fontAwesomeIcon("check-circle").outerHTML).join("")}activateListeners($html){super.activateListeners($html);const html=$html[0],carryMenuListener=__name2(event=>{if(!(event.currentTarget instanceof HTMLElement))throw ErrorPF2e("Unexpected error retrieving carry-type link");const menu=event.currentTarget,toggle=menu.nextElementSibling;toggle?.classList.contains("carry-type-hover")&&$(toggle).tooltipster("close");const carryType=menu.dataset.carryType;if(!setHasElement(ITEM_CARRY_TYPES,carryType))throw ErrorPF2e("Unexpected error retrieving requested carry type");const itemId=htmlClosest(menu,"[data-item-id]")?.dataset.itemId,item=this.actor.inventory.get(itemId,{strict:!0}),handsHeld=Number(menu.dataset.handsHeld)||0,inSlot=menu.dataset.inSlot==="true",current=item.system.equipped;(carryType!==current.carryType||inSlot!==current.inSlot||carryType==="held"&&handsHeld!==current.handsHeld)&&this.actor.adjustCarryType(item,{carryType,handsHeld,inSlot})},"carryMenuListener");for(const carryTypeMenu of htmlQueryAll(html,".tab.inventory a[data-carry-type]"))carryTypeMenu.addEventListener("click",carryMenuListener);const selectors="input[data-item-id][data-item-property], select[data-item-id][data-item-property]";$html.find(selectors).on("change",event=>{const $target=$(event.target),{itemId,itemProperty}=event.target.dataset;if(!itemId||!itemProperty)return;const value=(()=>{const value2=$(event.target).val();if(typeof value2>"u"||value2===null)return value2;switch($target.attr("data-dtype")??($target.attr("type")==="checkbox"?"Boolean":["number","range"].includes($target.attr("type")??"")?"Number":"String")){case"Boolean":return typeof value2=="boolean"?value2:value2==="true";case"Number":return Number(value2);case"String":return String(value2);default:return value2}})();this.actor.updateEmbeddedDocuments("Item",[{_id:itemId,[itemProperty]:value}])}),$html.find(".dots.dying, .dots.wounded").on("click contextmenu",event=>{const condition=Array.from(event.delegateTarget.classList).find(className=>["dying","wounded"].includes(className));if(condition){const currentMax=this.actor.system.attributes[condition]?.max;event.type==="click"&¤tMax?this.actor.increaseCondition(condition,{max:currentMax}):event.type==="contextmenu"&&this.actor.decreaseCondition(condition)}}),$html.find("[data-action=recovery-check]").tooltipster({theme:"crb-hover"}).filter(":not(.disabled)").on("click",event=>{this.actor.rollRecovery(event)}),$html.find(".skill-name.rollable, .skill-score.rollable").on("click",event=>{const skill=event.currentTarget.closest("[data-skill]")?.dataset.skill??"",key=objectHasKey(SKILL_DICTIONARY,skill)?SKILL_DICTIONARY[skill]:skill,rollParams=eventToRollParams(event);this.actor.skills[key]?.check.roll(rollParams)});for(const element of htmlQueryAll(html,"a[data-action=perception-check]"))element.addEventListener("click",event=>{const extraRollOptions=element.dataset.secret?["secret"]:[];this.actor.perception.roll({...eventToRollParams(event),extraRollOptions})});for(const section of htmlQueryAll(html,".tab.spellcasting, .tab.spells")??[]){for(const element of htmlQueryAll(section,"[data-action=spellcasting-create]")??[])element.addEventListener("click",event=>{createSpellcastingDialog(event,this.actor)});for(const element of htmlQueryAll(section,"[data-action=spellcasting-edit]")??[])element.addEventListener("click",event=>{const containerId=htmlClosest(event.target,"[data-item-id]")?.dataset.itemId,entry=this.actor.items.get(containerId,{strict:!0});entry.isOfType("spellcastingEntry")&&createSpellcastingDialog(event,entry)});for(const element of htmlQueryAll(section,"[data-action=spellcasting-remove]")??[])element.addEventListener("click",async event=>{const itemId=htmlClosest(event.currentTarget,"[data-item-id]")?.dataset.itemId,item=this.actor.items.get(itemId,{strict:!0}),title=game.i18n.localize("PF2E.DeleteSpellcastEntryTitle"),content=await renderTemplate("systems/pf2e/templates/actors/delete-spellcasting-dialog.hbs");await Dialog.confirm({title,content})&&item.delete()})}$html.find(".prepared-toggle").on("click",async event=>{event.preventDefault();const itemId=$(event.currentTarget).parents(".item-container").attr("data-container-id")??"";this.openSpellPreparationSheet(itemId)});for(const toggle of htmlQueryAll(html,".slotless-level-toggle"))toggle.addEventListener("click",async()=>{const itemId=htmlClosest(toggle,".item-container")?.dataset.containerId??"",spellcastingEntry=this.actor.items.get(itemId);if(!spellcastingEntry?.isOfType("spellcastingEntry"))throw ErrorPF2e("Tried to toggle visibility of slotless levels on a non-spellcasting entry");await spellcastingEntry.update({"system.showSlotlessLevels.value":!spellcastingEntry.showSlotlessLevels})});for(const button of htmlQueryAll(html,"button[data-action=cast-spell]"))button.addEventListener("click",()=>{const spellEl=htmlClosest(button,".item"),{itemId,slotLevel,slotId,entryId}=spellEl?.dataset??{},collection=this.actor.spellcasting.collections.get(entryId,{strict:!0}),spell=collection.get(itemId,{strict:!0});collection.entry.cast(spell,{slot:Number(slotId??NaN),level:Number(slotLevel??NaN)})});$html.find(".spell-slots-increment-reset").on("click",event=>{const target=$(event.currentTarget),itemId=target.data().itemId,itemLevel=target.data().level,item=this.actor.items.get(itemId);if(item?.isOfType("spellcastingEntry")){const{system}=item.toObject();if(!system.slots)return;const slotLevel=goesToEleven(itemLevel)?`slot${itemLevel}`:"slot0";system.slots[slotLevel].value=system.slots[slotLevel].max,item.update({system})}else if(item?.isOfType("spell")){const max=item.system.location.uses?.max;if(!max)return;item.update({"system.location.uses.value":max})}}),$html.find(".focus-pool").on("change",event=>{this.actor.update({"system.resources.focus.max":$(event.target).val()})}),$html.find(".toggle-signature-spell").on("click",event=>{__privateMethod(this,_onToggleSignatureSpell,onToggleSignatureSpell_fn).call(this,event)});for(const button of htmlQueryAll(html,".action-browse"))button.addEventListener("click",()=>__privateMethod(this,_onClickBrowseActions,onClickBrowseActions_fn).call(this,button));for(const button of htmlQueryAll(html,".spell-browse"))button.addEventListener("click",()=>__privateMethod(this,_onClickBrowseSpellCompendia,onClickBrowseSpellCompendia_fn).call(this,button))}async _onSortItem(event,itemSource){const dropItemEl=htmlClosest(event.target,".item"),dropContainerEl=htmlClosest(event.target,".item-container"),dropSlotType=dropItemEl?.dataset.itemType,dropContainerType=dropContainerEl?.dataset.containerType,item=this.actor.items.get(itemSource._id);if(!item)return[];if(item.isOfType("spell")){if(!(dropItemEl&&dropContainerEl))return[];const entryId=dropContainerEl.dataset.containerId,collection=this.actor.spellcasting.collections.get(entryId,{strict:!0});if(dropSlotType==="spellLevel"){const{level}=dropItemEl.dataset,spell=await collection.addSpell(item,{slotLevel:Number(level)});return this.openSpellPreparationSheet(collection.id),[spell??[]].flat()}else if(dropItemEl.dataset.slotId){const dropId=Number(dropItemEl.dataset.slotId),slotRank=Number(dropItemEl.dataset.slotLevel);if(Number.isInteger(dropId)&&Number.isInteger(slotRank)){const allocated=await collection.prepareSpell(item,slotRank,dropId);if(allocated instanceof SpellcastingEntryPF2e)return[allocated]}}else if(dropSlotType==="spell"){const dropId=dropItemEl.dataset.itemId??"",target=this.actor.items.get(dropId);if(target?.isOfType("spell")&&item.id!==dropId){const sourceLocation=item.system.location.value,testSibling=__name2((item2,test)=>item2.isCantrip!==test.isCantrip?!1:!!(item2.isCantrip&&test.isCantrip||item2.isFocusSpell&&test.isFocusSpell||item2.rank===test.rank),"testSibling");if(sourceLocation===entryId&&testSibling(item,target)){const siblings=collection.filter(s=>testSibling(item,s));return await item.sortRelative({target,siblings}),[target]}else{const spell=await collection.addSpell(item,{slotLevel:target.rank});return this.openSpellPreparationSheet(collection.id),[spell??[]].flat()}}}else if(dropContainerType==="spellcastingEntry"){CONFIG.debug.hooks&&console.debug("PF2e System | ***** spell from same actor dropped on a spellcasting entry *****");const dropId=htmlClosest(event.target,".item-container")?.dataset.containerId;return dropId?[await item.update({"system.location.value":dropId})]:[]}}else if(item.isOfType("spellcastingEntry")&&dropContainerType==="spellcastingEntry"){const sourceId=item.id,dropId=dropContainerEl?.dataset.containerId??"",source=this.actor.items.get(sourceId),target=this.actor.items.get(dropId);if(source?.isOfType("spellcastingEntry")&&target?.isOfType("spellcastingEntry")&&source.id!==target.id){const siblings=this.actor.itemTypes.spellcastingEntry;return await source.sortRelative({target,siblings}),[source]}}return super._onSortItem(event,itemSource)}async _handleDroppedItem(event,item,data){const containerEl=htmlClosest(event.target,".item-container[data-container-type=spellcastingEntry]");if(containerEl&&item.isOfType("spell")&&!item.isRitual){const entryId=containerEl.dataset.containerId,collection=this.actor.spellcasting.collections.get(entryId,{strict:!0}),slotLevel=Number(htmlClosest(event.target,"[data-slot-level]")?.dataset.slotLevel??0);return this.openSpellPreparationSheet(collection.id),[await collection.addSpell(item,{slotLevel:Math.max(slotLevel,item.baseRank)})??[]].flat()}return super._handleDroppedItem(event,item,data)}_getHeaderButtons(){const buttons=super._getHeaderButtons();if(!this.actor.isOfType("character","npc"))return buttons;if(this.isEditable){const index=buttons.findIndex(b=>b.class==="close");buttons.splice(index,0,{label:"Configure",class:"configure-creature",icon:"fa-solid fa-user-gear",onclick:()=>__privateMethod(this,_onConfigureActor,onConfigureActor_fn).call(this)})}return buttons}async _updateObject(event,formData){const heldShield=this.actor.heldShield;return heldShield&&typeof formData["system.attributes.shield.hp.value"]=="number"&&await heldShield.update({"system.hp.value":formData["system.attributes.shield.hp.value"]}),delete formData["system.attributes.shield.hp.value"],super._updateObject(event,formData)}};_onConfigureActor=new WeakSet,onConfigureActor_fn=__name2(function(){this.actorConfigClass&&new this.actorConfigClass(this.actor).render(!0)},"#onConfigureActor"),_onToggleSignatureSpell=new WeakSet,onToggleSignatureSpell_fn=__name2(function(event){const{itemId}=event.target.closest(".item").dataset,spell=this.actor.items.get(itemId);spell instanceof SpellPF2e&&spell.update({"system.location.signature":!spell.system.location.signature})},"#onToggleSignatureSpell"),_onClickBrowseActions=new WeakSet,onClickBrowseActions_fn=__name2(function(button){const types=(button.dataset.actionType||"").split(","),traits=(button.dataset.actionTrait||"").split(","),categories=(button.dataset.actionCategory||"").split(",");game.pf2e.compendiumBrowser.openActionTab({types,traits,categories})},"#onClickBrowseActions"),_onClickBrowseSpellCompendia=new WeakSet,onClickBrowseSpellCompendia_fn=__name2(function(button){const level=Number(button.dataset.level??null),spellcastingIndex=htmlClosest(button,"[data-container-id]")?.dataset.containerId??"",entry=this.actor.spellcasting.get(spellcastingIndex);entry&&game.pf2e.compendiumBrowser.openSpellTab(entry,level)},"#onClickBrowseSpellCompendia"),__name2(_CreatureSheetPF2e,"CreatureSheetPF2e");let CreatureSheetPF2e=_CreatureSheetPF2e;async function add(actor,event){const weaponGroups2=CONFIG.PF2E.weaponGroups,baseWeapons=CONFIG.PF2E.baseWeaponTypes,template=await renderTemplate("systems/pf2e/templates/actors/add-combat-proficiency-dialog.hbs",{message:game.i18n.localize("PF2E.AddCombatProficiency.Message"),weaponGroups:weaponGroups2,baseWeapons});new Dialog({title:game.i18n.localize("PF2E.AddCombatProficiency.Title"),content:template,buttons:{add:{icon:fontAwesomeIcon("check").outerHTML,label:game.i18n.localize("PF2E.AddShortLabel"),callback:async $dialog=>{const selection=$dialog.find("select[name=proficiency]").val();if(typeof selection=="string"&&selection){const proficiencyKey=selection in weaponGroups2?`weapon-group-${selection}`:`weapon-base-${selection}`;await actor.addAttackProficiency(proficiencyKey);const tab=htmlClosest(event.currentTarget,".tab.skills");if(tab){const $tab=$(tab);$tab.animate({scrollTop:$tab.height()},"slow")}}}},cancel:{icon:fontAwesomeIcon("times").outerHTML,label:game.i18n.localize("Cancel")}},default:"cancel"}).render(!0)}__name(add,"add"),__name2(add,"add");function remove(actor,event){const weaponGroups2=CONFIG.PF2E.weaponGroups,baseWeapons=CONFIG.PF2E.baseWeaponTypes,key=htmlClosest(event.currentTarget,"li.skill.custom")?.dataset.skill??"",translationKey=key?.replace(/^weapon-(?:base|group)-/,"")??"",name2=objectHasKey(weaponGroups2,translationKey)?game.i18n.localize(weaponGroups2[translationKey]):baseWeapons[translationKey],localize=localizer("PF2E.RemoveCombatProficiency"),message=localize("Message",{proficiency:name2});Dialog.confirm({title:localize("Title"),content:`

${message}

`,defaultYes:!1,yes:()=>{key in(actor._source.system.proficiencies?.attacks??{})&&actor.update({[`system.proficiencies.attacks.-=${key}`]:null})}})}__name(remove,"remove"),__name2(remove,"remove");const ManageAttackProficiencies={add,remove},_AttributeBuilder=class extends Application{static{__name(this,"_AttributeBuilder")}constructor(actor){super(),__privateAdd(this,_createButtons),__privateAdd(this,_calculateAncestryBoosts),__privateAdd(this,_calculateBackgroundBoosts),__privateAdd(this,_calculateLeveledBoosts),__privateAdd(this,_getBoostFlawLabels),__publicField(this,"actor"),__privateAdd(this,_abpEnabled,void 0),this.actor=actor,__privateSet(this,_abpEnabled,game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(actor)),actor.apps[this.appId]=this}static get defaultOptions(){return{...super.defaultOptions,classes:["attribute-builder"],title:game.i18n.localize("PF2E.Actor.Character.Attribute.Boosts"),template:"systems/pf2e/templates/actors/character/attribute-builder.hbs",width:"auto",height:"auto"}}get id(){return`attribute-builder-${this.actor.uuid}`}async getData(options={}){const{actor}=this,build=actor.system.build.attributes;return{...await super.getData(options),actor,attributes:CONFIG.PF2E.abilities,manual:build.manual,ancestry:actor.ancestry,background:actor.background,class:actor.class,attributeModifiers:mapValues$1(actor.abilities,(value,attribute)=>{const mod=build.manual?actor._source.system.abilities?.[attribute].mod??0:value.base;return{mod:addSign(Number(mod.toFixed(1))),label:CONFIG.PF2E.abilities[attribute]}}),manualKeyAttribute:actor.keyAttribute,keyOptions:build.keyOptions,...__privateMethod(this,_calculateAncestryBoosts,calculateAncestryBoosts_fn).call(this),backgroundBoosts:__privateMethod(this,_calculateBackgroundBoosts,calculateBackgroundBoosts_fn).call(this),legacyFlaws:actor.ancestry?.system.voluntary?.boost!==void 0,levelBoosts:__privateMethod(this,_calculateLeveledBoosts,calculateLeveledBoosts_fn).call(this)}}async _render(force,options){return maintainFocusInRender(this,()=>super._render(force,options))}async close(options={}){return delete this.actor.apps[this.appId],super.close(options)}activateListeners($html){super.activateListeners($html);const html=$html[0],{actor}=this;$html.find("[data-tooltip-content]").tooltipster({contentAsHTML:!0,arrow:!1,debug:!1,interactive:!0,maxWidth:350,side:["bottom"],theme:"crb-hover"});for(const input of htmlQueryAll(html,"input[type=text], input[type=number]"))input.addEventListener("focus",()=>{input.type==="text"&&input.dataset.dtype==="Number"&&(input.value=input.value.replace(/[^-.0-9]/g,""),input.type="number"),input.select()}),input.addEventListener("blur",()=>{if(input.type==="number"&&input.dataset.dtype==="Number"){input.type="text";const newValue=Math.clamped(Number(input.value)||0,-5,10);input.value=addSign(newValue);const propertyPath=input.dataset.property;if(!propertyPath)throw ErrorPF2e("Empty property path");actor.update({[propertyPath]:newValue})}});htmlQuery(html,"[data-action=toggle-alternate-ancestry-boosts]")?.addEventListener("click",()=>{actor.ancestry&&(actor.ancestry.system.alternateAncestryBoosts?actor.ancestry.update({"system.-=alternateAncestryBoosts":null}):actor.ancestry.update({"system.alternateAncestryBoosts":[]}))}),htmlQuery(html,"[data-action=toggle-legacy-voluntary-flaw]")?.addEventListener("click",async()=>{const ancestry=actor.ancestry;if(!ancestry)return;const voluntary=ancestry.system.voluntary;if(voluntary?.boost!==void 0){const flaws=uniq(voluntary.flaws);ancestry.update({system:{voluntary:{"-=boost":null,flaws}}})}else{const flaws=voluntary?.flaws.slice(0,2)??[];ancestry.update({system:{voluntary:{boost:null,flaws}}})}});for(const button of htmlQueryAll(html,"[data-section=ancestry] .boost"))button.addEventListener("click",async()=>{const ancestry=actor.ancestry,attribute=button.dataset.attribute;if(!ancestry||!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute))return;if(ancestry.system.alternateAncestryBoosts){const existingBoosts=ancestry.system.alternateAncestryBoosts,boosts=existingBoosts.includes(attribute)?existingBoosts.filter(b=>b!==attribute):[...existingBoosts,attribute].slice(0,2);ancestry.update({"system.alternateAncestryBoosts":boosts});return}const boostToRemove=Object.entries(ancestry.system.boosts??{}).find(([,b])=>b.selected===attribute);if(boostToRemove){await ancestry.update({[`system.boosts.${boostToRemove[0]}.selected`]:null});return}const freeBoost=Object.entries(ancestry.system.boosts??{}).find(([,b])=>!b.selected&&b.value.length>0);freeBoost&&await ancestry.update({[`system.boosts.${freeBoost[0]}.selected`]:attribute})});for(const button of htmlQueryAll(html,"[data-section=voluntary] .boost-button"))button.addEventListener("click",()=>{const ancestry=actor.ancestry,attribute=button.dataset.attribute;if(!ancestry||!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute))return;const removing=button.classList.contains("selected");if(button.dataset.action==="flaw"){const{flaws,boost}=ancestry.system.voluntary??{flaws:[]},alreadyHasFlaw=flaws.includes(attribute),isLegacy=boost!==void 0;if(removing&&alreadyHasFlaw&&!boost){flaws.splice(flaws.indexOf(attribute),1),ancestry.update({system:{voluntary:{flaws}}});return}const canDoubleFlaw=ancestry.lockedBoosts.includes(attribute)&&isLegacy,maxFlaws=isLegacy?2:6;flaws.length{const attribute=button.dataset.attribute;if(!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute))return;const boostToRemove=Object.entries(actor.background?.system.boosts??{}).find(([,b])=>b.selected===attribute);if(boostToRemove){actor.background?.update({[`system.boosts.${boostToRemove[0]}.selected`]:null});return}const freeBoost=Object.entries(actor.background?.system.boosts??{}).find(([,b])=>!b.selected&&b.value.length>0);freeBoost&&actor.background?.update({[`system.boosts.${freeBoost[0]}.selected`]:attribute})});for(const button of htmlQueryAll(html,"button[data-action=class-key-attribute]"))button.addEventListener("click",()=>{const attribute=button.dataset.attribute;if(!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute))throw ErrorPF2e(`Unrecognized attribute abbreviation: ${attribute}`);actor.system.build.attributes.manual?actor.update({"system.details.keyability.value":attribute}):actor.class?.update({"system.keyAbility.selected":attribute})});for(const button of htmlQueryAll(html,"[data-level] .boost"))button.addEventListener("click",()=>{const level=Number(htmlClosest(button,"[data-level]")?.dataset.level),attribute=button.dataset.attribute;if(!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute)||!tupleHasValue([1,5,10,15,20],level))return;const buildSource=mergeObject(actor.toObject().system.build??{},{attributes:{boosts:{}}}),boosts=buildSource.attributes.boosts[level]??=[];boosts.includes(attribute)?boosts.splice(boosts.indexOf(attribute),1):boosts.push(attribute),actor.update({"system.build":buildSource})});for(const button of htmlQueryAll(html,"button[data-action=apex]"))button.addEventListener("click",()=>{const attribute=button.dataset.attribute;if(!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute))throw ErrorPF2e(`Unrecognized attribute abbreviation: ${attribute}`);const current=this.actor.system.build.attributes.apex;actor.update({"system.build.attributes.apex":__privateGet(this,_abpEnabled)&&attribute!==current?attribute:null})});htmlQuery(html,"input[name=toggle-manual-mode]")?.addEventListener("click",()=>{actor.toggleAttributeManagement()}),htmlQuery(html,"button[data-action=close]")?.addEventListener("click",()=>this.close())}};_abpEnabled=new WeakMap,_createButtons=new WeakSet,createButtons_fn=__name2(function(){return Array.from(ATTRIBUTE_ABBREVIATIONS).reduce((accumulated,attribute)=>(accumulated[attribute]={ability:attribute},accumulated),{})},"#createButtons"),_calculateAncestryBoosts=new WeakSet,calculateAncestryBoosts_fn=__name2(function(){const{actor}=this,ancestry=actor.ancestry;if(!ancestry)return{ancestryBoosts:null,voluntaryFlaws:null};const buttons=__privateMethod(this,_createButtons,createButtons_fn).call(this),[maxBoosts,selectedBoosts]=(()=>{const alternateAncestryBoosts=ancestry.system.alternateAncestryBoosts;if(alternateAncestryBoosts)return[2,alternateAncestryBoosts];const baseBoosts=Object.values(ancestry.system.boosts),selectedBoosts2=baseBoosts.map(b=>b.selected).filter(b=>!!b);return[baseBoosts.filter(b=>b.value.length>0||b.selected).length,selectedBoosts2]})(),build=actor.system.build.attributes,netBoosted=difference(build.boosts.ancestry,build.flaws.ancestry),remaining=maxBoosts-selectedBoosts.length,lockedBoosts=ancestry.system.alternateAncestryBoosts?null:ancestry.lockedBoosts,lockedFlaws=ancestry.system.alternateAncestryBoosts?null:ancestry.lockedFlaws;for(const attribute of ATTRIBUTE_ABBREVIATIONS){const state=buttons[attribute],selected=selectedBoosts.includes(attribute);state.boost={selected,locked:lockedBoosts?.includes(attribute),disabled:selected?!1:!remaining||netBoosted.includes(attribute)},lockedFlaws?.includes(attribute)&&(state.flaw={selected:!0,locked:!0})}const voluntaryFlaws=(()=>{const voluntary=ancestry.system.voluntary??{flaws:[]},legacyFlaws=voluntary.boost!==void 0,flawsComplete=legacyFlaws&&voluntary.flaws.length>=2,buttons2=__privateMethod(this,_createButtons,createButtons_fn).call(this);for(const attribute of ATTRIBUTE_ABBREVIATIONS){const state=buttons2[attribute],numFlaws=voluntary.flaws.filter(f=>f===attribute).length;if(state.flaw={selected:numFlaws>0,disabled:!numFlaws&&flawsComplete},legacyFlaws){lockedBoosts?.includes(attribute)&&(state.flaw.second={selected:numFlaws>1,disabled:!numFlaws||numFlaws<2&&flawsComplete});const boosted=voluntary.boost===attribute;state.boost={selected:boosted,disabled:boosted?!1:!flawsComplete||!!voluntary.boost||netBoosted.includes(attribute)}}}return{remaining:voluntary&&legacyFlaws&&!voluntary.boost?1:0,buttons:buttons2,voluntaryBoostsRemaining:0,labels:__privateMethod(this,_getBoostFlawLabels,getBoostFlawLabels_fn).call(this,ancestry.system.flaws)}})();return{ancestryBoosts:{buttons,remaining,labels:__privateMethod(this,_getBoostFlawLabels,getBoostFlawLabels_fn).call(this,ancestry.system.boosts),alternate:!!ancestry.system.alternateAncestryBoosts},voluntaryFlaws}},"#calculateAncestryBoosts"),_calculateBackgroundBoosts=new WeakSet,calculateBackgroundBoosts_fn=__name2(function(){const{actor}=this;if(!actor.background)return null;const buttons=__privateMethod(this,_createButtons,createButtons_fn).call(this),boosts=Object.values(actor.background.system.boosts).filter(b=>b.value.length>0),selectedBoosts=boosts.map(b=>b.selected).filter(b=>!!b),unselectedRestricted=boosts.filter(b=>b.value.length<6&&!b.selected).flatMap(b=>b.value),remaining=boosts.length-selectedBoosts.length;for(const attribute of ATTRIBUTE_ABBREVIATIONS){const selected=selectedBoosts.includes(attribute),mightBeForced=unselectedRestricted.includes(attribute);buttons[attribute].boost={selected,disabled:!(selected||remaining)||!!unselectedRestricted.length&&!mightBeForced}}const labels=__privateMethod(this,_getBoostFlawLabels,getBoostFlawLabels_fn).call(this,actor.background.system.boosts),tooltip=(()=>{const boosts2=actor.background?.system.boosts??{};if(Object.values(boosts2).length===2&&Object.values(boosts2)[0].value.length===2&&Object.values(boosts2)[1].value.length===6){const choices=Object.values(boosts2)[0].value.map(b=>game.i18n.localize(CONFIG.PF2E.abilities[b]));return game.i18n.format("PF2E.Actor.Character.AttributeBuilder.BackgroundBoostDescription",{a:choices[0],b:choices[1]})}else return null})();return{buttons,remaining,labels,tooltip}},"#calculateBackgroundBoosts"),_calculateLeveledBoosts=new WeakSet,calculateLeveledBoosts_fn=__name2(function(){const build=this.actor.system.build.attributes,isGradual=game.settings.get("pf2e","gradualBoostsVariant"),boostIsPartial=__name2((attribute,level,isApex)=>{if(level<5||build.manual||isApex)return!1;const boosts=compact([build.boosts.ancestry.find(a=>a===attribute),build.boosts.background.find(a=>a===attribute),build.boosts.class===attribute?attribute:null,build.boosts[1].find(a=>a===attribute),level===20?build.boosts[20].find(a=>a===attribute):null,level>=15?build.boosts[15].find(a=>a===attribute):null,level>=10?build.boosts[10].find(a=>a===attribute):null,level>=5?build.boosts[5].find(a=>a===attribute):null]).length,flaws=Number(build.flaws.ancestry.some(a=>a===attribute)),netBoosts=boosts-flaws,cssClasses={0:!1,1:!0};return netBoosts>=5?cssClasses[netBoosts%2]:!1},"boostIsPartial");return[1,5,10,15,17,20].flatMap(level=>{const isApex=level===17;if(isApex&&!__privateGet(this,_abpEnabled))return[];const remaining=isApex?+!build.apex:build.allowedBoosts[level]-build.boosts[level].length,buttons=__privateMethod(this,_createButtons,createButtons_fn).call(this);for(const attribute of ATTRIBUTE_ABBREVIATIONS){const selected=isApex?build.apex===attribute:build.boosts[level].includes(attribute),partial=selected&&boostIsPartial(attribute,level,isApex);buttons[attribute].boost={selected,partial,disabled:!remaining}}const eligible=isApex?this.actor.level>=17:build.allowedBoosts[level]>0,minLevel=isGradual&&!isApex?Math.max(1,level-3):level;return{buttons,remaining,level,eligible,minLevel,isApex}})},"#calculateLeveledBoosts"),_getBoostFlawLabels=new WeakSet,getBoostFlawLabels_fn=__name2(function(boostData){return Object.values(boostData).flatMap(boosts=>boosts.value.length===6?game.i18n.localize("PF2E.AbilityFree"):boosts.value.length>0?boosts.value.map(b=>game.i18n.localize(CONFIG.PF2E.abilities[b])).join(" or "):[])},"#getBoostFlawLabels"),__name2(_AttributeBuilder,"AttributeBuilder");let AttributeBuilder=_AttributeBuilder;const _CreatureConfig=class extends DocumentSheet{static{__name(this,"_CreatureConfig")}get title(){const namespace=this.actor.isOfType("character")?"Character":"NPC";return game.i18n.localize(`PF2E.Actor.${namespace}.Configure.Title`)}get template(){return`systems/pf2e/templates/actors/${this.actor.type}/config.hbs`}get actor(){return this.object}static get defaultOptions(){const options=super.defaultOptions;return options.width=450,options}async getData(options={}){const source=this.actor._source,alliance=source.system.details?.alliance===null?"neutral":source.system.details?.alliance??"default",defaultValue=game.i18n.localize(this.actor.hasPlayerOwner?"PF2E.Actor.Creature.Alliance.Party":"PF2E.Actor.Creature.Alliance.Opposition"),allianceOptions={default:game.i18n.format("PF2E.Actor.Creature.Alliance.Default",{alliance:defaultValue}),opposition:"PF2E.Actor.Creature.Alliance.Opposition",party:"PF2E.Actor.Creature.Alliance.Party",neutral:"PF2E.Actor.Creature.Alliance.Neutral"};return{...await super.getData(options),alliances:createSheetOptions(allianceOptions,{value:[alliance]})}}async _updateObject(event,formData){const key="system.details.alliance",alliance=formData[key];if(alliance==="default")delete formData[key],formData["system.details.-=alliance"]=null;else if(alliance==="neutral")formData[key]=null;else if(!setHasElement(ALLIANCES,alliance))throw ErrorPF2e("Unrecognized alliance");return super._updateObject(event,formData)}};__name2(_CreatureConfig,"CreatureConfig");let CreatureConfig=_CreatureConfig;const _CharacterConfig=class extends CreatureConfig{static{__name(this,"_CharacterConfig")}async getData(options={}){const{showBasicUnarmed}=this.actor.flags.pf2e;return{...await super.getData(options),showBasicUnarmed}}};__name2(_CharacterConfig,"CharacterConfig");let CharacterConfig=_CharacterConfig;const _CraftingFormula=class{static{__name(this,"_CraftingFormula")}constructor(item,{dc,batchSize,deletable=!1}={}){this.item=item,this.dc=dc??calculateDC(item.level,{rarity:item.rarity,proficiencyWithoutLevel:game.settings.get("pf2e","proficiencyVariant")}),this.batchSize=Math.max(batchSize??1,this.defaultBatchSize),this.deletable=deletable}dc;batchSize;deletable;get uuid(){return this.item.uuid}get img(){return this.item.img}get name(){return this.item.name}get level(){return this.item.level}get rarity(){return this.item.rarity}get price(){return this.item.price}get cost(){return CoinsPF2e.fromPrice(this.price,this.batchSize)}get minimumBatchSize(){return STACK_DEFINITIONS[this.item.system.stackGroup??""]?.size??1}get defaultBatchSize(){const{item}=this,isMundaneAmmo=item instanceof ConsumablePF2e&&item.isAmmunition&&!item.isMagical,isConsumable=item instanceof ConsumablePF2e&&item.category!=="wand"||item instanceof WeaponPF2e&&item.baseType==="alchemical-bomb";return Math.max(this.minimumBatchSize,isMundaneAmmo?10:isConsumable?4:1)}get description(){return this.item.description}};__name2(_CraftingFormula,"CraftingFormula");let CraftingFormula=_CraftingFormula;const _CraftingEntry=class{static{__name(this,"_CraftingEntry")}constructor(actor,knownFormulas,data){__privateAdd(this,_updateRE),__publicField(this,"preparedCraftingFormulas"),__publicField(this,"preparedFormulaData"),__publicField(this,"name"),__publicField(this,"selector"),__publicField(this,"isAlchemical"),__publicField(this,"isDailyPrep"),__publicField(this,"isPrepared"),__publicField(this,"craftableItems"),__publicField(this,"maxSlots"),__publicField(this,"fieldDiscovery"),__publicField(this,"batchSize"),__publicField(this,"fieldDiscoveryBatchSize"),__publicField(this,"maxItemLevel"),__publicField(this,"parentItem"),this.selector=data.selector,this.name=data.name,this.isAlchemical=!!data.isAlchemical,this.isDailyPrep=!!data.isDailyPrep,this.isPrepared=!!data.isPrepared,this.maxSlots=data.maxSlots??0,this.maxItemLevel=data.maxItemLevel||actor.level,this.fieldDiscovery=data.fieldDiscovery?new PredicatePF2e(data.fieldDiscovery):null,this.batchSize=data.batchSize,this.fieldDiscoveryBatchSize=data.fieldDiscoveryBatchSize,this.craftableItems=new PredicatePF2e(data.craftableItems),this.preparedFormulaData=(data.preparedFormulaData||[]).map(prepData=>knownFormulas.find(formula2=>formula2.uuid===prepData.itemUUID)?prepData:null).filter(prepData=>!!prepData),this.parentItem=actor.items.get(data.parentItem,{strict:!0}),this.preparedCraftingFormulas=this.preparedFormulaData.sort((prepDataA,prepDataB)=>(prepDataA.sort??0)-(prepDataB.sort??0)).map(prepData=>{const formula=knownFormulas.find(formula2=>formula2.uuid===prepData.itemUUID);return formula?Object.assign(new CraftingFormula(formula.item),{quantity:prepData.quantity||1,expended:!!prepData.expended,isSignatureItem:!!prepData.isSignatureItem,sort:prepData.sort??0}):null}).filter(prepData=>!!prepData)}get actor(){return this.parentItem.actor}get formulas(){const formulas=this.preparedCraftingFormulas.map(formula=>({uuid:formula.uuid,img:formula.img,name:formula.name,expended:formula.expended,quantity:formula.quantity,isSignatureItem:formula.isSignatureItem}));if(this.maxSlots>0){const fill=this.maxSlots-formulas.length;if(fill>0){const nulls=new Array(fill).fill(null);return formulas.concat(nulls)}}return formulas}get reagentCost(){if(!this.isAlchemical)return 0;const fieldDiscoveryQuantity=this.preparedCraftingFormulas.filter(f=>!!this.fieldDiscovery?.test(f.item.getRollOptions("item"))||f.isSignatureItem).reduce((sum2,current)=>sum2+current.quantity,0),otherQuantity=this.preparedCraftingFormulas.filter(f=>!this.fieldDiscovery?.test(f.item.getRollOptions("item"))&&!f.isSignatureItem).reduce((sum2,current)=>sum2+current.quantity,0),fieldDiscoveryBatchSize=this.fieldDiscoveryBatchSize||3,batchSize=this.batchSize||2;return Math.floor(fieldDiscoveryQuantity/fieldDiscoveryBatchSize)+Math.ceil((fieldDiscoveryQuantity%fieldDiscoveryBatchSize+otherQuantity)/batchSize)}static isValid(data){return!!data&&!!data.name&&!!data.selector}async prepareFormula(formula){this.checkEntryRequirements(formula);const index=this.preparedFormulaData.findIndex(f=>f.itemUUID===formula.uuid);if(this.isAlchemical&&index!==-1){const formula2=this.preparedFormulaData[index];formula2.quantity?formula2.quantity+=1:formula2.quantity=2}else this.preparedFormulaData.push({itemUUID:formula.uuid,quantity:1});return __privateMethod(this,_updateRE,updateRE_fn).call(this)}checkEntryRequirements(formula,{warn=!0}={}){return this.maxSlots&&this.formulas.filter(f=>f!==null).length>=this.maxSlots?(warn&&ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.MaxSlots")),!1):this.actor.levelthis.maxItemLevel?(warn&&ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.MaxItemLevel")),!1):this.craftableItems.test(formula.item.getRollOptions("item"))?!0:(warn&&ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.ItemMissingTraits")),!1)}async unprepareFormula(index,itemUUID){const formula=this.preparedFormulaData[index];if(!(!formula||formula.itemUUID!==itemUUID))return this.preparedFormulaData.splice(index,1),__privateMethod(this,_updateRE,updateRE_fn).call(this)}async increaseFormulaQuantity(index,itemUUID){const formula=this.preparedFormulaData[index];if(!(!formula||formula.itemUUID!==itemUUID))return formula.quantity?formula.quantity+=1:formula.quantity=2,__privateMethod(this,_updateRE,updateRE_fn).call(this)}async decreaseFormulaQuantity(index,itemUUID){const formula=this.preparedFormulaData[index];if(!(!formula||formula.itemUUID!==itemUUID)){if(formula.quantity?formula.quantity-=1:formula.quantity=0,formula.quantity<=0){await this.unprepareFormula(index,itemUUID);return}return __privateMethod(this,_updateRE,updateRE_fn).call(this)}}async setFormulaQuantity(index,itemUUID,quantity){if(quantity<=0){await this.unprepareFormula(index,itemUUID);return}const formula=this.preparedFormulaData[index];if(!(!formula||formula.itemUUID!==itemUUID))return formula.quantity=quantity,__privateMethod(this,_updateRE,updateRE_fn).call(this)}async toggleFormulaExpended(index,itemUUID){const formula=this.preparedFormulaData[index];if(!(!formula||formula.itemUUID!==itemUUID))return formula.expended=!formula.expended,__privateMethod(this,_updateRE,updateRE_fn).call(this)}async toggleSignatureItem(itemUUID){const formula=this.preparedFormulaData.find(f=>f.itemUUID===itemUUID);if(formula)return formula.isSignatureItem=!formula.isSignatureItem,__privateMethod(this,_updateRE,updateRE_fn).call(this)}async updateFormulas(formulas){return this.preparedFormulaData=formulas,__privateMethod(this,_updateRE,updateRE_fn).call(this)}};_updateRE=new WeakSet,updateRE_fn=__name2(async function(){const rules=this.parentItem.toObject().system.rules,thisRule=rules.find(r=>r.key==="CraftingEntry"&&r.selector===this.selector);thisRule&&(thisRule.preparedFormulas=this.preparedFormulaData,await this.parentItem.update({"system.rules":rules}))},"#updateRE"),__name2(_CraftingEntry,"CraftingEntry");let CraftingEntry=_CraftingEntry;const _ElementalBlast=class{static{__name(this,"_ElementalBlast")}constructor(actor){if(__privateAdd(this,_prepareBlastConfigs),__privateAdd(this,_prepareBlastInfusion),__privateAdd(this,_getBlastConfig),__privateAdd(this,_createModifiedItem),__privateAdd(this,_strengthModToDamage),__publicField(this,"actor"),__publicField(this,"statistic"),__publicField(this,"item"),__publicField(this,"configs"),__publicField(this,"infusion"),!actor.isOfType("character"))throw ErrorPF2e("Must construct with a PC");this.actor=actor,this.statistic=this.actor.getStatistic("impulse"),this.item=this.actor.itemTypes.action.find(a=>a.slug==="elemental-blast")??null,this.infusion=__privateMethod(this,_prepareBlastInfusion,prepareBlastInfusion_fn).call(this),this.configs=__privateMethod(this,_prepareBlastConfigs,prepareBlastConfigs_fn).call(this)}get actionCost(){const cost=this.item?.flags.pf2e.rulesSelections.actionCost??1;if(cost!==1&&cost!==2)throw ErrorPF2e("Action cost must be 1 or 2");return cost}async attack(params){const{statistic,actionCost}=this;if(!(statistic&&this.item))throw ErrorPF2e("Unable to blast");if(!this.actor.rollOptions.all["self:effect:kinetic-aura"])throw ErrorPF2e("No kinetic gate");const{element,damageType}=params;if(!element)throw ErrorPF2e("No element provided");if(!objectHasKey(elementTraits,element))throw ErrorPF2e(`Unrecognized element: ${element}`);if(!damageType)throw ErrorPF2e("No damage type provided");if(!objectHasKey(CONFIG.PF2E.damageTypes,damageType))throw ErrorPF2e(`Unrecognized damage type: ${damageType}`);const blastConfig=__privateMethod(this,_getBlastConfig,getBlastConfig_fn).call(this,element,damageType),melee=!!(params.melee??=!0),item=__privateMethod(this,_createModifiedItem,createModifiedItem_fn).call(this,{config:blastConfig,damageType,melee});if(!item)return null;const thisToken=this.actor.getActiveTokens(!0,!1).shift()??null,targetToken=game.user.targets.first()??null;if(!params.melee&&thisToken&&targetToken&&thisToken.distanceTo(targetToken)>blastConfig.range.max)return ui.notifications.warn("PF2E.Action.Strike.OutOfRange",{localize:!0}),null;const actionSlug="elemental-blast",blastStatistic=statistic.extend({check:{domains:[`${actionSlug}-attack-roll`],modifiers:AttackTraitHelpers.createAttackModifiers({item})}}),label=await renderTemplate("systems/pf2e/templates/chat/action/header.hbs",{title:item.name,glyph:actionCost.toString(),subtitle:game.i18n.format("PF2E.ActionsCheck.x-attack-roll",{type:statistic.label})}),meleeOrRanged=params.melee?"melee":"ranged",mapIncreases=Math.clamped(params.mapIncreases??0,0,2)||0;return blastStatistic.roll({identifier:`${blastConfig.element}.${params.damageType}.${meleeOrRanged}.${actionCost}`,action:actionSlug,attackNumber:mapIncreases+1,target:targetToken?.actor??null,token:thisToken?.document??null,item,label,traits:item.system.traits.value,melee,damaging:!0,dc:{slug:"ac"},extraRollOptions:[`action:${actionSlug}`,`action:cost:${actionCost}`],...eventToRollParams(params.event)})}async damage(params){if(!this.statistic)return null;const melee=!!(params.melee??=!0),blastConfig=__privateMethod(this,_getBlastConfig,getBlastConfig_fn).call(this,params.element,params.damageType);if(!blastConfig)return null;const item=__privateMethod(this,_createModifiedItem,createModifiedItem_fn).call(this,{config:blastConfig,damageType:params.damageType,melee});if(!item)return null;const outcome=params.outcome??"success",meleeOrRanged=melee?"melee":"ranged",actionCost=Math.clamped(Number(params.actionCost??this.actionCost),1,2)||1,actionSlug="elemental-blast",domains=["damage","attack-damage","impulse-damage",`${actionSlug}-damage`],targetToken=game.user.targets.first()??null;item.flags.pf2e.attackItemBonus=blastConfig.statistic.check.modifiers.find(m=>m.enabled&&["item","potency"].includes(m.type))?.value??0;const context=await this.actor.getDamageRollContext({viewOnly:params.getFormula??!1,statistic:this.statistic.check,item,target:{token:targetToken},domains,outcome,melee,checkContext:params.checkContext,options:new Set([`action:${actionSlug}`,`action:cost:${actionCost}`,meleeOrRanged,...item.traits])}),baseDamage={category:null,damageType:params.damageType,terms:[{dice:{number:1,faces:blastConfig.dieFaces},modifier:0}]},damageSynthetics=processDamageCategoryStacking([baseDamage],{modifiers:extractModifiers(this.actor.synthetics,domains,{test:context.options,resolvables:{blast:item}}),dice:extractDamageDice(this.actor.synthetics.damageDice,domains,{test:context.options,resolvables:{blast:item,target:context.target?.actor??null}}),test:context.options}),extraModifiers=compact([...damageSynthetics.modifiers,__privateMethod(this,_strengthModToDamage,strengthModToDamage_fn).call(this,item,domains)]),modifiers=new StatisticModifier("",extraModifiers).modifiers;applyDamageDiceOverrides([baseDamage],damageSynthetics.dice);const formulaData={dice:damageSynthetics.dice,modifiers,base:[baseDamage],ignoredResistances:[]},damageContext={type:"damage-roll",sourceType:"attack",self:context.self,target:context.target,outcome,options:context.options,domains,...eventToRollParams(params.event)},damageData=createDamageFormula(formulaData,outcome==="success"?DEGREE_OF_SUCCESS.SUCCESS:DEGREE_OF_SUCCESS.CRITICAL_SUCCESS),roll=new DamageRoll(damageData.formula);if(params.getFormula)return roll.formula;const damageTemplate={name:`${game.i18n.localize("PF2E.DamageRoll")}: ${item.name}`,traits:item.system.traits.value,materials:[],modifiers,damage:{roll,breakdown:damageData.breakdown}};return DamagePF2e.roll(damageTemplate,damageContext)}async setDamageType({element,damageType}){if(!this.configs.some(c=>c.element===element&&c.damageTypes.some(dt=>dt.value===damageType)))throw ErrorPF2e(`Damage type "${damageType}" not available for ${element}`);await this.item?.update({[`flags.pf2e.damageSelections.${element}`]:damageType})}};_blastConfigSchema=new WeakMap,_blastInfusionSchema=new WeakMap,_prepareBlastConfigs=new WeakSet,prepareBlastConfigs_fn=__name2(function(){const{item,statistic,actionCost,infusion}=this;if(!item||!statistic)return[];const{kineticist}=this.actor.flags.pf2e;if(!isObject(kineticist)||!("elementalBlast"in kineticist)||!isObject(kineticist.elementalBlast))return[];const schema=__privateGet(_ElementalBlast,_blastConfigSchema),damageTypeSelections=(()=>{const flag=item.flags.pf2e.damageSelections;return isObject(flag)?flag:{}})(),blasts=Object.values(kineticist.elementalBlast).filter(b=>isObject(b)&&"element"in b).map(b=>schema.clean(b)),validationFailures=blasts.flatMap(b=>schema.validate(b)??[]);for(const failure of validationFailures)throw failure.asError();item.flags.pf2e.attackItemBonus=statistic.check.modifiers.find(m=>m.enabled&&["item","potency"].includes(m.type))?.value??0;const maps=(()=>{const domains=[...statistic.check.domains,"elemental-blast-attack-roll"],options=this.actor.getRollOptions(domains),modifier=statistic.check.mod,mapsFor=__name2(melee=>{const penalties=calculateMAPs(__privateMethod(this,_createModifiedItem,createModifiedItem_fn).call(this,{melee})??item,{domains,options});return{map1:game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(modifier+penalties.map1),penalty:penalties.map1}),map2:game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(modifier+penalties.map2),penalty:penalties.map2})}},"mapsFor");return{melee:mapsFor(!0),ranged:mapsFor(!1)}})();return blasts.map(blast=>{const damageTypes2=uniq(compact([blast.damageTypes,this.infusion?.damageTypes].flat())).map(dt=>({value:dt,label:game.i18n.localize(CONFIG.PF2E.damageTypes[dt]),icon:DAMAGE_TYPE_ICONS[dt]??"",selected:damageTypeSelections[blast.element]===dt})).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang)),firstDamageType=damageTypes2.at(0);firstDamageType&&!damageTypes2.some(dt=>dt.selected)&&(firstDamageType.selected=!0);const maxRange=infusion?.range?.max??blast.range,range=infusion?.range?.increment?{increment:infusion.range.increment,max:infusion.range.increment*6,label:game.i18n.format("PF2E.Action.Range.IncrementN",{n:infusion.range.increment})}:{increment:null,max:maxRange,label:game.i18n.format("PF2E.Action.Range.MaxN",{n:maxRange})};return{...blast,statistic,maps,item,actionCost,damageTypes:damageTypes2,range}})},"#prepareBlastConfigs"),_prepareBlastInfusion=new WeakSet,prepareBlastInfusion_fn=__name2(function(){const schema=__privateGet(_ElementalBlast,_blastInfusionSchema),flag=this.actor.flags.pf2e.kineticist,infusionData=isObject(flag)&&isObject(flag.elementalBlast)?flag.elementalBlast.infusion:null;return isObject(infusionData)?schema.clean(infusionData):null},"#prepareBlastInfusion"),_getBlastConfig=new WeakSet,getBlastConfig_fn=__name2(function(element,damageType){const config=this.configs.find(c=>c.element===element&&c.damageTypes.some(t=>t.value===damageType));if(!config)throw ErrorPF2e(`Elemental blast configuration of element ${element} and damage type ${damageType} not found.`);return config},"#getBlastConfig"),_createModifiedItem=new WeakSet,createModifiedItem_fn=__name2(function({melee,config,damageType}){const{item}=this;if(!item)return null;const traits=(()=>{const baseTraits=this.item?.system.traits.value??[],infusionTraits=melee?this.infusion?.traits.melee:this.infusion?.traits.ranged;return uniq(compact([baseTraits,infusionTraits,config?.element,damageType].flat()).filter(t=>t in CONFIG.PF2E.actionTraits)).sort()})(),clone=item.clone({system:{traits:{value:traits}}},{keepId:!0});return clone.range=melee?null:config?.range??null,clone},"#createModifiedItem"),_strengthModToDamage=new WeakSet,strengthModToDamage_fn=__name2(function(item,domains){if(!item.range)return null;const strengthModValue=this.actor.abilities.str.mod,{traits}=item,modifierValue=traits.has("thrown")?strengthModValue:traits.has("propulsive")?strengthModValue<0?strengthModValue:Math.floor(strengthModValue/2):null;return typeof modifierValue=="number"?new ModifierPF2e({slug:"str",label:CONFIG.PF2E.abilities.str,ability:"str",modifier:modifierValue,type:"ability",adjustments:extractModifierAdjustments(this.actor.synthetics.modifierAdjustments,domains,"str")}):null},"#strengthModToDamage"),__name2(_ElementalBlast,"ElementalBlast"),__privateAdd(_ElementalBlast,_blastConfigSchema,(()=>{const{fields:fields2}=foundry.data;return new fields2.SchemaField({element:new fields2.StringField({required:!0,choices:()=>CONFIG.PF2E.elementTraits,initial:void 0}),label:new fields2.StringField({required:!0,blank:!1,initial:void 0}),img:new fields2.FilePathField({required:!0,categories:["IMAGE"],nullable:!1,initial:"systems/pf2e/icons/default-icons/spell.svg"}),damageTypes:new fields2.ArrayField(new fields2.StringField({required:!0,choices:()=>CONFIG.PF2E.damageTypes,initial:void 0})),dieFaces:new fields2.NumberField({required:!0,nullable:!1,integer:!0,choices:[6,8],initial:void 0}),range:new fields2.NumberField({required:!0,nullable:!1,integer:!0,positive:!0,initial:void 0})})})()),__privateAdd(_ElementalBlast,_blastInfusionSchema,(()=>{const{fields:fields2}=foundry.data;return new fields2.SchemaField({damageTypes:new fields2.ArrayField(new fields2.StringField({required:!0,choices:()=>CONFIG.PF2E.damageTypes,initial:void 0})),range:new fields2.SchemaField({increment:new fields2.NumberField({required:!0,integer:!0,positive:!0,nullable:!1}),max:new fields2.NumberField({required:!0,integer:!0,positive:!0,nullable:!1})},{required:!1,nullable:!0,initial:null}),traits:new fields2.SchemaField({melee:new fields2.ArrayField(new fields2.StringField({required:!0,nullable:!1,choices:()=>CONFIG.PF2E.weaponTraits,initial:void 0})),ranged:new fields2.ArrayField(new fields2.StringField({required:!0,nullable:!1,choices:()=>CONFIG.PF2E.weaponTraits,initial:void 0}))})})})());let ElementalBlast=_ElementalBlast;const _PCSheetTabManager=class{static{__name(this,"_PCSheetTabManager")}constructor(actor,link){this.actor=actor,this.link=link,renderTemplate("systems/pf2e/templates/actors/character/manage-tabs.hbs").then(template=>{$(this.link).tooltipster({content:template,contentAsHTML:!0,delay:250,interactive:!0,theme:"crb-hover",title:game.i18n.localize("PF2E.TabManageTabsLabel"),trigger:"custom",triggerOpen:{click:!0},triggerClose:{originClick:!0,mouseleave:!0},functionReady:(_origin,helper)=>this.onReady(helper.tooltip),functionAfter:()=>this.onClose()})})}static initialize(actor,link){new this(actor,link)}onReady(tooltip){const tabVisibility=this.actor.flags.pf2e.sheetTabs,tabs=this.link.closest("nav")?.querySelectorAll("a.item[data-tab]")??[];for(const tab of Array.from(tabs)){const tabName=tab.dataset.tab??"",selector=`input[data-tab-name="${tabName}"]`;tooltip.querySelector(selector).checked=tabVisibility[tabName],tab.classList.contains("hidden")&&(tab.classList.remove("hidden"),tab.classList.add("to-hide"))}const checkboxes=Array.from(tooltip.querySelectorAll('input[type="checkbox"]'));for(const checkbox of checkboxes)this.handleOnChange(checkbox,checkboxes)}handleOnChange(checkbox,checkboxes){checkbox.addEventListener("change",async()=>{const nav=this.link.closest("nav"),tabName=checkbox?.dataset.tabName??"",tab=nav?.querySelector(`a.item[data-tab="${tabName}"]`);for(const c of checkboxes)c.readOnly=!0;checkbox.checked?(tab?.classList.remove("to-hide"),await this.actor.update({[`flags.pf2e.sheetTabs.-=${tabName}`]:null},{render:!1})):(tab?.classList.add("to-hide"),await this.actor.update({[`flags.pf2e.sheetTabs.${tabName}`]:!1},{render:!1}));for(const c of checkboxes)c.readOnly=!1})}onClose(){const tabs=Array.from(this.link.closest("nav")?.querySelectorAll("a.item[data-tab]")??[]);for(const tab of tabs)tab.classList.contains("to-hide")&&(tab.classList.remove("to-hide"),tab.classList.add("hidden"))}};__name2(_PCSheetTabManager,"PCSheetTabManager");let PCSheetTabManager=_PCSheetTabManager;const _CharacterSheetPF2e=class extends CreatureSheetPF2e{static{__name(this,"_CharacterSheetPF2e")}constructor(){super(...arguments),__privateAdd(this,_prepareAbilities),__privateAdd(this,_prepareCraftingEntries),__privateAdd(this,_getBlastData),__privateAdd(this,_activateBlastListeners),__privateAdd(this,_onClickBrowseFeats),__privateAdd(this,_onChangeAdjustStat),__privateAdd(this,_onChangeAdjustItemStat),__privateAdd(this,_onClickAdjustItemStat),__privateAdd(this,_getFeatSlotData),__privateAdd(this,_sortFormulas),__publicField(this,"actorConfigClass",CharacterConfig),__privateAdd(this,_knownFormulas,{}),__privateAdd(this,_formulaQuantities,{})}static get defaultOptions(){const options=super.defaultOptions;return options.classes=[...options.classes,"character"],options.width=750,options.height=800,options.scrollY.push(".tab.active .tab-content"),options.tabs=[{navSelector:".sheet-navigation",contentSelector:".sheet-content",initial:"character"},{navSelector:".actions-nav",contentSelector:".actions-panels",initial:"encounter"}],options}get template(){return`systems/pf2e/templates/actors/character/${this.actor.limited&&!game.user.isGM?"limited":"sheet"}.hbs`}async getData(options){const sheetData=await super.getData(options),{actor}=this;if(this.actor.limited){const tab=options?.tabs.find(t=>t.navSelector===".sheet-navigation");tab&&(tab.initial="biography")}sheetData.martialProficiencies={attacks:sortLabeledRecord(mapValues$1(sheetData.data.proficiencies.attacks,(data,key)=>{const groupMatch=/^weapon-group-([-\w]+)$/.exec(key),baseWeaponMatch=/^weapon-base-([-\w]+)$/.exec(key);if(objectHasKey(CONFIG.PF2E.weaponCategories,key)){const locKey=sluggify(key,{camel:"bactrian"});data.label=setHasElement(WEAPON_CATEGORIES,key)?`PF2E.Actor.Character.Proficiency.Attack.${locKey}`:CONFIG.PF2E.weaponCategories[key]}else if(Array.isArray(groupMatch)){const weaponGroup=groupMatch[1];data.label=CONFIG.PF2E.weaponGroups[weaponGroup]??weaponGroup}else if(Array.isArray(baseWeaponMatch)){const baseWeapon=baseWeaponMatch[1];data.label=CONFIG.PF2E.baseWeaponTypes[baseWeapon]??baseWeapon}else data.label??=key;const rank=data.rank??0;return data.value=createProficiencyModifier({actor,rank,domains:[]}).value,data})),defenses:sortLabeledRecord(mapValues$1(sheetData.data.proficiencies.defenses,(data,key)=>{if(key in CONFIG.PF2E.armorCategories){const locKey=sluggify(key,{camel:"bactrian"});data.label=`PF2E.Actor.Character.Proficiency.Defense.${locKey}`}const rank=data.rank??0;return data.value=createProficiencyModifier({actor,rank,domains:[]}).value,data}))};for(const key of["light-barding","heavy-barding"])sheetData.martialProficiencies.defenses[key]?.rank===0&&delete sheetData.martialProficiencies.defenses[key];sheetData.ancestry=actor.ancestry,sheetData.heritage=actor.heritage,sheetData.background=actor.background,sheetData.class=actor.class,sheetData.deity=actor.deity,sheetData.data.resources.heroPoints.hover=game.i18n.format(actor.heroPoints.value===1?"PF2E.HeroPointRatio.One":"PF2E.HeroPointRatio.Many",actor.heroPoints),sheetData.attributeBoostsAllocated=(()=>{const{build}=sheetData.data;if(build.attributes.manual||!isReallyPC(actor))return!0;const keyAttributeSelected=!sheetData.class||build.attributes.keyOptions.includes(sheetData.data.details.keyability.value),ancestryBoostsSelected=(sheetData.ancestry?.system.alternateAncestryBoosts?.length===2||Object.values(sheetData.ancestry?.system.boosts??{}).every(b=>b.value.length===0||!!b.selected))&&sheetData.ancestry?.system.voluntary?.boost!==null,backgroundBoostsSelected=Object.values(sheetData.background?.system.boosts??{}).every(b=>b.value.length===0||!!b.selected);return ancestryBoostsSelected&&backgroundBoostsSelected&&keyAttributeSelected&&[1,5,10,15,20].filter(l=>build.attributes.allowedBoosts[l]>build.attributes.boosts[l].length).length===0})();const allClassDCs=Object.values(sheetData.data.proficiencies.classDCs),classDCs=allClassDCs.filter(cdc=>cdc.rank>0||allClassDCs.length>1).map(classDC=>({...classDC,icon:this.getProficiencyIcon(classDC.rank),hover:CONFIG.PF2E.proficiencyLevels[classDC.rank],rankSlug:PROFICIENCY_RANKS[classDC.rank],rankName:game.i18n.format(`PF2E.ProficiencyLevel${classDC.rank}`)})).sort((a,b)=>a.primary?-1:b.primary?1:a.slug.localeCompare(b.slug)),primaryClassDC=sheetData.data.attributes.classDC?.slug??null;sheetData.classDCs={dcs:classDCs,primary:primaryClassDC,perDCDetails:classDCs.length>1||!primaryClassDC};const abpEnabled=game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(actor);sheetData.apexAttributeOptions=abpEnabled?[]:this.actor.itemTypes.equipment.flatMap(e=>e.system.apex?.selected===!1&&e.isInvested&&e.system.apex.attribute!==actor.system.build.attributes.apex?e.system.apex.attribute:[]),sheetData.magicTraditions=CONFIG.PF2E.magicTraditions,sheetData.preparationType=CONFIG.PF2E.preparationType,sheetData.data.attributes.perception.rankName=game.i18n.format(`PF2E.ProficiencyLevel${sheetData.data.attributes.perception.rank}`),sheetData.data.saves={fortitude:sheetData.data.saves.fortitude,reflex:sheetData.data.saves.reflex,will:sheetData.data.saves.will};for(const save of Object.values(sheetData.data.saves))save.rankName=game.i18n.format(`PF2E.ProficiencyLevel${save.rank}`);for(const save of Object.values(sheetData.data.saves))save.short=game.i18n.format(`PF2E.Saves${save.label}Short`);sheetData.data.details.keyability.singleOption=actor.class?.system.keyAbility.value.length===1,sheetData.hasStamina=game.settings.get("pf2e","staminaVariant"),sheetData.spellcastingEntries=await this.prepareSpellcasting(),sheetData.actions=__privateMethod(this,_prepareAbilities,prepareAbilities_fn).call(this),sheetData.feats=[...actor.feats,actor.feats.bonus];const craftingFormulas=await actor.getCraftingFormulas(),formulasByLevel=groupBy$1(craftingFormulas,f=>f.level),flags=actor.flags.pf2e,hasQuickAlchemy=!!(actor.rollOptions.all["feature:quick-alchemy"]||actor.rollOptions.all["feat:quick-alchemy"]);sheetData.crafting={noCost:flags.freeCrafting,hasQuickAlchemy,knownFormulas:formulasByLevel,entries:await __privateMethod(this,_prepareCraftingEntries,prepareCraftingEntries_fn).call(this,craftingFormulas)},__privateSet(this,_knownFormulas,Object.values(formulasByLevel).flat().reduce((result,entry)=>(entry.batchSize=__privateGet(this,_formulaQuantities)[entry.uuid]??entry.batchSize,result[entry.uuid]=entry,result),{})),sheetData.abpEnabled=AutomaticBonusProgression.isEnabled(actor),sheetData.data.skills=Object.fromEntries(Object.entries(sheetData.data.skills).sort(([_keyA,skillA],[_keyB,skillB])=>game.i18n.localize(skillA.label??"").localeCompare(game.i18n.localize(skillB.label??""),game.i18n.lang))),sheetData.tabVisibility=deepClone(actor.flags.pf2e.sheetTabs);const rollData=actor.getRollData(),biography=sheetData.biography=actor.system.details.biography,enrichPromises={appearance:TextEditor.enrichHTML(biography.appearance,{rollData,async:!0}),backstory:TextEditor.enrichHTML(biography.backstory,{rollData,async:!0}),campaignNotes:TextEditor.enrichHTML(biography.campaignNotes,{rollData,async:!0}),allies:TextEditor.enrichHTML(biography.allies,{rollData,async:!0}),enemies:TextEditor.enrichHTML(biography.enemies,{rollData,async:!0}),organizations:TextEditor.enrichHTML(biography.organizations,{rollData,async:!0})};await Promise.all(Object.values(enrichPromises));for(const[key,content]of Object.entries(enrichPromises))sheetData.enrichedContent[key]=await content;try{const action2=new ElementalBlast(this.actor),blastData=(await Promise.all(action2.configs.map(c=>__privateMethod(this,_getBlastData,getBlastData_fn).call(this,action2,c)))).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang));sheetData.elementalBlasts=blastData}catch{sheetData.elementalBlasts=[]}return sheetData}async prepareItems(sheetData){const actorData=sheetData.actor,lores=[];for(const itemData of sheetData.items)if(itemData.type==="lore"){itemData.system.icon=this.getProficiencyIcon((itemData.system.proficient||{}).value),itemData.system.hover=CONFIG.PF2E.proficiencyLevels[(itemData.system.proficient||{}).value];const rank=itemData.system.proficient?.value||0,proficiency=createProficiencyModifier({actor:this.actor,rank,domains:[]}).modifier,modifier=actorData.system.abilities.int.mod,itemBonus=Number((itemData.system.item||{}).value||0);itemData.system.itemBonus=itemBonus,itemData.system.value=modifier+proficiency+itemBonus,itemData.system.breakdown=`int modifier(${modifier}) + proficiency(${proficiency}) + item bonus(${itemBonus})`,lores.push(itemData)}actorData.pfsBoons=this.actor.pfsBoons,actorData.deityBoonsCurses=this.actor.deityBoonsCurses,actorData.lores=lores}prepareInventoryItem(item){const data=super.prepareInventoryItem(item);data.isInvestable=!item.isInContainer&&item.isIdentified&&item.isInvested!==null;const invested=this.actor.inventory.invested,canInvest=invested&&invested.value{this.toggleInitiativeLink()});const heroPointsPips=htmlQuery(html,"[data-action=adjust-hero-points]");heroPointsPips?.addEventListener("click",async()=>{const newValue=Math.min(this.actor.heroPoints.value+1,this.actor.heroPoints.max);await this.actor.update({"system.resources.heroPoints.value":newValue})}),heroPointsPips?.addEventListener("contextmenu",async event=>{event.preventDefault();const newValue=Math.max(this.actor.heroPoints.value-1,0);await this.actor.update({"system.resources.heroPoints.value":newValue})});for(const selectElem of htmlQueryAll(html,"select.adjust-stat-select"))selectElem.addEventListener("change",()=>__privateMethod(this,_onChangeAdjustStat,onChangeAdjustStat_fn).call(this,selectElem));$html.find(".adjust-item-stat").on("click contextmenu",event=>__privateMethod(this,_onClickAdjustItemStat,onClickAdjustItemStat_fn).call(this,event)),$html.find(".adjust-item-stat-select").on("change",event=>__privateMethod(this,_onChangeAdjustItemStat,onChangeAdjustItemStat_fn).call(this,event));{const title=$(".sheet-navigation .active").attr("title");title&&$html.find(".navigation-title").text(title)}$html.find(".sheet-navigation").on("mouseover",".item,.manage-tabs",event=>{const title=event.currentTarget.title;title&&$(event.currentTarget).parents(".sheet-navigation").find(".navigation-title").text(title)}),$html.find(".sheet-navigation").on("mouseout",".item,.manage-tabs",event=>{const parent=$(event.currentTarget).parents(".sheet-navigation"),title=parent.find(".item.active").attr("title");title&&parent.find(".navigation-title").text(title)}),$html.find(".open-compendium").on("click",event=>{if(event.currentTarget.dataset.compendium){const compendium=game.packs.get(event.currentTarget.dataset.compendium);compendium&&compendium.render(!0)}});const mainPanel=htmlQuery(html,".tab[data-tab=character]");if(mainPanel&&this.isEditable){new ContextMenu(mainPanel,".detail-item-control",[{name:"PF2E.EditItemTitle",icon:fontAwesomeIcon("edit").outerHTML,callback:target=>{const itemId=$(target).closest("[data-item-id]").attr("data-item-id");this.actor.items.get(itemId??"")?.sheet.render(!0,{focus:!0})}},{name:"PF2E.DeleteItemTitle",icon:fontAwesomeIcon("trash").outerHTML,callback:target=>{const row=htmlClosest(target[0],"[data-item-id]"),itemId=row?.dataset.itemId,item=this.actor.items.get(itemId??"");if(row&&item)this.deleteItem(row,item);else throw ErrorPF2e("Item not found")}}],{eventName:"click"});for(const link of htmlQueryAll(html,".crb-tag-selector"))link.addEventListener("click",()=>this.openTagSelector(link,{allowCustom:!1}));htmlQuery(mainPanel,"button[data-action=edit-attribute-boosts]")?.addEventListener("click",()=>{(Object.values(this.actor.apps).find(a=>a instanceof AttributeBuilder)??new AttributeBuilder(this.actor)).render(!0)});for(const link of htmlQueryAll(mainPanel,"a[data-action=apex-attribute]"))link.addEventListener("click",()=>{if(game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(this.actor))return;const attribute=htmlClosest(link,"[data-attribute]")?.dataset.attribute;if(setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute)){const apexItems=this.actor.itemTypes.equipment.filter(e=>e.system.apex),selection=apexItems.find(e=>e.isInvested&&e.system.apex?.attribute===attribute);this.actor.updateEmbeddedDocuments("Item",apexItems.map(e=>({_id:e.id,"system.apex.selected":e===selection})))}})}const actionsPanel=htmlQuery(html,".tab.actions");htmlQuery(actionsPanel,".toggle-unready-strikes")?.addEventListener("click",()=>{this.actor.setFlag("pf2e","showUnreadyStrikes",!this.actor.flags.pf2e.showUnreadyStrikes)});for(const strikeElem of htmlQueryAll(actionsPanel,".strikes-list li")){for(const tagElem of htmlQueryAll(strikeElem,".item-summary .item-properties.tags .tag"))tagElem.dataset.description&&$(tagElem).tooltipster({content:game.i18n.localize(tagElem.dataset.description),maxWidth:400,theme:"crb-hover"});const versatileToggleButtons=htmlQueryAll(strikeElem,"button[data-action=toggle-versatile]");for(const button of versatileToggleButtons)button.addEventListener("click",()=>{const weapon=this.getStrikeFromDOM(button)?.item,baseType=weapon?.system.damage.damageType??null,selection=button.classList.contains("selected")||button.value===baseType?null:button.value,selectionIsValid=objectHasKey(CONFIG.PF2E.damageTypes,selection)||selection===null;weapon&&selectionIsValid&&toggleWeaponTrait({trait:"versatile",weapon,selection})});const auxActionButtons=htmlQueryAll(strikeElem,"button[data-action=auxiliary-action]");for(const button of auxActionButtons){const modularSelect=htmlQuery(button,"select");button.addEventListener("click",()=>{const auxiliaryActionIndex=Number(button.dataset.auxiliaryActionIndex??NaN),strike=this.getStrikeFromDOM(button),selection=modularSelect?.value??null;strike?.auxiliaryActions?.at(auxiliaryActionIndex)?.execute({selection})});for(const eventType of["change","click","dragenter","input"])modularSelect?.addEventListener(eventType,event=>{event.stopImmediatePropagation()})}const meleeIcon=htmlQuery(strikeElem,".melee-icon");meleeIcon&&$(meleeIcon).tooltipster({content:game.i18n.localize("PF2E.Item.Weapon.MeleeUsage.Label"),position:"left",theme:"crb-hover"});const ammoSelect=htmlQuery(strikeElem,"select[data-action=link-ammo]");ammoSelect?.addEventListener("change",event=>{event.stopPropagation();const weapon=this.getStrikeFromDOM(ammoSelect)?.item,ammo=this.actor.items.get(ammoSelect.value);weapon?.update({system:{selectedAmmoId:ammo?.id??null}})})}for(const activeToggle of htmlQueryAll(actionsPanel,"[data-action=toggle-exploration]"))activeToggle.addEventListener("click",()=>{const actionId=htmlClosest(activeToggle,"[data-item-id]")?.dataset.itemId;if(!actionId)return;const exploration=this.actor.system.exploration.filter(id=>this.actor.items.has(id));exploration.findSplice(id=>id===actionId)||exploration.push(actionId),this.actor.update({"system.exploration":exploration})});htmlQuery(actionsPanel,"[data-action=clear-exploration]")?.addEventListener("click",()=>{this.actor.update({"system.exploration":[]})});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.actor.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.actor.addCustomModifier(stat,label,modifier,type)})}__privateMethod(this,_activateBlastListeners,activateBlastListeners_fn).call(this,actionsPanel);{const tab=html.querySelector(".tab.proficiencies");tab?.querySelector("h3.attacks-defenses")?.querySelector("button[data-action=add-attack-proficiency]")?.addEventListener("click",event=>{ManageAttackProficiencies.add(this.actor,event)});const list=tab?.querySelector("ol.combat-list")??null,links=htmlQueryAll(list,"li.custom a[data-action=remove-attack-proficiency]");for(const link of links)link.addEventListener("click",event=>{ManageAttackProficiencies.remove(this.actor,event)})}$html.find(".hover").tooltipster({trigger:"click",arrow:!1,contentAsHTML:!0,debug:!1,interactive:!0,side:["right","bottom"],theme:"crb-hover",minWidth:120}),$html.find("a[data-action=rest]").tooltipster({theme:"crb-hover"}).on("click",event=>{game.pf2e.actions.restForTheNight({event,actors:[this.actor]})}),$html.find("a[data-action=perception-check]").tooltipster({theme:"crb-hover"});const castingPanel=htmlQuery(html,".tab[data-tab=spellcasting]"),focusPips=htmlQueryAll(castingPanel,".focus-pool");if(focusPips.length>0){const listener=__name2(event=>{const change=event.type==="click"?1:-1,points=this.actor.system.resources.focus.value+change;this.actor.update({"system.resources.focus.value":points})},"listener");for(const pips of focusPips)pips.addEventListener("click",listener),pips.addEventListener("contextmenu",listener)}const craftingTab=htmlQuery(html,".tab.crafting");for(const element of htmlQueryAll(craftingTab,"li.formula-item")){const quantity=htmlQuery(element,"input[data-action=enter-quantity]");quantity?.addEventListener("change",async()=>{const itemUUID=element.dataset.itemId??"",formula=__privateGet(this,_knownFormulas)[itemUUID],minBatchSize=formula.minimumBatchSize,newValue=Number(quantity.value)||minBatchSize;if(newValue<1)return;const entrySelector=htmlClosest(element,"li.crafting-entry")?.dataset.entrySelector;if(entrySelector){const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");const index=element.dataset.itemIndex;await craftingEntry.setFormulaQuantity(Number(index),itemUUID??"",newValue);return}__privateGet(this,_formulaQuantities)[formula.uuid]=Math.max(newValue,minBatchSize),this.render()});for(const button of htmlQueryAll(element,"[data-action=increase-quantity], [data-action=decrease-quantity]"))button.addEventListener("click",async()=>{if(!quantity)return;const itemUUID=element.dataset.itemId??"",formula=__privateGet(this,_knownFormulas)[itemUUID],minBatchSize=formula.minimumBatchSize,step2=button.dataset.action==="increase-quantity"?minBatchSize:-minBatchSize,newValue=(Number(quantity.value)||step2)+step2;if(newValue<1)return;const entrySelector=htmlClosest(element,"li.crafting-entry")?.dataset.entrySelector;if(entrySelector){const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");const index=element.dataset.itemIndex;await craftingEntry.setFormulaQuantity(Number(index),itemUUID??"",newValue);return}__privateGet(this,_formulaQuantities)[formula.uuid]=Math.max(newValue,minBatchSize),this.render()});const craftButton=htmlQuery(element,"a[data-action=craft-item]");craftButton?.addEventListener("click",async event=>{const{itemUuid,free,prepared}=craftButton.dataset,itemQuantity=Number(quantity?.value)||1,formula=__privateGet(this,_knownFormulas)[itemUuid??""];if(!formula)return;if(prepared==="true"){if(element.dataset.expendedState==="true"){ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.FormulaExpended"));return}const index=element.dataset.itemIndex,entrySelector=htmlClosest(craftButton,"li.crafting-entry")?.dataset.entrySelector;if(!itemUuid||!index||!entrySelector)return;const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");await craftingEntry.toggleFormulaExpended(Number(index),itemUuid)}if(this.actor.flags.pf2e.quickAlchemy){const reagentValue=this.actor.system.resources.crafting.infusedReagents.value-1;if(reagentValue<0){ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.MissingReagents"));return}return await this.actor.update({"system.resources.crafting.infusedReagents.value":reagentValue},{render:!1}),craftItem(formula.item,1,this.actor,!0)}if(this.actor.flags.pf2e.freeCrafting){const itemId=itemUuid?.split(".").pop()??"";return isSpellConsumable(itemId)&&formula.item.isOfType("consumable")?craftSpellConsumable(formula.item,itemQuantity,this.actor):craftItem(formula.item,itemQuantity,this.actor)}const difficultyClass={value:formula.dc,visible:!0,scope:"check"};craft({difficultyClass,item:formula.item,quantity:itemQuantity,actors:this.actor,event,free:free==="true"})}),htmlQuery(element,"a.formula-delete")?.addEventListener("click",async()=>{const itemUuid=element.dataset.itemId;if(!itemUuid)return;const name2=__privateGet(this,_knownFormulas)[itemUuid]?.name,content=`

${game.i18n.format("PF2E.CraftingTab.RemoveFormulaDialogQuestion",{name:name2})}

`,title=game.i18n.localize("PF2E.CraftingTab.RemoveFormulaDialogTitle");if(await Dialog.confirm({title,content})){const actorFormulas=this.actor.toObject().system.crafting?.formulas??[];actorFormulas.findSplice(f=>f.uuid===itemUuid),this.actor.update({"system.crafting.formulas":actorFormulas})}}),htmlQuery(element,"a.formula-unprepare")?.addEventListener("click",async()=>{const itemUuid=element.dataset.itemId,index=element.dataset.itemIndex,entrySelector=element.dataset.entrySelector;if(!itemUuid||!index||!entrySelector)return;const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");const name2=__privateGet(this,_knownFormulas)[itemUuid]?.name,content=`

${game.i18n.format("PF2E.CraftingTab.UnprepareFormulaDialogQuestion",{name:name2})}

`,title=game.i18n.localize("PF2E.CraftingTab.UnprepareFormulaDialogTitle");await Dialog.confirm({title,content})&&await craftingEntry.unprepareFormula(Number(index),itemUuid)})}const $craftingTab=$html.find(".tab.crafting"),$craftingOptions=$craftingTab.find(".crafting-options input:checkbox");$craftingOptions.on("click",async event=>{const flags=[];$craftingOptions.each((_index,element)=>{element!==event.target&&flags.push($(element).attr("flag"))}),flags.forEach(async flag=>{await this.actor.setFlag("pf2e",flag,!1)})}),$craftingTab.find("a[data-action=quick-add]").on("click",async event=>{const{itemUuid}=event.currentTarget.dataset,formula=(await this.actor.getCraftingFormulas()).find(f=>f.uuid===itemUuid);if(!formula)return;const entries=(await this.actor.getCraftingEntries()).filter(e=>!!e.selector&&e.checkEntryRequirements(formula,{warn:!1}));for(const entry of entries)await entry.prepareFormula(formula);entries.length===0&&ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.NoEligibleEntry"))});const $formulas=$craftingTab.find(".craftingEntry-list");$formulas.find(".toggle-formula-expended").on("click",async event=>{const $target=$(event.currentTarget),itemUUID=$target.closest("li.formula-item").attr("data-item-id"),index=$target.closest("li.formula-item").attr("data-item-index"),entrySelector=$target.closest("li.crafting-entry").attr("data-entry-selector");if(!itemUUID||!index||!entrySelector)return;const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");await craftingEntry.toggleFormulaExpended(Number(index),itemUUID)}),$formulas.find(".toggle-signature-item").on("click",async event=>{const $target=$(event.currentTarget),itemUUID=$target.closest("li.formula-item").attr("data-item-id"),entrySelector=$target.closest("li.crafting-entry").attr("data-entry-selector");if(!itemUUID||!entrySelector)return;const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");await craftingEntry.toggleSignatureItem(itemUUID)}),$formulas.find(".infused-reagents").on("change",event=>{const change=Number($(event.target).val()),infusedReagents=this.actor.system.resources.crafting.infusedReagents,value=Math.clamped(change,0,infusedReagents?.max??0);this.actor.update({"system.resources.crafting.infusedReagents.value":value})}),$formulas.find(".daily-crafting").on("click",async()=>await this.actor.performDailyCrafting());for(const spellcastingCollectionEl of htmlQueryAll(html,".spellcasting-entry[data-item-id]")){const entry=this.actor.spellcasting.get(spellcastingCollectionEl.dataset.itemId??"");htmlQuery(spellcastingCollectionEl,"[data-action=spell-attack]")?.addEventListener("click",event=>{entry?.statistic?.check.roll(eventToRollParams(event))})}PCSheetTabManager.initialize(this.actor,$html.find("a[data-action=manage-tabs]")[0]);for(const link of htmlQueryAll(html,"[data-action=browse-feats]"))link.addEventListener("click",()=>__privateMethod(this,_onClickBrowseFeats,onClickBrowseFeats_fn).call(this,link));htmlQuery(html,".tab[data-tab=biography]")?.addEventListener("click",event=>{const section=htmlClosest(event.target,"a[data-action=toggle-bio-visibility")?.dataset.section;if(tupleHasValue(["appearance","backstory","personality","campaign"],section)){event.stopPropagation();const{biography}=this.actor.system.details,path=`system.details.biography.visibility.${section}`;this.actor.update({[path]:!biography.visibility[section]})}})}activateInventoryListeners(panel){super.activateInventoryListeners(panel),(this.isEditable?htmlQuery(panel,".inventory-pane"):null)?.addEventListener("click",event=>{const link=htmlClosest(event.target,"a[data-action=toggle-invested]"),itemId=htmlClosest(link,".item")?.dataset.itemId;itemId&&this.actor.toggleInvested(itemId)})}toggleInitiativeLink(link){if(link??=htmlQuery(this.element.get(0),"aside a[data-action=roll-initiative]"),!link)return;const alreadyRolled=game.combat&&typeof game.combat.combatants.find(c=>c.actor===this.actor)?.initiative=="number";if(!!(this.isEditable&&game.combat&&!alreadyRolled))link.classList.remove("disabled"),link.removeAttribute("title");else{link.classList.add("disabled");const reason=game.combat?alreadyRolled?"AlreadyRolled":null:"NoActiveEncounter";reason&&(link.title=game.i18n.format(`PF2E.Encounter.${reason}`,{actor:this.actor.name}))}}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("feat")){const slotData=__privateMethod(this,_getFeatSlotData,getFeatSlotData_fn).call(this,event);return this.actor.feats.insertFeat(item,slotData)}return super._onDropItem(event,data)}async _onDrop(event){const dataString=event.dataTransfer?.getData("text/plain"),dropData=(()=>{try{return JSON.parse(dataString??"")}catch{return null}})();if(dropData)if(isObject(dropData.pf2e)&&dropData.pf2e.type==="CraftingFormula"){const dropEntrySelector=typeof dropData.entrySelector=="string"?dropData.entrySelector:null;if(!dropEntrySelector){const containerEl=htmlClosest(event.target,".item-container");if(containerEl?.dataset.containerType==="craftingEntry"){const entrySelector=containerEl.dataset.entrySelector??"",craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)return;const craftingFormulas=await this.actor.getCraftingFormulas(),uuid2=dropData.pf2e.itemUuid,formula=craftingFormulas.find(f=>f.uuid===uuid2);formula&&craftingEntry.prepareFormula(formula);return}}const uuid=dropData.pf2e.itemUuid;if(typeof uuid=="string"){const formula=__privateGet(this,_knownFormulas)[uuid];if(formula){const targetUuid=htmlClosest(event.target,"li.formula-item")?.dataset.itemId??"";return __privateMethod(this,_sortFormulas,sortFormulas_fn).call(this,formula,targetUuid,dropEntrySelector)}}}else return super._onDrop(event)}async _onSortItem(event,itemSource){const item=this.actor.items.get(itemSource._id);if(item?.isOfType("feat")){const featSlot=__privateMethod(this,_getFeatSlotData,getFeatSlotData_fn).call(this,event);if(featSlot){const group=this.actor.feats.get(featSlot.groupId)??null,resorting=item.group===group&&!group?.slotted;if(group?.slotted&&!featSlot.slotId)return[];if(!resorting)return this.actor.feats.insertFeat(item,featSlot)}}return super._onSortItem(event,itemSource)}openTab(name2){["encounter","exploration","downtime"].includes(name2)?(super.openTab("actions"),this._tabs[1].activate(name2)):super.openTab(name2)}};_knownFormulas=new WeakMap,_formulaQuantities=new WeakMap,_prepareAbilities=new WeakSet,prepareAbilities_fn=__name2(function(){const{actor}=this,result={encounter:{action:{label:game.i18n.localize("PF2E.ActionsActionsHeader"),actions:[]},reaction:{label:game.i18n.localize("PF2E.ActionsReactionsHeader"),actions:[]},free:{label:game.i18n.localize("PF2E.ActionsFreeActionsHeader"),actions:[]}},exploration:{active:[],other:[]},downtime:[]};for(const item of actor.items){if(!item.isOfType("action")&&!(item.isOfType("feat")&&item.actionCost)||item.slug==="elemental-blast"&&this.actor.flags.pf2e.kineticist)continue;const 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})(),traits=item.system.traits.value,traitDescriptions2=item.isOfType("feat")?CONFIG.PF2E.featTraits:CONFIG.PF2E.actionTraits,action2={...pick$1(item,["id","name","actionCost","frequency"]),img,glyph:getActionGlyph(item.actionCost),traits:createSheetTags(traitDescriptions2,traits),feat:item.isOfType("feat")?item:null,hasEffect:!!item.system.selfEffect};if(traits.includes("exploration")){const active=actor.system.exploration.includes(item.id);action2.exploration={active},(active?result.exploration.active:result.exploration.other).push(action2)}else traits.includes("downtime")?result.downtime.push(action2):result.encounter[item.actionCost?.type??"free"]?.actions.push(action2)}for(const list of["action","reaction","free"])result.encounter[list].actions.sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang));return result.exploration.active.sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang)),result.exploration.other.sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang)),result.downtime.sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang)),result},"#prepareAbilities"),_prepareCraftingEntries=new WeakSet,prepareCraftingEntries_fn=__name2(async function(formulas){const craftingEntries={dailyCrafting:!1,other:[],alchemical:{entries:[],totalReagentCost:0,infusedReagents:this.actor.system.resources.crafting.infusedReagents}};for(const entry of await this.actor.getCraftingEntries(formulas))entry.isAlchemical?(craftingEntries.alchemical.entries.push(entry),craftingEntries.alchemical.totalReagentCost+=entry.reagentCost||0,craftingEntries.dailyCrafting=!0):(craftingEntries.other.push(entry),entry.isDailyPrep&&(craftingEntries.dailyCrafting=!0));return craftingEntries},"#prepareCraftingEntries"),_getBlastData=new WeakSet,getBlastData_fn=__name2(async function(blast,config){const damageType=config.damageTypes.find(dt=>dt.selected)?.value??"untyped",formulaFor=__name2((outcome,melee=!0)=>blast.damage({element:config.element,damageType,melee,outcome,getFormula:!0}),"formulaFor");return{...config,damageType,formula:{melee:{damage:await formulaFor("success"),critical:await formulaFor("criticalSuccess")},ranged:{damage:await formulaFor("success",!1),critical:await formulaFor("criticalSuccess",!1)}}}},"#getBlastData"),_activateBlastListeners=new WeakSet,activateBlastListeners_fn=__name2(function(panel){const blastList=htmlQuery(panel,"ol.elemental-blasts"),{elementTraits:elementTraits2,damageTypes:damageTypes2}=CONFIG.PF2E,selectors=["roll-attack","roll-damage","set-damage-type"].map(s=>`button[data-action=${s}]`).join(",");blastList?.addEventListener("click",async event=>{const button=htmlClosest(event.target,selectors),blastRow=htmlClosest(button,"li");if(!(button&&blastRow))return;event.stopPropagation();const blast=new ElementalBlast(this.actor),{element}=blastRow.dataset,damageType=button.value||blastRow.dataset.damageType;if(!objectHasKey(elementTraits2,element))throw ErrorPF2e("Unexpected error retrieve element");if(!objectHasKey(damageTypes2,damageType))throw ErrorPF2e("Unexpected error retrieving damage type");const melee=button.dataset.melee==="true";switch(button.dataset.action){case"roll-attack":{const mapIncreases=Math.clamped(Number(button.dataset.mapIncreases)||0,0,2);await blast.attack({mapIncreases,element,damageType,melee,event});break}case"roll-damage":{const outcome=button.dataset.outcome==="success"?"success":"criticalSuccess";await blast.damage({element,damageType,melee,outcome,event});break}case"set-damage-type":blast.setDamageType({element,damageType})}});for(const damageButton of htmlQueryAll(blastList,"button[data-action=roll-damage]")){const formula=damageButton.dataset.formula??"";$(damageButton).tooltipster({position:"top",theme:"crb-hover",content:formula})}},"#activateBlastListeners"),_onClickBrowseFeats=new WeakSet,onClickBrowseFeats_fn=__name2(async function(element){const maxLevel=Number(element.dataset.level)||this.actor.level,checkboxesFilterCodes=(element.dataset.filter??"").split(",").filter(s=>!!s).map(s=>s.trim()),featTab=game.pf2e.compendiumBrowser.tabs.feat,filter2=await featTab.getFilterData(),level=filter2.sliders.level;level.values.max=Math.min(maxLevel,level.values.upperLimit),level.isExpanded=level.values.max!==level.values.upperLimit;const{category}=filter2.checkboxes,{traits}=filter2.multiselects;for(const filterCode of checkboxesFilterCodes){const[filterType,...rest]=filterCode.split("-"),value=rest.join("-");if(!(filterType&&value))throw ErrorPF2e(`Invalid filter value for opening the compendium browser: "${filterCode}"`);if(filterType==="category"&&value in category.options)category.isExpanded=!0,category.options[value].selected=!0,category.selected.push(value);else if(filterType==="traits"){const trait=traits.options.find(t=>t.value===value);trait&&traits.selected.push(deepClone(trait))}else filterType==="conjunction"&&(value==="and"||value==="or")&&(filter2.multiselects.traits.conjunction=value)}return featTab.open(filter2)},"#onClickBrowseFeats"),_onChangeAdjustStat=new WeakSet,onChangeAdjustStat_fn=__name2(function(selectElem){const propertyKey=selectElem.dataset.property??"",currentValue=getProperty(this.actor,propertyKey),selectedValue=Number(selectElem.value);if(typeof currentValue!="number"||Number.isNaN(selectedValue))throw ErrorPF2e("Actor property not found");const newValue=Math.clamped(selectedValue,0,4),clone=this.actor.clone({[propertyKey]:newValue},{keepId:!0});newValue!==getProperty(clone,propertyKey)&&(ui.notifications.warn("PF2E.ErrorMessage.MinimumProfLevelSetByFeatures",{localize:!0}),selectElem.value=currentValue.toString())},"#onChangeAdjustStat"),_onChangeAdjustItemStat=new WeakSet,onChangeAdjustItemStat_fn=__name2(async function(event){const $select=$(event.delegateTarget),propertyKey=$select.attr("data-item-property")??"",selectedValue=Number($select.val()),itemId=$select.closest(".item").attr("data-item-id")??"",item=this.actor.items.get(itemId);if(!item)throw ErrorPF2e("Item not found");const newValue=(()=>{if(item.isOfType("spellcastingEntry"))return{"system.proficiency.value":()=>Math.clamped(selectedValue,0,4)}[propertyKey]?.();if(item.isOfType("lore"))return Math.clamped(selectedValue,0,4);throw ErrorPF2e("Item not recognized")})();typeof newValue=="number"&&await item.update({[propertyKey]:newValue}),newValue!==getProperty(item,propertyKey)&&ui.notifications.warn(game.i18n.localize("PF2E.ErrorMessage.MinimumProfLevelSetByFeatures"))},"#onChangeAdjustItemStat"),_onClickAdjustItemStat=new WeakSet,onClickAdjustItemStat_fn=__name2(async function(event){const $button=$(event.delegateTarget),itemId=$button.closest(".item").attr("data-item-id")??"",item=this.actor.items.get(itemId);if(!item)throw ErrorPF2e("Item not found");const propertyKey=$button.attr("data-item-property")??"",change=event.type==="click"?1:-1,newValue=(()=>{if(item.isOfType("spellcastingEntry")){const proficiencyRank=item.system.proficiency.value;return{"system.proficiency.value":()=>Math.clamped(proficiencyRank+change,0,4)}[propertyKey]?.()}else if(item.isOfType("lore")){const currentRank=item.system.proficient.value;return Math.clamped(currentRank+change,0,4)}else throw ErrorPF2e("Item not recognized")})();typeof newValue=="number"&&await item.update({[propertyKey]:newValue})},"#onClickAdjustItemStat"),_getFeatSlotData=new WeakSet,getFeatSlotData_fn=__name2(function(event){const groupId=htmlClosest(event.target,"[data-group-id]")?.dataset.groupId,slotId=htmlClosest(event.target,"[data-slot-id]")?.dataset.slotId||null;return groupId?{groupId,slotId}:null},"#getFeatSlotData"),_sortFormulas=new WeakSet,sortFormulas_fn=__name2(async function(sourceFormula,targetUuid,entrySelector){if(!UUIDUtils.isItemUUID(targetUuid)||sourceFormula.uuid===targetUuid)return;const sourceLevel=sourceFormula.level,targetLevel=__privateGet(this,_knownFormulas)[targetUuid].level;if(!entrySelector&&sourceLevel!==targetLevel)return;const performSort=__name2(async(formulas2,source2,target2,siblings)=>{const results=SortingHelpers.performIntegerSort(source2,{target:target2,siblings});if(results.length){for(const result of results){const formula=formulas2.find(f=>f===result.target);formula&&(formula.sort=result.update.sort)}entrySelector?await(await this.actor.getCraftingEntry(entrySelector))?.updateFormulas(formulas2):await this.actor.update({"system.crafting.formulas":formulas2})}},"performSort");if(entrySelector){const entry=await this.actor.getCraftingEntry(entrySelector);if(!entry)throw ErrorPF2e(`Crafting entry "${entrySelector}" doesn't exist!`);const formulas2=deepClone(entry.preparedFormulaData),source2=formulas2.find(f=>f.itemUUID===sourceFormula.uuid),target2=formulas2.find(f=>f.itemUUID===targetUuid);if(source2&&target2){const siblings=formulas2.filter(f=>f.itemUUID!==source2.itemUUID);return performSort(formulas2,source2,target2,siblings)}}const formulas=this.actor.toObject().system.crafting?.formulas??[],source=formulas.find(f=>f.uuid===sourceFormula.uuid),target=formulas.find(f=>f.uuid===targetUuid);if(source&&target){const siblings=formulas.filter(f=>f.uuid!==source.uuid);return performSort(formulas,source,target,siblings)}},"#sortFormulas"),__name2(_CharacterSheetPF2e,"CharacterSheetPF2e");let CharacterSheetPF2e=_CharacterSheetPF2e;const _AttackPopout=class extends CharacterSheetPF2e{static{__name(this,"_AttackPopout")}constructor(object,options){if(super(object,options),__publicField(this,"type","strike"),__privateAdd(this,_strikeItemId,""),__privateAdd(this,_strikeSlug,""),__privateAdd(this,_strike,void 0),__privateAdd(this,_elementTrait,void 0),__privateAdd(this,_blasts,[]),!options.type)throw ErrorPF2e('AttackPopout is missing mandatory "type" option.');if(options.type==="blast"){if(!options.elementTrait)throw ErrorPF2e('AttackPopout of type "blast" is missing mandatory "elementalTrait" option.');__privateSet(this,_elementTrait,options.elementTrait)}else{if(!options.strikeSlug)throw ErrorPF2e('AttackPopout of type "strike" is missing mandatory "strikeSlug" option.');if(!options.strikeItemId)throw ErrorPF2e('AttackPopout of type "strike" is missing mandatory "strikeItemId" option.');__privateSet(this,_strikeSlug,options.strikeSlug),__privateSet(this,_strikeItemId,options.strikeItemId)}this.type=options.type}get template(){return"systems/pf2e/templates/actors/character/attack-popout.hbs"}get id(){const id=super.id;return this.type==="strike"?`${id}-strike-${__privateGet(this,_strikeItemId)}-${__privateGet(this,_strikeSlug)}`:`${id}-blast-${__privateGet(this,_elementTrait)}`}static get defaultOptions(){return{...super.defaultOptions,submitOnChange:!1,submitOnClose:!1,width:480,height:"auto",resizable:!1}}get label(){return this.type==="blast"?__privateGet(this,_blasts).at(0)?.label??null:__privateGet(this,_strike)?.label??null}async getData(options){const base=await super.getData(options);return this.type==="blast"?(base.elementalBlasts=__privateSet(this,_blasts,base.elementalBlasts.filter(b=>b.element===__privateGet(this,_elementTrait))),base.data.actions=[],base.toggles=base.toggles.filter(t=>t.domain==="elemental-blast")):(base.elementalBlasts=[],__privateGet(this,_strikeSlug)&&__privateGet(this,_strikeItemId)&&__privateSet(this,_strike,base.data.actions.find(a=>a.item.id===__privateGet(this,_strikeItemId)&&a.slug===__privateGet(this,_strikeSlug)))),{...base,strike:__privateGet(this,_strike),strikeIndex:base.data.actions.findIndex(a=>a===__privateGet(this,_strike)),popoutType:this.type}}activateListeners($html){super.activateListeners($html);const html=$html[0],{label}=this;if(label){const title=htmlQuery(htmlClosest(html,"div.window-app"),"h4.window-title");title&&(title.innerHTML=game.i18n.localize(label))}}_getHeaderButtons(){return super._getHeaderButtons().filter(b=>b.label==="Close")}};_strikeItemId=new WeakMap,_strikeSlug=new WeakMap,_strike=new WeakMap,_elementTrait=new WeakMap,_blasts=new WeakMap,__name2(_AttackPopout,"AttackPopout");let AttackPopout=_AttackPopout;const _MacroPF2e=class extends Macro{static{__name(this,"_MacroPF2e")}get visible(){return this.permission>=CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER}};__name2(_MacroPF2e,"MacroPF2e");let MacroPF2e=_MacroPF2e;async function rollItemMacro(itemId){const speaker=ChatMessage.getSpeaker(),item=(canvas.tokens.get(speaker.token??"")?.actor??game.actors.get(speaker.actor??""))?.items?.get(itemId);if(!item){ui.notifications.warn(`Your controlled Actor does not have an item with ID ${itemId}`);return}return item.isOfType("action","feat")&&item.system.selfEffect?createSelfEffectMessage(item):item.toChat()}__name(rollItemMacro,"rollItemMacro"),__name2(rollItemMacro,"rollItemMacro");async function createActionMacro({actorUUID,actionIndex,elementTrait,slot}){const actor=resolveMacroActor(actorUUID);if(!actor?.isOfType("character","npc"))return;const data=(()=>{if(actor.isOfType("character")&&objectHasKey(CONFIG.PF2E.elementTraits,elementTrait)){const config=new ElementalBlast(actor).configs.find(c=>c.element===elementTrait);return config?{name:game.i18n.localize(config.label),command:`game.pf2e.rollActionMacro({ actorUUID: "${actorUUID}", type: "blast", elementTrait: "${elementTrait}" })`,img:config.img}:null}else if(actionIndex!==void 0){const action2=actor.system.actions[actionIndex];return action2?{name:`${game.i18n.localize("PF2E.WeaponStrikeLabel")}: ${action2.label}`,command:`game.pf2e.rollActionMacro({ actorUUID: "${actorUUID}", type: "strike", itemId: "${action2.item.id}", slug: "${action2.slug}" })`,img:action2.imageUrl}:null}return null})();if(!data)return;const actionMacro=game.macros.find(macro=>macro.name===data.name&¯o.command===data.command)??await MacroPF2e.create({command:data.command,name:data.name,type:"script",img:data.img,flags:{pf2e:{actionMacro:!0}}},{renderSheet:!1});game.user.assignHotbarMacro(actionMacro??null,slot)}__name(createActionMacro,"createActionMacro"),__name2(createActionMacro,"createActionMacro");async function rollActionMacro({actorUUID,itemId,elementTrait,slug,type}){const actor=resolveMacroActor(actorUUID);if(!actor?.isOfType("character","npc")){ui.notifications.error("PF2E.MacroActionNoActorError",{localize:!0});return}const strikes=actor.system.actions,strike=strikes.find(s=>s.item.id===itemId&&s.slug===slug)??strikes.find(s=>s.slug===slug);if(actor.isOfType("character")){const closedExisting=__name2(partialId=>{const appId=`AttackPopout-Actor-${actor.id}-${partialId}`,existing=Object.values(actor.apps).find(a=>a?.id===appId);return existing?(existing.close({force:!0}),!0):!1},"closedExisting");switch(type){case"blast":{if(closedExisting(`blast-${elementTrait}`))return;if(!actor.itemTypes.effect.find(e=>e.slug==="effect-kinetic-aura")){ui.notifications.error("PF2E.MacroActionNoActionError",{localize:!0});return}new AttackPopout(actor,{type,elementTrait}).render(!0);return}case"strike":{if(closedExisting(`strike-${itemId}-${slug}`))return;if(!strike){ui.notifications.error("PF2E.MacroActionNoActionError",{localize:!0});return}new AttackPopout(actor,{type,strikeItemId:itemId,strikeSlug:slug}).render(!0);return}}}if(!strike){ui.notifications.error("PF2E.MacroActionNoActionError",{localize:!0});return}const meleeOrRanged=strike.item.isMelee?"melee":"ranged",identifier=`${strike.item.id}.${strike.slug}.${meleeOrRanged}`,description=await TextEditor.enrichHTML(game.i18n.localize(strike.description),{async:!0}),templateData={actor,strike,identifier,description},content=await renderTemplate("systems/pf2e/templates/chat/strike-card.hbs",templateData),token=actor.token??actor.getActiveTokens(!0,!0).shift()??null,chatData={speaker:ChatMessagePF2e.getSpeaker({actor,token}),content,type:CONST.CHAT_MESSAGE_TYPES.OTHER},rollMode=game.settings.get("core","rollMode");return["gmroll","blindroll"].includes(rollMode)&&(chatData.whisper=ChatMessage.getWhisperRecipients("GM").map(u=>u.id)),rollMode==="blindroll"&&(chatData.blind=!0),ChatMessagePF2e.create(chatData)}__name(rollActionMacro,"rollActionMacro"),__name2(rollActionMacro,"rollActionMacro");async function createSkillMacro(skill,skillName,actorId,slot){const dictName=SKILL_DICTIONARY[skill]??skill,command=` const a = game.actors.get("${actorId}"); if (a) { const opts = a.getRollOptions(["all", "skill-check", "${dictName}"]); @@ -254,7 +256,7 @@ ${CheckFeat(actor,"mortal-healing")?`
- `},"askLevelPopupTemplate");function showXP(partyLevel,partySize,npcLevels,hazards){const xp=game.pf2e.gm.calculateXP(partyLevel,partySize,npcLevels,hazards,{proficiencyWithoutLevel:game.settings.get("pf2e","proficiencyVariant")});new Dialog({title:"XP",content:dialogTemplate(xp),buttons:{}}).render(!0)}__name(showXP,"showXP"),__name2(showXP,"showXP");function askPartyLevelAndSize(npcLevels,hazards){new Dialog({title:"Party Information",content:askLevelPopupTemplate,buttons:{no:{icon:'',label:"Cancel"},yes:{icon:'',label:"Calculate XP",callback:$html=>{const html=$html[0],partySize=Math.abs(Math.trunc(Number(htmlQuery(html,"[name=party-size]")?.value||1))),partyLevel=Math.abs(Math.trunc(Number(htmlQuery(html,"[name=party-level]")?.value||1)));localStorage.setItem("xpMacroPartySize",partySize.toString()),localStorage.setItem("xpMacroPartyLevel",partyLevel.toString()),showXP(partyLevel,partySize,npcLevels,hazards)}}},default:"yes"}).render(!0)}__name(askPartyLevelAndSize,"askPartyLevelAndSize"),__name2(askPartyLevelAndSize,"askPartyLevelAndSize");function xpFromEncounter(){const actors=canvas.tokens.controlled.flatMap(a=>a.actor??[]).filter(a=>!a.traits.has("minion")),npcLevels=getLevels(actors,"opposition"),pcLevels=getLevels(actors,"party"),hazards=getHazards(actors);if(npcLevels.length===0&&hazards.length===0){ui.notifications.error("You must select at least one opposition and/or hazard token and optionally all PC tokens");return}pcLevels.length===0?askPartyLevelAndSize(npcLevels,hazards):showXP(pcLevels[0],pcLevels.length,npcLevels,hazards)}__name(xpFromEncounter,"xpFromEncounter"),__name2(xpFromEncounter,"xpFromEncounter");const xpVariantCreatureDifferences=new Map([[-7,9],[-6,12],[-5,14],[-4,18],[-3,21],[-2,26],[-1,32],[0,40],[1,48],[2,60],[3,72],[4,90],[5,108],[6,135],[7,160]]),xpCreatureDifferences=new Map([[-4,10],[-3,15],[-2,20],[-1,30],[0,40],[1,60],[2,80],[3,120],[4,160]]),xpSimpleHazardDifferences=new Map([[-4,2],[-3,3],[-2,4],[-1,6],[0,8],[1,12],[2,16],[3,24],[4,32]]);function getXPFromMap(partyLevel,entityLevel,values){const difference2=entityLevel+1-(partyLevel+1),range=Math.floor(values.size/2),boundedDifference=Math.clamped(difference2,0-range,range);return values.get(boundedDifference)??0}__name(getXPFromMap,"getXPFromMap"),__name2(getXPFromMap,"getXPFromMap");function calculateCreatureXP(partyLevel,npcLevel,dcOptions){return dcOptions.proficiencyWithoutLevel?getXPFromMap(partyLevel,npcLevel,xpVariantCreatureDifferences):getXPFromMap(partyLevel,npcLevel,xpCreatureDifferences)}__name(calculateCreatureXP,"calculateCreatureXP"),__name2(calculateCreatureXP,"calculateCreatureXP");function getHazardXp(partyLevel,hazard,dcOptions){return hazard.isComplex?calculateCreatureXP(partyLevel,hazard.level,dcOptions):getXPFromMap(partyLevel,hazard.level,xpSimpleHazardDifferences)}__name(getHazardXp,"getHazardXp"),__name2(getHazardXp,"getHazardXp");function generateEncounterBudgets(partySize){const budget=partySize*20;return{trivial:Math.floor(budget*.5),low:Math.floor(budget*.75),moderate:budget,severe:Math.floor(budget*1.5),extreme:Math.floor(budget*2)}}__name(generateEncounterBudgets,"generateEncounterBudgets"),__name2(generateEncounterBudgets,"generateEncounterBudgets");const rewardEncounterBudgets=generateEncounterBudgets(4);function calculateEncounterRating(challenge,budgets){return challenge<=budgets.trivial?"trivial":challenge<=budgets.low?"low":challenge<=budgets.moderate?"moderate":challenge<=budgets.severe?"severe":"extreme"}__name(calculateEncounterRating,"calculateEncounterRating"),__name2(calculateEncounterRating,"calculateEncounterRating");function calculateXP(partyLevel,partySize,npcLevels,hazards,dcOptions){const creatureChallenge=npcLevels.map(level=>calculateCreatureXP(partyLevel,level,dcOptions)).reduce((a,b)=>a+b,0),hazardChallenge=hazards.map(hazard=>getHazardXp(partyLevel,hazard,dcOptions)).reduce((a,b)=>a+b,0),totalXP=creatureChallenge+hazardChallenge,encounterBudgets=generateEncounterBudgets(partySize),rating=calculateEncounterRating(totalXP,encounterBudgets),ratingXP=rewardEncounterBudgets[rating];return{partyLevel,partySize,totalXP,encounterBudgets,rating,ratingXP,xpPerPlayer:Math.floor(totalXP/partySize*4)}}__name(calculateXP,"calculateXP"),__name2(calculateXP,"calculateXP");const _EncounterPF2e=class extends Combat{static{__name(this,"_EncounterPF2e")}_sortCombatants(a,b){const resolveTie=__name2(()=>{const[priorityA,priorityB]=[a,b].map(combatant=>combatant.overridePriority(combatant.initiative??0)??(combatant.actor?.system.attributes.initiative?combatant.actor.system.attributes.initiative.tiebreakPriority:3));return priorityA===priorityB?a.id.localeCompare(b.id):priorityA-priorityB},"resolveTie");return typeof a.initiative=="number"&&typeof b.initiative=="number"&&a.initiative===b.initiative?resolveTie():super._sortCombatants(a,b)}getCombatantWithHigherInit(a,b){const sortResult=this._sortCombatants(a,b);return sortResult>0?b:sortResult<0?a:null}analyze(){if(!game.ready)return null;const{party}=game.actors,partyMembers=party?.members.filter(a=>a.alliance==="party"&&isReallyPC(a))??[],fightyPartyMembers=(()=>{const inEncounter=partyMembers.filter(m=>m.combatant?.encounter===this);return inEncounter.length>0?inEncounter:partyMembers})(),opposition=uniq(this.combatants.filter(c=>!!(c.actor?.alliance==="opposition"||c.actor?.isOfType("hazard"))&&!partyMembers.includes(c.actor)).flatMap(c=>c.actor??[]));if(!party||fightyPartyMembers.length===0||opposition.length===0)return null;const partyLevel=Math.round(meanBy(fightyPartyMembers.filter(m=>m.isOfType("character")),m=>m.level)),result=calculateXP(partyLevel,fightyPartyMembers.length,opposition.filter(e=>e.isOfType("character","npc")).map(e=>e.level),opposition.filter(e=>e.isOfType("hazard")),{proficiencyWithoutLevel:game.settings.get("pf2e","proficiencyVariant")}),threat=result.rating,budget={spent:result.totalXP,max:result.encounterBudgets[threat],partyLevel},award={xp:Math.floor(result.xpPerPlayer*(fightyPartyMembers.length/partyMembers.length)),recipients:partyMembers};return{threat,budget,award,participants:{party:fightyPartyMembers,opposition}}}prepareDerivedData(){super.prepareDerivedData(),this.metrics=this.analyze()}async createEmbeddedDocuments(embeddedName,data,context={}){const createData=data.filter(datum=>{const token=canvas.tokens.placeables.find(canvasToken=>canvasToken.id===datum.tokenId);if(!token)return!1;const{actor}=token;if(!actor)return ui.notifications.warn(`${token.name} has no associated actor.`),!1;const actorTraits=actor.traits;if(actor.type==="loot"||["minion","eidolon"].some(t=>actorTraits.has(t))){const actorTypes2=CONFIG.PF2E.actorTypes,type=game.i18n.localize(actorTraits.has("minion")?CONFIG.PF2E.creatureTraits.minion:actorTraits.has("eidolon")?CONFIG.PF2E.creatureTraits.eidolon:actorTypes2[actor.type]);return ui.notifications.info(game.i18n.format("PF2E.Encounter.ExcludingFromInitiative",{type,actor:actor.name})),!1}return!0});return super.createEmbeddedDocuments(embeddedName,createData,context)}async rollInitiative(ids,options={}){const extraRollOptions=options.extraRollOptions??[],rollMode=options.messageOptions?.rollMode??options.rollMode;options.secret&&extraRollOptions.push("secret");const fightyCombatants=ids.flatMap(id=>this.combatants.get(id)??[]).filter(c=>!!c.actor?.initiative),initiatives=(await Promise.all(fightyCombatants.map(async combatant=>combatant.actor?.initiative?.roll({...options,combatant,extraRollOptions,updateTracker:!1,rollMode})??null))).flatMap(result=>result?{id:result.combatant.id,value:result.roll.total,statistic:result.roll.options.domains?.find(s=>setHasElement(SKILL_LONG_FORMS,s)||s==="perception")??null}:[]);await this.setMultipleInitiatives(initiatives);const remainingIds=ids.filter(id=>!fightyCombatants.some(c=>c.id===id));return super.rollInitiative(remainingIds,options)}async setMultipleInitiatives(initiatives){const currentId=this.combatant?.id,updates=initiatives.map(i=>({_id:i.id,initiative:i.value,flags:{pf2e:{initiativeStatistic:i.statistic??null,overridePriority:{[i.value]:i.overridePriority}}}}));await this.updateEmbeddedDocuments("Combatant",updates),await this.update({turn:this.turns.findIndex(c=>c.id===currentId)})}async setInitiative(id,value){const combatant=this.combatants.get(id,{strict:!0});if(combatant.actor?.isOfType("character","npc"))return this.setMultipleInitiatives([{id:combatant.id,value,statistic:combatant.actor.attributes.initiative.statistic||"perception"}]);super.setInitiative(id,value)}async resetActors(){const actors=this.combatants.contents.flatMap(c=>c.actor??[]);resetActors(actors,{rerender:!1})}_onCreate(data,options,userId){super._onCreate(data,options,userId);const pcSheets=Object.values(ui.windows).filter(sheet=>sheet.constructor.name==="CharacterSheetPF2e");for(const sheet of pcSheets)sheet.toggleInitiativeLink()}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId),game.pf2e.StatusEffects.onUpdateEncounter(this);const{combatant,previous}=this,actor=combatant?.actor;if(!this.started)return;const[newRound,newTurn]=[changed.round,changed.turn],isRoundChange=typeof newRound=="number",isTurnChange=typeof newTurn=="number",isNextRound=isRoundChange&&(previous.round===null||newRound>previous.round),isNextTurn=isTurnChange&&(previous.turn===null||newTurn>previous.turn);(isRoundChange||isTurnChange)&&Promise.resolve().then(async()=>{if(isNextRound||isNextTurn){const previousCombatant=this.combatants.get(previous.combatantId??"");if(game.user===previousCombatant?.actor?.primaryUpdater){const alreadyWent=previousCombatant.flags.pf2e.roundOfLastTurnEnd===previous.round;typeof previous.round=="number"&&!alreadyWent&&await previousCombatant.endTurn({round:previous.round})}if(game.user===actor?.primaryUpdater){const alreadyWent=combatant?.roundOfLastTurn===this.round;combatant&&!alreadyWent&&await combatant.startTurn()}}this.resetActors(),await game.pf2e.effectTracker.refresh(),game.pf2e.effectPanel.refresh()})}_onDelete(options,userId){if(super._onDelete(options,userId),this.started&&(Hooks.callAll("pf2e.endTurn",this.combatant??null,this,userId),game.pf2e.effectTracker.onEncounterEnd(this)),!game.combat){const pcSheets=Object.values(ui.windows).filter(sheet=>sheet.constructor.name==="CharacterSheetPF2e");for(const sheet of pcSheets)sheet.toggleInitiativeLink()}game.user.clearTargets(),this.resetActors()}async _manageTurnEvents(adjustedTurn){if(this.previous||game.release.generation>11)return super._manageTurnEvents(adjustedTurn)}};__name2(_EncounterPF2e,"EncounterPF2e");let EncounterPF2e=_EncounterPF2e;const _CombatantPF2e=class extends Combatant{static{__name(this,"_CombatantPF2e")}get encounter(){return this.parent}get roundOfLastTurn(){return this.flags.pf2e.roundOfLastTurn}get playersCanSeeName(){return!!this.token?.playersCanSeeName}overridePriority(initiative){return this.flags.pf2e.overridePriority[initiative]??null}hasHigherInitiative({than}){if(this.parent.id!==than.parent.id)throw ErrorPF2e("The initiative of Combatants from different combats cannot be compared");return this.parent.getCombatantWithHigherInit(this,than)===this}static async fromActor(actor,render=!0,options={}){if(!game.combat)return ui.notifications.error(game.i18n.localize("PF2E.Encounter.NoActiveEncounter")),null;const token=actor.getActiveTokens().pop(),existing=game.combat.combatants.find(combatant=>combatant.actor===actor);return existing||(token?(await(options.combat??game.combat).createEmbeddedDocuments("Combatant",[{tokenId:token.id,actorId:token.actor?.id,sceneId:token.scene.id,hidden:token.document.hidden}],{render})).at(0)??null:(ui.notifications.error(game.i18n.format("PF2E.Encounter.NoTokenInScene",{actor:actor.name})),null))}static async createDocuments(data=[],context={}){const entries=data.map(d=>({token:(d.sceneId?game.scenes.get(d.sceneId):context.parent?.scene)?.tokens.get(d.tokenId??"")||null,data:d})),tokens=entries.map(e=>e.token);for(const token of tokens)token?.actor?.isOfType("party")&&await token?.actor.addToCombat({combat:context.parent});const nonPartyData=entries.filter(e=>!e.token?.actor?.isOfType("party")).map(e=>e.data);return super.createDocuments(nonPartyData,context)}async startTurn(){const{actor,encounter}=this;if(!encounter||!actor)return;const actorUpdates={};for(const rule of actor.rules)await rule.onTurnStart?.(actorUpdates);await this.update({"flags.pf2e.roundOfLastTurn":encounter.round}),Object.keys(actorUpdates).length>0&&await actor.update(actorUpdates);for(const effect of actor.itemTypes.effect)await effect.onTurnStartEnd("start");if(actor.isOfType("character")&&actor.familiar)for(const effect of actor.familiar.itemTypes.effect)await effect.onTurnStartEnd("start");Hooks.callAll("pf2e.startTurn",this,encounter,game.user.id)}async endTurn(options){const round=options.round,{actor,encounter}=this;if(!encounter||!actor)return;const activeConditions=actor.conditions.active;for(const condition of activeConditions)await condition.onEndTurn({token:this.token});for(const effect of actor.itemTypes.effect)await effect.onTurnStartEnd("end");if(actor.isOfType("character")&&actor.familiar)for(const effect of actor.familiar.itemTypes.effect)await effect.onTurnStartEnd("end");await this.update({"flags.pf2e.roundOfLastTurnEnd":round}),Hooks.callAll("pf2e.endTurn",this,encounter,game.user.id)}prepareBaseData(){super.prepareBaseData(),this.flags.pf2e=mergeObject(this.flags.pf2e??{},{overridePriority:{}}),this.flags.pf2e.roundOfLastTurn??=null,this.flags.pf2e.initiativeStatistic??=null}async toggleDefeated({to=!this.isDefeated}={}){to!==this.isDefeated&&(await this.update({defeated:to}),await this.token?.object?.toggleEffect(game.settings.get("pf2e","deathIcon"),{active:to,overlay:!0}),this.isDefeated&&this.token?.object?.isTargeted&&this.token.object.setTarget(!1,{releaseOthers:!1}))}updateResource(){return this.isNPC&&!game.user.isGM?this.resource=null:super.updateResource()}_getInitiativeFormula(){const{actor}=this;if(!actor)return"1d20";let bonus=0;return typeof actor.attributes.initiative?.totalModifier=="number"?bonus=actor.attributes.initiative.totalModifier:actor.attributes.perception&&(bonus=actor.attributes.perception.value),["1d20",bonus||0].join("+")}async toggleNameVisibility(){if(!this.token)return;const currentVisibility=this.token.displayName,visibilityToggles={[CONST.TOKEN_DISPLAY_MODES.ALWAYS]:CONST.TOKEN_DISPLAY_MODES.OWNER,[CONST.TOKEN_DISPLAY_MODES.CONTROL]:CONST.TOKEN_DISPLAY_MODES.HOVER,[CONST.TOKEN_DISPLAY_MODES.HOVER]:CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,[CONST.TOKEN_DISPLAY_MODES.NONE]:CONST.TOKEN_DISPLAY_MODES.HOVER,[CONST.TOKEN_DISPLAY_MODES.OWNER]:CONST.TOKEN_DISPLAY_MODES.ALWAYS,[CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER]:CONST.TOKEN_DISPLAY_MODES.HOVER};await this.token.update({displayName:visibilityToggles[currentVisibility]})}_onUpdate(changed,options,userId){if(super._onUpdate(changed,options,userId),this.encounter?.started&&typeof changed.initiative=="number"&&this.encounter.resetActors(),changed.defeated&&game.user.id===userId)for(const action2 of this.actor?.itemTypes.action??[])action2.system.deathNote&&action2.toMessage(void 0,{rollMode:this.actor?.hasPlayerOwner?"publicroll":"gmroll"})}_onDelete(options,userId){super._onDelete(options,userId),this.encounter?.started&&this.encounter.resetActors()}};__name2(_CombatantPF2e,"CombatantPF2e");let CombatantPF2e=_CombatantPF2e;const _ActorInitiative=class{static{__name(this,"_ActorInitiative")}actor;statistic;get attribute(){return this.statistic.attribute}get ability(){return foundry.utils.logCompatibilityWarning("`ActorInitiative#ability` is deprecated. Use `ActorInitiative#attribute` instead.",{since:"5.3.0",until:"6.0.0"}),this.attribute}constructor(actor){this.actor=actor;const initiativeSkill=actor.isOfType("hazard")?"stealth":actor.isOfType("character","npc")?actor.attributes.initiative?.statistic||"perception":null,base=initiativeSkill?actor.getStatistic(initiativeSkill):null,ponderousPenalty=actor.isOfType("character")?createPonderousPenalty(actor):null,rollLabel=game.i18n.format("PF2E.InitiativeWithSkill",{skillName:base?.label??""}),data={slug:"initiative",label:base?.label??"PF2E.InitiativeLabel",domains:["initiative"],rollOptions:[base?.slug??[]].flat(),check:{type:"initiative",label:rollLabel},modifiers:[ponderousPenalty??[]].flat()};this.statistic=base?base.extend(data):new Statistic(actor,data)}async roll(args={}){const combatant=args.combatant?.actor===this.actor?args.combatant:await CombatantPF2e.fromActor(this.actor,!1);if(!combatant)return null;combatant.hidden&&(args.rollMode=CONST.DICE_ROLL_MODES.PRIVATE);const roll=await this.statistic.roll(args);return roll?((args.updateTracker??!0)&&combatant.encounter.setInitiative(combatant.id,roll.total),{combatant,roll}):(game.combats.render(!1),null)}getTraceData(){const initiativeData=this.actor.attributes.initiative,tiebreakPriority=initiativeData?.tiebreakPriority??0;return{...this.statistic.getTraceData(),statistic:initiativeData?.statistic??"perception",tiebreakPriority}}};__name2(_ActorInitiative,"ActorInitiative");let ActorInitiative=_ActorInitiative;const _CreatureSizeRuleElement=class _CreatureSizeRuleElement2 extends RuleElementPF2e{static{__name(this,"_CreatureSizeRuleElement")}constructor(data,options){super(data,options),__privateAdd(this,_getReach),typeof this.value=="string"||typeof this.value=="number"||this.isBracketedValue(this.value)||this.failValidation("value must be a number, string, or bracketed value")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1}),reach:new RecordField(new fields2.StringField({required:!0,nullable:!1,choices:["add","upgrade","override"]}),new ResolvableValueField({required:!0,nullable:!1}),{required:!1,nullable:!1,initial:void 0}),resizeEquipment:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0}),minimumSize:new fields2.StringField({required:!1,nullable:!1,choices:SIZES,initial:void 0}),maximumSize:new fields2.StringField({required:!1,nullable:!1,choices:SIZES,initial:void 0})}}incrementSize(size,amount){return amount===0?size:this.incrementSize(_CreatureSizeRuleElement2.incrementMap[size],amount-1)}decrementSize(size,amount){return amount===0?size:this.decrementSize(_CreatureSizeRuleElement2.decrementMap[size],amount-1)}beforePrepareData(){if(!this.test())return;const value=this.resolveValue(this.value);if(!(typeof value=="string"||typeof value=="number")){this.failValidation(`CreatureSize Rule Element on actor ${this.actor.id} (${this.actor.name})`,"has a non-string, non-numeric value");return}const size=_CreatureSizeRuleElement2.wordToAbbreviation[value]??value;if(typeof size=="string"&&!tupleHasValue(SIZES,size)){this.failValidation(`"${size}" is not a recognized size`);return}const{actor}=this,originalSize=new ActorSizePF2e({value:actor.size});if(value===1){if(this.maximumSize&&!originalSize.isSmallerThan(this.maximumSize))return;actor.system.traits.size.increment()}else if(value===-1){if(this.minimumSize&&!originalSize.isLargerThan(this.minimumSize))return;actor.system.traits.size.decrement()}else if(tupleHasValue(SIZES,size))actor.system.traits.size=new ActorSizePF2e({value:size});else{const validValues=Array.from(new Set(Object.entries(_CreatureSizeRuleElement2.wordToAbbreviation).flat())).join('", "');this.failValidation(`CreatureSize Rule Element on actor ${actor.id} (${actor.name})`,`has an invalid value: must be one of "${validValues}", +1, or -1`);return}const{reach}=actor.system.attributes;if(reach.base=__privateMethod(this,_getReach,getReach_fn).call(this,originalSize),reach.manipulate=Math.max(reach.manipulate,reach.base),this.resizeEquipment){const sizeDifference=originalSize.difference(actor.system.traits.size,{smallIsMedium:!0});for(const item of actor.inventory.filter(i=>!(i instanceof TreasurePF2e&&i.isCoinage)))sizeDifference<0?item.system.size=this.incrementSize(item.size,Math.abs(sizeDifference)):sizeDifference>0&&(item.system.size=this.decrementSize(item.size,Math.abs(sizeDifference)))}}};_getReach=new WeakSet,getReach_fn=__name2(function(originalSize){const current=this.actor.attributes.reach.base;if(this.reach){const changeValue=(()=>{const resolved=this.resolveValue(this.reach.add??this.reach.upgrade??this.reach.override);return Math.trunc(Math.abs(Number(resolved)))})();if(!Number.isInteger(changeValue))return current;if(this.reach.add)return current+changeValue;if(this.reach.upgrade)return Math.max(current,changeValue);if(this.reach.override)return changeValue}const newSize=this.actor.system.traits.size;return newSize.isLargerThan(originalSize)?Math.max(SIZE_TO_REACH[this.actor.size],current):newSize.isSmallerThan(originalSize)?Math.min(SIZE_TO_REACH[this.actor.size],current):current},"#getReach"),__name2(_CreatureSizeRuleElement,"CreatureSizeRuleElement"),__publicField(_CreatureSizeRuleElement,"validActorTypes",["character","npc","familiar"]),__publicField(_CreatureSizeRuleElement,"wordToAbbreviation",{tiny:"tiny",small:"sm",medium:"med",large:"lg",huge:"huge",gargantuan:"grg"}),__publicField(_CreatureSizeRuleElement,"incrementMap",{tiny:"sm",sm:"med",med:"lg",lg:"huge",huge:"grg",grg:"grg"}),__publicField(_CreatureSizeRuleElement,"decrementMap",{tiny:"tiny",sm:"tiny",med:"sm",lg:"med",huge:"lg",grg:"huge"});let CreatureSizeRuleElement=_CreatureSizeRuleElement;const _IWRRuleElement=class extends RuleElementPF2e{static{__name(this,"_IWRRuleElement")}constructor(){super(...arguments),__privateAdd(this,_isValid)}static get dictionary(){return{}}static defineSchema(){const{fields:fields2}=foundry.data,{DataModelValidationFailure}=foundry.data.validation;return{...super.defineSchema(),mode:new fields2.StringField({required:!0,choices:["add","remove"],initial:"add"}),type:new fields2.ArrayField(new StrictStringField({required:!0,blank:!1,initial:void 0}),{validate:v=>Array.isArray(v)&&v.length>0||new DataModelValidationFailure({message:"must have at least one"})}),definition:new PredicateField({required:!1,initial:void 0}),exceptions:this.createExceptionsField(),override:new fields2.BooleanField}}static createExceptionsField(types){const customExceptionField=new foundry.data.fields.SchemaField({definition:new PredicateField({initial:void 0}),label:new StrictStringField({required:!0,blank:!1,initial:void 0})},{required:!0,initial:void 0}),exceptionField=new DataUnionField([new StrictStringField({required:!0,blank:!1,initial:void 0,choices:types}),customExceptionField],{required:!0,nullable:!1,initial:void 0});return new StrictArrayField(exceptionField)}static validateJoint(source){if(super.validateJoint(source),source.type.some(t=>t==="custom")){if(source.type.length>1)throw Error(' type: "custom" may not be included among other types');if(!source.definition)throw Error(" definition: must be present if defining a custom type")}else if(source.definition)throw Error(" definition: may only be present if defining a custom type");if(source.mode==="remove"&&source.exceptions.length>0)throw Error(' exceptions: may not be included with a mode of "remove"')}afterPrepareData(){if(!this.test())return;this.type=this.resolveInjectedProperties(this.type);const value=Math.floor(Number(this.resolveValue(this.value)));if(__privateMethod(this,_isValid,isValid_fn).call(this,value))if(this.mode==="add")this.property.push(...this.getIWR(value));else for(const toRemove of this.type)this.property.findSplice(iwr=>iwr.type===toRemove)}};_isValid=new WeakSet,isValid_fn=__name2(function(value){const{dictionary}=this.constructor,unrecognizedTypes=this.type.filter(t=>!(t in dictionary));if(unrecognizedTypes.length>0){for(const type of unrecognizedTypes)this.failValidation(`Type "${type}" is unrecognized`);return!1}return this.mode==="add"&&dictionary!==CONFIG.PF2E.immunityTypes&&(typeof value!="number"||value<0)?(this.failValidation("A `value` must be a positive number"),!1):!0},"#isValid"),__name2(_IWRRuleElement,"IWRRuleElement");let IWRRuleElement=_IWRRuleElement;const _ImmunityRuleElement=class extends IWRRuleElement{static{__name(this,"_ImmunityRuleElement")}value=null;static defineSchema(){return{...super.defineSchema(),exceptions:this.createExceptionsField(this.dictionary)}}static get dictionary(){return CONFIG.PF2E.immunityTypes}get property(){return this.actor.system.attributes.immunities}getIWR(){return this.type.map(t=>new Immunity({type:t,customLabel:t==="custom"?this.label:null,exceptions:this.exceptions,source:this.item.name})).filter(immunity=>{const existing=this.property.find(e=>e.type===immunity.type);return this.mode==="remove"||!(existing?.type===immunity.type&&existing.exceptions.every(x=>immunity.exceptions.includes(x)))})}};__name2(_ImmunityRuleElement,"ImmunityRuleElement");let ImmunityRuleElement=_ImmunityRuleElement;const _ResistanceRuleElement=class extends IWRRuleElement{static{__name(this,"_ResistanceRuleElement")}static defineSchema(){return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0}),exceptions:this.createExceptionsField(this.dictionary),doubleVs:this.createExceptionsField(this.dictionary)}}static get dictionary(){return CONFIG.PF2E.resistanceTypes}get property(){return this.actor.system.attributes.resistances}getIWR(value){if(value<=0)return[];const resistances=this.property;for(const resistanceType of[...this.type]){const current=resistances.find(r=>r.type===resistanceType);current&&(this.override?resistances.splice(resistances.indexOf(current),1):this.mode!=="remove"&&(current.value=Math.max(current.value,value),current.source=this.label,this.type.splice(this.type.indexOf(resistanceType),1)))}return this.type.map(t=>new Resistance({type:t,value,customLabel:t==="custom"?this.label:null,definition:this.definition,exceptions:this.exceptions,doubleVs:this.doubleVs,source:this.item.name}))}};__name2(_ResistanceRuleElement,"ResistanceRuleElement");let ResistanceRuleElement=_ResistanceRuleElement;const _WeaknessRuleElement=class extends IWRRuleElement{static{__name(this,"_WeaknessRuleElement")}static defineSchema(){return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0}),exceptions:this.createExceptionsField(this.dictionary)}}static get dictionary(){return CONFIG.PF2E.weaknessTypes}get property(){return this.actor.system.attributes.weaknesses}getIWR(value){if(value<=0)return[];const weaknesses=this.property;for(const weaknessType of[...this.type]){const current=weaknesses.find(w=>w.type===weaknessType);current&&(this.override?weaknesses.splice(weaknesses.indexOf(current),1):this.mode!=="remove"&&(current.value=Math.max(current.value,value),current.source=this.label,this.type.splice(this.type.indexOf(weaknessType),1)))}return this.type.map(t=>new Weakness({type:t,customLabel:t==="custom"?this.label:null,value,exceptions:this.exceptions,source:this.item.name}))}};__name2(_WeaknessRuleElement,"WeaknessRuleElement");let WeaknessRuleElement=_WeaknessRuleElement;const _SenseRuleElement=class extends RuleElementPF2e{static{__name(this,"_SenseRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,nullable:!1,choices:[...SENSE_TYPES]}),force:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),acuity:new fields2.StringField({required:!1,nullable:!1,choices:SENSE_ACUITIES,initial:void 0}),range:new ResolvableValueField({required:!1,nullable:!1,initial:void 0})}}constructor(data,options){data.selector&&(data.label??=CONFIG.PF2E.senses[data.selector]),super(data,options)}beforePrepareData(){if(this.ignored)return;const range=this.resolveValue(this.range,""),newSense=new CreatureSensePF2e({type:this.selector,acuity:this.acuity,value:String(range),source:this.item.name});this.actor.synthetics.senses.push({sense:newSense,predicate:this.predicate,force:this.force})}};__name2(_SenseRuleElement,"SenseRuleElement"),__publicField(_SenseRuleElement,"validActorTypes",["character","familiar"]);let SenseRuleElement=_SenseRuleElement;const _StrikeRuleElement=class extends RuleElementPF2e{static{__name(this,"_StrikeRuleElement")}constructor(source,options){source.img??=source.fist?"icons/skills/melee/unarmed-punch-fist.webp":options.parent.img,super(source,options),__privateAdd(this,_constructWeapon),this.fist&&(this.label=game.i18n.localize("PF2E.Weapon.Base.fist")),this.slug??=sluggify(this.label),this.battleForm??=!1,this.fist??=!1,this.options??=[]}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),category:new fields2.StringField({required:!0,blank:!1,choices:CONFIG.PF2E.weaponCategories,initial:"unarmed"}),group:new fields2.StringField({required:!0,nullable:!0,blank:!1,choices:CONFIG.PF2E.weaponGroups,initial:null}),baseType:new fields2.StringField({required:!0,nullable:!0,blank:!1,choices:CONFIG.PF2E.baseWeaponTypes,initial:null}),traits:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,choices:CONFIG.PF2E.npcAttackTraits})),traitToggles:new fields2.SchemaField({modular:new fields2.StringField({required:!0,blank:!1,nullable:!0,choices:CONFIG.PF2E.damageTypes,initial:null}),versatile:new fields2.StringField({required:!0,blank:!1,nullable:!0,choices:CONFIG.PF2E.damageTypes,initial:null})},{required:!0,nullable:!1,initial:{modular:null,versatile:null}}),otherTags:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,choices:CONFIG.PF2E.otherWeaponTags}),{required:!1,nullable:!1,initial:[]}),range:new fields2.SchemaField({increment:new fields2.NumberField({required:!1,integer:!0,min:5,nullable:!0,initial:5}),max:new fields2.NumberField({required:!1,integer:!0,min:5,nullable:!0,initial:null})},{required:!1,nullable:!0,initial:null}),damage:new fields2.SchemaField({base:new fields2.SchemaField({damageType:new fields2.StringField({required:!0,blank:!1,initial:"bludgeoning"}),dice:new ResolvableValueField({required:!0,nullable:!1,initial:1}),die:new fields2.StringField({required:!0,choices:CONFIG.PF2E.damageDie,initial:"d4"}),modifier:new fields2.NumberField({nullable:!1,integer:!0,initial:0})})}),img:new fields2.FilePathField({categories:["IMAGE"],nullable:!1,initial:()=>"systems/pf2e/icons/default-icons/melee.svg"}),attackModifier:new fields2.NumberField({integer:!0,positive:!0,nullable:!0,initial:null}),replaceAll:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0}),replaceBasicUnarmed:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0}),battleForm:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0}),ability:new fields2.StringField({required:!1,blank:!1,choices:CONFIG.PF2E.abilities,nullable:!0,initial:null}),options:new fields2.ArrayField(new fields2.StringField,{required:!1,initial:void 0}),fist:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0})}}validate(options){return(options?.changes??this._source).fist===!0?!0:super.validate(options)}_initializeSource(source,options){return"fist"in source&&source.fist===!0?source:super._initializeSource(source,options)}_initialize(options){this._source.fist?(this.key="Strike",this.priority=99,this.slug="fist",this.img=this._source.img,this.category="unarmed",this.group="brawling",this.baseType="fist",this.traits=["agile","finesse","nonlethal"],this.traitToggles=mergeObject({modular:null,versatile:null},this._source.traitToggles??{}),this.otherTags=[],this.range=null,this.damage={base:{dice:1,die:"d4",damageType:"bludgeoning",modifier:0}},this.battleForm=!1,this.fist=!0,this.replaceAll=!1,this.replaceBasicUnarmed=!1,this.predicate=new PredicatePF2e([...this._source.predicate??[],{gt:["hands-free",0]}])):super._initialize(options)}beforePrepareData(){if(this.ignored)return;const predicatePassed=this.predicate.length===0||(()=>{const rollOptions=new Set(this.actor.getRollOptions(["attack","attack-roll","strike-attack-roll"]));return this.resolveInjectedProperties(this.predicate).test(rollOptions)})(),damageType=this.resolveInjectedProperties(this.damage.base.damageType);if(!objectHasKey(CONFIG.PF2E.damageTypes,damageType))return this.failValidation("Unrecognized damage type");const dice=(()=>{const resolvedDice=Number(this.resolveValue(this.damage.base.dice));return Math.clamped(Math.trunc(resolvedDice),0,8)})();if(Number.isNaN(dice))return this.failValidation("dice does not resolve to a number");if(predicatePassed){const weapon=__privateMethod(this,_constructWeapon,constructWeapon_fn).call(this,damageType,dice),slug=weapon.slug??sluggify(weapon.name);this.actor.synthetics.strikes.set(slug,weapon)}}afterPrepareData(){if(!(this.ignored||!this.actor.isOfType("character")))if(this.replaceAll){const systemData=this.actor.system;systemData.actions=systemData.actions.filter(a=>a.item.id===this.item.id&&a.item.name===this.label&&a.item.group===this.group)}else this.replaceBasicUnarmed&&this.actor.system.actions.findSplice(a=>a.item?.slug==="basic-unarmed")}async toggleTrait({trait,selection}){const ruleSources=deepClone(this.item._source.system.rules),rule=ruleSources.at(this.sourceIndex??NaN);rule?.key==="Strike"&&(rule.traitToggles={...this.traitToggles,[trait]:selection},await this.item.update({"system.rules":ruleSources}))}};_constructWeapon=new WeakSet,constructWeapon_fn=__name2(function(damageType,dice){const actorIsNPC=this.actor.isOfType("npc"),source=deepClone({_id:this.item.id,name:this.label,type:"weapon",img:this.img,flags:{pf2e:{battleForm:this.battleForm,fixedAttack:actorIsNPC?this.attackModifier??null:null}},system:{slug:this.slug,description:{value:""},category:this.category,group:this.group,baseItem:this.baseType,attribute:this.ability,bonus:{value:actorIsNPC?this.attackModifier??0:0},damage:{...this.damage.base,dice,damageType},range:this.range?.increment??null,maxRange:this.range?.max??null,traits:{value:this.traits,otherTags:this.otherTags,rarity:"common",toggles:{modular:{selection:this.traitToggles.modular},versatile:{selection:this.traitToggles.versatile}}},options:{value:this.options},usage:{value:"held-in-one-hand"},equipped:{carryType:"held",handsHeld:1}}});return new WeaponPF2e(source,{parent:this.actor})},"#constructWeapon"),__name2(_StrikeRuleElement,"StrikeRuleElement"),__publicField(_StrikeRuleElement,"validActorTypes",["character","npc"]);let StrikeRuleElement=_StrikeRuleElement;const _TempHPRuleElement=class extends RuleElementPF2e{static{__name(this,"_TempHPRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1}),events:new StrictSchemaField({onCreate:new fields2.BooleanField({required:!1,nullable:!1}),onTurnStart:new fields2.BooleanField({required:!1,nullable:!1})},{required:!0,nullable:!1,initial:{onCreate:!0,onTurnStart:!1}})}}onCreate(actorUpdates){if(this.ignored||!this.events.onCreate)return;const updatedActorData=mergeObject(this.actor._source,actorUpdates,{inplace:!1}),value=this.resolveValue(this.value),rollOptions=Array.from(new Set([...this.actor.getRollOptions(),...this.actor.itemTypes.weapon.flatMap(w=>w.isEquipped?w.getRollOptions("self:weapon"):[])]));if(!this.test(rollOptions))return;if(typeof value!="number")return this.failValidation("Temporary HP requires a non-zero value field");const currentTempHP=Number(getProperty(updatedActorData,"system.attributes.hp.temp"))||0;value>currentTempHP&&(mergeObject(actorUpdates,{"system.attributes.hp.temp":value,"system.attributes.hp.tempsource":this.item.id}),this.broadcast(value,currentTempHP))}onTurnStart(actorUpdates){if(this.ignored||!this.events.onTurnStart)return;const rollOptions=Array.from(new Set([...this.actor.getRollOptions(["all"]),...this.actor.itemTypes.weapon.flatMap(w=>w.isEquipped?w.getRollOptions("self:weapon"):[])]));if(!this.test(rollOptions))return;const value=this.resolveValue(this.value);if(typeof value!="number")return this.failValidation("Temporary HP requires a non-zero value field");const updatedActorData=mergeObject(this.actor._source,actorUpdates,{inplace:!1}),currentTempHP=Number(getProperty(updatedActorData,"system.attributes.hp.temp"))||0;value>currentTempHP&&(actorUpdates["system.attributes.hp.temp"]=value,this.broadcast(value,currentTempHP))}onDelete(actorUpdates){const updatedActorData=mergeObject(this.actor._source,actorUpdates,{inplace:!1});if(getProperty(updatedActorData,"system.attributes.hp.tempsource")===this.item.id){mergeObject(actorUpdates,{"system.attributes.hp.temp":0});const hpData=getProperty(actorUpdates,"system.attributes.hp");isObject(hpData)&&(hpData["-=tempsource"]=null)}}broadcast(newQuantity,oldQuantity){const singularOrPlural=newQuantity===1?"PF2E.Encounter.Broadcast.TempHP.SingleNew":"PF2E.Encounter.Broadcast.TempHP.PluralNew",wasAt=oldQuantity>0?game.i18n.format("PF2E.Encounter.Broadcast.TempHP.WasAt",{oldQuantity}):"",[actor,item]=[this.actor.name,this.item.name],content=game.i18n.format(singularOrPlural,{actor,newQuantity,wasAt,item}),recipients=game.users.filter(u=>this.actor.testUserPermission(u,"OWNER")).map(u=>u.id),speaker=ChatMessagePF2e.getSpeaker({actor:this.actor,token:this.token});ChatMessagePF2e.create({content,speaker,whisper:recipients})}};__name2(_TempHPRuleElement,"TempHPRuleElement"),__publicField(_TempHPRuleElement,"validActorTypes",["character","npc","familiar"]);let TempHPRuleElement=_TempHPRuleElement;const _BattleFormRuleElement=class extends RuleElementPF2e{static{__name(this,"_BattleFormRuleElement")}constructor(data,options){super(data,options),__privateAdd(this,_setRollOptions),__privateAdd(this,_prepareAC),__privateAdd(this,_prepareSenses),__privateAdd(this,_prepareSize),__privateAdd(this,_prepareSpeeds),__privateAdd(this,_prepareSkills),__privateAdd(this,_prepareStrikes),__privateAdd(this,_prepareIWR),__privateAdd(this,_suppressModifiers),__privateAdd(this,_filterModifier),__privateAdd(this,_suppressNotes),__privateAdd(this,_resolveStrikeQueries),__publicField(this,"modifierLabel"),this.overrides=this.resolveValue(this.value,this.overrides),this.modifierLabel=this.getReducedLabel()}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!1,initial:void 0}),overrides:new fields2.SchemaField({traits:new fields2.ArrayField(new fields2.StringField),armorClass:new fields2.SchemaField({modifier:new ResolvableValueField({required:!1,nullable:!1,initial:0}),ignoreCheckPenalty:new fields2.BooleanField({required:!1,nullable:!1,initial:!0}),ignoreSpeedPenalty:new fields2.BooleanField({required:!1,nullable:!1,initial:!0})},{required:!1,initial:void 0}),tempHP:new ResolvableValueField({required:!1,nullable:!0,initial:null}),senses:new RecordField(new fields2.StringField({required:!0,blank:!1,choices:[...SENSE_TYPES]}),new fields2.SchemaField({acuity:new fields2.StringField({choices:SENSE_ACUITIES,required:!1,blank:!1,initial:void 0}),range:new fields2.NumberField({required:!1,nullable:!0,initial:void 0})}),{required:!1,initial:void 0}),size:new fields2.StringField({required:!1,blank:!1,initial:void 0}),speeds:new fields2.ObjectField({required:!1,initial:void 0}),skills:new fields2.ObjectField({required:!1,initial:void 0}),strikes:new fields2.ObjectField({required:!1}),immunities:new fields2.ArrayField(new fields2.ObjectField),weaknesses:new fields2.ArrayField(new fields2.ObjectField),resistances:new fields2.ArrayField(new fields2.ObjectField)},{required:!0,nullable:!1}),ownUnarmed:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),canCast:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),canSpeak:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),hasHands:new fields2.BooleanField({required:!1,nullable:!1,initial:!1})}}async preCreate({itemSource,ruleSource}){if(!this.test()){ruleSource.ignored=!0;return}const rules=itemSource.system?.rules??[];for(const rule of rules)if(["DamageDice","FlatModifier","Note"].includes(String(rule.key))){const predicate=rule.predicate??=[];Array.isArray(predicate)&&predicate.push("battle-form")}await __privateMethod(this,_resolveStrikeQueries,resolveStrikeQueries_fn).call(this,ruleSource)}onCreate(actorUpdates){if(this.ignored)return;const tempHP=this.overrides.tempHP;tempHP&&new TempHPRuleElement({key:"TempHP",label:this.label,value:tempHP},{parent:this.item}).onCreate(actorUpdates)}beforePrepareData(){if(this.ignored)return;const{actor}=this,{attributes}=actor;if(attributes.polymorphed){actor.synthetics.preparationWarnings.add("PF2e System | You are already under a polymorph effect"),this.ignored=!0;return}attributes.polymorphed=!0,attributes.battleForm=!0,__privateMethod(this,_setRollOptions,setRollOptions_fn).call(this),__privateMethod(this,_prepareSenses,prepareSenses_fn).call(this);for(const trait of this.overrides.traits){const currentTraits=actor.system.traits;currentTraits.value.includes(trait)||currentTraits.value.push(trait)}if(this.overrides.armorClass?.ignoreSpeedPenalty){const speedRollOptions=actor.rollOptions.speed??={};speedRollOptions["armor:ignore-speed-penalty"]=!0}}afterPrepareData(){this.ignored||(__privateMethod(this,_prepareAC,prepareAC_fn).call(this),__privateMethod(this,_prepareSize,prepareSize_fn).call(this),__privateMethod(this,_prepareSkills,prepareSkills_fn).call(this),__privateMethod(this,_prepareSpeeds,prepareSpeeds_fn).call(this),__privateMethod(this,_prepareStrikes,prepareStrikes_fn).call(this),__privateMethod(this,_prepareIWR,prepareIWR_fn).call(this),this.actor.initiative=new ActorInitiative(this.actor),this.actor.system.attributes.initiative=this.actor.initiative.getTraceData())}onDelete(actorUpdates){if(this.ignored)return;const tempHP=this.overrides.tempHP;tempHP&&new TempHPRuleElement({key:"TempHP",label:this.label,value:tempHP},{parent:this.item}).onDelete(actorUpdates)}applyDamageExclusion(weapon,modifiers){if(!this.ownUnarmed)for(const modifier of modifiers){if(modifier.predicate.some(s=>s instanceof Object&&"not"in s&&s.not==="battle-form"))continue;const isNumericBonus=modifier instanceof ModifierPF2e&&modifier.modifier>=0,isAbilityModifier=modifier instanceof ModifierPF2e&&modifier.type==="ability",isExtraDice=modifier instanceof DamageDicePF2e,isStatusOrCircumstance=isNumericBonus&&["status","circumstance"].includes(modifier.type),isDamageTrait=isExtraDice&&/^(?:deadly|fatal)-\d?d\d{1,2}$/.test(modifier.slug)&&tupleHasValue(this.overrides?.strikes?.[weapon.slug??""]?.traits??[],modifier.slug),isBattleFormModifier=!!(modifier.predicate.includes("battle-form")||modifier.predicate.some(s=>s instanceof Object&&"or"in s&&s.or.includes("battle-form"))||isDamageTrait);(isNumericBonus||isAbilityModifier||isExtraDice)&&!isStatusOrCircumstance&&!isBattleFormModifier&&(modifier.enabled=!1,modifier.ignored=!0,modifier.predicate.push({not:"battle-form"}))}}};_defaultIcons=new WeakMap,_setRollOptions=new WeakSet,setRollOptions_fn=__name2(function(){const{attributes,rollOptions}=this.actor;if(rollOptions.all.polymorph=!0,rollOptions.all["battle-form"]=!0,this.overrides.armorClass&&(rollOptions.all["armor:ignore-check-penalty"]=this.overrides.armorClass.ignoreCheckPenalty,rollOptions.all["armor:ignore-speed-penalty"]=this.overrides.armorClass.ignoreSpeedPenalty,this.overrides.armorClass.ignoreSpeedPenalty)){const speedRollOptions=rollOptions.speed??={};speedRollOptions["armor:ignore-speed-penalty"]=!0}if(this.overrides.skills)for(const key of SKILL_ABBREVIATIONS){if(!(key in this.overrides.skills))continue;const longForm=SKILL_DICTIONARY[key];rollOptions.all[`battle-form:${longForm}`]=!0}attributes.handsFree=Math.max(Object.values(this.overrides.strikes??{}).reduce((count,s)=>s.category==="unarmed"?count:count-1,2),0);for(const num of[0,1,2])attributes.handsFree===num?rollOptions.all[`hands-free:${num}`]=!0:delete rollOptions.all[`hands-free:${num}`]},"#setRollOptions"),_prepareAC=new WeakSet,prepareAC_fn=__name2(function(){const overrides=this.overrides,{actor}=this,{armorClass}=actor;if(!(Number(this.resolveValue(overrides.armorClass?.modifier,armorClass.value))||0))return;__privateMethod(this,_suppressModifiers,suppressModifiers_fn).call(this,armorClass);const newModifier=(Number(this.resolveValue(overrides.armorClass?.modifier))||0)-10;armorClass.modifiers.push(new ModifierPF2e(this.modifierLabel,newModifier,"untyped")),this.actor.system.attributes.ac=armorClass.parent.getTraceData()},"#prepareAC"),_prepareSenses=new WeakSet,prepareSenses_fn=__name2(function(){for(const senseType of SENSE_TYPES){const newSense=this.overrides.senses?.[senseType];if(!newSense)continue;newSense.acuity??="precise";const ruleData={key:"Sense",selector:senseType,force:!0,...newSense};new SenseRuleElement(ruleData,{parent:this.item}).beforePrepareData()}},"#prepareSenses"),_prepareSize=new WeakSet,prepareSize_fn=__name2(function(){if(!this.overrides.size)return;const ruleData={key:"CreatureSize",label:this.label,value:this.overrides.size};new CreatureSizeRuleElement(ruleData,{parent:this.item}).beforePrepareData()},"#prepareSize"),_prepareSpeeds=new WeakSet,prepareSpeeds_fn=__name2(function(){const{attributes}=this.actor,currentSpeeds=attributes.speed;for(const movementType of MOVEMENT_TYPES){const speedOverride=this.overrides.speeds?.[movementType];if(typeof speedOverride=="number")if(movementType==="land")__privateMethod(this,_suppressModifiers,suppressModifiers_fn).call(this,attributes.speed),attributes.speed.value=speedOverride;else{const{otherSpeeds}=currentSpeeds,label=game.i18n.localize(CONFIG.PF2E.speedTypes[movementType]);otherSpeeds.findSplice(s=>s.type===movementType),otherSpeeds.push({type:movementType,label,value:speedOverride});const newSpeed=this.actor.prepareSpeed(movementType);if(!newSpeed)throw ErrorPF2e("Unexpected failure retrieving movement type");__privateMethod(this,_suppressModifiers,suppressModifiers_fn).call(this,newSpeed),otherSpeeds.findSplice(s=>s.type===movementType),otherSpeeds.push(newSpeed)}}},"#prepareSpeeds"),_prepareSkills=new WeakSet,prepareSkills_fn=__name2(function(){for(const[skillShort,newSkill]of Object.entries(this.overrides.skills??{})){if(!setHasElement(SKILL_ABBREVIATIONS,skillShort))return this.failValidation(`Unrecognized skill abbreviation: ${skillShort}`);newSkill.ownIfHigher??=!0;const key=SKILL_DICTIONARY[skillShort],currentSkill=this.actor.skills[key],newModifier=Number(this.resolveValue(newSkill.modifier))||0;if(currentSkill.mod>newModifier&&newSkill.ownIfHigher)continue;const baseMod=new ModifierPF2e({label:this.modifierLabel,slug:"battle-form",modifier:newModifier,type:"untyped"});this.actor.skills[key]=currentSkill.extend({modifiers:[baseMod],filter:__privateMethod(this,_filterModifier,filterModifier_fn)}),this.actor.system.skills[skillShort]=mergeObject(this.actor.system.skills[skillShort],this.actor.skills[key].getTraceData())}},"#prepareSkills"),_prepareStrikes=new WeakSet,prepareStrikes_fn=__name2(function(){const{synthetics}=this.actor,strikes=this.overrides.strikes??{},ruleData=Object.entries(strikes).map(([slug,strikeData])=>({key:"Strike",label:game.i18n.localize(strikeData.label)??`PF2E.BattleForm.Attack.${sluggify(slug,{camel:"bactrian"})}`,slug,img:strikeData.img??__privateGet(_BattleFormRuleElement,_defaultIcons)[slug]??this.item.img,category:strikeData.category,group:strikeData.group,baseItem:strikeData.baseType,options:[slug],damage:{base:strikeData.damage},range:strikeData.range,maxRange:strikeData.maxRange,traits:strikeData.traits??[],ability:strikeData.ability,ownIfHigher:strikeData.ownIfHigher??=!0}));if(this.ownUnarmed){for(const[slug,weapon]of synthetics.strikes.entries())weapon.category!=="unarmed"&&synthetics.strikes.delete(slug);this.actor.rollOptions.all["battle-form:own-attack-modifier"]=!0}else{synthetics.strikes.clear();for(const striking of Object.values(synthetics.striking).flat())(striking.predicate??=new PredicatePF2e).push({not:"battle-form"});for(const datum of ruleData)datum.traits.includes("magical")||datum.traits.push("magical"),new StrikeRuleElement({...datum,battleForm:!0},{parent:this.item}).beforePrepareData()}this.actor.system.actions=this.actor.prepareStrikes({includeBasicUnarmed:this.ownUnarmed}).filter(a=>a.slug&&a.slug in strikes||this.ownUnarmed&&a.item.category==="unarmed");const strikeActions=this.actor.system.actions.flatMap(s=>[s,...s.altUsages]);for(const action2 of strikeActions){const strike=strikes[action2.slug??""]??null;if(!this.ownUnarmed&&strike&&(Number(this.resolveValue(strike.modifier))>=action2.totalModifier||!strike.ownIfHigher)){__privateMethod(this,_suppressModifiers,suppressModifiers_fn).call(this,action2),__privateMethod(this,_suppressNotes,suppressNotes_fn).call(this,Object.entries(synthetics.rollNotes).flatMap(([key,note])=>/\bdamage\b/.test(key)?note:[]));const baseModifier=Number(this.resolveValue(strike.modifier))||0;action2.unshift(new ModifierPF2e(this.modifierLabel,baseModifier,"untyped"))}else{const options=this.actor.rollOptions["strike-attack-roll"]??={};options["battle-form:own-attack-modifier"]=!0,action2.calculateTotal(new Set(this.actor.getRollOptions(action2.domains)))}}},"#prepareStrikes"),_prepareIWR=new WeakSet,prepareIWR_fn=__name2(function(){for(const immunity of this.overrides.immunities)new ImmunityRuleElement({key:"Immunity",...immunity},{parent:this.item}).afterPrepareData();for(const weakness of this.overrides.weaknesses){const args={key:"Weakness",...weakness,override:!0};new WeaknessRuleElement(args,{parent:this.item}).afterPrepareData()}for(const resistance of this.overrides.resistances){const args={key:"Resistance",...resistance,override:!0};new ResistanceRuleElement(args,{parent:this.item}).afterPrepareData()}},"#prepareIWR"),_suppressModifiers=new WeakSet,suppressModifiers_fn=__name2(function(statistic){for(const modifier of statistic.modifiers)__privateMethod(this,_filterModifier,filterModifier_fn).call(this,modifier)||(modifier.adjustments.push({slug:null,test:()=>!0,suppress:!0}),modifier.ignored=!0,modifier.enabled=!1);statistic instanceof StatisticModifier&&statistic.calculateTotal()},"#suppressModifiers"),_filterModifier=new WeakSet,filterModifier_fn=__name2(function(modifier){return modifier.slug==="battle-form"?!0:modifier.type==="ability"?!1:["status","circumstance"].includes(modifier.type)||modifier.modifier<0},"#filterModifier"),_suppressNotes=new WeakSet,suppressNotes_fn=__name2(function(notes){for(const note of notes)note.predicate.includes("battle-form")||(note.predicate=note.predicate instanceof PredicatePF2e?note.predicate:new PredicatePF2e(note.predicate),note.predicate.push({not:"battle-form"}))},"#suppressNotes"),_resolveStrikeQueries=new WeakSet,resolveStrikeQueries_fn=__name2(async function(ruleSource){const value=ruleSource.overrides?ruleSource.overrides:ruleSource.value??={};if(!__name2(v=>isObject(v)&&isObject(v.strikes),"hasStrikes")(value))return;const isStrikeQuery=__name2(maybeQuery=>isObject(maybeQuery)?typeof maybeQuery.query=="string"&&typeof maybeQuery.modifier=="number":!1,"isStrikeQuery");for(const[slug,strike]of Object.entries(value.strikes)){if(!isStrikeQuery(strike))continue;strike.pack=String(strike.pack??"pf2e.equipment-srd"),strike.ownIfHigher=!!(strike.ownIfHigher??!0);const queryObject=(()=>{try{const parsed=JSON.parse(String(this.resolveInjectedProperties(strike.query)));if(!isObject(parsed)||Array.isArray(parsed))throw Error("A strike query must be an NeDB query object");return parsed}catch(error){return error instanceof Error&&this.failValidation(error.message),ruleSource.ignored=!0,null}})();if(!queryObject){this.failValidation("Malformed query object");break}const weapon=(await game.packs.get(strike.pack)?.getDocuments(queryObject))?.[0];if(!(weapon instanceof WeaponPF2e)){this.failValidation("Failed to retrieve queried weapon");break}const resolved={label:weapon.name,img:weapon.img,ability:weapon.isRanged||weapon.traits.has("finesse")?"dex":"str",category:weapon.category,group:weapon.group,baseType:weapon.baseType,traits:deepClone(weapon.system.traits.value),modifier:strike.modifier,damage:deepClone(weapon.system.damage),ownIfHigher:strike.ownIfHigher};value.strikes[slug]=resolved}},"#resolveStrikeQueries"),__name2(_BattleFormRuleElement,"BattleFormRuleElement"),__publicField(_BattleFormRuleElement,"validActorTypes",["character"]),__privateAdd(_BattleFormRuleElement,_defaultIcons,["antler","beak","body","bone-shard","branch","claw","cube-face","fangs","fire-mote","fist","foot","foreleg","gust","horn","jaws","lighting-lash","mandibles","piercing-hymn","pincer","pseudopod","rock","spikes","stinger","tail","talon","tendril","tentacle","tongue","trunk","tusk","vine","water-spout","wave","wing"].reduce((accumulated,slug)=>{const path=slug==="fist"?"icons/skills/melee/unarmed-punch-fist.webp":`systems/pf2e/icons/unarmed-attacks/${slug}.webp`;return{...accumulated,[slug]:path}},{}));let BattleFormRuleElement=_BattleFormRuleElement;const _PickAThingPrompt=class extends Application{static{__name(this,"_PickAThingPrompt")}constructor(data){super(),__publicField(this,"item"),__privateAdd(this,_resolve3,void 0),__publicField(this,"selection",null),__publicField(this,"choices",[]),__publicField(this,"selectMenu"),__publicField(this,"predicate"),__publicField(this,"allowNoSelection"),this.item=data.item,this.predicate=data.predicate??new PredicatePF2e,this.options.title=data.title??this.item.name,this.allowNoSelection=data.allowNoSelection??!1}get actor(){return this.item.actor}static get defaultOptions(){return{...super.defaultOptions,classes:["pick-a-thing-prompt"],resizable:!1,height:"auto",width:"auto"}}getChoices(){return this.choices.filter(choice=>this.predicate.test(choice.domain??[]))??[]}getSelection(event){if(!(event.currentTarget instanceof HTMLElement))throw ErrorPF2e("Unexpected error retrieving form data");const selectedIndex=(event.currentTarget.closest(".choice")?.querySelector("button[data-action=pick]")??event.currentTarget.closest(".content")?.querySelector("tag")??event.currentTarget).getAttribute("value");return["",null].includes(selectedIndex)||!Number.isInteger(Number(selectedIndex))?null:this.choices.at(Number(selectedIndex))??null}async resolveSelection(){return this.choices=this.getChoices(),this.render(!0),new Promise(resolve=>{__privateSet(this,_resolve3,resolve)})}async getData(options={}){const slug=this.item.slug??sluggify(this.item.name);return options.id=`pick-a-${slug}`,{selectMenu:this.choices.length>9,choices:this.choices.map((c,index)=>({...c,value:index}))}}activateListeners($html){const html=$html[0];for(const element of htmlQueryAll(html,"a[data-choice], button[data-action=pick]"))element.addEventListener("click",event=>{this.selection=this.getSelection(event)??null,this.close()});const select=htmlQuery(html,"input[data-tagify-select]");select&&(this.selectMenu=new Tagify(select,{enforceWhitelist:!0,keepInvalidTags:!1,mode:"select",tagTextProp:"label",dropdown:{closeOnSelect:!0,enabled:1,highlightFirst:!0,mapValueTo:"label",maxItems:this.choices.length,searchKeys:["label"]},whitelist:this.choices.map((c,index)=>({value:index.toString(),label:c.label}))}),this.selectMenu.DOM.input.spellcheck=!1)}async close(options){var _a;for(const element of htmlQueryAll(this.element[0],"button, select"))element.style.pointerEvents="none";return this.choices.length===0?ui.notifications.warn(game.i18n.format("PF2E.UI.RuleElements.Prompt.NoValidOptions",{actor:this.actor.name,item:this.item.name})):!this.selection&&!this.allowNoSelection&&ui.notifications.warn(game.i18n.format("PF2E.UI.RuleElements.Prompt.NoSelectionMade",{item:this.item.name})),(_a=__privateGet(this,_resolve3))==null||_a.call(this,this.selection),super.close(options)}};_resolve3=new WeakMap,__name2(_PickAThingPrompt,"PickAThingPrompt");let PickAThingPrompt=_PickAThingPrompt;const _ChoiceSetPrompt=class extends PickAThingPrompt{static{__name(this,"_ChoiceSetPrompt")}prompt;containsItems;allowedDrops;constructor(data){super(data),this.prompt=data.prompt,this.choices=data.choices??[],this.containsItems=data.containsItems,this.allowedDrops=this.containsItems?data.allowedDrops:null}static get defaultOptions(){return{...super.defaultOptions,classes:["choice-set-prompt"],dragDrop:[{dropSelector:".drop-zone"}],template:"systems/pf2e/templates/system/rules-elements/choice-set-prompt.hbs"}}async getData(options={}){return{...await super.getData(options),choices:this.choices.map((c,index)=>({...c,value:index,hasUUID:UUIDUtils.isItemUUID(c.value)})),prompt:this.prompt,includeDropZone:!!this.allowedDrops,allowNoSelection:this.allowNoSelection,selectMenu:this.choices.length>9,containsItems:this.containsItems}}getChoices(){return this.choices}setChoices(choices){this.choices=choices}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"button[data-action=close]")?.addEventListener("click",()=>{this.close()});const renderItemSheet=__name2(async choice=>{if(!choice||!UUIDUtils.isItemUUID(choice.value))return;(await fromUuid(choice.value))?.sheet.render(!0)},"renderItemSheet");if(this.containsItems)if(this.selectMenu){const itemInfoAnchor=htmlQuery(html,"a.item-info");if(!itemInfoAnchor)return;const updateAnchor=__name2((disable,value="")=>{itemInfoAnchor.dataset.value=value,itemInfoAnchor.classList.toggle("disabled",disable),itemInfoAnchor.dataset.tooltip=game.i18n.localize(disable?"PF2E.UI.RuleElements.ChoiceSet.ViewItem.Disabled":"PF2E.UI.RuleElements.ChoiceSet.ViewItem.Tooltip")},"updateAnchor");itemInfoAnchor.addEventListener("click",event=>{renderItemSheet(this.getSelection(event))}),this.selectMenu.on("change",event=>{const data=event.detail.tagify.value.at(0);if(!data)return updateAnchor(!0);const index=Number(data.value);if(!isNaN(index)){const choice=this.choices.at(index);UUIDUtils.isItemUUID(choice?.value)?updateAnchor(!1,data.value):updateAnchor(!0)}})}else for(const anchor of htmlQueryAll(html,"a.item-info"))anchor.addEventListener("click",event=>{renderItemSheet(this.getSelection(event))})}async resolveSelection(){const firstChoice=this.choices.at(0);return!this.allowedDrops&&firstChoice&&this.choices.length===1?this.selection=firstChoice:(this.choices.length===0&&!this.allowedDrops&&this.close(),super.resolveSelection())}async _onDrop(event){event.preventDefault();const dataString=event.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??"");if(dropData?.type!=="Item"){ui.notifications.error("Only an item can be dropped here.");return}const droppedItem=await ItemPF2e.fromDropData(dropData);if(!droppedItem)throw ErrorPF2e("Unexpected error resolving drop");const isAllowedDrop=!!this.allowedDrops?.predicate.test(droppedItem.getRollOptions("item"));if(this.allowedDrops&&!isAllowedDrop){ui.notifications.error(game.i18n.format("PF2E.Item.ABC.InvalidDrop",{badType:droppedItem.name,goodType:game.i18n.localize(this.allowedDrops.label??"")}));return}const newChoice={value:this.containsItems&&this.choices.length>0&&this.choices.every(c=>!UUIDUtils.isItemUUID(c.value))?droppedItem.slug??sluggify(droppedItem.id):droppedItem.uuid,label:droppedItem.name},choicesLength=this.choices.push(newChoice),prompt=document.querySelector(`#${this.id}`),dropZone=prompt?.querySelector(".drop-zone");if(!prompt)throw ErrorPF2e("Unexpected error retrieving ChoiceSet dialog");if(prompt.style.height="unset",this.selectMenu){const{whitelist}=this.selectMenu.settings,menuChoice={value:String(choicesLength-1),label:newChoice.label};whitelist?.push(menuChoice.value),this.selectMenu.setPersistedData(whitelist,"whitelist"),this.selectMenu.addTags([menuChoice],!0,!0),this.selectMenu.setReadonly(!0),dropZone?.remove()}else{const img=document.createElement("img");img.src=droppedItem.img;const newButton=createHTMLElement("button",{classes:["with-image"],children:[img,createHTMLElement("span",{children:[droppedItem.name]})]});newButton.type="button",newButton.value=String(choicesLength-1),newButton.addEventListener("click",event2=>{this.selection=this.getSelection(event2)??null,this.close()}),dropZone?.replaceWith(newButton)}}_canDragDrop(){return this.actor.isOwner}};__name2(_ChoiceSetPrompt,"ChoiceSetPrompt");let ChoiceSetPrompt=_ChoiceSetPrompt;const _ChoiceSetRuleElement=class extends RuleElementPF2e{static{__name(this,"_ChoiceSetRuleElement")}constructor(data,options){if(super(data,options),__privateAdd(this,_setDefaultFlag),__privateAdd(this,_choicesFromArray),__privateAdd(this,_choicesFromPath),__privateAdd(this,_choicesFromOwnedItems),__privateAdd(this,_choicesFromAttacks),__privateAdd(this,_getPreselection),__privateAdd(this,_setRollOption),__publicField(this,"containsItems",!1),__publicField(this,"selection"),this.allowedDrops??=null,this.allowNoSelection??=!1,this.rollOption??=this.slug,this.flag=__privateMethod(this,_setDefaultFlag,setDefaultFlag_fn).call(this,this),this.selection=typeof data.selection=="string"||typeof data.selection=="number"||isObject(data.selection)?data.selection:null,isObject(this.choices)&&!Array.isArray(this.choices)&&!("filter"in this.choices)&&(this.choices.predicate=new PredicatePF2e(this.choices.predicate??[]),this.choices.unarmedAttacks&&this.choices.predicate.push("item:category:unarmed")),this.item.flags.pf2e.rulesSelections[this.flag]=this.selection,this.selection!==null)__privateMethod(this,_setRollOption,setRollOption_fn).call(this,this.selection);else if(!this.allowNoSelection&&this.test()){this.ignored=!0;for(const ruleData of this.item.system.rules)ruleData.ignored=!0}}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),choices:new DataUnionField([new StrictArrayField(new StrictObjectField({required:!0,nullable:!1,initial:void 0}),{required:!0,nullable:!1,initial:void 0}),new StrictObjectField({required:!0,nullable:!1,initial:void 0}),new StrictStringField({required:!0,nullable:!1,initial:void 0})],{required:!0,nullable:!1,initial:()=>[]}),prompt:new fields2.StringField({required:!0,blank:!1,nullable:!1,initial:"PF2E.UI.RuleElements.ChoiceSet.Prompt"}),adjustName:new fields2.BooleanField({required:!0,nullable:!1,initial:!0}),allowedDrops:new fields2.SchemaField({label:new fields2.StringField({required:!0,blank:!1,nullable:!0,initial:null}),predicate:new PredicateField},{required:!1,nullable:!0,initial:void 0}),flag:new fields2.StringField({required:!1,blank:!1,nullable:!1,initial:void 0}),rollOption:new fields2.StringField({required:!1,blank:!1,nullable:!0,initial:null}),allowNoSelection:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0})}}async preCreate({itemSource,ruleSource,pendingItems}){if(this.selection===null&&isObject(this.choices)&&"query"in this.choices){this.failValidation("As of FVTT version 11, choice set queries are no longer supported.");for(const ruleData of this.item.system.rules)ruleData.ignored=!0;return}const rollOptions=new Set([this.actor.getRollOptions(),this.item.getRollOptions("parent")].flat());if(!this.resolveInjectedProperties(this.predicate).test(rollOptions))return;if(isObject(this.choices)){const{choices}=this;if("ownedItems"in choices&&choices.ownedItems&&!choices.types?.length){console.warn("PF2E System | Failure during ChoiceSet preCreate: `types` is required if `ownedItems` is set"),ruleSource.ignored=!0;return}}__privateMethod(this,_setDefaultFlag,setDefaultFlag_fn).call(this,ruleSource);const inflatedChoices=await this.inflateChoices(rollOptions,pendingItems),selection=__privateMethod(this,_getPreselection,getPreselection_fn).call(this)??await new ChoiceSetPrompt({prompt:this.prompt,item:this.item,title:this.label,choices:inflatedChoices,containsItems:this.containsItems,allowedDrops:this.allowedDrops,allowNoSelection:this.allowNoSelection}).resolveSelection();if(selection){if(ruleSource.selection=selection.value,this.adjustName){const effectName=itemSource.name,label=game.i18n.localize(selection.label),name2=`${effectName} (${label})`,pattern=(()=>{const escaped=RegExp.escape(label);return new RegExp(`\\(${escaped}\\) \\(${escaped}\\)$`)})();itemSource.name=name2.replace(pattern,`(${label})`)}if(this.item.flags.pf2e.rulesSelections[this.flag]=selection.value,typeof ruleSource.rollOption=="string"&&UUIDUtils.isItemUUID(selection.value)){const item=await fromUuid(selection.value);if(item instanceof ItemPF2e){const slug=item.slug??sluggify(item.name);this.rollOption=ruleSource.rollOption=`${ruleSource.rollOption}:${slug}`}}__privateMethod(this,_setRollOption,setRollOption_fn).call(this,ruleSource.selection);for(const rule of this.item.rules)rule.ignored=!1,rule.onApplyActiveEffects?.()}else ruleSource.ignored=!0}async inflateChoices(rollOptions,pendingItems){const choices=Array.isArray(this.choices)?__privateMethod(this,_choicesFromArray,choicesFromArray_fn).call(this,this.choices,rollOptions):isObject(this.choices)?this.choices.ownedItems?__privateMethod(this,_choicesFromOwnedItems,choicesFromOwnedItems_fn).call(this,this.choices,rollOptions):this.choices.attacks||this.choices.unarmedAttacks?__privateMethod(this,_choicesFromAttacks,choicesFromAttacks_fn).call(this,new PredicatePF2e(this.resolveInjectedProperties(this.choices.predicate)),rollOptions):"filter"in this.choices&&Array.isArray(this.choices.filter)?await this.queryCompendium(this.choices,rollOptions,pendingItems):[]:typeof this.choices=="string"?__privateMethod(this,_choicesFromPath,choicesFromPath_fn).call(this,this.choices):[],choicesAreUUIDs=choices.every(c=>UUIDUtils.isItemUUID(c.value));if(choicesAreUUIDs){const itemChoices=await UUIDUtils.fromUUIDs(choices.map(c=>c.value));for(let i=0;i({value:c.value,label:game.i18n.localize(c.label),img:c.img}));return Array.isArray(this.choices)||choiceData.sort((a,b)=>a.label.localeCompare(b.label)),choiceData}catch{return[]}}async queryCompendium(choices,actorRollOptions,pendingItems){const filter2=Array.isArray(choices.filter)?new PredicatePF2e(this.resolveInjectedProperties(choices.filter)):new PredicatePF2e;if(!filter2.isValid||filter2.length===0)return this.failValidation("`filter` must be an array with at least one statement"),[];const itemType=objectHasKey(CONFIG.PF2E.Item.documentClasses,choices.itemType)?choices.itemType:"feat",packs=typeof choices.pack=="string"?compact([game.packs.get(choices.pack)]):game.packs.filter(p=>p.metadata.type==="Item"&&p.index.some(e=>e.type===itemType)),progress=new Progress({max:packs.length}),localize=localizer("PF2E.ProgressBar"),indexData=[];for(const pack of packs)progress.advance({label:localize("LoadingPack",{pack:pack.metadata.label})}),indexData.push(await pack.getIndex({fields:["flags","system.ancestry","system.baseItem","system.category","system.group","system.level","system.maxTakable","system.potencyRune","system.slug","system.traits"]}));progress.close({label:localize("LoadingComplete")});const filteredItems=indexData.flatMap(d=>d.contents).filter(s=>s.type===itemType).map(source=>{const parsedUUID=foundry.utils.parseUuid(source.uuid),pack=parsedUUID.collection instanceof CompendiumCollection?parsedUUID.collection.metadata.id:null;return new ItemProxyPF2e(deepClone(source),{pack})}).concat(game.items.filter(i=>i.type===itemType)).filter(i=>filter2.test([...i.getRollOptions("item"),...actorRollOptions])),existing=new Map;for(const feat of this.actor.itemTypes.feat){const slug=feat.slug??sluggify(feat.name);existing.set(slug,(existing.get(slug)??0)+1)}for(const featSource of pendingItems.filter(i=>i.type==="feat")){const slug=featSource.system?.slug??sluggify(featSource.name);existing.set(slug,(existing.get(slug)??0)+1)}return filteredItems.filter(i=>i instanceof FeatPF2e?(existing.get(i.slug??sluggify(i.name))??0)({value:choices.slugsAsValues?f.slug??sluggify(f.name):f.uuid,label:f.name,img:f.img}))}};_setDefaultFlag=new WeakSet,setDefaultFlag_fn=__name2(function(source){return source.flag=typeof source.flag=="string"&&source.flag.length>0?source.flag.replace(/[^-a-z0-9]/gi,""):sluggify(this.slug??this.item.slug??this.item.name,{camel:"dromedary"})},"#setDefaultFlag"),_choicesFromArray=new WeakSet,choicesFromArray_fn=__name2(function(choices,actorRollOptions){return choices.filter(c=>this.resolveInjectedProperties(new PredicatePF2e(c.predicate??[])).test(actorRollOptions))},"#choicesFromArray"),_choicesFromPath=new WeakSet,choicesFromPath_fn=__name2(function(path){const choiceObject=getProperty(CONFIG.PF2E,path)??getProperty(this.actor,path)??{};return Array.isArray(choiceObject)&&choiceObject.every(c=>isObject(c)&&typeof c.value=="string")?choiceObject:isObject(choiceObject)&&Object.values(choiceObject).every(c=>typeof c=="string")?Object.entries(choiceObject).map(([value,label])=>({value,label:String(label)})):[]},"#choicesFromPath"),_choicesFromOwnedItems=new WeakSet,choicesFromOwnedItems_fn=__name2(function(options,actorRollOptions){const{includeHandwraps,types}=options,predicate=new PredicatePF2e(this.resolveInjectedProperties(options.predicate)),choices=this.actor.items.filter(i=>i.isOfType(...types)&&predicate.test([...actorRollOptions,...i.getRollOptions("item")])).filter(i=>!i.isOfType("weapon")||i.category!=="unarmed").map(i=>({img:i.img,label:i.name,value:i.id}));return includeHandwraps&&choices.push(...this.actor.itemTypes.weapon.filter(i=>i.slug==="handwraps-of-mighty-blows"&&predicate.test([...actorRollOptions,...i.getRollOptions("item")])).map(h=>({img:h.img,label:h.name,value:"unarmed"}))),choices},"#choicesFromOwnedItems"),_choicesFromAttacks=new WeakSet,choicesFromAttacks_fn=__name2(function(predicate,actorRollOptions){return this.actor.isOfType("character","npc")?this.actor.system.actions.filter(a=>a.item.isOfType("melee","weapon")&&predicate.test([...actorRollOptions,...a.item.getRollOptions("item")])).map(a=>({img:a.item.img,label:a.item.name,value:a.item.slug??sluggify(a.item.name)})):[]},"#choicesFromAttacks"),_getPreselection=new WeakSet,getPreselection_fn=__name2(function(){return(Array.isArray(this.choices)?this.choices.find(c=>c.value===this.selection):null)??null},"#getPreselection"),_setRollOption=new WeakSet,setRollOption_fn=__name2(function(selection){if(!(this.rollOption&&(typeof selection=="string"||typeof selection=="number")))return;const suffix=UUIDUtils.isItemUUID(selection)?"":`:${selection}`;this.actor.rollOptions.all[`${this.rollOption}${suffix}`]=!0},"#setRollOption"),__name2(_ChoiceSetRuleElement,"ChoiceSetRuleElement");let ChoiceSetRuleElement=_ChoiceSetRuleElement;const _CraftingEntryRuleElement=class extends RuleElementPF2e{static{__name(this,"_CraftingEntryRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1}),isAlchemical:new fields2.BooleanField({required:!1,initial:void 0}),isDailyPrep:new fields2.BooleanField({required:!1,initial:void 0}),isPrepared:new fields2.BooleanField({required:!1,initial:void 0}),maxItemLevel:new ResolvableValueField({required:!1,nullable:!1,initial:1}),maxSlots:new fields2.NumberField({required:!1,nullable:!1,initial:void 0}),craftableItems:new PredicateField,preparedFormulas:new fields2.ArrayField(new fields2.SchemaField({itemUUID:new fields2.StringField({required:!0,blank:!1}),quantity:new fields2.NumberField({required:!1,nullable:!1,initial:void 0}),sort:new fields2.NumberField({required:!1,nullable:!1,initial:void 0}),expended:new fields2.BooleanField({required:!1,initial:void 0}),isSignatureItem:new fields2.BooleanField({required:!1,initial:void 0})},{required:!0,nullable:!1}),{initial:[]})}}constructor(data,options){super({priority:19,...data},options)}beforePrepareData(){if(this.ignored)return;const selector=this.resolveInjectedProperties(this.selector),craftableItems=this.craftableItems??[];if(!PredicatePF2e.isValid(craftableItems))return this.failValidation("Malformed craftableItems predicate");this.actor.system.crafting.entries[this.selector]={selector,name:this.label,isAlchemical:this.isAlchemical,isDailyPrep:this.isDailyPrep,isPrepared:this.isPrepared,craftableItems,maxItemLevel:Number(this.resolveValue(this.maxItemLevel))||1,maxSlots:this.maxSlots,parentItem:this.item.id,preparedFormulaData:this.preparedFormulas};const option=sluggify(this.selector);this.actor.rollOptions.all[`crafting:entry:${option}`]=!0}};__name2(_CraftingEntryRuleElement,"CraftingEntryRuleElement"),__publicField(_CraftingEntryRuleElement,"validActorTypes",["character"]);let CraftingEntryRuleElement=_CraftingEntryRuleElement;const _CraftingFormulaRuleElement=class extends RuleElementPF2e{static{__name(this,"_CraftingFormulaRuleElement")}constructor(data,options){if(super(data,options),!(typeof data.uuid=="string"&&/^(?:Compendium|Item)\..*[a-z0-9]{16}$/i.test(data.uuid))){const{item}=this;this.failValidation(`Crafting formula rule element on ${item.name} (${item.uuid}) has a malformed UUID`)}}beforePrepareData(){this.ignored||this.actor.system.crafting.formulas.find(f=>f.uuid===this.data.uuid)||this.actor.system.crafting.formulas.push({uuid:this.data.uuid})}};__name2(_CraftingFormulaRuleElement,"CraftingFormulaRuleElement"),__publicField(_CraftingFormulaRuleElement,"validActorTypes",["character"]);let CraftingFormulaRuleElement=_CraftingFormulaRuleElement;const _CritSpecRuleElement=class extends RuleElementPF2e{static{__name(this,"_CritSpecRuleElement")}constructor(){super(...arguments),__privateAdd(this,_getEffect)}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),alternate:new fields2.BooleanField,text:new fields2.StringField({blank:!1,nullable:!0,initial:null})}}static validateJoint(data){if(super.validateJoint(data),data.alternate&&!data.text)throw Error(" alternate: must also include text")}beforePrepareData(){if(this.ignored)return;const synthetic=__name2((weapon,options)=>this.resolveInjectedProperties(this.predicate).test(options)?__privateMethod(this,_getEffect,getEffect_fn).call(this,weapon):null,"synthetic");this.actor.synthetics.criticalSpecalizations[this.alternate?"alternate":"standard"].push(synthetic)}};_getEffect=new WeakSet,getEffect_fn=__name2(function(weapon){const text=this.text?this.resolveInjectedProperties(this.text.trim()):null,note=__name2(()=>[new RollNotePF2e({selector:"strike-damage",title:"PF2E.Actor.Creature.CriticalSpecialization",text:text??`PF2E.Item.Weapon.CriticalSpecialization.${weapon.group}`,outcome:["criticalSuccess"]})],"note");if(this.alternate)return note();const slug="critical-specialization";switch(weapon.group){case"dart":case"knife":{const dice=new DamageDicePF2e({slug,selector:"strike-damage",label:"PF2E.Actor.Creature.CriticalSpecialization",damageType:"bleed",diceNumber:1,dieSize:"d6",critical:!0}),bonusValue=AutomaticBonusProgression.isEnabled(this.actor)?AutomaticBonusProgression.getAttackPotency(this.actor.level):weapon.isOfType("melee")?weapon.linkedWeapon?.system.runes.potency??0:weapon.system.runes.potency,bonus=bonusValue>0?new ModifierPF2e({slug,label:"PF2E.Actor.Creature.CriticalSpecialization",type:"item",damageType:"bleed",modifier:bonusValue,critical:!0}):null;return[dice,bonus??[]].flat()}case"pick":return weapon.baseDamage.die?[new ModifierPF2e({slug,label:"PF2E.Actor.Creature.CriticalSpecialization",type:"untyped",modifier:2*weapon.baseDamage.dice,critical:!0})]:[];default:return weapon.group?note():[]}},"#getEffect"),__name2(_CritSpecRuleElement,"CritSpecRuleElement"),__publicField(_CritSpecRuleElement,"validActorTypes",["character","npc"]);let CritSpecRuleElement=_CritSpecRuleElement;const _DamageDiceRuleElement=class extends RuleElementPF2e{static{__name(this,"_DamageDiceRuleElement")}constructor(data,options){super(data,options),__privateAdd(this,_isValidOverride),__privateAdd(this,_resolvedBracketsIsValid),this.brackets=this.isBracketedValue(data.value)?data.value:null,data.override&&!__privateMethod(this,_isValidOverride,isValidOverride_fn).call(this,data.override)&&(this.failValidation("The override property must be an object with one property of 'upgrade' (boolean),","'downgrade (boolean)', 'diceNumber' (integer between 0 and 10), 'dieSize' (d6-d12), or 'damageType'","(recognized damage type)"),this.override=null)}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,initial:void 0})),diceNumber:new ResolvableValueField({required:!1,initial:void 0}),dieSize:new fields2.StringField({required:!1,blank:!1,nullable:!0,initial:null}),damageType:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),critical:new fields2.BooleanField({required:!1,nullable:!0,initial:void 0}),category:new fields2.StringField({choices:["persistent","precision","splash"],required:!1,blank:!1,initial:void 0}),brackets:new ResolvableValueField({required:!1,nullable:!0,initial:void 0}),override:new fields2.ObjectField({required:!1,nullable:!0,initial:void 0})}}beforePrepareData(){if(!this.ignored)for(const selector of this.resolveInjectedProperties(this.selector)){if(selector==="null")continue;const deferredDice=__name2((params={})=>{const label=this.getReducedLabel(),testPassed=this.predicate.length===0||this.resolveInjectedProperties(this.predicate).test([...params.test??this.actor.getRollOptions(["damage"]),...this.item.getRollOptions("parent")]),resolveOptions={...params,warn:testPassed},diceNumber=Number(this.resolveValue(this.diceNumber,0,resolveOptions))||0;if(this.ignored)return null;const resolvedBrackets=this.resolveValue(this.brackets,{},resolveOptions);if(!__privateMethod(this,_resolvedBracketsIsValid,resolvedBracketsIsValid_fn).call(this,resolvedBrackets))return testPassed&&this.failValidation("Brackets failed to validate"),null;const damageType=this.resolveInjectedProperties(this.damageType,resolveOptions);if(damageType!==null&&!objectHasKey(CONFIG.PF2E.damageTypes,damageType))return testPassed&&this.failValidation(`Unrecognized damage type: ${damageType}`),null;if(this.override){if(this.override.damageType&&=this.resolveInjectedProperties(this.override.damageType,resolveOptions),"damageType"in this.override&&!objectHasKey(CONFIG.PF2E.damageTypes,this.override.damageType))return testPassed&&this.failValidation("Unrecognized damage type in override"),null;if(this.override.diceNumber&&=Math.floor(Number(this.resolveValue(this.override.diceNumber,resolveOptions))),typeof this.override.diceNumber=="number"&&this.override.diceNumber<0)return testPassed&&this.failValidation("A dice number must resolve to at least zero"),null;if(this.override.dieSize&&=this.resolveInjectedProperties(this.override.dieSize,resolveOptions),"dieSize"in this.override&&!setHasElement(DAMAGE_DIE_FACES,this.override.dieSize))return testPassed&&this.failValidation("Unrecognized die size in override"),null}const dieSize=this.resolveInjectedProperties(this.dieSize,resolveOptions);return dieSize!==null&&!setHasElement(DAMAGE_DIE_FACES,dieSize)?(testPassed&&this.failValidation("Die size must be a recognized damage die size, null, or omitted"),null):new DamageDicePF2e({selector,slug:this.slug??sluggify(this.item.name),label,diceNumber,dieSize,critical:this.critical,category:this.category,damageType,predicate:this.predicate,override:deepClone(this.override),enabled:testPassed,...resolvedBrackets})},"deferredDice");(this.actor.synthetics.damageDice[selector]??=[]).push(deferredDice)}}};_isValidOverride=new WeakSet,isValidOverride_fn=__name2(function(override){return override===void 0?!0:isObject(override)&&(typeof override.upgrade=="boolean"&&!("downgrade"in override)||typeof override.downgrade=="boolean"&&!("upgrade"in override)||typeof override.damageType=="string"||typeof override.dieSize=="string"||typeof override.diceNumber=="string"||typeof override.diceNumber=="number"&&Number.isInteger(override.diceNumber)&&override.diceNumber>=0&&override.diceNumber<=256)},"#isValidOverride"),_resolvedBracketsIsValid=new WeakSet,resolvedBracketsIsValid_fn=__name2(function(value){if(!isObject(value))return!1;const keysAreValid=Object.keys(value).every(k=>["diceNumber","dieSize","override"].includes(k)),diceNumberIsValid=!("diceNumber"in value)||typeof value.diceNumber=="number",dieSizeIsValid=!("dieSize"in value)||setHasElement(DAMAGE_DIE_FACES,value.dieSize),overrideIsValid=!("override"in value)||__privateMethod(this,_isValidOverride,isValidOverride_fn).call(this,value.override);return keysAreValid&&diceNumberIsValid&&dieSizeIsValid&&overrideIsValid},"#resolvedBracketsIsValid"),__name2(_DamageDiceRuleElement,"DamageDiceRuleElement");let DamageDiceRuleElement=_DamageDiceRuleElement;const _DexterityModifierCapRuleElement=class extends RuleElementPF2e{static{__name(this,"_DexterityModifierCapRuleElement")}static defineSchema(){return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1})}}beforePrepareData(){if(!this.test())return;const value=this.resolveValue(this.value);if(typeof value!="number")return this.failValidation("value must be a number");this.actor.synthetics.dexterityModifierCaps.push({value,source:this.label})}};__name2(_DexterityModifierCapRuleElement,"DexterityModifierCapRuleElement"),__publicField(_DexterityModifierCapRuleElement,"validActorTypes",["character","npc"]);let DexterityModifierCapRuleElement=_DexterityModifierCapRuleElement;const{fields:fields$1,validation}=foundry.data,_ItemAlterationValidator=class extends fields$1.SchemaField{static{__name(this,"_ItemAlterationValidator")}constructor(fields2,options={}){super(fields2,options),__privateAdd(this,_validateForItem,void 0),__publicField(this,"operableOnInstances"),__publicField(this,"operableOnSource"),options.validateForItem&&__privateSet(this,_validateForItem,options.validateForItem),this.operableOnInstances=options.operableOnInstances??!0,this.operableOnSource=options.operableOnSource??!0}isValid(data){var _a;const{item,alteration}=data,failure=this.validate(alteration);if(failure)throw new validation.DataModelValidationError(failure);if(item.type!==alteration.itemType)return!1;const forItemFailure=(_a=__privateGet(this,_validateForItem))==null?void 0:_a.call(this,item);if(forItemFailure)throw new validation.DataModelValidationError(forItemFailure);if(!this.operableOnInstances&&item instanceof ItemPF2e)throw new validation.DataModelValidationError("may only be applied to source data");if(!this.operableOnSource&&!(item instanceof ItemPF2e))throw new validation.DataModelValidationError("may only be applied to existing items");return!0}};_validateForItem=new WeakMap,__name2(_ItemAlterationValidator,"ItemAlterationValidator");let ItemAlterationValidator=_ItemAlterationValidator;const itemHasCounterBadge=__name2(item=>{if(!(itemIsOfType(item,"condition")?typeof item.system.value.value=="number":itemIsOfType(item,"effect")?item.system.badge?.type==="counter":!1))throw new foundry.data.validation.DataModelValidationError("effect lacks a badge")},"itemHasCounterBadge"),ITEM_ALTERATION_VALIDATORS={"ac-bonus":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,nullable:!1,integer:!0,positive:!0,initial:void 0})}),"badge-max":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["effect"]}),mode:new fields$1.StringField({required:!0,choices:["downgrade","override"]}),value:new fields$1.NumberField({required:!0,nullable:!1,integer:!0,positive:!0,initial:void 0})},{validateForItem:itemHasCounterBadge}),"badge-value":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["condition","effect"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,integer:!0,nullable:!1,positive:!0,initial:void 0})},{validateForItem:itemHasCounterBadge}),"bulk-held-or-stowed":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:Array.from(PHYSICAL_ITEM_TYPES)}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:BULK_VALUES,initial:void 0})}),"bulk-worn":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor","backpack"]}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:BULK_VALUES,initial:void 0})}),category:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:["light","heavy","medium"],initial:void 0})}),"dex-cap":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new StrictNumberField({required:!0,nullable:!1,integer:!0,initial:void 0})}),"check-penalty":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new StrictNumberField({required:!0,nullable:!1,integer:!0,initial:void 0})}),hardness:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:Array.from(PHYSICAL_ITEM_TYPES)}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","multiply","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,integer:!0,nullable:!1,positive:!0})}),"hp-max":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:Array.from(PHYSICAL_ITEM_TYPES)}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","multiply","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,nullable:!1,positive:!0,initial:void 0})}),"material-type":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:Array.from(PHYSICAL_ITEM_TYPES)}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:Array.from(PRECIOUS_MATERIAL_TYPES),initial:void 0})}),"pd-recovery-dc":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["condition"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,integer:!0,nullable:!1,positive:!0,initial:void 0})},{validateForItem(item){if(item.system.slug!=="persistent-damage")return new foundry.data.validation.DataModelValidationFailure({message:"item must be a persistent damage condition"})}}),"persistent-damage":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["condition"]}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.SchemaField({formula:new fields$1.StringField({required:!0,blank:!1,validate:value=>DamageRoll.validate(String(value))}),damageType:new fields$1.StringField({required:!0,choices:()=>CONFIG.PF2E.damageTypes}),dc:new fields$1.NumberField({required:!0,integer:!0,positive:!0,nullable:!1,initial:15})},{nullable:!1})},{validateForItem(item){if(item.system.slug!=="persistent-damage")return new foundry.data.validation.DataModelValidationFailure({message:"item must be a persistent damage condition"})}}),rarity:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:Array.from(PHYSICAL_ITEM_TYPES)}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:RARITIES})}),"frequency-max":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["action","feat"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","multiply","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,integer:!0,nullable:!1,positive:!0})}),"frequency-per":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["action","feat"]}),mode:new fields$1.StringField({required:!0,choices:["downgrade","override","upgrade"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:()=>Object.keys(CONFIG.PF2E.frequencies),initial:void 0})}),"other-tags":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:()=>keys.strict(CONFIG.PF2E.Item.documentClasses)}),mode:new fields$1.StringField({required:!0,choices:["add","subtract","remove"]}),value:new SlugField({required:!0,nullable:!1,blank:!1,initial:void 0})}),"speed-penalty":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new StrictNumberField({required:!0,nullable:!1,integer:!0,initial:void 0})}),strength:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new StrictNumberField({required:!0,nullable:!1,integer:!0,positive:!0,initial:void 0})}),traits:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","remove","subtract"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:()=>CONFIG.PF2E.armorTraits,initial:void 0})})},_ItemAlteration=class extends foundry.abstract.DataModel{static{__name(this,"_ItemAlteration")}constructor(){super(...arguments),__privateAdd(this,_adjustCreatureShieldData),__privateAdd(this,_getNewInterval)}static defineSchema(){const{fields:fields2}=foundry.data;return{mode:new fields2.StringField({required:!0,choices:["add","downgrade","multiply","override","remove","subtract","upgrade"],initial:void 0}),property:new fields2.StringField({required:!0,choices:this.VALID_PROPERTIES,initial:void 0}),value:new ResolvableValueField}}get actor(){return this.parent.actor}resolveValue(...args){return this.parent.resolveValue(...args)}applyTo(item){const data={item,alteration:{mode:this.mode,itemType:item.type,value:this.value=this.parent.resolveValue(this.value)}},{DataModelValidationFailure}=foundry.data.validation;switch(this.property){case"ac-bonus":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const armor=data.item,newValue=AELikeRuleElement.getNewValue(this.mode,armor.system.acBonus,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();armor.system.acBonus=Math.max(newValue,0),__privateMethod(this,_adjustCreatureShieldData,adjustCreatureShieldData_fn).call(this,armor);return}case"badge-max":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const effect=data.item,{badge}=effect.system;if(badge?.type!=="counter"||!badge.value||!badge.max)return;const newValue=AELikeRuleElement.getNewValue(this.mode,badge.max,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();const hardMax=badge.labels?.length??newValue;badge.max=Math.clamped(newValue,1,hardMax),badge.value=Math.clamped(badge.value,1,badge.max);return}case"badge-value":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const effect=data.item,badge=itemIsOfType(effect,"condition")?effect.system.value:effect.system.badge??{value:0};if(typeof badge.value!="number")return;const newValue=AELikeRuleElement.getNewValue(this.mode,badge.value,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();const max="max"in badge?badge.max??1/0:1/0;badge.value=Math.clamped(newValue,1,max);return}case"bulk-held-or-stowed":{const validator=ITEM_ALTERATION_VALIDATORS[this.property];if(data.alteration.value=String(data.alteration.value),!validator.isValid(data))return;data.item.system.weight.value=data.alteration.value,data.item instanceof foundry.abstract.DataModel&&(data.item.system.bulk=organizeBulkData(data.item));return}case"bulk-worn":{const validator=ITEM_ALTERATION_VALIDATORS[this.property];if(data.alteration.value=String(data.alteration.value),!validator.isValid(data))return;data.item.system.equippedBulk.value=data.alteration.value,data.item instanceof foundry.abstract.DataModel&&(data.item.system.bulk=organizeBulkData(data.item));return}case"category":{ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)&&(data.item.system.category=data.alteration.value);return}case"check-penalty":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const newValue=AELikeRuleElement.getNewValue(this.mode,data.item.system.checkPenalty,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();data.item.system.checkPenalty=newValue===null?null:Math.min(newValue,0);return}case"dex-cap":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const newValue=AELikeRuleElement.getNewValue(this.mode,data.item.system.dexCap,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();data.item.system.dexCap=Math.max(newValue,0);return}case"hardness":{if(ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)){const{system}=data.item,{value}=data.alteration,newValue=AELikeRuleElement.getNewValue(this.mode,system.hardness,value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();system.hardness=Math.max(newValue,0),__privateMethod(this,_adjustCreatureShieldData,adjustCreatureShieldData_fn).call(this,data.item)}return}case"hp-max":{if(ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)){const{hp}=data.item.system,{value}=data.alteration,newValue=AELikeRuleElement.getNewValue(this.mode,hp.max,value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();hp.max=Math.max(Math.trunc(newValue),1),"brokenThreshold"in hp&&(hp.brokenThreshold=Math.floor(hp.max/2)),__privateMethod(this,_adjustCreatureShieldData,adjustCreatureShieldData_fn).call(this,data.item)}return}case"persistent-damage":{const pdObject=isObject(data.alteration.value)?data.alteration.value:{dc:NaN},dc=Math.trunc(Math.abs(Number(pdObject?.dc)||15));data.alteration.value={...pdObject,dc};const validator=ITEM_ALTERATION_VALIDATORS[this.property];validator.isValid(data)&&(data.item.system.persistent=validator.initialize(data.alteration).value);return}case"material-type":{ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)&&(data.item.system.material.type=data.alteration.value,data.item.system.material.grade="standard","_source"in data.item&&(data.item.name=game.pf2e.system.generateItemName(data.item)));return}case"rarity":{ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)&&(data.item.system.traits.rarity=data.alteration.value);return}case"pd-recovery-dc":{const validator=ITEM_ALTERATION_VALIDATORS[this.property];if(data.alteration.value=this.resolveValue(data.alteration.value)||15,validator.isValid(data)&&data.item.system.persistent){const{persistent}=data.item.system,newValue=AELikeRuleElement.getNewValue(this.mode,persistent.dc,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();persistent.dc=Math.max(newValue,0)}return}case"frequency-max":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)||!data.item.system.frequency)return;const frequency=data.item.system.frequency,newValue=AELikeRuleElement.getNewValue(this.mode,frequency.max,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();frequency.max=newValue,frequency.value=Math.clamped(frequency.value??newValue,0,newValue);return}case"frequency-per":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)||!data.item.system.frequency)return;const newValue=__privateMethod(this,_getNewInterval,getNewInterval_fn).call(this,this.mode,data.item.system.frequency.per,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();data.item.system.frequency.per=newValue;return}case"other-tags":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const otherTags=data.item.system.traits.otherTags,newValue=AELikeRuleElement.getNewValue(this.mode,otherTags,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();this.mode==="add"?otherTags.includes(newValue)||otherTags.push(newValue):["subtract","remove"].includes(this.mode)&&otherTags.splice(otherTags.indexOf(newValue),1);return}case"speed-penalty":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const newValue=AELikeRuleElement.getNewValue(this.mode,data.item.system.speedPenalty,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();data.item.system.speedPenalty=newValue===null?null:Math.min(newValue,0);return}case"strength":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const newValue=AELikeRuleElement.getNewValue(this.mode,data.item.system.strength,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();data.item.system.strength=newValue===null?null:Math.max(newValue,0);return}case"traits":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const newValue=AELikeRuleElement.getNewValue(this.mode,data.item.system.traits.value,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();const traits=data.item.system.traits.value;this.mode==="add"?traits.includes(newValue)||traits.push(newValue):["subtract","remove"].includes(this.mode)&&traits.splice(traits.indexOf(newValue),1);return}}}};_adjustCreatureShieldData=new WeakSet,adjustCreatureShieldData_fn=__name2(function(item){if("actor"in item&&item.actor?.isOfType("character","npc")&&item.isOfType("armor")&&item.isShield){const{heldShield}=item.actor;if(item===heldShield){const shieldData=item.actor.attributes.shield;shieldData.ac=item.system.acBonus,shieldData.hardness=item.system.hardness,shieldData.hp.max=item.system.hp.max,shieldData.brokenThreshold=Math.floor(item.system.hp.max/2)}}},"#adjustCreatureShieldData"),_getNewInterval=new WeakSet,getNewInterval_fn=__name2(function(mode,current,newValue){const{DataModelValidationFailure}=foundry.data.validation;if(!objectHasKey(CONFIG.PF2E.frequencies,newValue))return new DataModelValidationFailure({invalidValue:current,fallback:!1});if(mode==="override")return newValue;function getDuration(key){return key==="turn"||key==="round"?Duration.fromISO("PT6S"):key==="day"?Duration.fromISO("PT24H"):Duration.fromISO(key)}__name(getDuration,"getDuration"),__name2(getDuration,"getDuration");const newIsLonger=newValue==="round"&¤t==="turn"||newValue==="PT24H"&¤t==="day"||getDuration(newValue)>getDuration(current);return mode==="upgrade"&&newIsLonger||mode==="downgrade"&&!newIsLonger?newValue:current},"#getNewInterval"),__name2(_ItemAlteration,"ItemAlteration"),__publicField(_ItemAlteration,"VALID_PROPERTIES",["ac-bonus","badge-max","badge-value","bulk-held-or-stowed","bulk-worn","category","check-penalty","dex-cap","hardness","hp-max","material-type","pd-recovery-dc","persistent-damage","rarity","frequency-max","frequency-per","other-tags","speed-penalty","strength","traits"]);let ItemAlteration=_ItemAlteration;const _EphemeralEffectRuleElement=class extends RuleElementPF2e{static{__name(this,"_EphemeralEffectRuleElement")}constructor(){super(...arguments),__privateAdd(this,_createDeferredEffect)}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),affects:new fields2.StringField({required:!0,choices:["target","origin"],initial:"target"}),selectors:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,nullable:!1,initial:void 0})),uuid:new fields2.StringField({required:!0,blank:!1,nullable:!1,initial:void 0}),adjustName:new fields2.BooleanField({required:!0,nullable:!1,initial:!0}),alterations:new fields2.ArrayField(new fields2.EmbeddedDataField(ItemAlteration),{required:!1,nullable:!1,initial:[]})}}static validateJoint(data){if(super.validateJoint(data),data.selectors.length===0)throw Error("must have at least one selector")}afterPrepareData(){for(const selector of this.resolveInjectedProperties(this.selectors)){const deferredEffect=__privateMethod(this,_createDeferredEffect,createDeferredEffect_fn).call(this);(this.actor.synthetics.ephemeralEffects[selector]??={target:[],origin:[]})[this.affects].push(deferredEffect)}}};_createDeferredEffect=new WeakSet,createDeferredEffect_fn=__name2(function(){return async(params={})=>{if(!this.test(params.test??this.actor.getRollOptions()))return null;const uuid=this.resolveInjectedProperties(this.uuid);if(!UUIDUtils.isItemUUID(uuid))return this.failValidation(`"${uuid}" does not look like a UUID`),null;const effect=game.pf2e.ConditionManager.conditions.get(uuid)??await fromUuid(uuid);if(!(effect instanceof ItemPF2e&&effect.isOfType("condition","effect")))return this.failValidation(`unable to find effect or condition item with uuid "${uuid}"`),null;const source=effect.toObject();if(source.system.rules.some(r=>typeof r.key=="string"&&(r.key==="ChoiceSet"||r.key==="GrantItem"&&!("inMemoryOnly"in r&&r.inMemoryOnly===!0)))&&this.failValidation("an ephemeral effect may not include a choice set or grant"),this.adjustName){const label=this.getReducedLabel();source.name=`${source.name} (${label})`}try{for(const alteration of this.alterations)alteration.applyTo(source)}catch(error){return error instanceof Error&&this.failValidation(error.message),null}return source}},"#createDeferredEffect"),__name2(_EphemeralEffectRuleElement,"EphemeralEffectRuleElement");let EphemeralEffectRuleElement=_EphemeralEffectRuleElement;const _FastHealingRuleElement=class extends RuleElementPF2e{static{__name(this,"_FastHealingRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1}),type:new fields2.StringField({required:!1,nullable:!1,choices:["fast-healing","regeneration"],initial:"fast-healing"}),details:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),deactivatedBy:new fields2.ArrayField(new fields2.StringField({required:!0,nullable:!1,blank:!1}),{required:!1,initial:void 0})}}static validateJoint(data){if(super.validateJoint(data),data.type==="fast-healing"){if(data.deactivatedBy)throw data.ignored=!0,Error("deactivatedBy is only valid for type regeneration");data.details&&(data.details=game.i18n.localize(data.details))}else if(data.type==="regeneration"){if(data.details)throw data.ignored=!0,Error("details is only valid for type fast-healing");if(data.deactivatedBy?.length){const typesArr=data.deactivatedBy.map(type=>objectHasKey(CONFIG.PF2E.weaknessTypes,type)?game.i18n.localize(CONFIG.PF2E.weaknessTypes[type]):type),types=localizeList(typesArr);data.details=game.i18n.format("PF2E.Encounter.Broadcast.FastHealing.DeactivatedBy",{types})}}}async onTurnStart(){if(!this.test())return;const value=this.resolveValue(this.value);if(typeof value!="number"&&typeof value!="string")return this.failValidation("value must be a number or a roll formula");const roll=(await new DamageRoll(`${value}`).evaluate({async:!0})).toJSON(),receivedMessage=game.i18n.localize(`PF2E.Encounter.Broadcast.FastHealing.${this.type}.ReceivedMessage`),postFlavor=`
${this.details??this.getReducedLabel()}
`,flavor=`
${receivedMessage}
${postFlavor}`,rollMode=this.actor.hasPlayerOwner?"publicroll":"gmroll",speaker=ChatMessagePF2e.getSpeaker({actor:this.actor,token:this.token});ChatMessagePF2e.create({flavor,speaker,type:CONST.CHAT_MESSAGE_TYPES.ROLL,rolls:[roll]},{rollMode})}};__name2(_FastHealingRuleElement,"FastHealingRuleElement"),__publicField(_FastHealingRuleElement,"validActorTypes",["character","npc","familiar"]);let FastHealingRuleElement=_FastHealingRuleElement;const _FixedProficiencyRuleElement=class extends RuleElementPF2e{static{__name(this,"_FixedProficiencyRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1}),value:new ResolvableValueField({required:!0,initial:void 0}),ability:new fields2.StringField({required:!0,choices:[...ATTRIBUTE_ABBREVIATIONS]})}}static validateJoint(data){data.selector==="ac"&&(data.ability="dex")}beforePrepareData(){const selector=this.resolveInjectedProperties(this.selector),proficiencyBonus=Number(this.resolveValue(this.value))||0,abilityModifier=this.ability?this.actor.system.abilities[this.ability].mod:0,modifier=new ModifierPF2e({type:"proficiency",slug:this.slug??sluggify(this.label),label:this.label,modifier:proficiencyBonus+abilityModifier});(this.actor.synthetics.modifiers[selector]??=[]).push(()=>modifier)}afterPrepareData(){const selector=this.resolveInjectedProperties(this.selector),systemData=this.actor.system,proficiency=SKILL_EXPANDED[selector]?.shortForm??selector,statistic=setHasElement(SKILL_ABBREVIATIONS,proficiency)?this.actor.skills[proficiency]:proficiency==="ac"?systemData.attributes.ac:null;if(statistic){const toIgnore=statistic.modifiers.filter(m=>m.type==="proficiency"&&m.slug!==this.slug);for(const modifier of toIgnore)modifier.predicate=new PredicatePF2e(`overridden-by-${this.slug}`)}}};__name2(_FixedProficiencyRuleElement,"FixedProficiencyRuleElement"),__publicField(_FixedProficiencyRuleElement,"validActorTypes",["character"]);let FixedProficiencyRuleElement=_FixedProficiencyRuleElement;const _FlatModifierRuleElement=class extends RuleElementPF2e{static{__name(this,"_FlatModifierRuleElement")}constructor(source,options){super(source,options),!this.item.isOfType("physical")&&this.type!=="item"&&(this.fromEquipment=!1),this.type==="ability"&&(this.ability?(this.slug=this.ability,this.label=CONFIG.PF2E.abilities[this.ability],this.value=`@actor.abilities.${source.ability}.mod`):this.failValidation('A flat modifier of type "ability" must also have an "ability" property with an ability abbreviation')),this.critical=typeof source.critical=="boolean"&&this.selectors.some(s=>s.includes("damage"))?source.critical:null,this.force&&this.type==="untyped"&&this.failValidation("A forced bonus or penalty must have a type"),this.removeAfterRoll&&!this.item.isOfType("effect")&&this.failValidation(" removeAfterRoll: may only be used with effects")}static validateJoint(data){if(super.validateJoint(data),data.type!=="ability"&&data.value===void 0)throw Error('must have defined value if type is not "ability"')}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,initial:void 0})),type:new fields2.StringField({required:!0,choices:Array.from(MODIFIER_TYPES),initial:"untyped"}),ability:new fields2.StringField({required:!1,choices:CONFIG.PF2E.abilities,initial:void 0}),min:new fields2.NumberField({required:!1,nullable:!1,initial:void 0}),max:new fields2.NumberField({required:!1,nullable:!1,initial:void 0}),force:new fields2.BooleanField,hideIfDisabled:new fields2.BooleanField,fromEquipment:new fields2.BooleanField({required:!0,nullable:!1,initial:!0}),damageType:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:void 0}),damageCategory:new fields2.StringField({required:!1,blank:!1,choices:damageCategoriesUnique,initial:void 0}),critical:new fields2.BooleanField({required:!1,nullable:!0,initial:null}),value:new ResolvableValueField({required:!1,nullable:!1,initial:void 0}),removeAfterRoll:new DataUnionField([new StrictStringField({required:!1,nullable:!1,choices:["if-enabled"],initial:void 0}),new StrictBooleanField({required:!1,nullable:!1,initial:void 0}),new PredicateField({required:!1,nullable:!1,initial:void 0})],{required:!1,nullable:!1,initial:!1})}}get selectors(){return this.selector}beforePrepareData(){if(this.ignored)return;const label=this.getReducedLabel(),slug=this.slug??sluggify(label),selectors=this.selectors.map(s=>this.resolveInjectedProperties(s)).filter(s=>!!s);if(selectors.length===0)return this.failValidation("must have at least one selector");for(const selector of selectors){if(selector==="null")continue;const construct=__name2((options={})=>{const resolvedValue=Number(this.resolveValue(this.value,0,options))||0;if(this.ignored)return null;const finalValue=Math.clamped(resolvedValue,this.min??resolvedValue,this.max??resolvedValue);if(game.pf2e.variantRules.AutomaticBonusProgression.suppressRuleElement(this,finalValue))return null;const damageType=this.damageType&&this.resolveInjectedProperties(this.damageType,{warn:!1})||null;if(damageType!==null&&!objectHasKey(CONFIG.PF2E.damageTypes,damageType))return this.test(options.test??[])&&this.failValidation(`Unrecognized damage type: ${damageType}`),null;const modifier=new ModifierPF2e({slug,label,modifier:finalValue,type:this.type,ability:this.type==="ability"?this.ability:null,predicate:this.resolveInjectedProperties(this.predicate),rule:this,force:this.force,damageType,damageCategory:this.damageCategory,critical:this.critical,hideIfDisabled:this.hideIfDisabled,source:this.item.uuid});return options.test&&modifier.test(options.test),modifier},"construct");(this.actor.synthetics.modifiers[selector]??=[]).push(construct)}}async afterRoll({check,rollOptions}){if(this.ignored||!this.removeAfterRoll||!this.item.isOfType("effect"))return;(this.removeAfterRoll===!0||this.removeAfterRoll==="if-enabled"&&check.modifiers.some(m=>m.rule===this&&m.enabled)||Array.isArray(this.removeAfterRoll)&&this.removeAfterRoll.test(rollOptions))&&await this.item.delete()}};__name2(_FlatModifierRuleElement,"FlatModifierRuleElement");let FlatModifierRuleElement=_FlatModifierRuleElement;const _GrantItemRuleElement=class extends RuleElementPF2e{static{__name(this,"_GrantItemRuleElement")}constructor(data,options){data.inMemoryOnly&&(data.priority??=99),super(data,options),__privateAdd(this,_getOnDeleteActions),__privateAdd(this,_applyChoiceSelections),__privateAdd(this,_setGrantFlags),__privateAdd(this,_runGrantedItemPreCreates),__privateAdd(this,_createInMemoryCondition),__privateAdd(this,_trackItem),__publicField(this,"grantedId"),__publicField(this,"preselectChoices"),__publicField(this,"onDeleteActions"),this.inMemoryOnly?(this.reevaluateOnUpdate=!0,this.allowDuplicate=!0):this.reevaluateOnUpdate&&(this.allowDuplicate=!1),this.onDeleteActions=__privateMethod(this,_getOnDeleteActions,getOnDeleteActions_fn).call(this,data);const isValidPreselect=__name2(p=>Object.values(p).every(v=>["string","number"].includes(typeof v)),"isValidPreselect");if(this.preselectChoices=isObject(data.preselectChoices)&&isValidPreselect(data.preselectChoices)?deepClone(data.preselectChoices):{},this.grantedId=this.item.flags.pf2e.itemGrants[this.flag??""]?.id??null,this.track){const grantedItem=this.actor.inventory.get(this.grantedId??"")??null;__privateMethod(this,_trackItem,trackItem_fn).call(this,grantedItem)}this.item.isOfType("physical")&&this.failValidation("parent item must not be physical")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),uuid:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:void 0,label:"PF2E.UUID.Label"}),flag:new SlugField({required:!0,nullable:!0,initial:null,camel:"dromedary"}),reevaluateOnUpdate:new fields2.BooleanField({label:"PF2E.RuleEditor.GrantItem.ReevaluateOnUpdate"}),inMemoryOnly:new fields2.BooleanField,allowDuplicate:new fields2.BooleanField({initial:!0,label:"PF2E.RuleEditor.GrantItem.AllowDuplicate"}),alterations:new StrictArrayField(new fields2.EmbeddedDataField(ItemAlteration)),track:new fields2.BooleanField}}static validateJoint(data){if(super.validateJoint(data),data.track&&!data.flag)throw Error("must have explicit flag set if granted item is tracked")}async preCreate(args){if(this.inMemoryOnly)return;const{itemSource,pendingItems,context}=args,ruleSource=args.ruleSource;if(this.reevaluateOnUpdate&&this.predicate.length===0)return ruleSource.ignored=!0,this.failValidation("`reevaluateOnUpdate` may only be used with a predicate.");const uuid=this.resolveInjectedProperties(this.uuid),grantedItem=await(async()=>{try{return(await fromUuid(uuid))?.clone()??null}catch(error){return console.error(error),null}})();if(!(grantedItem instanceof ItemPF2e)||(ruleSource.flag=typeof ruleSource.flag=="string"&&ruleSource.flag.length>0?sluggify(ruleSource.flag,{camel:"dromedary"}):(()=>{const defaultFlag=sluggify(grantedItem.slug??grantedItem.name,{camel:"dromedary"}),flagPattern=new RegExp(`^${defaultFlag}\\d*$`),itemGrants=itemSource.flags?.pf2e?.itemGrants??{},nthGrant=Object.keys(itemGrants).filter(g=>flagPattern.test(g)).length;return nthGrant>0?`${defaultFlag}${nthGrant+1}`:defaultFlag})(),this.flag=String(ruleSource.flag),!this.test()))return;const existingItem=this.actor.items.find(i=>i.sourceId===uuid);if(!this.allowDuplicate&&existingItem){__privateMethod(this,_setGrantFlags,setGrantFlags_fn).call(this,itemSource,existingItem),ui.notifications.info(game.i18n.format("PF2E.UI.RuleElements.GrantItem.AlreadyHasItem",{actor:this.actor.name,item:grantedItem.name}));return}itemSource._id??=randomID();const grantedSource=grantedItem.toObject();grantedSource._id=randomID(),itemSource.type==="effect"&&grantedSource.type==="effect"&&(grantedSource.system.level.value=itemSource.system?.level?.value??grantedSource.system.level.value),grantedSource.flags=mergeObject(grantedSource.flags,{core:{sourceId:uuid}});const tempGranted=new ItemProxyPF2e(deepClone(grantedSource),{parent:this.actor});if(tempGranted.isOfType("affliction","condition","effect")&&this.actor.isImmuneTo(tempGranted)){ruleSource.ignored=!0;return}tempGranted.prepareActorData?.();for(const rule of tempGranted.prepareRuleElements({suppressWarnings:!0}))rule.onApplyActiveEffects?.();__privateMethod(this,_applyChoiceSelections,applyChoiceSelections_fn).call(this,tempGranted);try{for(const alteration of this.alterations)alteration.applyTo(grantedSource)}catch(error){error instanceof Error&&this.failValidation(error.message)}if(!this.ignored){for(const item of[this.item,tempGranted])if(item.isOfType("class","feat")){const prefix=item.isOfType("class")||!item.isFeature?item.type:"feature",slug=item.slug??sluggify(item.name);this.actor.rollOptions.all[`self:${prefix}:${slug}`]=!0}this.grantedId=grantedSource._id,context.keepId=!0,__privateMethod(this,_setGrantFlags,setGrantFlags_fn).call(this,itemSource,grantedSource),__privateMethod(this,_trackItem,trackItem_fn).call(this,tempGranted),args.reevaluation||await __privateMethod(this,_runGrantedItemPreCreates,runGrantedItemPreCreates_fn).call(this,args,tempGranted,grantedSource,context),pendingItems.push(grantedSource)}}async preUpdateActor(){const noAction={create:[],delete:[]};if(!this.reevaluateOnUpdate||this.inMemoryOnly)return noAction;if(this.grantedId&&this.actor.items.has(this.grantedId))return this.test()?noAction:{create:[],delete:[this.grantedId]};const itemSource=this.item.toObject(),ruleSource=itemSource.system.rules[this.sourceIndex??-1];if(!ruleSource)return noAction;const pendingItems=[],context={parent:this.actor,render:!1};if(await this.preCreate({itemSource,pendingItems,ruleSource,context,reevaluation:!0}),pendingItems.length>0){const updatedGrants=itemSource.flags.pf2e?.itemGrants??{};return await this.item.update({"flags.pf2e.itemGrants":updatedGrants},{render:!1}),{create:pendingItems,delete:[]}}return noAction}beforePrepareData(){const condition=__privateMethod(this,_createInMemoryCondition,createInMemoryCondition_fn).call(this);if(!condition)return;const{actor}=this;condition.rules=condition.prepareRuleElements();for(const rule of condition.rules)rule.beforePrepareData?.(),actor.rules.push(rule);actor.conditions.set(condition.id,condition)}};_getOnDeleteActions=new WeakSet,getOnDeleteActions_fn=__name2(function(data){const actions=data.onDeleteActions;if(isObject(actions)){const ACTIONS=_GrantItemRuleElement.ON_DELETE_ACTIONS;return tupleHasValue(ACTIONS,actions.granter)||tupleHasValue(ACTIONS,actions.grantee)?pick(actions,[actions.granter?"granter":[],actions.grantee?"grantee":[]].flat()):null}return null},"#getOnDeleteActions"),_applyChoiceSelections=new WeakSet,applyChoiceSelections_fn=__name2(function(grantedItem){const source=grantedItem._source;for(const[flag,selection]of Object.entries(this.preselectChoices??{})){const rule=grantedItem.rules.find(rule2=>rule2 instanceof ChoiceSetRuleElement&&rule2.flag===flag);if(rule){const ruleSource=source.system.rules[grantedItem.rules.indexOf(rule)],resolvedSelection=this.resolveInjectedProperties(selection);rule.selection=ruleSource.selection=resolvedSelection}}},"#applyChoiceSelections"),_setGrantFlags=new WeakSet,setGrantFlags_fn=__name2(function(granter,grantee){const flags=mergeObject(granter.flags??{},{pf2e:{itemGrants:{}}});if(!this.flag)throw ErrorPF2e("Unexpected failure looking up RE flag key");flags.pf2e.itemGrants[this.flag]={id:grantee instanceof ItemPF2e?grantee.id:grantee._id,onDelete:this.onDeleteActions?.grantee??"detach"};const grantedBy={id:granter._id,onDelete:this.onDeleteActions?.granter??(setHasElement(PHYSICAL_ITEM_TYPES,grantee.type)?"detach":"cascade")};grantee instanceof ItemPF2e?grantee.update({"flags.pf2e.grantedBy":grantedBy},{render:!1}):grantee.flags=mergeObject(grantee.flags??{},{pf2e:{grantedBy}})},"#setGrantFlags"),_runGrantedItemPreCreates=new WeakSet,runGrantedItemPreCreates_fn=__name2(async function(originalArgs,grantedItem,grantedSource,context){for(const rule of grantedItem.rules){const ruleSource=grantedSource.system.rules[grantedItem.rules.indexOf(rule)];await rule.preCreate?.({...originalArgs,itemSource:grantedSource,ruleSource,context})}},"#runGrantedItemPreCreates"),_createInMemoryCondition=new WeakSet,createInMemoryCondition_fn=__name2(function(){if(!this.inMemoryOnly||!this.test())return null;const validationFailure="an in-memory-only grant must be a condition",uuid=this.resolveInjectedProperties(this.uuid);if(!UUIDUtils.isItemUUID(uuid))return this.failValidation(validationFailure),null;const conditionSource=game.pf2e.ConditionManager.conditions.get(uuid)?.toObject();if(!conditionSource)return this.failValidation(validationFailure),null;if(this.actor.isImmuneTo(conditionSource.system.slug))return null;for(const alteration of this.alterations)alteration.applyTo(conditionSource);const flags={pf2e:{grantedBy:{id:this.item.id,onDelete:"cascade"}}};conditionSource.flags.pf2e?.grantedBy;const condition=new ConditionPF2e(mergeObject(conditionSource,{_id:randomID(),flags,system:{references:{parent:{id:this.item.id}}}}),{parent:this.actor});return condition.prepareSiblingData(),condition.prepareActorData(),condition},"#createInMemoryCondition"),_trackItem=new WeakSet,trackItem_fn=__name2(function(grantedItem){if(!(this.track&&this.flag&&this.grantedId&&grantedItem instanceof PhysicalItemPF2e))return;this.actor.flags.pf2e.trackedItems[this.flag]=this.grantedId;const slug=sluggify(this.flag),rollOptionsAll=this.actor.rollOptions.all;for(const statement of grantedItem.getRollOptions(slug))rollOptionsAll[statement]=!0},"#trackItem"),__name2(_GrantItemRuleElement,"GrantItemRuleElement"),__publicField(_GrantItemRuleElement,"validActorTypes",["character","npc","familiar"]),__publicField(_GrantItemRuleElement,"ON_DELETE_ACTIONS",["cascade","detach","restrict"]);let GrantItemRuleElement=_GrantItemRuleElement;const _ItemAlterationRuleElement=class extends RuleElementPF2e{static{__name(this,"_ItemAlterationRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data,baseSchema=super.defineSchema(),PRIORITIES=AELikeRuleElement.CHANGE_MODE_DEFAULT_PRIORITIES;return baseSchema.priority.initial=d=>(PRIORITIES[String(d.mode)]??50)+100,{...baseSchema,itemId:new fields2.StringField({required:!1,nullable:!1,blank:!1,initial:void 0}),itemType:new fields2.StringField({required:!1,nullable:!1,choices:mapValues$1(CONFIG.PF2E.Item.documentClasses,key=>`TYPES.Item.${key}`),initial:void 0}),...ItemAlteration.defineSchema()}}static validateJoint(data){if(super.validateJoint(data),!data.itemId&&!data.itemType)throw Error("one of itemId and itemType must be defined")}onApplyActiveEffects(){if(this.ignored)return;const actorRollOptions=this.predicate.length>0?this.actor.getRollOptions():[];try{const items=this.itemId?compact([this.actor.items.get(this.resolveInjectedProperties(this.itemId))]):this.itemType==="condition"?this.actor.conditions:this.actor.itemTypes[this.itemType];for(const item of items){const itemRollOptions=this.predicate.length>0?item.getRollOptions("item"):[],rollOptions=[...actorRollOptions,...itemRollOptions];if(this.test(rollOptions)){const data=pick$1(this,["mode","property","value"]);new ItemAlteration(data,{parent:this}).applyTo(item)}}}catch(error){error instanceof Error&&this.failValidation(error.message)}}async preCreate(){if(this.ignored||this.property!=="hp-max")return;const itemsOfType=this.itemType?this.actor.itemTypes[this.itemType]:[],actorRollOptions=this.actor.getRollOptions(),updates=itemsOfType.filter(i=>this.test([...actorRollOptions,...i.getRollOptions("item")])).flatMap(item=>{const source=item.toObject(),alteration=new ItemAlteration(pick$1(this,["mode","property","value"]),{parent:this});alteration.applyTo(source),alteration.applyTo(item);const newHP=source.system.hp,oldHP=item._source.system.hp,newHPValue=Math.floor(oldHP.value*(newHP.max/oldHP.max));return newHPValue===oldHP.value?[]:{_id:item.id,"system.hp.value":newHPValue}});updates.length>0&&await this.actor.updateEmbeddedDocuments("Item",updates,{render:!1})}};__name2(_ItemAlterationRuleElement,"ItemAlterationRuleElement");let ItemAlterationRuleElement=_ItemAlterationRuleElement;const _LoseHitPointsRuleElement=class extends RuleElementPF2e{static{__name(this,"_LoseHitPointsRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,initial:void 0}),reevaluateOnUpdate:new fields2.BooleanField({required:!1,initial:!1}),recoverable:new fields2.BooleanField({required:!1,initial:!0})}}onCreate(actorUpdates){if(this.ignored)return;const value=Math.trunc(Math.abs(Number(this.resolveValue(this.value))||0)),currentHP=this.actor._source.system.attributes.hp.value;actorUpdates["system.attributes.hp.value"]=Math.max(currentHP-value,0)}beforePrepareData(){if(this.ignored)return;const{actor}=this;if(!this.recoverable){const value=Math.trunc(Math.abs(Number(this.resolveValue(this.value))||0));actor.system.attributes.hp.unrecoverable+=value}}async preUpdate(changes){if(!this.reevaluateOnUpdate||this.ignored)return;const previousValue=Math.trunc(Math.abs(Number(this.resolveValue(this.value))||0)),newItem=this.item.clone(changes),rule=newItem.system.rules.find(r=>r.key===this.key),valueChange=Math.trunc(Math.abs(Number(this.resolveValue(String(rule?.value),0,{resolvables:{item:newItem}}))))-previousValue;if(valueChange>0){const currentHP=this.actor._source.system.attributes.hp.value;await this.actor.update({"system.attributes.hp.value":Math.max(currentHP-valueChange,0)},{render:!1})}}};__name2(_LoseHitPointsRuleElement,"LoseHitPointsRuleElement"),__publicField(_LoseHitPointsRuleElement,"validActorTypes",["character","familiar","npc"]);let LoseHitPointsRuleElement=_LoseHitPointsRuleElement;const ARMOR_CATEGORIES=new Set(["unarmored","light","medium","heavy","light-barding","heavy-barding"]),_MartialProficiencyRuleElement=class extends RuleElementPF2e{static{__name(this,"_MartialProficiencyRuleElement")}static defineSchema(){return{...super.defineSchema(),kind:new StrictStringField({required:!0,nullable:!1,choices:["attack","defense"],initial:"attack"}),definition:new PredicateField({required:!0,nullable:!1}),sameAs:new StrictStringField({required:!1,nullable:!1,choices:[...WEAPON_CATEGORIES,...ARMOR_CATEGORIES]}),maxRank:new StrictStringField({required:!1,nullable:!1,choices:["trained","expert","master","legendary"]}),value:new ResolvableValueField({required:!1,initial:void 0})}}constructor(data,options){super({priority:9,...data},options),this.slug??=sluggify(this.label)}onApplyActiveEffects(){if(!this.test())return;const rank=Math.clamped(Number(this.resolveValue(this.value))||1,1,4),key=this.kind==="attack"?"attacks":"defenses";this.actor.system.proficiencies[key][this.slug]={definition:this.resolveInjectedProperties(this.definition),immutable:!0,label:this.label,sameAs:this.sameAs,rank,maxRank:this.maxRank,value:0,breakdown:""}}};__name2(_MartialProficiencyRuleElement,"MartialProficiencyRuleElement"),__publicField(_MartialProficiencyRuleElement,"validActorTypes",["character"]);let MartialProficiencyRuleElement=_MartialProficiencyRuleElement;const _MultipleAttackPenaltyRuleElement=class extends RuleElementPF2e{static{__name(this,"_MultipleAttackPenaltyRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1,label:"PF2E.RuleEditor.General.Selector"}),value:new ResolvableValueField({required:!0,initial:void 0,label:"PF2E.RuleEditor.General.Value"})}}beforePrepareData(){if(this.ignored)return;const selector=this.resolveInjectedProperties(this.selector),value=Number(this.resolveValue(this.value))||0;if(selector&&value&&value<0){const map2={label:game.i18n.format("PF2E.UI.RuleElements.MultipleAttackPenalty.Breakdown",{label:this.label}),penalty:value,predicate:this.predicate};(this.actor.synthetics.multipleAttackPenalties[selector]??=[]).push(map2)}else this.failValidation("must have a negative value")}};__name2(_MultipleAttackPenaltyRuleElement,"MultipleAttackPenaltyRuleElement");let MultipleAttackPenaltyRuleElement=_MultipleAttackPenaltyRuleElement;const _RollNoteRuleElement=class extends RuleElementPF2e{static{__name(this,"_RollNoteRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,initial:void 0}),{required:!0,nullable:!1}),title:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),visibility:new fields2.StringField({required:!0,nullable:!0,choices:["gm","owner"],initial:null}),outcome:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,choices:DEGREE_OF_SUCCESS_STRINGS}),{required:!1,nullable:!1,initial:void 0}),text:new DataUnionField([new StrictStringField({required:!0,blank:!1}),new ResolvableValueField],{required:!0,nullable:!1})}}beforePrepareData(){if(!this.ignored)for(const selector of this.resolveInjectedProperties(this.selector)){if(selector==="null")continue;const title=this.resolveInjectedProperties(this.title)?.trim()??null,text=this.resolveInjectedProperties(String(this.resolveValue(this.text,"",{evaluate:!1}))).trim();if(!text)return this.failValidation("text field resolved empty");const note=new RollNotePF2e({selector,title:title?this.getReducedLabel(title):null,text,predicate:this.resolveInjectedProperties(this.predicate),outcome:this.outcome,visibility:this.visibility,rule:this});(this.actor.synthetics.rollNotes[selector]??=[]).push(note)}}};__name2(_RollNoteRuleElement,"RollNoteRuleElement");let RollNoteRuleElement=_RollNoteRuleElement;const _RollOptionRuleElement=class extends RuleElementPF2e{static{__name(this,"_RollOptionRuleElement")}constructor(source,options){super(source,options),__privateAdd(this,_resolveOption),__privateAdd(this,_setFlag),__privateAdd(this,_setRollOption2),source.removeAfterRoll&&!this.item.isOfType("effect")&&this.failValidation("removeAfterRoll may only be used on rule elements from effect items"),this.toggleable==="totm"&&!game.settings.get("pf2e","totmToggles")&&(this.ignored=!0);const firstSuboption=this.suboptions.at(0);firstSuboption&&this.suboptions.every(s=>!s.selected)&&(firstSuboption.selected=!0)}static defineSchema(){const{fields:fields2}=foundry.data,baseSchema=super.defineSchema();return baseSchema.priority.initial=AELikeRuleElement.CHANGE_MODE_DEFAULT_PRIORITIES.override,{...baseSchema,domain:new fields2.StringField({required:!0,nullable:!1,initial:"all",blank:!1}),option:new fields2.StringField({required:!0,nullable:!1,blank:!1}),phase:new fields2.StringField({required:!1,nullable:!1,choices:deepClone(AELikeRuleElement.PHASES),initial:"applyAEs"}),suboptions:new fields2.ArrayField(new fields2.SchemaField({label:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:void 0}),value:new StrictStringField({required:!0,nullable:!1,blank:!1,initial:void 0}),predicate:new PredicateField,selected:new fields2.BooleanField}),{required:!1,nullable:!1,initial:[],validate:v=>Array.isArray(v)&&v.length!==1,validationError:"must have zero or 2+ suboptions"}),value:new ResolvableValueField({required:!1,initial:d=>!d.toggleable,validate:v=>["boolean","string"].includes(typeof v),validationError:"must be a boolean, string, or otherwise omitted"}),toggleable:new DataUnionField([new StrictStringField({required:!1,nullable:!1,choices:["totm"],initial:void 0}),new StrictBooleanField({required:!1,nullable:!1,initial:!1})],{required:!1,nullable:!1,initial:void 0}),placement:new fields2.StringField({required:!1,nullable:!1,initial:void 0}),disabledIf:new PredicateField({required:!1,initial:void 0}),disabledValue:new fields2.BooleanField({required:!1,initial:void 0}),alwaysActive:new fields2.BooleanField({required:!1,initial:void 0}),count:new fields2.BooleanField({required:!1,initial:void 0}),removeAfterRoll:new fields2.BooleanField({required:!1,initial:void 0})}}static validateJoint(source){if(super.validateJoint(source),source.suboptions.length>0&&!source.toggleable)throw Error(" suboptions: must be omitted if not toggleable");if(source.disabledIf&&!source.toggleable)throw Error(" disabledIf: must be false if not toggleable");if(source.count&&source.toggleable)throw Error(" count: must be false if toggleable");if(typeof source.disabledValue=="boolean"&&(!source.toggleable||!source.disabledIf))throw Error(" disabledValue: may only be included if toggeable and there is a disabledIf predicate.");if(source.alwaysActive&&(!source.toggleable||source.suboptions.length===0))throw Error(" alwaysActive: must be false unless toggleable and containing suboptions");if(source.placement&&!source.toggleable)throw Error(" placement: may only be present if toggleable")}onApplyActiveEffects(){this.phase==="applyAEs"&&__privateMethod(this,_setRollOption2,setRollOption_fn2).call(this)}beforePrepareData(){this.phase==="beforeDerived"&&__privateMethod(this,_setRollOption2,setRollOption_fn2).call(this)}afterPrepareData(){this.phase==="afterDerived"&&__privateMethod(this,_setRollOption2,setRollOption_fn2).call(this)}resolveValue(){return this.toggleable==="totm"&&!game.settings.get("pf2e","totmToggles")?!1:this.alwaysActive?!0:!!super.resolveValue(this.value)}async toggle(newValue=!this.resolveValue(),newSuboption=null){if(!this.toggleable)throw ErrorPF2e("Attempted to toggle non-toggleable roll option");const rulesSource=this.item.toObject().system.rules,thisSource=typeof this.sourceIndex=="number"?rulesSource.at(this.sourceIndex):null;if(!thisSource)return null;if(thisSource.value=newValue,newSuboption&&Array.isArray(thisSource.suboptions)&&thisSource.suboptions.every(o=>isObject(o)))for(const suboption of thisSource.suboptions)suboption.selected=suboption.value===newSuboption;return(await this.actor.updateEmbeddedDocuments("Item",[{_id:this.item.id,"system.rules":rulesSource}])).length===1?newValue:null}beforeRoll(domains,rollOptions){if(!(this.test(rollOptions)&&domains.includes(this.domain)))return;this.value=this.resolveValue();const option=__privateMethod(this,_resolveOption,resolveOption_fn).call(this);this.value?rollOptions.add(option):rollOptions.delete(option)}async afterRoll({domains,rollOptions}){const option=__privateMethod(this,_resolveOption,resolveOption_fn).call(this);!this.ignored&&this.removeAfterRoll&&this.value&&this.actor.items.has(this.item.id)&&domains.includes(this.domain)&&rollOptions.has(option)&&(game.settings.get("pf2e","automation.removeExpiredEffects")?await this.item.delete():game.settings.get("pf2e","automation.effectExpiration")&&await this.item.update({"system.duration.value":-1,"system.expired":!0}))}};_resolveOption=new WeakSet,resolveOption_fn=__name2(function({appendSuboption=!0}={}){const baseOption=this.resolveInjectedProperties(this.option).replace(/[^-:\w]/g,"").replace(/:+/g,":").replace(/-+/g,"-").trim();if(appendSuboption){const selectedSuboption=this.suboptions.find(o=>o.selected);return selectedSuboption?`${baseOption}:${selectedSuboption.value}`:baseOption}else return baseOption},"#resolveOption"),_setFlag=new WeakSet,setFlag_fn=__name2(function(value){const suboption=this.suboptions.find(o=>o.selected)??this.suboptions.at(0);if(suboption){const flagKey=sluggify(__privateMethod(this,_resolveOption,resolveOption_fn).call(this,{appendSuboption:!1}),{camel:"dromedary"});if(value){const flagValue=/^\d+$/.test(suboption.value)?Number(suboption.value):suboption.value;this.item.flags.pf2e.rulesSelections[flagKey]=flagValue}else this.item.flags.pf2e.rulesSelections[flagKey]=null}},"#setFlag"),_setRollOption2=new WeakSet,setRollOption_fn2=__name2(function(){this.domain=this.resolveInjectedProperties(this.domain);const isStandardDomain=/^[-a-z0-9]+$/.test(this.domain)&&/[a-z]/.test(this.domain),isIdDomain=/^[a-zA-Z0-9]{16}-[-a-z0-9]+[a-z0-9]$/.test(this.domain);if(!isStandardDomain&&!isIdDomain)return this.failValidation("domain must be a string consisting of only lowercase letters, numbers, and hyphens.");const optionSet=new Set([this.actor.getRollOptions([this.domain]),this.parent.getRollOptions("parent")].flat());if(!this.test(optionSet))return __privateMethod(this,_setFlag,setFlag_fn).call(this,!1);const{rollOptions}=this.actor,domainRecord=rollOptions[this.domain]??={},baseOption=this.option=__privateMethod(this,_resolveOption,resolveOption_fn).call(this,{appendSuboption:!1});if(!baseOption){this.failValidation('The "option" property must be a string consisting of only letters, numbers, colons, and hyphens');return}if(this.count){const existing=Object.keys(domainRecord).flatMap(key=>({key,count:Number(new RegExp(`^${baseOption}:(\\d+)$`).exec(key)?.[1])})).find(keyAndCount=>!!keyAndCount.count);existing?(delete domainRecord[existing.key],domainRecord[`${baseOption}:${existing.count+1}`]=!0):domainRecord[`${baseOption}:1`]=!0}else{const suboptions=this.suboptions.filter(s=>s.predicate.test(optionSet));if(suboptions.length>0&&!suboptions.some(s=>s.selected)){suboptions[0].selected=!0;for(const otherSuboption of this.suboptions)otherSuboption!==suboptions[0]&&(otherSuboption.selected=!1)}else if(this.suboptions.length>0&&suboptions.length===0)return;const fullOption=__privateMethod(this,_resolveOption,resolveOption_fn).call(this),value=this.resolveValue();if(value&&(domainRecord[fullOption]=value,domainRecord[baseOption]=value),this.toggleable){const toggle={itemId:this.item.id,label:this.getReducedLabel(),placement:this.placement??"actions-tab",domain:this.domain,option:baseOption,suboptions,alwaysActive:!!this.alwaysActive,checked:value,enabled:!0};if(this.disabledIf){const rollOptions2=this.actor.getRollOptions([this.domain]);toggle.enabled=!this.disabledIf.test(rollOptions2),!toggle.enabled&&!this.alwaysActive&&typeof this.disabledValue=="boolean"&&(toggle.checked=this.disabledValue,this.disabledValue||delete domainRecord[fullOption])}this.actor.synthetics.toggles.push(toggle)}__privateMethod(this,_setFlag,setFlag_fn).call(this,value)}},"#setRollOption"),__name2(_RollOptionRuleElement,"RollOptionRuleElement");let RollOptionRuleElement=_RollOptionRuleElement;const _RollTwiceRuleElement=class extends RuleElementPF2e{static{__name(this,"_RollTwiceRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1}),keep:new fields2.StringField({required:!0,choices:["lower","higher"]}),removeAfterRoll:new fields2.BooleanField({required:!1,initial:void 0})}}beforePrepareData(){if(this.ignored)return;const synthetic={keep:this.keep};this.predicate&&(synthetic.predicate=this.predicate),(this.actor.synthetics.rollTwice[this.selector]??=[]).push(synthetic)}async afterRoll({domains,roll,rollOptions}){if(!this.actor.items.has(this.item.id))return;const expireEffects=game.settings.get("pf2e","automation.effectExpiration"),removeExpired=game.settings.get("pf2e","automation.removeExpiredEffects"),removeAfterRoll=this.removeAfterRoll??((expireEffects||removeExpired)&&this.item.isOfType("effect"));if((roll?.dice.some(d=>["kh","kl"].some(m=>d.modifiers.includes(m)))??!1)&&removeAfterRoll&&domains.includes(this.selector)&&this.test(rollOptions)){for(const rule of this.item.rules)rule.ignored=!0;removeExpired?await this.item.delete():expireEffects&&await this.item.update({"system.duration.value":-1,"system.expired":!0})}}};__name2(_RollTwiceRuleElement,"RollTwiceRuleElement");let RollTwiceRuleElement=_RollTwiceRuleElement;const _SpecialStatisticRuleElement=class extends RuleElementPF2e{static{__name(this,"_SpecialStatisticRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),slug:new SlugField({required:!0,nullable:!1,initial:void 0,validate:v=>typeof v=="string"&&!(v in CONFIG.PF2E.magicTraditions||v in CONFIG.PF2E.classTraits||setHasElement(SKILL_LONG_FORMS,v)||tupleHasValue(SAVE_TYPES,v)||["perception","initiative"].includes(v))}),type:new fields2.StringField({required:!0,choices:["simple","check","attack-roll"],initial:"check"}),extends:new fields2.StringField({required:!0,nullable:!0,initial:null}),attribute:new fields2.StringField({required:!0,choices:Array.from(ATTRIBUTE_ABBREVIATIONS),nullable:!0,initial:null})}}afterPrepareData(){if(this.type==="simple")return;const checkDomains=this.type==="check"?[`${this.slug}-check`]:[`${this.slug}-attack-roll`],extendedFrom=this.extends?this.actor.getStatistic(this.extends):null,data={slug:this.slug,label:this.label,attribute:this.attribute??extendedFrom?.attribute??null,domains:[this.slug],check:{type:this.type==="check"?"check":"attack-roll",domains:checkDomains},dc:{domains:[`${this.slug}-dc`]}},statistic=extendedFrom?.extend(data)??new Statistic(this.actor,data);statistic?this.actor.synthetics.statistics.set(this.slug,statistic):this.failValidation(`Unable to find statistic ${this.extends} to extend from`)}};__name2(_SpecialStatisticRuleElement,"SpecialStatisticRuleElement");let SpecialStatisticRuleElement=_SpecialStatisticRuleElement;const _StrikingRuleElement=class extends RuleElementPF2e{static{__name(this,"_StrikingRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1}),value:new ResolvableValueField({required:!1,nullable:!1,initial:void 0})}}beforePrepareData(){if(this.ignored)return;const selector=this.resolveInjectedProperties(this.selector),strikingValue=this.value??(this.item instanceof WeaponPF2e?getStrikingDice(this.item.system):0),value=this.resolveValue(strikingValue);if(selector&&typeof value=="number"){const striking={label:this.getReducedLabel(),bonus:value,predicate:this.predicate};(this.actor.synthetics.striking[selector]??=[]).push(striking)}else this.failValidation("Striking requires at least a selector field and a non-empty resolved value")}};__name2(_StrikingRuleElement,"StrikingRuleElement"),__publicField(_StrikingRuleElement,"validActorTypes",["character","npc"]);let StrikingRuleElement=_StrikingRuleElement;const _SubstituteRollRuleElement=class extends RuleElementPF2e{static{__name(this,"_SubstituteRollRuleElement")}constructor(source,options){super(source,options),this.removeAfterRoll&&!this.item.isOfType("effect")&&this.failValidation(" removeAfterRoll: may only be used with effects")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1,initial:"check"}),value:new ResolvableValueField({required:!0,nullable:!1}),required:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),effectType:new fields2.StringField({required:!0,nullable:!1,choices:["fortune","misfortune"],initial:"fortune"}),removeAfterRoll:new DataUnionField([new StrictStringField({required:!1,nullable:!1,choices:["if-enabled"],initial:void 0}),new StrictBooleanField({required:!1,nullable:!1,initial:void 0}),new PredicateField({required:!1,nullable:!1,initial:void 0})],{required:!1,nullable:!1,initial:!1})}}beforePrepareData(){const value=Math.clamped(Math.trunc(Number(this.resolveValue(this.value))),1,20);if(Number.isNaN(value))return this.failValidation("value must resolve to a number");const selector=this.resolveInjectedProperties(this.selector);(this.actor.synthetics.rollSubstitutions[selector]??=[]).push({slug:this.slug??sluggify(this.item.name),label:this.label,value,predicate:this.predicate,required:this.required,selected:this.required,effectType:this.effectType})}async afterRoll(params){if(!this.removeAfterRoll||this.ignored)return;if(this.removeAfterRoll===!0){await this.item.delete();return}if(Array.isArray(this.removeAfterRoll)&&this.removeAfterRoll.test(params.rollOptions)){await this.item.delete();return}const rollSubstituted=params.roll.dice.length===0,substitutionIncluded=!!params.context.substitutions?.some(s=>s.slug===this.slug&&s.selected);this.removeAfterRoll==="if-enabled"&&rollSubstituted&&substitutionIncluded&&await this.item.delete()}};__name2(_SubstituteRollRuleElement,"SubstituteRollRuleElement");let SubstituteRollRuleElement=_SubstituteRollRuleElement;const _TokenEffect=class{static{__name(this,"_TokenEffect")}constructor(effect){__privateAdd(this,_effect,void 0),__publicField(this,"tint",null),__publicField(this,"isTemporary",!0),__privateSet(this,_effect,effect)}get id(){return __privateGet(this,_effect).id}get _id(){return __privateGet(this,_effect).id}get parent(){return __privateGet(this,_effect).parent}get name(){return __privateGet(this,_effect).name}get icon(){return __privateGet(this,_effect).img}get changes(){return[]}get description(){return __privateGet(this,_effect).description}get flags(){return __privateGet(this,_effect).flags}get statuses(){return new Set([__privateGet(this,_effect).slug??sluggify(__privateGet(this,_effect).name)])}get disabled(){return __privateGet(this,_effect).isOfType("effect")&&__privateGet(this,_effect).isExpired}get duration(){const effect=__privateGet(this,_effect),isEffect=effect.isOfType("effect");return{type:"none",seconds:null,rounds:null,turns:null,combat:null,startTime:isEffect?effect.system.start.value:null,startRound:null,startTurn:isEffect?effect.system.start.initiative:null,label:isEffect?effect.system.remaining:""}}get transfer(){return!1}get origin(){return __privateGet(this,_effect).uuid}getFlag(scope,flag){return __privateGet(this,_effect).getFlag(scope,flag)}};_effect=new WeakMap,__name2(_TokenEffect,"TokenEffect");let TokenEffect=_TokenEffect;const _TokenEffectIconRuleElement=class extends RuleElementPF2e{static{__name(this,"_TokenEffectIconRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new fields2.StringField({required:!1,blank:!1,initial:void 0})}}afterPrepareData(){if(!this.test())return;const path=this.value?this.resolveInjectedProperties(this.value).trim():this.item.img;if(!isImageFilePath(path))return this.failValidation("value is not a valid image file path");this.actor.synthetics.tokenEffectIcons.push(new TokenEffect(new EffectPF2e({type:"effect",name:this.label,img:path})))}};__name2(_TokenEffectIconRuleElement,"TokenEffectIconRuleElement");let TokenEffectIconRuleElement=_TokenEffectIconRuleElement;const _TokenImageRuleElement=class extends RuleElementPF2e{static{__name(this,"_TokenImageRuleElement")}constructor(data,options){super(data,options),__privateAdd(this,_srcIsValid),typeof this.value=="string"||this.isBracketedValue(this.value)||this.failValidation("value must be a string or a bracketed value")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0,label:"TOKEN.ImagePath"}),scale:new fields2.NumberField({required:!1,nullable:!0,positive:!0,initial:null,label:"Scale"}),tint:new fields2.ColorField({label:"TOKEN.TintColor"}),alpha:new fields2.AlphaField({label:"PF2E.RuleEditor.General.Opacity"})}}afterPrepareData(){const src=this.resolveValue(this.value);if(!__privateMethod(this,_srcIsValid,srcIsValid_fn).call(this,src))return this.failValidation("Missing or invalid value field");if(!this.test())return;const texture={src};this.scale&&(texture.scaleX=this.scale,texture.scaleY=this.scale),this.tint&&(texture.tint=this.tint),this.alpha&&(this.actor.synthetics.tokenOverrides.alpha=this.alpha),this.actor.synthetics.tokenOverrides.texture=texture}};_srcIsValid=new WeakSet,srcIsValid_fn=__name2(function(src){if(typeof src!="string")return!1;const extension=/(?<=\.)[a-z0-9]{3,4}$/i.exec(src)?.at(0);return!!extension&&(extension in CONST.IMAGE_FILE_EXTENSIONS||extension in CONST.VIDEO_FILE_EXTENSIONS)},"#srcIsValid"),__name2(_TokenImageRuleElement,"TokenImageRuleElement");let TokenImageRuleElement=_TokenImageRuleElement;const _TokenLightRuleElement=class extends RuleElementPF2e{static{__name(this,"_TokenLightRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new fields2.SchemaField({...foundry.data.LightData.defineSchema(),dim:new ResolvableValueField({required:!1,nullable:!1,initial:void 0}),bright:new ResolvableValueField({required:!1,nullable:!1,initial:void 0})})}}constructor(data,options){super(data,options),this.validateData()}validateData(){const light=this.value;for(const key of["dim","bright"])if(light[key]!==void 0){const resolvedValue=this.resolveValue(light[key]);if(typeof resolvedValue=="number")light[key]=resolvedValue;else return this.failValidation(`${key} must resolve to a number`)}try{new foundry.data.LightData(light)}catch(error){error instanceof Error&&this.failValidation(error.message)}}afterPrepareData(){this.test()&&(this.actor.synthetics.tokenOverrides.light=deepClone(this.value))}};__name2(_TokenLightRuleElement,"TokenLightRuleElement");let TokenLightRuleElement=_TokenLightRuleElement;const _MarkTargetPrompt=class{static{__name(this,"_MarkTargetPrompt")}constructor(params){__privateAdd(this,_cancelHandler),__publicField(this,"prompt"),__publicField(this,"requirements"),__privateAdd(this,_target,void 0),__privateAdd(this,_resolve4,void 0),this.prompt=params.prompt??"PF2E.UI.RuleElements.TokenMark.TargetToken",this.requirements=params.requirements}async resolveTarget(){return game.user.targets.clear(),this.activateListeners(),ui.notifications.info(this.prompt,{localize:!0}),new Promise(resolve=>{__privateSet(this,_resolve4,resolve)})}activateListeners(){document.activeElement instanceof HTMLElement&&document.activeElement.blur();const hookParams=["targetToken",(_user,token,targeted)=>{var _a;__privateSet(this,_target,targeted&&token instanceof TokenPF2e?token.document:null),(_a=__privateGet(this,_resolve4))==null||_a.call(this,__privateGet(this,_target))}];Hooks.once(...hookParams);const cancelHandler=__privateMethod(this,_cancelHandler,cancelHandler_fn).call(this,hookParams);document.addEventListener("keyup",cancelHandler),window.setTimeout(()=>{var _a;Hooks.off(...hookParams),document.removeEventListener("keyup",cancelHandler),__privateGet(this,_target)===void 0&&((_a=__privateGet(this,_resolve4))==null||_a.call(this,null))},15e3)}};_target=new WeakMap,_resolve4=new WeakMap,_cancelHandler=new WeakSet,cancelHandler_fn=__name2(function(hookParams){const handler=__name2(event=>{event.key==="Escape"&&(event.stopPropagation(),ui.notifications.info("PF2E.UI.RuleElements.TokenMark.Timeout",{localize:!0}),Hooks.off(...hookParams),document.removeEventListener("keyup",handler))},"handler");return handler},"#cancelHandler"),__name2(_MarkTargetPrompt,"MarkTargetPrompt");let MarkTargetPrompt=_MarkTargetPrompt;const _TokenMarkRuleElement=class extends RuleElementPF2e{static{__name(this,"_TokenMarkRuleElement")}constructor(){super(...arguments),__privateAdd(this,_checkRuleSource)}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),slug:new SlugField({required:!0,nullable:!1,initial:void 0}),uuid:new fields2.StringField({required:!1,nullable:!0,initial:null})}}async preCreate({ruleSource,itemSource,pendingItems}){if(this.ignored)return;if(this.uuid&&=this.resolveInjectedProperties(this.uuid),this.actor.getActiveTokens().length===0){this.ignored=ruleSource.ignored=!0;return}const token=fromUuidSync(this.uuid??"")??(game.user.targets.size===1?Array.from(game.user.targets)[0].document:await new MarkTargetPrompt({prompt:null,requirements:null}).resolveTarget());if(!(token instanceof TokenDocumentPF2e)){pendingItems.splice(pendingItems.indexOf(itemSource),1);return}__privateMethod(this,_checkRuleSource,checkRuleSource_fn).call(this,ruleSource),this.uuid=ruleSource.uuid=token.uuid}beforePrepareData(){UUIDUtils.isTokenUUID(this.uuid)&&this.test()&&this.actor.synthetics.tokenMarks.set(this.uuid,this.slug)}};_checkRuleSource=new WeakSet,checkRuleSource_fn=__name2(function(source){if(!(source.key==="TokenMark"&&source.slug===this.slug))throw ErrorPF2e("Unexpected rule element passed")},"#checkRuleSource"),__name2(_TokenMarkRuleElement,"TokenMarkRuleElement");let TokenMarkRuleElement=_TokenMarkRuleElement;const _TokenNameRuleElement=class extends RuleElementPF2e{static{__name(this,"_TokenNameRuleElement")}static defineSchema(){return{...super.defineSchema(),value:new ResolvableValueField({required:!0})}}afterPrepareData(){const name2=this.resolveValue(this.value);if(typeof name2!="string")return this.failValidation("value must resolve to a string");this.test()&&(this.actor.synthetics.tokenOverrides.name=name2)}};__name2(_TokenNameRuleElement,"TokenNameRuleElement");let TokenNameRuleElement=_TokenNameRuleElement;const _WeaponPotencyRuleElement=class extends RuleElementPF2e{static{__name(this,"_WeaponPotencyRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,nullable:!1,blank:!1}),value:new ResolvableValueField({required:!0})}}beforePrepareData(){if(this.ignored)return;const{weaponPotency}=this.actor.synthetics,selector=this.resolveInjectedProperties(this.selector),{item}=this,potencyValue=this.value??(item.isOfType("weapon")?item.system.potencyRune.value:0),value=this.resolveValue(potencyValue);if(selector&&typeof value=="number"){const bonusType=AutomaticBonusProgression.isEnabled(this.actor)?"potency":"item",potency={label:this.getReducedLabel(),bonus:value,type:bonusType,predicate:this.predicate};(weaponPotency[selector]??=[]).push(potency)}else this.failValidation("Weapon potency requires at least a selector field and a non-empty value field")}};__name2(_WeaponPotencyRuleElement,"WeaponPotencyRuleElement"),__publicField(_WeaponPotencyRuleElement,"validActorTypes",["character","npc"]);let WeaponPotencyRuleElement=_WeaponPotencyRuleElement;const _RuleElements=class{static{__name(this,"_RuleElements")}static get all(){return{...this.builtin,...this.custom}}static fromOwnedItem(options){const rules=[],item=options.parent;for(const[sourceIndex,source]of item.system.rules.entries()){if(typeof source.key!="string"){console.error(`PF2e System | Missing key in rule element ${source.key} on item ${item.name} (${item.uuid})`);continue}const REConstructor=this.custom[source.key]??this.custom[source.key]??this.builtin[source.key];if(REConstructor){const rule=(()=>{try{return new REConstructor(source,{...options,sourceIndex})}catch(error){return options?.suppressWarnings||(console.warn(`PF2e System | Failed to construct rule element ${source.key} on item ${item.name}`,`(${item.uuid})`),console.warn(error)),null}})();rule&&rules.push(rule)}else{const{name:name2,uuid}=item;console.warn(`PF2e System | Unrecognized rule element ${source.key} on item ${name2} (${uuid})`)}}return rules}};__name2(_RuleElements,"RuleElements"),__publicField(_RuleElements,"builtin",{ActiveEffectLike:AELikeRuleElement,ActorTraits:ActorTraitsRuleElement,AdjustDegreeOfSuccess:AdjustDegreeOfSuccessRuleElement,AdjustModifier:AdjustModifierRuleElement,AdjustStrike:AdjustStrikeRuleElement,Aura:AuraRuleElement,BaseSpeed:BaseSpeedRuleElement,BattleForm:BattleFormRuleElement,ChoiceSet:ChoiceSetRuleElement,CraftingEntry:CraftingEntryRuleElement,CraftingFormula:CraftingFormulaRuleElement,CreatureSize:CreatureSizeRuleElement,CriticalSpecialization:CritSpecRuleElement,DamageDice:DamageDiceRuleElement,DexterityModifierCap:DexterityModifierCapRuleElement,EphemeralEffect:EphemeralEffectRuleElement,FastHealing:FastHealingRuleElement,FixedProficiency:FixedProficiencyRuleElement,FlatModifier:FlatModifierRuleElement,GrantItem:GrantItemRuleElement,Immunity:ImmunityRuleElement,ItemAlteration:ItemAlterationRuleElement,LoseHitPoints:LoseHitPointsRuleElement,MartialProficiency:MartialProficiencyRuleElement,MultipleAttackPenalty:MultipleAttackPenaltyRuleElement,Note:RollNoteRuleElement,Resistance:ResistanceRuleElement,RollOption:RollOptionRuleElement,RollTwice:RollTwiceRuleElement,Sense:SenseRuleElement,SpecialStatistic:SpecialStatisticRuleElement,Strike:StrikeRuleElement,Striking:StrikingRuleElement,SubstituteRoll:SubstituteRollRuleElement,TempHP:TempHPRuleElement,TokenEffectIcon:TokenEffectIconRuleElement,TokenImage:TokenImageRuleElement,TokenLight:TokenLightRuleElement,TokenMark:TokenMarkRuleElement,TokenName:TokenNameRuleElement,Weakness:WeaknessRuleElement,WeaponPotency:WeaponPotencyRuleElement}),__publicField(_RuleElements,"custom",{});let RuleElements=_RuleElements;const CodeMirror={EditorView,basicSetup,json,jsonLinter:()=>linter(jsonParseLinter()),keybindings:keymap.of([indentWithTab]),ruleElementExtensions:options=>[json(),CodeMirror.jsonLinter(),autocompletion({override:[ruleElementAutocomplete(options)]})]};function ruleElementAutocomplete(options){const validKeysByPath=(()=>options.schema?{"":Object.keys(options.schema)}:{"":["key"]})();return context=>{const node=syntaxTree(context.state).resolveInner(context.pos,-1),isProperty=node.name==="Object"||node.type.name==="PropertyName",isValue=!isProperty&&(node.name==="Property"||node.parent?.name==="Property");if(isProperty){const basePath=resolveNodePath(context,node),keys2=basePath!==null?validKeysByPath[basePath]:[];return keys2?.length?{from:node.from,to:node.to,options:keys2.map(o=>({label:`"${o}"`}))}:null}else if(isValue&&resolveNodePath(context,node)==="key"){const options2=Object.keys(RuleElements.all);return{from:node.from,to:node.to,options:options2.map(o=>({label:`"${o}"`}))}}return null}}__name(ruleElementAutocomplete,"ruleElementAutocomplete"),__name2(ruleElementAutocomplete,"ruleElementAutocomplete");function resolveNodePath(context,node){node=node.type.name==="PropertyName"&&node.parent?node.parent:node;const parent=node.parent;if(!parent||parent.type.name==="JsonText")return"";const parentType=parent.type.name;if(parentType==="\u26A0")return null;const name2=(()=>parentType==="Object"?!parent.parent||parent.parent.type.name==="JsonText"?"":".":parentType==="Property"?context.state.sliceDoc(parent.from,parent.to).match(/^"([^"]*)"/)?.[1]:parentType==="Array"?"[]":null)();if(name2===null)return null;const basePath=resolveNodePath(context,parent);return basePath===null?null:basePath+name2}__name(resolveNodePath,"resolveNodePath"),__name2(resolveNodePath,"resolveNodePath");const _RuleElementForm=class{static{__name(this,"_RuleElementForm")}constructor(options){__privateAdd(this,_getFormHelpers),__publicField(this,"template","systems/pf2e/templates/items/rules/default.hbs"),__publicField(this,"tabs",null),__privateAdd(this,_activeTab,null),this.initialize(options)}get basePath(){return`system.rules.${this.index}`}initialize(options){this.sheet=options.sheet,this.index=options.index,this.rule=options.rule,this.object=options.object??(()=>{const RuleElementClass=RuleElements.all[String(this.rule.key)];if(!RuleElementClass)return null;const actor=new ActorProxyPF2e({_id:randomID(),name:"temp",type:"character"}),item=new ItemProxyPF2e(this.item.toObject(),{parent:actor});return new RuleElementClass(deepClone(this.rule),{parent:item,strict:!1,suppressWarnings:!0})})(),this.schema=this.object?.schema??RuleElements.all[String(this.rule.key)]?.schema??null}get item(){return this.sheet.item}get fieldIdPrefix(){return`field-${this.sheet.appId}-${this.index}-`}getInitialValue(){if(this.constructor.name==="RuleElementForm")return{};const initial=this.schema?.getInitialValue();if(!initial)return{};for(const property of["ignored","priority","slug"])delete initial[property];const removeArrays=__name2(object=>{for(const[key,value]of Object.entries(object))Array.isArray(value)?delete object[key]:isObject(value)&&removeArrays(value)},"removeArrays");return removeArrays(initial),initial}async getData(){const[label,recognized]=(()=>{const locPath=`PF2E.RuleElement.${this.rule.key}`,localized=game.i18n.localize(locPath);return localized===locPath?[game.i18n.localize("PF2E.RuleElement.Unrecognized"),!1]:[localized,!0]})(),mergedRule=mergeObject(this.getInitialValue(),this.rule);return{...pick$1(this,["index","rule","object"]),item:this.item,label,fieldIdPrefix:this.fieldIdPrefix,recognized,basePath:this.basePath,rule:mergedRule,fields:this.schema?.fields,form:await __privateMethod(this,_getFormHelpers,getFormHelpers_fn).call(this,mergedRule)}}async render(){const data=await this.getData();return renderTemplate("systems/pf2e/templates/items/rules/partials/outer.hbs",{...data,template:await renderTemplate(this.template,data)})}async updateItem(updates){const rules=this.item.toObject().system.rules,result=mergeObject(this.rule,updates,{performDeletions:!0});this.schema&&cleanDataUsingSchema(this.schema.fields,result),rules[this.index]=result,await this.item.update({"system.rules":rules})}activateListeners(html){this.element=html;const selectorElement=htmlQuery(html,".selector-list");tagify$1(selectorElement);const priorityInput=htmlQuery(html,".rule-element-header .priority input");priorityInput?.addEventListener("change",event=>{event.stopPropagation();const value=priorityInput.value;value===""||Number.isNaN(Number(value))?this.updateItem({"-=priority":null}):this.updateItem({priority:Number(value)})});for(const button of htmlQueryAll(html,"[data-action=toggle-brackets]"))button.addEventListener("click",()=>{const property=button.dataset.property??"value",value=getProperty(this.rule,property);isBracketedValue(value)?this.updateItem({[property]:""}):this.updateItem({[property]:{brackets:[{value:""}]}})});for(const button of htmlQueryAll(html,"[data-action=add-bracket]")){const property=button.dataset.property??"value";button.addEventListener("click",()=>{const value=getProperty(this.rule,property);isBracketedValue(value)&&(value.brackets.push({value:""}),this.updateItem({[property]:value}))})}for(const button of htmlQueryAll(html,"[data-action=delete-bracket]")){const property=button.dataset.property??"value";button.addEventListener("click",()=>{const value=getProperty(this.rule,property),idx=Number(htmlClosest(button,"[data-idx]")?.dataset.idx);isBracketedValue(value)&&(value.brackets.splice(idx,1),this.updateItem({[property]:value}))})}if(this.tabs){for(const anchor of htmlQueryAll(html,"a[data-rule-tab]"))anchor.addEventListener("click",()=>{this.activateTab(html,anchor.dataset.ruleTab)});this.activateTab(html,__privateGet(this,_activeTab))}for(const dropZone of htmlQueryAll(html,"div.rules-drop-zone"))dropZone.addEventListener("drop",event=>{this.onDrop(event,dropZone)})}async onDrop(event,_element){const data=event.dataTransfer?.getData("text/plain");return data?await ItemPF2e.fromDropData(JSON.parse(data))??null:null}activateTab(html,tabName){if(!this.tabs)return;const activeTab=tabName??this.tabs.names.at(0);if(!(!activeTab||!this.tabs.names.includes(activeTab))){__privateSet(this,_activeTab,activeTab);for(const element of htmlQueryAll(html,"[data-rule-tab]"))element.dataset.ruleTab===activeTab?(element.classList.add("active"),element.tagName!=="A"&&(element.style.display=this.tabs.displayStyle)):(element.classList.remove("active"),element.tagName!=="A"&&(element.style.display="none"))}}updateObject(source){if(typeof source=="string"){try{this.rule=JSON.parse(source)}catch(error){if(error instanceof Error)throw ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.RuleElementSyntax",{message:error.message})),console.warn("Syntax error in rule element definition.",error.message,source),error}return}source=mergeObject(duplicate(this.rule),source);for(const slider of htmlQueryAll(this.element,"input[type=range"))slider.style.pointerEvents="none";cleanPredicate(source),this.schema&&cleanDataUsingSchema(this.schema.fields,source),this.rule=source}};_activeTab=new WeakMap,_getFormHelpers=new WeakSet,getFormHelpers_fn=__name2(async function(rule){const valueTemplate=await getTemplate("systems/pf2e/templates/items/rules/partials/resolvable-value.hbs"),bracketsTemplate=await getTemplate("systems/pf2e/templates/items/rules/partials/resolvable-brackets.hbs"),dropZoneTemplate=await getTemplate("systems/pf2e/templates/items/rules/partials/drop-zone.hbs"),getResolvableData=__name2(property=>{const value=getProperty(rule,property),mode=isBracketedValue(value)?"brackets":isObject(value)?"object":"primitive";return{value,mode,property,path:`${this.basePath}.${property}`}},"getResolvableData");return{resolvableValue:(property,options={})=>valueTemplate({...getResolvableData(property),inputId:`${this.fieldIdPrefix}${property}`,fileInput:options.hash?.fileInput??!1}),resolvableAddBracket:property=>getResolvableData(property).mode!=="brackets"?"":createHTMLElement("a",{children:[fontAwesomeIcon("plus",{fixedWidth:!0})],dataset:{action:"add-bracket",property}}).outerHTML,resolvableBrackets:property=>bracketsTemplate(getResolvableData(property)),dropZone:(dropId,dropText,dropTooltip)=>dropZoneTemplate({dropId,dropText,dropTooltip})}},"#getFormHelpers"),__name2(_RuleElementForm,"RuleElementForm");let RuleElementForm=_RuleElementForm;function cleanDataUsingSchema(schema,data){const{fields:fields2}=foundry.data,deleteIfInitial=__name2((key,field)=>{if(data[key]===void 0)return!0;const initialValue=typeof field.initial=="function"?field.initial():field.initial,valueRaw=data[key],value=isObject$1(valueRaw)&&isObject$1(initialValue)?{...initialValue,...valueRaw}:valueRaw;return equals(initialValue,value)&&delete data[key],!(key in data)},"deleteIfInitial");for(const[key,field]of Object.entries(schema))if(!deleteIfInitial(key,field)){if(field instanceof ResolvableValueField){data[key]=field.clean(data[key]),deleteIfInitial(key,field);continue}if("fields"in field){const value=data[key];if(isObject$1(value)){cleanDataUsingSchema(field.fields,value),deleteIfInitial(key,field);continue}}if(field instanceof fields2.ArrayField&&field.element instanceof fields2.SchemaField){const value=data[key];if(Array.isArray(value)){for(const data2 of value)isObject$1(data2)&&(data2.predicate&&cleanPredicate(data2),cleanDataUsingSchema(field.element.fields,data2));continue}}field instanceof fields2.StringField&&(data[key]=field.clean(data[key],{}),deleteIfInitial(key,field))}}__name(cleanDataUsingSchema,"cleanDataUsingSchema"),__name2(cleanDataUsingSchema,"cleanDataUsingSchema");function cleanPredicate(source){const predicateValue=source.predicate;if(typeof predicateValue=="string")if(predicateValue.trim()==="")delete source.predicate;else try{source.predicate=JSON.parse(predicateValue)}catch(error){if(error instanceof Error)throw ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.RuleElementSyntax",{message:error.message})),error}}__name(cleanPredicate,"cleanPredicate"),__name2(cleanPredicate,"cleanPredicate");const _AuraForm=class extends RuleElementForm{static{__name(this,"_AuraForm")}constructor(){super(...arguments),__privateAdd(this,_addEffect),__privateAdd(this,_updateEffectsMap),__privateAdd(this,_deleteEffect),__publicField(this,"template","systems/pf2e/templates/items/rules/aura.hbs"),__publicField(this,"tabs",{names:["basic","effects","appearance"],displayStyle:"grid"}),__privateAdd(this,_effectsMap,new Map)}get effectsArray(){return[...__privateGet(this,_effectsMap).values()]}getInitialValue(){return __privateGet(this,_effectsMap).clear(),__privateSet(this,_effectsMap,new Map(this.object.effects.map((e,index)=>[index,deepClone(e)]))),super.getInitialValue()}activateListeners(html){super.activateListeners(html);const traitsElement=htmlQuery(html,".tagify-traits");if(traitsElement){const whitelist={...CONFIG.PF2E.spellTraits,...CONFIG.PF2E.actionTraits};tagify$1(traitsElement,{whitelist,enforceWhitelist:!1})}for(const eventsElement of htmlQueryAll(html,".tagify-events")){const whitelist=[["enter",game.i18n.localize("PF2E.RuleEditor.Aura.Effects.EventsOptions.Enter")],["turn-start",game.i18n.localize("PF2E.RuleEditor.Aura.Effects.EventsOptions.TurnStart")],["turn-end",game.i18n.localize("PF2E.RuleEditor.Aura.Effects.EventsOptions.TurnEnd")]].sort((a,b)=>a[1].localeCompare(b[1],game.i18n.lang));tagify$1(eventsElement,{whitelist:mapToObj(whitelist,w=>[w[0],w[1]]),enforceWhitelist:!0})}for(const element of htmlQueryAll(html,"a[data-action=remove-effect]"))element.addEventListener("click",()=>{__privateMethod(this,_deleteEffect,deleteEffect_fn).call(this,element.dataset.effectId)});for(const button of htmlQueryAll(html,"div[data-rule-tab=effects] button[data-action=toggle-brackets]")){const fieldset=htmlClosest(button,"fieldset"),select=htmlQuery(fieldset,"select"),input=htmlQuery(fieldset,"input");select&&input&&!select.value&&(button.disabled=!0,input.disabled=!0)}for(const key of["border","highlight"]){const inputName=`system.rules.${this.index}.appearance.${key}.color`,textInput=htmlQuery(html,`input[type=text][name="${inputName}"]`),colorInput=htmlQuery(html,`input[type=color][data-edit="${inputName}"]`),checkbox=htmlQuery(html,`input[type=checkbox][name="${inputName}"]`);textInput&&colorInput&&checkbox&&(this.object.appearance[key]?.color==="user-color"?(textInput.removeAttribute("name"),textInput.disabled=!0,colorInput.disabled=!0):checkbox.removeAttribute("name"),checkbox.addEventListener("change",()=>{checkbox.checked?(checkbox.name=textInput.name,textInput.removeAttribute("name"),textInput.disabled=!0,colorInput.disabled=!0,textInput.value=colorInput.value=userColorForActor(this.object.actor)):(textInput.name=checkbox.name,checkbox.removeAttribute("name"),textInput.disabled=!1,colorInput.disabled=!1,textInput.value=colorInput.value="#000000")}))}const translationX=htmlQuery(html,"input[data-translation=x]"),translationY=htmlQuery(html,"input[data-translation=y]");translationX&&translationY&&(translationX.addEventListener("change",()=>{translationX.value!==""&&translationY.value===""&&(translationY.value=translationX.value)}),translationY.addEventListener("change",()=>{translationY.value!==""&&translationX.value===""&&(translationX.value=translationY.value)}))}async getData(){const{border,highlight}=this.object.appearance,userColor=userColorForActor(this.object.actor);return{...await super.getData(),affectsOptions:{all:"PF2E.RuleEditor.Aura.Effects.AffectsOptions.All",allies:"PF2E.RuleEditor.Aura.Effects.AffectsOptions.Allies",enemies:"PF2E.RuleEditor.Aura.Effects.AffectsOptions.Enemies"},effects:this.effectsArray.map(e=>({...e,item:fromUuidSync(e.uuid)})),borderColor:border?.color==="user-color"?userColor:border?.color??null,highlightColor:highlight.color==="user-color"?userColor:highlight?.color,saveTypes:CONFIG.PF2E.saves,isImageFile:isImageFilePath(this.rule.appearance?.texture?.src)}}async onDrop(event,element){const{id}=element.dataset;if(id!=="aura-effect-drop")return null;const item=await super.onDrop(event,element);return!item?.isOfType("effect")||!this.schema?null:(__privateMethod(this,_addEffect,addEffect_fn).call(this,item.uuid),item)}async updateItem(updates){const expanded=expandObject(updates);return expanded.effects&&(expanded.effects=__privateMethod(this,_updateEffectsMap,updateEffectsMap_fn).call(this,expanded)),super.updateItem(expanded)}updateObject(source){source.effects=__privateMethod(this,_updateEffectsMap,updateEffectsMap_fn).call(this,source);for(const key of["level","radius"]){if(key in source&&!source[key]){delete source[key];continue}const stringValue=source[key],maybeIntegerValue=typeof stringValue=="string"&&/^\d+$/.test(stringValue)?Number(stringValue):NaN;Number.isInteger(maybeIntegerValue)&&(source[key]=maybeIntegerValue)}const appearance=source.appearance;appearance?.border?.alpha===0&&(appearance.border=null),appearance?.border?.color===null&&(appearance.border.color="#000000"),appearance?.highlight?.color===null&&(appearance.highlight.color="#000000");const texture=appearance?.texture;if(texture){if(texture.translation){const{x,y}=texture.translation;!x&&!y&&(texture.translation=null)}texture.src?isImageFilePath(texture.src)&&(texture.loop=!0,texture.playbackRate=1):appearance.texture=null}super.updateObject(source)}};_effectsMap=new WeakMap,_addEffect=new WeakSet,addEffect_fn=__name2(function(uuid){const index=__privateGet(this,_effectsMap).size+1;__privateGet(this,_effectsMap).set(index,{uuid}),this.updateItem({effects:this.effectsArray})},"#addEffect"),_updateEffectsMap=new WeakSet,updateEffectsMap_fn=__name2(function(source){return __privateSet(this,_effectsMap,new Map(Object.values(source.effects??{}).map((data,index)=>{const updatedData=deepClone(data),deletions={};if(updatedData.save&&(updatedData.save.type??data.save?.type?updatedData.save.dc||=null:deletions["-=save"]=null),updatedData.affects!=="enemies"&&updatedData.includesSelf&&(deletions["-=includesSelf"]=null),updatedData.removeOnExit&&(deletions["-=removeOnExit"]=null),updatedData.predicate)try{const parsed=JSON.parse(String(updatedData.predicate));updatedData.predicate=Array.isArray(parsed)?parsed:[]}catch{deletions["-=predicate"]=null}else deletions["-=predicate"]=null;return[index,mergeObject(updatedData,deletions,{performDeletions:!0})]}))),this.effectsArray},"#updateEffectsMap"),_deleteEffect=new WeakSet,deleteEffect_fn=__name2(function(id){const index=Number(id);Number.isNaN(index)||__privateGet(this,_effectsMap).delete(index)&&this.updateItem({effects:this.effectsArray})},"#deleteEffect"),__name2(_AuraForm,"AuraForm");let AuraForm=_AuraForm;const _FastHealingForm=class extends RuleElementForm{static{__name(this,"_FastHealingForm")}template="systems/pf2e/templates/items/rules/fast-healing.hbs";activateListeners(html){super.activateListeners(html);const selectorElement=htmlQuery(html,".deactivated-by");if(selectorElement){const whitelist=CONFIG.PF2E.weaknessTypes;tagify$1(selectorElement,{whitelist,enforceWhitelist:!1})}}async getData(){return{...await super.getData(),types:{"fast-healing":"PF2E.Encounter.Broadcast.FastHealing.fast-healing.Name",regeneration:"PF2E.Encounter.Broadcast.FastHealing.regeneration.Name"}}}updateObject(source){delete source[source.type==="regeneration"?"details":"deactivatedBy"],super.updateObject(source)}};__name2(_FastHealingForm,"FastHealingForm");let FastHealingForm=_FastHealingForm;const _FlatModifierForm=class extends RuleElementForm{static{__name(this,"_FlatModifierForm")}template="systems/pf2e/templates/items/rules/flat-modifier.hbs";get isDamage(){return[this.rule.selector??[]].flat().some(s=>s==="damage"||String(s).endsWith("-damage"))}activateListeners(html){super.activateListeners(html),htmlQuery(html,"[data-action=toggle-selector]")?.addEventListener("click",()=>{const selector=this.rule.selector,newValue=Array.isArray(selector)?selector.at(0)??"":[selector??""].filter(s=>!!s);this.updateItem({selector:newValue})})}async getData(){const data=await super.getData(),types=(()=>{const abpEnabled=AutomaticBonusProgression.isEnabled(null),entries=Array.from(MODIFIER_TYPES).filter(t=>abpEnabled||t!=="potency").map(t=>[t,game.i18n.localize(`PF2E.ModifierType.${t}`)]).sort((a,b)=>a[0]==="untyped"?-1:b[0]==="untyped"?1:a[1].localeCompare(b[1]));return fromPairs(entries)})();return{...data,selectorIsArray:Array.isArray(this.rule.selector),abilities:CONFIG.PF2E.abilities,types,damageCategories:pick$1(CONFIG.PF2E.damageCategories,Array.from(DAMAGE_CATEGORIES_UNIQUE)),isDamage:this.isDamage}}updateObject(formData){delete formData[formData.type==="ability"?"value":"ability"],formData.critical=tupleHasValue([!1,"false"],formData.critical)?!1:!!formData.critical||null,this.isDamage||(delete formData.damageCategory,delete formData.damageType,delete formData.critical),super.updateObject(formData)}};__name2(_FlatModifierForm,"FlatModifierForm");let FlatModifierForm=_FlatModifierForm;const _GrantItemForm=class extends RuleElementForm{static{__name(this,"_GrantItemForm")}template="systems/pf2e/templates/items/rules/grant-item.hbs";async getData(){const data=await super.getData(),uuid=this.rule.uuid?String(this.rule.uuid):null,granted=uuid?await fromUuid(uuid):null;return{...data,granted}}updateObject(ruleData){super.updateObject(ruleData),typeof ruleData.uuid=="string"&&(ruleData.uuid=ruleData.uuid.trim())}};__name2(_GrantItemForm,"GrantItemForm");let GrantItemForm=_GrantItemForm;const _MultipleAttackPenaltyForm=class extends RuleElementForm{static{__name(this,"_MultipleAttackPenaltyForm")}template="systems/pf2e/templates/items/rules/multiple-attack-penalty.hbs"};__name2(_MultipleAttackPenaltyForm,"MultipleAttackPenaltyForm");let MultipleAttackPenaltyForm=_MultipleAttackPenaltyForm;const _RollNoteForm=class extends RuleElementForm{static{__name(this,"_RollNoteForm")}html=null;template="systems/pf2e/templates/items/rules/note.hbs";async getData(){return{...await super.getData(),selectorIsArray:Array.isArray(this.rule.selector)}}activateListeners(html){super.activateListeners(html),this.html=html,htmlQuery(html,"[data-action=toggle-selector]")?.addEventListener("click",()=>{const selector=this.rule.selector,newValue=Array.isArray(selector)?selector.at(0)??"":[selector??""].filter(s=>!!s);this.updateItem({selector:newValue})});const optionsEl=htmlQuery(html,".outcomes");tagify$1(optionsEl,{whitelist:[...DEGREE_OF_SUCCESS_STRINGS],maxTags:3})}updateObject(ruleData){super.updateObject(ruleData);const{html}=this;if(html){const shouldBeHidden=htmlQuery(html,".hidden-value")?.checked,isHidden=["gm","owner"].includes(String(ruleData.visibility));shouldBeHidden!==isHidden&&(shouldBeHidden?ruleData.visibility="owner":delete ruleData.visibility)}Array.isArray(ruleData.outcome)&&ruleData.outcome.length===0&&delete ruleData.outcome,typeof ruleData.title=="string"&&(ruleData.title=ruleData.title.trim())}};__name2(_RollNoteForm,"RollNoteForm");let RollNoteForm=_RollNoteForm;const _TokenImageForm=class extends RuleElementForm{static{__name(this,"_TokenImageForm")}template="systems/pf2e/templates/items/rules/token-image.hbs";async getData(){return{...await super.getData(),scaleEnabled:this.object.scale!==null}}activateListeners(html){super.activateListeners(html);const tintInput=htmlQuery(html,`input[name="system.rules.${this.index}.tint"]`),scaleCheckbox=htmlQuery(html,"input[data-action=toggle-scale]"),scaleInput=htmlQuery(html,`input[name="system.rules.${this.index}.scale"]`);tintInput&&scaleCheckbox&&scaleInput&&(tintInput.id=`${this.fieldIdPrefix}-tint`,scaleInput.id=`${this.fieldIdPrefix}-scale`,scaleInput.disabled=this.object.scale===null,scaleCheckbox.addEventListener("change",event=>{event.stopPropagation();const newValue=this.object.scale===null?1:null;this.updateItem({scale:newValue})}))}};__name2(_TokenImageForm,"TokenImageForm");let TokenImageForm=_TokenImageForm;const _TokenLightForm=class extends RuleElementForm{static{__name(this,"_TokenLightForm")}template="systems/pf2e/templates/items/rules/token-light.hbs";tabs={names:["basic","animation","advanced"],displayStyle:"grid"};async getData(){const data=await super.getData();return{...data,colorationTechniques:AdaptiveLightingShader.SHADER_TECHNIQUES,light:data.rule.value,lightAnimations:mapValues$1(CONFIG.Canvas.lightAnimations,value=>value.label)}}};__name2(_TokenLightForm,"TokenLightForm");let TokenLightForm=_TokenLightForm;const RULE_ELEMENT_FORMS={Aura:AuraForm,FastHealing:FastHealingForm,FlatModifier:FlatModifierForm,GrantItem:GrantItemForm,MultipleAttackPenalty:MultipleAttackPenaltyForm,Note:RollNoteForm,TokenImage:TokenImageForm,TokenLight:TokenLightForm},_ItemSheetPF2e=class extends ItemSheet{static{__name(this,"_ItemSheetPF2e")}constructor(){super(...arguments),__privateAdd(this,_createRuleElementForms),__privateAdd(this,_selectedRuleElementType,Object.keys(RuleElements.all).at(0)??null),__privateAdd(this,_editingRuleElementIndex,null),__privateAdd(this,_rulesLastScrollTop,null),__privateAdd(this,_ruleElementForms,[])}static get defaultOptions(){const options=super.defaultOptions;return options.width=695,options.height=460,options.classes=options.classes.concat(["pf2e","item"]),options.template="systems/pf2e/templates/items/sheet.hbs",options.scrollY=[".tab.active",".inventory-details","div[data-rule-tab]"],options.tabs=[{navSelector:".tabs",contentSelector:".sheet-body",initial:"description"},{navSelector:".mystify-nav",contentSelector:".mystify-sheet",initial:"unidentified"}],options}get editingRuleElement(){return __privateGet(this,_editingRuleElementIndex)===null?null:this.item.toObject().system.rules[__privateGet(this,_editingRuleElementIndex)]??null}get validTraits(){return objectHasKey(CONFIG.PF2E.Item.traits,this.item.type)?CONFIG.PF2E.Item.traits[this.item.type]:null}async getData(options={}){options.id=this.id,options.classes?.push(this.item.type),options.editable=this.isEditable,options.sheetConfig&&=Object.values(CONFIG.Item.sheetClasses[this.item.type]).filter(c=>c.canConfigure).length>1;const{item}=this;__privateMethod(this,_createRuleElementForms,createRuleElementForms_fn).call(this);const enrichedContent={},rollData={...this.item.getRollData(),...this.actor?.getRollData()};enrichedContent.description=await TextEditor.enrichHTML(item._source.system.description.value,{rollData,async:!0}),enrichedContent.gmNotes=await TextEditor.enrichHTML(item.system.description.gm.trim(),{rollData,async:!0});const validTraits=this.validTraits,hasRarity=!item.isOfType("action","condition","deity","effect","lore","melee"),itemTraits=item.system.traits?.value??[],sourceTraits=item._source.system.traits?.value??[],traits=validTraits?createSheetTags(validTraits,itemTraits):null,traitTagifyData=validTraits?createTagifyTraits(itemTraits,{sourceTraits,record:validTraits}):null;return{itemType:null,showTraits:this.validTraits!==null,hasSidebar:this.item.isOfType("condition","lore"),sidebarTitle:game.i18n.format("PF2E.Item.SidebarSummary",{type:game.i18n.localize(`TYPES.Item.${this.item.type}`)}),sidebarTemplate:`systems/pf2e/templates/items/${sluggify(item.type)}-sidebar.hbs`,detailsTemplate:`systems/pf2e/templates/items/${sluggify(item.type)}-details.hbs`,cssClass:this.isEditable?"editable":"locked",editable:this.isEditable,document:item,item,isPhysical:!1,data:item.system,fieldIdPrefix:`field-${this.appId}-`,enrichedContent,limited:this.item.limited,options:this.options,owner:this.item.isOwner,title:this.title,user:{isGM:game.user.isGM},rarity:hasRarity?this.item.system.traits?.rarity??"common":null,rarities:CONFIG.PF2E.rarityTraits,traits,traitTagifyData,enabledRulesUI:game.user.isGM||game.settings.get("pf2e","enabledRulesUI"),ruleEditing:!!this.editingRuleElement,rules:{selection:{selected:__privateGet(this,_selectedRuleElementType),types:sortStringRecord(Object.keys(RuleElements.all).reduce((result,key)=>mergeObject(result,{[key]:`PF2E.RuleElement.${key}`}),{}))},elements:await Promise.all(__privateGet(this,_ruleElementForms).map(async form=>({template:await form.render()})))},proficiencies:CONFIG.PF2E.proficiencyLevels}}onTagSelector(anchor){if((anchor.dataset.tagSelector??"")!=="basic")throw ErrorPF2e("Item sheets can only use the basic tag selector");const propertyIsFlat=anchor.dataset.flat==="true",objectProperty=anchor.dataset.property??"",title=anchor.dataset.title,configTypes=(anchor.dataset.configTypes??"").split(",").map(type=>type.trim()).filter(tag=>tupleHasValue(SELECTABLE_TAG_FIELDS,tag)),selectorOptions={objectProperty,configTypes,title,flat:propertyIsFlat};anchor.dataset.noCustom==="true"?selectorOptions.allowCustom=!1:this.actor&&configTypes.includes("attackEffects")&&(selectorOptions.customChoices=this.getAttackEffectOptions()),new TagSelectorBasic(this.item,selectorOptions).render(!0)}getAttackEffectOptions(){return(this.actor?.items.contents??[]).filter(i=>i.isOfType("action","consumable")).reduce((options,item)=>{const key=item.slug??sluggify(item.name);return{...options,[key]:item.name}},deepClone(CONFIG.PF2E.attackEffects))}async activateEditor(name2,options={},initialContent){const sourceContent=name2==="system.description.value"?this.item._source.system.description.value:initialContent,mutuallyExclusive=["system.description.gm","system.description.value"];if(mutuallyExclusive.includes(name2)){const html=this.element[0];for(const elementName of mutuallyExclusive.filter(n=>n!==name2)){const element=htmlQuery(html,`[data-edit="${elementName}"]`),section=htmlClosest(element,".editor-container");section&&(section.style.display="none")}htmlQuery(html,".tab.description")?.classList.add("editing")}return super.activateEditor(name2,options,sourceContent)}async close(options){return __privateSet(this,_editingRuleElementIndex,null),super.close(options)}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const anchor of htmlQueryAll(html,"a.tag-selector"))anchor.addEventListener("click",()=>this.onTagSelector(anchor));const rulesPanel=htmlQuery(html,".tab[data-tab=rules]"),slugInput=htmlQuery(rulesPanel,'input[name="system.slug"]');slugInput&&(slugInput.addEventListener("change",()=>{slugInput.value=sluggify(slugInput.value)}),htmlQuery(rulesPanel,"a[data-action=regenerate-slug]")?.addEventListener("click",()=>{if(this._submitting)return;slugInput.value=sluggify(this.item.name);const event=new Event("change");slugInput.dispatchEvent(event)}));const ruleElementSelect=htmlQuery(rulesPanel,"select[data-action=select-rule-element]");ruleElementSelect?.addEventListener("change",()=>{__privateSet(this,_selectedRuleElementType,ruleElementSelect.value)});for(const anchor of htmlQueryAll(rulesPanel,"a.add-rule-element"))anchor.addEventListener("click",async event=>{await this._onSubmit(event);const rulesData=this.item.toObject().system.rules,key=__privateGet(this,_selectedRuleElementType)??"NewRuleElement";this.item.update({"system.rules":rulesData.concat({key})})});for(const anchor of htmlQueryAll(rulesPanel,"a.edit-rule-element"))anchor.addEventListener("click",async()=>{if(this._submitting)return;const index=Number(anchor.dataset.ruleIndex??"NaN")??null;__privateSet(this,_editingRuleElementIndex,index),__privateSet(this,_rulesLastScrollTop,rulesPanel?.scrollTop??null),this.render()});for(const anchor of htmlQueryAll(rulesPanel,".rules a.remove-rule-element"))anchor.addEventListener("click",async event=>{await this._onSubmit(event);const rules2=this.item.toObject().system.rules,index=Number(anchor.dataset.ruleIndex??"NaN");rules2&&Number.isInteger(index)&&rules2.length>index&&(rules2.splice(index,1),this.item.update({"system.rules":rules2}))});for(const anchor of htmlQueryAll(rulesPanel,"a[data-clipboard]"))anchor.addEventListener("click",()=>{const clipText=anchor.dataset.clipboard;clipText&&(game.clipboard.copyPlainText(clipText),ui.notifications.info(game.i18n.format("PF2E.ClipboardNotification",{clipText})))});const editingRuleElement=this.editingRuleElement;if(editingRuleElement){const ruleText=JSON.stringify(editingRuleElement,null,2),schema=RuleElements.all[String(editingRuleElement.key)]?.schema.fields,view=new CodeMirror.EditorView({doc:ruleText,extensions:[CodeMirror.basicSetup,CodeMirror.keybindings,...CodeMirror.ruleElementExtensions({schema})]});html.querySelector(".rule-editing .editor-placeholder")?.replaceWith(view.dom);const closeBtn=html.querySelector(".rule-editing button[data-action=close]");closeBtn?.addEventListener("click",()=>{__privateSet(this,_editingRuleElementIndex,null),this.render()}),closeBtn?.removeAttribute("disabled"),html.querySelector(".rule-editing button[data-action=apply]")?.addEventListener("click",()=>{const value=view.state.doc.toString();if(__privateGet(this,_editingRuleElementIndex)===null){__privateSet(this,_editingRuleElementIndex,null),this.render();return}try{const rules2=this.item.toObject().system.rules;rules2[__privateGet(this,_editingRuleElementIndex)]=JSON.parse(value),__privateSet(this,_editingRuleElementIndex,null),this.item.update({"system.rules":rules2})}catch(error){if(error instanceof Error)throw ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.RuleElementSyntax",{message:error.message})),console.warn("Syntax error in rule element definition.",error.message,value),error}})}const ruleSections=html.querySelectorAll(".rules .rule-form");for(const ruleSection of Array.from(ruleSections)){const idx=ruleSection.dataset.idx?Number(ruleSection.dataset.idx):NaN;__privateGet(this,_ruleElementForms).at(idx)?.activateListeners(ruleSection)}InlineRollLinks.listen(html,this.item);const{validTraits}=this,tagElement=html.querySelector(".sheet-header .tags"),traitsPrepend=html.querySelector(".traits-extra");if(validTraits!==null&&tagElement instanceof HTMLInputElement){const tags=tagify$1(tagElement,{whitelist:validTraits});traitsPrepend&&tags.DOM.scope.prepend(traitsPrepend.content)}else tagElement&&traitsPrepend&&tagElement.append(traitsPrepend.content);const modifiedPropertyFields=htmlQueryAll(html,"[data-property]");for(const input of modifiedPropertyFields){const propertyPath=input.dataset.property??"",baseValue=input.dataset.valueBase??String(getProperty(this.item._source,propertyPath)??"").trim();input.addEventListener("focus",()=>{input.dataset.value=input.value,input.value=baseValue,input.name=propertyPath}),input.addEventListener("blur",()=>{input.removeAttribute("name"),input.value===baseValue&&(input.value=input.dataset.value??"")})}htmlQuery(html,".add-skill-variant")?.addEventListener("click",()=>{if(!this.item.isOfType("lore"))return;const variants=this.item.system.variants??{},index=Object.keys(variants).length;this.item.update({[`system.variants.${index}`]:{label:"+X in terrain",options:""}})});for(const button of htmlQueryAll(html,".skill-variants .remove-skill-variant"))button.addEventListener("click",event=>{if(!(event.currentTarget instanceof HTMLElement))return;const index=event.currentTarget.dataset.skillVariantIndex;this.item.update({[`system.variants.-=${index}`]:null})});for(const infoCircle of htmlQueryAll(html,"i.fa-info-circle[title]"))infoCircle.classList.contains("small")?$(infoCircle).tooltipster({maxWidth:275,position:"right",theme:"crb-hover",contentAsHTML:!0}):infoCircle.classList.contains("large")&&$(infoCircle).tooltipster({maxWidth:400,theme:"crb-hover",contentAsHTML:!0});if(this.isEditable&&game.user.isGM&&!this.item.system.description.gm&&!(this.item.isOfType("spell")&&this.item.isVariant)){const descriptionEditors=htmlQuery(html,".tab[data-tab=description]"),mainEditor=htmlQuery(descriptionEditors,".main .editor");if(!mainEditor)throw ErrorPF2e("Unexpected error retrieving description editor");const addGMNotesLink=document.createElement("a");addGMNotesLink.className=addGMNotesLink.dataset.action="add-gm-notes",addGMNotesLink.innerHTML=fontAwesomeIcon("fa-note-medical",{style:"regular"}).outerHTML,addGMNotesLink.dataset.tooltip="PF2E.Item.GMNotes.Add",mainEditor.prepend(addGMNotesLink),addGMNotesLink.addEventListener("click",()=>{htmlQuery(descriptionEditors,".gm-notes")?.classList.add("has-content"),this.activateEditor("system.description.gm")})}const rules=htmlQuery(html,".rule-element-forms");rules&&Sortable.create(rules,{...SORTABLE_DEFAULTS,handle:".drag-handle",onEnd:event=>{const currentIndex=event.oldDraggableIndex,newIndex=event.newDraggableIndex;if(currentIndex===void 0||newIndex===void 0){this.render();return}const rules2=this.item.toObject().system.rules,movingRule=rules2.at(currentIndex);movingRule&&newIndex<=rules2.length?(rules2.splice(currentIndex,1),rules2.splice(newIndex,0,movingRule),this.item.update({"system.rules":rules2})):this.render()}})}_getSubmitData(updateData=null){const fd=new FormDataExtended(this.form,{editors:this.editors}),data=updateData?mergeObject(fd.object,updateData):expandObject(fd.object),flattenedData=flattenObject(data);return processTagifyInSubmitData(this.form,flattenedData),flattenedData}_getHeaderButtons(){const buttons=super._getHeaderButtons();return game.settings.get("pf2e","dataTools")&&this.isEditable&&this.item.sourceId?.startsWith("Compendium.")&&buttons.unshift({label:"Refresh",class:"refresh-from-compendium",icon:"fa-solid fa-sync-alt",onclick:()=>this.item.refreshFromCompendium()}),buttons}_canDragDrop(_selector){return this.item.isOwner}async _onSubmit(event,{updateData=null,preventClose=!1,preventRender=!1}={}){return $(this.form).find("tags ~ input").each((_i,input)=>{input.value===""&&(input.value="[]")}),super._onSubmit(event,{updateData,preventClose,preventRender})}async _updateObject(event,formData){const expanded=expandObject(formData),form=htmlClosest(event.target,".rule-form[data-idx]");if(form){const idx=Number(form.dataset.idx),ruleForm=__privateGet(this,_ruleElementForms)[idx],itemRules=this.item.toObject().system.rules;if(idx>=itemRules.length||!ruleForm)throw ErrorPF2e(`Invalid rule form update, no rule form available at index ${idx}`);const incomingData=expanded.system?.rules?.[idx];incomingData&&(ruleForm.updateObject(incomingData),itemRules[idx]=ruleForm.rule,this.item.update({"system.rules":itemRules}))}return delete expanded.system?.rules,super._updateObject(event,flattenObject(expanded))}async _render(force,options){if(await maintainFocusInRender(this,()=>super._render(force,options)),__privateGet(this,_editingRuleElementIndex)===null&&__privateGet(this,_rulesLastScrollTop)){const html=this.element[0],rulesTab=htmlQuery(html,".tab[data-tab=rules]");rulesTab&&(rulesTab.scrollTop=__privateGet(this,_rulesLastScrollTop)),__privateSet(this,_rulesLastScrollTop,null)}}};_selectedRuleElementType=new WeakMap,_editingRuleElementIndex=new WeakMap,_rulesLastScrollTop=new WeakMap,_ruleElementForms=new WeakMap,_createRuleElementForms=new WeakSet,createRuleElementForms_fn=__name2(function(){const rules=this.item.toObject().system.rules,previousForms=[...__privateGet(this,_ruleElementForms)],processedRules=rules.map((rule,index)=>{const options={sheet:this,index,rule,object:this.item.rules.find(r=>r.sourceIndex===index)??null},FormClass=RULE_ELEMENT_FORMS[String(rule.key)]??RuleElementForm,existing=previousForms.find(f=>equals(f.rule,rule)&&f.constructor.name===FormClass.name)??null;return existing&&previousForms.splice(previousForms.indexOf(existing),1),{options,FormClass,existing}});for(const rule of processedRules.filter(p=>!p.existing)){const existing=__privateGet(this,_ruleElementForms)[rule.options.index];existing instanceof rule.FormClass&&(rule.existing=existing)}__privateSet(this,_ruleElementForms,processedRules.map(processed=>processed.existing?(processed.existing.initialize(processed.options),processed.existing):new processed.FormClass(processed.options)))},"#createRuleElementForms"),__name2(_ItemSheetPF2e,"ItemSheetPF2e");let ItemSheetPF2e=_ItemSheetPF2e;const _SettingsMenuPF2e=class extends FormApplication{static{__name(this,"_SettingsMenuPF2e")}cache={};static get defaultOptions(){const options=super.defaultOptions;return options.classes.push("settings-menu","sheet"),mergeObject(options,{title:`PF2E.SETTINGS.${this.namespace.titleCase()}.Name`,id:`${this.namespace}-settings`,template:"systems/pf2e/templates/system/settings/menu.hbs",width:550,height:"auto",tabs:[{navSelector:".sheet-tabs",contentSelector:"form"}],closeOnSubmit:!1,submitOnChange:!0})}static get prefix(){return`${this.namespace}.`}get namespace(){return this.constructor.namespace}get prefix(){return this.constructor.prefix}static get settings(){return{}}static registerSettings(){const settings=this.settings;for(const setting of this.SETTINGS)game.settings.register("pf2e",`${this.prefix}${setting}`,{...settings[setting],scope:"world",config:!1})}async getData(){const settings=this.constructor.settings,templateData=settingsToSheetData(settings,this.cache,this.prefix);return mergeObject(await super.getData(),{settings:templateData,instructions:`PF2E.SETTINGS.${this.namespace.titleCase()}.Hint`})}activateListeners($html){super.activateListeners($html);const html=$html[0],{highlightSetting}=this.options;if(highlightSetting){const formGroup=htmlClosest(htmlQuery(html,`label[for="${highlightSetting}"]`),".form-group");formGroup&&(formGroup.style.animation="glow 0.75s infinite alternate")}}async _updateObject(event,data){for(const key of this.constructor.SETTINGS){const settingKey=`${this.prefix}${key}`,value=data[key];this.cache[key]=value,event.type==="submit"&&await game.settings.set("pf2e",settingKey,value)}event.type==="submit"?this.close():this.render()}_injectHTML($html){super._injectHTML($html);for(const key of this.constructor.SETTINGS){const settingKey=`${this.prefix}${key}`;this.cache[key]=game.settings.get("pf2e",settingKey)}}};__name2(_SettingsMenuPF2e,"SettingsMenuPF2e"),__publicField(_SettingsMenuPF2e,"namespace"),__publicField(_SettingsMenuPF2e,"SETTINGS");let SettingsMenuPF2e=_SettingsMenuPF2e;function settingsToSheetData(settings,cache,prefix=""){return Object.entries(settings).reduce((result,[key,setting])=>{const lookupKey=`${prefix}${key}`,value=key in cache?cache[key]:game.settings.get("pf2e",lookupKey);return cache[key]=value,result[key]={...setting,key,value,isSelect:!!setting.choices,isCheckbox:setting.type===Boolean},result},{})}__name(settingsToSheetData,"settingsToSheetData"),__name2(settingsToSheetData,"settingsToSheetData");function isHomebrewFlagCategory(value){return isObject$1(value)&&Object.entries(value).every(([_hbKey,hbLabel])=>typeof hbLabel=="string"||isObject(hbLabel)&&isLabelAndDescription(hbLabel))}__name(isHomebrewFlagCategory,"isHomebrewFlagCategory"),__name2(isHomebrewFlagCategory,"isHomebrewFlagCategory");function isHomebrewCustomDamage(value){return Object.values(value).every(value2=>isObject(value2)&&typeof value2.label=="string"&&["physical","energy"].includes(value2.category??""))}__name(isHomebrewCustomDamage,"isHomebrewCustomDamage"),__name2(isHomebrewCustomDamage,"isHomebrewCustomDamage");function isLabelAndDescription(obj){return typeof obj.label=="string"&&typeof obj.description=="string"}__name(isLabelAndDescription,"isLabelAndDescription"),__name2(isLabelAndDescription,"isLabelAndDescription");function prepareCleanup(listKey,deletions){var _a;const Migration=(_a=class extends MigrationBase{static{__name(this,"_a")}async updateActor(source){if(source.type==="character"||source.type==="npc")switch(listKey){case"creatureTraits":{const traits=source.system.traits;traits.value=traits.value.filter(t=>!deletions.includes(t));break}case"languages":{const languages=source.system.traits.languages;languages.value=languages.value.filter(l=>!deletions.includes(l));break}case"weaponCategories":{if(source.type==="character"){const attacks=source.system.proficiencies?.attacks??{};for(const key of deletions)attacks[key]&&(delete attacks[key],attacks[`-=${key}`]=null)}break}case"weaponGroups":{if(source.type==="character"){const proficiencyKeys=deletions.map(deletion=>`weapon-group-${deletion}`),attacks=source.system.proficiencies?.attacks??{};for(const key of proficiencyKeys)delete attacks[key],attacks[`-=${key}`]=null}break}case"baseWeapons":{if(source.type==="character"){const proficiencyKeys=deletions.map(deletion=>`weapon-base-${deletion}`),attacks=source.system.proficiencies?.attacks??{};for(const key of proficiencyKeys)delete attacks[key],attacks[`-=${key}`]=null}break}case"weaponTraits":{const weaponsAndAttacks=source.items.filter(i=>["melee","weapon"].includes(i.type));for(const itemSource of weaponsAndAttacks){const traits=itemSource.system.traits.value;for(const deleted of deletions)traits.findSplice(t=>t===deleted)}}}}async updateItem(source){switch(listKey){case"creatureTraits":{if(source.system.traits?.value){const traits=source.system.traits;traits.value=traits.value.filter(t=>!deletions.includes(t))}break}case"featTraits":{if(source.type==="feat"){const traits=source.system.traits;traits.value=traits.value.filter(t=>!deletions.includes(t))}break}case"magicSchools":case"spellTraits":{if(source.type==="spell"){const traits=source.system.traits;traits.value=traits.value.filter(t=>!deletions.includes(t))}break}case"weaponCategories":{if(source.type==="weapon"){const systemData=source.system;systemData.category=deletions.includes(systemData.category??"")?"simple":systemData.category}break}case"weaponGroups":{if(source.type==="weapon"){const systemData=source.system;systemData.group=deletions.includes(systemData.group??"")?null:systemData.group}break}case"baseWeapons":{if(source.type==="weapon"){const base=source.system.baseItem;source.system.baseItem=deletions.includes(base??"")?null:base}break}}}},__name2(_a,"Migration"),__publicField(_a,"version",MigrationRunnerBase.LATEST_SCHEMA_VERSION),_a);return new Migration}__name(prepareCleanup,"prepareCleanup"),__name2(prepareCleanup,"prepareCleanup");const tagify="",_HomebrewElements=class extends SettingsMenuPF2e{static{__name(this,"_HomebrewElements")}constructor(){super(...arguments),__privateAdd(this,_processDeletions),__privateAdd(this,_refreshSettings),__privateAdd(this,_registerModuleTags),__privateAdd(this,_getConfigRecord),__privateAdd(this,_updateConfigRecords),__privateAdd(this,_initialRefresh,!0),__privateAdd(this,_damageManager,new DamageTypeManager)}static get SETTINGS(){return Object.keys(this.settings)}static get defaultOptions(){return mergeObject(super.defaultOptions,{template:"systems/pf2e/templates/system/settings/homebrew.hbs"})}static get traitSettings(){return HOMEBREW_TRAIT_KEYS.reduce((result,key)=>(result[key]={name:CONFIG.PF2E.SETTINGS.homebrew[key].name,hint:CONFIG.PF2E.SETTINGS.homebrew[key].hint,default:[],type:Object},result),{})}static get settings(){return{...this.traitSettings,damageTypes:{name:"PF2E.SETTINGS.Homebrew.DamageTypes.Name",default:[],type:Object}}}activateListeners($form){super.activateListeners($form);const html=$form[0];$form.find("button[name=reset]").on("click",()=>{this.render()});for(const key of HOMEBREW_TRAIT_KEYS){const $input=$form.find(`input[name="${key}"]`);new Tagify($input[0],{editTags:1,hooks:{beforeRemoveTag:tags=>{const localize=localizer("PF2E.SETTINGS.Homebrew.ConfirmDelete"),response=(async()=>{const content=localize("Message",{element:tags[0].data.value});return await Dialog.confirm({title:localize("Title"),content:`

${content}

`})})();return(async()=>await response?Promise.resolve():Promise.reject())()}}})}htmlQuery(html,"[data-action=damage-add]")?.addEventListener("click",async()=>{this.cache.damageTypes.push({label:"Custom",category:"physical",icon:"fa-question"}),this.render()});for(const element of htmlQueryAll(html,"[data-action=damage-delete]"))element.addEventListener("click",async event=>{const idx=htmlClosest(event.target,"[data-idx]")?.dataset.idx;idx&&this.cache.damageTypes.splice(Number(idx),1),this.render()})}async getData(){const data=await super.getData(),traitSettings=settingsToSheetData(this.constructor.traitSettings,this.cache,this.prefix),damageCategories2=pick(CONFIG.PF2E.damageCategories,["physical","energy"]);return{...data,traitSettings,damageCategories:damageCategories2,customDamageTypes:(this.cache.damageTypes??[]).map(customType=>({...customType,slug:`hb_${sluggify(customType.label)}`}))}}async _onSubmit(event,{updateData=null,preventClose=!1,preventRender=!1}={}){return this.form.querySelectorAll("tags ~ input").forEach(input=>{input.value===""&&(input.value="[]")}),super._onSubmit(event,{updateData,preventClose,preventRender})}_getSubmitData(updateData){const original=super._getSubmitData(updateData),data=expandObject(original);if("damageTypes"in data&&data.damageTypes&&typeof data.damageTypes=="object"){data.damageTypes=Object.values(data.damageTypes);for(const type of data.damageTypes){const sanitized=sluggify(type.icon??"");type.icon=sanitized.startsWith("fa-")?sanitized:null}}return data}async _updateObject(event,data){for(const key of HOMEBREW_TRAIT_KEYS)for(const tag of data[key])tag.id??=`hb_${sluggify(tag.value)}`;if(event.type==="submit"){const cleanupTasks=HOMEBREW_TRAIT_KEYS.map(key=>__privateMethod(this,_processDeletions,processDeletions_fn).call(this,key,data[key])).filter(task=>!!task);new MigrationRunner().runMigrations(cleanupTasks),await super._updateObject(event,data),__privateMethod(this,_refreshSettings,refreshSettings_fn).call(this)}else return super._updateObject(event,data)}onInit(){__privateMethod(this,_refreshSettings,refreshSettings_fn).call(this),__privateMethod(this,_registerModuleTags,registerModuleTags_fn).call(this)}};_initialRefresh=new WeakMap,_damageManager=new WeakMap,_processDeletions=new WeakSet,processDeletions_fn=__name2(function(listKey,newTagList){const oldTagList=game.settings.get("pf2e",`homebrew.${listKey}`),newIDList=newTagList.map(tag=>tag.id),deletions=oldTagList.flatMap(oldTag=>newIDList.includes(oldTag.id)?[]:oldTag.id),coreElements=listKey==="baseWeapons"?CONFIG.PF2E.baseWeaponTypes:CONFIG.PF2E[listKey];for(const id of deletions)if(delete coreElements[id],objectHasKey(SECONDARY_TRAIT_RECORDS,listKey))for(const recordKey of SECONDARY_TRAIT_RECORDS[listKey]){const secondaryRecord=CONFIG.PF2E[recordKey];delete secondaryRecord[id]}return game.user.isGM&&deletions.length>0?prepareCleanup(listKey,deletions):null},"#processDeletions"),_refreshSettings=new WeakSet,refreshSettings_fn=__name2(function(){__privateGet(this,_initialRefresh)||__privateGet(this,_damageManager).deleteAllHomebrew();for(const listKey of HOMEBREW_TRAIT_KEYS){const settingsKey=`homebrew.${listKey}`,elements=game.settings.get("pf2e",settingsKey);__privateMethod(this,_updateConfigRecords,updateConfigRecords_fn).call(this,elements,listKey)}const customTypes=game.settings.get("pf2e","homebrew.damageTypes");for(const data of customTypes)__privateGet(this,_damageManager).addCustomDamage(data);const activeModules=[...game.modules.entries()].filter(([_key,foundryModule])=>foundryModule.active);for(const[key,foundryModule]of activeModules){const homebrew=foundryModule.flags?.[key]?.["pf2e-homebrew"];if(isObject(homebrew)&&"damageTypes"in homebrew){const elements=homebrew.damageTypes;if(!isObject(elements)||!isHomebrewCustomDamage(elements)){console.warn(`PF2E System | Homebrew record damageTypes is malformed in module ${key}`);continue}for(const[slug,value]of Object.entries(elements))__privateGet(this,_damageManager).addCustomDamage(value,{slug})}}if(__privateGet(this,_initialRefresh))__privateSet(this,_initialRefresh,!1);else{const sheets=Object.values(ui.windows).filter(app=>app instanceof ActorSheet||app instanceof ItemSheetPF2e);for(const sheet of sheets)sheet.render(!1)}},"#refreshSettings"),_registerModuleTags=new WeakSet,registerModuleTags_fn=__name2(function(){const activeModules=[...game.modules.entries()].filter(([_key,foundryModule])=>foundryModule.active);for(const[key,foundryModule]of activeModules){const homebrew=foundryModule.flags?.[key]?.["pf2e-homebrew"];if(isObject$1(homebrew)){for(const recordKey of Object.keys(homebrew))if(!["damageTypes"].includes(recordKey))if(tupleHasValue(HOMEBREW_TRAIT_KEYS,recordKey)){const elements=homebrew[recordKey];if(!isObject(elements)||!isHomebrewFlagCategory(elements)){console.warn(`PF2E System | Homebrew record ${recordKey} is malformed in module ${key}`);continue}const tags=Object.entries(elements).map(([id,value])=>({id:`hb_${id}`,value:typeof value=="string"?value:value.label}));__privateMethod(this,_updateConfigRecords,updateConfigRecords_fn).call(this,tags,recordKey);for(const[key2,value]of Object.entries(elements))if(typeof value=="object"){const hbKey=`hb_${key2}`;CONFIG.PF2E.traitsDescriptions[hbKey]=value.description}}else{console.warn(`PF2E System | Invalid homebrew record "${recordKey}" in module ${key}`);continue}}}},"#registerModuleTags"),_getConfigRecord=new WeakSet,getConfigRecord_fn=__name2(function(recordKey){return recordKey==="baseWeapons"?CONFIG.PF2E.baseWeaponTypes:CONFIG.PF2E[recordKey]},"#getConfigRecord"),_updateConfigRecords=new WeakSet,updateConfigRecords_fn=__name2(function(elements,listKey){const coreElements=__privateMethod(this,_getConfigRecord,getConfigRecord_fn).call(this,listKey);for(const element of elements)if(coreElements[element.id]=element.value,objectHasKey(SECONDARY_TRAIT_RECORDS,listKey))for(const recordKey of SECONDARY_TRAIT_RECORDS[listKey]){const record=CONFIG.PF2E[recordKey];record[element.id]=element.value}},"#updateConfigRecords"),__name2(_HomebrewElements,"HomebrewElements"),__publicField(_HomebrewElements,"namespace","homebrew");let HomebrewElements=_HomebrewElements;const _DamageTypeManager=class{static{__name(this,"_DamageTypeManager")}collections={physical:PHYSICAL_DAMAGE_TYPES,energy:ENERGY_DAMAGE_TYPES,DAMAGE_TYPES,BASE_DAMAGE_TYPES_TO_CATEGORIES,DAMAGE_TYPE_ICONS,damageTypesLocalization:CONFIG.PF2E.damageTypes,damageRollFlavorsLocalization:CONFIG.PF2E.damageRollFlavors,immunityTypes,weaknessTypes,resistanceTypes};addCustomDamage(data,options={}){const collections=this.collections,slug=`hb_${options.slug??sluggify(data.label)}`;collections.DAMAGE_TYPES.add(slug),collections[tupleHasValue(["physical","energy"],data.category)?data.category:"physical"].push(slug),collections.BASE_DAMAGE_TYPES_TO_CATEGORIES[slug]=data.category,collections.DAMAGE_TYPE_ICONS[slug]=data.icon?.substring(3)??null,collections.damageTypesLocalization[slug]=data.label;const damageFlavor=data.label.toLocaleLowerCase();collections.damageRollFlavorsLocalization[slug]=damageFlavor,collections.immunityTypes[slug]=damageFlavor,collections.weaknessTypes[slug]=damageFlavor,collections.resistanceTypes[slug]=damageFlavor}deleteAllHomebrew(){for(const collection of Object.values(this.collections))if(collection instanceof Set){const hbTraits=[...collection].filter(tag=>tag.startsWith("hb_"));for(const trait of hbTraits)collection.delete(trait)}else{const hbTraits=Object.keys(collection).filter(tag=>tag.startsWith("hb_"));for(const trait of hbTraits)delete collection[trait]}}};__name2(_DamageTypeManager,"DamageTypeManager");let DamageTypeManager=_DamageTypeManager;const _Migration674StableHomebrewTagIDs=class extends MigrationBase{static{__name(this,"_Migration674StableHomebrewTagIDs")}homebrewKeys=deepClone(HOMEBREW_TRAIT_KEYS);homebrewTags=this.homebrewKeys.reduce((settings,key)=>mergeObject(settings,{[key]:game.settings.get("pf2e",`homebrew.${key}`)}),{});updateDocumentTags(documentTags=[]){for(const key of this.homebrewKeys){const homebrewTags=this.homebrewTags[key];for(const tag of homebrewTags){const index=documentTags.indexOf(tag.id);index!==-1&&documentTags.splice(index,1,`hb_${sluggify(tag.value)}`)}}}async updateActor(source){source.type==="familiar"||!source.system.traits?.traits||(this.updateDocumentTags(source.system.traits.traits.value),(source.type==="character"||source.type==="npc")&&this.updateDocumentTags(source.system.traits?.languages.value))}async updateItem(itemSource){this.updateDocumentTags(itemSource.system.traits?.value)}async migrate(){for(const key of this.homebrewKeys){const tags=this.homebrewTags[key];for(const tag of tags){tag.id=`hb_${sluggify(tag.value)}`;const tagMap=key==="baseWeapons"?CONFIG.PF2E.baseWeaponTypes:CONFIG.PF2E[key];tagMap[tag.id]=tag.value,delete tagMap[key]}tags.length>0&&await game.settings.set("pf2e",`homebrew.${key}`,tags)}}};__name2(_Migration674StableHomebrewTagIDs,"Migration674StableHomebrewTagIDs"),__publicField(_Migration674StableHomebrewTagIDs,"version",.674);let Migration674StableHomebrewTagIDs=_Migration674StableHomebrewTagIDs;const _Migration675FlatModifierAEsToREs=class extends MigrationBase{static{__name(this,"_Migration675FlatModifierAEsToREs")}constructor(){super(...arguments),__privateAdd(this,_isFlatModifier),__privateAdd(this,_toRuleElement)}async updateActor(actorSource){for(const effect of[...actorSource.effects])effect.changes.some(change=>change.key.endsWith(".modifiers"))&&actorSource.effects.splice(actorSource.effects.indexOf(effect),1)}async updateItem(itemSource){for(const effect of[...itemSource.effects]){for(const change of effect.changes.filter(change2=>change2.key.endsWith(".modifiers"))){const reData=__privateMethod(this,_toRuleElement,toRuleElement_fn).call(this,change.value);reData&&(effect.changes.splice(effect.changes.indexOf(change),1),itemSource.system.rules.push(reData))}effect.changes.length===0&&itemSource.effects.splice(itemSource.effects.indexOf(effect),1)}}};_isFlatModifier=new WeakSet,isFlatModifier_fn=__name2(function(data){return typeof data=="object"&&data!==null&&__name2(obj=>(typeof obj.modifier=="number"||typeof obj.modifier=="string")&&typeof obj.type=="string","dataIsModifier")(data)},"#isFlatModifier"),_toRuleElement=new WeakSet,toRuleElement_fn=__name2(function(aeValue){const aeModifier=(()=>{try{const parsed=JSON.parse(aeValue);return __privateMethod(this,_isFlatModifier,isFlatModifier_fn).call(this,parsed)?parsed:null}catch(error){return console.warn(error),null}})();return typeof aeModifier?.modifier=="string"&&aeModifier.modifier.replace("@data.","@"),aeModifier&&{key:"FlatModifier",type:aeModifier.type,value:aeModifier.modifier,selector:"hp"}},"#toRuleElement"),__name2(_Migration675FlatModifierAEsToREs,"Migration675FlatModifierAEsToREs"),__publicField(_Migration675FlatModifierAEsToREs,"version",.675);let Migration675FlatModifierAEsToREs=_Migration675FlatModifierAEsToREs;const _Migration676ReplaceItemsWithRELikeAEs=class extends MigrationBase{static{__name(this,"_Migration676ReplaceItemsWithRELikeAEs")}toughnessPromise=fromUuid("Compendium.pf2e.feats-srd.AmP0qu7c5dlBSath");stoutnessPromise=fromUuid("Compendium.pf2e.feats-srd.COP89tjrNhEucuRW");toughPromise=fromUuid("Compendium.pf2e.familiar-abilities.Le8UWr5BU8rV3iBf");replaceItem({items,type,slug,replacement}){if(!(replacement instanceof ItemPF2e))throw ErrorPF2e("Unexpected error retrieving compendium item");const current=items.find(itemSource=>itemSource.type===type&&itemSource.system.slug?.replace(/'/g,"")===slug);if(current){const newSource=replacement.toObject();current.type==="feat"&&newSource.type==="feat"&&(newSource.system.location=current.system.location),items.splice(items.indexOf(current),1,newSource)}}async updateActor(actorSource){actorSource.type==="familiar"?this.replaceItem({items:actorSource.items,type:"effect",slug:"tough",replacement:await this.toughPromise}):actorSource.type==="character"&&(this.replaceItem({items:actorSource.items,type:"feat",slug:"toughness",replacement:await this.toughnessPromise}),this.replaceItem({items:actorSource.items,type:"feat",slug:"mountains-stoutness",replacement:await this.stoutnessPromise}))}};__name2(_Migration676ReplaceItemsWithRELikeAEs,"Migration676ReplaceItemsWithRELikeAEs"),__publicField(_Migration676ReplaceItemsWithRELikeAEs,"version",.676);let Migration676ReplaceItemsWithRELikeAEs=_Migration676ReplaceItemsWithRELikeAEs;const _Migration677RuleValueDataRefs=class extends MigrationBase{static{__name(this,"_Migration677RuleValueDataRefs")}async updateItem(itemSource){for(const rule of itemSource.system.rules)typeof rule.value=="string"&&(rule.value=rule.value.replace("@data.","@"))}};__name2(_Migration677RuleValueDataRefs,"Migration677RuleValueDataRefs"),__publicField(_Migration677RuleValueDataRefs,"version",.677);let Migration677RuleValueDataRefs=_Migration677RuleValueDataRefs;const _Migration678SeparateNPCAttackTraits=class extends MigrationBase{static{__name(this,"_Migration678SeparateNPCAttackTraits")}async updateItem(itemSource){if(itemSource.type==="weapon"){const weaponTraits2=itemSource.system.traits.value,rangeTraits2=weaponTraits2.filter(trait=>/^range(?!d)/.test(trait));for(const trait of rangeTraits2)weaponTraits2.splice(weaponTraits2.indexOf(trait),1);const reloadTraits=weaponTraits2.filter(trait=>trait.startsWith("reload"));for(const trait of reloadTraits)weaponTraits2.splice(weaponTraits2.indexOf(trait),1);itemSource.system.traits.value=[...new Set(weaponTraits2)].sort()}if(!itemSource.system.traits)return;const itemTraits=itemSource.system.traits.value??[];for(const trait of itemTraits)tupleHasValue(RARITIES,trait)&&(itemTraits.splice(itemTraits.indexOf(trait),1),trait!=="common"&&isObject(itemSource.system.traits.rarity)&&itemSource.system.traits.rarity.value==="common"&&(itemSource.system.traits.rarity.value=trait))}};__name2(_Migration678SeparateNPCAttackTraits,"Migration678SeparateNPCAttackTraits"),__publicField(_Migration678SeparateNPCAttackTraits,"version",.678);let Migration678SeparateNPCAttackTraits=_Migration678SeparateNPCAttackTraits;const _Migration679TowerShieldSpeedPenalty=class extends MigrationBase{static{__name(this,"_Migration679TowerShieldSpeedPenalty")}towerShieldSlugs=["darkwood-tower-shield-high-grade","darkwood-tower-shield-standard-grade","tower-shield"];async updateItem(source){if(source.type==="armor"){const systemData=source.system;systemData.speed&&this.towerShieldSlugs.includes(systemData.slug??"")&&(systemData.speed.value=-5),systemData.armor&&(systemData.armor.value=Number(systemData.armor.value)||0),systemData.speed&&(systemData.speed.value=Number(systemData.speed.value)||0);const potencyRune=systemData.potencyRune;potencyRune.value=Number(systemData.potencyRune.value)||0,"resilient"in systemData&&("game"in globalThis?systemData["-=resilient"]=null:delete systemData.resilient)}}};__name2(_Migration679TowerShieldSpeedPenalty,"Migration679TowerShieldSpeedPenalty"),__publicField(_Migration679TowerShieldSpeedPenalty,"version",.679);let Migration679TowerShieldSpeedPenalty=_Migration679TowerShieldSpeedPenalty;const _Migration680SetWeaponHands=class extends MigrationBase{static{__name(this,"_Migration680SetWeaponHands")}oneHandedWeapons=new Set(["repeating-hand-crossbow"]);onePlusHandedWeapons=new Set(["backpack-ballista","backpack-catapult","composite-longbow","composite-shortbow","hongali-hornbow","longbow","shortbow","sun-sling"]);shieldAttachments=new Set(["shield-boss","shield-spikes"]);firearmAttachments=new Set(["bayonette","reinforced-stock"]);wornGloves=new Set(["handwraps-of-mighty-blows"]);twoHandedWeapons=new Set(["adze","alchemical-crossbow","arquebus","axe-musket","bladed-diabolo","bladed-scarf","blunderbuss","bo-staff","boarding-pike","butchering-axe","combat-grapnel","crossbow","double-barreled-musket","dueling-spear","dwarven-scattergun","elven-branched-spear","elven-curve-blade","explosive-dogslicer","falchion","fauchard","fire-lance","flingflenser","flintlock-musket","gill-hook","glaive","gnome-amalgam-musket","greataxe","greatclub","greatpick","greatsword","guisarme","gun-sword","halberd","halfling-sling-staff","hammer-gun","harmona-gun","heavy-crossbow","horsechopper","kusarigama","lance","longspear","maul","meteor-hammer","mithral-tree","naginata","ogre-hook","ranseur","repeating-crossbow","repeating-heavy-crossbow","scythe","shauth-lash","spiked-chain","taw-launcher","three-peaked-tree","thundermace","war-flail","whip-claw"]);isShield(source){return source.type==="armor"&&(source.system.armorType?.value==="shield"||source.system.category==="shield")}async updateItem(itemSource){if(this.isShield(itemSource))itemSource.system.usage.value="held-in-one-hand";else if(itemSource.type==="weapon"){itemSource.system.usage??={value:"held-in-one-hand"};const{baseItem,slug,traits}=itemSource.system,usage=itemSource.system.usage;if(this.twoHandedWeapons.has(baseItem||slug||""))usage.value="held-in-two-hands";else if(this.onePlusHandedWeapons.has(baseItem||slug||""))usage.value="held-in-one-plus-hands";else if(this.oneHandedWeapons.has(baseItem||slug||""))usage.value="held-in-one-hand";else if(this.shieldAttachments.has(baseItem||slug||"")){usage.value="held-in-one-hand";const attachedIndex=traits.value.findIndex(trait=>trait==="attached");attachedIndex!==-1&&traits.value.splice(attachedIndex,1,"attached-to-shield")}else if(this.firearmAttachments.has(baseItem||slug||"")){usage.value="held-in-one-hand";const attachedIndex=traits.value.findIndex(trait=>trait==="attached");attachedIndex!==-1&&traits.value.splice(attachedIndex,1,"attached-to-crossbow-or-firearm")}else this.wornGloves.has(baseItem||slug||"")&&(usage.value="worn-gloves")}}};__name2(_Migration680SetWeaponHands,"Migration680SetWeaponHands"),__publicField(_Migration680SetWeaponHands,"version",.68);let Migration680SetWeaponHands=_Migration680SetWeaponHands;const _Migration681GiantLanguageToJotun=class extends MigrationBase{static{__name(this,"_Migration681GiantLanguageToJotun")}replaceGiant({value}){const giantIndex=value.indexOf("giant");giantIndex!==-1&&value.splice(giantIndex,1,"jotun")}async updateActor(actorSource){(actorSource.type==="character"||actorSource.type==="npc")&&this.replaceGiant(actorSource.system.traits.languages)}async updateItem(itemSource){itemSource.type==="ancestry"&&this.replaceGiant(itemSource.system.additionalLanguages)}};__name2(_Migration681GiantLanguageToJotun,"Migration681GiantLanguageToJotun"),__publicField(_Migration681GiantLanguageToJotun,"version",.681);let Migration681GiantLanguageToJotun=_Migration681GiantLanguageToJotun;const _Migration682BiographyFields=class extends MigrationBase{static{__name(this,"_Migration682BiographyFields")}replaceBiographyData(old){old.details.biography.public?(old.details.biography.appearance=old.details.biography.public,old.details.biography["-=public"]=null):old.details.biography.appearance??="",old.details.biography.value?(old.details.biography.campaignNotes=old.details.biography.value,old.details.biography["-=value"]=null):old.details.biography.campaignNotes??="","game"in globalThis||(delete old.details.biography.public,delete old.details.biography.value),old.details.biography.backstory??="",old.details.biography.birthPlace??="",old.details.biography.attitude??="",old.details.biography.beliefs??="",old.details.biography.likes??="",old.details.biography.dislikes??="",old.details.biography.catchphrases??="",old.details.biography.allies??="",old.details.biography.enemies??="",old.details.biography.organaizations??=""}async updateActor(source){source.type==="character"&&this.replaceBiographyData(source.system)}};__name2(_Migration682BiographyFields,"Migration682BiographyFields"),__publicField(_Migration682BiographyFields,"version",.682);let Migration682BiographyFields=_Migration682BiographyFields;const _Migration683FlavorTextToPublicNotes=class extends MigrationBase{static{__name(this,"_Migration683FlavorTextToPublicNotes")}replaceFlavorTextData(old){old.details.flavorText?(old.details.publicNotes=old.details.flavorText,old.details["-=flavorText"]=null):old.details.publicNotes??="","game"in globalThis||delete old.details.flavorText,old.details.blurb??="",old.details.privateNotes??=""}async updateActor(actorSource){actorSource.type==="npc"&&this.replaceFlavorTextData(actorSource.system)}};__name2(_Migration683FlavorTextToPublicNotes,"Migration683FlavorTextToPublicNotes"),__publicField(_Migration683FlavorTextToPublicNotes,"version",.683);let Migration683FlavorTextToPublicNotes=_Migration683FlavorTextToPublicNotes;const _Migration684RationsToConsumable=class extends MigrationBase{static{__name(this,"_Migration684RationsToConsumable")}constructor(){super(...arguments),__privateAdd(this,_isOldRations),__privateAdd(this,_getRationRefs),__privateAdd(this,_rationsSourceId,"Compendium.pf2e.equipment-srd.L9ZV076913otGtiB"),__privateAdd(this,_rationsPromise,fromUuid(__privateGet(this,_rationsSourceId)))}async updateActor(source){const oldRations=source.items.filter(i=>__privateMethod(this,_isOldRations,isOldRations_fn).call(this,i)),rations=await __privateGet(this,_rationsPromise);if(!(rations instanceof ConsumablePF2e))throw ErrorPF2e("Unexpected error acquiring compendium item");for(const oldRation of oldRations){const newRation=rations.toObject();newRation.folder=oldRation.folder,newRation.sort=oldRation.sort;const oldContainerId=oldRation.system.containerId??{value:null};oldContainerId instanceof Object&&(newRation.system.containerId=oldContainerId.value);const oldQuantity=oldRation.system.quantity;isObject(oldQuantity)&&(newRation.system.quantity=Math.ceil((oldQuantity.value??1)/7)),source.items.findSplice(item=>item===oldRation,newRation)}}async updateItem(source){if(source.type!=="kit")return;const rationRefs=__privateMethod(this,_getRationRefs,getRationRefs_fn).call(this,Object.values(source.system.items));for(const rationRef of rationRefs)rationRef.quantity=Math.ceil(rationRef.quantity/7)}};_rationsSourceId=new WeakMap,_rationsPromise=new WeakMap,_isOldRations=new WeakSet,isOldRations_fn=__name2(function(itemSource){return itemSource?.type==="equipment"&&itemSource.flags.core?.sourceId===__privateGet(this,_rationsSourceId)},"#isOldRations"),_getRationRefs=new WeakSet,getRationRefs_fn=__name2(function(itemRefs){return itemRefs.reduce((rationRefs,itemRef)=>(itemRef.isContainer&&itemRef.items?rationRefs.push(...__privateMethod(this,_getRationRefs,getRationRefs_fn).call(this,Object.values(itemRef.items))):itemRef.pack==="pf2e.equipment-srd"&&itemRef.id==="L9ZV076913otGtiB"&&rationRefs.push(itemRef),rationRefs),[])},"#getRationRefs"),__name2(_Migration684RationsToConsumable,"Migration684RationsToConsumable"),__publicField(_Migration684RationsToConsumable,"version",.684);let Migration684RationsToConsumable=_Migration684RationsToConsumable;const _Migration685FixMeleeUsageTraits=class extends MigrationBase{static{__name(this,"_Migration685FixMeleeUsageTraits")}async updateItem(itemSource){if(itemSource.type==="weapon"){const systemData=itemSource.system;systemData.meleeUsage&&!Array.isArray(systemData.meleeUsage.traits)&&(systemData.meleeUsage.traits=systemData.meleeUsage.traits?.value??[])}}};__name2(_Migration685FixMeleeUsageTraits,"Migration685FixMeleeUsageTraits"),__publicField(_Migration685FixMeleeUsageTraits,"version",.685);let Migration685FixMeleeUsageTraits=_Migration685FixMeleeUsageTraits;const _Migration686HeroPointsToResources=class extends MigrationBase{static{__name(this,"_Migration686HeroPointsToResources")}async updateActor(actorSource){if(actorSource.type!=="character")return;const systemSource=actorSource.system;if(systemSource.attributes.heroPoints){const resources=systemSource.resources;resources.heroPoints={value:systemSource.attributes.heroPoints.rank},systemSource.attributes["-=heroPoints"]=null,"game"in globalThis||delete systemSource.attributes.heroPoints}}};__name2(_Migration686HeroPointsToResources,"Migration686HeroPointsToResources"),__publicField(_Migration686HeroPointsToResources,"version",.686);let Migration686HeroPointsToResources=_Migration686HeroPointsToResources;const _Migration687FamiliarityAEsToREs=class extends MigrationBase{static{__name(this,"_Migration687FamiliarityAEsToREs")}isFamiliarityAE(data){return typeof data=="object"&&data!==null&&__name2(obj=>typeof obj.trait=="string"&&typeof obj.category=="string","dataIsFamiliarity")(data)}toRuleElement(sameAs,aeValue){const aeData=(()=>{try{const parsed=JSON.parse(aeValue);return this.isFamiliarityAE(parsed)?parsed:null}catch(error){return console.warn(error),null}})();return aeData&&{key:"LinkedProficiency",slug:`${aeData.category}-${aeData.trait}-weapons`,predicate:{all:[`weapon:trait:${aeData.trait}`,`weapon:category:${aeData.category}`]},sameAs}}async updateActor(actorSource){actorSource.effects=[]}async updateItem(itemSource){for(const effect of[...itemSource.effects])for(const change of effect.changes.filter(change2=>change2.key.startsWith("system.martial."))){const linkTo=change.key.replace(/^data\.martial\.|\.familiarity$/g,""),reData=this.toRuleElement(linkTo,change.value);reData&&itemSource.system.rules.push(reData)}itemSource.effects=[]}};__name2(_Migration687FamiliarityAEsToREs,"Migration687FamiliarityAEsToREs"),__publicField(_Migration687FamiliarityAEsToREs,"version",.687);let Migration687FamiliarityAEsToREs=_Migration687FamiliarityAEsToREs;const _Migration688ClampSpellLevel=class extends MigrationBase{static{__name(this,"_Migration688ClampSpellLevel")}async updateItem(itemSource){itemSource.type==="spell"&&(itemSource.system.level.value=Math.min(Math.max(itemSource.system.level.value,1),10))}};__name2(_Migration688ClampSpellLevel,"Migration688ClampSpellLevel"),__publicField(_Migration688ClampSpellLevel,"version",.688);let Migration688ClampSpellLevel=_Migration688ClampSpellLevel;const _Migration689EncumberanceActiveEffects=class extends MigrationBase{static{__name(this,"_Migration689EncumberanceActiveEffects")}async updateItem(itemSource){const systemData=itemSource.system,slug=systemData.slug??sluggify(itemSource.name),amountToIncreaseBy=(()=>itemSource.type==="feat"&&slug==="hefty-hauler"?2:itemSource.type==="feat"&&slug==="hardy-traveler"||itemSource.type==="equipment"&&slug==="lifting-belt"?1:0)();if(amountToIncreaseBy===0||systemData.rules.some(r=>r.key==="ActiveEffectLike"))return;const rules=[{key:"ActiveEffectLike",path:"system.attributes.bonusEncumbranceBulk",mode:"add",value:amountToIncreaseBy},{key:"ActiveEffectLike",path:"system.attributes.bonusLimitBulk",mode:"add",value:amountToIncreaseBy}];for(const rule of rules)systemData.rules.push(rule)}};__name2(_Migration689EncumberanceActiveEffects,"Migration689EncumberanceActiveEffects"),__publicField(_Migration689EncumberanceActiveEffects,"version",.689);let Migration689EncumberanceActiveEffects=_Migration689EncumberanceActiveEffects;const _Migration690InitiativeTiebreakItems=class extends MigrationBase{static{__name(this,"_Migration690InitiativeTiebreakItems")}itemSlugs=["ambush-awareness","elven-instincts","pilgrims-token"];rule={key:"ActiveEffectLike",path:"system.attributes.initiative.tiebreakPriority",mode:"override",value:0};async updateItem(itemSource){this.itemSlugs.includes(itemSource.system.slug??"")&&!itemSource.system.rules.some(rule=>rule.key==="ActiveEffectLike")&&!(itemSource.system.slug==="pilgrims-token"&&itemSource.type!=="equipment")&&itemSource.system.rules.push(this.rule)}};__name2(_Migration690InitiativeTiebreakItems,"Migration690InitiativeTiebreakItems"),__publicField(_Migration690InitiativeTiebreakItems,"version",.69);let Migration690InitiativeTiebreakItems=_Migration690InitiativeTiebreakItems;const _Migration691WeaponRangeAbilityCategoryGroup=class extends MigrationBase{static{__name(this,"_Migration691WeaponRangeAbilityCategoryGroup")}isOldGroupData(group){return isObject(group)&&(typeof group.value=="string"||group.value===null)}isOldRangeData(range){return range instanceof Object&&"value"in range&&typeof range.value=="string"}async updateItem(itemSource){if(itemSource.type==="weapon"){const systemData=itemSource.system;systemData.category=(systemData.weaponType?systemData.weaponType.value:systemData.category)||"simple",systemData.weaponType&&(systemData["-=weaponType"]=null,"game"in globalThis||delete systemData.weaponType),systemData.group=(this.isOldGroupData(systemData.group)?systemData.group.value:systemData.group)||null;const hasOldRangeData=this.isOldRangeData(systemData.range);if(systemData.range=hasOldRangeData?Number(systemData.range.value)||null:systemData.range,hasOldRangeData&&isObject(systemData.ability)&&(systemData.ability.value==="str"&&!setHasElement(MANDATORY_RANGED_GROUPS,systemData.group)&&(systemData.range=null),delete systemData.ability,systemData["-=ability"]=null),setHasElement(MANDATORY_RANGED_GROUPS,systemData.group)){const thrownIndex=systemData.traits.value.findIndex(trait=>/^thrown-\d+/.test(trait));thrownIndex!==-1&&(systemData.traits.value[thrownIndex]="thrown",systemData.reload.value="-")}systemData.baseItem==="falchion"?systemData.group="sword":systemData.baseItem==="orc-knuckle-dagger"&&(systemData.group="knife")}const{rules}=itemSource.system,strikeRules=rules.filter(rule=>/\bStrike$/.test(String(rule.key)));for(const rule of strikeRules)rule.key="Strike",rule.range=Number(rule.range)||null,delete rule.ability}};__name2(_Migration691WeaponRangeAbilityCategoryGroup,"Migration691WeaponRangeAbilityCategoryGroup"),__publicField(_Migration691WeaponRangeAbilityCategoryGroup,"version",.691);let Migration691WeaponRangeAbilityCategoryGroup=_Migration691WeaponRangeAbilityCategoryGroup;const _Migration692CraftingEntryFeatReplacement=class extends MigrationBase{static{__name(this,"_Migration692CraftingEntryFeatReplacement")}requiresFlush=!0;slugToPromise=new Map([["advanced-alchemy",fromUuid("Compendium.pf2e.classfeatures.Pe0zmIqyTBc2Td0I")],["field-discovery-bomber",fromUuid("Compendium.pf2e.classfeatures.8QAFgy9U8PxEa7Dw")],["field-discovery-chirurgeon",fromUuid("Compendium.pf2e.classfeatures.qC0Iz6SlG2i9gv6g")],["field-discovery-mutagenist",fromUuid("Compendium.pf2e.classfeatures.V4Jt7eDnJBLv5bDj")],["field-discovery-toxicologist",fromUuid("Compendium.pf2e.classfeatures.6zo2PJGYoig7nFpR")],["infused-reagents",fromUuid("Compendium.pf2e.classfeatures.wySB9VHOW1v3TX1L")],["alchemist-dedication",fromUuid("Compendium.pf2e.feats-srd.CJMkxlxHiHZQYDCz")],["deeper-dabbler",fromUuid("Compendium.pf2e.feats-srd.PTXZ2C3AV8tZf0iX")],["efficient-alchemy-paragon",fromUuid("Compendium.pf2e.feats-srd.2FBZ0apnmZ7b61ct")],["expert-alchemy",fromUuid("Compendium.pf2e.feats-srd.soHLtpMM9h3AE7PD")],["expert-fireworks-crafter",fromUuid("Compendium.pf2e.feats-srd.dDFQJem5K9Jzxgda")],["expert-herbalism",fromUuid("Compendium.pf2e.feats-srd.owJorCBZmUi5lIV0")],["expert-poisoner",fromUuid("Compendium.pf2e.feats-srd.VruIzuysxw4tY6rk")],["firework-technician-dedication",fromUuid("Compendium.pf2e.feats-srd.MVbNnjqQOK9d8Ki3")],["gadget-specialist",fromUuid("Compendium.pf2e.feats-srd.DQN7YC7s7T0pL6Aa")],["herbalist-dedication",fromUuid("Compendium.pf2e.feats-srd.5CRt5Dy9eLv5LpRF")],["master-alchemy",fromUuid("Compendium.pf2e.feats-srd.f6k9lIrIS4SfnCnG")],["munitions-crafter",fromUuid("Compendium.pf2e.feats-srd.lFVqejlf52cdYrZy")],["munitions-machinist",fromUuid("Compendium.pf2e.feats-srd.lh3STEvbGnP7jVMr")],["plentiful-snares",fromUuid("Compendium.pf2e.feats-srd.wGaxWwJhIXbMJft1")],["poisoner-dedication",fromUuid("Compendium.pf2e.feats-srd.y7DDs03GtDnmhxFp")],["snare-genius",fromUuid("Compendium.pf2e.feats-srd.8DIzXO1YpsU3DpJw")],["snare-specialist",fromUuid("Compendium.pf2e.feats-srd.0haS0qXR9xTYKoTG")],["snarecrafter-dedication",fromUuid("Compendium.pf2e.feats-srd.4MUbwilvb9dI0X59")],["talisman-dabbler-dedication",fromUuid("Compendium.pf2e.feats-srd.1t5479E6bdvFs4E7")],["ubiquitous-gadgets",fromUuid("Compendium.pf2e.feats-srd.ny0nfGTDUE4p8TtO")],["ubiquitous-snares",fromUuid("Compendium.pf2e.feats-srd.bX2WI5k0afqPpCfm")]]);replaceItem({items,current,replacement}){if(!(replacement instanceof ItemPF2e))throw ErrorPF2e("Unexpected error retrieving compendium item");const newSource=replacement.toObject();current.type==="feat"&&newSource.type==="feat"&&(newSource.system.location=current.system.location),items.splice(items.indexOf(current),1,newSource)}async updateActor(actorSource){actorSource.type==="character"&&this.slugToPromise.forEach(async(promise,slug)=>{const current=actorSource.items.find(itemSource=>itemSource.type==="feat"&&itemSource.system.slug===slug);current&&this.replaceItem({items:actorSource.items,current,replacement:await promise})})}};__name2(_Migration692CraftingEntryFeatReplacement,"Migration692CraftingEntryFeatReplacement"),__publicField(_Migration692CraftingEntryFeatReplacement,"version",.692);let Migration692CraftingEntryFeatReplacement=_Migration692CraftingEntryFeatReplacement;const _Migration693ArmorCategoryGroup=class extends MigrationBase{static{__name(this,"_Migration693ArmorCategoryGroup")}isOldGroupData(group){return group instanceof Object&&"value"in group&&(typeof group.value=="string"||group.value===null)}async updateItem(itemSource){if(itemSource.type!=="armor")return;const systemData=itemSource.system;systemData.category=(systemData.armorType?systemData.armorType.value:systemData.category)||"simple",systemData.armorType&&(systemData["-=armorType"]=null,"game"in globalThis||delete systemData.armorType),systemData.group=(this.isOldGroupData(systemData.group)?systemData.group.value:systemData.group)||null}};__name2(_Migration693ArmorCategoryGroup,"Migration693ArmorCategoryGroup"),__publicField(_Migration693ArmorCategoryGroup,"version",.693);let Migration693ArmorCategoryGroup=_Migration693ArmorCategoryGroup;const _Migration694RetireSystemTokenSettings=class extends MigrationBase{static{__name(this,"_Migration694RetireSystemTokenSettings")}async migrate(){const systemNameHover=Number(game.settings.storage.get("world").getItem("pf2e.defaultTokenSettingsName"))||CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,systemBarHover=Number(game.settings.storage.get("world").getItem("pf2e.defaultTokenSettingsBar"))||CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,coreTokenDefaults=game.settings.get("core","defaultToken");coreTokenDefaults.displayName=systemNameHover,coreTokenDefaults.displayBars=systemBarHover}};__name2(_Migration694RetireSystemTokenSettings,"Migration694RetireSystemTokenSettings"),__publicField(_Migration694RetireSystemTokenSettings,"version",.694);let Migration694RetireSystemTokenSettings=_Migration694RetireSystemTokenSettings;const _Migration695SummonToSummoned=class extends MigrationBase{static{__name(this,"_Migration695SummonToSummoned")}async updateItem(itemSource){const traits=itemSource.system.traits;if(traits?.value)if(itemSource.type==="action")traits.custom??="",traits.custom.toLowerCase()==="summon"&&(traits.custom="",traits.value=Array.from(new Set([...traits.value,"summon"])).sort());else{const index=traits.value.indexOf("summon");index!==-1&&(traits.value[index]="summoned")}}};__name2(_Migration695SummonToSummoned,"Migration695SummonToSummoned"),__publicField(_Migration695SummonToSummoned,"version",.695);let Migration695SummonToSummoned=_Migration695SummonToSummoned;const _Migration696FlatAbilityModifiers=class extends MigrationBase{static{__name(this,"_Migration696FlatAbilityModifiers")}abilityModPattern=/@abilities\.([a-z]{3})\.mod\b/;abbreviationMap=new Map(Array.from(ATTRIBUTE_ABBREVIATIONS).map(a=>[`PF2E.Ability${sluggify(a,{camel:"bactrian"})}`,a]));async updateItem(itemSource){const rules=itemSource.system.rules;for(const rule of rules)if(typeof rule.key=="string"&&rule.key.endsWith("FlatModifier")&&rule.type==="ability"&&!setHasElement(ATTRIBUTE_ABBREVIATIONS,rule.ability)){const abilityFromValue=this.abilityModPattern.exec(String(rule.value))?.[1]??null;rule.ability=abilityFromValue??this.abbreviationMap.get(String(rule.label??""))??"str",typeof rule.value=="string"&&rule.value.startsWith("@")&&rule.value.endsWith(".mod")&&delete rule.value}itemSource.system.slug==="thief-racket"&&!rules.some(rule=>rule.ability==="dex")&&rules.unshift({ability:"dex",key:"FlatModifier",predicate:{all:["weapon:melee","weapon:trait:finesse"],not:["weapon:category:unarmed"]},selector:"damage",type:"ability"})}};__name2(_Migration696FlatAbilityModifiers,"Migration696FlatAbilityModifiers"),__publicField(_Migration696FlatAbilityModifiers,"version",.696);let Migration696FlatAbilityModifiers=_Migration696FlatAbilityModifiers;const _Migration697WeaponReachTrait=class extends MigrationBase{static{__name(this,"_Migration697WeaponReachTrait")}async updateItem(itemSource){if(itemSource.type==="weapon"){const traits=itemSource.system.traits.value,numericReach=traits.find(t=>/^reach-\d+$/.test(t));numericReach&&traits.splice(traits.indexOf(numericReach),1,"reach")}}};__name2(_Migration697WeaponReachTrait,"Migration697WeaponReachTrait"),__publicField(_Migration697WeaponReachTrait,"version",.697);let Migration697WeaponReachTrait=_Migration697WeaponReachTrait;const _Migration698RemoveDerivedActorTraits=class extends MigrationBase{static{__name(this,"_Migration698RemoveDerivedActorTraits")}async updateActor(source){if(!((source.type==="character"||source.type==="npc")&&"traits"in source.system.traits&&isObject(source.system.traits.traits)&&"value"in source.system.traits.traits&&Array.isArray(source.system.traits.traits.value)))return;const traits=source.system.traits.traits.value;for(const trait of ALIGNMENT_TRAITS){const index=traits.indexOf(trait);index>=0&&traits.splice(index,1)}if(source.type==="character"){const ancestry=source.items.find(i=>i.type==="ancestry");if(!ancestry)return;for(const trait of ancestry.system.traits.value){const index=traits.indexOf(trait);index>=0&&traits.splice(index,1)}}}};__name2(_Migration698RemoveDerivedActorTraits,"Migration698RemoveDerivedActorTraits"),__publicField(_Migration698RemoveDerivedActorTraits,"version",.698);let Migration698RemoveDerivedActorTraits=_Migration698RemoveDerivedActorTraits;const _Migration699ItemDescriptionEmptyString=class extends MigrationBase{static{__name(this,"_Migration699ItemDescriptionEmptyString")}async updateItem(itemSource){itemSource.system.description.value??=""}};__name2(_Migration699ItemDescriptionEmptyString,"Migration699ItemDescriptionEmptyString"),__publicField(_Migration699ItemDescriptionEmptyString,"version",.699);let Migration699ItemDescriptionEmptyString=_Migration699ItemDescriptionEmptyString;const _Migration700SingleClassFeatures=class extends MigrationBase{static{__name(this,"_Migration700SingleClassFeatures")}constructor(){super(...arguments),__privateAdd(this,_migrateClass),__privateAdd(this,_migrateFeature),__privateAdd(this,_isClassFeature2),__publicField(this,"itemIds",{alertness:["D8CSi8c9XiRpVc5M","OZaJz4exCoz6vuuv","qJ4fwGpoNC36ZQ8I","2o1Cj7hDayDlslqY","TAIOtk5VvPZvv4nu"],"armor-expertise":["x5jaCJxsmD5sx3KB","fRifyINZF5SKDfib"],"armor-mastery":["CGB1TczFhQhdQxml","IPDwS5pTgU3Cq6Nl"],evasion:["MV6XIuAgN9uSA0Da","EZuWfYSv3ASLyKtu","DqWr3LqUpT3Xi2xq"],"expert-spellcaster":["cD3nSupdCvONuHiE","mdzk070ixIDpid7V"],"great-fortitude":["F57Na5VxfBp56kke","25GSAotUcDwInYgG"],"improved-evasion":["L5D0NwFXdLiVSnk5","6XwGONPdr9SFDtDc"],"incredible-senses":["nLwPMPLRne1HnL00","iyb5FU2BpsCCan8Q","kktZhQPJgC5F4hgU"],"iron-will":["wMyDcVNmA7xGK83S","JVCxv4HuLaaFhAf4"],juggernaut:["OMZs5y16jZRW9KQK","sHCFQZM0xHCOYOId","Ba97T4anGhizfaCt","pzTRQxuoNOeWAalC","ojB0UJWpSekQPjT7"],"lightning-reflexes":["TUOeATt52P43r5W0","rz87RgR1crWTd7j5","Xqd0vrxq2bLXxdaB","tfugXJHITCnArN1b","7PzcKaDGy6tIkQh4","EJzjY6AIsTYqW0ee"],"magical-fortitude":["70jqXP2eS4tRZ0Ok","MzyPNlxrNA5OKVd7"],"master-spellcaster":["l1InYvhnQSz6Ucxc","zu9PcxvfoZlqQVk5"],"medium-armor-expertise":["FCEp9jjxxgRJDJV3","tzUaTqB6GHAeffOl"],"medium-armor-mastery":["cGMSYAErbUG5E8X2","NcEpvnIZfKzG1Iou"],resolve:["JQAujUXjczVnYDEI","D2g6sZQAWaTccviQ","vv63fioCtOvDIdF2","9WjZSliQZJlyGvUi"],"vigilant-senses":["0npO4rPscGm0dX13","NTp146fjLreL5zsj"],"weapon-expertise":["9XLUh9iMepZesdmc","F5BHEav90oOJ2LwN","O99eXctsEjEpuBwe"],"weapon-specialization":["9EqIasqfI8YIM3Pt","WiM7X4xmpMx4s6LD","1NGTc0gqEtwaFqUK"]}),__publicField(this,"features",["Alertness","Armor Expertise","Armor Mastery","Evasion","Expert Spellcaster","Great Fortitude","Improved Evasion","Incredible Senses","Iron Will","Juggernaut","Lightning Reflexes","Magical Fortitude","Master Spellcaster","Medium Armor Expertise","Medium Armor Mastery","Resolve","Vigilant Senses","Weapon Expertise","Weapon Specialization"].map(name2=>({slug:sluggify(name2),name:name2})))}async updateItem(source){source.type==="class"?__privateMethod(this,_migrateClass,migrateClass_fn).call(this,source):source.type==="feat"&&__privateMethod(this,_migrateFeature,migrateFeature_fn).call(this,source)}};_migrateClass=new WeakSet,migrateClass_fn=__name2(function(itemSource){for(const refId in itemSource.system.items){const itemRef=itemSource.system.items[refId];itemRef.level=Number(itemRef.level)||1;for(const feature of this.features)itemSource.system.slug==="swashbuckler"&&feature.slug==="weapon-expertise"||this.itemIds[feature.slug].includes(itemRef.id??"")&&(itemRef.id=this.itemIds[feature.slug][0],itemRef.name=feature.name)}},"#migrateClass"),_migrateFeature=new WeakSet,migrateFeature_fn=__name2(function(source){if(__privateMethod(this,_isClassFeature2,isClassFeature_fn2).call(this,source))for(const feature of this.features)source.system.slug==="swashbuckler"&&feature.slug==="weapon-expertise"||source.system.slug?.startsWith(`${feature.slug}-level-`)&&(source.system.slug=feature.slug,source.name.startsWith(`${feature.name} `)&&(source.name=feature.name),source.system.traits.value=[])},"#migrateFeature"),_isClassFeature2=new WeakSet,isClassFeature_fn2=__name2(function(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"},"#isClassFeature"),__name2(_Migration700SingleClassFeatures,"Migration700SingleClassFeatures"),__publicField(_Migration700SingleClassFeatures,"version",.7);let Migration700SingleClassFeatures=_Migration700SingleClassFeatures;const _Migration701ModifierNameToSlug=class extends MigrationBase{static{__name(this,"_Migration701ModifierNameToSlug")}async updateItem(itemSource){const rules=itemSource.system.rules.filter(r=>["FlatModifier","DamageDice"].includes(String(r.key)));for(const rule of rules)rule.name&&(rule.label?rule.slug=sluggify(rule.name):rule.label=rule.name,delete rule.name),rule.label==="Rage"&&(rule.label="PF2E.TraitRage")}};__name2(_Migration701ModifierNameToSlug,"Migration701ModifierNameToSlug"),__publicField(_Migration701ModifierNameToSlug,"version",.701);let Migration701ModifierNameToSlug=_Migration701ModifierNameToSlug;const _Migration702REFormulasAtInstanceLevel=class extends MigrationBase{static{__name(this,"_Migration702REFormulasAtInstanceLevel")}raiseToInstanceLevel(value){return value.replace(/@[a-z.]+/gi,match=>["@mod","@castLevel","@heighten","@item.badge.value"].includes(match)||match.indexOf("@spell")>=0?match:match==="@details.level.value"||match==="@actor.details.level.value"?"@actor.level":match==="@item.value.value"?"@item.badge.value":match.startsWith("@abilities.")?match.replace(/\babilities\b/,"actor.abilities"):match.startsWith("@attributes.")?match.replace(/\battributes\b/,"actor.attributes"):match==="@item.level.value"?"@item.level":/^@item\.[a-z]+$/.test(match)?match:match.replace(/@item\.(?!data\b)/,"@item.system.").replace(/@(?!(?:item|actor|[A-Z]\w+))/,"@actor.system."))}async updateItem(itemSource){const rules=itemSource.system.rules;for(const rule of rules)try{if(typeof rule.value=="string")rule.value=this.raiseToInstanceLevel(rule.value);else if(isObject(rule.value)&&"brackets"in rule.value&&Array.isArray(rule.value.brackets))for(const bracket of rule.value.brackets)isObject(bracket)&&typeof bracket.value=="string"&&(bracket.value=this.raiseToInstanceLevel(bracket.value));rule.key==="Note"&&rule.text&&(rule.text=this.raiseToInstanceLevel(rule.text))}catch{continue}}};__name2(_Migration702REFormulasAtInstanceLevel,"Migration702REFormulasAtInstanceLevel"),__publicField(_Migration702REFormulasAtInstanceLevel,"version",.702);let Migration702REFormulasAtInstanceLevel=_Migration702REFormulasAtInstanceLevel;const _Migration703SpellDamageStructure=class extends MigrationBase{static{__name(this,"_Migration703SpellDamageStructure")}async updateItem(itemSource){itemSource.type==="spell"&&(itemSource.system.damage instanceof Object?itemSource.system.damage.value instanceof Object||(itemSource.system.damage.value={}):itemSource.system.damage={value:{}})}};__name2(_Migration703SpellDamageStructure,"Migration703SpellDamageStructure"),__publicField(_Migration703SpellDamageStructure,"version",.703);let Migration703SpellDamageStructure=_Migration703SpellDamageStructure;const _Migration704MartialProficiencyRE=class extends MigrationBase{static{__name(this,"_Migration704MartialProficiencyRE")}async updateItem(itemSource){const rules=itemSource.system.rules.filter(r=>r.key==="LinkedProficiency");for(const rule of rules)if(rule.key="MartialProficiency",rule.definition=rule.predicate,delete rule.predicate,typeof rule.slug=="string"&&itemSource.system.slug?.endsWith("-weapon-familiarity")&&!rule.label){const key=sluggify(rule.slug,{camel:"bactrian"});rule.label=`PF2E.SpecificRule.MartialProficiency.${key}`}if(itemSource.type==="class"&&itemSource.system.slug==="gunslinger"&&itemSource.system.rules.length===0){const gunslingerRules=[{definition:{all:["weapon:category:simple"],any:["weapon:group:firearm","weapon:tag:crossbow"]},key:"MartialProficiency",label:"PF2E.SpecificRule.MartialProficiency.SimpleFirearmsCrossbows",slug:"simple-firearms-crossbows",value:2},{definition:{all:["weapon:category:martial"],any:["weapon:group:firearm","weapon:tag:crossbow"]},key:"MartialProficiency",label:"PF2E.SpecificRule.MartialProficiency.MartialFirearmsCrossbows",slug:"martial-firearms-crossbows",value:2},{definition:{all:["weapon:category:advanced"],any:["weapon:group:firearm","weapon:tag:crossbow"]},key:"MartialProficiency",label:"PF2E.SpecificRule.MartialProficiency.AdvancedFirearmsCrossbows",slug:"advanced-firearms-crossbows",value:1}];itemSource.system.rules=gunslingerRules}}};__name2(_Migration704MartialProficiencyRE,"Migration704MartialProficiencyRE"),__publicField(_Migration704MartialProficiencyRE,"version",.704);let Migration704MartialProficiencyRE=_Migration704MartialProficiencyRE;const _Migration705GunslingerCatchUp=class extends MigrationBase{static{__name(this,"_Migration705GunslingerCatchUp")}constructor(){super(...arguments),__privateAdd(this,_isClassFeature3)}async updateItem(source){if(__privateMethod(this,_isClassFeature3,isClassFeature_fn3).call(this,source))switch(source.system.slug){case"singular-expertise":{const rules=[{key:"FlatModifier",selector:"firearm-weapon-group-damage",type:"circumstance",value:1},{key:"FlatModifier",predicate:{all:["weapon:tag:crossbow"]},selector:"bow-weapon-group-damage",type:"circumstance",value:1}];source.system.rules=rules;break}case"gunslinger-weapon-mastery":{const rules=[{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.unarmed.rank",value:2},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.simple.rank",value:2},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.martial.rank",value:2},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.advanced-firearms-crossbows.rank",value:2},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.simple-firearms-crossbows.rank",value:3},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.martial-firearms-crossbows.rank",value:3}];source.system.rules=rules;break}case"gunslinging-legend":{const rules=[{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.unarmed.rank",value:3},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.simple.rank",value:3},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.martial.rank",value:3},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.advanced-firearms-crossbows.rank",value:3},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.simple-firearms-crossbows.rank",value:4},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.martial-firearms-crossbows.rank",value:4}];source.system.rules=rules;break}}}};_isClassFeature3=new WeakSet,isClassFeature_fn3=__name2(function(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"},"#isClassFeature"),__name2(_Migration705GunslingerCatchUp,"Migration705GunslingerCatchUp"),__publicField(_Migration705GunslingerCatchUp,"version",.705);let Migration705GunslingerCatchUp=_Migration705GunslingerCatchUp;const _Migration706FormulasAtInstanceLevelEverythingElse=class extends Migration702REFormulasAtInstanceLevel{static{__name(this,"_Migration706FormulasAtInstanceLevelEverythingElse")}async updateItem(itemSource){if(itemSource.system.description.value&&(itemSource.system.description.value=this.replaceInlineRolls(itemSource.system.description.value)),itemSource.type==="spell")for(const value of Object.values(itemSource.system.damage.value))value.value=this.raiseToInstanceLevel(value.value);if(itemSource.type==="melee")for(const value of Object.values(itemSource.system.damageRolls))value.damage=this.raiseToInstanceLevel(value.damage)}replaceInlineRolls(value){return value.replace(/\[\[(.*)\]\]/g,match=>this.raiseToInstanceLevel(match))}};__name2(_Migration706FormulasAtInstanceLevelEverythingElse,"Migration706FormulasAtInstanceLevelEverythingElse"),__publicField(_Migration706FormulasAtInstanceLevelEverythingElse,"version",.706);let Migration706FormulasAtInstanceLevelEverythingElse=_Migration706FormulasAtInstanceLevelEverythingElse;const _Migration707BracketedFormulasAtInstanceLevel=class extends Migration702REFormulasAtInstanceLevel{static{__name(this,"_Migration707BracketedFormulasAtInstanceLevel")}};__name2(_Migration707BracketedFormulasAtInstanceLevel,"Migration707BracketedFormulasAtInstanceLevel"),__publicField(_Migration707BracketedFormulasAtInstanceLevel,"version",.707);let Migration707BracketedFormulasAtInstanceLevel=_Migration707BracketedFormulasAtInstanceLevel;const _Migration708SpecificRuleLabel=class extends MigrationBase{static{__name(this,"_Migration708SpecificRuleLabel")}async updateItem(itemSource){for(const rule of itemSource.system.rules)rule.label&&(rule.label=String(rule.label).replace(/\bSpecificRules\b/,"SpecificRule"))}};__name2(_Migration708SpecificRuleLabel,"Migration708SpecificRuleLabel"),__publicField(_Migration708SpecificRuleLabel,"version",.708);let Migration708SpecificRuleLabel=_Migration708SpecificRuleLabel;const _Migration709REFormulasAtInstanceLevelRedux=class extends Migration702REFormulasAtInstanceLevel{static{__name(this,"_Migration709REFormulasAtInstanceLevelRedux")}walkObject(obj){if(Array.isArray(obj))for(let i=0;ir.key==="BattleForm");for(const rule of rules)this.walkObject(rule);itemSource.type==="spell"&&itemSource.system.slug==="wild-shape"&&(itemSource.system.rules=[])}};__name2(_Migration709REFormulasAtInstanceLevelRedux,"Migration709REFormulasAtInstanceLevelRedux"),__publicField(_Migration709REFormulasAtInstanceLevelRedux,"version",.709);let Migration709REFormulasAtInstanceLevelRedux=_Migration709REFormulasAtInstanceLevelRedux;const _Migration710RarityToString=class extends MigrationBase{static{__name(this,"_Migration710RarityToString")}updateTraits(traits){typeof traits?.rarity=="object"&&traits.rarity!==null&&(traits.rarity=traits.rarity.value)}async updateActor(actorSource){"traits"in actorSource.system&&this.updateTraits(actorSource.system.traits??null)}async updateItem(itemSource){"traits"in itemSource.system&&this.updateTraits(itemSource.system.traits??null)}};__name2(_Migration710RarityToString,"Migration710RarityToString"),__publicField(_Migration710RarityToString,"version",.71);let Migration710RarityToString=_Migration710RarityToString;const toDelete=["featType","actionCategory","actions","actionType","level","location"],_Migration711HeritageItems=class extends MigrationBase{static{__name(this,"_Migration711HeritageItems")}constructor(){super(...arguments),__privateAdd(this,_isHeritageFeature),__privateAdd(this,_heritageFromFeat),__privateAdd(this,_officialAncestries,{tengu:{name:"Tengu",uuid:"Compendium.pf2e.ancestries.Item.18xDKYPDBLEv2myX"},kitsune:{name:"Kitsune",uuid:"Compendium.pf2e.ancestries.Item.4BL5wf1VF9feC2rY"},poppet:{name:"Poppet",uuid:"Compendium.pf2e.ancestries.Item.6F2fSFC1Eo1JdpY4"},kobold:{name:"Kobold",uuid:"Compendium.pf2e.ancestries.Item.7oQxL6wgsokD3QXG"},catfolk:{name:"Catfolk",uuid:"Compendium.pf2e.ancestries.Item.972EkpJOPv9KkQIW"},dwarf:{name:"Dwarf",uuid:"Compendium.pf2e.ancestries.Item.BYj5ZvlXZdpaEgA6"},gnome:{name:"Gnome",uuid:"Compendium.pf2e.ancestries.Item.CYlfsYLJcBOgqKtD"},fleshwarp:{name:"Fleshwarp",uuid:"Compendium.pf2e.ancestries.Item.FXlXmNBFiiz9oasi"},strix:{name:"Strix",uuid:"Compendium.pf2e.ancestries.Item.GXcC6oVa5quzgNHD"},android:{name:"Android",uuid:"Compendium.pf2e.ancestries.Item.GfLwE884NoRC7cRi"},halfling:{name:"Halfling",uuid:"Compendium.pf2e.ancestries.Item.GgZAHbrjnzWOZy2v"},lizardfolk:{name:"Lizardfolk",uuid:"Compendium.pf2e.ancestries.Item.HWEgF7Gmoq55VhTL"},human:{name:"Human",uuid:"Compendium.pf2e.ancestries.Item.IiG7DgeLWYrSNXuX"},ratfolk:{name:"Ratfolk",uuid:"Compendium.pf2e.ancestries.Item.P6PcVnCkh4XMdefw"},elf:{name:"Elf",uuid:"Compendium.pf2e.ancestries.Item.PgKmsA2aKdbLU6O0"},anadi:{name:"Anadi",uuid:"Compendium.pf2e.ancestries.Item.TQEqWqc7BYiadUdY"},sprite:{name:"Sprite",uuid:"Compendium.pf2e.ancestries.Item.TRqoeYfGAFjQbviF"},goloma:{name:"Goloma",uuid:"Compendium.pf2e.ancestries.Item.c4secsSNG2AO7I5i"},leshy:{name:"Leshy",uuid:"Compendium.pf2e.ancestries.Item.cdhgByGG1WtuaK73"},fetchling:{name:"Fetchling",uuid:"Compendium.pf2e.ancestries.Item.hIA3qiUsxvLZXrFP"},grippli:{name:"Grippli",uuid:"Compendium.pf2e.ancestries.Item.hXM5jXezIki1cMI2"},automaton:{name:"Automaton",uuid:"Compendium.pf2e.ancestries.Item.kYsBAJ103T44agJF"},orc:{name:"Orc",uuid:"Compendium.pf2e.ancestries.Item.lSGWXjcbOa6O5fTx"},hobgoblin:{name:"Hobgoblin",uuid:"Compendium.pf2e.ancestries.Item.piNLXUrm9iaGqD2i"},shoony:{name:"Shoony",uuid:"Compendium.pf2e.ancestries.Item.q6rsqYARyOGXZA8F"},goblin:{name:"Goblin",uuid:"Compendium.pf2e.ancestries.Item.sQfjTMDaZbT9DThq"},conrasu:{name:"Conrasu",uuid:"Compendium.pf2e.ancestries.Item.tZn4qIHCUA6wCdnI"},gnoll:{name:"Gnoll",uuid:"Compendium.pf2e.ancestries.Item.vxbQ1Yw4qwgjTzqo"},shisk:{name:"Shisk",uuid:"Compendium.pf2e.ancestries.Item.x1YinOddgUxwOLqP"},azarketi:{name:"Azarketi",uuid:"Compendium.pf2e.ancestries.Item.yFoojz6q3ZjvceFw"}}),__privateAdd(this,_heritagesWithoutAncestryInName,{"half-elf":"human","half-orc":"human","skilled-heritage":"human","versatile-heritage":"human",draxie:"sprite",grig:"sprite",melixie:"sprite",nyktera:"sprite",pixie:"sprite","deep-rat":"ratfolk","desert-rat":"ratfolk","longsnout-rat":"ratfolk","sewer-rat":"ratfolk","shadow-rat":"ratfolk","snow-rat":"ratfolk","tunnel-rat":"ratfolk","rite-of-invocation":"conrasu","rite-of-knowing":"conrasu","rite-of-light":"conrasu","rite-of-passage":"conrasu","rite-of-reinforcement":"conrasu"}),__privateAdd(this,_ancestrySlugs,Object.keys(__privateGet(this,_officialAncestries)))}async updateActor(actorSource){const heritageFeatures=actorSource.items.filter(i=>__privateMethod(this,_isHeritageFeature,isHeritageFeature_fn).call(this,i)),firstHeritageFeature=heritageFeatures[0];if(!actorSource.items.some(i=>i.type==="heritage")&&firstHeritageFeature&&actorSource.type==="character"){const heritageSource=__privateMethod(this,_heritageFromFeat,heritageFromFeat_fn).call(this,firstHeritageFeature);actorSource.items.push(heritageSource);const details=actorSource.system.details;details.heritage&&(details["-=heritage"]=null,"game"in globalThis||delete details.heritage)}for(const feature of heritageFeatures)actorSource.items.splice(actorSource.items.indexOf(feature),1)}async updateItem(itemSource,actorSource){if(actorSource||!__privateMethod(this,_isHeritageFeature,isHeritageFeature_fn).call(this,itemSource))return;const newSource=itemSource;newSource.type="heritage",itemSource.img==="systems/pf2e/icons/default-icons/feat.svg"&&(itemSource.img="systems/pf2e/icons/default-icons/heritage.svg");const newSystemData=__privateMethod(this,_heritageFromFeat,heritageFromFeat_fn).call(this,itemSource).system,deletionProperties=toDelete.map(k=>`-=${k}`);for(const property of deletionProperties)newSystemData[property]=null;if(!("game"in globalThis))for(const property of toDelete)delete newSystemData[property];newSource.system=newSystemData}};_isHeritageFeature=new WeakSet,isHeritageFeature_fn=__name2(function(feature){return feature.type==="feat"&&feature.system.featType?.value==="heritage"},"#isHeritageFeature"),_officialAncestries=new WeakMap,_heritagesWithoutAncestryInName=new WeakMap,_ancestrySlugs=new WeakMap,_heritageFromFeat=new WeakSet,heritageFromFeat_fn=__name2(function(feature){const featureSlug=feature.system.slug??"",ancestrySlug=__privateGet(this,_heritagesWithoutAncestryInName)[featureSlug]??__privateGet(this,_ancestrySlugs).find(s=>featureSlug.includes(s)),ancestryReference=__privateGet(this,_officialAncestries)[ancestrySlug??""]??null,traits=feature.system.traits,{flags}=feature;return flags.core?.sourceId&&(flags.core.sourceId=flags.core.sourceId.replace("ancestryfeatures","heritages")),{_id:randomID(),type:"heritage",img:feature.img.endsWith("/feat.svg")?"systems/pf2e/icons/default-icons/heritage.svg":feature.img,name:feature.name,effects:[],folder:feature.folder,flags:feature.flags,sort:feature.sort,ownership:feature.ownership,system:{description:feature.system.description,rules:feature.system.rules,schema:feature.system.schema,_migration:{version:null,previous:null},slug:feature.system.slug,ancestry:ancestryReference,traits:{value:traits.value.filter(t=>(t in creatureTraits||t.startsWith("hb_"))&&!(t in __privateGet(this,_officialAncestries))),rarity:traits.rarity,otherTags:[]}}}},"#heritageFromFeat"),__name2(_Migration711HeritageItems,"Migration711HeritageItems"),__publicField(_Migration711HeritageItems,"version",.711);let Migration711HeritageItems=_Migration711HeritageItems;const _Migration712ActorShieldStructure=class extends MigrationBase{static{__name(this,"_Migration712ActorShieldStructure")}async updateActor(source){if(source.type==="character"||source.type==="npc"){const attributes=source.system.attributes;attributes.shield&&(attributes["-=shield"]=null,"game"in globalThis?attributes.shield={}:delete attributes.shield)}}};__name2(_Migration712ActorShieldStructure,"Migration712ActorShieldStructure"),__publicField(_Migration712ActorShieldStructure,"version",.712);let Migration712ActorShieldStructure=_Migration712ActorShieldStructure;const _Migration713FistToStrikeRE=class extends MigrationBase{static{__name(this,"_Migration713FistToStrikeRE")}async updateItem(itemSource){const fistFeatures=["powerful-fist","martial-artist-dedication"];if(!(itemSource.type==="feat"&&fistFeatures.includes(itemSource.system.slug))||itemSource.system.rules.some(rule=>rule.key==="Strike"))return;const strike={key:"Strike",img:"systems/pf2e/icons/features/classes/powerful-fist.webp",slug:"fist",category:"unarmed",damage:{base:{damageType:"bludgeoning",dice:1,die:"d6"}},group:"brawling",label:"PF2E.Strike.Fist.Label",range:null,traits:["agile","finesse","nonlethal","unarmed"]};itemSource.system.rules=[strike]}};__name2(_Migration713FistToStrikeRE,"Migration713FistToStrikeRE"),__publicField(_Migration713FistToStrikeRE,"version",.713);let Migration713FistToStrikeRE=_Migration713FistToStrikeRE;const _Migration714RangeIncrementREs=class extends MigrationBase{static{__name(this,"_Migration714RangeIncrementREs")}farLobber={definition:{all:["weapon:base:alchemical-bomb"]},key:"AdjustStrike",mode:"upgrade",property:"range-increment",value:30};farShot={definition:{all:["weapon:ranged"]},key:"AdjustStrike",mode:"multiply",property:"range-increment",value:2};farThrow={key:"AdjustModifier",mode:"add",predicate:{all:["weapon:trait:thrown"]},selectors:["ranged-attack-roll"],slug:"range-penalty",value:1};huntPrey={key:"RollOption",domain:"ranged-attack-roll",option:"ignore-range-penalty:2",predicate:{all:["hunted-prey"]}};legendaryShot={key:"RollOption",domain:"ranged-attack-roll",option:"ignore-range-penalty:5"};masterfulHunter=(()=>({key:"RollOption",domain:"ranged-attack-roll",option:"ignore-range-penalty:3",predicate:{all:["hunted-prey",{gte:["weapon:proficiency:rank",3]}]}}))();shootistsEdge=(()=>[{key:"ActiveEffectLike",mode:"upgrade",path:"system.attributes.classDC.rank",value:3},{key:"RollOption",domain:"ranged-attack-roll",option:"ignore-range-penalty:3",phase:"beforeRoll",predicate:{all:[{gte:["weapon:proficiency:rank",3]}]}}])();triangulate=[{default:!0,key:"ToggleProperty",label:"PF2E.SpecificRule.ToggleProperty.Triangulate",property:"flags.pf2e.rollOptions.all.triangulate"},{domain:"ranged-attack-roll",key:"RollOption",option:"ignore-range-penalty:2",predicate:{all:["triangulate"]}},{key:"AdjustModifier",mode:"add",predicate:{all:["triangulate"]},selectors:["ranged-attack-roll"],slug:"range-penalty",value:1}];uncannyBombs={definition:{all:["weapon:base:alchemical-bomb"]},key:"AdjustStrike",mode:"upgrade",property:"range-increment",value:60};unerringShot=(()=>({key:"RollOption",option:"ignore-range-penalty",phase:"beforeRoll",predicate:{all:[{gte:["weapon:proficiency:rank",3]}]}}))();async updateItem(source){const{rules}=source.system;if(source.type==="feat")switch(source.system.slug){case"far-lobber":{source.system.rules=[this.farLobber];return}case"far-shot":{source.system.rules=[this.farShot];return}case"far-throw":{source.system.rules=[this.farThrow];return}case"hunt-prey":{!rules.some(r=>r.key==="RollOption"&&r.option===this.huntPrey.option)&&rules.push(this.huntPrey);return}case"legendary-shot":{source.system.rules=[this.legendaryShot];return}case"masterful-hunter":{!rules.some(r=>r.key==="RollOption"&&r.option===this.masterfulHunter.option)&&rules.push(this.masterfulHunter);return}case"shootists-edge":{source.system.rules=this.shootistsEdge;return}case"triangulate":{source.system.rules=this.triangulate;return}case"uncanny-bombs":{source.system.rules=[this.uncannyBombs];return}case"unerring-shot":{source.system.rules=[this.unerringShot];return}}}};__name2(_Migration714RangeIncrementREs,"Migration714RangeIncrementREs"),__publicField(_Migration714RangeIncrementREs,"version",.714);let Migration714RangeIncrementREs=_Migration714RangeIncrementREs;const _Migration715DangerousSorcery=class extends MigrationBase{static{__name(this,"_Migration715DangerousSorcery")}dangerousSorcery={key:"FlatModifier",phase:"afterDerived",predicate:{all:["item:spell-slot","item:duration:0","damaging-effect"]},selector:"spell-damage",value:"@spell.level"};async updateItem(source){if(source.type!=="feat")return;(source.system.slug??sluggify(source.name))==="dangerous-sorcery"&&!source.system.rules.length&&(source.system.rules=[this.dangerousSorcery])}};__name2(_Migration715DangerousSorcery,"Migration715DangerousSorcery"),__publicField(_Migration715DangerousSorcery,"version",.715);let Migration715DangerousSorcery=_Migration715DangerousSorcery;const _Migration716StrikeDamageSelector=class extends MigrationBase{static{__name(this,"_Migration716StrikeDamageSelector")}itemsToSkip=new Set(["effect-fanatical-frenzy","effect-heroic-recovery","effect-lantern-of-hope","effect-lantern-of-hope-gestalt","spell-effect-inspire-courage","spell-effect-inspire-heroics-courage-2","spell-effect-inspire-heroics-courage-3","spell-effect-stoke-the-heart"]);async updateItem(source){if(this.itemsToSkip.has(source.system.slug??""))return;const{rules}=source.system;for(const rule of rules)isObject(rule)&&["damage","mundane-damage"].includes(String(rule.selector??""))&&(rule.selector="strike-damage")}};__name2(_Migration716StrikeDamageSelector,"Migration716StrikeDamageSelector"),__publicField(_Migration716StrikeDamageSelector,"version",.716);let Migration716StrikeDamageSelector=_Migration716StrikeDamageSelector;const _Migration717TakeFeatLimits=class extends MigrationBase{static{__name(this,"_Migration717TakeFeatLimits")}levelOneOnly=new Set(["celestial-eyes","chance-death","deliberate-death","elemental-eyes","eyes-of-the-night","fiendish-eyes","gravesight","willing-death"]);maxTakeable={"additional-lore":1/0,"advanced-domain":1/0,"advanced-general-training":1/0,"animal-senses":1/0,"animal-senses-darkvision":1/0,"animal-senses-low-light-vision":1/0,"animal-senses-scent-imprecise":1/0,"armor-proficiency":3,assurance:1/0,"automatic-knowledge":1/0,"blessing-of-the-sun-gods":1/0,"consult-the-spirits":1/0,"domain-initiate":1/0,"general-training":1/0,"greater-animal-senses":1/0,"greater-sun-blessing":1/0,"hellknight-order-cross-training":1/0,"living-weapon":1/0,"magic-arrow":1/0,"modular-dynamo":1/0,multilingual:1/0,"settlement-scholastics":1/0,"skill-training":1/0,"terrain-stalker":1/0};async updateItem(source){if(source.type!=="feat")return;const slug=source.system.slug??"";source.system.traits.value.includes("lineage")||this.levelOneOnly.has(slug)?source.system.onlyLevel1=!0:"game"in globalThis&&(source.system.onlyLevel1=!1),!source.system.onlyLevel1&&slug in this.maxTakeable?source.system.maxTakable=this.maxTakeable[slug]:"game"in globalThis&&(source.system.maxTakable=1)}};__name2(_Migration717TakeFeatLimits,"Migration717TakeFeatLimits"),__publicField(_Migration717TakeFeatLimits,"version",.717);let Migration717TakeFeatLimits=_Migration717TakeFeatLimits;function isEquipped(usage,equipped){return equipped.carryType==="dropped"?!1:usage.type==="carried"?!0:usage.type!==equipped.carryType||usage.type==="worn"&&usage.where&&!equipped.inSlot?!1:usage.type==="held"?(equipped.handsHeld??0)>=(usage.hands??1):!0}__name(isEquipped,"isEquipped"),__name2(isEquipped,"isEquipped");function getUsageDetails(usage){switch(usage){case"carried":case"":return{value:"carried",type:"carried"};case"held-in-one-hand":case"held-in-one-plus-hands":return{value:usage,type:"held",hands:1};case"held-in-two-hands":return{value:usage,type:"held",hands:2};case"worn":return{value:usage,type:"worn"};case"wornarmor":case"wornamulet":case"wornanklets":case"wornarmbands":case"wornbackpack":case"wornbarding":case"wornbelt":case"wornbeltpouch":case"wornbracers":case"wornbracelet":case"worncloak":case"worncirclet":case"wornclothing":case"worncollar":case"worncrown":case"wornepaulet":case"worneyepiece":case"wornfootwear":case"worngarment":case"worngloves":case"wornheadwear":case"wornmask":case"wornnecklace":case"wornonbelt":case"wornring":case"wornshoes":case"wornhorseshoes":case"wornsaddle":case"wornwrist":return{value:usage,type:"worn",where:usage.substring(4)}}return{value:usage,type:"worn"}}__name(getUsageDetails,"getUsageDetails"),__name2(getUsageDetails,"getUsageDetails");const _Migration718CarryType=class extends MigrationBase{static{__name(this,"_Migration718CarryType")}async updateItem(itemData,actor){if(!isPhysicalData(itemData))return;const systemData=itemData.system;if(systemData.usage instanceof Object||(systemData.usage={value:"held-in-one-hand"}),systemData.usage.value==="worn-gloves")systemData.usage.value="worngloves";else if(itemData.type==="armor"){const{category}=itemData.system;systemData.usage.value=category==="shield"?"held-in-one-hand":"wornarmor"}else itemData.type==="equipment"&&systemData.slug?.startsWith("clothing-")&&(systemData.usage.value="worn");if("game"in globalThis||actor)systemData.equipped??={carryType:"worn"},systemData.equipped.carryType??="worn";else{delete systemData.equipped;return}const equipped=systemData.equipped;if(!("value"in equipped))return;if(!(actor&&["character","npc"].includes(actor.type??""))){equipped["-=value"]=null,delete equipped.value;return}const containerId=itemData.system.containerId??{value:null};if(containerId instanceof Object&&containerId.value){const inStowingContainer=actor.items.some(i=>i.type==="backpack"&&i.system.stowing&&i._id===containerId.value);if(!inStowingContainer)containerId.value=null;else if(inStowingContainer){equipped.carryType="stowed";return}}equipped.carryType="worn";const usage=getUsageDetails(systemData.usage.value);usage.type==="worn"?equipped.inSlot=!!equipped.value:usage.type==="held"&&(equipped.value&&(equipped.carryType="held"),equipped.handsHeld=equipped.value?usage.hands??1:0),equipped["-=value"]=null,delete equipped.value}};__name2(_Migration718CarryType,"Migration718CarryType"),__publicField(_Migration718CarryType,"version",.718);let Migration718CarryType=_Migration718CarryType;const _Migration719ShrugFlanking=class extends MigrationBase{static{__name(this,"_Migration719ShrugFlanking")}async updateItem(source,actorSource){const slug=source.system.slug??"";switch(source.type){case"action":{if(slug==="all-around-vision")source.system.rules=[this.allAroundVision];else if(actorSource?.type==="npc"&&source.name==="Deny Advantage"){const npcId=actorSource.flags.core?.sourceId?.replace(/^Compendium\.[^.]+\./,"")??actorSource._id;if(this.needsDenyAdvantage(source.system.rules)){const rule=this.npcDenyAvantage(npcId);source.system.rules.push(rule)}}return}case"effect":{slug==="stance-wolf-stance"&&(source.system.rules=this.wolfStanceRules);return}case"feat":{source.system.slug=source.system.slug?.replace(/^deny-advantage-level-\d$/,"deny-advantage")??null;const featSlug=source.system.slug??"";if(["constant-gaze","deny-advantage"].includes(featSlug)&&this.needsDenyAdvantage(source.system.rules))source.system.rules.push(this.denyAdvantage);else if(featSlug==="gang-up")source.system.rules=[this.gangUp];else if(featSlug.startsWith("side-by-side")){const sideBySide=this.gangUp;sideBySide.value="animal-companion",source.system.rules=[sideBySide]}else if(["pack-tactics","squad-tactics"].includes(featSlug)){const tactics=this.gangUp;tactics.value=2,source.system.rules=[tactics]}}}}get allAroundVision(){return{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.flankable",value:!1}}get denyAdvantage(){return{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.flatFootable",value:"@actor.level"}}get gangUp(){return{key:"ActiveEffectLike",mode:"add",path:"system.attributes.flanking.canGangUp",value:1}}npcVariants=new Map([["YsBSkW3aFwU1bl3w",13],["0Kb4z4h8KVqfrIju",8],["B09JfuBZHjcRXztU",4],["aaDiR0EIWRQx8wdy",3],["x4m5ks6Rd8fYzXPm",4],["qKHkamxIPbqxEiwp",6],["lCvJquCqvZJVnafy",8],["vkLhqX5oR1t89puZ",7],["aIT5S2fKgMZ6pVP2",11],["l6EuZR6zCdqyCywW",6],["QKkvnlqrhgLHuP1t",10],["ZY3q7AV1qbwWwNl2",8],["6pPolNZycfDiOl2I",8],["cQMM2Ld0IBM9GcDo",11],["VkG5yl9xcmziwpQD",4],["JrowrtDilEG8dN2s",11],["1lkay2gwgEquq0NF",6],["EMl8hARVJk8SNVyW",4],["j31HXlZiUqQrAHSB",12],["pjnTEh0NVd1DB6jI",4]]);get wolfStanceRules(){return[{category:"unarmed",damage:{base:{damageType:"piercing",dice:1,die:"d8"}},group:"brawling",key:"Strike",label:"PF2E.SpecificRule.Stance.Attack.WolfJaws",range:null,slug:"wolf-jaws",traits:["agile","backstabber","finesse","unarmed","nonlethal"]},{definition:{all:["weapon:wolf-jaws"]},key:"AdjustStrike",mode:"add",predicate:{all:["self:flanking"]},property:"traits",value:"trip"}]}npcDenyAvantage(npcId=""){const{denyAdvantage}=this;return denyAdvantage.value=this.npcVariants.get(npcId)??"@actor.level",denyAdvantage}needsDenyAdvantage(rules){return!rules.some(r=>r.key==="ActiveEffectLike"&&r.path==="system.attributes.flanking.flatFootable")}};__name2(_Migration719ShrugFlanking,"Migration719ShrugFlanking"),__publicField(_Migration719ShrugFlanking,"version",.719);let Migration719ShrugFlanking=_Migration719ShrugFlanking;const _Migration720UpdateSpellDescriptions=class extends MigrationBase{static{__name(this,"_Migration720UpdateSpellDescriptions")}spellUUIDs=new Set(["Compendium.pf2e.spells-srd.GoKkejPj5yWJPIPK","Compendium.pf2e.spells-srd.1b55SgYTV65JvmQd","Compendium.pf2e.spells-srd.b515AZlB0sridKSq","Compendium.pf2e.spells-srd.NBSBFHxBm88qxQUy","Compendium.pf2e.spells-srd.9TauMFkIsmvKJNzZ","Compendium.pf2e.spells-srd.LoBjvguamA12iyW0","Compendium.pf2e.spells-srd.IWUe32Y5k2QFd7YQ","Compendium.pf2e.spells-srd.WBmvzNDfpwka3qT4"]);spells=UUIDUtils.fromUUIDs([...this.spellUUIDs]);async updateItem(source){if(!(source.type==="spell"&&setHasElement(this.spellUUIDs,source.flags.core?.sourceId)))return;const spell=(await this.spells).find(s=>s instanceof SpellPF2e&&s.slug===source.system.slug);spell&&(source.system.description.value=spell.description)}};__name2(_Migration720UpdateSpellDescriptions,"Migration720UpdateSpellDescriptions"),__publicField(_Migration720UpdateSpellDescriptions,"version",.72);let Migration720UpdateSpellDescriptions=_Migration720UpdateSpellDescriptions;const _Migration721SetReloadValues=class extends MigrationBase{static{__name(this,"_Migration721SetReloadValues")}toUpdate=new Set(["air-repeater","composite-longbow","composite-shortbow","godsbreath-bow","hunters-bow","long-air-repeater","longbow","oathbow","repeating-crossbow","repeating-hand-crossbow","shortbow","singing-shortbow-greater","singing-shortbow","sky-piercing-bow"]);async updateItem(source){source.type==="weapon"&&setHasElement(this.toUpdate,source.system.slug)&&(source.system.reload.value="0")}};__name2(_Migration721SetReloadValues,"Migration721SetReloadValues"),__publicField(_Migration721SetReloadValues,"version",.721);let Migration721SetReloadValues=_Migration721SetReloadValues;const _Migration722CraftingSystemData=class extends MigrationBase{static{__name(this,"_Migration722CraftingSystemData")}async updateActor(source){if(source.type!=="character")return;if(!isObject(source.system.crafting)){const filledCrafting={entries:{},formulas:[]};source.system.crafting=filledCrafting}const crafting=source.system.crafting??{};(!isObject(crafting.entries)||Array.isArray(crafting.entries))&&(crafting.entries={}),Array.isArray(crafting.formulas)||(crafting.formulas=[])}};__name2(_Migration722CraftingSystemData,"Migration722CraftingSystemData"),__publicField(_Migration722CraftingSystemData,"version",.722);let Migration722CraftingSystemData=_Migration722CraftingSystemData;const _Migration723CumulativeItemBonuses=class extends MigrationBase{static{__name(this,"_Migration723CumulativeItemBonuses")}stanceFeats=(async()=>(await UUIDUtils.fromUUIDs(["Compendium.pf2e.feats-srd.ZPclfDmiHzEqblry","Compendium.pf2e.feats-srd.ZL5UU9quCTvcWzfY","Compendium.pf2e.feats-srd.n2hawNmzW7DBn1Lm","Compendium.pf2e.feats-srd.hO4sKslTrSQMLbGx"])).filter(d=>d instanceof FeatPF2e&&!!d.slug).reduce((record,f)=>({...record,[f.slug]:f}),{}))();mountainPattern=/^mountain-(?:stance|stronghold|quake)$/;async updateActor(source){if(source.type!=="character")return;const effects=source.items.filter(i=>i.type==="effect");for(const effect of effects)effect.system.slug?.startsWith("stance-mountain")&&source.items.findSplice(i=>i===effect)}async updateItem(source){if(source.system.slug)switch(source.type){case"feat":{if(source.system.slug==="animal-skin"){const feat=(await this.stanceFeats)[source.system.slug];feat&&(source.system.rules=feat.toObject().system.rules)}else if(this.mountainPattern.test(source.system.slug)){const feat=(await this.stanceFeats)[source.system.slug];feat&&(source.system.description.value=feat.description)}return}case"equipment":{if(!source.system.slug.startsWith("bracers-of-armor-"))return;for(const rule of source.system.rules)rule.key==="FlatModifier"&&(rule.slug="bracers-of-armor");return}case"effect":{if(source.system.slug!=="spell-effect-mage-armor")return;for(const rule of source.system.rules)rule.key==="FlatModifier"&&(rule.slug="mage-armor")}}}async updateMacro(source){source.type==="script"&&source.command.includes("Stance: Mountain Stance")&&(source.command=String.raw`const actors = canvas.tokens.controlled.flatMap((token) => token.actor ?? []); + `},"askLevelPopupTemplate");function showXP(partyLevel,partySize,npcLevels,hazards){const xp=game.pf2e.gm.calculateXP(partyLevel,partySize,npcLevels,hazards,{proficiencyWithoutLevel:game.settings.get("pf2e","proficiencyVariant")});new Dialog({title:"XP",content:dialogTemplate(xp),buttons:{}}).render(!0)}__name(showXP,"showXP"),__name2(showXP,"showXP");function askPartyLevelAndSize(npcLevels,hazards){new Dialog({title:"Party Information",content:askLevelPopupTemplate,buttons:{no:{icon:'',label:"Cancel"},yes:{icon:'',label:"Calculate XP",callback:$html=>{const html=$html[0],partySize=Math.abs(Math.trunc(Number(htmlQuery(html,"[name=party-size]")?.value||1))),partyLevel=Math.abs(Math.trunc(Number(htmlQuery(html,"[name=party-level]")?.value||1)));localStorage.setItem("xpMacroPartySize",partySize.toString()),localStorage.setItem("xpMacroPartyLevel",partyLevel.toString()),showXP(partyLevel,partySize,npcLevels,hazards)}}},default:"yes"}).render(!0)}__name(askPartyLevelAndSize,"askPartyLevelAndSize"),__name2(askPartyLevelAndSize,"askPartyLevelAndSize");function xpFromEncounter(){const actors=canvas.tokens.controlled.flatMap(a=>a.actor??[]).filter(a=>!a.traits.has("minion")),npcLevels=getLevels(actors,"opposition"),pcLevels=getLevels(actors,"party"),hazards=getHazards(actors);if(npcLevels.length===0&&hazards.length===0){ui.notifications.error("You must select at least one opposition and/or hazard token and optionally all PC tokens");return}pcLevels.length===0?askPartyLevelAndSize(npcLevels,hazards):showXP(pcLevels[0],pcLevels.length,npcLevels,hazards)}__name(xpFromEncounter,"xpFromEncounter"),__name2(xpFromEncounter,"xpFromEncounter");const xpVariantCreatureDifferences=new Map([[-7,9],[-6,12],[-5,14],[-4,18],[-3,21],[-2,26],[-1,32],[0,40],[1,48],[2,60],[3,72],[4,90],[5,108],[6,135],[7,160]]),xpCreatureDifferences=new Map([[-4,10],[-3,15],[-2,20],[-1,30],[0,40],[1,60],[2,80],[3,120],[4,160]]),xpSimpleHazardDifferences=new Map([[-4,2],[-3,3],[-2,4],[-1,6],[0,8],[1,12],[2,16],[3,24],[4,32]]);function getXPFromMap(partyLevel,entityLevel,values){const difference2=entityLevel+1-(partyLevel+1),range=Math.floor(values.size/2),boundedDifference=Math.clamped(difference2,0-range,range);return values.get(boundedDifference)??0}__name(getXPFromMap,"getXPFromMap"),__name2(getXPFromMap,"getXPFromMap");function calculateCreatureXP(partyLevel,npcLevel,dcOptions){return dcOptions.proficiencyWithoutLevel?getXPFromMap(partyLevel,npcLevel,xpVariantCreatureDifferences):getXPFromMap(partyLevel,npcLevel,xpCreatureDifferences)}__name(calculateCreatureXP,"calculateCreatureXP"),__name2(calculateCreatureXP,"calculateCreatureXP");function getHazardXp(partyLevel,hazard,dcOptions){return hazard.isComplex?calculateCreatureXP(partyLevel,hazard.level,dcOptions):getXPFromMap(partyLevel,hazard.level,xpSimpleHazardDifferences)}__name(getHazardXp,"getHazardXp"),__name2(getHazardXp,"getHazardXp");function generateEncounterBudgets(partySize){const budget=partySize*20;return{trivial:Math.floor(budget*.5),low:Math.floor(budget*.75),moderate:budget,severe:Math.floor(budget*1.5),extreme:Math.floor(budget*2)}}__name(generateEncounterBudgets,"generateEncounterBudgets"),__name2(generateEncounterBudgets,"generateEncounterBudgets");const rewardEncounterBudgets=generateEncounterBudgets(4);function calculateEncounterRating(challenge,budgets){return challenge<=budgets.trivial?"trivial":challenge<=budgets.low?"low":challenge<=budgets.moderate?"moderate":challenge<=budgets.severe?"severe":"extreme"}__name(calculateEncounterRating,"calculateEncounterRating"),__name2(calculateEncounterRating,"calculateEncounterRating");function calculateXP(partyLevel,partySize,npcLevels,hazards,dcOptions){const creatureChallenge=npcLevels.map(level=>calculateCreatureXP(partyLevel,level,dcOptions)).reduce((a,b)=>a+b,0),hazardChallenge=hazards.map(hazard=>getHazardXp(partyLevel,hazard,dcOptions)).reduce((a,b)=>a+b,0),totalXP=creatureChallenge+hazardChallenge,encounterBudgets=generateEncounterBudgets(partySize),rating=calculateEncounterRating(totalXP,encounterBudgets),ratingXP=rewardEncounterBudgets[rating];return{partyLevel,partySize,totalXP,encounterBudgets,rating,ratingXP,xpPerPlayer:Math.floor(totalXP/partySize*4)}}__name(calculateXP,"calculateXP"),__name2(calculateXP,"calculateXP");const _EncounterPF2e=class extends Combat{static{__name(this,"_EncounterPF2e")}_sortCombatants(a,b){const resolveTie=__name2(()=>{const[priorityA,priorityB]=[a,b].map(combatant=>combatant.overridePriority(combatant.initiative??0)??(combatant.actor?.system.attributes.initiative?combatant.actor.system.attributes.initiative.tiebreakPriority:3));return priorityA===priorityB?a.id.localeCompare(b.id):priorityA-priorityB},"resolveTie");return typeof a.initiative=="number"&&typeof b.initiative=="number"&&a.initiative===b.initiative?resolveTie():super._sortCombatants(a,b)}getCombatantWithHigherInit(a,b){const sortResult=this._sortCombatants(a,b);return sortResult>0?b:sortResult<0?a:null}analyze(){if(!game.ready)return null;const{party}=game.actors,partyMembers=party?.members.filter(a=>a.alliance==="party"&&isReallyPC(a))??[],fightyPartyMembers=(()=>{const inEncounter=partyMembers.filter(m=>m.combatant?.encounter===this);return inEncounter.length>0?inEncounter:partyMembers})(),opposition=uniq(this.combatants.filter(c=>!!(c.actor?.alliance==="opposition"||c.actor?.isOfType("hazard"))&&!partyMembers.includes(c.actor)).flatMap(c=>c.actor??[]));if(!party||fightyPartyMembers.length===0||opposition.length===0)return null;const partyLevel=Math.round(meanBy(fightyPartyMembers.filter(m=>m.isOfType("character")),m=>m.level)),result=calculateXP(partyLevel,fightyPartyMembers.length,opposition.filter(e=>e.isOfType("character","npc")).map(e=>e.level),opposition.filter(e=>e.isOfType("hazard")),{proficiencyWithoutLevel:game.settings.get("pf2e","proficiencyVariant")}),threat=result.rating,budget={spent:result.totalXP,max:result.encounterBudgets[threat],partyLevel},award={xp:Math.floor(result.xpPerPlayer*(fightyPartyMembers.length/partyMembers.length)),recipients:partyMembers};return{threat,budget,award,participants:{party:fightyPartyMembers,opposition}}}prepareDerivedData(){super.prepareDerivedData(),this.metrics=this.analyze()}async createEmbeddedDocuments(embeddedName,data,context={}){const createData=data.filter(datum=>{const token=canvas.tokens.placeables.find(canvasToken=>canvasToken.id===datum.tokenId);if(!token)return!1;const{actor}=token;if(!actor)return ui.notifications.warn(`${token.name} has no associated actor.`),!1;const actorTraits=actor.traits;if(actor.type==="loot"||["minion","eidolon"].some(t=>actorTraits.has(t))){const actorTypes2=CONFIG.PF2E.actorTypes,type=game.i18n.localize(actorTraits.has("minion")?CONFIG.PF2E.creatureTraits.minion:actorTraits.has("eidolon")?CONFIG.PF2E.creatureTraits.eidolon:actorTypes2[actor.type]);return ui.notifications.info(game.i18n.format("PF2E.Encounter.ExcludingFromInitiative",{type,actor:actor.name})),!1}return!0});return super.createEmbeddedDocuments(embeddedName,createData,context)}async rollInitiative(ids,options={}){const extraRollOptions=options.extraRollOptions??[],rollMode=options.messageOptions?.rollMode??options.rollMode;options.secret&&extraRollOptions.push("secret");const fightyCombatants=ids.flatMap(id=>this.combatants.get(id)??[]).filter(c=>!!c.actor?.initiative),initiatives=(await Promise.all(fightyCombatants.map(async combatant=>combatant.actor?.initiative?.roll({...options,combatant,extraRollOptions,updateTracker:!1,rollMode})??null))).flatMap(result=>result?{id:result.combatant.id,value:result.roll.total,statistic:result.roll.options.domains?.find(s=>setHasElement(SKILL_LONG_FORMS,s)||s==="perception")??null}:[]);await this.setMultipleInitiatives(initiatives);const remainingIds=ids.filter(id=>!fightyCombatants.some(c=>c.id===id));return super.rollInitiative(remainingIds,options)}async setMultipleInitiatives(initiatives){const currentId=this.combatant?.id,updates=initiatives.map(i=>({_id:i.id,initiative:i.value,flags:{pf2e:{initiativeStatistic:i.statistic??null,overridePriority:{[i.value]:i.overridePriority}}}}));await this.updateEmbeddedDocuments("Combatant",updates),await this.update({turn:this.turns.findIndex(c=>c.id===currentId)})}async setInitiative(id,value){const combatant=this.combatants.get(id,{strict:!0});if(combatant.actor?.isOfType("character","npc"))return this.setMultipleInitiatives([{id:combatant.id,value,statistic:combatant.actor.attributes.initiative.statistic||"perception"}]);super.setInitiative(id,value)}async resetActors(){const actors=this.combatants.contents.flatMap(c=>c.actor??[]);resetActors(actors,{rerender:!1})}_onCreate(data,options,userId){super._onCreate(data,options,userId);const pcSheets=Object.values(ui.windows).filter(sheet=>sheet.constructor.name==="CharacterSheetPF2e");for(const sheet of pcSheets)sheet.toggleInitiativeLink()}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId),game.pf2e.StatusEffects.onUpdateEncounter(this);const{combatant,previous}=this,actor=combatant?.actor;if(!this.started)return;const[newRound,newTurn]=[changed.round,changed.turn],isRoundChange=typeof newRound=="number",isTurnChange=typeof newTurn=="number",isNextRound=isRoundChange&&(previous.round===null||newRound>previous.round),isNextTurn=isTurnChange&&(previous.turn===null||newTurn>previous.turn);(isRoundChange||isTurnChange)&&Promise.resolve().then(async()=>{if(isNextRound||isNextTurn){const previousCombatant=this.combatants.get(previous.combatantId??"");if(game.user===previousCombatant?.actor?.primaryUpdater){const alreadyWent=previousCombatant.flags.pf2e.roundOfLastTurnEnd===previous.round;typeof previous.round=="number"&&!alreadyWent&&await previousCombatant.endTurn({round:previous.round})}if(game.user===actor?.primaryUpdater){const alreadyWent=combatant?.roundOfLastTurn===this.round;combatant&&!alreadyWent&&await combatant.startTurn()}}this.resetActors(),await game.pf2e.effectTracker.refresh(),game.pf2e.effectPanel.refresh()})}_onDelete(options,userId){if(super._onDelete(options,userId),this.started&&(Hooks.callAll("pf2e.endTurn",this.combatant??null,this,userId),game.pf2e.effectTracker.onEncounterEnd(this)),!game.combat){const pcSheets=Object.values(ui.windows).filter(sheet=>sheet.constructor.name==="CharacterSheetPF2e");for(const sheet of pcSheets)sheet.toggleInitiativeLink()}game.user.clearTargets(),this.resetActors()}async _manageTurnEvents(adjustedTurn){if(this.previous||game.release.generation>11)return super._manageTurnEvents(adjustedTurn)}};__name2(_EncounterPF2e,"EncounterPF2e");let EncounterPF2e=_EncounterPF2e;const _CombatantPF2e=class extends Combatant{static{__name(this,"_CombatantPF2e")}get encounter(){return this.parent}get roundOfLastTurn(){return this.flags.pf2e.roundOfLastTurn}get playersCanSeeName(){return!!this.token?.playersCanSeeName}overridePriority(initiative){return this.flags.pf2e.overridePriority[initiative]??null}hasHigherInitiative({than}){if(this.parent.id!==than.parent.id)throw ErrorPF2e("The initiative of Combatants from different combats cannot be compared");return this.parent.getCombatantWithHigherInit(this,than)===this}static async fromActor(actor,render=!0,options={}){if(!game.combat)return ui.notifications.error(game.i18n.localize("PF2E.Encounter.NoActiveEncounter")),null;const token=actor.getActiveTokens().pop(),existing=game.combat.combatants.find(combatant=>combatant.actor===actor);return existing||(token?(await(options.combat??game.combat).createEmbeddedDocuments("Combatant",[{tokenId:token.id,actorId:token.actor?.id,sceneId:token.scene.id,hidden:token.document.hidden}],{render})).at(0)??null:(ui.notifications.error(game.i18n.format("PF2E.Encounter.NoTokenInScene",{actor:actor.name})),null))}static async createDocuments(data=[],context={}){const entries=data.map(d=>({token:(d.sceneId?game.scenes.get(d.sceneId):context.parent?.scene)?.tokens.get(d.tokenId??"")||null,data:d})),tokens=entries.map(e=>e.token);for(const token of tokens)token?.actor?.isOfType("party")&&await token?.actor.addToCombat({combat:context.parent});const nonPartyData=entries.filter(e=>!e.token?.actor?.isOfType("party")).map(e=>e.data);return super.createDocuments(nonPartyData,context)}async startTurn(){const{actor,encounter}=this;if(!encounter||!actor)return;const actorUpdates={};for(const rule of actor.rules)await rule.onTurnStart?.(actorUpdates);await this.update({"flags.pf2e.roundOfLastTurn":encounter.round}),Object.keys(actorUpdates).length>0&&await actor.update(actorUpdates);for(const effect of actor.itemTypes.effect)await effect.onTurnStartEnd("start");if(actor.isOfType("character")&&actor.familiar)for(const effect of actor.familiar.itemTypes.effect)await effect.onTurnStartEnd("start");Hooks.callAll("pf2e.startTurn",this,encounter,game.user.id)}async endTurn(options){const round=options.round,{actor,encounter}=this;if(!encounter||!actor)return;const activeConditions=actor.conditions.active;for(const condition of activeConditions)await condition.onEndTurn({token:this.token});for(const effect of actor.itemTypes.effect)await effect.onTurnStartEnd("end");if(actor.isOfType("character")&&actor.familiar)for(const effect of actor.familiar.itemTypes.effect)await effect.onTurnStartEnd("end");await this.update({"flags.pf2e.roundOfLastTurnEnd":round}),Hooks.callAll("pf2e.endTurn",this,encounter,game.user.id)}prepareBaseData(){super.prepareBaseData(),this.flags.pf2e=mergeObject(this.flags.pf2e??{},{overridePriority:{}}),this.flags.pf2e.roundOfLastTurn??=null,this.flags.pf2e.initiativeStatistic??=null}async toggleDefeated({to=!this.isDefeated}={}){to!==this.isDefeated&&(await this.update({defeated:to}),await this.token?.object?.toggleEffect(game.settings.get("pf2e","deathIcon"),{active:to,overlay:!0}),this.isDefeated&&this.token?.object?.isTargeted&&this.token.object.setTarget(!1,{releaseOthers:!1}))}updateResource(){return this.isNPC&&!game.user.isGM?this.resource=null:super.updateResource()}_getInitiativeFormula(){const{actor}=this;if(!actor)return"1d20";let bonus=0;return typeof actor.attributes.initiative?.totalModifier=="number"?bonus=actor.attributes.initiative.totalModifier:actor.attributes.perception&&(bonus=actor.attributes.perception.value),["1d20",bonus||0].join("+")}async toggleNameVisibility(){if(!this.token)return;const currentVisibility=this.token.displayName,visibilityToggles={[CONST.TOKEN_DISPLAY_MODES.ALWAYS]:CONST.TOKEN_DISPLAY_MODES.OWNER,[CONST.TOKEN_DISPLAY_MODES.CONTROL]:CONST.TOKEN_DISPLAY_MODES.HOVER,[CONST.TOKEN_DISPLAY_MODES.HOVER]:CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,[CONST.TOKEN_DISPLAY_MODES.NONE]:CONST.TOKEN_DISPLAY_MODES.HOVER,[CONST.TOKEN_DISPLAY_MODES.OWNER]:CONST.TOKEN_DISPLAY_MODES.ALWAYS,[CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER]:CONST.TOKEN_DISPLAY_MODES.HOVER};await this.token.update({displayName:visibilityToggles[currentVisibility]})}_onUpdate(changed,options,userId){if(super._onUpdate(changed,options,userId),this.encounter?.started&&typeof changed.initiative=="number"&&this.encounter.resetActors(),changed.defeated&&game.user.id===userId)for(const action2 of this.actor?.itemTypes.action??[])action2.system.deathNote&&action2.toMessage(void 0,{rollMode:this.actor?.hasPlayerOwner?"publicroll":"gmroll"})}_onDelete(options,userId){super._onDelete(options,userId),this.encounter?.started&&this.encounter.resetActors()}};__name2(_CombatantPF2e,"CombatantPF2e");let CombatantPF2e=_CombatantPF2e;const _ActorInitiative=class{static{__name(this,"_ActorInitiative")}actor;statistic;get attribute(){return this.statistic.attribute}get ability(){return foundry.utils.logCompatibilityWarning("`ActorInitiative#ability` is deprecated. Use `ActorInitiative#attribute` instead.",{since:"5.3.0",until:"6.0.0"}),this.attribute}constructor(actor){this.actor=actor;const initiativeSkill=actor.isOfType("hazard")?"stealth":actor.isOfType("character","npc")?actor.attributes.initiative?.statistic||"perception":null,base=initiativeSkill?actor.getStatistic(initiativeSkill):null,ponderousPenalty=actor.isOfType("character")?createPonderousPenalty(actor):null,rollLabel=game.i18n.format("PF2E.InitiativeWithSkill",{skillName:base?.label??""}),data={slug:"initiative",label:base?.label??"PF2E.InitiativeLabel",domains:["initiative"],rollOptions:[base?.slug??[]].flat(),check:{type:"initiative",label:rollLabel},modifiers:[ponderousPenalty??[]].flat()};this.statistic=base?base.extend(data):new Statistic(actor,data)}async roll(args={}){const combatant=args.combatant?.actor===this.actor?args.combatant:await CombatantPF2e.fromActor(this.actor,!1);if(!combatant)return null;combatant.hidden&&(args.rollMode=CONST.DICE_ROLL_MODES.PRIVATE);const roll=await this.statistic.roll(args);return roll?((args.updateTracker??!0)&&combatant.encounter.setInitiative(combatant.id,roll.total),{combatant,roll}):(game.combats.render(!1),null)}getTraceData(){const initiativeData=this.actor.attributes.initiative,tiebreakPriority=initiativeData?.tiebreakPriority??0;return{...this.statistic.getTraceData(),statistic:initiativeData?.statistic??"perception",tiebreakPriority}}};__name2(_ActorInitiative,"ActorInitiative");let ActorInitiative=_ActorInitiative;const _CreatureSizeRuleElement=class _CreatureSizeRuleElement2 extends RuleElementPF2e{static{__name(this,"_CreatureSizeRuleElement")}constructor(data,options){super(data,options),__privateAdd(this,_getReach),typeof this.value=="string"||typeof this.value=="number"||this.isBracketedValue(this.value)||this.failValidation("value must be a number, string, or bracketed value")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1}),reach:new RecordField(new fields2.StringField({required:!0,nullable:!1,choices:["add","upgrade","override"]}),new ResolvableValueField({required:!0,nullable:!1}),{required:!1,nullable:!1,initial:void 0}),resizeEquipment:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0}),minimumSize:new fields2.StringField({required:!1,nullable:!1,choices:SIZES,initial:void 0}),maximumSize:new fields2.StringField({required:!1,nullable:!1,choices:SIZES,initial:void 0})}}incrementSize(size,amount){return amount===0?size:this.incrementSize(_CreatureSizeRuleElement2.incrementMap[size],amount-1)}decrementSize(size,amount){return amount===0?size:this.decrementSize(_CreatureSizeRuleElement2.decrementMap[size],amount-1)}beforePrepareData(){if(!this.test())return;const value=this.resolveValue(this.value);if(!(typeof value=="string"||typeof value=="number")){this.failValidation(`CreatureSize Rule Element on actor ${this.actor.id} (${this.actor.name})`,"has a non-string, non-numeric value");return}const size=_CreatureSizeRuleElement2.wordToAbbreviation[value]??value;if(typeof size=="string"&&!tupleHasValue(SIZES,size)){this.failValidation(`"${size}" is not a recognized size`);return}const{actor}=this,originalSize=new ActorSizePF2e({value:actor.size});if(value===1){if(this.maximumSize&&!originalSize.isSmallerThan(this.maximumSize))return;actor.system.traits.size.increment()}else if(value===-1){if(this.minimumSize&&!originalSize.isLargerThan(this.minimumSize))return;actor.system.traits.size.decrement()}else if(tupleHasValue(SIZES,size))actor.system.traits.size=new ActorSizePF2e({value:size});else{const validValues=Array.from(new Set(Object.entries(_CreatureSizeRuleElement2.wordToAbbreviation).flat())).join('", "');this.failValidation(`CreatureSize Rule Element on actor ${actor.id} (${actor.name})`,`has an invalid value: must be one of "${validValues}", +1, or -1`);return}const{reach}=actor.system.attributes;if(reach.base=__privateMethod(this,_getReach,getReach_fn).call(this,originalSize),reach.manipulate=Math.max(reach.manipulate,reach.base),this.resizeEquipment){const sizeDifference=originalSize.difference(actor.system.traits.size,{smallIsMedium:!0});for(const item of actor.inventory.filter(i=>!(i instanceof TreasurePF2e&&i.isCoinage)))sizeDifference<0?item.system.size=this.incrementSize(item.size,Math.abs(sizeDifference)):sizeDifference>0&&(item.system.size=this.decrementSize(item.size,Math.abs(sizeDifference)))}}};_getReach=new WeakSet,getReach_fn=__name2(function(originalSize){const current=this.actor.attributes.reach.base;if(this.reach){const changeValue=(()=>{const resolved=this.resolveValue(this.reach.add??this.reach.upgrade??this.reach.override);return Math.trunc(Math.abs(Number(resolved)))})();if(!Number.isInteger(changeValue))return current;if(this.reach.add)return current+changeValue;if(this.reach.upgrade)return Math.max(current,changeValue);if(this.reach.override)return changeValue}const newSize=this.actor.system.traits.size;return newSize.isLargerThan(originalSize)?Math.max(SIZE_TO_REACH[this.actor.size],current):newSize.isSmallerThan(originalSize)?Math.min(SIZE_TO_REACH[this.actor.size],current):current},"#getReach"),__name2(_CreatureSizeRuleElement,"CreatureSizeRuleElement"),__publicField(_CreatureSizeRuleElement,"validActorTypes",["character","npc","familiar"]),__publicField(_CreatureSizeRuleElement,"wordToAbbreviation",{tiny:"tiny",small:"sm",medium:"med",large:"lg",huge:"huge",gargantuan:"grg"}),__publicField(_CreatureSizeRuleElement,"incrementMap",{tiny:"sm",sm:"med",med:"lg",lg:"huge",huge:"grg",grg:"grg"}),__publicField(_CreatureSizeRuleElement,"decrementMap",{tiny:"tiny",sm:"tiny",med:"sm",lg:"med",huge:"lg",grg:"huge"});let CreatureSizeRuleElement=_CreatureSizeRuleElement;const _IWRRuleElement=class extends RuleElementPF2e{static{__name(this,"_IWRRuleElement")}constructor(){super(...arguments),__privateAdd(this,_isValid)}static get dictionary(){return{}}static defineSchema(){const{fields:fields2}=foundry.data,{DataModelValidationFailure}=foundry.data.validation;return{...super.defineSchema(),mode:new fields2.StringField({required:!0,choices:["add","remove"],initial:"add"}),type:new fields2.ArrayField(new StrictStringField({required:!0,blank:!1,initial:void 0}),{validate:v=>Array.isArray(v)&&v.length>0||new DataModelValidationFailure({message:"must have at least one"})}),definition:new PredicateField({required:!1,initial:void 0}),exceptions:this.createExceptionsField(),override:new fields2.BooleanField}}static createExceptionsField(types){const customExceptionField=new foundry.data.fields.SchemaField({definition:new PredicateField({initial:void 0}),label:new StrictStringField({required:!0,blank:!1,initial:void 0})},{required:!0,initial:void 0}),exceptionField=new DataUnionField([new StrictStringField({required:!0,blank:!1,initial:void 0,choices:types}),customExceptionField],{required:!0,nullable:!1,initial:void 0});return new StrictArrayField(exceptionField)}static validateJoint(source){if(super.validateJoint(source),source.type.some(t=>t==="custom")){if(source.type.length>1)throw Error(' type: "custom" may not be included among other types');if(!source.definition)throw Error(" definition: must be present if defining a custom type")}else if(source.definition)throw Error(" definition: may only be present if defining a custom type");if(source.mode==="remove"&&source.exceptions.length>0)throw Error(' exceptions: may not be included with a mode of "remove"')}afterPrepareData(){if(!this.test())return;this.type=this.resolveInjectedProperties(this.type);const value=Math.floor(Number(this.resolveValue(this.value)));if(__privateMethod(this,_isValid,isValid_fn).call(this,value))if(this.mode==="add")this.property.push(...this.getIWR(value));else for(const toRemove of this.type)this.property.findSplice(iwr=>iwr.type===toRemove)}};_isValid=new WeakSet,isValid_fn=__name2(function(value){const{dictionary}=this.constructor,unrecognizedTypes=this.type.filter(t=>!(t in dictionary));if(unrecognizedTypes.length>0){for(const type of unrecognizedTypes)this.failValidation(`Type "${type}" is unrecognized`);return!1}return this.mode==="add"&&dictionary!==CONFIG.PF2E.immunityTypes&&(typeof value!="number"||value<0)?(this.failValidation("A `value` must be a positive number"),!1):!0},"#isValid"),__name2(_IWRRuleElement,"IWRRuleElement");let IWRRuleElement=_IWRRuleElement;const _ImmunityRuleElement=class extends IWRRuleElement{static{__name(this,"_ImmunityRuleElement")}value=null;static defineSchema(){return{...super.defineSchema(),exceptions:this.createExceptionsField(this.dictionary)}}static get dictionary(){return CONFIG.PF2E.immunityTypes}get property(){return this.actor.system.attributes.immunities}getIWR(){return this.type.map(t=>new Immunity({type:t,customLabel:t==="custom"?this.label:null,definition:this.definition,exceptions:this.exceptions,source:this.item.name})).filter(immunity=>{const existing=this.property.find(e=>e.type===immunity.type);return this.mode==="remove"||!(existing?.type===immunity.type&&existing.exceptions.every(x=>immunity.exceptions.includes(x)))})}};__name2(_ImmunityRuleElement,"ImmunityRuleElement");let ImmunityRuleElement=_ImmunityRuleElement;const _ResistanceRuleElement=class extends IWRRuleElement{static{__name(this,"_ResistanceRuleElement")}static defineSchema(){return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0}),exceptions:this.createExceptionsField(this.dictionary),doubleVs:this.createExceptionsField(this.dictionary)}}static get dictionary(){return CONFIG.PF2E.resistanceTypes}get property(){return this.actor.system.attributes.resistances}getIWR(value){if(value<=0)return[];const resistances=this.property;for(const resistanceType of[...this.type]){const current=resistances.find(r=>r.type===resistanceType);current&&(this.override?resistances.splice(resistances.indexOf(current),1):this.mode!=="remove"&&(current.value=Math.max(current.value,value),current.source=this.label,this.type.splice(this.type.indexOf(resistanceType),1)))}return this.type.map(t=>new Resistance({type:t,value,customLabel:t==="custom"?this.label:null,definition:this.definition,exceptions:this.exceptions,doubleVs:this.doubleVs,source:this.item.name}))}};__name2(_ResistanceRuleElement,"ResistanceRuleElement");let ResistanceRuleElement=_ResistanceRuleElement;const _WeaknessRuleElement=class extends IWRRuleElement{static{__name(this,"_WeaknessRuleElement")}static defineSchema(){return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0}),exceptions:this.createExceptionsField(this.dictionary)}}static get dictionary(){return CONFIG.PF2E.weaknessTypes}get property(){return this.actor.system.attributes.weaknesses}getIWR(value){if(value<=0)return[];const weaknesses=this.property;for(const weaknessType of[...this.type]){const current=weaknesses.find(w=>w.type===weaknessType);current&&(this.override?weaknesses.splice(weaknesses.indexOf(current),1):this.mode!=="remove"&&(current.value=Math.max(current.value,value),current.source=this.label,this.type.splice(this.type.indexOf(weaknessType),1)))}return this.type.map(t=>new Weakness({type:t,customLabel:t==="custom"?this.label:null,definition:this.definition,value,exceptions:this.exceptions,source:this.item.name}))}};__name2(_WeaknessRuleElement,"WeaknessRuleElement");let WeaknessRuleElement=_WeaknessRuleElement;const _SenseRuleElement=class extends RuleElementPF2e{static{__name(this,"_SenseRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,nullable:!1,choices:[...SENSE_TYPES]}),force:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),acuity:new fields2.StringField({required:!1,nullable:!1,choices:SENSE_ACUITIES,initial:void 0}),range:new ResolvableValueField({required:!1,nullable:!1,initial:void 0})}}constructor(data,options){data.selector&&(data.label??=CONFIG.PF2E.senses[data.selector]),super(data,options)}beforePrepareData(){if(this.ignored)return;const range=this.resolveValue(this.range,""),newSense=new CreatureSensePF2e({type:this.selector,acuity:this.acuity,value:String(range),source:this.item.name});this.actor.synthetics.senses.push({sense:newSense,predicate:this.predicate,force:this.force})}};__name2(_SenseRuleElement,"SenseRuleElement"),__publicField(_SenseRuleElement,"validActorTypes",["character","familiar"]);let SenseRuleElement=_SenseRuleElement;const _StrikeRuleElement=class extends RuleElementPF2e{static{__name(this,"_StrikeRuleElement")}constructor(source,options){source.img??=source.fist?"icons/skills/melee/unarmed-punch-fist.webp":options.parent.img,super(source,options),__privateAdd(this,_constructWeapon),this.fist&&(this.label=game.i18n.localize("PF2E.Weapon.Base.fist")),this.slug??=sluggify(this.label),this.battleForm??=!1,this.fist??=!1,this.options??=[]}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),category:new fields2.StringField({required:!0,blank:!1,choices:CONFIG.PF2E.weaponCategories,initial:"unarmed"}),group:new fields2.StringField({required:!0,nullable:!0,blank:!1,choices:CONFIG.PF2E.weaponGroups,initial:null}),baseType:new fields2.StringField({required:!0,nullable:!0,blank:!1,choices:CONFIG.PF2E.baseWeaponTypes,initial:null}),traits:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,choices:CONFIG.PF2E.npcAttackTraits})),traitToggles:new fields2.SchemaField({modular:new fields2.StringField({required:!0,blank:!1,nullable:!0,choices:CONFIG.PF2E.damageTypes,initial:null}),versatile:new fields2.StringField({required:!0,blank:!1,nullable:!0,choices:CONFIG.PF2E.damageTypes,initial:null})},{required:!0,nullable:!1,initial:{modular:null,versatile:null}}),otherTags:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,choices:CONFIG.PF2E.otherWeaponTags}),{required:!1,nullable:!1,initial:[]}),range:new fields2.SchemaField({increment:new fields2.NumberField({required:!1,integer:!0,min:5,nullable:!0,initial:5}),max:new fields2.NumberField({required:!1,integer:!0,min:5,nullable:!0,initial:null})},{required:!1,nullable:!0,initial:null}),damage:new fields2.SchemaField({base:new fields2.SchemaField({damageType:new fields2.StringField({required:!0,blank:!1,initial:"bludgeoning"}),dice:new ResolvableValueField({required:!0,nullable:!1,initial:1}),die:new fields2.StringField({required:!0,choices:CONFIG.PF2E.damageDie,initial:"d4"}),modifier:new fields2.NumberField({nullable:!1,integer:!0,initial:0})})}),img:new fields2.FilePathField({categories:["IMAGE"],nullable:!1,initial:()=>"systems/pf2e/icons/default-icons/melee.svg"}),attackModifier:new fields2.NumberField({integer:!0,positive:!0,nullable:!0,initial:null}),replaceAll:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0}),replaceBasicUnarmed:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0}),battleForm:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0}),ability:new fields2.StringField({required:!1,blank:!1,choices:CONFIG.PF2E.abilities,nullable:!0,initial:null}),options:new fields2.ArrayField(new fields2.StringField,{required:!1,initial:void 0}),fist:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0})}}validate(options){return(options?.changes??this._source).fist===!0?!0:super.validate(options)}_initializeSource(source,options){return"fist"in source&&source.fist===!0?source:super._initializeSource(source,options)}_initialize(options){this._source.fist?(this.key="Strike",this.priority=99,this.slug="fist",this.img=this._source.img,this.category="unarmed",this.group="brawling",this.baseType="fist",this.traits=["agile","finesse","nonlethal"],this.traitToggles=mergeObject({modular:null,versatile:null},this._source.traitToggles??{}),this.otherTags=[],this.range=null,this.damage={base:{dice:1,die:"d4",damageType:"bludgeoning",modifier:0}},this.battleForm=!1,this.fist=!0,this.replaceAll=!1,this.replaceBasicUnarmed=!1,this.predicate=new PredicatePF2e([...this._source.predicate??[],{gt:["hands-free",0]}])):super._initialize(options)}beforePrepareData(){if(this.ignored)return;const predicatePassed=this.predicate.length===0||(()=>{const rollOptions=new Set(this.actor.getRollOptions(["attack","attack-roll","strike-attack-roll"]));return this.resolveInjectedProperties(this.predicate).test(rollOptions)})(),damageType=this.resolveInjectedProperties(this.damage.base.damageType);if(!objectHasKey(CONFIG.PF2E.damageTypes,damageType))return this.failValidation("Unrecognized damage type");const dice=(()=>{const resolvedDice=Number(this.resolveValue(this.damage.base.dice));return Math.clamped(Math.trunc(resolvedDice),0,8)})();if(Number.isNaN(dice))return this.failValidation("dice does not resolve to a number");if(predicatePassed){const weapon=__privateMethod(this,_constructWeapon,constructWeapon_fn).call(this,damageType,dice),slug=weapon.slug??sluggify(weapon.name);this.actor.synthetics.strikes.set(slug,weapon)}}afterPrepareData(){if(!(this.ignored||!this.actor.isOfType("character")))if(this.replaceAll){const systemData=this.actor.system;systemData.actions=systemData.actions.filter(a=>a.item.id===this.item.id&&a.item.name===this.label&&a.item.group===this.group)}else this.replaceBasicUnarmed&&this.actor.system.actions.findSplice(a=>a.item?.slug==="basic-unarmed")}async toggleTrait({trait,selection}){const ruleSources=deepClone(this.item._source.system.rules),rule=ruleSources.at(this.sourceIndex??NaN);rule?.key==="Strike"&&(rule.traitToggles={...this.traitToggles,[trait]:selection},await this.item.update({"system.rules":ruleSources}))}};_constructWeapon=new WeakSet,constructWeapon_fn=__name2(function(damageType,dice){const actorIsNPC=this.actor.isOfType("npc"),source=deepClone({_id:this.item.id,name:this.label,type:"weapon",img:this.img,flags:{pf2e:{battleForm:this.battleForm,fixedAttack:actorIsNPC?this.attackModifier??null:null}},system:{slug:this.slug,description:{value:""},category:this.category,group:this.group,baseItem:this.baseType,attribute:this.ability,bonus:{value:actorIsNPC?this.attackModifier??0:0},damage:{...this.damage.base,dice,damageType},range:this.range?.increment??null,maxRange:this.range?.max??null,traits:{value:this.traits,otherTags:this.otherTags,rarity:"common",toggles:{modular:{selection:this.traitToggles.modular},versatile:{selection:this.traitToggles.versatile}}},options:{value:this.options},usage:{value:"held-in-one-hand"},equipped:{carryType:"held",handsHeld:1}}});return new WeaponPF2e(source,{parent:this.actor})},"#constructWeapon"),__name2(_StrikeRuleElement,"StrikeRuleElement"),__publicField(_StrikeRuleElement,"validActorTypes",["character","npc"]);let StrikeRuleElement=_StrikeRuleElement;const _TempHPRuleElement=class extends RuleElementPF2e{static{__name(this,"_TempHPRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1}),events:new StrictSchemaField({onCreate:new fields2.BooleanField({required:!1,nullable:!1}),onTurnStart:new fields2.BooleanField({required:!1,nullable:!1})},{required:!0,nullable:!1,initial:{onCreate:!0,onTurnStart:!1}})}}onCreate(actorUpdates){if(this.ignored||!this.events.onCreate)return;const updatedActorData=mergeObject(this.actor._source,actorUpdates,{inplace:!1}),value=this.resolveValue(this.value),rollOptions=Array.from(new Set([...this.actor.getRollOptions(),...this.actor.itemTypes.weapon.flatMap(w=>w.isEquipped?w.getRollOptions("self:weapon"):[])]));if(!this.test(rollOptions))return;if(typeof value!="number")return this.failValidation("Temporary HP requires a non-zero value field");const currentTempHP=Number(getProperty(updatedActorData,"system.attributes.hp.temp"))||0;value>currentTempHP&&(mergeObject(actorUpdates,{"system.attributes.hp.temp":value,"system.attributes.hp.tempsource":this.item.id}),this.broadcast(value,currentTempHP))}onTurnStart(actorUpdates){if(this.ignored||!this.events.onTurnStart)return;const rollOptions=Array.from(new Set([...this.actor.getRollOptions(["all"]),...this.actor.itemTypes.weapon.flatMap(w=>w.isEquipped?w.getRollOptions("self:weapon"):[])]));if(!this.test(rollOptions))return;const value=this.resolveValue(this.value);if(typeof value!="number")return this.failValidation("Temporary HP requires a non-zero value field");const updatedActorData=mergeObject(this.actor._source,actorUpdates,{inplace:!1}),currentTempHP=Number(getProperty(updatedActorData,"system.attributes.hp.temp"))||0;value>currentTempHP&&(actorUpdates["system.attributes.hp.temp"]=value,this.broadcast(value,currentTempHP))}onDelete(actorUpdates){const updatedActorData=mergeObject(this.actor._source,actorUpdates,{inplace:!1});if(getProperty(updatedActorData,"system.attributes.hp.tempsource")===this.item.id){mergeObject(actorUpdates,{"system.attributes.hp.temp":0});const hpData=getProperty(actorUpdates,"system.attributes.hp");isObject(hpData)&&(hpData["-=tempsource"]=null)}}broadcast(newQuantity,oldQuantity){const singularOrPlural=newQuantity===1?"PF2E.Encounter.Broadcast.TempHP.SingleNew":"PF2E.Encounter.Broadcast.TempHP.PluralNew",wasAt=oldQuantity>0?game.i18n.format("PF2E.Encounter.Broadcast.TempHP.WasAt",{oldQuantity}):"",[actor,item]=[this.actor.name,this.item.name],content=game.i18n.format(singularOrPlural,{actor,newQuantity,wasAt,item}),recipients=game.users.filter(u=>this.actor.testUserPermission(u,"OWNER")).map(u=>u.id),speaker=ChatMessagePF2e.getSpeaker({actor:this.actor,token:this.token});ChatMessagePF2e.create({content,speaker,whisper:recipients})}};__name2(_TempHPRuleElement,"TempHPRuleElement"),__publicField(_TempHPRuleElement,"validActorTypes",["character","npc","familiar"]);let TempHPRuleElement=_TempHPRuleElement;const _BattleFormRuleElement=class extends RuleElementPF2e{static{__name(this,"_BattleFormRuleElement")}constructor(data,options){super(data,options),__privateAdd(this,_setRollOptions),__privateAdd(this,_prepareAC),__privateAdd(this,_prepareSenses),__privateAdd(this,_prepareSize),__privateAdd(this,_prepareSpeeds),__privateAdd(this,_prepareSkills),__privateAdd(this,_prepareStrikes),__privateAdd(this,_prepareIWR),__privateAdd(this,_suppressModifiers),__privateAdd(this,_filterModifier),__privateAdd(this,_suppressNotes),__privateAdd(this,_resolveStrikeQueries),__publicField(this,"modifierLabel"),this.overrides=this.resolveValue(this.value,this.overrides),this.modifierLabel=this.getReducedLabel()}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!1,initial:void 0}),overrides:new fields2.SchemaField({traits:new fields2.ArrayField(new fields2.StringField),armorClass:new fields2.SchemaField({modifier:new ResolvableValueField({required:!1,nullable:!1,initial:0}),ignoreCheckPenalty:new fields2.BooleanField({required:!1,nullable:!1,initial:!0}),ignoreSpeedPenalty:new fields2.BooleanField({required:!1,nullable:!1,initial:!0})},{required:!1,initial:void 0}),tempHP:new ResolvableValueField({required:!1,nullable:!0,initial:null}),senses:new RecordField(new fields2.StringField({required:!0,blank:!1,choices:[...SENSE_TYPES]}),new fields2.SchemaField({acuity:new fields2.StringField({choices:SENSE_ACUITIES,required:!1,blank:!1,initial:void 0}),range:new fields2.NumberField({required:!1,nullable:!0,initial:void 0})}),{required:!1,initial:void 0}),size:new fields2.StringField({required:!1,blank:!1,initial:void 0}),speeds:new fields2.ObjectField({required:!1,initial:void 0}),skills:new fields2.ObjectField({required:!1,initial:void 0}),strikes:new fields2.ObjectField({required:!1}),immunities:new fields2.ArrayField(new fields2.ObjectField),weaknesses:new fields2.ArrayField(new fields2.ObjectField),resistances:new fields2.ArrayField(new fields2.ObjectField)},{required:!0,nullable:!1}),ownUnarmed:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),canCast:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),canSpeak:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),hasHands:new fields2.BooleanField({required:!1,nullable:!1,initial:!1})}}async preCreate({itemSource,ruleSource}){if(!this.test()){ruleSource.ignored=!0;return}const rules=itemSource.system?.rules??[];for(const rule of rules)if(["DamageDice","FlatModifier","Note"].includes(String(rule.key))){const predicate=rule.predicate??=[];Array.isArray(predicate)&&predicate.push("battle-form")}await __privateMethod(this,_resolveStrikeQueries,resolveStrikeQueries_fn).call(this,ruleSource)}onCreate(actorUpdates){if(this.ignored)return;const tempHP=this.overrides.tempHP;tempHP&&new TempHPRuleElement({key:"TempHP",label:this.label,value:tempHP},{parent:this.item}).onCreate(actorUpdates)}beforePrepareData(){if(this.ignored)return;const{actor}=this,{attributes}=actor;if(attributes.polymorphed){actor.synthetics.preparationWarnings.add("PF2e System | You are already under a polymorph effect"),this.ignored=!0;return}attributes.polymorphed=!0,attributes.battleForm=!0,__privateMethod(this,_setRollOptions,setRollOptions_fn).call(this),__privateMethod(this,_prepareSenses,prepareSenses_fn).call(this);for(const trait of this.overrides.traits){const currentTraits=actor.system.traits;currentTraits.value.includes(trait)||currentTraits.value.push(trait)}if(this.overrides.armorClass?.ignoreSpeedPenalty){const speedRollOptions=actor.rollOptions.speed??={};speedRollOptions["armor:ignore-speed-penalty"]=!0}}afterPrepareData(){this.ignored||(__privateMethod(this,_prepareAC,prepareAC_fn).call(this),__privateMethod(this,_prepareSize,prepareSize_fn).call(this),__privateMethod(this,_prepareSkills,prepareSkills_fn).call(this),__privateMethod(this,_prepareSpeeds,prepareSpeeds_fn).call(this),__privateMethod(this,_prepareStrikes,prepareStrikes_fn).call(this),__privateMethod(this,_prepareIWR,prepareIWR_fn).call(this),this.actor.initiative=new ActorInitiative(this.actor),this.actor.system.attributes.initiative=this.actor.initiative.getTraceData())}onDelete(actorUpdates){if(this.ignored)return;const tempHP=this.overrides.tempHP;tempHP&&new TempHPRuleElement({key:"TempHP",label:this.label,value:tempHP},{parent:this.item}).onDelete(actorUpdates)}applyDamageExclusion(weapon,modifiers){if(!this.ownUnarmed)for(const modifier of modifiers){if(modifier.predicate.some(s=>s instanceof Object&&"not"in s&&s.not==="battle-form"))continue;const isNumericBonus=modifier instanceof ModifierPF2e&&modifier.modifier>=0,isAbilityModifier=modifier instanceof ModifierPF2e&&modifier.type==="ability",isExtraDice=modifier instanceof DamageDicePF2e,isStatusOrCircumstance=isNumericBonus&&["status","circumstance"].includes(modifier.type),isDamageTrait=isExtraDice&&/^(?:deadly|fatal)-\d?d\d{1,2}$/.test(modifier.slug)&&tupleHasValue(this.overrides?.strikes?.[weapon.slug??""]?.traits??[],modifier.slug),isBattleFormModifier=!!(modifier.predicate.includes("battle-form")||modifier.predicate.some(s=>s instanceof Object&&"or"in s&&s.or.includes("battle-form"))||isDamageTrait);(isNumericBonus||isAbilityModifier||isExtraDice)&&!isStatusOrCircumstance&&!isBattleFormModifier&&(modifier.enabled=!1,modifier.ignored=!0,modifier.predicate.push({not:"battle-form"}))}}};_defaultIcons=new WeakMap,_setRollOptions=new WeakSet,setRollOptions_fn=__name2(function(){const{attributes,rollOptions}=this.actor;if(rollOptions.all.polymorph=!0,rollOptions.all["battle-form"]=!0,this.overrides.armorClass&&(rollOptions.all["armor:ignore-check-penalty"]=this.overrides.armorClass.ignoreCheckPenalty,rollOptions.all["armor:ignore-speed-penalty"]=this.overrides.armorClass.ignoreSpeedPenalty,this.overrides.armorClass.ignoreSpeedPenalty)){const speedRollOptions=rollOptions.speed??={};speedRollOptions["armor:ignore-speed-penalty"]=!0}if(this.overrides.skills)for(const key of SKILL_ABBREVIATIONS){if(!(key in this.overrides.skills))continue;const longForm=SKILL_DICTIONARY[key];rollOptions.all[`battle-form:${longForm}`]=!0}attributes.handsFree=Math.max(Object.values(this.overrides.strikes??{}).reduce((count,s)=>s.category==="unarmed"?count:count-1,2),0);for(const num of[0,1,2])attributes.handsFree===num?rollOptions.all[`hands-free:${num}`]=!0:delete rollOptions.all[`hands-free:${num}`]},"#setRollOptions"),_prepareAC=new WeakSet,prepareAC_fn=__name2(function(){const overrides=this.overrides,{actor}=this,{armorClass}=actor;if(!(Number(this.resolveValue(overrides.armorClass?.modifier,armorClass.value))||0))return;__privateMethod(this,_suppressModifiers,suppressModifiers_fn).call(this,armorClass);const newModifier=(Number(this.resolveValue(overrides.armorClass?.modifier))||0)-10;armorClass.modifiers.push(new ModifierPF2e(this.modifierLabel,newModifier,"untyped")),this.actor.system.attributes.ac=armorClass.parent.getTraceData()},"#prepareAC"),_prepareSenses=new WeakSet,prepareSenses_fn=__name2(function(){for(const senseType of SENSE_TYPES){const newSense=this.overrides.senses?.[senseType];if(!newSense)continue;newSense.acuity??="precise";const ruleData={key:"Sense",selector:senseType,force:!0,...newSense};new SenseRuleElement(ruleData,{parent:this.item}).beforePrepareData()}},"#prepareSenses"),_prepareSize=new WeakSet,prepareSize_fn=__name2(function(){if(!this.overrides.size)return;const ruleData={key:"CreatureSize",label:this.label,value:this.overrides.size};new CreatureSizeRuleElement(ruleData,{parent:this.item}).beforePrepareData()},"#prepareSize"),_prepareSpeeds=new WeakSet,prepareSpeeds_fn=__name2(function(){const{attributes}=this.actor,currentSpeeds=attributes.speed;for(const movementType of MOVEMENT_TYPES){const speedOverride=this.overrides.speeds?.[movementType];if(typeof speedOverride=="number")if(movementType==="land")__privateMethod(this,_suppressModifiers,suppressModifiers_fn).call(this,attributes.speed),attributes.speed.value=speedOverride;else{const{otherSpeeds}=currentSpeeds,label=game.i18n.localize(CONFIG.PF2E.speedTypes[movementType]);otherSpeeds.findSplice(s=>s.type===movementType),otherSpeeds.push({type:movementType,label,value:speedOverride});const newSpeed=this.actor.prepareSpeed(movementType);if(!newSpeed)throw ErrorPF2e("Unexpected failure retrieving movement type");__privateMethod(this,_suppressModifiers,suppressModifiers_fn).call(this,newSpeed),otherSpeeds.findSplice(s=>s.type===movementType),otherSpeeds.push(newSpeed)}}},"#prepareSpeeds"),_prepareSkills=new WeakSet,prepareSkills_fn=__name2(function(){for(const[skillShort,newSkill]of Object.entries(this.overrides.skills??{})){if(!setHasElement(SKILL_ABBREVIATIONS,skillShort))return this.failValidation(`Unrecognized skill abbreviation: ${skillShort}`);newSkill.ownIfHigher??=!0;const key=SKILL_DICTIONARY[skillShort],currentSkill=this.actor.skills[key],newModifier=Number(this.resolveValue(newSkill.modifier))||0;if(currentSkill.mod>newModifier&&newSkill.ownIfHigher)continue;const baseMod=new ModifierPF2e({label:this.modifierLabel,slug:"battle-form",modifier:newModifier,type:"untyped"});this.actor.skills[key]=currentSkill.extend({modifiers:[baseMod],filter:__privateMethod(this,_filterModifier,filterModifier_fn)}),this.actor.system.skills[skillShort]=mergeObject(this.actor.system.skills[skillShort],this.actor.skills[key].getTraceData())}},"#prepareSkills"),_prepareStrikes=new WeakSet,prepareStrikes_fn=__name2(function(){const{synthetics}=this.actor,strikes=this.overrides.strikes??{},ruleData=Object.entries(strikes).map(([slug,strikeData])=>({key:"Strike",label:game.i18n.localize(strikeData.label)??`PF2E.BattleForm.Attack.${sluggify(slug,{camel:"bactrian"})}`,slug,img:strikeData.img??__privateGet(_BattleFormRuleElement,_defaultIcons)[slug]??this.item.img,category:strikeData.category,group:strikeData.group,baseItem:strikeData.baseType,options:[slug],damage:{base:strikeData.damage},range:strikeData.range,maxRange:strikeData.maxRange,traits:strikeData.traits??[],ability:strikeData.ability,ownIfHigher:strikeData.ownIfHigher??=!0}));if(this.ownUnarmed){for(const[slug,weapon]of synthetics.strikes.entries())weapon.category!=="unarmed"&&synthetics.strikes.delete(slug);this.actor.rollOptions.all["battle-form:own-attack-modifier"]=!0}else{synthetics.strikes.clear();for(const striking of Object.values(synthetics.striking).flat())(striking.predicate??=new PredicatePF2e).push({not:"battle-form"});for(const datum of ruleData)datum.traits.includes("magical")||datum.traits.push("magical"),new StrikeRuleElement({...datum,battleForm:!0},{parent:this.item}).beforePrepareData()}this.actor.system.actions=this.actor.prepareStrikes({includeBasicUnarmed:this.ownUnarmed}).filter(a=>a.slug&&a.slug in strikes||this.ownUnarmed&&a.item.category==="unarmed");const strikeActions=this.actor.system.actions.flatMap(s=>[s,...s.altUsages]);for(const action2 of strikeActions){const strike=strikes[action2.slug??""]??null;if(!this.ownUnarmed&&strike&&(Number(this.resolveValue(strike.modifier))>=action2.totalModifier||!strike.ownIfHigher)){__privateMethod(this,_suppressModifiers,suppressModifiers_fn).call(this,action2),__privateMethod(this,_suppressNotes,suppressNotes_fn).call(this,Object.entries(synthetics.rollNotes).flatMap(([key,note])=>/\bdamage\b/.test(key)?note:[]));const baseModifier=Number(this.resolveValue(strike.modifier))||0;action2.unshift(new ModifierPF2e(this.modifierLabel,baseModifier,"untyped"))}else{const options=this.actor.rollOptions["strike-attack-roll"]??={};options["battle-form:own-attack-modifier"]=!0,action2.calculateTotal(new Set(this.actor.getRollOptions(action2.domains)))}}},"#prepareStrikes"),_prepareIWR=new WeakSet,prepareIWR_fn=__name2(function(){for(const immunity of this.overrides.immunities)new ImmunityRuleElement({key:"Immunity",...immunity},{parent:this.item}).afterPrepareData();for(const weakness of this.overrides.weaknesses){const args={key:"Weakness",...weakness,override:!0};new WeaknessRuleElement(args,{parent:this.item}).afterPrepareData()}for(const resistance of this.overrides.resistances){const args={key:"Resistance",...resistance,override:!0};new ResistanceRuleElement(args,{parent:this.item}).afterPrepareData()}},"#prepareIWR"),_suppressModifiers=new WeakSet,suppressModifiers_fn=__name2(function(statistic){for(const modifier of statistic.modifiers)__privateMethod(this,_filterModifier,filterModifier_fn).call(this,modifier)||(modifier.adjustments.push({slug:null,test:()=>!0,suppress:!0}),modifier.ignored=!0,modifier.enabled=!1);statistic instanceof StatisticModifier&&statistic.calculateTotal()},"#suppressModifiers"),_filterModifier=new WeakSet,filterModifier_fn=__name2(function(modifier){return modifier.slug==="battle-form"?!0:modifier.type==="ability"?!1:["status","circumstance"].includes(modifier.type)||modifier.modifier<0},"#filterModifier"),_suppressNotes=new WeakSet,suppressNotes_fn=__name2(function(notes){for(const note of notes)note.predicate.includes("battle-form")||(note.predicate=note.predicate instanceof PredicatePF2e?note.predicate:new PredicatePF2e(note.predicate),note.predicate.push({not:"battle-form"}))},"#suppressNotes"),_resolveStrikeQueries=new WeakSet,resolveStrikeQueries_fn=__name2(async function(ruleSource){const value=ruleSource.overrides?ruleSource.overrides:ruleSource.value??={};if(!__name2(v=>isObject(v)&&isObject(v.strikes),"hasStrikes")(value))return;const isStrikeQuery=__name2(maybeQuery=>isObject(maybeQuery)?typeof maybeQuery.query=="string"&&typeof maybeQuery.modifier=="number":!1,"isStrikeQuery");for(const[slug,strike]of Object.entries(value.strikes)){if(!isStrikeQuery(strike))continue;strike.pack=String(strike.pack??"pf2e.equipment-srd"),strike.ownIfHigher=!!(strike.ownIfHigher??!0);const queryObject=(()=>{try{const parsed=JSON.parse(String(this.resolveInjectedProperties(strike.query)));if(!isObject(parsed)||Array.isArray(parsed))throw Error("A strike query must be an NeDB query object");return parsed}catch(error){return error instanceof Error&&this.failValidation(error.message),ruleSource.ignored=!0,null}})();if(!queryObject){this.failValidation("Malformed query object");break}const weapon=(await game.packs.get(strike.pack)?.getDocuments(queryObject))?.[0];if(!(weapon instanceof WeaponPF2e)){this.failValidation("Failed to retrieve queried weapon");break}const resolved={label:weapon.name,img:weapon.img,ability:weapon.isRanged||weapon.traits.has("finesse")?"dex":"str",category:weapon.category,group:weapon.group,baseType:weapon.baseType,traits:deepClone(weapon.system.traits.value),modifier:strike.modifier,damage:deepClone(weapon.system.damage),ownIfHigher:strike.ownIfHigher};value.strikes[slug]=resolved}},"#resolveStrikeQueries"),__name2(_BattleFormRuleElement,"BattleFormRuleElement"),__publicField(_BattleFormRuleElement,"validActorTypes",["character"]),__privateAdd(_BattleFormRuleElement,_defaultIcons,["antler","beak","body","bone-shard","branch","claw","cube-face","fangs","fire-mote","fist","foot","foreleg","gust","horn","jaws","lighting-lash","mandibles","piercing-hymn","pincer","pseudopod","rock","spikes","stinger","tail","talon","tendril","tentacle","tongue","trunk","tusk","vine","water-spout","wave","wing"].reduce((accumulated,slug)=>{const path=slug==="fist"?"icons/skills/melee/unarmed-punch-fist.webp":`systems/pf2e/icons/unarmed-attacks/${slug}.webp`;return{...accumulated,[slug]:path}},{}));let BattleFormRuleElement=_BattleFormRuleElement;const _PickAThingPrompt=class extends Application{static{__name(this,"_PickAThingPrompt")}constructor(data){super(),__publicField(this,"item"),__privateAdd(this,_resolve3,void 0),__publicField(this,"selection",null),__publicField(this,"choices",[]),__publicField(this,"selectMenu"),__publicField(this,"predicate"),__publicField(this,"allowNoSelection"),this.item=data.item,this.predicate=data.predicate??new PredicatePF2e,this.options.title=data.title??this.item.name,this.allowNoSelection=data.allowNoSelection??!1}get actor(){return this.item.actor}static get defaultOptions(){return{...super.defaultOptions,classes:["pick-a-thing-prompt"],resizable:!1,height:"auto",width:"auto"}}getChoices(){return this.choices.filter(choice=>this.predicate.test(choice.domain??[]))??[]}getSelection(event){if(!(event.currentTarget instanceof HTMLElement))throw ErrorPF2e("Unexpected error retrieving form data");const selectedIndex=(event.currentTarget.closest(".choice")?.querySelector("button[data-action=pick]")??event.currentTarget.closest(".content")?.querySelector("tag")??event.currentTarget).getAttribute("value");return["",null].includes(selectedIndex)||!Number.isInteger(Number(selectedIndex))?null:this.choices.at(Number(selectedIndex))??null}async resolveSelection(){return this.choices=this.getChoices(),this.render(!0),new Promise(resolve=>{__privateSet(this,_resolve3,resolve)})}async getData(options={}){const slug=this.item.slug??sluggify(this.item.name);return options.id=`pick-a-${slug}`,{selectMenu:this.choices.length>9,choices:this.choices.map((c,index)=>({...c,value:index}))}}activateListeners($html){const html=$html[0];for(const element of htmlQueryAll(html,"a[data-choice], button[data-action=pick]"))element.addEventListener("click",event=>{this.selection=this.getSelection(event)??null,this.close()});const select=htmlQuery(html,"input[data-tagify-select]");select&&(this.selectMenu=new Tagify(select,{enforceWhitelist:!0,keepInvalidTags:!1,mode:"select",tagTextProp:"label",dropdown:{closeOnSelect:!0,enabled:1,highlightFirst:!0,mapValueTo:"label",maxItems:this.choices.length,searchKeys:["label"]},whitelist:this.choices.map((c,index)=>({value:index.toString(),label:c.label}))}),this.selectMenu.DOM.input.spellcheck=!1)}async close(options){var _a;for(const element of htmlQueryAll(this.element[0],"button, select"))element.style.pointerEvents="none";return this.choices.length===0?ui.notifications.warn(game.i18n.format("PF2E.UI.RuleElements.Prompt.NoValidOptions",{actor:this.actor.name,item:this.item.name})):!this.selection&&!this.allowNoSelection&&ui.notifications.warn(game.i18n.format("PF2E.UI.RuleElements.Prompt.NoSelectionMade",{item:this.item.name})),(_a=__privateGet(this,_resolve3))==null||_a.call(this,this.selection),super.close(options)}};_resolve3=new WeakMap,__name2(_PickAThingPrompt,"PickAThingPrompt");let PickAThingPrompt=_PickAThingPrompt;const _ChoiceSetPrompt=class extends PickAThingPrompt{static{__name(this,"_ChoiceSetPrompt")}prompt;containsItems;allowedDrops;constructor(data){super(data),this.prompt=data.prompt,this.choices=data.choices??[],this.containsItems=data.containsItems,this.allowedDrops=this.containsItems?data.allowedDrops:null}static get defaultOptions(){return{...super.defaultOptions,classes:["choice-set-prompt"],dragDrop:[{dropSelector:".drop-zone"}],template:"systems/pf2e/templates/system/rules-elements/choice-set-prompt.hbs"}}async getData(options={}){return{...await super.getData(options),choices:this.choices.map((c,index)=>({...c,value:index,hasUUID:UUIDUtils.isItemUUID(c.value)})),prompt:this.prompt,includeDropZone:!!this.allowedDrops,allowNoSelection:this.allowNoSelection,selectMenu:this.choices.length>9,containsItems:this.containsItems}}getChoices(){return this.choices}setChoices(choices){this.choices=choices}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"button[data-action=close]")?.addEventListener("click",()=>{this.close()});const renderItemSheet=__name2(async choice=>{if(!choice||!UUIDUtils.isItemUUID(choice.value))return;(await fromUuid(choice.value))?.sheet.render(!0)},"renderItemSheet");if(this.containsItems)if(this.selectMenu){const itemInfoAnchor=htmlQuery(html,"a.item-info");if(!itemInfoAnchor)return;const updateAnchor=__name2((disable,value="")=>{itemInfoAnchor.dataset.value=value,itemInfoAnchor.classList.toggle("disabled",disable),itemInfoAnchor.dataset.tooltip=game.i18n.localize(disable?"PF2E.UI.RuleElements.ChoiceSet.ViewItem.Disabled":"PF2E.UI.RuleElements.ChoiceSet.ViewItem.Tooltip")},"updateAnchor");itemInfoAnchor.addEventListener("click",event=>{renderItemSheet(this.getSelection(event))}),this.selectMenu.on("change",event=>{const data=event.detail.tagify.value.at(0);if(!data)return updateAnchor(!0);const index=Number(data.value);if(!isNaN(index)){const choice=this.choices.at(index);UUIDUtils.isItemUUID(choice?.value)?updateAnchor(!1,data.value):updateAnchor(!0)}})}else for(const anchor of htmlQueryAll(html,"a.item-info"))anchor.addEventListener("click",event=>{renderItemSheet(this.getSelection(event))})}async resolveSelection(){const firstChoice=this.choices.at(0);return!this.allowedDrops&&firstChoice&&this.choices.length===1?this.selection=firstChoice:(this.choices.length===0&&!this.allowedDrops&&this.close(),super.resolveSelection())}async _onDrop(event){event.preventDefault();const dataString=event.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??"");if(dropData?.type!=="Item"){ui.notifications.error("Only an item can be dropped here.");return}const droppedItem=await ItemPF2e.fromDropData(dropData);if(!droppedItem)throw ErrorPF2e("Unexpected error resolving drop");const isAllowedDrop=!!this.allowedDrops?.predicate.test(droppedItem.getRollOptions("item"));if(this.allowedDrops&&!isAllowedDrop){ui.notifications.error(game.i18n.format("PF2E.Item.ABC.InvalidDrop",{badType:droppedItem.name,goodType:game.i18n.localize(this.allowedDrops.label??"")}));return}const newChoice={value:this.containsItems&&this.choices.length>0&&this.choices.every(c=>!UUIDUtils.isItemUUID(c.value))?droppedItem.slug??sluggify(droppedItem.id):droppedItem.uuid,label:droppedItem.name},choicesLength=this.choices.push(newChoice),prompt=document.querySelector(`#${this.id}`),dropZone=prompt?.querySelector(".drop-zone");if(!prompt)throw ErrorPF2e("Unexpected error retrieving ChoiceSet dialog");if(prompt.style.height="unset",this.selectMenu){const{whitelist}=this.selectMenu.settings,menuChoice={value:String(choicesLength-1),label:newChoice.label};whitelist?.push(menuChoice.value),this.selectMenu.setPersistedData(whitelist,"whitelist"),this.selectMenu.addTags([menuChoice],!0,!0),this.selectMenu.setReadonly(!0),dropZone?.remove()}else{const img=document.createElement("img");img.src=droppedItem.img;const newButton=createHTMLElement("button",{classes:["with-image"],children:[img,createHTMLElement("span",{children:[droppedItem.name]})]});newButton.type="button",newButton.value=String(choicesLength-1),newButton.addEventListener("click",event2=>{this.selection=this.getSelection(event2)??null,this.close()}),dropZone?.replaceWith(newButton)}}_canDragDrop(){return this.actor.isOwner}};__name2(_ChoiceSetPrompt,"ChoiceSetPrompt");let ChoiceSetPrompt=_ChoiceSetPrompt;const _ChoiceSetRuleElement=class extends RuleElementPF2e{static{__name(this,"_ChoiceSetRuleElement")}constructor(data,options){if(super(data,options),__privateAdd(this,_setDefaultFlag),__privateAdd(this,_choicesFromArray),__privateAdd(this,_choicesFromPath),__privateAdd(this,_choicesFromOwnedItems),__privateAdd(this,_choicesFromAttacks),__privateAdd(this,_getPreselection),__privateAdd(this,_setRollOption),__publicField(this,"containsItems",!1),__publicField(this,"selection"),this.allowedDrops??=null,this.allowNoSelection??=!1,this.rollOption??=this.slug,this.flag=__privateMethod(this,_setDefaultFlag,setDefaultFlag_fn).call(this,this),this.selection=typeof data.selection=="string"||typeof data.selection=="number"||isObject(data.selection)?data.selection:null,isObject(this.choices)&&!Array.isArray(this.choices)&&!("filter"in this.choices)&&(this.choices.predicate=new PredicatePF2e(this.choices.predicate??[]),this.choices.unarmedAttacks&&this.choices.predicate.push("item:category:unarmed")),this.item.flags.pf2e.rulesSelections[this.flag]=this.selection,this.selection!==null)__privateMethod(this,_setRollOption,setRollOption_fn).call(this,this.selection);else if(!this.allowNoSelection&&this.test()){this.ignored=!0;for(const ruleData of this.item.system.rules)ruleData.ignored=!0}}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),choices:new DataUnionField([new StrictArrayField(new StrictObjectField({required:!0,nullable:!1,initial:void 0}),{required:!0,nullable:!1,initial:void 0}),new StrictObjectField({required:!0,nullable:!1,initial:void 0}),new StrictStringField({required:!0,nullable:!1,initial:void 0})],{required:!0,nullable:!1,initial:()=>[]}),prompt:new fields2.StringField({required:!0,blank:!1,nullable:!1,initial:"PF2E.UI.RuleElements.ChoiceSet.Prompt"}),adjustName:new fields2.BooleanField({required:!0,nullable:!1,initial:!0}),allowedDrops:new fields2.SchemaField({label:new fields2.StringField({required:!0,blank:!1,nullable:!0,initial:null}),predicate:new PredicateField},{required:!1,nullable:!0,initial:void 0}),flag:new fields2.StringField({required:!1,blank:!1,nullable:!1,initial:void 0}),rollOption:new fields2.StringField({required:!1,blank:!1,nullable:!0,initial:null}),allowNoSelection:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0})}}async preCreate({itemSource,ruleSource,pendingItems}){if(this.selection===null&&isObject(this.choices)&&"query"in this.choices){this.failValidation("As of FVTT version 11, choice set queries are no longer supported.");for(const ruleData of this.item.system.rules)ruleData.ignored=!0;return}const rollOptions=new Set([this.actor.getRollOptions(),this.item.getRollOptions("parent")].flat());if(!this.resolveInjectedProperties(this.predicate).test(rollOptions))return;if(isObject(this.choices)){const{choices}=this;if("ownedItems"in choices&&choices.ownedItems&&!choices.types?.length){console.warn("PF2E System | Failure during ChoiceSet preCreate: `types` is required if `ownedItems` is set"),ruleSource.ignored=!0;return}}__privateMethod(this,_setDefaultFlag,setDefaultFlag_fn).call(this,ruleSource);const inflatedChoices=await this.inflateChoices(rollOptions,pendingItems),selection=__privateMethod(this,_getPreselection,getPreselection_fn).call(this)??await new ChoiceSetPrompt({prompt:this.prompt,item:this.item,title:this.label,choices:inflatedChoices,containsItems:this.containsItems,allowedDrops:this.allowedDrops,allowNoSelection:this.allowNoSelection}).resolveSelection();if(selection){if(ruleSource.selection=selection.value,this.adjustName){const effectName=itemSource.name,label=game.i18n.localize(selection.label),name2=`${effectName} (${label})`,pattern=(()=>{const escaped=RegExp.escape(label);return new RegExp(`\\(${escaped}\\) \\(${escaped}\\)$`)})();itemSource.name=name2.replace(pattern,`(${label})`)}if(this.item.flags.pf2e.rulesSelections[this.flag]=selection.value,typeof ruleSource.rollOption=="string"&&UUIDUtils.isItemUUID(selection.value)){const item=await fromUuid(selection.value);if(item instanceof ItemPF2e){const slug=item.slug??sluggify(item.name);this.rollOption=ruleSource.rollOption=`${ruleSource.rollOption}:${slug}`}}__privateMethod(this,_setRollOption,setRollOption_fn).call(this,ruleSource.selection);for(const rule of this.item.rules)rule.ignored=!1,rule.onApplyActiveEffects?.()}else ruleSource.ignored=!0}async inflateChoices(rollOptions,pendingItems){const choices=Array.isArray(this.choices)?__privateMethod(this,_choicesFromArray,choicesFromArray_fn).call(this,this.choices,rollOptions):isObject(this.choices)?this.choices.ownedItems?__privateMethod(this,_choicesFromOwnedItems,choicesFromOwnedItems_fn).call(this,this.choices,rollOptions):this.choices.attacks||this.choices.unarmedAttacks?__privateMethod(this,_choicesFromAttacks,choicesFromAttacks_fn).call(this,new PredicatePF2e(this.resolveInjectedProperties(this.choices.predicate)),rollOptions):"filter"in this.choices&&Array.isArray(this.choices.filter)?await this.queryCompendium(this.choices,rollOptions,pendingItems):[]:typeof this.choices=="string"?__privateMethod(this,_choicesFromPath,choicesFromPath_fn).call(this,this.choices):[],choicesAreUUIDs=choices.every(c=>UUIDUtils.isItemUUID(c.value));if(choicesAreUUIDs){const itemChoices=await UUIDUtils.fromUUIDs(choices.map(c=>c.value));for(let i=0;i({value:c.value,label:game.i18n.localize(c.label),img:c.img}));return Array.isArray(this.choices)||choiceData.sort((a,b)=>a.label.localeCompare(b.label)),choiceData}catch{return[]}}async queryCompendium(choices,actorRollOptions,pendingItems){const filter2=Array.isArray(choices.filter)?new PredicatePF2e(this.resolveInjectedProperties(choices.filter)):new PredicatePF2e;if(!filter2.isValid||filter2.length===0)return this.failValidation("`filter` must be an array with at least one statement"),[];const itemType=objectHasKey(CONFIG.PF2E.Item.documentClasses,choices.itemType)?choices.itemType:"feat",packs=typeof choices.pack=="string"?compact([game.packs.get(choices.pack)]):game.packs.filter(p=>p.metadata.type==="Item"&&p.index.some(e=>e.type===itemType)),progress=new Progress({max:packs.length}),localize=localizer("PF2E.ProgressBar"),indexData=[];for(const pack of packs)progress.advance({label:localize("LoadingPack",{pack:pack.metadata.label})}),indexData.push(await pack.getIndex({fields:["flags","system.ancestry","system.baseItem","system.category","system.group","system.level","system.maxTakable","system.potencyRune","system.slug","system.traits"]}));progress.close({label:localize("LoadingComplete")});const filteredItems=indexData.flatMap(d=>d.contents).filter(s=>s.type===itemType).map(source=>{const parsedUUID=foundry.utils.parseUuid(source.uuid),pack=parsedUUID.collection instanceof CompendiumCollection?parsedUUID.collection.metadata.id:null;return new ItemProxyPF2e(deepClone(source),{pack})}).concat(game.items.filter(i=>i.type===itemType)).filter(i=>filter2.test([...i.getRollOptions("item"),...actorRollOptions])),existing=new Map;for(const feat of this.actor.itemTypes.feat){const slug=feat.slug??sluggify(feat.name);existing.set(slug,(existing.get(slug)??0)+1)}for(const featSource of pendingItems.filter(i=>i.type==="feat")){const slug=featSource.system?.slug??sluggify(featSource.name);existing.set(slug,(existing.get(slug)??0)+1)}return filteredItems.filter(i=>i instanceof FeatPF2e?(existing.get(i.slug??sluggify(i.name))??0)({value:choices.slugsAsValues?f.slug??sluggify(f.name):f.uuid,label:f.name,img:f.img}))}};_setDefaultFlag=new WeakSet,setDefaultFlag_fn=__name2(function(source){return source.flag=typeof source.flag=="string"&&source.flag.length>0?source.flag.replace(/[^-a-z0-9]/gi,""):sluggify(this.slug??this.item.slug??this.item.name,{camel:"dromedary"})},"#setDefaultFlag"),_choicesFromArray=new WeakSet,choicesFromArray_fn=__name2(function(choices,actorRollOptions){return choices.filter(c=>this.resolveInjectedProperties(new PredicatePF2e(c.predicate??[])).test(actorRollOptions))},"#choicesFromArray"),_choicesFromPath=new WeakSet,choicesFromPath_fn=__name2(function(path){const choiceObject=getProperty(CONFIG.PF2E,path)??getProperty(this.actor,path)??{};return Array.isArray(choiceObject)&&choiceObject.every(c=>isObject(c)&&typeof c.value=="string")?choiceObject:isObject(choiceObject)&&Object.values(choiceObject).every(c=>typeof c=="string")?Object.entries(choiceObject).map(([value,label])=>({value,label:String(label)})):[]},"#choicesFromPath"),_choicesFromOwnedItems=new WeakSet,choicesFromOwnedItems_fn=__name2(function(options,actorRollOptions){const{includeHandwraps,types}=options,predicate=new PredicatePF2e(this.resolveInjectedProperties(options.predicate)),choices=this.actor.items.filter(i=>i.isOfType(...types)&&predicate.test([...actorRollOptions,...i.getRollOptions("item")])).filter(i=>!i.isOfType("weapon")||i.category!=="unarmed").map(i=>({img:i.img,label:i.name,value:i.id}));return includeHandwraps&&choices.push(...this.actor.itemTypes.weapon.filter(i=>i.slug==="handwraps-of-mighty-blows"&&predicate.test([...actorRollOptions,...i.getRollOptions("item")])).map(h=>({img:h.img,label:h.name,value:"unarmed"}))),choices},"#choicesFromOwnedItems"),_choicesFromAttacks=new WeakSet,choicesFromAttacks_fn=__name2(function(predicate,actorRollOptions){return this.actor.isOfType("character","npc")?this.actor.system.actions.filter(a=>a.item.isOfType("melee","weapon")&&predicate.test([...actorRollOptions,...a.item.getRollOptions("item")])).map(a=>({img:a.item.img,label:a.item.name,value:a.item.slug??sluggify(a.item.name)})):[]},"#choicesFromAttacks"),_getPreselection=new WeakSet,getPreselection_fn=__name2(function(){return(Array.isArray(this.choices)?this.choices.find(c=>c.value===this.selection):null)??null},"#getPreselection"),_setRollOption=new WeakSet,setRollOption_fn=__name2(function(selection){if(!(this.rollOption&&(typeof selection=="string"||typeof selection=="number")))return;const suffix=UUIDUtils.isItemUUID(selection)?"":`:${selection}`;this.actor.rollOptions.all[`${this.rollOption}${suffix}`]=!0},"#setRollOption"),__name2(_ChoiceSetRuleElement,"ChoiceSetRuleElement");let ChoiceSetRuleElement=_ChoiceSetRuleElement;const _CraftingEntryRuleElement=class extends RuleElementPF2e{static{__name(this,"_CraftingEntryRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1}),isAlchemical:new fields2.BooleanField({required:!1,initial:void 0}),isDailyPrep:new fields2.BooleanField({required:!1,initial:void 0}),isPrepared:new fields2.BooleanField({required:!1,initial:void 0}),maxItemLevel:new ResolvableValueField({required:!1,nullable:!1,initial:1}),maxSlots:new fields2.NumberField({required:!1,nullable:!1,initial:void 0}),craftableItems:new PredicateField,preparedFormulas:new fields2.ArrayField(new fields2.SchemaField({itemUUID:new fields2.StringField({required:!0,blank:!1}),quantity:new fields2.NumberField({required:!1,nullable:!1,initial:void 0}),sort:new fields2.NumberField({required:!1,nullable:!1,initial:void 0}),expended:new fields2.BooleanField({required:!1,initial:void 0}),isSignatureItem:new fields2.BooleanField({required:!1,initial:void 0})},{required:!0,nullable:!1}),{initial:[]})}}constructor(data,options){super({priority:19,...data},options)}beforePrepareData(){if(this.ignored)return;const selector=this.resolveInjectedProperties(this.selector),craftableItems=this.craftableItems??[];if(!PredicatePF2e.isValid(craftableItems))return this.failValidation("Malformed craftableItems predicate");this.actor.system.crafting.entries[this.selector]={selector,name:this.label,isAlchemical:this.isAlchemical,isDailyPrep:this.isDailyPrep,isPrepared:this.isPrepared,craftableItems,maxItemLevel:Number(this.resolveValue(this.maxItemLevel))||1,maxSlots:this.maxSlots,parentItem:this.item.id,preparedFormulaData:this.preparedFormulas};const option=sluggify(this.selector);this.actor.rollOptions.all[`crafting:entry:${option}`]=!0}};__name2(_CraftingEntryRuleElement,"CraftingEntryRuleElement"),__publicField(_CraftingEntryRuleElement,"validActorTypes",["character"]);let CraftingEntryRuleElement=_CraftingEntryRuleElement;const _CraftingFormulaRuleElement=class extends RuleElementPF2e{static{__name(this,"_CraftingFormulaRuleElement")}constructor(data,options){if(super(data,options),!(typeof data.uuid=="string"&&/^(?:Compendium|Item)\..*[a-z0-9]{16}$/i.test(data.uuid))){const{item}=this;this.failValidation(`Crafting formula rule element on ${item.name} (${item.uuid}) has a malformed UUID`)}}beforePrepareData(){this.ignored||this.actor.system.crafting.formulas.find(f=>f.uuid===this.data.uuid)||this.actor.system.crafting.formulas.push({uuid:this.data.uuid})}};__name2(_CraftingFormulaRuleElement,"CraftingFormulaRuleElement"),__publicField(_CraftingFormulaRuleElement,"validActorTypes",["character"]);let CraftingFormulaRuleElement=_CraftingFormulaRuleElement;const _CritSpecRuleElement=class extends RuleElementPF2e{static{__name(this,"_CritSpecRuleElement")}constructor(){super(...arguments),__privateAdd(this,_getEffect)}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),alternate:new fields2.BooleanField,text:new fields2.StringField({blank:!1,nullable:!0,initial:null}),damageDice:new fields2.SchemaField({number:new ResolvableValueField({required:!0,nullable:!1,initial:void 0}),faces:new fields2.NumberField({required:!0,nullable:!1,choices:[4,6,8,10,12],initial:void 0}),damageType:new fields2.StringField({required:!1,nullable:!0,choices:()=>CONFIG.PF2E.damageTypes,initial:null}),category:new fields2.StringField({required:!1,nullable:!0,choices:Array.from(DAMAGE_CATEGORIES_UNIQUE),initial:null})},{required:!1,nullable:!0,initial:null}),modifier:new fields2.SchemaField({type:new fields2.StringField({required:!0,nullable:!1,choices:Array.from(MODIFIER_TYPES),initial:"untyped"}),damageType:new fields2.StringField({required:!1,nullable:!0,choices:()=>CONFIG.PF2E.damageTypes,initial:null}),category:new fields2.StringField({required:!1,nullable:!0,choices:Array.from(DAMAGE_CATEGORIES_UNIQUE),initial:null}),value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0})},{required:!1,nullable:!0,initial:null})}}static validateJoint(data){if(super.validateJoint(data),data.alternate&&!data.text&&!data.damageDice&&!data.modifier)throw Error(" alternate: must also include at least one of text, damage dice, or modifier");if(!data.alternate&&(data.text||data.damageDice||data.modifier)){const badProperty=["text","damageDice","modifier"].find(k=>data[k]);throw Error(` ${badProperty}: may only be used if alternate is true`)}}beforePrepareData(){if(this.ignored)return;const synthetic=__name2((weapon,options)=>this.resolveInjectedProperties(this.predicate).test(options)?__privateMethod(this,_getEffect,getEffect_fn).call(this,weapon):null,"synthetic");this.ignored||this.actor.synthetics.criticalSpecalizations[this.alternate?"alternate":"standard"].push(synthetic)}};_getEffect=new WeakSet,getEffect_fn=__name2(function(weapon){const text=this.text?this.resolveInjectedProperties(this.text.trim()):null,slug="critical-specialization",label="PF2E.Actor.Creature.CriticalSpecialization",note=__name2(()=>this.alternate&&!this.text?null:new RollNotePF2e({selector:"strike-damage",title:label,text:text??`PF2E.Item.Weapon.CriticalSpecialization.${weapon.group}`,outcome:["criticalSuccess"]}),"note"),resolveInteger=__name2((value,fallback)=>{const resolved=this.resolveValue(value,0,{resolvables:{weapon}});return Math.clamped(Math.trunc(Math.abs(Number(resolved))),1,10)||fallback},"resolveInteger"),damageDice=__name2(()=>this.alternate&&this.damageDice?new DamageDicePF2e({slug,label,selector:"strike-damage",diceNumber:resolveInteger(this.damageDice.number,1),dieSize:`d${this.damageDice.faces}`,damageType:this.damageDice.damageType,category:this.damageDice.category,critical:!0}):null,"damageDice"),modifier=__name2(()=>this.alternate&&this.modifier?new ModifierPF2e({slug,label,type:this.modifier.type,modifier:resolveInteger(this.modifier.value,0),damageType:this.modifier.damageType,damageCategory:this.modifier.category,critical:!0}):null,"modifier");if(this.alternate)return compact([note(),damageDice(),modifier()]);switch(weapon.group){case"dart":case"knife":{const dice=new DamageDicePF2e({slug,selector:"strike-damage",label,damageType:"bleed",diceNumber:1,dieSize:"d6",critical:!0}),bonusValue=AutomaticBonusProgression.isEnabled(this.actor)?AutomaticBonusProgression.getAttackPotency(this.actor.level):weapon.isOfType("melee")?weapon.linkedWeapon?.system.runes.potency??0:weapon.system.runes.potency,bonus=bonusValue>0?new ModifierPF2e({slug,label,type:"item",damageType:"bleed",modifier:bonusValue,critical:!0}):null;return[dice,bonus??[]].flat()}case"pick":return weapon.baseDamage.die?[new ModifierPF2e({slug,label,type:"untyped",modifier:2*weapon.baseDamage.dice,critical:!0})]:[];default:return weapon.group?compact([note()]):[]}},"#getEffect"),__name2(_CritSpecRuleElement,"CritSpecRuleElement"),__publicField(_CritSpecRuleElement,"validActorTypes",["character","npc"]);let CritSpecRuleElement=_CritSpecRuleElement;const _DamageDiceRuleElement=class extends RuleElementPF2e{static{__name(this,"_DamageDiceRuleElement")}constructor(data,options){super(data,options),__privateAdd(this,_isValidOverride),__privateAdd(this,_resolvedBracketsIsValid),this.brackets=this.isBracketedValue(data.value)?data.value:null,data.override&&!__privateMethod(this,_isValidOverride,isValidOverride_fn).call(this,data.override)&&(this.failValidation("The override property must be an object with one property of 'upgrade' (boolean),","'downgrade (boolean)', 'diceNumber' (integer between 0 and 10), 'dieSize' (d6-d12), or 'damageType'","(recognized damage type)"),this.override=null)}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,initial:void 0})),diceNumber:new ResolvableValueField({required:!1,initial:void 0}),dieSize:new fields2.StringField({required:!1,blank:!1,nullable:!0,initial:null}),damageType:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),critical:new fields2.BooleanField({required:!1,nullable:!0,initial:void 0}),category:new fields2.StringField({choices:["persistent","precision","splash"],required:!1,blank:!1,initial:void 0}),brackets:new ResolvableValueField({required:!1,nullable:!0,initial:void 0}),override:new fields2.ObjectField({required:!1,nullable:!0,initial:void 0})}}beforePrepareData(){if(!this.ignored)for(const selector of this.resolveInjectedProperties(this.selector)){if(selector==="null")continue;const deferredDice=__name2((params={})=>{const label=this.getReducedLabel(),testPassed=this.predicate.length===0||this.resolveInjectedProperties(this.predicate).test([...params.test??this.actor.getRollOptions(["damage"]),...this.item.getRollOptions("parent")]),resolveOptions={...params,warn:testPassed},diceNumber=Number(this.resolveValue(this.diceNumber,0,resolveOptions))||0;if(this.ignored)return null;const resolvedBrackets=this.resolveValue(this.brackets,{},resolveOptions);if(!__privateMethod(this,_resolvedBracketsIsValid,resolvedBracketsIsValid_fn).call(this,resolvedBrackets))return testPassed&&this.failValidation("Brackets failed to validate"),null;const damageType=this.resolveInjectedProperties(this.damageType,resolveOptions);if(damageType!==null&&!objectHasKey(CONFIG.PF2E.damageTypes,damageType))return testPassed&&this.failValidation(`Unrecognized damage type: ${damageType}`),null;if(this.override){if(this.override.damageType&&=this.resolveInjectedProperties(this.override.damageType,resolveOptions),"damageType"in this.override&&!objectHasKey(CONFIG.PF2E.damageTypes,this.override.damageType))return testPassed&&this.failValidation("Unrecognized damage type in override"),null;if(this.override.diceNumber&&=Math.floor(Number(this.resolveValue(this.override.diceNumber,resolveOptions))),typeof this.override.diceNumber=="number"&&this.override.diceNumber<0)return testPassed&&this.failValidation("A dice number must resolve to at least zero"),null;if(this.override.dieSize&&=this.resolveInjectedProperties(this.override.dieSize,resolveOptions),"dieSize"in this.override&&!setHasElement(DAMAGE_DIE_FACES,this.override.dieSize))return testPassed&&this.failValidation("Unrecognized die size in override"),null}const dieSize=this.resolveInjectedProperties(this.dieSize,resolveOptions);return dieSize!==null&&!setHasElement(DAMAGE_DIE_FACES,dieSize)?(testPassed&&this.failValidation("Die size must be a recognized damage die size, null, or omitted"),null):new DamageDicePF2e({selector,slug:this.slug??sluggify(this.item.name),label,diceNumber,dieSize,critical:this.critical,category:this.category,damageType,predicate:this.predicate,override:deepClone(this.override),enabled:testPassed,...resolvedBrackets})},"deferredDice");(this.actor.synthetics.damageDice[selector]??=[]).push(deferredDice)}}};_isValidOverride=new WeakSet,isValidOverride_fn=__name2(function(override){return override===void 0?!0:isObject(override)&&(typeof override.upgrade=="boolean"&&!("downgrade"in override)||typeof override.downgrade=="boolean"&&!("upgrade"in override)||typeof override.damageType=="string"||typeof override.dieSize=="string"||typeof override.diceNumber=="string"||typeof override.diceNumber=="number"&&Number.isInteger(override.diceNumber)&&override.diceNumber>=0&&override.diceNumber<=256)},"#isValidOverride"),_resolvedBracketsIsValid=new WeakSet,resolvedBracketsIsValid_fn=__name2(function(value){if(!isObject(value))return!1;const keysAreValid=Object.keys(value).every(k=>["diceNumber","dieSize","override"].includes(k)),diceNumberIsValid=!("diceNumber"in value)||typeof value.diceNumber=="number",dieSizeIsValid=!("dieSize"in value)||setHasElement(DAMAGE_DIE_FACES,value.dieSize),overrideIsValid=!("override"in value)||__privateMethod(this,_isValidOverride,isValidOverride_fn).call(this,value.override);return keysAreValid&&diceNumberIsValid&&dieSizeIsValid&&overrideIsValid},"#resolvedBracketsIsValid"),__name2(_DamageDiceRuleElement,"DamageDiceRuleElement");let DamageDiceRuleElement=_DamageDiceRuleElement;const _DexterityModifierCapRuleElement=class extends RuleElementPF2e{static{__name(this,"_DexterityModifierCapRuleElement")}static defineSchema(){return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1})}}beforePrepareData(){if(!this.test())return;const value=this.resolveValue(this.value);if(typeof value!="number")return this.failValidation("value must be a number");this.actor.synthetics.dexterityModifierCaps.push({value,source:this.label})}};__name2(_DexterityModifierCapRuleElement,"DexterityModifierCapRuleElement"),__publicField(_DexterityModifierCapRuleElement,"validActorTypes",["character","npc"]);let DexterityModifierCapRuleElement=_DexterityModifierCapRuleElement;const{fields:fields$1,validation}=foundry.data,_ItemAlterationValidator=class extends fields$1.SchemaField{static{__name(this,"_ItemAlterationValidator")}constructor(fields2,options={}){super(fields2,options),__privateAdd(this,_validateForItem,void 0),__publicField(this,"operableOnInstances"),__publicField(this,"operableOnSource"),options.validateForItem&&__privateSet(this,_validateForItem,options.validateForItem),this.operableOnInstances=options.operableOnInstances??!0,this.operableOnSource=options.operableOnSource??!0}isValid(data){var _a;const{item,alteration}=data,failure=this.validate(alteration);if(failure)throw new validation.DataModelValidationError(failure);if(item.type!==alteration.itemType)return!1;const forItemFailure=(_a=__privateGet(this,_validateForItem))==null?void 0:_a.call(this,item);if(forItemFailure)throw new validation.DataModelValidationError(forItemFailure);if(!this.operableOnInstances&&item instanceof ItemPF2e)throw new validation.DataModelValidationError("may only be applied to source data");if(!this.operableOnSource&&!(item instanceof ItemPF2e))throw new validation.DataModelValidationError("may only be applied to existing items");return!0}};_validateForItem=new WeakMap,__name2(_ItemAlterationValidator,"ItemAlterationValidator");let ItemAlterationValidator=_ItemAlterationValidator;const itemHasCounterBadge=__name2(item=>{if(!(itemIsOfType(item,"condition")?typeof item.system.value.value=="number":itemIsOfType(item,"effect")?item.system.badge?.type==="counter":!1))throw new foundry.data.validation.DataModelValidationError("effect lacks a badge")},"itemHasCounterBadge"),ITEM_ALTERATION_VALIDATORS={"ac-bonus":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,nullable:!1,integer:!0,positive:!0,initial:void 0})}),"badge-max":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["effect"]}),mode:new fields$1.StringField({required:!0,choices:["downgrade","override"]}),value:new fields$1.NumberField({required:!0,nullable:!1,integer:!0,positive:!0,initial:void 0})},{validateForItem:itemHasCounterBadge}),"badge-value":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["condition","effect"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,integer:!0,nullable:!1,positive:!0,initial:void 0})},{validateForItem:itemHasCounterBadge}),"bulk-held-or-stowed":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:Array.from(PHYSICAL_ITEM_TYPES)}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:BULK_VALUES,initial:void 0})}),"bulk-worn":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor","backpack"]}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:BULK_VALUES,initial:void 0})}),category:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:["light","heavy","medium"],initial:void 0})}),"dex-cap":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new StrictNumberField({required:!0,nullable:!1,integer:!0,initial:void 0})}),"check-penalty":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new StrictNumberField({required:!0,nullable:!1,integer:!0,initial:void 0})}),hardness:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:Array.from(PHYSICAL_ITEM_TYPES)}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","multiply","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,integer:!0,nullable:!1,positive:!0})}),"hp-max":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:Array.from(PHYSICAL_ITEM_TYPES)}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","multiply","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,nullable:!1,positive:!0,initial:void 0})}),"material-type":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:Array.from(PHYSICAL_ITEM_TYPES)}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:Array.from(PRECIOUS_MATERIAL_TYPES),initial:void 0})}),"pd-recovery-dc":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["condition"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,integer:!0,nullable:!1,positive:!0,initial:void 0})},{validateForItem(item){if(item.system.slug!=="persistent-damage")return new foundry.data.validation.DataModelValidationFailure({message:"item must be a persistent damage condition"})}}),"persistent-damage":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["condition"]}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.SchemaField({formula:new fields$1.StringField({required:!0,blank:!1,validate:value=>DamageRoll.validate(String(value))}),damageType:new fields$1.StringField({required:!0,choices:()=>CONFIG.PF2E.damageTypes}),dc:new fields$1.NumberField({required:!0,integer:!0,positive:!0,nullable:!1,initial:15})},{nullable:!1})},{validateForItem(item){if(item.system.slug!=="persistent-damage")return new foundry.data.validation.DataModelValidationFailure({message:"item must be a persistent damage condition"})}}),rarity:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:Array.from(PHYSICAL_ITEM_TYPES)}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:RARITIES})}),"frequency-max":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["action","feat"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","multiply","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,integer:!0,nullable:!1,positive:!0})}),"frequency-per":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["action","feat"]}),mode:new fields$1.StringField({required:!0,choices:["downgrade","override","upgrade"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:()=>Object.keys(CONFIG.PF2E.frequencies),initial:void 0})}),"other-tags":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:()=>keys.strict(CONFIG.PF2E.Item.documentClasses)}),mode:new fields$1.StringField({required:!0,choices:["add","subtract","remove"]}),value:new SlugField({required:!0,nullable:!1,blank:!1,initial:void 0})}),"speed-penalty":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new StrictNumberField({required:!0,nullable:!1,integer:!0,initial:void 0})}),strength:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new StrictNumberField({required:!0,nullable:!1,integer:!0,positive:!0,initial:void 0})}),traits:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","remove","subtract"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:()=>CONFIG.PF2E.armorTraits,initial:void 0})})},_ItemAlteration=class extends foundry.abstract.DataModel{static{__name(this,"_ItemAlteration")}constructor(){super(...arguments),__privateAdd(this,_adjustCreatureShieldData),__privateAdd(this,_getNewInterval)}static defineSchema(){const{fields:fields2}=foundry.data;return{mode:new fields2.StringField({required:!0,choices:["add","downgrade","multiply","override","remove","subtract","upgrade"],initial:void 0}),property:new fields2.StringField({required:!0,choices:this.VALID_PROPERTIES,initial:void 0}),value:new ResolvableValueField}}get actor(){return this.parent.actor}resolveValue(...args){return this.parent.resolveValue(...args)}applyTo(item){const data={item,alteration:{mode:this.mode,itemType:item.type,value:this.value=this.parent.resolveValue(this.value)}},{DataModelValidationFailure}=foundry.data.validation;switch(this.property){case"ac-bonus":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const armor=data.item,newValue=AELikeRuleElement.getNewValue(this.mode,armor.system.acBonus,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();armor.system.acBonus=Math.max(newValue,0),__privateMethod(this,_adjustCreatureShieldData,adjustCreatureShieldData_fn).call(this,armor);return}case"badge-max":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const effect=data.item,{badge}=effect.system;if(badge?.type!=="counter"||!badge.value||!badge.max)return;const newValue=AELikeRuleElement.getNewValue(this.mode,badge.max,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();const hardMax=badge.labels?.length??newValue;badge.max=Math.clamped(newValue,1,hardMax),badge.value=Math.clamped(badge.value,1,badge.max);return}case"badge-value":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const effect=data.item,badge=itemIsOfType(effect,"condition")?effect.system.value:effect.system.badge??{value:0};if(typeof badge.value!="number")return;const newValue=AELikeRuleElement.getNewValue(this.mode,badge.value,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();const max="max"in badge?badge.max??1/0:1/0;badge.value=Math.clamped(newValue,1,max);return}case"bulk-held-or-stowed":{const validator=ITEM_ALTERATION_VALIDATORS[this.property];if(data.alteration.value=String(data.alteration.value),!validator.isValid(data))return;data.item.system.weight.value=data.alteration.value,data.item instanceof foundry.abstract.DataModel&&(data.item.system.bulk=organizeBulkData(data.item));return}case"bulk-worn":{const validator=ITEM_ALTERATION_VALIDATORS[this.property];if(data.alteration.value=String(data.alteration.value),!validator.isValid(data))return;data.item.system.equippedBulk.value=data.alteration.value,data.item instanceof foundry.abstract.DataModel&&(data.item.system.bulk=organizeBulkData(data.item));return}case"category":{ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)&&(data.item.system.category=data.alteration.value);return}case"check-penalty":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const newValue=AELikeRuleElement.getNewValue(this.mode,data.item.system.checkPenalty,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();data.item.system.checkPenalty=newValue===null?null:Math.min(newValue,0);return}case"dex-cap":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const newValue=AELikeRuleElement.getNewValue(this.mode,data.item.system.dexCap,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();data.item.system.dexCap=Math.max(newValue,0);return}case"hardness":{if(ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)){const{system}=data.item,{value}=data.alteration,newValue=AELikeRuleElement.getNewValue(this.mode,system.hardness,value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();system.hardness=Math.max(newValue,0),__privateMethod(this,_adjustCreatureShieldData,adjustCreatureShieldData_fn).call(this,data.item)}return}case"hp-max":{if(ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)){const{hp}=data.item.system,{value}=data.alteration,newValue=AELikeRuleElement.getNewValue(this.mode,hp.max,value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();hp.max=Math.max(Math.trunc(newValue),1),"brokenThreshold"in hp&&(hp.brokenThreshold=Math.floor(hp.max/2)),__privateMethod(this,_adjustCreatureShieldData,adjustCreatureShieldData_fn).call(this,data.item)}return}case"persistent-damage":{const pdObject=isObject(data.alteration.value)?data.alteration.value:{dc:NaN},dc=Math.trunc(Math.abs(Number(pdObject?.dc)||15));data.alteration.value={...pdObject,dc};const validator=ITEM_ALTERATION_VALIDATORS[this.property];validator.isValid(data)&&(data.item.system.persistent=validator.initialize(data.alteration).value);return}case"material-type":{ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)&&(data.item.system.material.type=data.alteration.value,data.item.system.material.grade="standard","_source"in data.item&&(data.item.name=game.pf2e.system.generateItemName(data.item)));return}case"rarity":{ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)&&(data.item.system.traits.rarity=data.alteration.value);return}case"pd-recovery-dc":{const validator=ITEM_ALTERATION_VALIDATORS[this.property];if(data.alteration.value=this.resolveValue(data.alteration.value)||15,validator.isValid(data)&&data.item.system.persistent){const{persistent}=data.item.system,newValue=AELikeRuleElement.getNewValue(this.mode,persistent.dc,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();persistent.dc=Math.max(newValue,0)}return}case"frequency-max":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)||!data.item.system.frequency)return;const frequency=data.item.system.frequency,newValue=AELikeRuleElement.getNewValue(this.mode,frequency.max,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();frequency.max=newValue,frequency.value=Math.clamped(frequency.value??newValue,0,newValue);return}case"frequency-per":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)||!data.item.system.frequency)return;const newValue=__privateMethod(this,_getNewInterval,getNewInterval_fn).call(this,this.mode,data.item.system.frequency.per,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();data.item.system.frequency.per=newValue;return}case"other-tags":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const otherTags=data.item.system.traits.otherTags,newValue=AELikeRuleElement.getNewValue(this.mode,otherTags,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();this.mode==="add"?otherTags.includes(newValue)||otherTags.push(newValue):["subtract","remove"].includes(this.mode)&&otherTags.splice(otherTags.indexOf(newValue),1);return}case"speed-penalty":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const newValue=AELikeRuleElement.getNewValue(this.mode,data.item.system.speedPenalty,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();data.item.system.speedPenalty=newValue===null?null:Math.min(newValue,0);return}case"strength":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const newValue=AELikeRuleElement.getNewValue(this.mode,data.item.system.strength,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();data.item.system.strength=newValue===null?null:Math.max(newValue,0);return}case"traits":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const newValue=AELikeRuleElement.getNewValue(this.mode,data.item.system.traits.value,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();const traits=data.item.system.traits.value;this.mode==="add"?traits.includes(newValue)||traits.push(newValue):["subtract","remove"].includes(this.mode)&&traits.splice(traits.indexOf(newValue),1);return}}}};_adjustCreatureShieldData=new WeakSet,adjustCreatureShieldData_fn=__name2(function(item){if("actor"in item&&item.actor?.isOfType("character","npc")&&item.isOfType("armor")&&item.isShield){const{heldShield}=item.actor;if(item===heldShield){const shieldData=item.actor.attributes.shield;shieldData.ac=item.system.acBonus,shieldData.hardness=item.system.hardness,shieldData.hp.max=item.system.hp.max,shieldData.brokenThreshold=Math.floor(item.system.hp.max/2)}}},"#adjustCreatureShieldData"),_getNewInterval=new WeakSet,getNewInterval_fn=__name2(function(mode,current,newValue){const{DataModelValidationFailure}=foundry.data.validation;if(!objectHasKey(CONFIG.PF2E.frequencies,newValue))return new DataModelValidationFailure({invalidValue:current,fallback:!1});if(mode==="override")return newValue;function getDuration(key){return key==="turn"||key==="round"?Duration.fromISO("PT6S"):key==="day"?Duration.fromISO("PT24H"):Duration.fromISO(key)}__name(getDuration,"getDuration"),__name2(getDuration,"getDuration");const newIsLonger=newValue==="round"&¤t==="turn"||newValue==="PT24H"&¤t==="day"||getDuration(newValue)>getDuration(current);return mode==="upgrade"&&newIsLonger||mode==="downgrade"&&!newIsLonger?newValue:current},"#getNewInterval"),__name2(_ItemAlteration,"ItemAlteration"),__publicField(_ItemAlteration,"VALID_PROPERTIES",["ac-bonus","badge-max","badge-value","bulk-held-or-stowed","bulk-worn","category","check-penalty","dex-cap","hardness","hp-max","material-type","pd-recovery-dc","persistent-damage","rarity","frequency-max","frequency-per","other-tags","speed-penalty","strength","traits"]);let ItemAlteration=_ItemAlteration;const _EphemeralEffectRuleElement=class extends RuleElementPF2e{static{__name(this,"_EphemeralEffectRuleElement")}constructor(){super(...arguments),__privateAdd(this,_createDeferredEffect)}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),affects:new fields2.StringField({required:!0,choices:["target","origin"],initial:"target"}),selectors:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,nullable:!1,initial:void 0})),uuid:new fields2.StringField({required:!0,blank:!1,nullable:!1,initial:void 0}),adjustName:new fields2.BooleanField({required:!0,nullable:!1,initial:!0}),alterations:new fields2.ArrayField(new fields2.EmbeddedDataField(ItemAlteration),{required:!1,nullable:!1,initial:[]})}}static validateJoint(data){if(super.validateJoint(data),data.selectors.length===0)throw Error("must have at least one selector")}afterPrepareData(){for(const selector of this.resolveInjectedProperties(this.selectors)){const deferredEffect=__privateMethod(this,_createDeferredEffect,createDeferredEffect_fn).call(this);(this.actor.synthetics.ephemeralEffects[selector]??={target:[],origin:[]})[this.affects].push(deferredEffect)}}};_createDeferredEffect=new WeakSet,createDeferredEffect_fn=__name2(function(){return async(params={})=>{if(!this.test(params.test??this.actor.getRollOptions()))return null;const uuid=this.resolveInjectedProperties(this.uuid);if(!UUIDUtils.isItemUUID(uuid))return this.failValidation(`"${uuid}" does not look like a UUID`),null;const effect=game.pf2e.ConditionManager.conditions.get(uuid)??await fromUuid(uuid);if(!(effect instanceof ItemPF2e&&effect.isOfType("condition","effect")))return this.failValidation(`unable to find effect or condition item with uuid "${uuid}"`),null;const source=effect.toObject();if(source.system.rules.some(r=>typeof r.key=="string"&&(r.key==="ChoiceSet"||r.key==="GrantItem"&&!("inMemoryOnly"in r&&r.inMemoryOnly===!0)))&&this.failValidation("an ephemeral effect may not include a choice set or grant"),this.adjustName){const label=this.getReducedLabel();source.name=`${source.name} (${label})`}try{for(const alteration of this.alterations)alteration.applyTo(source)}catch(error){return error instanceof Error&&this.failValidation(error.message),null}return source}},"#createDeferredEffect"),__name2(_EphemeralEffectRuleElement,"EphemeralEffectRuleElement");let EphemeralEffectRuleElement=_EphemeralEffectRuleElement;const _FastHealingRuleElement=class extends RuleElementPF2e{static{__name(this,"_FastHealingRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1}),type:new fields2.StringField({required:!1,nullable:!1,choices:["fast-healing","regeneration"],initial:"fast-healing"}),details:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),deactivatedBy:new fields2.ArrayField(new fields2.StringField({required:!0,nullable:!1,blank:!1}),{required:!1,initial:void 0})}}static validateJoint(data){if(super.validateJoint(data),data.type==="fast-healing"){if(data.deactivatedBy)throw data.ignored=!0,Error("deactivatedBy is only valid for type regeneration");data.details&&(data.details=game.i18n.localize(data.details))}else if(data.type==="regeneration"){if(data.details)throw data.ignored=!0,Error("details is only valid for type fast-healing");if(data.deactivatedBy?.length){const typesArr=data.deactivatedBy.map(type=>objectHasKey(CONFIG.PF2E.weaknessTypes,type)?game.i18n.localize(CONFIG.PF2E.weaknessTypes[type]):type),types=localizeList(typesArr);data.details=game.i18n.format("PF2E.Encounter.Broadcast.FastHealing.DeactivatedBy",{types})}}}async onTurnStart(){if(!this.test())return;const value=this.resolveValue(this.value);if(typeof value!="number"&&typeof value!="string")return this.failValidation("value must be a number or a roll formula");const roll=(await new DamageRoll(`${value}`).evaluate({async:!0})).toJSON(),receivedMessage=game.i18n.localize(`PF2E.Encounter.Broadcast.FastHealing.${this.type}.ReceivedMessage`),postFlavor=`
${this.details??this.getReducedLabel()}
`,flavor=`
${receivedMessage}
${postFlavor}`,rollMode=this.actor.hasPlayerOwner?"publicroll":"gmroll",speaker=ChatMessagePF2e.getSpeaker({actor:this.actor,token:this.token});ChatMessagePF2e.create({flavor,speaker,type:CONST.CHAT_MESSAGE_TYPES.ROLL,rolls:[roll]},{rollMode})}};__name2(_FastHealingRuleElement,"FastHealingRuleElement"),__publicField(_FastHealingRuleElement,"validActorTypes",["character","npc","familiar"]);let FastHealingRuleElement=_FastHealingRuleElement;const _FixedProficiencyRuleElement=class extends RuleElementPF2e{static{__name(this,"_FixedProficiencyRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1}),value:new ResolvableValueField({required:!0,initial:void 0}),ability:new fields2.StringField({required:!0,choices:[...ATTRIBUTE_ABBREVIATIONS]})}}static validateJoint(data){data.selector==="ac"&&(data.ability="dex")}beforePrepareData(){const selector=this.resolveInjectedProperties(this.selector),proficiencyBonus=Number(this.resolveValue(this.value))||0,abilityModifier=this.ability?this.actor.system.abilities[this.ability].mod:0,modifier=new ModifierPF2e({type:"proficiency",slug:this.slug??sluggify(this.label),label:this.label,modifier:proficiencyBonus+abilityModifier});(this.actor.synthetics.modifiers[selector]??=[]).push(()=>modifier)}afterPrepareData(){const selector=this.resolveInjectedProperties(this.selector),systemData=this.actor.system,proficiency=SKILL_EXPANDED[selector]?.shortForm??selector,statistic=setHasElement(SKILL_ABBREVIATIONS,proficiency)?this.actor.skills[proficiency]:proficiency==="ac"?systemData.attributes.ac:null;if(statistic){const toIgnore=statistic.modifiers.filter(m=>m.type==="proficiency"&&m.slug!==this.slug);for(const modifier of toIgnore)modifier.predicate=new PredicatePF2e(`overridden-by-${this.slug}`)}}};__name2(_FixedProficiencyRuleElement,"FixedProficiencyRuleElement"),__publicField(_FixedProficiencyRuleElement,"validActorTypes",["character"]);let FixedProficiencyRuleElement=_FixedProficiencyRuleElement;const _FlatModifierRuleElement=class extends RuleElementPF2e{static{__name(this,"_FlatModifierRuleElement")}constructor(source,options){super(source,options),!this.item.isOfType("physical")&&this.type!=="item"&&(this.fromEquipment=!1),this.type==="ability"&&(this.ability?(this.slug=this.ability,this.label=CONFIG.PF2E.abilities[this.ability],this.value=`@actor.abilities.${source.ability}.mod`):this.failValidation('A flat modifier of type "ability" must also have an "ability" property with an ability abbreviation')),this.critical=typeof source.critical=="boolean"&&this.selectors.some(s=>s.includes("damage"))?source.critical:null,this.force&&this.type==="untyped"&&this.failValidation("A forced bonus or penalty must have a type"),this.removeAfterRoll&&!this.item.isOfType("effect")&&this.failValidation(" removeAfterRoll: may only be used with effects")}static validateJoint(data){if(super.validateJoint(data),data.type!=="ability"&&data.value===void 0)throw Error('must have defined value if type is not "ability"')}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,initial:void 0})),type:new fields2.StringField({required:!0,choices:Array.from(MODIFIER_TYPES),initial:"untyped"}),ability:new fields2.StringField({required:!1,choices:CONFIG.PF2E.abilities,initial:void 0}),min:new fields2.NumberField({required:!1,nullable:!1,initial:void 0}),max:new fields2.NumberField({required:!1,nullable:!1,initial:void 0}),force:new fields2.BooleanField,hideIfDisabled:new fields2.BooleanField,fromEquipment:new fields2.BooleanField({required:!0,nullable:!1,initial:!0}),damageType:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:void 0}),damageCategory:new fields2.StringField({required:!1,blank:!1,choices:damageCategoriesUnique,initial:void 0}),critical:new fields2.BooleanField({required:!1,nullable:!0,initial:null}),value:new ResolvableValueField({required:!1,nullable:!1,initial:void 0}),removeAfterRoll:new DataUnionField([new StrictStringField({required:!1,nullable:!1,choices:["if-enabled"],initial:void 0}),new StrictBooleanField({required:!1,nullable:!1,initial:void 0}),new PredicateField({required:!1,nullable:!1,initial:void 0})],{required:!1,nullable:!1,initial:!1})}}get selectors(){return this.selector}beforePrepareData(){if(this.ignored)return;const label=this.getReducedLabel(),slug=this.slug??sluggify(label),selectors=this.selectors.map(s=>this.resolveInjectedProperties(s)).filter(s=>!!s);if(selectors.length===0)return this.failValidation("must have at least one selector");for(const selector of selectors){if(selector==="null")continue;const construct=__name2((options={})=>{const resolvedValue=Number(this.resolveValue(this.value,0,options))||0;if(this.ignored)return null;const finalValue=Math.clamped(resolvedValue,this.min??resolvedValue,this.max??resolvedValue);if(game.pf2e.variantRules.AutomaticBonusProgression.suppressRuleElement(this,finalValue))return null;const damageType=this.damageType&&this.resolveInjectedProperties(this.damageType,{warn:!1})||null;if(damageType!==null&&!objectHasKey(CONFIG.PF2E.damageTypes,damageType))return this.test(options.test??[])&&this.failValidation(`Unrecognized damage type: ${damageType}`),null;const modifier=new ModifierPF2e({slug,label,modifier:finalValue,type:this.type,ability:this.type==="ability"?this.ability:null,predicate:this.resolveInjectedProperties(this.predicate),rule:this,force:this.force,damageType,damageCategory:this.damageCategory,critical:this.critical,hideIfDisabled:this.hideIfDisabled,source:this.item.uuid});return options.test&&modifier.test(options.test),modifier},"construct");(this.actor.synthetics.modifiers[selector]??=[]).push(construct)}}async afterRoll({check,rollOptions}){if(this.ignored||!this.removeAfterRoll||!this.item.isOfType("effect"))return;(this.removeAfterRoll===!0||this.removeAfterRoll==="if-enabled"&&check.modifiers.some(m=>m.rule===this&&m.enabled)||Array.isArray(this.removeAfterRoll)&&this.removeAfterRoll.test(rollOptions))&&await this.item.delete()}};__name2(_FlatModifierRuleElement,"FlatModifierRuleElement");let FlatModifierRuleElement=_FlatModifierRuleElement;const _GrantItemRuleElement=class extends RuleElementPF2e{static{__name(this,"_GrantItemRuleElement")}constructor(data,options){data.inMemoryOnly&&(data.priority??=99),super(data,options),__privateAdd(this,_getOnDeleteActions),__privateAdd(this,_applyChoiceSelections),__privateAdd(this,_setGrantFlags),__privateAdd(this,_runGrantedItemPreCreates),__privateAdd(this,_createInMemoryCondition),__privateAdd(this,_trackItem),__publicField(this,"grantedId"),__publicField(this,"preselectChoices"),__publicField(this,"onDeleteActions"),this.inMemoryOnly?(this.reevaluateOnUpdate=!0,this.allowDuplicate=!0):this.reevaluateOnUpdate&&(this.allowDuplicate=!1),this.onDeleteActions=__privateMethod(this,_getOnDeleteActions,getOnDeleteActions_fn).call(this,data);const isValidPreselect=__name2(p=>Object.values(p).every(v=>["string","number"].includes(typeof v)),"isValidPreselect");if(this.preselectChoices=isObject(data.preselectChoices)&&isValidPreselect(data.preselectChoices)?deepClone(data.preselectChoices):{},this.grantedId=this.item.flags.pf2e.itemGrants[this.flag??""]?.id??null,this.track){const grantedItem=this.actor.inventory.get(this.grantedId??"")??null;__privateMethod(this,_trackItem,trackItem_fn).call(this,grantedItem)}this.item.isOfType("physical")&&this.failValidation("parent item must not be physical")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),uuid:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:void 0,label:"PF2E.UUID.Label"}),flag:new SlugField({required:!0,nullable:!0,initial:null,camel:"dromedary"}),reevaluateOnUpdate:new fields2.BooleanField({label:"PF2E.RuleEditor.GrantItem.ReevaluateOnUpdate"}),inMemoryOnly:new fields2.BooleanField,allowDuplicate:new fields2.BooleanField({initial:!0,label:"PF2E.RuleEditor.GrantItem.AllowDuplicate"}),alterations:new StrictArrayField(new fields2.EmbeddedDataField(ItemAlteration)),track:new fields2.BooleanField}}static validateJoint(data){if(super.validateJoint(data),data.track&&!data.flag)throw Error("must have explicit flag set if granted item is tracked")}async preCreate(args){if(this.inMemoryOnly)return;const{itemSource,pendingItems,context}=args,ruleSource=args.ruleSource;if(this.reevaluateOnUpdate&&this.predicate.length===0)return ruleSource.ignored=!0,this.failValidation("`reevaluateOnUpdate` may only be used with a predicate.");const uuid=this.resolveInjectedProperties(this.uuid),grantedItem=await(async()=>{try{return(await fromUuid(uuid))?.clone()??null}catch(error){return console.error(error),null}})();if(!(grantedItem instanceof ItemPF2e)||(ruleSource.flag=typeof ruleSource.flag=="string"&&ruleSource.flag.length>0?sluggify(ruleSource.flag,{camel:"dromedary"}):(()=>{const defaultFlag=sluggify(grantedItem.slug??grantedItem.name,{camel:"dromedary"}),flagPattern=new RegExp(`^${defaultFlag}\\d*$`),itemGrants=itemSource.flags?.pf2e?.itemGrants??{},nthGrant=Object.keys(itemGrants).filter(g=>flagPattern.test(g)).length;return nthGrant>0?`${defaultFlag}${nthGrant+1}`:defaultFlag})(),this.flag=String(ruleSource.flag),!this.test()))return;const existingItem=this.actor.items.find(i=>i.sourceId===uuid);if(!this.allowDuplicate&&existingItem){__privateMethod(this,_setGrantFlags,setGrantFlags_fn).call(this,itemSource,existingItem),ui.notifications.info(game.i18n.format("PF2E.UI.RuleElements.GrantItem.AlreadyHasItem",{actor:this.actor.name,item:grantedItem.name}));return}itemSource._id??=randomID();const grantedSource=grantedItem.toObject();grantedSource._id=randomID(),itemSource.type==="effect"&&grantedSource.type==="effect"&&(grantedSource.system.level.value=itemSource.system?.level?.value??grantedSource.system.level.value),grantedSource.flags=mergeObject(grantedSource.flags,{core:{sourceId:uuid}});const tempGranted=new ItemProxyPF2e(deepClone(grantedSource),{parent:this.actor});if(tempGranted.isOfType("affliction","condition","effect")&&this.actor.isImmuneTo(tempGranted)){ruleSource.ignored=!0;return}tempGranted.prepareActorData?.();for(const rule of tempGranted.prepareRuleElements({suppressWarnings:!0}))rule.onApplyActiveEffects?.();__privateMethod(this,_applyChoiceSelections,applyChoiceSelections_fn).call(this,tempGranted);try{for(const alteration of this.alterations)alteration.applyTo(grantedSource)}catch(error){error instanceof Error&&this.failValidation(error.message)}if(!this.ignored){for(const item of[this.item,tempGranted])if(item.isOfType("class","feat")){const prefix=item.isOfType("class")||!item.isFeature?item.type:"feature",slug=item.slug??sluggify(item.name);this.actor.rollOptions.all[`self:${prefix}:${slug}`]=!0}this.grantedId=grantedSource._id,context.keepId=!0,__privateMethod(this,_setGrantFlags,setGrantFlags_fn).call(this,itemSource,grantedSource),__privateMethod(this,_trackItem,trackItem_fn).call(this,tempGranted),args.reevaluation||await __privateMethod(this,_runGrantedItemPreCreates,runGrantedItemPreCreates_fn).call(this,args,tempGranted,grantedSource,context),pendingItems.push(grantedSource)}}async preUpdateActor(){const noAction={create:[],delete:[]};if(!this.reevaluateOnUpdate||this.inMemoryOnly)return noAction;if(this.grantedId&&this.actor.items.has(this.grantedId))return this.test()?noAction:{create:[],delete:[this.grantedId]};const itemSource=this.item.toObject(),ruleSource=itemSource.system.rules[this.sourceIndex??-1];if(!ruleSource)return noAction;const pendingItems=[],context={parent:this.actor,render:!1};if(await this.preCreate({itemSource,pendingItems,ruleSource,context,reevaluation:!0}),pendingItems.length>0){const updatedGrants=itemSource.flags.pf2e?.itemGrants??{};return await this.item.update({"flags.pf2e.itemGrants":updatedGrants},{render:!1}),{create:pendingItems,delete:[]}}return noAction}onApplyActiveEffects(){const condition=__privateMethod(this,_createInMemoryCondition,createInMemoryCondition_fn).call(this);if(!condition)return;const{actor}=this;condition.rules=condition.prepareRuleElements();for(const rule of condition.rules)rule.onApplyActiveEffects?.(),rule.beforePrepareData?.(),actor.rules.push(rule);actor.conditions.set(condition.id,condition)}};_getOnDeleteActions=new WeakSet,getOnDeleteActions_fn=__name2(function(data){const actions=data.onDeleteActions;if(isObject(actions)){const ACTIONS=_GrantItemRuleElement.ON_DELETE_ACTIONS;return tupleHasValue(ACTIONS,actions.granter)||tupleHasValue(ACTIONS,actions.grantee)?pick(actions,[actions.granter?"granter":[],actions.grantee?"grantee":[]].flat()):null}return null},"#getOnDeleteActions"),_applyChoiceSelections=new WeakSet,applyChoiceSelections_fn=__name2(function(grantedItem){const source=grantedItem._source;for(const[flag,selection]of Object.entries(this.preselectChoices??{})){const rule=grantedItem.rules.find(rule2=>rule2 instanceof ChoiceSetRuleElement&&rule2.flag===flag);if(rule){const ruleSource=source.system.rules[grantedItem.rules.indexOf(rule)],resolvedSelection=this.resolveInjectedProperties(selection);rule.selection=ruleSource.selection=resolvedSelection}}},"#applyChoiceSelections"),_setGrantFlags=new WeakSet,setGrantFlags_fn=__name2(function(granter,grantee){const flags=mergeObject(granter.flags??{},{pf2e:{itemGrants:{}}});if(!this.flag)throw ErrorPF2e("Unexpected failure looking up RE flag key");flags.pf2e.itemGrants[this.flag]={id:grantee instanceof ItemPF2e?grantee.id:grantee._id,onDelete:this.onDeleteActions?.grantee??"detach"};const grantedBy={id:granter._id,onDelete:this.onDeleteActions?.granter??(setHasElement(PHYSICAL_ITEM_TYPES,grantee.type)?"detach":"cascade")};grantee instanceof ItemPF2e?grantee.update({"flags.pf2e.grantedBy":grantedBy},{render:!1}):grantee.flags=mergeObject(grantee.flags??{},{pf2e:{grantedBy}})},"#setGrantFlags"),_runGrantedItemPreCreates=new WeakSet,runGrantedItemPreCreates_fn=__name2(async function(originalArgs,grantedItem,grantedSource,context){for(const rule of grantedItem.rules){const ruleSource=grantedSource.system.rules[grantedItem.rules.indexOf(rule)];await rule.preCreate?.({...originalArgs,itemSource:grantedSource,ruleSource,context})}},"#runGrantedItemPreCreates"),_createInMemoryCondition=new WeakSet,createInMemoryCondition_fn=__name2(function(){if(!this.inMemoryOnly||!this.test())return null;const validationFailure="an in-memory-only grant must be a condition",uuid=this.resolveInjectedProperties(this.uuid);if(!UUIDUtils.isItemUUID(uuid))return this.failValidation(validationFailure),null;const conditionSource=game.pf2e.ConditionManager.conditions.get(uuid)?.toObject();if(!conditionSource)return this.failValidation(validationFailure),null;if(this.actor.isImmuneTo(conditionSource.system.slug))return null;for(const alteration of this.alterations)alteration.applyTo(conditionSource);const flags={pf2e:{grantedBy:{id:this.item.id,onDelete:"cascade"}}};conditionSource.flags.pf2e?.grantedBy;const condition=new ConditionPF2e(mergeObject(conditionSource,{_id:randomID(),flags,system:{references:{parent:{id:this.item.id}}}}),{parent:this.actor});return condition.prepareSiblingData(),condition.prepareActorData(),condition},"#createInMemoryCondition"),_trackItem=new WeakSet,trackItem_fn=__name2(function(grantedItem){if(!(this.track&&this.flag&&this.grantedId&&grantedItem instanceof PhysicalItemPF2e))return;this.actor.flags.pf2e.trackedItems[this.flag]=this.grantedId;const slug=sluggify(this.flag),rollOptionsAll=this.actor.rollOptions.all;for(const statement of grantedItem.getRollOptions(slug))rollOptionsAll[statement]=!0},"#trackItem"),__name2(_GrantItemRuleElement,"GrantItemRuleElement"),__publicField(_GrantItemRuleElement,"validActorTypes",["character","npc","familiar"]),__publicField(_GrantItemRuleElement,"ON_DELETE_ACTIONS",["cascade","detach","restrict"]);let GrantItemRuleElement=_GrantItemRuleElement;const _ItemAlterationRuleElement=class extends RuleElementPF2e{static{__name(this,"_ItemAlterationRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data,baseSchema=super.defineSchema(),PRIORITIES=AELikeRuleElement.CHANGE_MODE_DEFAULT_PRIORITIES;return baseSchema.priority.initial=d=>(PRIORITIES[String(d.mode)]??50)+100,{...baseSchema,itemId:new fields2.StringField({required:!1,nullable:!1,blank:!1,initial:void 0}),itemType:new fields2.StringField({required:!1,nullable:!1,choices:mapValues$1(CONFIG.PF2E.Item.documentClasses,key=>`TYPES.Item.${key}`),initial:void 0}),...ItemAlteration.defineSchema()}}static validateJoint(data){if(super.validateJoint(data),!data.itemId&&!data.itemType)throw Error("one of itemId and itemType must be defined")}onApplyActiveEffects(){if(this.ignored)return;const actorRollOptions=this.predicate.length>0?this.actor.getRollOptions():[];try{const items=this.itemId?compact([this.actor.items.get(this.resolveInjectedProperties(this.itemId))]):this.itemType==="condition"?this.actor.conditions:this.actor.itemTypes[this.itemType];for(const item of items){const itemRollOptions=this.predicate.length>0?item.getRollOptions("item"):[],rollOptions=[...actorRollOptions,...itemRollOptions];if(this.test(rollOptions)){const data=pick$1(this,["mode","property","value"]);new ItemAlteration(data,{parent:this}).applyTo(item)}}}catch(error){error instanceof Error&&this.failValidation(error.message)}}async preCreate(){if(this.ignored||this.property!=="hp-max")return;const itemsOfType=this.itemType?this.actor.itemTypes[this.itemType]:[],actorRollOptions=this.actor.getRollOptions(),updates=itemsOfType.filter(i=>this.test([...actorRollOptions,...i.getRollOptions("item")])).flatMap(item=>{const source=item.toObject(),alteration=new ItemAlteration(pick$1(this,["mode","property","value"]),{parent:this});alteration.applyTo(source),alteration.applyTo(item);const newHP=source.system.hp,oldHP=item._source.system.hp,newHPValue=Math.floor(oldHP.value*(newHP.max/oldHP.max));return newHPValue===oldHP.value?[]:{_id:item.id,"system.hp.value":newHPValue}});updates.length>0&&await this.actor.updateEmbeddedDocuments("Item",updates,{render:!1})}};__name2(_ItemAlterationRuleElement,"ItemAlterationRuleElement");let ItemAlterationRuleElement=_ItemAlterationRuleElement;const _LoseHitPointsRuleElement=class extends RuleElementPF2e{static{__name(this,"_LoseHitPointsRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,initial:void 0}),reevaluateOnUpdate:new fields2.BooleanField({required:!1,initial:!1}),recoverable:new fields2.BooleanField({required:!1,initial:!0})}}onCreate(actorUpdates){if(this.ignored)return;const value=Math.trunc(Math.abs(Number(this.resolveValue(this.value))||0)),currentHP=this.actor._source.system.attributes.hp.value;actorUpdates["system.attributes.hp.value"]=Math.max(currentHP-value,0)}beforePrepareData(){if(this.ignored)return;const{actor}=this;if(!this.recoverable){const value=Math.trunc(Math.abs(Number(this.resolveValue(this.value))||0));actor.system.attributes.hp.unrecoverable+=value}}async preUpdate(changes){if(!this.reevaluateOnUpdate||this.ignored)return;const previousValue=Math.trunc(Math.abs(Number(this.resolveValue(this.value))||0)),newItem=this.item.clone(changes),rule=newItem.system.rules.find(r=>r.key===this.key),valueChange=Math.trunc(Math.abs(Number(this.resolveValue(String(rule?.value),0,{resolvables:{item:newItem}}))))-previousValue;if(valueChange>0){const currentHP=this.actor._source.system.attributes.hp.value;await this.actor.update({"system.attributes.hp.value":Math.max(currentHP-valueChange,0)},{render:!1})}}};__name2(_LoseHitPointsRuleElement,"LoseHitPointsRuleElement"),__publicField(_LoseHitPointsRuleElement,"validActorTypes",["character","familiar","npc"]);let LoseHitPointsRuleElement=_LoseHitPointsRuleElement;const ARMOR_CATEGORIES=new Set(["unarmored","light","medium","heavy","light-barding","heavy-barding"]),_MartialProficiencyRuleElement=class extends RuleElementPF2e{static{__name(this,"_MartialProficiencyRuleElement")}static defineSchema(){return{...super.defineSchema(),kind:new StrictStringField({required:!0,nullable:!1,choices:["attack","defense"],initial:"attack"}),definition:new PredicateField({required:!0,nullable:!1}),sameAs:new StrictStringField({required:!1,nullable:!1,choices:[...WEAPON_CATEGORIES,...ARMOR_CATEGORIES]}),maxRank:new StrictStringField({required:!1,nullable:!1,choices:["trained","expert","master","legendary"]}),value:new ResolvableValueField({required:!1,initial:void 0})}}constructor(data,options){super({priority:9,...data},options),this.slug??=sluggify(this.label)}onApplyActiveEffects(){if(!this.test())return;const rank=Math.clamped(Number(this.resolveValue(this.value))||1,1,4),key=this.kind==="attack"?"attacks":"defenses";this.actor.system.proficiencies[key][this.slug]={definition:this.resolveInjectedProperties(this.definition),immutable:!0,label:this.label,sameAs:this.sameAs,rank,maxRank:this.maxRank,value:0,breakdown:""}}};__name2(_MartialProficiencyRuleElement,"MartialProficiencyRuleElement"),__publicField(_MartialProficiencyRuleElement,"validActorTypes",["character"]);let MartialProficiencyRuleElement=_MartialProficiencyRuleElement;const _MultipleAttackPenaltyRuleElement=class extends RuleElementPF2e{static{__name(this,"_MultipleAttackPenaltyRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1,label:"PF2E.RuleEditor.General.Selector"}),value:new ResolvableValueField({required:!0,initial:void 0,label:"PF2E.RuleEditor.General.Value"})}}beforePrepareData(){if(this.ignored)return;const selector=this.resolveInjectedProperties(this.selector),value=Number(this.resolveValue(this.value))||0;if(selector&&value&&value<0){const map2={label:game.i18n.format("PF2E.UI.RuleElements.MultipleAttackPenalty.Breakdown",{label:this.label}),penalty:value,predicate:this.predicate};(this.actor.synthetics.multipleAttackPenalties[selector]??=[]).push(map2)}else this.failValidation("must have a negative value")}};__name2(_MultipleAttackPenaltyRuleElement,"MultipleAttackPenaltyRuleElement");let MultipleAttackPenaltyRuleElement=_MultipleAttackPenaltyRuleElement;const _RollNoteRuleElement=class extends RuleElementPF2e{static{__name(this,"_RollNoteRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,initial:void 0}),{required:!0,nullable:!1}),title:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),visibility:new fields2.StringField({required:!0,nullable:!0,choices:["gm","owner"],initial:null}),outcome:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,choices:DEGREE_OF_SUCCESS_STRINGS}),{required:!1,nullable:!1,initial:void 0}),text:new DataUnionField([new StrictStringField({required:!0,blank:!1}),new ResolvableValueField],{required:!0,nullable:!1})}}beforePrepareData(){if(!this.ignored)for(const selector of this.resolveInjectedProperties(this.selector)){if(selector==="null")continue;const title=this.resolveInjectedProperties(this.title)?.trim()??null,text=this.resolveInjectedProperties(String(this.resolveValue(this.text,"",{evaluate:!1}))).trim();if(!text)return this.failValidation("text field resolved empty");const note=new RollNotePF2e({selector,title:title?this.getReducedLabel(title):null,text,predicate:this.resolveInjectedProperties(this.predicate),outcome:this.outcome,visibility:this.visibility,rule:this});(this.actor.synthetics.rollNotes[selector]??=[]).push(note)}}};__name2(_RollNoteRuleElement,"RollNoteRuleElement");let RollNoteRuleElement=_RollNoteRuleElement;const _RollOptionRuleElement=class extends RuleElementPF2e{static{__name(this,"_RollOptionRuleElement")}constructor(source,options){super(source,options),__privateAdd(this,_resolveOption),__privateAdd(this,_setFlag),__privateAdd(this,_setRollOption2),source.removeAfterRoll&&!this.item.isOfType("effect")&&this.failValidation("removeAfterRoll may only be used on rule elements from effect items"),this.toggleable==="totm"&&!game.settings.get("pf2e","totmToggles")&&(this.ignored=!0);const firstSuboption=this.suboptions.at(0);firstSuboption&&this.suboptions.every(s=>!s.selected)&&(firstSuboption.selected=!0)}static defineSchema(){const{fields:fields2}=foundry.data,baseSchema=super.defineSchema();return baseSchema.priority.initial=AELikeRuleElement.CHANGE_MODE_DEFAULT_PRIORITIES.override,{...baseSchema,domain:new fields2.StringField({required:!0,nullable:!1,initial:"all",blank:!1}),option:new fields2.StringField({required:!0,nullable:!1,blank:!1}),phase:new fields2.StringField({required:!1,nullable:!1,choices:deepClone(AELikeRuleElement.PHASES),initial:"applyAEs"}),suboptions:new fields2.ArrayField(new fields2.SchemaField({label:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:void 0}),value:new StrictStringField({required:!0,nullable:!1,blank:!1,initial:void 0}),predicate:new PredicateField,selected:new fields2.BooleanField}),{required:!1,nullable:!1,initial:[],validate:v=>Array.isArray(v)&&v.length!==1,validationError:"must have zero or 2+ suboptions"}),value:new ResolvableValueField({required:!1,initial:d=>!d.toggleable,validate:v=>["boolean","string"].includes(typeof v),validationError:"must be a boolean, string, or otherwise omitted"}),toggleable:new DataUnionField([new StrictStringField({required:!1,nullable:!1,choices:["totm"],initial:void 0}),new StrictBooleanField({required:!1,nullable:!1,initial:!1})],{required:!1,nullable:!1,initial:void 0}),placement:new fields2.StringField({required:!1,nullable:!1,initial:void 0}),disabledIf:new PredicateField({required:!1,initial:void 0}),disabledValue:new fields2.BooleanField({required:!1,initial:void 0}),alwaysActive:new fields2.BooleanField({required:!1,initial:void 0}),count:new fields2.BooleanField({required:!1,initial:void 0}),removeAfterRoll:new fields2.BooleanField({required:!1,initial:void 0})}}static validateJoint(source){if(super.validateJoint(source),source.suboptions.length>0&&!source.toggleable)throw Error(" suboptions: must be omitted if not toggleable");if(source.disabledIf&&!source.toggleable)throw Error(" disabledIf: must be false if not toggleable");if(source.count&&source.toggleable)throw Error(" count: must be false if toggleable");if(typeof source.disabledValue=="boolean"&&(!source.toggleable||!source.disabledIf))throw Error(" disabledValue: may only be included if toggeable and there is a disabledIf predicate.");if(source.alwaysActive&&(!source.toggleable||source.suboptions.length===0))throw Error(" alwaysActive: must be false unless toggleable and containing suboptions");if(source.placement&&!source.toggleable)throw Error(" placement: may only be present if toggleable")}onApplyActiveEffects(){this.phase==="applyAEs"&&__privateMethod(this,_setRollOption2,setRollOption_fn2).call(this)}beforePrepareData(){this.phase==="beforeDerived"&&__privateMethod(this,_setRollOption2,setRollOption_fn2).call(this)}afterPrepareData(){this.phase==="afterDerived"&&__privateMethod(this,_setRollOption2,setRollOption_fn2).call(this)}resolveValue(){return this.toggleable==="totm"&&!game.settings.get("pf2e","totmToggles")?!1:this.alwaysActive?!0:!!super.resolveValue(this.value)}async toggle(newValue=!this.resolveValue(),newSuboption=null){if(!this.toggleable)throw ErrorPF2e("Attempted to toggle non-toggleable roll option");const rulesSource=this.item.toObject().system.rules,thisSource=typeof this.sourceIndex=="number"?rulesSource.at(this.sourceIndex):null;if(!thisSource)return null;if(thisSource.value=newValue,newSuboption&&Array.isArray(thisSource.suboptions)&&thisSource.suboptions.every(o=>isObject(o)))for(const suboption of thisSource.suboptions)suboption.selected=suboption.value===newSuboption;return(await this.actor.updateEmbeddedDocuments("Item",[{_id:this.item.id,"system.rules":rulesSource}])).length===1?newValue:null}beforeRoll(domains,rollOptions){if(!(this.test(rollOptions)&&domains.includes(this.domain)))return;this.value=this.resolveValue();const option=__privateMethod(this,_resolveOption,resolveOption_fn).call(this);this.value?rollOptions.add(option):rollOptions.delete(option)}async afterRoll({domains,rollOptions}){const option=__privateMethod(this,_resolveOption,resolveOption_fn).call(this);!this.ignored&&this.removeAfterRoll&&this.value&&this.actor.items.has(this.item.id)&&domains.includes(this.domain)&&rollOptions.has(option)&&(game.settings.get("pf2e","automation.removeExpiredEffects")?await this.item.delete():game.settings.get("pf2e","automation.effectExpiration")&&await this.item.update({"system.duration.value":-1,"system.expired":!0}))}};_resolveOption=new WeakSet,resolveOption_fn=__name2(function({appendSuboption=!0}={}){const baseOption=this.resolveInjectedProperties(this.option).replace(/[^-:\w]/g,"").replace(/:+/g,":").replace(/-+/g,"-").trim();if(appendSuboption){const selectedSuboption=this.suboptions.find(o=>o.selected);return selectedSuboption?`${baseOption}:${selectedSuboption.value}`:baseOption}else return baseOption},"#resolveOption"),_setFlag=new WeakSet,setFlag_fn=__name2(function(value){const suboption=this.suboptions.find(o=>o.selected)??this.suboptions.at(0);if(suboption){const flagKey=sluggify(__privateMethod(this,_resolveOption,resolveOption_fn).call(this,{appendSuboption:!1}),{camel:"dromedary"});if(value){const flagValue=/^\d+$/.test(suboption.value)?Number(suboption.value):suboption.value;this.item.flags.pf2e.rulesSelections[flagKey]=flagValue}else this.item.flags.pf2e.rulesSelections[flagKey]=null}},"#setFlag"),_setRollOption2=new WeakSet,setRollOption_fn2=__name2(function(){this.domain=this.resolveInjectedProperties(this.domain);const isStandardDomain=/^[-a-z0-9]+$/.test(this.domain)&&/[a-z]/.test(this.domain),isIdDomain=/^[a-zA-Z0-9]{16}-[-a-z0-9]+[a-z0-9]$/.test(this.domain);if(!isStandardDomain&&!isIdDomain)return this.failValidation("domain must be a string consisting of only lowercase letters, numbers, and hyphens.");const optionSet=new Set([this.actor.getRollOptions([this.domain]),this.parent.getRollOptions("parent")].flat());if(!this.test(optionSet))return __privateMethod(this,_setFlag,setFlag_fn).call(this,!1);const{rollOptions}=this.actor,domainRecord=rollOptions[this.domain]??={},baseOption=this.option=__privateMethod(this,_resolveOption,resolveOption_fn).call(this,{appendSuboption:!1});if(!baseOption){this.failValidation('The "option" property must be a string consisting of only letters, numbers, colons, and hyphens');return}if(this.count){const existing=Object.keys(domainRecord).flatMap(key=>({key,count:Number(new RegExp(`^${baseOption}:(\\d+)$`).exec(key)?.[1])})).find(keyAndCount=>!!keyAndCount.count);existing?(delete domainRecord[existing.key],domainRecord[`${baseOption}:${existing.count+1}`]=!0):domainRecord[`${baseOption}:1`]=!0}else{const suboptions=this.suboptions.filter(s=>s.predicate.test(optionSet));if(suboptions.length>0&&!suboptions.some(s=>s.selected)){suboptions[0].selected=!0;for(const otherSuboption of this.suboptions)otherSuboption!==suboptions[0]&&(otherSuboption.selected=!1)}else if(this.suboptions.length>0&&suboptions.length===0)return;const fullOption=__privateMethod(this,_resolveOption,resolveOption_fn).call(this),value=this.resolveValue();if(value&&(domainRecord[fullOption]=value,domainRecord[baseOption]=value),this.toggleable){const toggle={itemId:this.item.id,label:this.getReducedLabel(),placement:this.placement??"actions-tab",domain:this.domain,option:baseOption,suboptions,alwaysActive:!!this.alwaysActive,checked:value,enabled:!0};if(this.disabledIf){const rollOptions2=this.actor.getRollOptions([this.domain]);toggle.enabled=!this.disabledIf.test(rollOptions2),!toggle.enabled&&!this.alwaysActive&&typeof this.disabledValue=="boolean"&&(toggle.checked=this.disabledValue,this.disabledValue||delete domainRecord[fullOption])}this.actor.synthetics.toggles.push(toggle)}__privateMethod(this,_setFlag,setFlag_fn).call(this,value)}},"#setRollOption"),__name2(_RollOptionRuleElement,"RollOptionRuleElement");let RollOptionRuleElement=_RollOptionRuleElement;const _RollTwiceRuleElement=class extends RuleElementPF2e{static{__name(this,"_RollTwiceRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1}),keep:new fields2.StringField({required:!0,choices:["lower","higher"]}),removeAfterRoll:new fields2.BooleanField({required:!1,initial:void 0})}}beforePrepareData(){if(this.ignored)return;const synthetic={keep:this.keep};this.predicate&&(synthetic.predicate=this.predicate),(this.actor.synthetics.rollTwice[this.selector]??=[]).push(synthetic)}async afterRoll({domains,roll,rollOptions}){if(!this.actor.items.has(this.item.id))return;const expireEffects=game.settings.get("pf2e","automation.effectExpiration"),removeExpired=game.settings.get("pf2e","automation.removeExpiredEffects"),removeAfterRoll=this.removeAfterRoll??((expireEffects||removeExpired)&&this.item.isOfType("effect"));if((roll?.dice.some(d=>["kh","kl"].some(m=>d.modifiers.includes(m)))??!1)&&removeAfterRoll&&domains.includes(this.selector)&&this.test(rollOptions)){for(const rule of this.item.rules)rule.ignored=!0;removeExpired?await this.item.delete():expireEffects&&await this.item.update({"system.duration.value":-1,"system.expired":!0})}}};__name2(_RollTwiceRuleElement,"RollTwiceRuleElement");let RollTwiceRuleElement=_RollTwiceRuleElement;const _SpecialStatisticRuleElement=class extends RuleElementPF2e{static{__name(this,"_SpecialStatisticRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),slug:new SlugField({required:!0,nullable:!1,initial:void 0,validate:v=>typeof v=="string"&&!(v in CONFIG.PF2E.magicTraditions||v in CONFIG.PF2E.classTraits||setHasElement(SKILL_LONG_FORMS,v)||tupleHasValue(SAVE_TYPES,v)||["perception","initiative"].includes(v))}),type:new fields2.StringField({required:!0,choices:["simple","check","attack-roll"],initial:"check"}),extends:new fields2.StringField({required:!0,nullable:!0,initial:null}),attribute:new fields2.StringField({required:!0,choices:Array.from(ATTRIBUTE_ABBREVIATIONS),nullable:!0,initial:null})}}afterPrepareData(){if(this.type==="simple")return;const checkDomains=this.type==="check"?[`${this.slug}-check`]:[`${this.slug}-attack-roll`],extendedFrom=this.extends?this.actor.getStatistic(this.extends):null,data={slug:this.slug,label:this.label,attribute:this.attribute??extendedFrom?.attribute??null,domains:[this.slug],check:{type:this.type==="check"?"check":"attack-roll",domains:checkDomains},dc:{domains:[`${this.slug}-dc`]}},statistic=extendedFrom?.extend(data)??new Statistic(this.actor,data);statistic?this.actor.synthetics.statistics.set(this.slug,statistic):this.failValidation(`Unable to find statistic ${this.extends} to extend from`)}};__name2(_SpecialStatisticRuleElement,"SpecialStatisticRuleElement");let SpecialStatisticRuleElement=_SpecialStatisticRuleElement;const _StrikingRuleElement=class extends RuleElementPF2e{static{__name(this,"_StrikingRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1}),value:new ResolvableValueField({required:!1,nullable:!1,initial:void 0})}}beforePrepareData(){if(this.ignored)return;const selector=this.resolveInjectedProperties(this.selector),strikingValue=this.value??(this.item instanceof WeaponPF2e?getStrikingDice(this.item.system):0),value=this.resolveValue(strikingValue);if(selector&&typeof value=="number"){const striking={label:this.getReducedLabel(),bonus:value,predicate:this.predicate};(this.actor.synthetics.striking[selector]??=[]).push(striking)}else this.failValidation("Striking requires at least a selector field and a non-empty resolved value")}};__name2(_StrikingRuleElement,"StrikingRuleElement"),__publicField(_StrikingRuleElement,"validActorTypes",["character","npc"]);let StrikingRuleElement=_StrikingRuleElement;const _SubstituteRollRuleElement=class extends RuleElementPF2e{static{__name(this,"_SubstituteRollRuleElement")}constructor(source,options){super(source,options),this.removeAfterRoll&&!this.item.isOfType("effect")&&this.failValidation(" removeAfterRoll: may only be used with effects")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1,initial:"check"}),value:new ResolvableValueField({required:!0,nullable:!1}),required:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),effectType:new fields2.StringField({required:!0,nullable:!1,choices:["fortune","misfortune"],initial:"fortune"}),removeAfterRoll:new DataUnionField([new StrictStringField({required:!1,nullable:!1,choices:["if-enabled"],initial:void 0}),new StrictBooleanField({required:!1,nullable:!1,initial:void 0}),new PredicateField({required:!1,nullable:!1,initial:void 0})],{required:!1,nullable:!1,initial:!1})}}beforePrepareData(){const value=Math.clamped(Math.trunc(Number(this.resolveValue(this.value))),1,20);if(Number.isNaN(value))return this.failValidation("value must resolve to a number");const selector=this.resolveInjectedProperties(this.selector);(this.actor.synthetics.rollSubstitutions[selector]??=[]).push({slug:this.slug??sluggify(this.item.name),label:this.label,value,predicate:this.predicate,required:this.required,selected:this.required,effectType:this.effectType})}async afterRoll(params){if(!this.removeAfterRoll||this.ignored)return;if(this.removeAfterRoll===!0){await this.item.delete();return}if(Array.isArray(this.removeAfterRoll)&&this.removeAfterRoll.test(params.rollOptions)){await this.item.delete();return}const rollSubstituted=params.roll.dice.length===0,substitutionIncluded=!!params.context.substitutions?.some(s=>s.slug===this.slug&&s.selected);this.removeAfterRoll==="if-enabled"&&rollSubstituted&&substitutionIncluded&&await this.item.delete()}};__name2(_SubstituteRollRuleElement,"SubstituteRollRuleElement");let SubstituteRollRuleElement=_SubstituteRollRuleElement;const _TokenEffect=class{static{__name(this,"_TokenEffect")}constructor(effect){__privateAdd(this,_effect,void 0),__publicField(this,"tint",null),__publicField(this,"isTemporary",!0),__privateSet(this,_effect,effect)}get id(){return __privateGet(this,_effect).id}get _id(){return __privateGet(this,_effect).id}get parent(){return __privateGet(this,_effect).parent}get name(){return __privateGet(this,_effect).name}get icon(){return __privateGet(this,_effect).img}get changes(){return[]}get description(){return __privateGet(this,_effect).description}get flags(){return __privateGet(this,_effect).flags}get statuses(){return new Set([__privateGet(this,_effect).slug??sluggify(__privateGet(this,_effect).name)])}get disabled(){return __privateGet(this,_effect).isOfType("effect")&&__privateGet(this,_effect).isExpired}get duration(){const effect=__privateGet(this,_effect),isEffect=effect.isOfType("effect");return{type:"none",seconds:null,rounds:null,turns:null,combat:null,startTime:isEffect?effect.system.start.value:null,startRound:null,startTurn:isEffect?effect.system.start.initiative:null,label:isEffect?effect.system.remaining:""}}get transfer(){return!1}get origin(){return __privateGet(this,_effect).uuid}getFlag(scope,flag){return __privateGet(this,_effect).getFlag(scope,flag)}};_effect=new WeakMap,__name2(_TokenEffect,"TokenEffect");let TokenEffect=_TokenEffect;const _TokenEffectIconRuleElement=class extends RuleElementPF2e{static{__name(this,"_TokenEffectIconRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new fields2.StringField({required:!1,blank:!1,initial:void 0})}}afterPrepareData(){if(!this.test())return;const path=this.value?this.resolveInjectedProperties(this.value).trim():this.item.img;if(!isImageFilePath(path))return this.failValidation("value is not a valid image file path");this.actor.synthetics.tokenEffectIcons.push(new TokenEffect(new EffectPF2e({type:"effect",name:this.label,img:path})))}};__name2(_TokenEffectIconRuleElement,"TokenEffectIconRuleElement");let TokenEffectIconRuleElement=_TokenEffectIconRuleElement;const _TokenImageRuleElement=class extends RuleElementPF2e{static{__name(this,"_TokenImageRuleElement")}constructor(data,options){super(data,options),__privateAdd(this,_srcIsValid),typeof this.value=="string"||this.isBracketedValue(this.value)||this.failValidation("value must be a string or a bracketed value")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0,label:"TOKEN.ImagePath"}),scale:new fields2.NumberField({required:!1,nullable:!0,positive:!0,initial:null,label:"Scale"}),tint:new fields2.ColorField({label:"TOKEN.TintColor"}),alpha:new fields2.AlphaField({label:"PF2E.RuleEditor.General.Opacity"})}}afterPrepareData(){const src=this.resolveValue(this.value);if(!__privateMethod(this,_srcIsValid,srcIsValid_fn).call(this,src))return this.failValidation("Missing or invalid value field");if(!this.test())return;const texture={src};this.scale&&(texture.scaleX=this.scale,texture.scaleY=this.scale),this.tint&&(texture.tint=this.tint),this.alpha&&(this.actor.synthetics.tokenOverrides.alpha=this.alpha),this.actor.synthetics.tokenOverrides.texture=texture}};_srcIsValid=new WeakSet,srcIsValid_fn=__name2(function(src){if(typeof src!="string")return!1;const extension=/(?<=\.)[a-z0-9]{3,4}$/i.exec(src)?.at(0);return!!extension&&(extension in CONST.IMAGE_FILE_EXTENSIONS||extension in CONST.VIDEO_FILE_EXTENSIONS)},"#srcIsValid"),__name2(_TokenImageRuleElement,"TokenImageRuleElement");let TokenImageRuleElement=_TokenImageRuleElement;const _TokenLightRuleElement=class extends RuleElementPF2e{static{__name(this,"_TokenLightRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new fields2.SchemaField({...foundry.data.LightData.defineSchema(),dim:new ResolvableValueField({required:!1,nullable:!1,initial:void 0}),bright:new ResolvableValueField({required:!1,nullable:!1,initial:void 0})})}}constructor(data,options){super(data,options),this.validateData()}validateData(){const light=this.value;for(const key of["dim","bright"])if(light[key]!==void 0){const resolvedValue=this.resolveValue(light[key]);if(typeof resolvedValue=="number")light[key]=resolvedValue;else return this.failValidation(`${key} must resolve to a number`)}try{new foundry.data.LightData(light)}catch(error){error instanceof Error&&this.failValidation(error.message)}}afterPrepareData(){this.test()&&(this.actor.synthetics.tokenOverrides.light=deepClone(this.value))}};__name2(_TokenLightRuleElement,"TokenLightRuleElement");let TokenLightRuleElement=_TokenLightRuleElement;const _MarkTargetPrompt=class{static{__name(this,"_MarkTargetPrompt")}constructor(params){__privateAdd(this,_cancelHandler),__publicField(this,"prompt"),__publicField(this,"requirements"),__privateAdd(this,_target,void 0),__privateAdd(this,_resolve4,void 0),this.prompt=params.prompt??"PF2E.UI.RuleElements.TokenMark.TargetToken",this.requirements=params.requirements}async resolveTarget(){return game.user.targets.clear(),this.activateListeners(),ui.notifications.info(this.prompt,{localize:!0}),new Promise(resolve=>{__privateSet(this,_resolve4,resolve)})}activateListeners(){document.activeElement instanceof HTMLElement&&document.activeElement.blur();const hookParams=["targetToken",(_user,token,targeted)=>{var _a;__privateSet(this,_target,targeted&&token instanceof TokenPF2e?token.document:null),(_a=__privateGet(this,_resolve4))==null||_a.call(this,__privateGet(this,_target))}];Hooks.once(...hookParams);const cancelHandler=__privateMethod(this,_cancelHandler,cancelHandler_fn).call(this,hookParams);document.addEventListener("keyup",cancelHandler),window.setTimeout(()=>{var _a;Hooks.off(...hookParams),document.removeEventListener("keyup",cancelHandler),__privateGet(this,_target)===void 0&&((_a=__privateGet(this,_resolve4))==null||_a.call(this,null))},15e3)}};_target=new WeakMap,_resolve4=new WeakMap,_cancelHandler=new WeakSet,cancelHandler_fn=__name2(function(hookParams){const handler=__name2(event=>{event.key==="Escape"&&(event.stopPropagation(),ui.notifications.info("PF2E.UI.RuleElements.TokenMark.Timeout",{localize:!0}),Hooks.off(...hookParams),document.removeEventListener("keyup",handler))},"handler");return handler},"#cancelHandler"),__name2(_MarkTargetPrompt,"MarkTargetPrompt");let MarkTargetPrompt=_MarkTargetPrompt;const _TokenMarkRuleElement=class extends RuleElementPF2e{static{__name(this,"_TokenMarkRuleElement")}constructor(){super(...arguments),__privateAdd(this,_checkRuleSource)}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),slug:new SlugField({required:!0,nullable:!1,initial:void 0}),uuid:new fields2.StringField({required:!1,nullable:!0,initial:null})}}async preCreate({ruleSource,itemSource,pendingItems}){if(this.ignored)return;if(this.uuid&&=this.resolveInjectedProperties(this.uuid),this.actor.getActiveTokens().length===0){this.ignored=ruleSource.ignored=!0;return}const token=fromUuidSync(this.uuid??"")??(game.user.targets.size===1?Array.from(game.user.targets)[0].document:await new MarkTargetPrompt({prompt:null,requirements:null}).resolveTarget());if(!(token instanceof TokenDocumentPF2e)){pendingItems.splice(pendingItems.indexOf(itemSource),1);return}__privateMethod(this,_checkRuleSource,checkRuleSource_fn).call(this,ruleSource),this.uuid=ruleSource.uuid=token.uuid}beforePrepareData(){UUIDUtils.isTokenUUID(this.uuid)&&this.test()&&this.actor.synthetics.tokenMarks.set(this.uuid,this.slug)}};_checkRuleSource=new WeakSet,checkRuleSource_fn=__name2(function(source){if(!(source.key==="TokenMark"&&source.slug===this.slug))throw ErrorPF2e("Unexpected rule element passed")},"#checkRuleSource"),__name2(_TokenMarkRuleElement,"TokenMarkRuleElement");let TokenMarkRuleElement=_TokenMarkRuleElement;const _TokenNameRuleElement=class extends RuleElementPF2e{static{__name(this,"_TokenNameRuleElement")}static defineSchema(){return{...super.defineSchema(),value:new ResolvableValueField({required:!0})}}afterPrepareData(){const name2=this.resolveValue(this.value);if(typeof name2!="string")return this.failValidation("value must resolve to a string");this.test()&&(this.actor.synthetics.tokenOverrides.name=name2)}};__name2(_TokenNameRuleElement,"TokenNameRuleElement");let TokenNameRuleElement=_TokenNameRuleElement;const _WeaponPotencyRuleElement=class extends RuleElementPF2e{static{__name(this,"_WeaponPotencyRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,nullable:!1,blank:!1}),value:new ResolvableValueField({required:!0})}}beforePrepareData(){if(this.ignored)return;const{weaponPotency}=this.actor.synthetics,selector=this.resolveInjectedProperties(this.selector),{item}=this,potencyValue=this.value??(item.isOfType("weapon")?item.system.potencyRune.value:0),value=this.resolveValue(potencyValue);if(selector&&typeof value=="number"){const bonusType=AutomaticBonusProgression.isEnabled(this.actor)?"potency":"item",potency={label:this.getReducedLabel(),bonus:value,type:bonusType,predicate:this.predicate};(weaponPotency[selector]??=[]).push(potency)}else this.failValidation("Weapon potency requires at least a selector field and a non-empty value field")}};__name2(_WeaponPotencyRuleElement,"WeaponPotencyRuleElement"),__publicField(_WeaponPotencyRuleElement,"validActorTypes",["character","npc"]);let WeaponPotencyRuleElement=_WeaponPotencyRuleElement;const _RuleElements=class{static{__name(this,"_RuleElements")}static get all(){return{...this.builtin,...this.custom}}static fromOwnedItem(options){const rules=[],item=options.parent;for(const[sourceIndex,source]of item.system.rules.entries()){if(typeof source.key!="string"){console.error(`PF2e System | Missing key in rule element ${source.key} on item ${item.name} (${item.uuid})`);continue}const REConstructor=this.custom[source.key]??this.custom[source.key]??this.builtin[source.key];if(REConstructor){const rule=(()=>{try{return new REConstructor(source,{...options,sourceIndex})}catch(error){return options?.suppressWarnings||(console.warn(`PF2e System | Failed to construct rule element ${source.key} on item ${item.name}`,`(${item.uuid})`),console.warn(error)),null}})();rule&&rules.push(rule)}else{const{name:name2,uuid}=item;console.warn(`PF2e System | Unrecognized rule element ${source.key} on item ${name2} (${uuid})`)}}return rules}};__name2(_RuleElements,"RuleElements"),__publicField(_RuleElements,"builtin",{ActiveEffectLike:AELikeRuleElement,ActorTraits:ActorTraitsRuleElement,AdjustDegreeOfSuccess:AdjustDegreeOfSuccessRuleElement,AdjustModifier:AdjustModifierRuleElement,AdjustStrike:AdjustStrikeRuleElement,Aura:AuraRuleElement,BaseSpeed:BaseSpeedRuleElement,BattleForm:BattleFormRuleElement,ChoiceSet:ChoiceSetRuleElement,CraftingEntry:CraftingEntryRuleElement,CraftingFormula:CraftingFormulaRuleElement,CreatureSize:CreatureSizeRuleElement,CriticalSpecialization:CritSpecRuleElement,DamageDice:DamageDiceRuleElement,DexterityModifierCap:DexterityModifierCapRuleElement,EphemeralEffect:EphemeralEffectRuleElement,FastHealing:FastHealingRuleElement,FixedProficiency:FixedProficiencyRuleElement,FlatModifier:FlatModifierRuleElement,GrantItem:GrantItemRuleElement,Immunity:ImmunityRuleElement,ItemAlteration:ItemAlterationRuleElement,LoseHitPoints:LoseHitPointsRuleElement,MartialProficiency:MartialProficiencyRuleElement,MultipleAttackPenalty:MultipleAttackPenaltyRuleElement,Note:RollNoteRuleElement,Resistance:ResistanceRuleElement,RollOption:RollOptionRuleElement,RollTwice:RollTwiceRuleElement,Sense:SenseRuleElement,SpecialStatistic:SpecialStatisticRuleElement,Strike:StrikeRuleElement,Striking:StrikingRuleElement,SubstituteRoll:SubstituteRollRuleElement,TempHP:TempHPRuleElement,TokenEffectIcon:TokenEffectIconRuleElement,TokenImage:TokenImageRuleElement,TokenLight:TokenLightRuleElement,TokenMark:TokenMarkRuleElement,TokenName:TokenNameRuleElement,Weakness:WeaknessRuleElement,WeaponPotency:WeaponPotencyRuleElement}),__publicField(_RuleElements,"custom",{});let RuleElements=_RuleElements;const CodeMirror={EditorView,basicSetup,json,jsonLinter:()=>linter(jsonParseLinter()),keybindings:keymap.of([indentWithTab]),ruleElementExtensions:options=>[json(),CodeMirror.jsonLinter(),autocompletion({override:[ruleElementAutocomplete(options)]})]};function ruleElementAutocomplete(options){const validKeysByPath=(()=>options.schema?{"":Object.keys(options.schema)}:{"":["key"]})();return context=>{const node=syntaxTree(context.state).resolveInner(context.pos,-1),isProperty=node.name==="Object"||node.type.name==="PropertyName",isValue=!isProperty&&(node.name==="Property"||node.parent?.name==="Property");if(isProperty){const basePath=resolveNodePath(context,node),keys2=basePath!==null?validKeysByPath[basePath]:[];return keys2?.length?{from:node.from,to:node.to,options:keys2.map(o=>({label:`"${o}"`}))}:null}else if(isValue&&resolveNodePath(context,node)==="key"){const options2=Object.keys(RuleElements.all);return{from:node.from,to:node.to,options:options2.map(o=>({label:`"${o}"`}))}}return null}}__name(ruleElementAutocomplete,"ruleElementAutocomplete"),__name2(ruleElementAutocomplete,"ruleElementAutocomplete");function resolveNodePath(context,node){node=node.type.name==="PropertyName"&&node.parent?node.parent:node;const parent=node.parent;if(!parent||parent.type.name==="JsonText")return"";const parentType=parent.type.name;if(parentType==="\u26A0")return null;const name2=(()=>parentType==="Object"?!parent.parent||parent.parent.type.name==="JsonText"?"":".":parentType==="Property"?context.state.sliceDoc(parent.from,parent.to).match(/^"([^"]*)"/)?.[1]:parentType==="Array"?"[]":null)();if(name2===null)return null;const basePath=resolveNodePath(context,parent);return basePath===null?null:basePath+name2}__name(resolveNodePath,"resolveNodePath"),__name2(resolveNodePath,"resolveNodePath");const _RuleElementForm=class{static{__name(this,"_RuleElementForm")}constructor(options){__privateAdd(this,_getFormHelpers),__publicField(this,"template","systems/pf2e/templates/items/rules/default.hbs"),__publicField(this,"tabs",null),__privateAdd(this,_activeTab,null),this.initialize(options)}get basePath(){return`system.rules.${this.index}`}initialize(options){this.sheet=options.sheet,this.index=options.index,this.rule=options.rule,this.object=options.object??(()=>{const RuleElementClass=RuleElements.all[String(this.rule.key)];if(!RuleElementClass)return null;const actor=new ActorProxyPF2e({_id:randomID(),name:"temp",type:"character"}),item=new ItemProxyPF2e(this.item.toObject(),{parent:actor});return new RuleElementClass(deepClone(this.rule),{parent:item,strict:!1,suppressWarnings:!0})})(),this.schema=this.object?.schema??RuleElements.all[String(this.rule.key)]?.schema??null}get item(){return this.sheet.item}get fieldIdPrefix(){return`field-${this.sheet.appId}-${this.index}-`}getInitialValue(){if(this.constructor.name==="RuleElementForm")return{};const initial=this.schema?.getInitialValue();if(!initial)return{};for(const property of["ignored","priority","slug"])delete initial[property];const removeArrays=__name2(object=>{for(const[key,value]of Object.entries(object))Array.isArray(value)?delete object[key]:isObject(value)&&removeArrays(value)},"removeArrays");return removeArrays(initial),initial}async getData(){const[label,recognized]=(()=>{const locPath=`PF2E.RuleElement.${this.rule.key}`,localized=game.i18n.localize(locPath);return localized===locPath?[game.i18n.localize("PF2E.RuleElement.Unrecognized"),!1]:[localized,!0]})(),mergedRule=mergeObject(this.getInitialValue(),this.rule);return{...pick$1(this,["index","rule","object"]),item:this.item,label,fieldIdPrefix:this.fieldIdPrefix,recognized,basePath:this.basePath,rule:mergedRule,fields:this.schema?.fields,form:await __privateMethod(this,_getFormHelpers,getFormHelpers_fn).call(this,mergedRule)}}async render(){const data=await this.getData();return renderTemplate("systems/pf2e/templates/items/rules/partials/outer.hbs",{...data,template:await renderTemplate(this.template,data)})}async updateItem(updates){const rules=this.item.toObject().system.rules,result=mergeObject(this.rule,updates,{performDeletions:!0});this.schema&&cleanDataUsingSchema(this.schema.fields,result),rules[this.index]=result,await this.item.update({"system.rules":rules})}activateListeners(html){this.element=html;const selectorElement=htmlQuery(html,".selector-list");tagify$1(selectorElement);const priorityInput=htmlQuery(html,".rule-element-header .priority input");priorityInput?.addEventListener("change",event=>{event.stopPropagation();const value=priorityInput.value;value===""||Number.isNaN(Number(value))?this.updateItem({"-=priority":null}):this.updateItem({priority:Number(value)})});for(const button of htmlQueryAll(html,"[data-action=toggle-brackets]"))button.addEventListener("click",()=>{const property=button.dataset.property??"value",value=getProperty(this.rule,property);isBracketedValue(value)?this.updateItem({[property]:""}):this.updateItem({[property]:{brackets:[{value:""}]}})});for(const button of htmlQueryAll(html,"[data-action=add-bracket]")){const property=button.dataset.property??"value";button.addEventListener("click",()=>{const value=getProperty(this.rule,property);isBracketedValue(value)&&(value.brackets.push({value:""}),this.updateItem({[property]:value}))})}for(const button of htmlQueryAll(html,"[data-action=delete-bracket]")){const property=button.dataset.property??"value";button.addEventListener("click",()=>{const value=getProperty(this.rule,property),idx=Number(htmlClosest(button,"[data-idx]")?.dataset.idx);isBracketedValue(value)&&(value.brackets.splice(idx,1),this.updateItem({[property]:value}))})}if(this.tabs){for(const anchor of htmlQueryAll(html,"a[data-rule-tab]"))anchor.addEventListener("click",()=>{this.activateTab(html,anchor.dataset.ruleTab)});this.activateTab(html,__privateGet(this,_activeTab))}for(const dropZone of htmlQueryAll(html,"div.rules-drop-zone"))dropZone.addEventListener("drop",event=>{this.onDrop(event,dropZone)})}async onDrop(event,_element){const data=event.dataTransfer?.getData("text/plain");return data?await ItemPF2e.fromDropData(JSON.parse(data))??null:null}activateTab(html,tabName){if(!this.tabs)return;const activeTab=tabName??this.tabs.names.at(0);if(!(!activeTab||!this.tabs.names.includes(activeTab))){__privateSet(this,_activeTab,activeTab);for(const element of htmlQueryAll(html,"[data-rule-tab]"))element.dataset.ruleTab===activeTab?(element.classList.add("active"),element.tagName!=="A"&&(element.style.display=this.tabs.displayStyle)):(element.classList.remove("active"),element.tagName!=="A"&&(element.style.display="none"))}}updateObject(source){if(typeof source=="string"){try{this.rule=JSON.parse(source)}catch(error){if(error instanceof Error)throw ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.RuleElementSyntax",{message:error.message})),console.warn("Syntax error in rule element definition.",error.message,source),error}return}source=mergeObject(duplicate(this.rule),source);for(const slider of htmlQueryAll(this.element,"input[type=range"))slider.style.pointerEvents="none";cleanPredicate(source),this.schema&&cleanDataUsingSchema(this.schema.fields,source),this.rule=source}};_activeTab=new WeakMap,_getFormHelpers=new WeakSet,getFormHelpers_fn=__name2(async function(rule){const valueTemplate=await getTemplate("systems/pf2e/templates/items/rules/partials/resolvable-value.hbs"),bracketsTemplate=await getTemplate("systems/pf2e/templates/items/rules/partials/resolvable-brackets.hbs"),dropZoneTemplate=await getTemplate("systems/pf2e/templates/items/rules/partials/drop-zone.hbs"),getResolvableData=__name2(property=>{const value=getProperty(rule,property),mode=isBracketedValue(value)?"brackets":isObject(value)?"object":"primitive";return{value,mode,property,path:`${this.basePath}.${property}`}},"getResolvableData");return{resolvableValue:(property,options={})=>valueTemplate({...getResolvableData(property),inputId:`${this.fieldIdPrefix}${property}`,fileInput:options.hash?.fileInput??!1}),resolvableAddBracket:property=>getResolvableData(property).mode!=="brackets"?"":createHTMLElement("a",{children:[fontAwesomeIcon("plus",{fixedWidth:!0})],dataset:{action:"add-bracket",property}}).outerHTML,resolvableBrackets:property=>bracketsTemplate(getResolvableData(property)),dropZone:(dropId,dropText,dropTooltip)=>dropZoneTemplate({dropId,dropText,dropTooltip})}},"#getFormHelpers"),__name2(_RuleElementForm,"RuleElementForm");let RuleElementForm=_RuleElementForm;function cleanDataUsingSchema(schema,data){const{fields:fields2}=foundry.data,deleteIfInitial=__name2((key,field)=>{if(data[key]===void 0)return!0;const initialValue=typeof field.initial=="function"?field.initial():field.initial,valueRaw=data[key],value=isObject$1(valueRaw)&&isObject$1(initialValue)?{...initialValue,...valueRaw}:valueRaw;return equals(initialValue,value)&&delete data[key],!(key in data)},"deleteIfInitial");for(const[key,field]of Object.entries(schema))if(!deleteIfInitial(key,field)){if(field instanceof ResolvableValueField){data[key]=field.clean(data[key]),deleteIfInitial(key,field);continue}if("fields"in field){const value=data[key];if(isObject$1(value)){cleanDataUsingSchema(field.fields,value),deleteIfInitial(key,field);continue}}if(field instanceof fields2.ArrayField&&field.element instanceof fields2.SchemaField){const value=data[key];if(Array.isArray(value)){for(const data2 of value)isObject$1(data2)&&(data2.predicate&&cleanPredicate(data2),cleanDataUsingSchema(field.element.fields,data2));continue}}field instanceof fields2.StringField&&(data[key]=field.clean(data[key],{}),deleteIfInitial(key,field))}}__name(cleanDataUsingSchema,"cleanDataUsingSchema"),__name2(cleanDataUsingSchema,"cleanDataUsingSchema");function cleanPredicate(source){const predicateValue=source.predicate;if(typeof predicateValue=="string")if(predicateValue.trim()==="")delete source.predicate;else try{source.predicate=JSON.parse(predicateValue)}catch(error){if(error instanceof Error)throw ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.RuleElementSyntax",{message:error.message})),error}}__name(cleanPredicate,"cleanPredicate"),__name2(cleanPredicate,"cleanPredicate");const _AuraForm=class extends RuleElementForm{static{__name(this,"_AuraForm")}constructor(){super(...arguments),__privateAdd(this,_addEffect),__privateAdd(this,_updateEffectsMap),__privateAdd(this,_deleteEffect),__publicField(this,"template","systems/pf2e/templates/items/rules/aura.hbs"),__publicField(this,"tabs",{names:["basic","effects","appearance"],displayStyle:"grid"}),__privateAdd(this,_effectsMap,new Map)}get effectsArray(){return[...__privateGet(this,_effectsMap).values()]}getInitialValue(){return __privateGet(this,_effectsMap).clear(),__privateSet(this,_effectsMap,new Map(this.object.effects.map((e,index)=>[index,deepClone(e)]))),super.getInitialValue()}activateListeners(html){super.activateListeners(html);const traitsElement=htmlQuery(html,".tagify-traits");if(traitsElement){const whitelist={...CONFIG.PF2E.spellTraits,...CONFIG.PF2E.actionTraits};tagify$1(traitsElement,{whitelist,enforceWhitelist:!1})}for(const eventsElement of htmlQueryAll(html,".tagify-events")){const whitelist=[["enter",game.i18n.localize("PF2E.RuleEditor.Aura.Effects.EventsOptions.Enter")],["turn-start",game.i18n.localize("PF2E.RuleEditor.Aura.Effects.EventsOptions.TurnStart")],["turn-end",game.i18n.localize("PF2E.RuleEditor.Aura.Effects.EventsOptions.TurnEnd")]].sort((a,b)=>a[1].localeCompare(b[1],game.i18n.lang));tagify$1(eventsElement,{whitelist:mapToObj(whitelist,w=>[w[0],w[1]]),enforceWhitelist:!0})}for(const element of htmlQueryAll(html,"a[data-action=remove-effect]"))element.addEventListener("click",()=>{__privateMethod(this,_deleteEffect,deleteEffect_fn).call(this,element.dataset.effectId)});for(const button of htmlQueryAll(html,"div[data-rule-tab=effects] button[data-action=toggle-brackets]")){const fieldset=htmlClosest(button,"fieldset"),select=htmlQuery(fieldset,"select"),input=htmlQuery(fieldset,"input");select&&input&&!select.value&&(button.disabled=!0,input.disabled=!0)}for(const key of["border","highlight"]){const inputName=`system.rules.${this.index}.appearance.${key}.color`,textInput=htmlQuery(html,`input[type=text][name="${inputName}"]`),colorInput=htmlQuery(html,`input[type=color][data-edit="${inputName}"]`),checkbox=htmlQuery(html,`input[type=checkbox][name="${inputName}"]`);textInput&&colorInput&&checkbox&&(this.object.appearance[key]?.color==="user-color"?(textInput.removeAttribute("name"),textInput.disabled=!0,colorInput.disabled=!0):checkbox.removeAttribute("name"),checkbox.addEventListener("change",()=>{checkbox.checked?(checkbox.name=textInput.name,textInput.removeAttribute("name"),textInput.disabled=!0,colorInput.disabled=!0,textInput.value=colorInput.value=userColorForActor(this.object.actor)):(textInput.name=checkbox.name,checkbox.removeAttribute("name"),textInput.disabled=!1,colorInput.disabled=!1,textInput.value=colorInput.value="#000000")}))}const translationX=htmlQuery(html,"input[data-translation=x]"),translationY=htmlQuery(html,"input[data-translation=y]");translationX&&translationY&&(translationX.addEventListener("change",()=>{translationX.value!==""&&translationY.value===""&&(translationY.value=translationX.value)}),translationY.addEventListener("change",()=>{translationY.value!==""&&translationX.value===""&&(translationX.value=translationY.value)}))}async getData(){const{border,highlight}=this.object.appearance,userColor=userColorForActor(this.object.actor);return{...await super.getData(),affectsOptions:{all:"PF2E.RuleEditor.Aura.Effects.AffectsOptions.All",allies:"PF2E.RuleEditor.Aura.Effects.AffectsOptions.Allies",enemies:"PF2E.RuleEditor.Aura.Effects.AffectsOptions.Enemies"},effects:this.effectsArray.map(e=>({...e,item:fromUuidSync(e.uuid)})),borderColor:border?.color==="user-color"?userColor:border?.color??null,highlightColor:highlight.color==="user-color"?userColor:highlight?.color,saveTypes:CONFIG.PF2E.saves,isImageFile:isImageFilePath(this.rule.appearance?.texture?.src)}}async onDrop(event,element){const{id}=element.dataset;if(id!=="aura-effect-drop")return null;const item=await super.onDrop(event,element);return!item?.isOfType("effect")||!this.schema?null:(__privateMethod(this,_addEffect,addEffect_fn).call(this,item.uuid),item)}async updateItem(updates){const expanded=expandObject(updates);return expanded.effects&&(expanded.effects=__privateMethod(this,_updateEffectsMap,updateEffectsMap_fn).call(this,expanded)),super.updateItem(expanded)}updateObject(source){source.effects=__privateMethod(this,_updateEffectsMap,updateEffectsMap_fn).call(this,source);for(const key of["level","radius"]){if(key in source&&!source[key]){delete source[key];continue}const stringValue=source[key],maybeIntegerValue=typeof stringValue=="string"&&/^\d+$/.test(stringValue)?Number(stringValue):NaN;Number.isInteger(maybeIntegerValue)&&(source[key]=maybeIntegerValue)}const appearance=source.appearance;appearance?.border?.alpha===0&&(appearance.border=null),appearance?.border?.color===null&&(appearance.border.color="#000000"),appearance?.highlight?.color===null&&(appearance.highlight.color="#000000");const texture=appearance?.texture;if(texture){if(texture.translation){const{x,y}=texture.translation;!x&&!y&&(texture.translation=null)}texture.src?isImageFilePath(texture.src)&&(texture.loop=!0,texture.playbackRate=1):appearance.texture=null}super.updateObject(source)}};_effectsMap=new WeakMap,_addEffect=new WeakSet,addEffect_fn=__name2(function(uuid){const index=__privateGet(this,_effectsMap).size+1;__privateGet(this,_effectsMap).set(index,{uuid}),this.updateItem({effects:this.effectsArray})},"#addEffect"),_updateEffectsMap=new WeakSet,updateEffectsMap_fn=__name2(function(source){return __privateSet(this,_effectsMap,new Map(Object.values(source.effects??{}).map((data,index)=>{const updatedData=deepClone(data),deletions={};if(updatedData.save&&(updatedData.save.type??data.save?.type?updatedData.save.dc||=null:deletions["-=save"]=null),updatedData.affects!=="enemies"&&updatedData.includesSelf&&(deletions["-=includesSelf"]=null),updatedData.removeOnExit&&(deletions["-=removeOnExit"]=null),updatedData.predicate)try{const parsed=JSON.parse(String(updatedData.predicate));updatedData.predicate=Array.isArray(parsed)?parsed:[]}catch{deletions["-=predicate"]=null}else deletions["-=predicate"]=null;return[index,mergeObject(updatedData,deletions,{performDeletions:!0})]}))),this.effectsArray},"#updateEffectsMap"),_deleteEffect=new WeakSet,deleteEffect_fn=__name2(function(id){const index=Number(id);Number.isNaN(index)||__privateGet(this,_effectsMap).delete(index)&&this.updateItem({effects:this.effectsArray})},"#deleteEffect"),__name2(_AuraForm,"AuraForm");let AuraForm=_AuraForm;const _FastHealingForm=class extends RuleElementForm{static{__name(this,"_FastHealingForm")}template="systems/pf2e/templates/items/rules/fast-healing.hbs";activateListeners(html){super.activateListeners(html);const selectorElement=htmlQuery(html,".deactivated-by");if(selectorElement){const whitelist=CONFIG.PF2E.weaknessTypes;tagify$1(selectorElement,{whitelist,enforceWhitelist:!1})}}async getData(){return{...await super.getData(),types:{"fast-healing":"PF2E.Encounter.Broadcast.FastHealing.fast-healing.Name",regeneration:"PF2E.Encounter.Broadcast.FastHealing.regeneration.Name"}}}updateObject(source){delete source[source.type==="regeneration"?"details":"deactivatedBy"],super.updateObject(source)}};__name2(_FastHealingForm,"FastHealingForm");let FastHealingForm=_FastHealingForm;const _FlatModifierForm=class extends RuleElementForm{static{__name(this,"_FlatModifierForm")}template="systems/pf2e/templates/items/rules/flat-modifier.hbs";get isDamage(){return[this.rule.selector??[]].flat().some(s=>s==="damage"||String(s).endsWith("-damage"))}activateListeners(html){super.activateListeners(html),htmlQuery(html,"[data-action=toggle-selector]")?.addEventListener("click",()=>{const selector=this.rule.selector,newValue=Array.isArray(selector)?selector.at(0)??"":[selector??""].filter(s=>!!s);this.updateItem({selector:newValue})})}async getData(){const data=await super.getData(),types=(()=>{const abpEnabled=AutomaticBonusProgression.isEnabled(null),entries=Array.from(MODIFIER_TYPES).filter(t=>abpEnabled||t!=="potency").map(t=>[t,game.i18n.localize(`PF2E.ModifierType.${t}`)]).sort((a,b)=>a[0]==="untyped"?-1:b[0]==="untyped"?1:a[1].localeCompare(b[1]));return fromPairs(entries)})();return{...data,selectorIsArray:Array.isArray(this.rule.selector),abilities:CONFIG.PF2E.abilities,types,damageCategories:pick$1(CONFIG.PF2E.damageCategories,Array.from(DAMAGE_CATEGORIES_UNIQUE)),isDamage:this.isDamage}}updateObject(formData){delete formData[formData.type==="ability"?"value":"ability"],formData.critical=tupleHasValue([!1,"false"],formData.critical)?!1:!!formData.critical||null,this.isDamage||(delete formData.damageCategory,delete formData.damageType,delete formData.critical),super.updateObject(formData)}};__name2(_FlatModifierForm,"FlatModifierForm");let FlatModifierForm=_FlatModifierForm;const _GrantItemForm=class extends RuleElementForm{static{__name(this,"_GrantItemForm")}template="systems/pf2e/templates/items/rules/grant-item.hbs";async getData(){const data=await super.getData(),uuid=this.rule.uuid?String(this.rule.uuid):null,granted=uuid?await fromUuid(uuid):null;return{...data,granted}}updateObject(ruleData){super.updateObject(ruleData),typeof ruleData.uuid=="string"&&(ruleData.uuid=ruleData.uuid.trim())}};__name2(_GrantItemForm,"GrantItemForm");let GrantItemForm=_GrantItemForm;const _MultipleAttackPenaltyForm=class extends RuleElementForm{static{__name(this,"_MultipleAttackPenaltyForm")}template="systems/pf2e/templates/items/rules/multiple-attack-penalty.hbs"};__name2(_MultipleAttackPenaltyForm,"MultipleAttackPenaltyForm");let MultipleAttackPenaltyForm=_MultipleAttackPenaltyForm;const _RollNoteForm=class extends RuleElementForm{static{__name(this,"_RollNoteForm")}html=null;template="systems/pf2e/templates/items/rules/note.hbs";async getData(){return{...await super.getData(),selectorIsArray:Array.isArray(this.rule.selector)}}activateListeners(html){super.activateListeners(html),this.html=html,htmlQuery(html,"[data-action=toggle-selector]")?.addEventListener("click",()=>{const selector=this.rule.selector,newValue=Array.isArray(selector)?selector.at(0)??"":[selector??""].filter(s=>!!s);this.updateItem({selector:newValue})});const optionsEl=htmlQuery(html,".outcomes");tagify$1(optionsEl,{whitelist:[...DEGREE_OF_SUCCESS_STRINGS],maxTags:3})}updateObject(ruleData){super.updateObject(ruleData);const{html}=this;if(html){const shouldBeHidden=htmlQuery(html,".hidden-value")?.checked,isHidden=["gm","owner"].includes(String(ruleData.visibility));shouldBeHidden!==isHidden&&(shouldBeHidden?ruleData.visibility="owner":delete ruleData.visibility)}Array.isArray(ruleData.outcome)&&ruleData.outcome.length===0&&delete ruleData.outcome,typeof ruleData.title=="string"&&(ruleData.title=ruleData.title.trim())}};__name2(_RollNoteForm,"RollNoteForm");let RollNoteForm=_RollNoteForm;const _TokenImageForm=class extends RuleElementForm{static{__name(this,"_TokenImageForm")}template="systems/pf2e/templates/items/rules/token-image.hbs";async getData(){return{...await super.getData(),scaleEnabled:this.object.scale!==null}}activateListeners(html){super.activateListeners(html);const tintInput=htmlQuery(html,`input[name="system.rules.${this.index}.tint"]`),scaleCheckbox=htmlQuery(html,"input[data-action=toggle-scale]"),scaleInput=htmlQuery(html,`input[name="system.rules.${this.index}.scale"]`);tintInput&&scaleCheckbox&&scaleInput&&(tintInput.id=`${this.fieldIdPrefix}-tint`,scaleInput.id=`${this.fieldIdPrefix}-scale`,scaleInput.disabled=this.object.scale===null,scaleCheckbox.addEventListener("change",event=>{event.stopPropagation();const newValue=this.object.scale===null?1:null;this.updateItem({scale:newValue})}))}};__name2(_TokenImageForm,"TokenImageForm");let TokenImageForm=_TokenImageForm;const _TokenLightForm=class extends RuleElementForm{static{__name(this,"_TokenLightForm")}template="systems/pf2e/templates/items/rules/token-light.hbs";tabs={names:["basic","animation","advanced"],displayStyle:"grid"};async getData(){const data=await super.getData();return{...data,colorationTechniques:AdaptiveLightingShader.SHADER_TECHNIQUES,light:data.rule.value,lightAnimations:mapValues$1(CONFIG.Canvas.lightAnimations,value=>value.label)}}};__name2(_TokenLightForm,"TokenLightForm");let TokenLightForm=_TokenLightForm;const RULE_ELEMENT_FORMS={Aura:AuraForm,FastHealing:FastHealingForm,FlatModifier:FlatModifierForm,GrantItem:GrantItemForm,MultipleAttackPenalty:MultipleAttackPenaltyForm,Note:RollNoteForm,TokenImage:TokenImageForm,TokenLight:TokenLightForm},_ItemSheetPF2e=class extends ItemSheet{static{__name(this,"_ItemSheetPF2e")}constructor(){super(...arguments),__privateAdd(this,_createRuleElementForms),__privateAdd(this,_selectedRuleElementType,Object.keys(RuleElements.all).at(0)??null),__privateAdd(this,_editingRuleElementIndex,null),__privateAdd(this,_rulesLastScrollTop,null),__privateAdd(this,_ruleElementForms,[])}static get defaultOptions(){const options=super.defaultOptions;return options.width=695,options.height=460,options.classes=options.classes.concat(["pf2e","item"]),options.template="systems/pf2e/templates/items/sheet.hbs",options.scrollY=[".tab.active",".inventory-details","div[data-rule-tab]"],options.tabs=[{navSelector:".tabs",contentSelector:".sheet-body",initial:"description"},{navSelector:".mystify-nav",contentSelector:".mystify-sheet",initial:"unidentified"}],options}get editingRuleElement(){return __privateGet(this,_editingRuleElementIndex)===null?null:this.item.toObject().system.rules[__privateGet(this,_editingRuleElementIndex)]??null}get validTraits(){return objectHasKey(CONFIG.PF2E.Item.traits,this.item.type)?CONFIG.PF2E.Item.traits[this.item.type]:null}async getData(options={}){options.id=this.id,options.classes?.push(this.item.type),options.editable=this.isEditable,options.sheetConfig&&=Object.values(CONFIG.Item.sheetClasses[this.item.type]).filter(c=>c.canConfigure).length>1;const{item}=this;__privateMethod(this,_createRuleElementForms,createRuleElementForms_fn).call(this);const enrichedContent={},rollData={...this.item.getRollData(),...this.actor?.getRollData()};enrichedContent.description=await TextEditor.enrichHTML(item._source.system.description.value,{rollData,async:!0}),enrichedContent.gmNotes=await TextEditor.enrichHTML(item.system.description.gm.trim(),{rollData,async:!0});const validTraits=this.validTraits,hasRarity=!item.isOfType("action","condition","deity","effect","lore","melee"),itemTraits=item.system.traits?.value??[],sourceTraits=item._source.system.traits?.value??[],traits=validTraits?createSheetTags(validTraits,itemTraits):null,traitTagifyData=validTraits?createTagifyTraits(itemTraits,{sourceTraits,record:validTraits}):null;return{itemType:null,showTraits:this.validTraits!==null,hasSidebar:this.item.isOfType("condition","lore"),sidebarTitle:game.i18n.format("PF2E.Item.SidebarSummary",{type:game.i18n.localize(`TYPES.Item.${this.item.type}`)}),sidebarTemplate:`systems/pf2e/templates/items/${sluggify(item.type)}-sidebar.hbs`,detailsTemplate:`systems/pf2e/templates/items/${sluggify(item.type)}-details.hbs`,cssClass:this.isEditable?"editable":"locked",editable:this.isEditable,document:item,item,isPhysical:!1,data:item.system,fieldIdPrefix:`field-${this.appId}-`,enrichedContent,limited:this.item.limited,options:this.options,owner:this.item.isOwner,title:this.title,user:{isGM:game.user.isGM},rarity:hasRarity?this.item.system.traits?.rarity??"common":null,rarities:CONFIG.PF2E.rarityTraits,traits,traitTagifyData,enabledRulesUI:game.user.isGM||game.settings.get("pf2e","enabledRulesUI"),ruleEditing:!!this.editingRuleElement,rules:{selection:{selected:__privateGet(this,_selectedRuleElementType),types:sortStringRecord(Object.keys(RuleElements.all).reduce((result,key)=>mergeObject(result,{[key]:`PF2E.RuleElement.${key}`}),{}))},elements:await Promise.all(__privateGet(this,_ruleElementForms).map(async form=>({template:await form.render()})))},proficiencies:CONFIG.PF2E.proficiencyLevels}}onTagSelector(anchor){if((anchor.dataset.tagSelector??"")!=="basic")throw ErrorPF2e("Item sheets can only use the basic tag selector");const propertyIsFlat=anchor.dataset.flat==="true",objectProperty=anchor.dataset.property??"",title=anchor.dataset.title,configTypes=(anchor.dataset.configTypes??"").split(",").map(type=>type.trim()).filter(tag=>tupleHasValue(SELECTABLE_TAG_FIELDS,tag)),selectorOptions={objectProperty,configTypes,title,flat:propertyIsFlat};anchor.dataset.noCustom==="true"?selectorOptions.allowCustom=!1:this.actor&&configTypes.includes("attackEffects")&&(selectorOptions.customChoices=this.getAttackEffectOptions()),new TagSelectorBasic(this.item,selectorOptions).render(!0)}getAttackEffectOptions(){return(this.actor?.items.contents??[]).filter(i=>i.isOfType("action","consumable")).reduce((options,item)=>{const key=item.slug??sluggify(item.name);return{...options,[key]:item.name}},deepClone(CONFIG.PF2E.attackEffects))}async activateEditor(name2,options={},initialContent){const sourceContent=name2==="system.description.value"?this.item._source.system.description.value:initialContent,mutuallyExclusive=["system.description.gm","system.description.value"];if(mutuallyExclusive.includes(name2)){const html=this.element[0];for(const elementName of mutuallyExclusive.filter(n=>n!==name2)){const element=htmlQuery(html,`[data-edit="${elementName}"]`),section=htmlClosest(element,".editor-container");section&&(section.style.display="none")}htmlQuery(html,".tab.description")?.classList.add("editing")}return super.activateEditor(name2,options,sourceContent)}async close(options){return __privateSet(this,_editingRuleElementIndex,null),super.close(options)}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const anchor of htmlQueryAll(html,"a.tag-selector"))anchor.addEventListener("click",()=>this.onTagSelector(anchor));const rulesPanel=htmlQuery(html,".tab[data-tab=rules]"),slugInput=htmlQuery(rulesPanel,'input[name="system.slug"]');slugInput&&(slugInput.addEventListener("change",()=>{slugInput.value=sluggify(slugInput.value)}),htmlQuery(rulesPanel,"a[data-action=regenerate-slug]")?.addEventListener("click",()=>{if(this._submitting)return;slugInput.value=sluggify(this.item.name);const event=new Event("change");slugInput.dispatchEvent(event)}));const ruleElementSelect=htmlQuery(rulesPanel,"select[data-action=select-rule-element]");ruleElementSelect?.addEventListener("change",()=>{__privateSet(this,_selectedRuleElementType,ruleElementSelect.value)});for(const anchor of htmlQueryAll(rulesPanel,"a.add-rule-element"))anchor.addEventListener("click",async event=>{await this._onSubmit(event);const rulesData=this.item.toObject().system.rules,key=__privateGet(this,_selectedRuleElementType)??"NewRuleElement";this.item.update({"system.rules":rulesData.concat({key})})});for(const anchor of htmlQueryAll(rulesPanel,"a.edit-rule-element"))anchor.addEventListener("click",async()=>{if(this._submitting)return;const index=Number(anchor.dataset.ruleIndex??"NaN")??null;__privateSet(this,_editingRuleElementIndex,index),__privateSet(this,_rulesLastScrollTop,rulesPanel?.scrollTop??null),this.render()});for(const anchor of htmlQueryAll(rulesPanel,".rules a.remove-rule-element"))anchor.addEventListener("click",async event=>{await this._onSubmit(event);const rules2=this.item.toObject().system.rules,index=Number(anchor.dataset.ruleIndex??"NaN");rules2&&Number.isInteger(index)&&rules2.length>index&&(rules2.splice(index,1),this.item.update({"system.rules":rules2}))});for(const anchor of htmlQueryAll(rulesPanel,"a[data-clipboard]"))anchor.addEventListener("click",()=>{const clipText=anchor.dataset.clipboard;clipText&&(game.clipboard.copyPlainText(clipText),ui.notifications.info(game.i18n.format("PF2E.ClipboardNotification",{clipText})))});const editingRuleElement=this.editingRuleElement;if(editingRuleElement){const ruleText=JSON.stringify(editingRuleElement,null,2),schema=RuleElements.all[String(editingRuleElement.key)]?.schema.fields,view=new CodeMirror.EditorView({doc:ruleText,extensions:[CodeMirror.basicSetup,CodeMirror.keybindings,...CodeMirror.ruleElementExtensions({schema})]});html.querySelector(".rule-editing .editor-placeholder")?.replaceWith(view.dom);const closeBtn=html.querySelector(".rule-editing button[data-action=close]");closeBtn?.addEventListener("click",()=>{__privateSet(this,_editingRuleElementIndex,null),this.render()}),closeBtn?.removeAttribute("disabled"),html.querySelector(".rule-editing button[data-action=apply]")?.addEventListener("click",()=>{const value=view.state.doc.toString();if(__privateGet(this,_editingRuleElementIndex)===null){__privateSet(this,_editingRuleElementIndex,null),this.render();return}try{const rules2=this.item.toObject().system.rules;rules2[__privateGet(this,_editingRuleElementIndex)]=JSON.parse(value),__privateSet(this,_editingRuleElementIndex,null),this.item.update({"system.rules":rules2})}catch(error){if(error instanceof Error)throw ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.RuleElementSyntax",{message:error.message})),console.warn("Syntax error in rule element definition.",error.message,value),error}})}const ruleSections=html.querySelectorAll(".rules .rule-form");for(const ruleSection of Array.from(ruleSections)){const idx=ruleSection.dataset.idx?Number(ruleSection.dataset.idx):NaN;__privateGet(this,_ruleElementForms).at(idx)?.activateListeners(ruleSection)}InlineRollLinks.listen(html,this.item);const{validTraits}=this,tagElement=html.querySelector(".sheet-header .tags"),traitsPrepend=html.querySelector(".traits-extra");if(validTraits!==null&&tagElement instanceof HTMLInputElement){const tags=tagify$1(tagElement,{whitelist:validTraits});traitsPrepend&&tags.DOM.scope.prepend(traitsPrepend.content)}else tagElement&&traitsPrepend&&tagElement.append(traitsPrepend.content);tagify$1(htmlQuery(html,'input[type=text][name="system.traits.otherTags"]'),{maxTags:6});const modifiedPropertyFields=htmlQueryAll(html,"[data-property]");for(const input of modifiedPropertyFields){const propertyPath=input.dataset.property??"",baseValue=input.dataset.valueBase??String(getProperty(this.item._source,propertyPath)??"").trim();input.addEventListener("focus",()=>{input.dataset.value=input.value,input.value=baseValue,input.name=propertyPath}),input.addEventListener("blur",()=>{input.removeAttribute("name"),input.value===baseValue&&(input.value=input.dataset.value??"")})}htmlQuery(html,".add-skill-variant")?.addEventListener("click",()=>{if(!this.item.isOfType("lore"))return;const variants=this.item.system.variants??{},index=Object.keys(variants).length;this.item.update({[`system.variants.${index}`]:{label:"+X in terrain",options:""}})});for(const button of htmlQueryAll(html,".skill-variants .remove-skill-variant"))button.addEventListener("click",event=>{if(!(event.currentTarget instanceof HTMLElement))return;const index=event.currentTarget.dataset.skillVariantIndex;this.item.update({[`system.variants.-=${index}`]:null})});if(this.isEditable&&game.user.isGM&&!this.item.system.description.gm&&!(this.item.isOfType("spell")&&this.item.isVariant)){const descriptionEditors=htmlQuery(html,".tab[data-tab=description]"),mainEditor=htmlQuery(descriptionEditors,".main .editor");if(!mainEditor)throw ErrorPF2e("Unexpected error retrieving description editor");const addGMNotesLink=document.createElement("a");addGMNotesLink.className=addGMNotesLink.dataset.action="add-gm-notes",addGMNotesLink.innerHTML=fontAwesomeIcon("fa-note-medical",{style:"regular"}).outerHTML,addGMNotesLink.dataset.tooltip="PF2E.Item.GMNotes.Add",mainEditor.prepend(addGMNotesLink),addGMNotesLink.addEventListener("click",()=>{htmlQuery(descriptionEditors,".gm-notes")?.classList.add("has-content"),this.activateEditor("system.description.gm")})}const rules=htmlQuery(html,".rule-element-forms");rules&&Sortable.create(rules,{...SORTABLE_DEFAULTS,handle:".drag-handle",onEnd:event=>{const currentIndex=event.oldDraggableIndex,newIndex=event.newDraggableIndex;if(currentIndex===void 0||newIndex===void 0){this.render();return}const rules2=this.item.toObject().system.rules,movingRule=rules2.at(currentIndex);movingRule&&newIndex<=rules2.length?(rules2.splice(currentIndex,1),rules2.splice(newIndex,0,movingRule),this.item.update({"system.rules":rules2})):this.render()}})}_getSubmitData(updateData=null){const fd=new FormDataExtended(this.form,{editors:this.editors}),data=updateData?mergeObject(fd.object,updateData):expandObject(fd.object),flattenedData=flattenObject(data);return processTagifyInSubmitData(this.form,flattenedData),flattenedData}_getHeaderButtons(){const buttons=super._getHeaderButtons();return game.settings.get("pf2e","dataTools")&&this.isEditable&&this.item.sourceId?.startsWith("Compendium.")&&buttons.unshift({label:"Refresh",class:"refresh-from-compendium",icon:"fa-solid fa-sync-alt",onclick:()=>this.item.refreshFromCompendium()}),buttons}_canDragDrop(_selector){return this.item.isOwner}async _onSubmit(event,{updateData=null,preventClose=!1,preventRender=!1}={}){return $(this.form).find("tags ~ input").each((_i,input)=>{input.value===""&&(input.value="[]")}),super._onSubmit(event,{updateData,preventClose,preventRender})}async _updateObject(event,formData){const expanded=expandObject(formData),form=htmlClosest(event.target,".rule-form[data-idx]");if(form){const idx=Number(form.dataset.idx),ruleForm=__privateGet(this,_ruleElementForms)[idx],itemRules=this.item.toObject().system.rules;if(idx>=itemRules.length||!ruleForm)throw ErrorPF2e(`Invalid rule form update, no rule form available at index ${idx}`);const incomingData=expanded.system?.rules?.[idx];incomingData&&(ruleForm.updateObject(incomingData),itemRules[idx]=ruleForm.rule,this.item.update({"system.rules":itemRules}))}return delete expanded.system?.rules,super._updateObject(event,flattenObject(expanded))}async _render(force,options){if(await maintainFocusInRender(this,()=>super._render(force,options)),__privateGet(this,_editingRuleElementIndex)===null&&__privateGet(this,_rulesLastScrollTop)){const html=this.element[0],rulesTab=htmlQuery(html,".tab[data-tab=rules]");rulesTab&&(rulesTab.scrollTop=__privateGet(this,_rulesLastScrollTop)),__privateSet(this,_rulesLastScrollTop,null)}}};_selectedRuleElementType=new WeakMap,_editingRuleElementIndex=new WeakMap,_rulesLastScrollTop=new WeakMap,_ruleElementForms=new WeakMap,_createRuleElementForms=new WeakSet,createRuleElementForms_fn=__name2(function(){const rules=this.item.toObject().system.rules,previousForms=[...__privateGet(this,_ruleElementForms)],processedRules=rules.map((rule,index)=>{const options={sheet:this,index,rule,object:this.item.rules.find(r=>r.sourceIndex===index)??null},FormClass=RULE_ELEMENT_FORMS[String(rule.key)]??RuleElementForm,existing=previousForms.find(f=>equals(f.rule,rule)&&f.constructor.name===FormClass.name)??null;return existing&&previousForms.splice(previousForms.indexOf(existing),1),{options,FormClass,existing}});for(const rule of processedRules.filter(p=>!p.existing)){const existing=__privateGet(this,_ruleElementForms)[rule.options.index];existing instanceof rule.FormClass&&(rule.existing=existing)}__privateSet(this,_ruleElementForms,processedRules.map(processed=>processed.existing?(processed.existing.initialize(processed.options),processed.existing):new processed.FormClass(processed.options)))},"#createRuleElementForms"),__name2(_ItemSheetPF2e,"ItemSheetPF2e");let ItemSheetPF2e=_ItemSheetPF2e;const _SettingsMenuPF2e=class extends FormApplication{static{__name(this,"_SettingsMenuPF2e")}cache={};static get defaultOptions(){const options=super.defaultOptions;return options.classes.push("settings-menu","sheet"),mergeObject(options,{title:`PF2E.SETTINGS.${this.namespace.titleCase()}.Name`,id:`${this.namespace}-settings`,template:"systems/pf2e/templates/system/settings/menu.hbs",width:550,height:"auto",tabs:[{navSelector:".sheet-tabs",contentSelector:"form"}],closeOnSubmit:!1,submitOnChange:!0})}static get prefix(){return`${this.namespace}.`}get namespace(){return this.constructor.namespace}get prefix(){return this.constructor.prefix}static get settings(){return{}}static registerSettings(){const settings=this.settings;for(const setting of this.SETTINGS)game.settings.register("pf2e",`${this.prefix}${setting}`,{...settings[setting],scope:"world",config:!1})}async getData(){const settings=this.constructor.settings,templateData=settingsToSheetData(settings,this.cache,this.prefix);return mergeObject(await super.getData(),{settings:templateData,instructions:`PF2E.SETTINGS.${this.namespace.titleCase()}.Hint`})}activateListeners($html){super.activateListeners($html);const html=$html[0],{highlightSetting}=this.options;if(highlightSetting){const formGroup=htmlClosest(htmlQuery(html,`label[for="${highlightSetting}"]`),".form-group");formGroup&&(formGroup.style.animation="glow 0.75s infinite alternate")}}async _updateObject(event,data){for(const key of this.constructor.SETTINGS){const settingKey=`${this.prefix}${key}`,value=data[key];this.cache[key]=value,event.type==="submit"&&await game.settings.set("pf2e",settingKey,value)}event.type==="submit"?this.close():this.render()}_injectHTML($html){super._injectHTML($html);for(const key of this.constructor.SETTINGS){const settingKey=`${this.prefix}${key}`;this.cache[key]=game.settings.get("pf2e",settingKey)}}};__name2(_SettingsMenuPF2e,"SettingsMenuPF2e"),__publicField(_SettingsMenuPF2e,"namespace"),__publicField(_SettingsMenuPF2e,"SETTINGS");let SettingsMenuPF2e=_SettingsMenuPF2e;function settingsToSheetData(settings,cache,prefix=""){return Object.entries(settings).reduce((result,[key,setting])=>{const lookupKey=`${prefix}${key}`,value=key in cache?cache[key]:game.settings.get("pf2e",lookupKey);return cache[key]=value,result[key]={...setting,key,value,isSelect:!!setting.choices,isCheckbox:setting.type===Boolean},result},{})}__name(settingsToSheetData,"settingsToSheetData"),__name2(settingsToSheetData,"settingsToSheetData");function isHomebrewFlagCategory(value){return isObject$1(value)&&Object.entries(value).every(([_hbKey,hbLabel])=>typeof hbLabel=="string"||isObject(hbLabel)&&isLabelAndDescription(hbLabel))}__name(isHomebrewFlagCategory,"isHomebrewFlagCategory"),__name2(isHomebrewFlagCategory,"isHomebrewFlagCategory");function isHomebrewCustomDamage(value){return Object.values(value).every(value2=>isObject(value2)&&typeof value2.label=="string"&&["physical","energy"].includes(value2.category??""))}__name(isHomebrewCustomDamage,"isHomebrewCustomDamage"),__name2(isHomebrewCustomDamage,"isHomebrewCustomDamage");function isLabelAndDescription(obj){return typeof obj.label=="string"&&typeof obj.description=="string"}__name(isLabelAndDescription,"isLabelAndDescription"),__name2(isLabelAndDescription,"isLabelAndDescription");function prepareCleanup(listKey,deletions){var _a;const Migration=(_a=class extends MigrationBase{static{__name(this,"_a")}async updateActor(source){if(source.type==="character"||source.type==="npc")switch(listKey){case"creatureTraits":{const traits=source.system.traits;traits.value=traits.value.filter(t=>!deletions.includes(t));break}case"languages":{const languages=source.system.traits.languages;languages.value=languages.value.filter(l=>!deletions.includes(l));break}case"weaponCategories":{if(source.type==="character"){const attacks=source.system.proficiencies?.attacks??{};for(const key of deletions)attacks[key]&&(delete attacks[key],attacks[`-=${key}`]=null)}break}case"weaponGroups":{if(source.type==="character"){const proficiencyKeys=deletions.map(deletion=>`weapon-group-${deletion}`),attacks=source.system.proficiencies?.attacks??{};for(const key of proficiencyKeys)delete attacks[key],attacks[`-=${key}`]=null}break}case"baseWeapons":{if(source.type==="character"){const proficiencyKeys=deletions.map(deletion=>`weapon-base-${deletion}`),attacks=source.system.proficiencies?.attacks??{};for(const key of proficiencyKeys)delete attacks[key],attacks[`-=${key}`]=null}break}case"weaponTraits":{const weaponsAndAttacks=source.items.filter(i=>["melee","weapon"].includes(i.type));for(const itemSource of weaponsAndAttacks){const traits=itemSource.system.traits.value;for(const deleted of deletions)traits.findSplice(t=>t===deleted)}}}}async updateItem(source){switch(listKey){case"creatureTraits":{if(source.system.traits?.value){const traits=source.system.traits;traits.value=traits.value.filter(t=>!deletions.includes(t))}break}case"featTraits":{if(source.type==="feat"){const traits=source.system.traits;traits.value=traits.value.filter(t=>!deletions.includes(t))}break}case"magicSchools":case"spellTraits":{if(source.type==="spell"){const traits=source.system.traits;traits.value=traits.value.filter(t=>!deletions.includes(t))}break}case"weaponCategories":{if(source.type==="weapon"){const systemData=source.system;systemData.category=deletions.includes(systemData.category??"")?"simple":systemData.category}break}case"weaponGroups":{if(source.type==="weapon"){const systemData=source.system;systemData.group=deletions.includes(systemData.group??"")?null:systemData.group}break}case"baseWeapons":{if(source.type==="weapon"){const base=source.system.baseItem;source.system.baseItem=deletions.includes(base??"")?null:base}break}}}},__name2(_a,"Migration"),__publicField(_a,"version",MigrationRunnerBase.LATEST_SCHEMA_VERSION),_a);return new Migration}__name(prepareCleanup,"prepareCleanup"),__name2(prepareCleanup,"prepareCleanup");const tagify="",_HomebrewElements=class extends SettingsMenuPF2e{static{__name(this,"_HomebrewElements")}constructor(){super(...arguments),__privateAdd(this,_processDeletions),__privateAdd(this,_refreshSettings),__privateAdd(this,_registerModuleTags),__privateAdd(this,_getConfigRecord),__privateAdd(this,_updateConfigRecords),__privateAdd(this,_initialRefresh,!0),__privateAdd(this,_damageManager,new DamageTypeManager)}static get SETTINGS(){return Object.keys(this.settings)}static get defaultOptions(){return mergeObject(super.defaultOptions,{template:"systems/pf2e/templates/system/settings/homebrew.hbs"})}static get traitSettings(){return HOMEBREW_TRAIT_KEYS.reduce((result,key)=>(result[key]={name:CONFIG.PF2E.SETTINGS.homebrew[key].name,hint:CONFIG.PF2E.SETTINGS.homebrew[key].hint,default:[],type:Object},result),{})}static get settings(){return{...this.traitSettings,damageTypes:{name:"PF2E.SETTINGS.Homebrew.DamageTypes.Name",default:[],type:Object}}}activateListeners($form){super.activateListeners($form);const html=$form[0];$form.find("button[name=reset]").on("click",()=>{this.render()});for(const key of HOMEBREW_TRAIT_KEYS){const $input=$form.find(`input[name="${key}"]`);new Tagify($input[0],{editTags:1,hooks:{beforeRemoveTag:tags=>{const localize=localizer("PF2E.SETTINGS.Homebrew.ConfirmDelete"),response=(async()=>{const content=localize("Message",{element:tags[0].data.value});return await Dialog.confirm({title:localize("Title"),content:`

${content}

`})})();return(async()=>await response?Promise.resolve():Promise.reject())()}}})}htmlQuery(html,"[data-action=damage-add]")?.addEventListener("click",async()=>{this.cache.damageTypes.push({label:"Custom",category:"physical",icon:"fa-question"}),this.render()});for(const element of htmlQueryAll(html,"[data-action=damage-delete]"))element.addEventListener("click",async event=>{const idx=htmlClosest(event.target,"[data-idx]")?.dataset.idx;idx&&this.cache.damageTypes.splice(Number(idx),1),this.render()})}async getData(){const data=await super.getData(),traitSettings=settingsToSheetData(this.constructor.traitSettings,this.cache,this.prefix),damageCategories2=pick(CONFIG.PF2E.damageCategories,["physical","energy"]);return{...data,traitSettings,damageCategories:damageCategories2,customDamageTypes:(this.cache.damageTypes??[]).map(customType=>({...customType,slug:`hb_${sluggify(customType.label)}`}))}}async _onSubmit(event,{updateData=null,preventClose=!1,preventRender=!1}={}){return this.form.querySelectorAll("tags ~ input").forEach(input=>{input.value===""&&(input.value="[]")}),super._onSubmit(event,{updateData,preventClose,preventRender})}_getSubmitData(updateData){const original=super._getSubmitData(updateData),data=expandObject(original);if("damageTypes"in data&&data.damageTypes&&typeof data.damageTypes=="object"){data.damageTypes=Object.values(data.damageTypes);for(const type of data.damageTypes){const sanitized=sluggify(type.icon??"");type.icon=sanitized.startsWith("fa-")?sanitized:null}}return data}async _updateObject(event,data){for(const key of HOMEBREW_TRAIT_KEYS)for(const tag of data[key])tag.id??=`hb_${sluggify(tag.value)}`;if(event.type==="submit"){const cleanupTasks=HOMEBREW_TRAIT_KEYS.map(key=>__privateMethod(this,_processDeletions,processDeletions_fn).call(this,key,data[key])).filter(task=>!!task);new MigrationRunner().runMigrations(cleanupTasks),await super._updateObject(event,data),__privateMethod(this,_refreshSettings,refreshSettings_fn).call(this)}else return super._updateObject(event,data)}onInit(){__privateMethod(this,_refreshSettings,refreshSettings_fn).call(this),__privateMethod(this,_registerModuleTags,registerModuleTags_fn).call(this)}};_initialRefresh=new WeakMap,_damageManager=new WeakMap,_processDeletions=new WeakSet,processDeletions_fn=__name2(function(listKey,newTagList){const oldTagList=game.settings.get("pf2e",`homebrew.${listKey}`),newIDList=newTagList.map(tag=>tag.id),deletions=oldTagList.flatMap(oldTag=>newIDList.includes(oldTag.id)?[]:oldTag.id),coreElements=listKey==="baseWeapons"?CONFIG.PF2E.baseWeaponTypes:CONFIG.PF2E[listKey];for(const id of deletions)if(delete coreElements[id],objectHasKey(SECONDARY_TRAIT_RECORDS,listKey))for(const recordKey of SECONDARY_TRAIT_RECORDS[listKey]){const secondaryRecord=CONFIG.PF2E[recordKey];delete secondaryRecord[id]}return game.user.isGM&&deletions.length>0?prepareCleanup(listKey,deletions):null},"#processDeletions"),_refreshSettings=new WeakSet,refreshSettings_fn=__name2(function(){__privateGet(this,_initialRefresh)||__privateGet(this,_damageManager).deleteAllHomebrew();for(const listKey of HOMEBREW_TRAIT_KEYS){const settingsKey=`homebrew.${listKey}`,elements=game.settings.get("pf2e",settingsKey);__privateMethod(this,_updateConfigRecords,updateConfigRecords_fn).call(this,elements,listKey)}const customTypes=game.settings.get("pf2e","homebrew.damageTypes");for(const data of customTypes)__privateGet(this,_damageManager).addCustomDamage(data);const activeModules=[...game.modules.entries()].filter(([_key,foundryModule])=>foundryModule.active);for(const[key,foundryModule]of activeModules){const homebrew=foundryModule.flags?.[key]?.["pf2e-homebrew"];if(isObject(homebrew)&&"damageTypes"in homebrew){const elements=homebrew.damageTypes;if(!isObject(elements)||!isHomebrewCustomDamage(elements)){console.warn(`PF2E System | Homebrew record damageTypes is malformed in module ${key}`);continue}for(const[slug,value]of Object.entries(elements))__privateGet(this,_damageManager).addCustomDamage(value,{slug})}}if(__privateGet(this,_initialRefresh))__privateSet(this,_initialRefresh,!1);else{const sheets=Object.values(ui.windows).filter(app=>app instanceof ActorSheet||app instanceof ItemSheetPF2e);for(const sheet of sheets)sheet.render(!1)}},"#refreshSettings"),_registerModuleTags=new WeakSet,registerModuleTags_fn=__name2(function(){const activeModules=[...game.modules.entries()].filter(([_key,foundryModule])=>foundryModule.active);for(const[key,foundryModule]of activeModules){const homebrew=foundryModule.flags?.[key]?.["pf2e-homebrew"];if(isObject$1(homebrew)){for(const recordKey of Object.keys(homebrew))if(!["damageTypes"].includes(recordKey))if(tupleHasValue(HOMEBREW_TRAIT_KEYS,recordKey)){const elements=homebrew[recordKey];if(!isObject(elements)||!isHomebrewFlagCategory(elements)){console.warn(`PF2E System | Homebrew record ${recordKey} is malformed in module ${key}`);continue}const tags=Object.entries(elements).map(([id,value])=>({id:`hb_${id}`,value:typeof value=="string"?value:value.label}));__privateMethod(this,_updateConfigRecords,updateConfigRecords_fn).call(this,tags,recordKey);for(const[key2,value]of Object.entries(elements))if(typeof value=="object"){const hbKey=`hb_${key2}`;CONFIG.PF2E.traitsDescriptions[hbKey]=value.description}}else{console.warn(`PF2E System | Invalid homebrew record "${recordKey}" in module ${key}`);continue}}}},"#registerModuleTags"),_getConfigRecord=new WeakSet,getConfigRecord_fn=__name2(function(recordKey){return recordKey==="baseWeapons"?CONFIG.PF2E.baseWeaponTypes:CONFIG.PF2E[recordKey]},"#getConfigRecord"),_updateConfigRecords=new WeakSet,updateConfigRecords_fn=__name2(function(elements,listKey){const coreElements=__privateMethod(this,_getConfigRecord,getConfigRecord_fn).call(this,listKey);for(const element of elements)if(coreElements[element.id]=element.value,objectHasKey(SECONDARY_TRAIT_RECORDS,listKey))for(const recordKey of SECONDARY_TRAIT_RECORDS[listKey]){const record=CONFIG.PF2E[recordKey];record[element.id]=element.value}},"#updateConfigRecords"),__name2(_HomebrewElements,"HomebrewElements"),__publicField(_HomebrewElements,"namespace","homebrew");let HomebrewElements=_HomebrewElements;const _DamageTypeManager=class{static{__name(this,"_DamageTypeManager")}collections={physical:PHYSICAL_DAMAGE_TYPES,energy:ENERGY_DAMAGE_TYPES,DAMAGE_TYPES,BASE_DAMAGE_TYPES_TO_CATEGORIES,DAMAGE_TYPE_ICONS,damageTypesLocalization:CONFIG.PF2E.damageTypes,damageRollFlavorsLocalization:CONFIG.PF2E.damageRollFlavors,immunityTypes,weaknessTypes,resistanceTypes};addCustomDamage(data,options={}){const collections=this.collections,slug=`hb_${options.slug??sluggify(data.label)}`;collections.DAMAGE_TYPES.add(slug),collections[tupleHasValue(["physical","energy"],data.category)?data.category:"physical"].push(slug),collections.BASE_DAMAGE_TYPES_TO_CATEGORIES[slug]=data.category,collections.DAMAGE_TYPE_ICONS[slug]=data.icon?.substring(3)??null,collections.damageTypesLocalization[slug]=data.label;const damageFlavor=data.label.toLocaleLowerCase();collections.damageRollFlavorsLocalization[slug]=damageFlavor,collections.immunityTypes[slug]=damageFlavor,collections.weaknessTypes[slug]=damageFlavor,collections.resistanceTypes[slug]=damageFlavor}deleteAllHomebrew(){for(const collection of Object.values(this.collections))if(collection instanceof Set){const hbTraits=[...collection].filter(tag=>tag.startsWith("hb_"));for(const trait of hbTraits)collection.delete(trait)}else{const hbTraits=Object.keys(collection).filter(tag=>tag.startsWith("hb_"));for(const trait of hbTraits)delete collection[trait]}}};__name2(_DamageTypeManager,"DamageTypeManager");let DamageTypeManager=_DamageTypeManager;const _Migration674StableHomebrewTagIDs=class extends MigrationBase{static{__name(this,"_Migration674StableHomebrewTagIDs")}homebrewKeys=deepClone(HOMEBREW_TRAIT_KEYS);homebrewTags=this.homebrewKeys.reduce((settings,key)=>mergeObject(settings,{[key]:game.settings.get("pf2e",`homebrew.${key}`)}),{});updateDocumentTags(documentTags=[]){for(const key of this.homebrewKeys){const homebrewTags=this.homebrewTags[key];for(const tag of homebrewTags){const index=documentTags.indexOf(tag.id);index!==-1&&documentTags.splice(index,1,`hb_${sluggify(tag.value)}`)}}}async updateActor(source){source.type==="familiar"||!source.system.traits?.traits||(this.updateDocumentTags(source.system.traits.traits.value),(source.type==="character"||source.type==="npc")&&this.updateDocumentTags(source.system.traits?.languages.value))}async updateItem(itemSource){this.updateDocumentTags(itemSource.system.traits?.value)}async migrate(){for(const key of this.homebrewKeys){const tags=this.homebrewTags[key];for(const tag of tags){tag.id=`hb_${sluggify(tag.value)}`;const tagMap=key==="baseWeapons"?CONFIG.PF2E.baseWeaponTypes:CONFIG.PF2E[key];tagMap[tag.id]=tag.value,delete tagMap[key]}tags.length>0&&await game.settings.set("pf2e",`homebrew.${key}`,tags)}}};__name2(_Migration674StableHomebrewTagIDs,"Migration674StableHomebrewTagIDs"),__publicField(_Migration674StableHomebrewTagIDs,"version",.674);let Migration674StableHomebrewTagIDs=_Migration674StableHomebrewTagIDs;const _Migration675FlatModifierAEsToREs=class extends MigrationBase{static{__name(this,"_Migration675FlatModifierAEsToREs")}constructor(){super(...arguments),__privateAdd(this,_isFlatModifier),__privateAdd(this,_toRuleElement)}async updateActor(actorSource){for(const effect of[...actorSource.effects])effect.changes.some(change=>change.key.endsWith(".modifiers"))&&actorSource.effects.splice(actorSource.effects.indexOf(effect),1)}async updateItem(itemSource){for(const effect of[...itemSource.effects]){for(const change of effect.changes.filter(change2=>change2.key.endsWith(".modifiers"))){const reData=__privateMethod(this,_toRuleElement,toRuleElement_fn).call(this,change.value);reData&&(effect.changes.splice(effect.changes.indexOf(change),1),itemSource.system.rules.push(reData))}effect.changes.length===0&&itemSource.effects.splice(itemSource.effects.indexOf(effect),1)}}};_isFlatModifier=new WeakSet,isFlatModifier_fn=__name2(function(data){return typeof data=="object"&&data!==null&&__name2(obj=>(typeof obj.modifier=="number"||typeof obj.modifier=="string")&&typeof obj.type=="string","dataIsModifier")(data)},"#isFlatModifier"),_toRuleElement=new WeakSet,toRuleElement_fn=__name2(function(aeValue){const aeModifier=(()=>{try{const parsed=JSON.parse(aeValue);return __privateMethod(this,_isFlatModifier,isFlatModifier_fn).call(this,parsed)?parsed:null}catch(error){return console.warn(error),null}})();return typeof aeModifier?.modifier=="string"&&aeModifier.modifier.replace("@data.","@"),aeModifier&&{key:"FlatModifier",type:aeModifier.type,value:aeModifier.modifier,selector:"hp"}},"#toRuleElement"),__name2(_Migration675FlatModifierAEsToREs,"Migration675FlatModifierAEsToREs"),__publicField(_Migration675FlatModifierAEsToREs,"version",.675);let Migration675FlatModifierAEsToREs=_Migration675FlatModifierAEsToREs;const _Migration676ReplaceItemsWithRELikeAEs=class extends MigrationBase{static{__name(this,"_Migration676ReplaceItemsWithRELikeAEs")}toughnessPromise=fromUuid("Compendium.pf2e.feats-srd.AmP0qu7c5dlBSath");stoutnessPromise=fromUuid("Compendium.pf2e.feats-srd.COP89tjrNhEucuRW");toughPromise=fromUuid("Compendium.pf2e.familiar-abilities.Le8UWr5BU8rV3iBf");replaceItem({items,type,slug,replacement}){if(!(replacement instanceof ItemPF2e))throw ErrorPF2e("Unexpected error retrieving compendium item");const current=items.find(itemSource=>itemSource.type===type&&itemSource.system.slug?.replace(/'/g,"")===slug);if(current){const newSource=replacement.toObject();current.type==="feat"&&newSource.type==="feat"&&(newSource.system.location=current.system.location),items.splice(items.indexOf(current),1,newSource)}}async updateActor(actorSource){actorSource.type==="familiar"?this.replaceItem({items:actorSource.items,type:"effect",slug:"tough",replacement:await this.toughPromise}):actorSource.type==="character"&&(this.replaceItem({items:actorSource.items,type:"feat",slug:"toughness",replacement:await this.toughnessPromise}),this.replaceItem({items:actorSource.items,type:"feat",slug:"mountains-stoutness",replacement:await this.stoutnessPromise}))}};__name2(_Migration676ReplaceItemsWithRELikeAEs,"Migration676ReplaceItemsWithRELikeAEs"),__publicField(_Migration676ReplaceItemsWithRELikeAEs,"version",.676);let Migration676ReplaceItemsWithRELikeAEs=_Migration676ReplaceItemsWithRELikeAEs;const _Migration677RuleValueDataRefs=class extends MigrationBase{static{__name(this,"_Migration677RuleValueDataRefs")}async updateItem(itemSource){for(const rule of itemSource.system.rules)typeof rule.value=="string"&&(rule.value=rule.value.replace("@data.","@"))}};__name2(_Migration677RuleValueDataRefs,"Migration677RuleValueDataRefs"),__publicField(_Migration677RuleValueDataRefs,"version",.677);let Migration677RuleValueDataRefs=_Migration677RuleValueDataRefs;const _Migration678SeparateNPCAttackTraits=class extends MigrationBase{static{__name(this,"_Migration678SeparateNPCAttackTraits")}async updateItem(itemSource){if(itemSource.type==="weapon"){const weaponTraits2=itemSource.system.traits.value,rangeTraits2=weaponTraits2.filter(trait=>/^range(?!d)/.test(trait));for(const trait of rangeTraits2)weaponTraits2.splice(weaponTraits2.indexOf(trait),1);const reloadTraits=weaponTraits2.filter(trait=>trait.startsWith("reload"));for(const trait of reloadTraits)weaponTraits2.splice(weaponTraits2.indexOf(trait),1);itemSource.system.traits.value=[...new Set(weaponTraits2)].sort()}if(!itemSource.system.traits)return;const itemTraits=itemSource.system.traits.value??[];for(const trait of itemTraits)tupleHasValue(RARITIES,trait)&&(itemTraits.splice(itemTraits.indexOf(trait),1),trait!=="common"&&isObject(itemSource.system.traits.rarity)&&itemSource.system.traits.rarity.value==="common"&&(itemSource.system.traits.rarity.value=trait))}};__name2(_Migration678SeparateNPCAttackTraits,"Migration678SeparateNPCAttackTraits"),__publicField(_Migration678SeparateNPCAttackTraits,"version",.678);let Migration678SeparateNPCAttackTraits=_Migration678SeparateNPCAttackTraits;const _Migration679TowerShieldSpeedPenalty=class extends MigrationBase{static{__name(this,"_Migration679TowerShieldSpeedPenalty")}towerShieldSlugs=["darkwood-tower-shield-high-grade","darkwood-tower-shield-standard-grade","tower-shield"];async updateItem(source){if(source.type==="armor"){const systemData=source.system;systemData.speed&&this.towerShieldSlugs.includes(systemData.slug??"")&&(systemData.speed.value=-5),systemData.armor&&(systemData.armor.value=Number(systemData.armor.value)||0),systemData.speed&&(systemData.speed.value=Number(systemData.speed.value)||0);const potencyRune=systemData.potencyRune;potencyRune.value=Number(systemData.potencyRune.value)||0,"resilient"in systemData&&("game"in globalThis?systemData["-=resilient"]=null:delete systemData.resilient)}}};__name2(_Migration679TowerShieldSpeedPenalty,"Migration679TowerShieldSpeedPenalty"),__publicField(_Migration679TowerShieldSpeedPenalty,"version",.679);let Migration679TowerShieldSpeedPenalty=_Migration679TowerShieldSpeedPenalty;const _Migration680SetWeaponHands=class extends MigrationBase{static{__name(this,"_Migration680SetWeaponHands")}oneHandedWeapons=new Set(["repeating-hand-crossbow"]);onePlusHandedWeapons=new Set(["backpack-ballista","backpack-catapult","composite-longbow","composite-shortbow","hongali-hornbow","longbow","shortbow","sun-sling"]);shieldAttachments=new Set(["shield-boss","shield-spikes"]);firearmAttachments=new Set(["bayonette","reinforced-stock"]);wornGloves=new Set(["handwraps-of-mighty-blows"]);twoHandedWeapons=new Set(["adze","alchemical-crossbow","arquebus","axe-musket","bladed-diabolo","bladed-scarf","blunderbuss","bo-staff","boarding-pike","butchering-axe","combat-grapnel","crossbow","double-barreled-musket","dueling-spear","dwarven-scattergun","elven-branched-spear","elven-curve-blade","explosive-dogslicer","falchion","fauchard","fire-lance","flingflenser","flintlock-musket","gill-hook","glaive","gnome-amalgam-musket","greataxe","greatclub","greatpick","greatsword","guisarme","gun-sword","halberd","halfling-sling-staff","hammer-gun","harmona-gun","heavy-crossbow","horsechopper","kusarigama","lance","longspear","maul","meteor-hammer","mithral-tree","naginata","ogre-hook","ranseur","repeating-crossbow","repeating-heavy-crossbow","scythe","shauth-lash","spiked-chain","taw-launcher","three-peaked-tree","thundermace","war-flail","whip-claw"]);isShield(source){return source.type==="armor"&&(source.system.armorType?.value==="shield"||source.system.category==="shield")}async updateItem(itemSource){if(this.isShield(itemSource))itemSource.system.usage.value="held-in-one-hand";else if(itemSource.type==="weapon"){itemSource.system.usage??={value:"held-in-one-hand"};const{baseItem,slug,traits}=itemSource.system,usage=itemSource.system.usage;if(this.twoHandedWeapons.has(baseItem||slug||""))usage.value="held-in-two-hands";else if(this.onePlusHandedWeapons.has(baseItem||slug||""))usage.value="held-in-one-plus-hands";else if(this.oneHandedWeapons.has(baseItem||slug||""))usage.value="held-in-one-hand";else if(this.shieldAttachments.has(baseItem||slug||"")){usage.value="held-in-one-hand";const attachedIndex=traits.value.findIndex(trait=>trait==="attached");attachedIndex!==-1&&traits.value.splice(attachedIndex,1,"attached-to-shield")}else if(this.firearmAttachments.has(baseItem||slug||"")){usage.value="held-in-one-hand";const attachedIndex=traits.value.findIndex(trait=>trait==="attached");attachedIndex!==-1&&traits.value.splice(attachedIndex,1,"attached-to-crossbow-or-firearm")}else this.wornGloves.has(baseItem||slug||"")&&(usage.value="worn-gloves")}}};__name2(_Migration680SetWeaponHands,"Migration680SetWeaponHands"),__publicField(_Migration680SetWeaponHands,"version",.68);let Migration680SetWeaponHands=_Migration680SetWeaponHands;const _Migration681GiantLanguageToJotun=class extends MigrationBase{static{__name(this,"_Migration681GiantLanguageToJotun")}replaceGiant({value}){const giantIndex=value.indexOf("giant");giantIndex!==-1&&value.splice(giantIndex,1,"jotun")}async updateActor(actorSource){(actorSource.type==="character"||actorSource.type==="npc")&&this.replaceGiant(actorSource.system.traits.languages)}async updateItem(itemSource){itemSource.type==="ancestry"&&this.replaceGiant(itemSource.system.additionalLanguages)}};__name2(_Migration681GiantLanguageToJotun,"Migration681GiantLanguageToJotun"),__publicField(_Migration681GiantLanguageToJotun,"version",.681);let Migration681GiantLanguageToJotun=_Migration681GiantLanguageToJotun;const _Migration682BiographyFields=class extends MigrationBase{static{__name(this,"_Migration682BiographyFields")}replaceBiographyData(old){old.details.biography.public?(old.details.biography.appearance=old.details.biography.public,old.details.biography["-=public"]=null):old.details.biography.appearance??="",old.details.biography.value?(old.details.biography.campaignNotes=old.details.biography.value,old.details.biography["-=value"]=null):old.details.biography.campaignNotes??="","game"in globalThis||(delete old.details.biography.public,delete old.details.biography.value),old.details.biography.backstory??="",old.details.biography.birthPlace??="",old.details.biography.attitude??="",old.details.biography.beliefs??="",old.details.biography.likes??="",old.details.biography.dislikes??="",old.details.biography.catchphrases??="",old.details.biography.allies??="",old.details.biography.enemies??="",old.details.biography.organaizations??=""}async updateActor(source){source.type==="character"&&this.replaceBiographyData(source.system)}};__name2(_Migration682BiographyFields,"Migration682BiographyFields"),__publicField(_Migration682BiographyFields,"version",.682);let Migration682BiographyFields=_Migration682BiographyFields;const _Migration683FlavorTextToPublicNotes=class extends MigrationBase{static{__name(this,"_Migration683FlavorTextToPublicNotes")}replaceFlavorTextData(old){old.details.flavorText?(old.details.publicNotes=old.details.flavorText,old.details["-=flavorText"]=null):old.details.publicNotes??="","game"in globalThis||delete old.details.flavorText,old.details.blurb??="",old.details.privateNotes??=""}async updateActor(actorSource){actorSource.type==="npc"&&this.replaceFlavorTextData(actorSource.system)}};__name2(_Migration683FlavorTextToPublicNotes,"Migration683FlavorTextToPublicNotes"),__publicField(_Migration683FlavorTextToPublicNotes,"version",.683);let Migration683FlavorTextToPublicNotes=_Migration683FlavorTextToPublicNotes;const _Migration684RationsToConsumable=class extends MigrationBase{static{__name(this,"_Migration684RationsToConsumable")}constructor(){super(...arguments),__privateAdd(this,_isOldRations),__privateAdd(this,_getRationRefs),__privateAdd(this,_rationsSourceId,"Compendium.pf2e.equipment-srd.L9ZV076913otGtiB"),__privateAdd(this,_rationsPromise,fromUuid(__privateGet(this,_rationsSourceId)))}async updateActor(source){const oldRations=source.items.filter(i=>__privateMethod(this,_isOldRations,isOldRations_fn).call(this,i)),rations=await __privateGet(this,_rationsPromise);if(!(rations instanceof ConsumablePF2e))throw ErrorPF2e("Unexpected error acquiring compendium item");for(const oldRation of oldRations){const newRation=rations.toObject();newRation.folder=oldRation.folder,newRation.sort=oldRation.sort;const oldContainerId=oldRation.system.containerId??{value:null};oldContainerId instanceof Object&&(newRation.system.containerId=oldContainerId.value);const oldQuantity=oldRation.system.quantity;isObject(oldQuantity)&&(newRation.system.quantity=Math.ceil((oldQuantity.value??1)/7)),source.items.findSplice(item=>item===oldRation,newRation)}}async updateItem(source){if(source.type!=="kit")return;const rationRefs=__privateMethod(this,_getRationRefs,getRationRefs_fn).call(this,Object.values(source.system.items));for(const rationRef of rationRefs)rationRef.quantity=Math.ceil(rationRef.quantity/7)}};_rationsSourceId=new WeakMap,_rationsPromise=new WeakMap,_isOldRations=new WeakSet,isOldRations_fn=__name2(function(itemSource){return itemSource?.type==="equipment"&&itemSource.flags.core?.sourceId===__privateGet(this,_rationsSourceId)},"#isOldRations"),_getRationRefs=new WeakSet,getRationRefs_fn=__name2(function(itemRefs){return itemRefs.reduce((rationRefs,itemRef)=>(itemRef.isContainer&&itemRef.items?rationRefs.push(...__privateMethod(this,_getRationRefs,getRationRefs_fn).call(this,Object.values(itemRef.items))):itemRef.pack==="pf2e.equipment-srd"&&itemRef.id==="L9ZV076913otGtiB"&&rationRefs.push(itemRef),rationRefs),[])},"#getRationRefs"),__name2(_Migration684RationsToConsumable,"Migration684RationsToConsumable"),__publicField(_Migration684RationsToConsumable,"version",.684);let Migration684RationsToConsumable=_Migration684RationsToConsumable;const _Migration685FixMeleeUsageTraits=class extends MigrationBase{static{__name(this,"_Migration685FixMeleeUsageTraits")}async updateItem(itemSource){if(itemSource.type==="weapon"){const systemData=itemSource.system;systemData.meleeUsage&&!Array.isArray(systemData.meleeUsage.traits)&&(systemData.meleeUsage.traits=systemData.meleeUsage.traits?.value??[])}}};__name2(_Migration685FixMeleeUsageTraits,"Migration685FixMeleeUsageTraits"),__publicField(_Migration685FixMeleeUsageTraits,"version",.685);let Migration685FixMeleeUsageTraits=_Migration685FixMeleeUsageTraits;const _Migration686HeroPointsToResources=class extends MigrationBase{static{__name(this,"_Migration686HeroPointsToResources")}async updateActor(actorSource){if(actorSource.type!=="character")return;const systemSource=actorSource.system;if(systemSource.attributes.heroPoints){const resources=systemSource.resources;resources.heroPoints={value:systemSource.attributes.heroPoints.rank},systemSource.attributes["-=heroPoints"]=null,"game"in globalThis||delete systemSource.attributes.heroPoints}}};__name2(_Migration686HeroPointsToResources,"Migration686HeroPointsToResources"),__publicField(_Migration686HeroPointsToResources,"version",.686);let Migration686HeroPointsToResources=_Migration686HeroPointsToResources;const _Migration687FamiliarityAEsToREs=class extends MigrationBase{static{__name(this,"_Migration687FamiliarityAEsToREs")}isFamiliarityAE(data){return typeof data=="object"&&data!==null&&__name2(obj=>typeof obj.trait=="string"&&typeof obj.category=="string","dataIsFamiliarity")(data)}toRuleElement(sameAs,aeValue){const aeData=(()=>{try{const parsed=JSON.parse(aeValue);return this.isFamiliarityAE(parsed)?parsed:null}catch(error){return console.warn(error),null}})();return aeData&&{key:"LinkedProficiency",slug:`${aeData.category}-${aeData.trait}-weapons`,predicate:{all:[`weapon:trait:${aeData.trait}`,`weapon:category:${aeData.category}`]},sameAs}}async updateActor(actorSource){actorSource.effects=[]}async updateItem(itemSource){for(const effect of[...itemSource.effects])for(const change of effect.changes.filter(change2=>change2.key.startsWith("system.martial."))){const linkTo=change.key.replace(/^data\.martial\.|\.familiarity$/g,""),reData=this.toRuleElement(linkTo,change.value);reData&&itemSource.system.rules.push(reData)}itemSource.effects=[]}};__name2(_Migration687FamiliarityAEsToREs,"Migration687FamiliarityAEsToREs"),__publicField(_Migration687FamiliarityAEsToREs,"version",.687);let Migration687FamiliarityAEsToREs=_Migration687FamiliarityAEsToREs;const _Migration688ClampSpellLevel=class extends MigrationBase{static{__name(this,"_Migration688ClampSpellLevel")}async updateItem(itemSource){itemSource.type==="spell"&&(itemSource.system.level.value=Math.min(Math.max(itemSource.system.level.value,1),10))}};__name2(_Migration688ClampSpellLevel,"Migration688ClampSpellLevel"),__publicField(_Migration688ClampSpellLevel,"version",.688);let Migration688ClampSpellLevel=_Migration688ClampSpellLevel;const _Migration689EncumberanceActiveEffects=class extends MigrationBase{static{__name(this,"_Migration689EncumberanceActiveEffects")}async updateItem(itemSource){const systemData=itemSource.system,slug=systemData.slug??sluggify(itemSource.name),amountToIncreaseBy=(()=>itemSource.type==="feat"&&slug==="hefty-hauler"?2:itemSource.type==="feat"&&slug==="hardy-traveler"||itemSource.type==="equipment"&&slug==="lifting-belt"?1:0)();if(amountToIncreaseBy===0||systemData.rules.some(r=>r.key==="ActiveEffectLike"))return;const rules=[{key:"ActiveEffectLike",path:"system.attributes.bonusEncumbranceBulk",mode:"add",value:amountToIncreaseBy},{key:"ActiveEffectLike",path:"system.attributes.bonusLimitBulk",mode:"add",value:amountToIncreaseBy}];for(const rule of rules)systemData.rules.push(rule)}};__name2(_Migration689EncumberanceActiveEffects,"Migration689EncumberanceActiveEffects"),__publicField(_Migration689EncumberanceActiveEffects,"version",.689);let Migration689EncumberanceActiveEffects=_Migration689EncumberanceActiveEffects;const _Migration690InitiativeTiebreakItems=class extends MigrationBase{static{__name(this,"_Migration690InitiativeTiebreakItems")}itemSlugs=["ambush-awareness","elven-instincts","pilgrims-token"];rule={key:"ActiveEffectLike",path:"system.attributes.initiative.tiebreakPriority",mode:"override",value:0};async updateItem(itemSource){this.itemSlugs.includes(itemSource.system.slug??"")&&!itemSource.system.rules.some(rule=>rule.key==="ActiveEffectLike")&&!(itemSource.system.slug==="pilgrims-token"&&itemSource.type!=="equipment")&&itemSource.system.rules.push(this.rule)}};__name2(_Migration690InitiativeTiebreakItems,"Migration690InitiativeTiebreakItems"),__publicField(_Migration690InitiativeTiebreakItems,"version",.69);let Migration690InitiativeTiebreakItems=_Migration690InitiativeTiebreakItems;const _Migration691WeaponRangeAbilityCategoryGroup=class extends MigrationBase{static{__name(this,"_Migration691WeaponRangeAbilityCategoryGroup")}isOldGroupData(group){return isObject(group)&&(typeof group.value=="string"||group.value===null)}isOldRangeData(range){return range instanceof Object&&"value"in range&&typeof range.value=="string"}async updateItem(itemSource){if(itemSource.type==="weapon"){const systemData=itemSource.system;systemData.category=(systemData.weaponType?systemData.weaponType.value:systemData.category)||"simple",systemData.weaponType&&(systemData["-=weaponType"]=null,"game"in globalThis||delete systemData.weaponType),systemData.group=(this.isOldGroupData(systemData.group)?systemData.group.value:systemData.group)||null;const hasOldRangeData=this.isOldRangeData(systemData.range);if(systemData.range=hasOldRangeData?Number(systemData.range.value)||null:systemData.range,hasOldRangeData&&isObject(systemData.ability)&&(systemData.ability.value==="str"&&!setHasElement(MANDATORY_RANGED_GROUPS,systemData.group)&&(systemData.range=null),delete systemData.ability,systemData["-=ability"]=null),setHasElement(MANDATORY_RANGED_GROUPS,systemData.group)){const thrownIndex=systemData.traits.value.findIndex(trait=>/^thrown-\d+/.test(trait));thrownIndex!==-1&&(systemData.traits.value[thrownIndex]="thrown",systemData.reload.value="-")}systemData.baseItem==="falchion"?systemData.group="sword":systemData.baseItem==="orc-knuckle-dagger"&&(systemData.group="knife")}const{rules}=itemSource.system,strikeRules=rules.filter(rule=>/\bStrike$/.test(String(rule.key)));for(const rule of strikeRules)rule.key="Strike",rule.range=Number(rule.range)||null,delete rule.ability}};__name2(_Migration691WeaponRangeAbilityCategoryGroup,"Migration691WeaponRangeAbilityCategoryGroup"),__publicField(_Migration691WeaponRangeAbilityCategoryGroup,"version",.691);let Migration691WeaponRangeAbilityCategoryGroup=_Migration691WeaponRangeAbilityCategoryGroup;const _Migration692CraftingEntryFeatReplacement=class extends MigrationBase{static{__name(this,"_Migration692CraftingEntryFeatReplacement")}requiresFlush=!0;slugToPromise=new Map([["advanced-alchemy",fromUuid("Compendium.pf2e.classfeatures.Pe0zmIqyTBc2Td0I")],["field-discovery-bomber",fromUuid("Compendium.pf2e.classfeatures.8QAFgy9U8PxEa7Dw")],["field-discovery-chirurgeon",fromUuid("Compendium.pf2e.classfeatures.qC0Iz6SlG2i9gv6g")],["field-discovery-mutagenist",fromUuid("Compendium.pf2e.classfeatures.V4Jt7eDnJBLv5bDj")],["field-discovery-toxicologist",fromUuid("Compendium.pf2e.classfeatures.6zo2PJGYoig7nFpR")],["infused-reagents",fromUuid("Compendium.pf2e.classfeatures.wySB9VHOW1v3TX1L")],["alchemist-dedication",fromUuid("Compendium.pf2e.feats-srd.CJMkxlxHiHZQYDCz")],["deeper-dabbler",fromUuid("Compendium.pf2e.feats-srd.PTXZ2C3AV8tZf0iX")],["efficient-alchemy-paragon",fromUuid("Compendium.pf2e.feats-srd.2FBZ0apnmZ7b61ct")],["expert-alchemy",fromUuid("Compendium.pf2e.feats-srd.soHLtpMM9h3AE7PD")],["expert-fireworks-crafter",fromUuid("Compendium.pf2e.feats-srd.dDFQJem5K9Jzxgda")],["expert-herbalism",fromUuid("Compendium.pf2e.feats-srd.owJorCBZmUi5lIV0")],["expert-poisoner",fromUuid("Compendium.pf2e.feats-srd.VruIzuysxw4tY6rk")],["firework-technician-dedication",fromUuid("Compendium.pf2e.feats-srd.MVbNnjqQOK9d8Ki3")],["gadget-specialist",fromUuid("Compendium.pf2e.feats-srd.DQN7YC7s7T0pL6Aa")],["herbalist-dedication",fromUuid("Compendium.pf2e.feats-srd.5CRt5Dy9eLv5LpRF")],["master-alchemy",fromUuid("Compendium.pf2e.feats-srd.f6k9lIrIS4SfnCnG")],["munitions-crafter",fromUuid("Compendium.pf2e.feats-srd.lFVqejlf52cdYrZy")],["munitions-machinist",fromUuid("Compendium.pf2e.feats-srd.lh3STEvbGnP7jVMr")],["plentiful-snares",fromUuid("Compendium.pf2e.feats-srd.wGaxWwJhIXbMJft1")],["poisoner-dedication",fromUuid("Compendium.pf2e.feats-srd.y7DDs03GtDnmhxFp")],["snare-genius",fromUuid("Compendium.pf2e.feats-srd.8DIzXO1YpsU3DpJw")],["snare-specialist",fromUuid("Compendium.pf2e.feats-srd.0haS0qXR9xTYKoTG")],["snarecrafter-dedication",fromUuid("Compendium.pf2e.feats-srd.4MUbwilvb9dI0X59")],["talisman-dabbler-dedication",fromUuid("Compendium.pf2e.feats-srd.1t5479E6bdvFs4E7")],["ubiquitous-gadgets",fromUuid("Compendium.pf2e.feats-srd.ny0nfGTDUE4p8TtO")],["ubiquitous-snares",fromUuid("Compendium.pf2e.feats-srd.bX2WI5k0afqPpCfm")]]);replaceItem({items,current,replacement}){if(!(replacement instanceof ItemPF2e))throw ErrorPF2e("Unexpected error retrieving compendium item");const newSource=replacement.toObject();current.type==="feat"&&newSource.type==="feat"&&(newSource.system.location=current.system.location),items.splice(items.indexOf(current),1,newSource)}async updateActor(actorSource){actorSource.type==="character"&&this.slugToPromise.forEach(async(promise,slug)=>{const current=actorSource.items.find(itemSource=>itemSource.type==="feat"&&itemSource.system.slug===slug);current&&this.replaceItem({items:actorSource.items,current,replacement:await promise})})}};__name2(_Migration692CraftingEntryFeatReplacement,"Migration692CraftingEntryFeatReplacement"),__publicField(_Migration692CraftingEntryFeatReplacement,"version",.692);let Migration692CraftingEntryFeatReplacement=_Migration692CraftingEntryFeatReplacement;const _Migration693ArmorCategoryGroup=class extends MigrationBase{static{__name(this,"_Migration693ArmorCategoryGroup")}isOldGroupData(group){return group instanceof Object&&"value"in group&&(typeof group.value=="string"||group.value===null)}async updateItem(itemSource){if(itemSource.type!=="armor")return;const systemData=itemSource.system;systemData.category=(systemData.armorType?systemData.armorType.value:systemData.category)||"simple",systemData.armorType&&(systemData["-=armorType"]=null,"game"in globalThis||delete systemData.armorType),systemData.group=(this.isOldGroupData(systemData.group)?systemData.group.value:systemData.group)||null}};__name2(_Migration693ArmorCategoryGroup,"Migration693ArmorCategoryGroup"),__publicField(_Migration693ArmorCategoryGroup,"version",.693);let Migration693ArmorCategoryGroup=_Migration693ArmorCategoryGroup;const _Migration694RetireSystemTokenSettings=class extends MigrationBase{static{__name(this,"_Migration694RetireSystemTokenSettings")}async migrate(){const systemNameHover=Number(game.settings.storage.get("world").getItem("pf2e.defaultTokenSettingsName"))||CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,systemBarHover=Number(game.settings.storage.get("world").getItem("pf2e.defaultTokenSettingsBar"))||CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,coreTokenDefaults=game.settings.get("core","defaultToken");coreTokenDefaults.displayName=systemNameHover,coreTokenDefaults.displayBars=systemBarHover}};__name2(_Migration694RetireSystemTokenSettings,"Migration694RetireSystemTokenSettings"),__publicField(_Migration694RetireSystemTokenSettings,"version",.694);let Migration694RetireSystemTokenSettings=_Migration694RetireSystemTokenSettings;const _Migration695SummonToSummoned=class extends MigrationBase{static{__name(this,"_Migration695SummonToSummoned")}async updateItem(itemSource){const traits=itemSource.system.traits;if(traits?.value)if(itemSource.type==="action")traits.custom??="",traits.custom.toLowerCase()==="summon"&&(traits.custom="",traits.value=Array.from(new Set([...traits.value,"summon"])).sort());else{const index=traits.value.indexOf("summon");index!==-1&&(traits.value[index]="summoned")}}};__name2(_Migration695SummonToSummoned,"Migration695SummonToSummoned"),__publicField(_Migration695SummonToSummoned,"version",.695);let Migration695SummonToSummoned=_Migration695SummonToSummoned;const _Migration696FlatAbilityModifiers=class extends MigrationBase{static{__name(this,"_Migration696FlatAbilityModifiers")}abilityModPattern=/@abilities\.([a-z]{3})\.mod\b/;abbreviationMap=new Map(Array.from(ATTRIBUTE_ABBREVIATIONS).map(a=>[`PF2E.Ability${sluggify(a,{camel:"bactrian"})}`,a]));async updateItem(itemSource){const rules=itemSource.system.rules;for(const rule of rules)if(typeof rule.key=="string"&&rule.key.endsWith("FlatModifier")&&rule.type==="ability"&&!setHasElement(ATTRIBUTE_ABBREVIATIONS,rule.ability)){const abilityFromValue=this.abilityModPattern.exec(String(rule.value))?.[1]??null;rule.ability=abilityFromValue??this.abbreviationMap.get(String(rule.label??""))??"str",typeof rule.value=="string"&&rule.value.startsWith("@")&&rule.value.endsWith(".mod")&&delete rule.value}itemSource.system.slug==="thief-racket"&&!rules.some(rule=>rule.ability==="dex")&&rules.unshift({ability:"dex",key:"FlatModifier",predicate:{all:["weapon:melee","weapon:trait:finesse"],not:["weapon:category:unarmed"]},selector:"damage",type:"ability"})}};__name2(_Migration696FlatAbilityModifiers,"Migration696FlatAbilityModifiers"),__publicField(_Migration696FlatAbilityModifiers,"version",.696);let Migration696FlatAbilityModifiers=_Migration696FlatAbilityModifiers;const _Migration697WeaponReachTrait=class extends MigrationBase{static{__name(this,"_Migration697WeaponReachTrait")}async updateItem(itemSource){if(itemSource.type==="weapon"){const traits=itemSource.system.traits.value,numericReach=traits.find(t=>/^reach-\d+$/.test(t));numericReach&&traits.splice(traits.indexOf(numericReach),1,"reach")}}};__name2(_Migration697WeaponReachTrait,"Migration697WeaponReachTrait"),__publicField(_Migration697WeaponReachTrait,"version",.697);let Migration697WeaponReachTrait=_Migration697WeaponReachTrait;const _Migration698RemoveDerivedActorTraits=class extends MigrationBase{static{__name(this,"_Migration698RemoveDerivedActorTraits")}async updateActor(source){if(!((source.type==="character"||source.type==="npc")&&"traits"in source.system.traits&&isObject(source.system.traits.traits)&&"value"in source.system.traits.traits&&Array.isArray(source.system.traits.traits.value)))return;const traits=source.system.traits.traits.value;for(const trait of ALIGNMENT_TRAITS){const index=traits.indexOf(trait);index>=0&&traits.splice(index,1)}if(source.type==="character"){const ancestry=source.items.find(i=>i.type==="ancestry");if(!ancestry)return;for(const trait of ancestry.system.traits.value){const index=traits.indexOf(trait);index>=0&&traits.splice(index,1)}}}};__name2(_Migration698RemoveDerivedActorTraits,"Migration698RemoveDerivedActorTraits"),__publicField(_Migration698RemoveDerivedActorTraits,"version",.698);let Migration698RemoveDerivedActorTraits=_Migration698RemoveDerivedActorTraits;const _Migration699ItemDescriptionEmptyString=class extends MigrationBase{static{__name(this,"_Migration699ItemDescriptionEmptyString")}async updateItem(itemSource){itemSource.system.description.value??=""}};__name2(_Migration699ItemDescriptionEmptyString,"Migration699ItemDescriptionEmptyString"),__publicField(_Migration699ItemDescriptionEmptyString,"version",.699);let Migration699ItemDescriptionEmptyString=_Migration699ItemDescriptionEmptyString;const _Migration700SingleClassFeatures=class extends MigrationBase{static{__name(this,"_Migration700SingleClassFeatures")}constructor(){super(...arguments),__privateAdd(this,_migrateClass),__privateAdd(this,_migrateFeature),__privateAdd(this,_isClassFeature2),__publicField(this,"itemIds",{alertness:["D8CSi8c9XiRpVc5M","OZaJz4exCoz6vuuv","qJ4fwGpoNC36ZQ8I","2o1Cj7hDayDlslqY","TAIOtk5VvPZvv4nu"],"armor-expertise":["x5jaCJxsmD5sx3KB","fRifyINZF5SKDfib"],"armor-mastery":["CGB1TczFhQhdQxml","IPDwS5pTgU3Cq6Nl"],evasion:["MV6XIuAgN9uSA0Da","EZuWfYSv3ASLyKtu","DqWr3LqUpT3Xi2xq"],"expert-spellcaster":["cD3nSupdCvONuHiE","mdzk070ixIDpid7V"],"great-fortitude":["F57Na5VxfBp56kke","25GSAotUcDwInYgG"],"improved-evasion":["L5D0NwFXdLiVSnk5","6XwGONPdr9SFDtDc"],"incredible-senses":["nLwPMPLRne1HnL00","iyb5FU2BpsCCan8Q","kktZhQPJgC5F4hgU"],"iron-will":["wMyDcVNmA7xGK83S","JVCxv4HuLaaFhAf4"],juggernaut:["OMZs5y16jZRW9KQK","sHCFQZM0xHCOYOId","Ba97T4anGhizfaCt","pzTRQxuoNOeWAalC","ojB0UJWpSekQPjT7"],"lightning-reflexes":["TUOeATt52P43r5W0","rz87RgR1crWTd7j5","Xqd0vrxq2bLXxdaB","tfugXJHITCnArN1b","7PzcKaDGy6tIkQh4","EJzjY6AIsTYqW0ee"],"magical-fortitude":["70jqXP2eS4tRZ0Ok","MzyPNlxrNA5OKVd7"],"master-spellcaster":["l1InYvhnQSz6Ucxc","zu9PcxvfoZlqQVk5"],"medium-armor-expertise":["FCEp9jjxxgRJDJV3","tzUaTqB6GHAeffOl"],"medium-armor-mastery":["cGMSYAErbUG5E8X2","NcEpvnIZfKzG1Iou"],resolve:["JQAujUXjczVnYDEI","D2g6sZQAWaTccviQ","vv63fioCtOvDIdF2","9WjZSliQZJlyGvUi"],"vigilant-senses":["0npO4rPscGm0dX13","NTp146fjLreL5zsj"],"weapon-expertise":["9XLUh9iMepZesdmc","F5BHEav90oOJ2LwN","O99eXctsEjEpuBwe"],"weapon-specialization":["9EqIasqfI8YIM3Pt","WiM7X4xmpMx4s6LD","1NGTc0gqEtwaFqUK"]}),__publicField(this,"features",["Alertness","Armor Expertise","Armor Mastery","Evasion","Expert Spellcaster","Great Fortitude","Improved Evasion","Incredible Senses","Iron Will","Juggernaut","Lightning Reflexes","Magical Fortitude","Master Spellcaster","Medium Armor Expertise","Medium Armor Mastery","Resolve","Vigilant Senses","Weapon Expertise","Weapon Specialization"].map(name2=>({slug:sluggify(name2),name:name2})))}async updateItem(source){source.type==="class"?__privateMethod(this,_migrateClass,migrateClass_fn).call(this,source):source.type==="feat"&&__privateMethod(this,_migrateFeature,migrateFeature_fn).call(this,source)}};_migrateClass=new WeakSet,migrateClass_fn=__name2(function(itemSource){for(const refId in itemSource.system.items){const itemRef=itemSource.system.items[refId];itemRef.level=Number(itemRef.level)||1;for(const feature of this.features)itemSource.system.slug==="swashbuckler"&&feature.slug==="weapon-expertise"||this.itemIds[feature.slug].includes(itemRef.id??"")&&(itemRef.id=this.itemIds[feature.slug][0],itemRef.name=feature.name)}},"#migrateClass"),_migrateFeature=new WeakSet,migrateFeature_fn=__name2(function(source){if(__privateMethod(this,_isClassFeature2,isClassFeature_fn2).call(this,source))for(const feature of this.features)source.system.slug==="swashbuckler"&&feature.slug==="weapon-expertise"||source.system.slug?.startsWith(`${feature.slug}-level-`)&&(source.system.slug=feature.slug,source.name.startsWith(`${feature.name} `)&&(source.name=feature.name),source.system.traits.value=[])},"#migrateFeature"),_isClassFeature2=new WeakSet,isClassFeature_fn2=__name2(function(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"},"#isClassFeature"),__name2(_Migration700SingleClassFeatures,"Migration700SingleClassFeatures"),__publicField(_Migration700SingleClassFeatures,"version",.7);let Migration700SingleClassFeatures=_Migration700SingleClassFeatures;const _Migration701ModifierNameToSlug=class extends MigrationBase{static{__name(this,"_Migration701ModifierNameToSlug")}async updateItem(itemSource){const rules=itemSource.system.rules.filter(r=>["FlatModifier","DamageDice"].includes(String(r.key)));for(const rule of rules)rule.name&&(rule.label?rule.slug=sluggify(rule.name):rule.label=rule.name,delete rule.name),rule.label==="Rage"&&(rule.label="PF2E.TraitRage")}};__name2(_Migration701ModifierNameToSlug,"Migration701ModifierNameToSlug"),__publicField(_Migration701ModifierNameToSlug,"version",.701);let Migration701ModifierNameToSlug=_Migration701ModifierNameToSlug;const _Migration702REFormulasAtInstanceLevel=class extends MigrationBase{static{__name(this,"_Migration702REFormulasAtInstanceLevel")}raiseToInstanceLevel(value){return value.replace(/@[a-z.]+/gi,match=>["@mod","@castLevel","@heighten","@item.badge.value"].includes(match)||match.indexOf("@spell")>=0?match:match==="@details.level.value"||match==="@actor.details.level.value"?"@actor.level":match==="@item.value.value"?"@item.badge.value":match.startsWith("@abilities.")?match.replace(/\babilities\b/,"actor.abilities"):match.startsWith("@attributes.")?match.replace(/\battributes\b/,"actor.attributes"):match==="@item.level.value"?"@item.level":/^@item\.[a-z]+$/.test(match)?match:match.replace(/@item\.(?!data\b)/,"@item.system.").replace(/@(?!(?:item|actor|[A-Z]\w+))/,"@actor.system."))}async updateItem(itemSource){const rules=itemSource.system.rules;for(const rule of rules)try{if(typeof rule.value=="string")rule.value=this.raiseToInstanceLevel(rule.value);else if(isObject(rule.value)&&"brackets"in rule.value&&Array.isArray(rule.value.brackets))for(const bracket of rule.value.brackets)isObject(bracket)&&typeof bracket.value=="string"&&(bracket.value=this.raiseToInstanceLevel(bracket.value));rule.key==="Note"&&rule.text&&(rule.text=this.raiseToInstanceLevel(rule.text))}catch{continue}}};__name2(_Migration702REFormulasAtInstanceLevel,"Migration702REFormulasAtInstanceLevel"),__publicField(_Migration702REFormulasAtInstanceLevel,"version",.702);let Migration702REFormulasAtInstanceLevel=_Migration702REFormulasAtInstanceLevel;const _Migration703SpellDamageStructure=class extends MigrationBase{static{__name(this,"_Migration703SpellDamageStructure")}async updateItem(itemSource){itemSource.type==="spell"&&(itemSource.system.damage instanceof Object?itemSource.system.damage.value instanceof Object||(itemSource.system.damage.value={}):itemSource.system.damage={value:{}})}};__name2(_Migration703SpellDamageStructure,"Migration703SpellDamageStructure"),__publicField(_Migration703SpellDamageStructure,"version",.703);let Migration703SpellDamageStructure=_Migration703SpellDamageStructure;const _Migration704MartialProficiencyRE=class extends MigrationBase{static{__name(this,"_Migration704MartialProficiencyRE")}async updateItem(itemSource){const rules=itemSource.system.rules.filter(r=>r.key==="LinkedProficiency");for(const rule of rules)if(rule.key="MartialProficiency",rule.definition=rule.predicate,delete rule.predicate,typeof rule.slug=="string"&&itemSource.system.slug?.endsWith("-weapon-familiarity")&&!rule.label){const key=sluggify(rule.slug,{camel:"bactrian"});rule.label=`PF2E.SpecificRule.MartialProficiency.${key}`}if(itemSource.type==="class"&&itemSource.system.slug==="gunslinger"&&itemSource.system.rules.length===0){const gunslingerRules=[{definition:{all:["weapon:category:simple"],any:["weapon:group:firearm","weapon:tag:crossbow"]},key:"MartialProficiency",label:"PF2E.SpecificRule.MartialProficiency.SimpleFirearmsCrossbows",slug:"simple-firearms-crossbows",value:2},{definition:{all:["weapon:category:martial"],any:["weapon:group:firearm","weapon:tag:crossbow"]},key:"MartialProficiency",label:"PF2E.SpecificRule.MartialProficiency.MartialFirearmsCrossbows",slug:"martial-firearms-crossbows",value:2},{definition:{all:["weapon:category:advanced"],any:["weapon:group:firearm","weapon:tag:crossbow"]},key:"MartialProficiency",label:"PF2E.SpecificRule.MartialProficiency.AdvancedFirearmsCrossbows",slug:"advanced-firearms-crossbows",value:1}];itemSource.system.rules=gunslingerRules}}};__name2(_Migration704MartialProficiencyRE,"Migration704MartialProficiencyRE"),__publicField(_Migration704MartialProficiencyRE,"version",.704);let Migration704MartialProficiencyRE=_Migration704MartialProficiencyRE;const _Migration705GunslingerCatchUp=class extends MigrationBase{static{__name(this,"_Migration705GunslingerCatchUp")}constructor(){super(...arguments),__privateAdd(this,_isClassFeature3)}async updateItem(source){if(__privateMethod(this,_isClassFeature3,isClassFeature_fn3).call(this,source))switch(source.system.slug){case"singular-expertise":{const rules=[{key:"FlatModifier",selector:"firearm-weapon-group-damage",type:"circumstance",value:1},{key:"FlatModifier",predicate:{all:["weapon:tag:crossbow"]},selector:"bow-weapon-group-damage",type:"circumstance",value:1}];source.system.rules=rules;break}case"gunslinger-weapon-mastery":{const rules=[{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.unarmed.rank",value:2},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.simple.rank",value:2},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.martial.rank",value:2},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.advanced-firearms-crossbows.rank",value:2},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.simple-firearms-crossbows.rank",value:3},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.martial-firearms-crossbows.rank",value:3}];source.system.rules=rules;break}case"gunslinging-legend":{const rules=[{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.unarmed.rank",value:3},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.simple.rank",value:3},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.martial.rank",value:3},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.advanced-firearms-crossbows.rank",value:3},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.simple-firearms-crossbows.rank",value:4},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.martial-firearms-crossbows.rank",value:4}];source.system.rules=rules;break}}}};_isClassFeature3=new WeakSet,isClassFeature_fn3=__name2(function(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"},"#isClassFeature"),__name2(_Migration705GunslingerCatchUp,"Migration705GunslingerCatchUp"),__publicField(_Migration705GunslingerCatchUp,"version",.705);let Migration705GunslingerCatchUp=_Migration705GunslingerCatchUp;const _Migration706FormulasAtInstanceLevelEverythingElse=class extends Migration702REFormulasAtInstanceLevel{static{__name(this,"_Migration706FormulasAtInstanceLevelEverythingElse")}async updateItem(itemSource){if(itemSource.system.description.value&&(itemSource.system.description.value=this.replaceInlineRolls(itemSource.system.description.value)),itemSource.type==="spell")for(const value of Object.values(itemSource.system.damage.value))value.value=this.raiseToInstanceLevel(value.value);if(itemSource.type==="melee")for(const value of Object.values(itemSource.system.damageRolls))value.damage=this.raiseToInstanceLevel(value.damage)}replaceInlineRolls(value){return value.replace(/\[\[(.*)\]\]/g,match=>this.raiseToInstanceLevel(match))}};__name2(_Migration706FormulasAtInstanceLevelEverythingElse,"Migration706FormulasAtInstanceLevelEverythingElse"),__publicField(_Migration706FormulasAtInstanceLevelEverythingElse,"version",.706);let Migration706FormulasAtInstanceLevelEverythingElse=_Migration706FormulasAtInstanceLevelEverythingElse;const _Migration707BracketedFormulasAtInstanceLevel=class extends Migration702REFormulasAtInstanceLevel{static{__name(this,"_Migration707BracketedFormulasAtInstanceLevel")}};__name2(_Migration707BracketedFormulasAtInstanceLevel,"Migration707BracketedFormulasAtInstanceLevel"),__publicField(_Migration707BracketedFormulasAtInstanceLevel,"version",.707);let Migration707BracketedFormulasAtInstanceLevel=_Migration707BracketedFormulasAtInstanceLevel;const _Migration708SpecificRuleLabel=class extends MigrationBase{static{__name(this,"_Migration708SpecificRuleLabel")}async updateItem(itemSource){for(const rule of itemSource.system.rules)rule.label&&(rule.label=String(rule.label).replace(/\bSpecificRules\b/,"SpecificRule"))}};__name2(_Migration708SpecificRuleLabel,"Migration708SpecificRuleLabel"),__publicField(_Migration708SpecificRuleLabel,"version",.708);let Migration708SpecificRuleLabel=_Migration708SpecificRuleLabel;const _Migration709REFormulasAtInstanceLevelRedux=class extends Migration702REFormulasAtInstanceLevel{static{__name(this,"_Migration709REFormulasAtInstanceLevelRedux")}walkObject(obj){if(Array.isArray(obj))for(let i=0;ir.key==="BattleForm");for(const rule of rules)this.walkObject(rule);itemSource.type==="spell"&&itemSource.system.slug==="wild-shape"&&(itemSource.system.rules=[])}};__name2(_Migration709REFormulasAtInstanceLevelRedux,"Migration709REFormulasAtInstanceLevelRedux"),__publicField(_Migration709REFormulasAtInstanceLevelRedux,"version",.709);let Migration709REFormulasAtInstanceLevelRedux=_Migration709REFormulasAtInstanceLevelRedux;const _Migration710RarityToString=class extends MigrationBase{static{__name(this,"_Migration710RarityToString")}updateTraits(traits){typeof traits?.rarity=="object"&&traits.rarity!==null&&(traits.rarity=traits.rarity.value)}async updateActor(actorSource){"traits"in actorSource.system&&this.updateTraits(actorSource.system.traits??null)}async updateItem(itemSource){"traits"in itemSource.system&&this.updateTraits(itemSource.system.traits??null)}};__name2(_Migration710RarityToString,"Migration710RarityToString"),__publicField(_Migration710RarityToString,"version",.71);let Migration710RarityToString=_Migration710RarityToString;const toDelete=["featType","actionCategory","actions","actionType","level","location"],_Migration711HeritageItems=class extends MigrationBase{static{__name(this,"_Migration711HeritageItems")}constructor(){super(...arguments),__privateAdd(this,_isHeritageFeature),__privateAdd(this,_heritageFromFeat),__privateAdd(this,_officialAncestries,{tengu:{name:"Tengu",uuid:"Compendium.pf2e.ancestries.Item.18xDKYPDBLEv2myX"},kitsune:{name:"Kitsune",uuid:"Compendium.pf2e.ancestries.Item.4BL5wf1VF9feC2rY"},poppet:{name:"Poppet",uuid:"Compendium.pf2e.ancestries.Item.6F2fSFC1Eo1JdpY4"},kobold:{name:"Kobold",uuid:"Compendium.pf2e.ancestries.Item.7oQxL6wgsokD3QXG"},catfolk:{name:"Catfolk",uuid:"Compendium.pf2e.ancestries.Item.972EkpJOPv9KkQIW"},dwarf:{name:"Dwarf",uuid:"Compendium.pf2e.ancestries.Item.BYj5ZvlXZdpaEgA6"},gnome:{name:"Gnome",uuid:"Compendium.pf2e.ancestries.Item.CYlfsYLJcBOgqKtD"},fleshwarp:{name:"Fleshwarp",uuid:"Compendium.pf2e.ancestries.Item.FXlXmNBFiiz9oasi"},strix:{name:"Strix",uuid:"Compendium.pf2e.ancestries.Item.GXcC6oVa5quzgNHD"},android:{name:"Android",uuid:"Compendium.pf2e.ancestries.Item.GfLwE884NoRC7cRi"},halfling:{name:"Halfling",uuid:"Compendium.pf2e.ancestries.Item.GgZAHbrjnzWOZy2v"},lizardfolk:{name:"Lizardfolk",uuid:"Compendium.pf2e.ancestries.Item.HWEgF7Gmoq55VhTL"},human:{name:"Human",uuid:"Compendium.pf2e.ancestries.Item.IiG7DgeLWYrSNXuX"},ratfolk:{name:"Ratfolk",uuid:"Compendium.pf2e.ancestries.Item.P6PcVnCkh4XMdefw"},elf:{name:"Elf",uuid:"Compendium.pf2e.ancestries.Item.PgKmsA2aKdbLU6O0"},anadi:{name:"Anadi",uuid:"Compendium.pf2e.ancestries.Item.TQEqWqc7BYiadUdY"},sprite:{name:"Sprite",uuid:"Compendium.pf2e.ancestries.Item.TRqoeYfGAFjQbviF"},goloma:{name:"Goloma",uuid:"Compendium.pf2e.ancestries.Item.c4secsSNG2AO7I5i"},leshy:{name:"Leshy",uuid:"Compendium.pf2e.ancestries.Item.cdhgByGG1WtuaK73"},fetchling:{name:"Fetchling",uuid:"Compendium.pf2e.ancestries.Item.hIA3qiUsxvLZXrFP"},grippli:{name:"Grippli",uuid:"Compendium.pf2e.ancestries.Item.hXM5jXezIki1cMI2"},automaton:{name:"Automaton",uuid:"Compendium.pf2e.ancestries.Item.kYsBAJ103T44agJF"},orc:{name:"Orc",uuid:"Compendium.pf2e.ancestries.Item.lSGWXjcbOa6O5fTx"},hobgoblin:{name:"Hobgoblin",uuid:"Compendium.pf2e.ancestries.Item.piNLXUrm9iaGqD2i"},shoony:{name:"Shoony",uuid:"Compendium.pf2e.ancestries.Item.q6rsqYARyOGXZA8F"},goblin:{name:"Goblin",uuid:"Compendium.pf2e.ancestries.Item.sQfjTMDaZbT9DThq"},conrasu:{name:"Conrasu",uuid:"Compendium.pf2e.ancestries.Item.tZn4qIHCUA6wCdnI"},gnoll:{name:"Gnoll",uuid:"Compendium.pf2e.ancestries.Item.vxbQ1Yw4qwgjTzqo"},shisk:{name:"Shisk",uuid:"Compendium.pf2e.ancestries.Item.x1YinOddgUxwOLqP"},azarketi:{name:"Azarketi",uuid:"Compendium.pf2e.ancestries.Item.yFoojz6q3ZjvceFw"}}),__privateAdd(this,_heritagesWithoutAncestryInName,{"half-elf":"human","half-orc":"human","skilled-heritage":"human","versatile-heritage":"human",draxie:"sprite",grig:"sprite",melixie:"sprite",nyktera:"sprite",pixie:"sprite","deep-rat":"ratfolk","desert-rat":"ratfolk","longsnout-rat":"ratfolk","sewer-rat":"ratfolk","shadow-rat":"ratfolk","snow-rat":"ratfolk","tunnel-rat":"ratfolk","rite-of-invocation":"conrasu","rite-of-knowing":"conrasu","rite-of-light":"conrasu","rite-of-passage":"conrasu","rite-of-reinforcement":"conrasu"}),__privateAdd(this,_ancestrySlugs,Object.keys(__privateGet(this,_officialAncestries)))}async updateActor(actorSource){const heritageFeatures=actorSource.items.filter(i=>__privateMethod(this,_isHeritageFeature,isHeritageFeature_fn).call(this,i)),firstHeritageFeature=heritageFeatures[0];if(!actorSource.items.some(i=>i.type==="heritage")&&firstHeritageFeature&&actorSource.type==="character"){const heritageSource=__privateMethod(this,_heritageFromFeat,heritageFromFeat_fn).call(this,firstHeritageFeature);actorSource.items.push(heritageSource);const details=actorSource.system.details;details.heritage&&(details["-=heritage"]=null,"game"in globalThis||delete details.heritage)}for(const feature of heritageFeatures)actorSource.items.splice(actorSource.items.indexOf(feature),1)}async updateItem(itemSource,actorSource){if(actorSource||!__privateMethod(this,_isHeritageFeature,isHeritageFeature_fn).call(this,itemSource))return;const newSource=itemSource;newSource.type="heritage",itemSource.img==="systems/pf2e/icons/default-icons/feat.svg"&&(itemSource.img="systems/pf2e/icons/default-icons/heritage.svg");const newSystemData=__privateMethod(this,_heritageFromFeat,heritageFromFeat_fn).call(this,itemSource).system,deletionProperties=toDelete.map(k=>`-=${k}`);for(const property of deletionProperties)newSystemData[property]=null;if(!("game"in globalThis))for(const property of toDelete)delete newSystemData[property];newSource.system=newSystemData}};_isHeritageFeature=new WeakSet,isHeritageFeature_fn=__name2(function(feature){return feature.type==="feat"&&feature.system.featType?.value==="heritage"},"#isHeritageFeature"),_officialAncestries=new WeakMap,_heritagesWithoutAncestryInName=new WeakMap,_ancestrySlugs=new WeakMap,_heritageFromFeat=new WeakSet,heritageFromFeat_fn=__name2(function(feature){const featureSlug=feature.system.slug??"",ancestrySlug=__privateGet(this,_heritagesWithoutAncestryInName)[featureSlug]??__privateGet(this,_ancestrySlugs).find(s=>featureSlug.includes(s)),ancestryReference=__privateGet(this,_officialAncestries)[ancestrySlug??""]??null,traits=feature.system.traits,{flags}=feature;return flags.core?.sourceId&&(flags.core.sourceId=flags.core.sourceId.replace("ancestryfeatures","heritages")),{_id:randomID(),type:"heritage",img:feature.img.endsWith("/feat.svg")?"systems/pf2e/icons/default-icons/heritage.svg":feature.img,name:feature.name,effects:[],folder:feature.folder,flags:feature.flags,sort:feature.sort,ownership:feature.ownership,system:{description:feature.system.description,rules:feature.system.rules,schema:feature.system.schema,_migration:{version:null,previous:null},slug:feature.system.slug,ancestry:ancestryReference,traits:{value:traits.value.filter(t=>(t in creatureTraits||t.startsWith("hb_"))&&!(t in __privateGet(this,_officialAncestries))),rarity:traits.rarity,otherTags:[]}}}},"#heritageFromFeat"),__name2(_Migration711HeritageItems,"Migration711HeritageItems"),__publicField(_Migration711HeritageItems,"version",.711);let Migration711HeritageItems=_Migration711HeritageItems;const _Migration712ActorShieldStructure=class extends MigrationBase{static{__name(this,"_Migration712ActorShieldStructure")}async updateActor(source){if(source.type==="character"||source.type==="npc"){const attributes=source.system.attributes;attributes.shield&&(attributes["-=shield"]=null,"game"in globalThis?attributes.shield={}:delete attributes.shield)}}};__name2(_Migration712ActorShieldStructure,"Migration712ActorShieldStructure"),__publicField(_Migration712ActorShieldStructure,"version",.712);let Migration712ActorShieldStructure=_Migration712ActorShieldStructure;const _Migration713FistToStrikeRE=class extends MigrationBase{static{__name(this,"_Migration713FistToStrikeRE")}async updateItem(itemSource){const fistFeatures=["powerful-fist","martial-artist-dedication"];if(!(itemSource.type==="feat"&&fistFeatures.includes(itemSource.system.slug))||itemSource.system.rules.some(rule=>rule.key==="Strike"))return;const strike={key:"Strike",img:"systems/pf2e/icons/features/classes/powerful-fist.webp",slug:"fist",category:"unarmed",damage:{base:{damageType:"bludgeoning",dice:1,die:"d6"}},group:"brawling",label:"PF2E.Strike.Fist.Label",range:null,traits:["agile","finesse","nonlethal","unarmed"]};itemSource.system.rules=[strike]}};__name2(_Migration713FistToStrikeRE,"Migration713FistToStrikeRE"),__publicField(_Migration713FistToStrikeRE,"version",.713);let Migration713FistToStrikeRE=_Migration713FistToStrikeRE;const _Migration714RangeIncrementREs=class extends MigrationBase{static{__name(this,"_Migration714RangeIncrementREs")}farLobber={definition:{all:["weapon:base:alchemical-bomb"]},key:"AdjustStrike",mode:"upgrade",property:"range-increment",value:30};farShot={definition:{all:["weapon:ranged"]},key:"AdjustStrike",mode:"multiply",property:"range-increment",value:2};farThrow={key:"AdjustModifier",mode:"add",predicate:{all:["weapon:trait:thrown"]},selectors:["ranged-attack-roll"],slug:"range-penalty",value:1};huntPrey={key:"RollOption",domain:"ranged-attack-roll",option:"ignore-range-penalty:2",predicate:{all:["hunted-prey"]}};legendaryShot={key:"RollOption",domain:"ranged-attack-roll",option:"ignore-range-penalty:5"};masterfulHunter=(()=>({key:"RollOption",domain:"ranged-attack-roll",option:"ignore-range-penalty:3",predicate:{all:["hunted-prey",{gte:["weapon:proficiency:rank",3]}]}}))();shootistsEdge=(()=>[{key:"ActiveEffectLike",mode:"upgrade",path:"system.attributes.classDC.rank",value:3},{key:"RollOption",domain:"ranged-attack-roll",option:"ignore-range-penalty:3",phase:"beforeRoll",predicate:{all:[{gte:["weapon:proficiency:rank",3]}]}}])();triangulate=[{default:!0,key:"ToggleProperty",label:"PF2E.SpecificRule.ToggleProperty.Triangulate",property:"flags.pf2e.rollOptions.all.triangulate"},{domain:"ranged-attack-roll",key:"RollOption",option:"ignore-range-penalty:2",predicate:{all:["triangulate"]}},{key:"AdjustModifier",mode:"add",predicate:{all:["triangulate"]},selectors:["ranged-attack-roll"],slug:"range-penalty",value:1}];uncannyBombs={definition:{all:["weapon:base:alchemical-bomb"]},key:"AdjustStrike",mode:"upgrade",property:"range-increment",value:60};unerringShot=(()=>({key:"RollOption",option:"ignore-range-penalty",phase:"beforeRoll",predicate:{all:[{gte:["weapon:proficiency:rank",3]}]}}))();async updateItem(source){const{rules}=source.system;if(source.type==="feat")switch(source.system.slug){case"far-lobber":{source.system.rules=[this.farLobber];return}case"far-shot":{source.system.rules=[this.farShot];return}case"far-throw":{source.system.rules=[this.farThrow];return}case"hunt-prey":{!rules.some(r=>r.key==="RollOption"&&r.option===this.huntPrey.option)&&rules.push(this.huntPrey);return}case"legendary-shot":{source.system.rules=[this.legendaryShot];return}case"masterful-hunter":{!rules.some(r=>r.key==="RollOption"&&r.option===this.masterfulHunter.option)&&rules.push(this.masterfulHunter);return}case"shootists-edge":{source.system.rules=this.shootistsEdge;return}case"triangulate":{source.system.rules=this.triangulate;return}case"uncanny-bombs":{source.system.rules=[this.uncannyBombs];return}case"unerring-shot":{source.system.rules=[this.unerringShot];return}}}};__name2(_Migration714RangeIncrementREs,"Migration714RangeIncrementREs"),__publicField(_Migration714RangeIncrementREs,"version",.714);let Migration714RangeIncrementREs=_Migration714RangeIncrementREs;const _Migration715DangerousSorcery=class extends MigrationBase{static{__name(this,"_Migration715DangerousSorcery")}dangerousSorcery={key:"FlatModifier",phase:"afterDerived",predicate:{all:["item:spell-slot","item:duration:0","damaging-effect"]},selector:"spell-damage",value:"@spell.level"};async updateItem(source){if(source.type!=="feat")return;(source.system.slug??sluggify(source.name))==="dangerous-sorcery"&&!source.system.rules.length&&(source.system.rules=[this.dangerousSorcery])}};__name2(_Migration715DangerousSorcery,"Migration715DangerousSorcery"),__publicField(_Migration715DangerousSorcery,"version",.715);let Migration715DangerousSorcery=_Migration715DangerousSorcery;const _Migration716StrikeDamageSelector=class extends MigrationBase{static{__name(this,"_Migration716StrikeDamageSelector")}itemsToSkip=new Set(["effect-fanatical-frenzy","effect-heroic-recovery","effect-lantern-of-hope","effect-lantern-of-hope-gestalt","spell-effect-inspire-courage","spell-effect-inspire-heroics-courage-2","spell-effect-inspire-heroics-courage-3","spell-effect-stoke-the-heart"]);async updateItem(source){if(this.itemsToSkip.has(source.system.slug??""))return;const{rules}=source.system;for(const rule of rules)isObject(rule)&&["damage","mundane-damage"].includes(String(rule.selector??""))&&(rule.selector="strike-damage")}};__name2(_Migration716StrikeDamageSelector,"Migration716StrikeDamageSelector"),__publicField(_Migration716StrikeDamageSelector,"version",.716);let Migration716StrikeDamageSelector=_Migration716StrikeDamageSelector;const _Migration717TakeFeatLimits=class extends MigrationBase{static{__name(this,"_Migration717TakeFeatLimits")}levelOneOnly=new Set(["celestial-eyes","chance-death","deliberate-death","elemental-eyes","eyes-of-the-night","fiendish-eyes","gravesight","willing-death"]);maxTakeable={"additional-lore":1/0,"advanced-domain":1/0,"advanced-general-training":1/0,"animal-senses":1/0,"animal-senses-darkvision":1/0,"animal-senses-low-light-vision":1/0,"animal-senses-scent-imprecise":1/0,"armor-proficiency":3,assurance:1/0,"automatic-knowledge":1/0,"blessing-of-the-sun-gods":1/0,"consult-the-spirits":1/0,"domain-initiate":1/0,"general-training":1/0,"greater-animal-senses":1/0,"greater-sun-blessing":1/0,"hellknight-order-cross-training":1/0,"living-weapon":1/0,"magic-arrow":1/0,"modular-dynamo":1/0,multilingual:1/0,"settlement-scholastics":1/0,"skill-training":1/0,"terrain-stalker":1/0};async updateItem(source){if(source.type!=="feat")return;const slug=source.system.slug??"";source.system.traits.value.includes("lineage")||this.levelOneOnly.has(slug)?source.system.onlyLevel1=!0:"game"in globalThis&&(source.system.onlyLevel1=!1),!source.system.onlyLevel1&&slug in this.maxTakeable?source.system.maxTakable=this.maxTakeable[slug]:"game"in globalThis&&(source.system.maxTakable=1)}};__name2(_Migration717TakeFeatLimits,"Migration717TakeFeatLimits"),__publicField(_Migration717TakeFeatLimits,"version",.717);let Migration717TakeFeatLimits=_Migration717TakeFeatLimits;function isEquipped(usage,equipped){return equipped.carryType==="dropped"?!1:usage.type==="carried"?!0:usage.type!==equipped.carryType||usage.type==="worn"&&usage.where&&!equipped.inSlot?!1:usage.type==="held"?(equipped.handsHeld??0)>=(usage.hands??1):!0}__name(isEquipped,"isEquipped"),__name2(isEquipped,"isEquipped");function getUsageDetails(usage){switch(usage){case"carried":case"":return{value:"carried",type:"carried"};case"held-in-one-hand":case"held-in-one-plus-hands":return{value:usage,type:"held",hands:1};case"held-in-two-hands":return{value:usage,type:"held",hands:2};case"worn":return{value:usage,type:"worn"};case"wornarmor":case"wornamulet":case"wornanklets":case"wornarmbands":case"wornbackpack":case"wornbarding":case"wornbelt":case"wornbeltpouch":case"wornbracers":case"wornbracelet":case"worncloak":case"worncirclet":case"wornclothing":case"worncollar":case"worncrown":case"wornepaulet":case"worneyepiece":case"wornfootwear":case"worngarment":case"worngloves":case"wornheadwear":case"wornmask":case"wornnecklace":case"wornonbelt":case"wornring":case"wornshoes":case"wornhorseshoes":case"wornsaddle":case"wornwrist":return{value:usage,type:"worn",where:usage.substring(4)}}return{value:usage,type:"worn"}}__name(getUsageDetails,"getUsageDetails"),__name2(getUsageDetails,"getUsageDetails");const _Migration718CarryType=class extends MigrationBase{static{__name(this,"_Migration718CarryType")}async updateItem(itemData,actor){if(!isPhysicalData(itemData))return;const systemData=itemData.system;if(systemData.usage instanceof Object||(systemData.usage={value:"held-in-one-hand"}),systemData.usage.value==="worn-gloves")systemData.usage.value="worngloves";else if(itemData.type==="armor"){const{category}=itemData.system;systemData.usage.value=category==="shield"?"held-in-one-hand":"wornarmor"}else itemData.type==="equipment"&&systemData.slug?.startsWith("clothing-")&&(systemData.usage.value="worn");if("game"in globalThis||actor)systemData.equipped??={carryType:"worn"},systemData.equipped.carryType??="worn";else{delete systemData.equipped;return}const equipped=systemData.equipped;if(!("value"in equipped))return;if(!(actor&&["character","npc"].includes(actor.type??""))){equipped["-=value"]=null,delete equipped.value;return}const containerId=itemData.system.containerId??{value:null};if(containerId instanceof Object&&containerId.value){const inStowingContainer=actor.items.some(i=>i.type==="backpack"&&i.system.stowing&&i._id===containerId.value);if(!inStowingContainer)containerId.value=null;else if(inStowingContainer){equipped.carryType="stowed";return}}equipped.carryType="worn";const usage=getUsageDetails(systemData.usage.value);usage.type==="worn"?equipped.inSlot=!!equipped.value:usage.type==="held"&&(equipped.value&&(equipped.carryType="held"),equipped.handsHeld=equipped.value?usage.hands??1:0),equipped["-=value"]=null,delete equipped.value}};__name2(_Migration718CarryType,"Migration718CarryType"),__publicField(_Migration718CarryType,"version",.718);let Migration718CarryType=_Migration718CarryType;const _Migration719ShrugFlanking=class extends MigrationBase{static{__name(this,"_Migration719ShrugFlanking")}async updateItem(source,actorSource){const slug=source.system.slug??"";switch(source.type){case"action":{if(slug==="all-around-vision")source.system.rules=[this.allAroundVision];else if(actorSource?.type==="npc"&&source.name==="Deny Advantage"){const npcId=actorSource.flags.core?.sourceId?.replace(/^Compendium\.[^.]+\./,"")??actorSource._id;if(this.needsDenyAdvantage(source.system.rules)){const rule=this.npcDenyAvantage(npcId);source.system.rules.push(rule)}}return}case"effect":{slug==="stance-wolf-stance"&&(source.system.rules=this.wolfStanceRules);return}case"feat":{source.system.slug=source.system.slug?.replace(/^deny-advantage-level-\d$/,"deny-advantage")??null;const featSlug=source.system.slug??"";if(["constant-gaze","deny-advantage"].includes(featSlug)&&this.needsDenyAdvantage(source.system.rules))source.system.rules.push(this.denyAdvantage);else if(featSlug==="gang-up")source.system.rules=[this.gangUp];else if(featSlug.startsWith("side-by-side")){const sideBySide=this.gangUp;sideBySide.value="animal-companion",source.system.rules=[sideBySide]}else if(["pack-tactics","squad-tactics"].includes(featSlug)){const tactics=this.gangUp;tactics.value=2,source.system.rules=[tactics]}}}}get allAroundVision(){return{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.flankable",value:!1}}get denyAdvantage(){return{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.flatFootable",value:"@actor.level"}}get gangUp(){return{key:"ActiveEffectLike",mode:"add",path:"system.attributes.flanking.canGangUp",value:1}}npcVariants=new Map([["YsBSkW3aFwU1bl3w",13],["0Kb4z4h8KVqfrIju",8],["B09JfuBZHjcRXztU",4],["aaDiR0EIWRQx8wdy",3],["x4m5ks6Rd8fYzXPm",4],["qKHkamxIPbqxEiwp",6],["lCvJquCqvZJVnafy",8],["vkLhqX5oR1t89puZ",7],["aIT5S2fKgMZ6pVP2",11],["l6EuZR6zCdqyCywW",6],["QKkvnlqrhgLHuP1t",10],["ZY3q7AV1qbwWwNl2",8],["6pPolNZycfDiOl2I",8],["cQMM2Ld0IBM9GcDo",11],["VkG5yl9xcmziwpQD",4],["JrowrtDilEG8dN2s",11],["1lkay2gwgEquq0NF",6],["EMl8hARVJk8SNVyW",4],["j31HXlZiUqQrAHSB",12],["pjnTEh0NVd1DB6jI",4]]);get wolfStanceRules(){return[{category:"unarmed",damage:{base:{damageType:"piercing",dice:1,die:"d8"}},group:"brawling",key:"Strike",label:"PF2E.SpecificRule.Stance.Attack.WolfJaws",range:null,slug:"wolf-jaws",traits:["agile","backstabber","finesse","unarmed","nonlethal"]},{definition:{all:["weapon:wolf-jaws"]},key:"AdjustStrike",mode:"add",predicate:{all:["self:flanking"]},property:"traits",value:"trip"}]}npcDenyAvantage(npcId=""){const{denyAdvantage}=this;return denyAdvantage.value=this.npcVariants.get(npcId)??"@actor.level",denyAdvantage}needsDenyAdvantage(rules){return!rules.some(r=>r.key==="ActiveEffectLike"&&r.path==="system.attributes.flanking.flatFootable")}};__name2(_Migration719ShrugFlanking,"Migration719ShrugFlanking"),__publicField(_Migration719ShrugFlanking,"version",.719);let Migration719ShrugFlanking=_Migration719ShrugFlanking;const _Migration720UpdateSpellDescriptions=class extends MigrationBase{static{__name(this,"_Migration720UpdateSpellDescriptions")}spellUUIDs=new Set(["Compendium.pf2e.spells-srd.GoKkejPj5yWJPIPK","Compendium.pf2e.spells-srd.1b55SgYTV65JvmQd","Compendium.pf2e.spells-srd.b515AZlB0sridKSq","Compendium.pf2e.spells-srd.NBSBFHxBm88qxQUy","Compendium.pf2e.spells-srd.9TauMFkIsmvKJNzZ","Compendium.pf2e.spells-srd.LoBjvguamA12iyW0","Compendium.pf2e.spells-srd.IWUe32Y5k2QFd7YQ","Compendium.pf2e.spells-srd.WBmvzNDfpwka3qT4"]);spells=UUIDUtils.fromUUIDs([...this.spellUUIDs]);async updateItem(source){if(!(source.type==="spell"&&setHasElement(this.spellUUIDs,source.flags.core?.sourceId)))return;const spell=(await this.spells).find(s=>s instanceof SpellPF2e&&s.slug===source.system.slug);spell&&(source.system.description.value=spell.description)}};__name2(_Migration720UpdateSpellDescriptions,"Migration720UpdateSpellDescriptions"),__publicField(_Migration720UpdateSpellDescriptions,"version",.72);let Migration720UpdateSpellDescriptions=_Migration720UpdateSpellDescriptions;const _Migration721SetReloadValues=class extends MigrationBase{static{__name(this,"_Migration721SetReloadValues")}toUpdate=new Set(["air-repeater","composite-longbow","composite-shortbow","godsbreath-bow","hunters-bow","long-air-repeater","longbow","oathbow","repeating-crossbow","repeating-hand-crossbow","shortbow","singing-shortbow-greater","singing-shortbow","sky-piercing-bow"]);async updateItem(source){source.type==="weapon"&&setHasElement(this.toUpdate,source.system.slug)&&(source.system.reload.value="0")}};__name2(_Migration721SetReloadValues,"Migration721SetReloadValues"),__publicField(_Migration721SetReloadValues,"version",.721);let Migration721SetReloadValues=_Migration721SetReloadValues;const _Migration722CraftingSystemData=class extends MigrationBase{static{__name(this,"_Migration722CraftingSystemData")}async updateActor(source){if(source.type!=="character")return;if(!isObject(source.system.crafting)){const filledCrafting={entries:{},formulas:[]};source.system.crafting=filledCrafting}const crafting=source.system.crafting??{};(!isObject(crafting.entries)||Array.isArray(crafting.entries))&&(crafting.entries={}),Array.isArray(crafting.formulas)||(crafting.formulas=[])}};__name2(_Migration722CraftingSystemData,"Migration722CraftingSystemData"),__publicField(_Migration722CraftingSystemData,"version",.722);let Migration722CraftingSystemData=_Migration722CraftingSystemData;const _Migration723CumulativeItemBonuses=class extends MigrationBase{static{__name(this,"_Migration723CumulativeItemBonuses")}stanceFeats=(async()=>(await UUIDUtils.fromUUIDs(["Compendium.pf2e.feats-srd.ZPclfDmiHzEqblry","Compendium.pf2e.feats-srd.ZL5UU9quCTvcWzfY","Compendium.pf2e.feats-srd.n2hawNmzW7DBn1Lm","Compendium.pf2e.feats-srd.hO4sKslTrSQMLbGx"])).filter(d=>d instanceof FeatPF2e&&!!d.slug).reduce((record,f)=>({...record,[f.slug]:f}),{}))();mountainPattern=/^mountain-(?:stance|stronghold|quake)$/;async updateActor(source){if(source.type!=="character")return;const effects=source.items.filter(i=>i.type==="effect");for(const effect of effects)effect.system.slug?.startsWith("stance-mountain")&&source.items.findSplice(i=>i===effect)}async updateItem(source){if(source.system.slug)switch(source.type){case"feat":{if(source.system.slug==="animal-skin"){const feat=(await this.stanceFeats)[source.system.slug];feat&&(source.system.rules=feat.toObject().system.rules)}else if(this.mountainPattern.test(source.system.slug)){const feat=(await this.stanceFeats)[source.system.slug];feat&&(source.system.description.value=feat.description)}return}case"equipment":{if(!source.system.slug.startsWith("bracers-of-armor-"))return;for(const rule of source.system.rules)rule.key==="FlatModifier"&&(rule.slug="bracers-of-armor");return}case"effect":{if(source.system.slug!=="spell-effect-mage-armor")return;for(const rule of source.system.rules)rule.key==="FlatModifier"&&(rule.slug="mage-armor")}}}async updateMacro(source){source.type==="script"&&source.command.includes("Stance: Mountain Stance")&&(source.command=String.raw`const actors = canvas.tokens.controlled.flatMap((token) => token.actor ?? []); if (actors.length === 0 && game.user.character) actors.push(game.user.character); if (actors.length === 0) { const message = game.i18n.localize("PF2E.ErrorMessage.NoTokenSelected"); @@ -272,7 +274,7 @@ for (const actor of actors) { } else { await actor.createEmbeddedDocuments("Item", [source]); } -}`)}};__name2(_Migration723CumulativeItemBonuses,"Migration723CumulativeItemBonuses"),__publicField(_Migration723CumulativeItemBonuses,"version",.723);let Migration723CumulativeItemBonuses=_Migration723CumulativeItemBonuses;const _Migration724CraftingMaxItemLevel=class extends MigrationBase{static{__name(this,"_Migration724CraftingMaxItemLevel")}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=mergeObject({all:[]},isObject(rule.predicate)?rule.predicate:{}),slug=sluggify(selector);predicate.all=Array.from(new Set([...predicate.all,`crafting:entry:${slug}`]))}}}};__name2(_Migration724CraftingMaxItemLevel,"Migration724CraftingMaxItemLevel"),__publicField(_Migration724CraftingMaxItemLevel,"version",.724);let Migration724CraftingMaxItemLevel=_Migration724CraftingMaxItemLevel;const _Migration725QuickClimbREs=class extends MigrationBase{static{__name(this,"_Migration725QuickClimbREs")}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:'

{item|name} You move 5 more feet on a success, and 10 more feet on a critical success.

'}];async updateItem(source){source.type==="feat"&&source.system.slug==="quick-climb"&&(source.system.rules=deepClone(this.quickClimb))}};__name2(_Migration725QuickClimbREs,"Migration725QuickClimbREs"),__publicField(_Migration725QuickClimbREs,"version",.725);let Migration725QuickClimbREs=_Migration725QuickClimbREs;const _Migration726JournalSetting=class extends MigrationBase{static{__name(this,"_Migration726JournalSetting")}async migrate(){const sheetClasses=game.settings.get("core","sheetClasses");if(isObject(sheetClasses)&&sheetClasses.JournalEntry?.base)return;const theme=game.settings.storage.get("world").getItem("pf2e.journalEntryTheme");if(!theme)return;const base=theme==="pf2eTheme"?"pf2e.JournalSheetStyledPF2e":"pf2e.JournalSheetPF2e";DocumentSheetConfig.updateDefaultSheets({JournalEntry:{base}})}};__name2(_Migration726JournalSetting,"Migration726JournalSetting"),__publicField(_Migration726JournalSetting,"version",.726);let Migration726JournalSetting=_Migration726JournalSetting;const _Migration727TrimSelfRollOptions=class extends MigrationBase{static{__name(this,"_Migration727TrimSelfRollOptions")}optionPattern=/^self:(ability|class|feat(?:ure)?|perception|skill):/;optionReplacement="$1:";trimRollOption(option){return option.replace(this.optionPattern,this.optionReplacement)}trimPredicates(obj){for(const[key,value]of Object.entries(obj))typeof value=="string"?obj[key]=this.trimRollOption(value):Array.isArray(value)?obj[key]=value.map(e=>typeof e=="string"?this.trimRollOption(e):isObject(e)?this.trimPredicates(e):e):isObject(value)&&(obj[key]=this.trimPredicates(value));return obj}async updateItem(source){source.system.rules=source.system.rules.map(r=>this.trimPredicates(r))}};__name2(_Migration727TrimSelfRollOptions,"Migration727TrimSelfRollOptions"),__publicField(_Migration727TrimSelfRollOptions,"version",.727);let Migration727TrimSelfRollOptions=_Migration727TrimSelfRollOptions;const _Migration728FlattenPhysicalProperties=class extends MigrationBase{static{__name(this,"_Migration728FlattenPhysicalProperties")}booleanKeys=["temporary","collapsed"];numericKeys=["quantity","hardness"];stringKeys=["stackGroup","containerId"];async updateItem(source){if(!isPhysicalData(source))return;const systemSource=source.system;if(systemSource.currency&&(delete systemSource.currency,systemSource["-=currency"]=null),systemSource.hands&&(delete systemSource.hands,systemSource["-=hands"]=null),systemSource.equipped&&systemSource.invested instanceof Object){const value=systemSource.invested.value;if(typeof value=="boolean"||value===null){const shouldBeBoolean=source.system.traits.value.includes("invested")||source.type==="armor"&&(source.system.potencyRune.value??0)>0;systemSource.equipped.invested=shouldBeBoolean?!!value:null}}if(delete systemSource.invested,systemSource["-=invested"]=null,systemSource.capacity&&source.type!=="book"&&(delete systemSource.capacity,systemSource["-=capacity"]=null),source.type!=="backpack"&&(delete systemSource.bulkCapacity,systemSource["-=bulkCapacity"]=null,delete systemSource.collapsed,systemSource["-=collapsed"]=null),systemSource.size instanceof Object){const size=SIZES.includes(systemSource.size.value)?systemSource.size.value:"med";systemSource.size=size}"brokenThreshold"in systemSource&&(systemSource.brokenThreshold instanceof Object&&(systemSource.hp.brokenThreshold=Number(systemSource.brokenThreshold.value)),delete systemSource.brokenThreshold,systemSource["-=brokenThreshold"]=null),systemSource.hp.value=Number(systemSource.hp.value),systemSource.maxHp instanceof Object&&(systemSource.hp.max=Number(systemSource.maxHp.value)||0,delete systemSource.maxHp,systemSource["-=maxHp"]=null);for(const key of this.booleanKeys){const value=systemSource[key];value instanceof Object&&(systemSource[key]=value.value)}for(const key of this.numericKeys){const value=systemSource[key];value instanceof Object&&(systemSource[key]=Number(value.value)||0)}for(const key of this.stringKeys){const value=systemSource[key];value instanceof Object&&(systemSource[key]=String(value.value)||null)}}};__name2(_Migration728FlattenPhysicalProperties,"Migration728FlattenPhysicalProperties"),__publicField(_Migration728FlattenPhysicalProperties,"version",.728);let Migration728FlattenPhysicalProperties=_Migration728FlattenPhysicalProperties;const _Migration729CumulativeItemBonusCleanup=class extends MigrationBase{static{__name(this,"_Migration729CumulativeItemBonusCleanup")}constructor(){super(...arguments),__privateAdd(this,_explorersClothingVariants,new Set(["clothing-explorers","robe-of-the-arch-magi","robe-of-the-arch-magi-greater","sarkorian-god-caller-garb"]))}isExplorersClothing(source){return source.type==="armor"&&__privateGet(this,_explorersClothingVariants).has(source.system.slug??"")}isStanceEffectOrAnimalSkinFeat(source){return source.type==="effect"&&source.system.slug==="stance-mountain-stance"||source.type==="feat"&&source.system.slug==="animal-skin"}async updateItem(source){if(this.isExplorersClothing(source))source.system.category="unarmored",source.system.group="cloth",source.system.baseItem="explorers-clothing",source.system.traits.value.includes("comfort")||source.system.traits.value.push("comfort");else if(this.isStanceEffectOrAnimalSkinFeat(source)){const rule=source.system.rules.find(r=>r.key==="AdjustModifier"&&r.slug==="clothing-explorers");rule&&(rule.slug="explorers-clothing")}else if(source.type==="equipment"){const isBracers=!!source.system.slug?.startsWith("bracers-of-armor-");for(const rule of source.system.rules)rule.key==="FlatModifier"&&rule.slug==="bracers-of-armor"&&!isBracers&&(source.system.slug==="metuaks-pendant"?rule.slug="metuaks-pendant":delete rule.slug)}}};_explorersClothingVariants=new WeakMap,__name2(_Migration729CumulativeItemBonusCleanup,"Migration729CumulativeItemBonusCleanup"),__publicField(_Migration729CumulativeItemBonusCleanup,"version",.729);let Migration729CumulativeItemBonusCleanup=_Migration729CumulativeItemBonusCleanup;const _Migration730DeruneHandwraps=class extends MigrationBase{static{__name(this,"_Migration730DeruneHandwraps")}async updateItem(source){if(source.type==="weapon"&&source.system.slug==="handwraps-of-mighty-blows"){const{rules}=source.system;for(const rule of[...rules])["Striking","WeaponPotency"].includes(String(rule.key))&&source.system.rules.splice(rules.indexOf(rule),1)}}};__name2(_Migration730DeruneHandwraps,"Migration730DeruneHandwraps"),__publicField(_Migration730DeruneHandwraps,"version",.73);let Migration730DeruneHandwraps=_Migration730DeruneHandwraps;const _Migration731TogglePropertyToRollOption=class extends Migration727TrimSelfRollOptions{static{__name(this,"_Migration731TogglePropertyToRollOption")}constructor(){super(...arguments),__publicField(this,"optionPattern",/^target:flatFooted$/),__publicField(this,"optionReplacement","target:condition:flat-footed"),__privateAdd(this,_pathPattern,/^flags\.pf2e\.rollOptions\.([^.]+)\.([^.]+)$/)}async updateItem(source){source.system.rules=source.system.rules.map(r=>this.trimPredicates(r));const rules=source.system.rules;for(const rule of[...rules]){if(rule.key!=="ToggleProperty")continue;const match=__privateGet(this,_pathPattern).exec(rule.property?.trim()??"");if(!(match?.length===3&&match[1].length>=2&&match[2].length>=1)){rules.splice(rules.indexOf(rule),1);continue}rule.key="RollOption",rule.domain=match[1],rule.option=match[2],rule.toggleable=!0,delete rule.property,typeof rule.default=="boolean"&&(rule.value=rule.default,delete rule.default),sluggify(String(rule.label??""))===source.system.slug&&delete rule.label}}async updateActor(source){source.flags.pf2e?.rollOptions?.all&&(source.flags.pf2e.rollOptions.all["-=panache"]=!1,source.flags.pf2e.rollOptions.all["-=rage"]=!1,source.flags.pf2e.rollOptions.all["-=target:flatFooted"]=!1)}};_pathPattern=new WeakMap,__name2(_Migration731TogglePropertyToRollOption,"Migration731TogglePropertyToRollOption"),__publicField(_Migration731TogglePropertyToRollOption,"version",.731);let Migration731TogglePropertyToRollOption=_Migration731TogglePropertyToRollOption;const _Migration732FixDedicationFeatTypes=class extends MigrationBase{static{__name(this,"_Migration732FixDedicationFeatTypes")}constructor(){super(...arguments),__privateAdd(this,_hasWellFormedFeatType)}async updateItem(source){if(source.type==="feat"){const system=source.system;if(!__privateMethod(this,_hasWellFormedFeatType,hasWellFormedFeatType_fn).call(this,system))system.featType={value:"bonus"};else{const{featType}=system;(featType.value==="dedication"||featType.value==="class"&&source.system.slug?.endsWith("-dedication"))&&(featType.value="archetype")}}}};_hasWellFormedFeatType=new WeakSet,hasWellFormedFeatType_fn=__name2(function(system){return"featType"in system&&isObject(system.featType)&&"value"in system.featType&&typeof system.featType=="string"},"#hasWellFormedFeatType"),__name2(_Migration732FixDedicationFeatTypes,"Migration732FixDedicationFeatTypes"),__publicField(_Migration732FixDedicationFeatTypes,"version",.732);let Migration732FixDedicationFeatTypes=_Migration732FixDedicationFeatTypes;const _Migration733ItemBonusFromEquipment=class extends MigrationBase{static{__name(this,"_Migration733ItemBonusFromEquipment")}slugs=new Set(["animal-skin","stance-mountain-stance","spell-effect-mage-armor"]);async updateItem(source){const compendiumItem=this.slugs.has(source.system.slug??""),homebrewItem=!compendiumItem&&source.type==="feat";if(!(compendiumItem||homebrewItem))return;const rules=source.system.rules;for(const rule of rules)rule.key==="FlatModifier"&&rule.type==="item"&&(rule.fromEquipment=!1)}};__name2(_Migration733ItemBonusFromEquipment,"Migration733ItemBonusFromEquipment"),__publicField(_Migration733ItemBonusFromEquipment,"version",.733);let Migration733ItemBonusFromEquipment=_Migration733ItemBonusFromEquipment;const _Migration734SpellLocationPropsAndSignature=class extends MigrationBase{static{__name(this,"_Migration734SpellLocationPropsAndSignature")}async updateActor(actor){const entries=actor.items.filter(item=>item.type==="spellcastingEntry"),spells=actor.items.filter(item=>item.type==="spell");for(const spellSource of spells){const spellData=spellSource.system,entrySource=entries.find(entry=>entry._id===spellData.location.value);if(!entrySource)continue;const entryData=entrySource.system;if(!entryData.signatureSpells)continue;entryData.signatureSpells.value.includes(spellSource._id??"")&&(spellData.location.signature=!0)}}async updateItem(source,actor){if(source.type==="spellcastingEntry"){const data=source.system;data.signatureSpells&&(delete data.signatureSpells,"game"in globalThis&&(data["-=signatureSpells"]=null))}if(source.type==="spell"){const data=source.system;(data.heightenedLevel||data.autoHeightenLevel)&&(actor&&(data.location.heightenedLevel=data.heightenedLevel?.value??void 0,data.location.autoHeightenLevel=data.autoHeightenLevel?.value??void 0),delete data.autoHeightenLevel,delete data.heightenedLevel,"game"in globalThis&&(data["-=autoHeightenLevel"]=null,data["-=heightenedLevel"]=null))}}};__name2(_Migration734SpellLocationPropsAndSignature,"Migration734SpellLocationPropsAndSignature"),__publicField(_Migration734SpellLocationPropsAndSignature,"version",.734);let Migration734SpellLocationPropsAndSignature=_Migration734SpellLocationPropsAndSignature;const _Migration735FirearmAmmoAlchemical=class extends MigrationBase{static{__name(this,"_Migration735FirearmAmmoAlchemical")}constructor(){super(...arguments),__privateAdd(this,_needsTrait)}async updateItem(source){source.type==="consumable"&&__privateMethod(this,_needsTrait,needsTrait_fn).call(this,source)&&source.system.traits.value.unshift("alchemical")}};_needsTrait=new WeakSet,needsTrait_fn=__name2(function(source){return source.system.consumableType.value==="ammo"&&!!source.system.stackGroup?.startsWith("rounds")&&source.system.slug!=="cutlery"&&!source.system.traits.value.includes("alchemical")},"#needsTrait"),__name2(_Migration735FirearmAmmoAlchemical,"Migration735FirearmAmmoAlchemical"),__publicField(_Migration735FirearmAmmoAlchemical,"version",.735);let Migration735FirearmAmmoAlchemical=_Migration735FirearmAmmoAlchemical;const _Migration736RemoveBrokenThreshold=class extends MigrationBase{static{__name(this,"_Migration736RemoveBrokenThreshold")}constructor(){super(...arguments),__privateAdd(this,_hasBrokenThreshold)}async updateItem(source){__privateMethod(this,_hasBrokenThreshold,hasBrokenThreshold_fn).call(this,source)&&(delete source.system.brokenThreshold,source.system["-=brokenThreshold"]=null)}};_hasBrokenThreshold=new WeakSet,hasBrokenThreshold_fn=__name2(function(source){return isPhysicalData(source)&&"brokenThreshold"in source.system},"#hasBrokenThreshold"),__name2(_Migration736RemoveBrokenThreshold,"Migration736RemoveBrokenThreshold"),__publicField(_Migration736RemoveBrokenThreshold,"version",.736);let Migration736RemoveBrokenThreshold=_Migration736RemoveBrokenThreshold;const _Migration737NormalizeRuleElementKeys=class extends Migration731TogglePropertyToRollOption{static{__name(this,"_Migration737NormalizeRuleElementKeys")}async updateItem(source){const rules=source.system.rules;for(const rule of[...rules]){if(!isObject(rule)||typeof rule.key!="string"){rules.splice(rules.indexOf(rule),1);continue}rule.key=rule.key.trim().replace(/^PF2E\.RuleElement\./,"")}return super.updateItem(source)}};__name2(_Migration737NormalizeRuleElementKeys,"Migration737NormalizeRuleElementKeys"),__publicField(_Migration737NormalizeRuleElementKeys,"version",.737);let Migration737NormalizeRuleElementKeys=_Migration737NormalizeRuleElementKeys;const _Migration738UpdateLaughingShadow=class extends MigrationBase{static{__name(this,"_Migration738UpdateLaughingShadow")}constructor(){super(...arguments),__privateAdd(this,_shadowPromise,fromUuid("Compendium.pf2e.classfeatures.3gVDqDPSz4fB5T9G")),__privateAdd(this,_cascadePromise,fromUuid("Compendium.pf2e.feature-effects.fsjO5oTKttsbpaKl"))}async updateActor(source){const rollOptionsAll=source.flags.pf2e?.rollOptions?.all;rollOptionsAll instanceof Object&&"feature:laughing-shadow:damage"in rollOptionsAll&&(rollOptionsAll["-=feature:laughing-shadow:damage"]=!1)}async updateItem(source){if(source.type==="feat"&&source.system.slug==="laughing-shadow"){const laughingShadow=await __privateGet(this,_shadowPromise);if(!(laughingShadow instanceof ItemPF2e))return;source.system.rules=deepClone(laughingShadow._source.system.rules)}else if(source.type==="effect"&&source.system.slug==="stance-arcane-cascade"){const arcaneCascade=await __privateGet(this,_cascadePromise);if(!(arcaneCascade instanceof ItemPF2e))return;const newRules=deepClone(arcaneCascade._source.system.rules),withSelection=source.system.rules.find(r=>r.key==="ChoiceSet"&&typeof r.selection=="string");if(withSelection){const unselected=newRules.find(r=>r.key==="ChoiceSet");unselected&&(unselected.selection=withSelection.selection)}source.system.rules=newRules}}};_shadowPromise=new WeakMap,_cascadePromise=new WeakMap,__name2(_Migration738UpdateLaughingShadow,"Migration738UpdateLaughingShadow"),__publicField(_Migration738UpdateLaughingShadow,"version",.738);let Migration738UpdateLaughingShadow=_Migration738UpdateLaughingShadow;const _Migration739RecoveryCheckDC=class extends MigrationBase{static{__name(this,"_Migration739RecoveryCheckDC")}toughness=[{key:"FlatModifier",selector:"hp",value:"@actor.level"},{key:"ActiveEffectLike",mode:"downgrade",path:"system.attributes.dying.recoveryDC",value:9}];defyDeath=[{key:"ActiveEffectLike",mode:"downgrade",predicate:{not:["feat:toughness"]},path:"system.attributes.dying.recoveryDC",value:9},{key:"ActiveEffectLike",mode:"downgrade",predicate:{all:["feat:toughness"]},path:"system.attributes.dying.recoveryDC",value:8}];mountainsStoutness=[{key:"FlatModifier",selector:"hp",type:"untyped",value:"@actor.level"},{key:"ActiveEffectLike",mode:"downgrade",predicate:{not:["feat:toughness"]},path:"system.attributes.dying.recoveryDC",value:9},{key:"ActiveEffectLike",mode:"downgrade",predicate:{all:["feat:toughness"]},path:"system.attributes.dying.recoveryDC",value:6}];async updateItem(source){if(source.type!=="feat")return;if(source.system.slug==="toughness"){source.system.rules=this.toughness;return}else if(source.system.slug==="defy-death"){source.system.rules=this.defyDeath;return}else if(source.system.slug==="mountains-stoutness"){source.system.rules=this.mountainsStoutness;return}const{rules}=source.system;for(const rule of[...rules])rule.key==="RecoveryCheckDC"&&source.system.rules.splice(rules.indexOf(rule),1)}};__name2(_Migration739RecoveryCheckDC,"Migration739RecoveryCheckDC"),__publicField(_Migration739RecoveryCheckDC,"version",.739);let Migration739RecoveryCheckDC=_Migration739RecoveryCheckDC;const _Migration740MaxTakable=class extends MigrationBase{static{__name(this,"_Migration740MaxTakable")}async updateItem(source){if(source.type!=="feat")return;const systemData=source.system;"maxTaken"in systemData&&(typeof systemData.maxTaken=="number"&&typeof systemData.maxTakable!="number"&&(systemData.maxTakable=systemData.maxTaken),delete systemData.maxTaken,systemData["-=maxTaken"]=null),"maxTakable"in systemData&&typeof systemData.maxTakable!="number"&&(systemData.maxTakable=null)}};__name2(_Migration740MaxTakable,"Migration740MaxTakable"),__publicField(_Migration740MaxTakable,"version",.74);let Migration740MaxTakable=_Migration740MaxTakable;const _Migration741RollOptionToggleToItem=class extends MigrationBase{static{__name(this,"_Migration741RollOptionToggleToItem")}async updateActor(source){if(!(source.flags.pf2e?.rollOptions instanceof Object))return;const rules=source.items.flatMap(i=>i.system.rules).filter(r=>!!r.toggleable&&r.key==="RollOption"&&typeof r.domain=="string"&&r.domain.length>0&&typeof r.option=="string"&&r.option.length>0),{rollOptions}=source.flags.pf2e;for(const rule of rules){const domain=rollOptions[rule.domain];domain instanceof Object&&rule.option in domain&&(domain[`-=${rule.option}`]=!1,rule.value=!!domain[rule.option])}}};__name2(_Migration741RollOptionToggleToItem,"Migration741RollOptionToggleToItem"),__publicField(_Migration741RollOptionToggleToItem,"version",.741);let Migration741RollOptionToggleToItem=_Migration741RollOptionToggleToItem;const _Migration742RMAbilityBoostLevels=class extends MigrationBase{static{__name(this,"_Migration742RMAbilityBoostLevels")}async updateItem(source){if(source.type!=="class")return;const systemData=source.system;"abilityBoostLevels"in source.system&&(delete systemData.abilityBoostLevels,systemData["-=abilityBoostLevels"]=null)}};__name2(_Migration742RMAbilityBoostLevels,"Migration742RMAbilityBoostLevels"),__publicField(_Migration742RMAbilityBoostLevels,"version",.742);let Migration742RMAbilityBoostLevels=_Migration742RMAbilityBoostLevels;const _Migration743FixWeaknessStructure=class extends MigrationBase{static{__name(this,"_Migration743FixWeaknessStructure")}async updateActor(source){if(source.type!=="character"&&source.type!=="npc")return;const traits=source.system.traits;Array.isArray(traits.dv)||(traits.dv=[]),Array.isArray(traits.dr)||(traits.dr=[])}};__name2(_Migration743FixWeaknessStructure,"Migration743FixWeaknessStructure"),__publicField(_Migration743FixWeaknessStructure,"version",.743);let Migration743FixWeaknessStructure=_Migration743FixWeaknessStructure;const _Migration744MigrateSpellHeighten=class extends MigrationBase{static{__name(this,"_Migration744MigrateSpellHeighten")}async updateItem(source){if(source.type!=="spell")return;const system=source.system;system.scaling&&(system.heightening={type:"interval",interval:system.scaling.interval,damage:system.scaling.damage},delete system.scaling,system["-=scaling"]=null)}};__name2(_Migration744MigrateSpellHeighten,"Migration744MigrateSpellHeighten"),__publicField(_Migration744MigrateSpellHeighten,"version",.744);let Migration744MigrateSpellHeighten=_Migration744MigrateSpellHeighten;const _Migration745EffectTargetToChoiceSet=class extends MigrationBase{static{__name(this,"_Migration745EffectTargetToChoiceSet")}constructor(){super(...arguments),__privateAdd(this,_isEffectTargetRE),__privateAdd(this,_toChoiceSet)}async updateItem(source,actorSource){const{rules}=source.system;for(const rule of rules)if(__privateMethod(this,_isEffectTargetRE,isEffectTargetRE_fn).call(this,rule)){rules[rules.indexOf(rule)]=__privateMethod(this,_toChoiceSet,toChoiceSet_fn).call(this,rule,source,actorSource??null);const otherRules=rules.filter(r=>typeof r.selector=="string"&&/item\|data\.target/.test(r.selector));for(const other of otherRules){const flag=sluggify(source.system.slug??source.name,{camel:"dromedary"});other.selector=other.selector.replace(/\bdata\.target\b/,`flags.pf2e.rulesSelections.${flag}`)}}}};_isEffectTargetRE=new WeakSet,isEffectTargetRE_fn=__name2(function(rule){return rule.key==="EffectTarget"},"#isEffectTargetRE"),_toChoiceSet=new WeakSet,toChoiceSet_fn=__name2(function(rule,itemSource,actorSource){const newRE={key:"ChoiceSet",choices:{ownedItems:!0,types:["weapon"]},prompt:"PF2E.SpecificRule.Prompt.Weapon"};if(typeof rule.targetId=="string"&&actorSource){const weapon=actorSource.items.find(i=>i.type==="weapon"&&i._id===rule.targetId);weapon&&(newRE.selection=weapon.system.slug??sluggify(weapon.name))}return itemSource.system.slug?.includes("blade-ally")?newRE.choices.includeHandwraps=!0:itemSource.system.slug?.includes("weapon-surge")?newRE.choices.predicate={all:["item:equipped"]}:itemSource.system.slug==="shillelagh"?(newRE.adjustName=!1,newRE.prompt="PF2E.SpecificRule.Prompt.Shillelagh",newRE.choices.predicate={all:["item:equipped"],any:["item:base:club","item:base:staff"]}):isObject(rule.predicate)&&(newRE.choices.predicate=deepClone(rule.predicate)),newRE},"#toChoiceSet"),__name2(_Migration745EffectTargetToChoiceSet,"Migration745EffectTargetToChoiceSet"),__publicField(_Migration745EffectTargetToChoiceSet,"version",.745);let Migration745EffectTargetToChoiceSet=_Migration745EffectTargetToChoiceSet;const _Migration746StandardizePricing=class extends MigrationBase{static{__name(this,"_Migration746StandardizePricing")}async updateItem(item){if(!(!isPhysicalData(item)&&item.type!=="kit"))if(isObject(item.system.price)||(item.system.price={value:CoinsPF2e.fromString(String(item.system.price)).toObject()}),item.type==="treasure"){const systemData=item.system;if(systemData.denomination||systemData.value){const value=systemData.value?.value??0,denomination=systemData.denomination?.value??"gp";systemData.price={value:{[denomination]:value}},systemData["-=denomination"]=null,delete systemData.denomination,systemData["-=value"]=null,delete systemData.value}}else isObject(item.system.price.value)||(item.system.price.value=CoinsPF2e.fromString(String(item.system.price.value)).toObject())}};__name2(_Migration746StandardizePricing,"Migration746StandardizePricing"),__publicField(_Migration746StandardizePricing,"version",.746);let Migration746StandardizePricing=_Migration746StandardizePricing;const _Migration747FixedHeightening=class extends MigrationBase{static{__name(this,"_Migration747FixedHeightening")}constructor(){super(...arguments),__privateAdd(this,_loadedSpells,void 0),__publicField(this,"fixedHeightenSpells",new Set(["Compendium.pf2e.spells-srd.0fKHBh5goe2eiFYL","Compendium.pf2e.spells-srd.10VcmSYNBrvBphu1","Compendium.pf2e.spells-srd.2gQYrCPwBmwau26O","Compendium.pf2e.spells-srd.2iQKhCQBijhj5Rf3","Compendium.pf2e.spells-srd.4koZzrnMXhhosn0D","Compendium.pf2e.spells-srd.5WM3WjshXgrkVCg6","Compendium.pf2e.spells-srd.7CUgqHunmHfW2lC5","Compendium.pf2e.spells-srd.7OFKYR1VY6EXDuiR","Compendium.pf2e.spells-srd.9s5tqqXNzcoKamWx","Compendium.pf2e.spells-srd.BCuHKrDeJ4eq53M6","Compendium.pf2e.spells-srd.CxpFy4HJHf4ACbxF","Compendium.pf2e.spells-srd.D2nPKbIS67m9199U","Compendium.pf2e.spells-srd.DCQHaLrYXMI37dvW","Compendium.pf2e.spells-srd.DgcSiOCR1uDXGaEA","Compendium.pf2e.spells-srd.EfFMLVbmkBWmzoLF","Compendium.pf2e.spells-srd.Et8RSCLx8w7uOLvo","Compendium.pf2e.spells-srd.F23T5tHPo3WsFiHW","Compendium.pf2e.spells-srd.FhOaQDTSnsY7tiam","Compendium.pf2e.spells-srd.Fr58LDSrbndgld9n","Compendium.pf2e.spells-srd.GaRQlC9Yw1BGKHfN","Compendium.pf2e.spells-srd.HGmBY8KjgLV97nUp","Compendium.pf2e.spells-srd.HHGUBGle4OjoxvNR","Compendium.pf2e.spells-srd.HTou8cG05yuSkesj","Compendium.pf2e.spells-srd.HWrNMQENi9WSGbnF","Compendium.pf2e.spells-srd.HcIAQZjNXHemoXSU","Compendium.pf2e.spells-srd.Ifc2b6bNVdjKV7Si","Compendium.pf2e.spells-srd.JHntYF0SbaWKq7wR","Compendium.pf2e.spells-srd.LQzlKbYjZSMFQawP","Compendium.pf2e.spells-srd.LiGbewa9pO0yjbsY","Compendium.pf2e.spells-srd.Llx0xKvtu8S4z6TI","Compendium.pf2e.spells-srd.Mkbq9xlAUxHUHyR2","Compendium.pf2e.spells-srd.OAt2ZEns1gIOCgrn","Compendium.pf2e.spells-srd.OhD2Z6rIGGD5ocZA","Compendium.pf2e.spells-srd.PRrZ7anETWPm90YY","Compendium.pf2e.spells-srd.PjhUmyKnq6K5uDby","Compendium.pf2e.spells-srd.Popa5umI3H33levx","Compendium.pf2e.spells-srd.Pwq6T7xpfAJXV5aj","Compendium.pf2e.spells-srd.Q7QQ91vQtyi1Ux36","Compendium.pf2e.spells-srd.Seaah9amXg70RKw2","Compendium.pf2e.spells-srd.U58aQWJ47VrI36yP","Compendium.pf2e.spells-srd.UmXhuKrYZR3W16mQ","Compendium.pf2e.spells-srd.VTb0yI6P1bLkzuRr","Compendium.pf2e.spells-srd.VlNcjmYyu95vOUe8","Compendium.pf2e.spells-srd.W02bHXylIpoXbO4e","Compendium.pf2e.spells-srd.WsUwpfmhKrKwoIe3","Compendium.pf2e.spells-srd.Wt94cw03L77sbud7","Compendium.pf2e.spells-srd.XhgMx9WC6NfXd9RP","Compendium.pf2e.spells-srd.ZAX0OOcKtYMQlquR","Compendium.pf2e.spells-srd.ZqmP9gijBmK7y8Xy","Compendium.pf2e.spells-srd.aIHY2DArKFweIrpf","Compendium.pf2e.spells-srd.atlgGNI1E1Ox3O3a","Compendium.pf2e.spells-srd.bay4AfSu2iIozNNW","Compendium.pf2e.spells-srd.czO0wbT1i320gcu9","Compendium.pf2e.spells-srd.dINQzhqGmIsqGMUY","Compendium.pf2e.spells-srd.drmvQJETA3WZzXyw","Compendium.pf2e.spells-srd.e36Z2t6tLdW3RUzZ","Compendium.pf2e.spells-srd.fprqWKUc0jnMIyGU","Compendium.pf2e.spells-srd.gISYsBFby1TiXfBt","Compendium.pf2e.spells-srd.ivKnEtI1z4UqEKIA","Compendium.pf2e.spells-srd.kuoYff1csM5eAcAP","Compendium.pf2e.spells-srd.lbrWMnS2pecKaSVB","Compendium.pf2e.spells-srd.lsR3RLEdBG4rcSzd","Compendium.pf2e.spells-srd.nXmC2Xx9WmS5NsAo","Compendium.pf2e.spells-srd.o6YCGx4lycsYpww4","Compendium.pf2e.spells-srd.pZTqGY1MLRjgKasV","Compendium.pf2e.spells-srd.pt3gEnzA159uHcJC","Compendium.pf2e.spells-srd.pwzdSlJgYqN7bs2w","Compendium.pf2e.spells-srd.q5qmNn144ZJGxnvJ","Compendium.pf2e.spells-srd.qTr2oCgIXl703Whb","Compendium.pf2e.spells-srd.qwlh6aDgi86U3Q7H","Compendium.pf2e.spells-srd.r4HLQcYwB62bTayl","Compendium.pf2e.spells-srd.sFwoKj0TsacsmoWj","Compendium.pf2e.spells-srd.vLA0q0WOK2YPuJs6","Compendium.pf2e.spells-srd.vLzFcIaSXs7YTIqJ","Compendium.pf2e.spells-srd.vTQvfYu2llKQedmY","Compendium.pf2e.spells-srd.vctIUOOgSmxAF0KG","Compendium.pf2e.spells-srd.wzctak6BxOW8xvFV","Compendium.pf2e.spells-srd.x5rGOmhDRDVQPrnW","Compendium.pf2e.spells-srd.x7SPrsRxGb2Vy2nu","Compendium.pf2e.spells-srd.x9RIFhquazom4p02","Compendium.pf2e.spells-srd.xRgU9rrhmGAgG4Rc","Compendium.pf2e.spells-srd.yH13KXUK2x093NUv","Compendium.pf2e.spells-srd.yM3KTTSAIHhyuP14","Compendium.pf2e.spells-srd.zlnXpME1T2uvn8Lr","Compendium.pf2e.spells-srd.zul5cBTfr7NXHBZf"]))}async updateItem(item){if(item.type!=="spell")return;const isAcidSplash=(item.system.slug??sluggify(item.name))==="acid-splash";if(item.system.heightening?.type==="fixed"&&!isAcidSplash)return;const sourceId=item.flags.core?.sourceId;if(sourceId&&this.fixedHeightenSpells.has(sourceId)){const spell=(await this.loadSpells())[sourceId];spell&&spell.system.heightening?.type==="fixed"&&(item.system.heightening=spell.system.heightening,this.overwriteDamage(item,spell))}}overwriteDamage(spell,newSpell){const newDamage=newSpell.system.damage,newKeys=new Set(Object.keys(newDamage.value)),diff=Object.keys(spell.system.damage.value).filter(key=>!newKeys.has(key)),damage=spell.system.damage;damage.value=newDamage.value;for(const deleteKey of diff)damage.value[`-=${deleteKey}`]=null}async loadSpells(){if(__privateGet(this,_loadedSpells))return __privateGet(this,_loadedSpells);const spells=await UUIDUtils.fromUUIDs([...this.fixedHeightenSpells]);return __privateSet(this,_loadedSpells,spells.reduce((record,spell)=>({...record,[spell.uuid]:spell}),{})),__privateGet(this,_loadedSpells)}};_loadedSpells=new WeakMap,__name2(_Migration747FixedHeightening,"Migration747FixedHeightening"),__publicField(_Migration747FixedHeightening,"version",.747);let Migration747FixedHeightening=_Migration747FixedHeightening;const _Migration748BatchConsumablePricing=class extends MigrationBase{static{__name(this,"_Migration748BatchConsumablePricing")}async updateItem(item){if(!isPhysicalData(item))return;const slug=item.system.slug??sluggify(item.name);batched_5.has(slug)&&(item.system.price.per=5),batched_10.has(slug)&&(item.system.price.per=10)}};__name2(_Migration748BatchConsumablePricing,"Migration748BatchConsumablePricing"),__publicField(_Migration748BatchConsumablePricing,"version",.748);let Migration748BatchConsumablePricing=_Migration748BatchConsumablePricing;const batched_5=new Set(["rounds-harmona-gun","rounds-dwarven-scattergun","rounds-flingflenser","rounds-explosive-dogslicer"]),batched_10=new Set(["rounds-three-peaked-tree","rounds-dragon-mouth-pistol","rounds-pepperbox","rounds-fire-lance","rounds-flintlock-pistol","rounds-clan-pistol","bolts","rounds-hand-cannon","sun-shot","rounds-dagger-pistol","rounds-dueling-pistol","rounds-flintlock-musket","rounds-hammer-gun","rounds-black-powder-knuckle-dusters","rounds-slide-pistol","sling-bullets","rounds-double-barreled-musket","rounds-mace-multipistol","rounds-gnome-amalgam-musket","cutlery","rounds-axe-musket","rounds-mithral-tree","wooden-taws","rounds-gun-sword","rounds-blunderbuss","rounds-jezail","rounds-double-barreled-pistol","rounds-arquebus","rounds-cane-pistol","rounds-rapier-pistol","rounds-coat-pistol","rounds-piercing-wind","blowgun-darts","arrows","light-writer-plates","practice-target"]),_Migration749AssuranceREs=class extends MigrationBase{static{__name(this,"_Migration749AssuranceREs")}constructor(){super(...arguments),__privateAdd(this,_isChoiceSetWithSelection),__privateAdd(this,_newRules)}async updateItem(source){const{slug,rules}=source.system;if(!(source.type==="feat"&&slug?.startsWith("assurance")))return;const firstRule=rules.at(0);if(slug==="assurance"&&firstRule&&rules.length===1&&__privateMethod(this,_isChoiceSetWithSelection,isChoiceSetWithSelection_fn).call(this,firstRule))firstRule.flag="assurance",rules.push(...__privateMethod(this,_newRules,newRules_fn).call(this,"choice"));else if(rules.length===0){const skill=/^assurance-([a-z]+)$/.exec(slug)?.at(1);setHasElement(SKILL_LONG_FORMS,skill)&&rules.push(...__privateMethod(this,_newRules,newRules_fn).call(this,skill))}}};_isChoiceSetWithSelection=new WeakSet,isChoiceSetWithSelection_fn=__name2(function(rule){return rule.key==="ChoiceSet"},"#isChoiceSetWithSelection"),_newRules=new WeakSet,newRules_fn=__name2(function(skill){const selector=skill==="choice"?"{item|flags.pf2e.rulesSelections.assurance}":skill;return[{key:"SubstituteRoll",label:"PF2E.SpecificRule.SubstituteRoll.Assurance",selector,slug:"assurance",value:10},{key:"AdjustModifier",predicate:{all:["substitute:assurance"],not:["bonus:type:proficiency"]},selector,suppress:!0}]},"#newRules"),__name2(_Migration749AssuranceREs,"Migration749AssuranceREs"),__publicField(_Migration749AssuranceREs,"version",.749);let Migration749AssuranceREs=_Migration749AssuranceREs;const _Migration750FixCorruptedPrice=class extends MigrationBase{static{__name(this,"_Migration750FixCorruptedPrice")}async updateItem(item){!isPhysicalData(item)&&item.type!=="kit"||typeof item.system.price=="string"&&(item.system.price={value:CoinsPF2e.fromString(item.system.price).toObject()})}};__name2(_Migration750FixCorruptedPrice,"Migration750FixCorruptedPrice"),__publicField(_Migration750FixCorruptedPrice,"version",.75);let Migration750FixCorruptedPrice=_Migration750FixCorruptedPrice;const _Migration751ResetRollOptions=class extends MigrationBase{static{__name(this,"_Migration751ResetRollOptions")}async updateActor(source){isObject(source.flags.pf2e)&&"rollOptions"in source.flags.pf2e&&(source.flags.pf2e["-=rollOptions"]=null)}};__name2(_Migration751ResetRollOptions,"Migration751ResetRollOptions"),__publicField(_Migration751ResetRollOptions,"version",.751);let Migration751ResetRollOptions=_Migration751ResetRollOptions;const _Migration752StrikeVsWeaponTraits=class extends MigrationBase{static{__name(this,"_Migration752StrikeVsWeaponTraits")}constructor(){super(...arguments),__privateAdd(this,_toSkip,new Set(["ghost-hunter","stance-arcane-cascade","spirit-strikes"]))}async updateItem(source){if(__privateGet(this,_toSkip).has(source.system.slug??""))return;const rules=source.system.rules.filter(r=>r.key==="AdjustStrike"&&r.property==="traits");for(const rule of rules)objectHasKey(weaponTraits,rule.value)&&(rule.property="weapon-traits")}};_toSkip=new WeakMap,__name2(_Migration752StrikeVsWeaponTraits,"Migration752StrikeVsWeaponTraits"),__publicField(_Migration752StrikeVsWeaponTraits,"version",.752);let Migration752StrikeVsWeaponTraits=_Migration752StrikeVsWeaponTraits;const _Migration753WeaponReloadTimes=class extends MigrationBase{static{__name(this,"_Migration753WeaponReloadTimes")}constructor(){super(...arguments),__privateAdd(this,_hasThrownTrait)}async updateItem(source){if(source.type!=="weapon")return;const slug=source.system.slug??"";["backpack-catapult","backpack-catapult"].includes(slug)?source.system.reload.value="10":(source.system.baseItem==="alchemical-bomb"||__privateMethod(this,_hasThrownTrait,hasThrownTrait_fn).call(this,source))&&(source.system.reload.value="-")}};_hasThrownTrait=new WeakSet,hasThrownTrait_fn=__name2(function(source){return source.system.traits.value.some(t=>t.startsWith("thrown"))},"#hasThrownTrait"),__name2(_Migration753WeaponReloadTimes,"Migration753WeaponReloadTimes"),__publicField(_Migration753WeaponReloadTimes,"version",.753);let Migration753WeaponReloadTimes=_Migration753WeaponReloadTimes;const _Migration754MightyBulwarkAdjustModifiers=class extends MigrationBase{static{__name(this,"_Migration754MightyBulwarkAdjustModifiers")}async updateItem(source){if(!(source.type==="feat"&&source.system.slug==="mighty-bulwark"))return;const newRules=[{key:"FlatModifier",predicate:{all:["self:armor:trait:bulwark"]},selector:"reflex",type:"untyped",value:4},{key:"AdjustModifier",predicate:{all:["self:armor:trait:bulwark"]},selector:"reflex",slug:"dex",suppress:!0},{key:"AdjustModifier",selector:"reflex",slug:"bulwark",suppress:!0}];source.system.rules=newRules}};__name2(_Migration754MightyBulwarkAdjustModifiers,"Migration754MightyBulwarkAdjustModifiers"),__publicField(_Migration754MightyBulwarkAdjustModifiers,"version",.754);let Migration754MightyBulwarkAdjustModifiers=_Migration754MightyBulwarkAdjustModifiers;const _Migration755GrantIdsToData=class extends MigrationBase{static{__name(this,"_Migration755GrantIdsToData")}async updateActor(source){for(const item of source.items){if(!item.flags.pf2e)continue;const systemFlags=item.flags.pf2e,{grantedBy,itemGrants}=systemFlags;typeof grantedBy=="string"&&(source.items.find(i=>i._id===grantedBy)?systemFlags.grantedBy={id:grantedBy}:systemFlags["-=grantedBy"]=null),Array.isArray(itemGrants)&&(systemFlags.itemGrants=itemGrants.flatMap(grant=>typeof grant=="string"?source.items.find(i=>i._id===grant)?{id:grant}:[]:grant))}}};__name2(_Migration755GrantIdsToData,"Migration755GrantIdsToData"),__publicField(_Migration755GrantIdsToData,"version",.755);let Migration755GrantIdsToData=_Migration755GrantIdsToData;const _Migration756RMStoredResourceMaxes=class extends MigrationBase{static{__name(this,"_Migration756RMStoredResourceMaxes")}async updateActor(source){source.type==="character"&&(source["system.resources.focus.-=max"]=null,source["system.resources.crafting.infusedReagents.-=max"]=null,source["system.resources.-=investiture"]=null)}};__name2(_Migration756RMStoredResourceMaxes,"Migration756RMStoredResourceMaxes"),__publicField(_Migration756RMStoredResourceMaxes,"version",.756);let Migration756RMStoredResourceMaxes=_Migration756RMStoredResourceMaxes;const _Migration757HillockHalfling=class extends MigrationBase{static{__name(this,"_Migration757HillockHalfling")}async updateItem(itemSource){if(itemSource.type!=="heritage"||(itemSource.system.slug??sluggify(itemSource.name))!=="hillock-halfling")return;const rules=itemSource.system.rules;if(!rules.some(rule=>"path"in rule&&rule.path==="system.attributes.hp.recoveryAddend")){const element={key:"ActiveEffectLike",mode:"add",path:"system.attributes.hp.recoveryAddend",value:"@actor.level"};rules.push(element)}}};__name2(_Migration757HillockHalfling,"Migration757HillockHalfling"),__publicField(_Migration757HillockHalfling,"version",.757);let Migration757HillockHalfling=_Migration757HillockHalfling;const _Migration758PrunePCAttributes=class extends MigrationBase{static{__name(this,"_Migration758PrunePCAttributes")}toDelete=["-=ac","-=ancestryhp","-=battleForm","-=classDC","-=classOrSpellDC","-=classhp","-=dexCap","-=doomed","-=dying","-=familiarAbilities","-=flanking","-=flatbonushp","-=flatbonussp","-=handsFree","-=hardness","hp.-=breakdown","hp.-=details","hp.-=max","hp.-=name","hp.-=negativeHealing","hp.-=recoveryMultiplier","hp.-=totalModifier","hp.-=tempsource","hp.-=_modifiers","initiative.-=_modifiers","initiative.-=breakdown","initiative.-=label","initiative.-=name","initiative.-=roll","initiative.-=tiebreakPriority","initiative.-=totalModifier","-=levelbonushp","-=levelbonussp","-=perception","-=polymorphed","-=reach","-=shield","speed.-=_modifiers","speed.-=breakdown","speed.-=name","speed.-=total","speed.-=totalModifier","speed.-=type","-=spellDC","-=wounded"];async updateActor(source){if(source.type==="character")for(const key of this.toDelete)source[`system.attributes.${key}`]=null}};__name2(_Migration758PrunePCAttributes,"Migration758PrunePCAttributes"),__publicField(_Migration758PrunePCAttributes,"version",.758);let Migration758PrunePCAttributes=_Migration758PrunePCAttributes;const _Migration759CritSpecRE=class extends MigrationBase{static{__name(this,"_Migration759CritSpecRE")}async updateItem(source){if(!["feat","weapon"].includes(source.type))return;const critSpecKey="CriticalSpecialization";if(!source.system.rules.some(r=>r.key===critSpecKey))switch(source.system.slug){case"archer-dedication":{source.system.rules.push({key:critSpecKey,predicate:{all:["weapon:group:bow",{gte:["weapon:proficiency:rank",2]}]}});return}case"azarketi-weapon-aptitude":{source.system.rules=[{key:critSpecKey,predicate:{any:["weapon:trait:azarketi","weapon:base:crossbow","weapon:base:hand-crossbow","weapon:base:longspear","weapon:base:spear","weapon:base:trident"]}}];return}case"brawling-focus":{source.system.rules=[{key:critSpecKey,predicate:{any:["weapon:group:brawling",{and:["feat:monastic-weaponry","weapon:trait:monk",{not:"weapon:category:unarmed"},{gte:["weapon:proficiency:rank",1]}]}]}}];return}case"brutality":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{all:["self:effect:rage","weapon:melee"]}});return}case"catfolk-weapon-rake":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:catfolk","weapon:base:hatchet","weapon:base:kama","weapon:base:kukri","weapon:base:scimitar","weapon:base:sickle"]}}];return}case"conrasu-weapon-understanding":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:conrasu","weapon:base:glaive","weapon:base:longspear","weapon:base:longsword","weapon:base:shortbow","weapon:base:spear"]}}];return}case"dwarven-weapon-cunning":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:dwarf","weapon:base:battle-axe","weapon:base:pick","weapon:base:warhammer"]}}];return}case"elven-weapon-elegance":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:elf","weapon:base:longbow","weapon:base:longsword","weapon:base:rapier","weapon:base:shortbow"]}}];return}case"fighter-weapon-mastery":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{all:[{gte:["weapon:proficiency:rank",3]}]}});return}case"genie-weapon-flourish":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:geniekin","weapon:base:falchion","weapon:base:ranseur","weapon:base:scimitar","weapon:base:trident"]}}];return}case"gnoll-weapon-practicality":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:gnoll","weapon:base:flail","weapon:base:khopesh","weapon:base:mambele","weapon:base:spear","weapon:base:war-flail"]}}];return}case"gnome-weapon-innovator":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:gnome","weapon:base:glaive","weapon:base:kukri"]}}];return}case"goblin-weapon-frenzy":{source.system.rules=[{key:"CriticalSpecialization",predicate:{all:["weapon:trait:goblin"]}}];return}case"grippli-weapon-innovator":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:grippli","weapon:base:blowgun","weapon:base:hatchet","weapon:base:scythe","weapon:base:shortbow"]}}];return}case"gunslinger-weapon-mastery":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{any:["weapon:group:firearm","weapon:tag:crossbow"]}});return}case"halfling-weapon-trickster":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:halfling","weapon:base:shortsword","weapon:base:sling"]}}];return}case"hobgoblin-weapon-discipline":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:group:polearm","weapon:group:spear","weapon:group:sword"]}}];return}case"improvised-critical":{source.system.rules=[{key:critSpecKey,predicate:{all:["weapon:tag:improvised"]}}];return}case"kobold-weapon-innovator":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:kobold","weapon:base:crossbow","weapon:base:greatpick","weapon:base:light-pick","weapon:base:pick","weapon:base:spear"]}}];return}case"mauler-dedication":{source.system.rules.push({key:"CriticalSpecialization",predicate:{all:["weapon:melee",{or:["weapon:category:simple","weapon:category:martial"]},{or:["weapon:usage:hands:2","weapon:trait:two-hand-d6","weapon:trait:two-hand-d8","weapon:trait:two-hand-d10","weapon:trait:two-hand-d12"]}]}});return}case"orc-weapon-carnage":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:orc","weapon:base:falchion","weapon:base:greataxe"]}}];return}case"ranger-weapon-expertise":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{all:["hunted-prey"],any:["weapon:category:simple","weapon:category:martial"]}});return}case"spike-launcher":{const rule={key:critSpecKey,alternate:!0,predicate:{all:["weapon:id:{item|_id}"]},text:"PF2E.Item.Weapon.CriticalSpecialization.bow"};source.system.rules.push(rule);return}case"student-of-the-staff":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.unshift({key:critSpecKey,predicate:{all:["weapon:base:staff"]}});return}case"sun-sling":{source.system.rules.push({key:critSpecKey,predicate:{all:["weapon:id:{item|_id}","feat:suns-fury"]}});return}case"suns-fury":{source.system.rules=[];return}case"third-doctrine-warpriest":{source.system.rules.push({key:critSpecKey,predicate:{all:["weapon:deity-favored"]}});return}case"vanths-weapon-execution":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:base:bo-staff","weapon:base:longbow","weapon:base:scythe","weapon:base:staff"]}}];return}case"weapon-expertise-swashbuckler":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{all:[{gte:["weapon:proficiency:rank",2]}]}});return}case"weapon-tricks":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{all:["target:condition:flat-footed"],any:[{and:[{or:["weapon:trait:agile","weapon:trait:finesse"]},{or:["weapon:category:simple","weapon:category:unarmed"]}]},"weapon:base:rapier","weapon:base:sap","weapon:base:shortbow","weapon:base:shortsword"]}});return}}}};__name2(_Migration759CritSpecRE,"Migration759CritSpecRE"),__publicField(_Migration759CritSpecRE,"version",.759);let Migration759CritSpecRE=_Migration759CritSpecRE;const _Migration760SeparateNoteTitle=class extends MigrationBase{static{__name(this,"_Migration760SeparateNoteTitle")}constructor(){super(...arguments),__privateAdd(this,_cleanText)}async updateItem(source){const notes=source.system.rules.filter(r=>r.key==="Note"&&typeof r.text=="string"&&!("title"in r));for(const note of notes){if(note.text=note.text.trim(),!note.text.startsWith("{const text=note.text.includes("

")?note.text:`${note.text}

`;try{const fragment=document.createElement("template");fragment.innerHTML=text;const children2=Array.from(fragment.content.childNodes);if(children2.length===1&&children2[0]instanceof HTMLElement)return children2[0];if(children2.length===2&&children2[0]instanceof HTMLParagraphElement&&children2[1]instanceof Text){const[first,second]=children2;return first.append(second),first}else return null}catch{return null}})();if(pElement?.nodeName!=="P")continue;const children=Array.from(pElement.childNodes);if(children.length===1&&children[0]instanceof Text){note.text=__privateMethod(this,_cleanText,cleanText_fn).call(this,children[0].textContent??""),pElement.dataset.visibility&&["gm","owner"].includes(pElement.dataset.visibility)&&(note.visibility=pElement.dataset.visibility);continue}if(children.length!==2||!(children[0]instanceof HTMLElement)||children[0].nodeName!=="STRONG"||!(children[1]instanceof Text))continue;const strongElement=children[0];strongElement.remove();const newText=pElement.innerHTML.trim();if(newText===""||note.text.includes("typeof group=="string"?`PF2E.Item.Weapon.CriticalSpecialization.${group.toLowerCase()}`:substring)},"#cleanText"),__name2(_Migration760SeparateNoteTitle,"Migration760SeparateNoteTitle"),__publicField(_Migration760SeparateNoteTitle,"version",.76);let Migration760SeparateNoteTitle=_Migration760SeparateNoteTitle;const _Migration761ShotRules=class extends MigrationBase{static{__name(this,"_Migration761ShotRules")}constructor(){super(...arguments),__privateAdd(this,_updateEffect),__privateAdd(this,_updateFeat)}async updateItem(source){switch(source.type){case"effect":__privateMethod(this,_updateEffect,updateEffect_fn).call(this,source);break;case"feat":__privateMethod(this,_updateFeat,updateFeat_fn).call(this,source);break}}};_updateEffect=new WeakSet,updateEffect_fn=__name2(function(source){if(source.system.slug==="stance-multishot-stance"){const newRules=[{key:"AdjustModifier",mode:"add",predicate:{all:["double-shot"]},relabel:"{item|name}",selector:"ranged-attack-roll",slug:"double-shot",value:1},{key:"AdjustModifier",mode:"add",predicate:{all:["triple-shot"]},relabel:"{item|name}",selector:"ranged-attack-roll",slug:"double-shot",value:1}];source.system.rules=newRules}},"#updateEffect"),_updateFeat=new WeakSet,updateFeat_fn=__name2(function(source){switch(source.system.slug){case"double-shot":{const newRules=[{domain:"ranged-attack-roll",key:"RollOption",option:"double-shot",toggleable:!0},{key:"FlatModifier",predicate:{all:["double-shot","weapon:reload:0"]},selector:"ranged-attack-roll",slug:"double-shot",value:-2}];source.system.rules=newRules;break}case"triple-shot":{const newRules=[{domain:"ranged-attack-roll",disabledIf:{not:["double-shot"]},key:"RollOption",option:"triple-shot",priority:51,toggleable:!0},{key:"AdjustModifier",mode:"override",predicate:{all:["double-shot","triple-shot"]},relabel:"{item|name}",selector:"ranged-attack-roll",slug:"double-shot",value:-4}];source.system.rules=newRules;break}}},"#updateFeat"),__name2(_Migration761ShotRules,"Migration761ShotRules"),__publicField(_Migration761ShotRules,"version",.761);let Migration761ShotRules=_Migration761ShotRules;const _Migration762UpdateBackgroundItems=class extends MigrationBase{static{__name(this,"_Migration762UpdateBackgroundItems")}async updateItem(source){source.type==="background"&&(source.system.slug==="amnesiac"||source.system.slug==="discarded-duplicate")&&Object.values(source.system.boosts).length!==3&&(source.system.boosts[2]={value:["cha","con","dex","int","str","wis"],selected:null})}};__name2(_Migration762UpdateBackgroundItems,"Migration762UpdateBackgroundItems"),__publicField(_Migration762UpdateBackgroundItems,"version",.762);let Migration762UpdateBackgroundItems=_Migration762UpdateBackgroundItems;const _Migration763RestoreAnimalStrikeOptions=class extends MigrationBase{static{__name(this,"_Migration763RestoreAnimalStrikeOptions")}async updateItem(source){if(source.type!=="feat"||!/^[a-z]+-animal-instinct$/.test(source.system.slug??""))return;const strikeRE=source.system.rules.find(r=>r.key==="Strike"&&!Array.isArray(r.options));strikeRE&&(strikeRE.options=["animal-instinct"])}};__name2(_Migration763RestoreAnimalStrikeOptions,"Migration763RestoreAnimalStrikeOptions"),__publicField(_Migration763RestoreAnimalStrikeOptions,"version",.763);let Migration763RestoreAnimalStrikeOptions=_Migration763RestoreAnimalStrikeOptions;const _Migration764PanacheVivaciousREs=class extends MigrationBase{static{__name(this,"_Migration764PanacheVivaciousREs")}constructor(){super(...arguments),__privateAdd(this,_vivaciousRules)}async updateItem(source){source.type==="feat"&&(source.system.slug==="panache"?source.system.rules=[]:source.system.slug==="vivacious-speed"&&(source.system.rules=__privateGet(this,_vivaciousRules,vivaciousRules_get)))}};_vivaciousRules=new WeakSet,vivaciousRules_get=__name2(function(){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}]}}]},"#vivaciousRules"),__name2(_Migration764PanacheVivaciousREs,"Migration764PanacheVivaciousREs"),__publicField(_Migration764PanacheVivaciousREs,"version",.764);let Migration764PanacheVivaciousREs=_Migration764PanacheVivaciousREs;const _Migration765ChoiceOwnedItemTypes=class extends MigrationBase{static{__name(this,"_Migration765ChoiceOwnedItemTypes")}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"])}};__name2(_Migration765ChoiceOwnedItemTypes,"Migration765ChoiceOwnedItemTypes"),__publicField(_Migration765ChoiceOwnedItemTypes,"version",.765);let Migration765ChoiceOwnedItemTypes=_Migration765ChoiceOwnedItemTypes;const _Migration766WipeURLSources=class extends MigrationBase{static{__name(this,"_Migration766WipeURLSources")}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="")}};__name2(_Migration766WipeURLSources,"Migration766WipeURLSources"),__publicField(_Migration766WipeURLSources,"version",.766);let Migration766WipeURLSources=_Migration766WipeURLSources;const _Migration767ConvertVoluntaryFlaws=class extends MigrationBase{static{__name(this,"_Migration767ConvertVoluntaryFlaws")}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)}};__name2(_Migration767ConvertVoluntaryFlaws,"Migration767ConvertVoluntaryFlaws"),__publicField(_Migration767ConvertVoluntaryFlaws,"version",.767);let Migration767ConvertVoluntaryFlaws=_Migration767ConvertVoluntaryFlaws;const _Migration768AddNewAuras=class extends MigrationBase{static{__name(this,"_Migration768AddNewAuras")}constructor(){super(...arguments),__privateAdd(this,_auraOfLife,{effects:[{affects:"allies",events:["enter"],uuid:"Compendium.pf2e.feat-effects.FPuICuxBLiDaEbDX"}],key:"Aura",radius:15,slug:"aura-of-life"}),__privateAdd(this,_enlightenedPresence,{effects:[{affects:"allies",events:["enter"],uuid:"Compendium.pf2e.feat-effects.XM1AA8z5cHm8sJXM"}],key:"Aura",radius:15,slug:"enlightened-presence",traits:["emotion","mental"]}),__privateAdd(this,_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"]}]),__privateAdd(this,_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=[deepClone(__privateGet(this,_auraOfLife))];break;case"enlightened-presence":source.system.rules=[deepClone(__privateGet(this,_enlightenedPresence))];break;case"eternal-blessing":source.system.rules=deepClone(__privateGet(this,_eternalBlessing));break;case"marshal-dedication":source.system.rules=[deepClone(__privateGet(this,_marshalsAura))];break}}};_auraOfLife=new WeakMap,_enlightenedPresence=new WeakMap,_eternalBlessing=new WeakMap,_marshalsAura=new WeakMap,__name2(_Migration768AddNewAuras,"Migration768AddNewAuras"),__publicField(_Migration768AddNewAuras,"version",.768);let Migration768AddNewAuras=_Migration768AddNewAuras;const _Migration769NoUniversalistFocusPool=class extends MigrationBase{static{__name(this,"_Migration769NoUniversalistFocusPool")}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"]})}}};__name2(_Migration769NoUniversalistFocusPool,"Migration769NoUniversalistFocusPool"),__publicField(_Migration769NoUniversalistFocusPool,"version",.769);let Migration769NoUniversalistFocusPool=_Migration769NoUniversalistFocusPool;const _Migration770REDataToSystem=class extends MigrationBase{static{__name(this,"_Migration770REDataToSystem")}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."))}};__name2(_Migration770REDataToSystem,"Migration770REDataToSystem"),__publicField(_Migration770REDataToSystem,"version",.77);let Migration770REDataToSystem=_Migration770REDataToSystem;const _Migration771SpellVariantsToSystem=class extends MigrationBase{static{__name(this,"_Migration771SpellVariantsToSystem")}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)}}}};__name2(_Migration771SpellVariantsToSystem,"Migration771SpellVariantsToSystem"),__publicField(_Migration771SpellVariantsToSystem,"version",.771);let Migration771SpellVariantsToSystem=_Migration771SpellVariantsToSystem;const _Migration772V10EmbeddedSpellData=class extends MigrationBase{static{__name(this,"_Migration772V10EmbeddedSpellData")}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)}}};__name2(_Migration772V10EmbeddedSpellData,"Migration772V10EmbeddedSpellData"),__publicField(_Migration772V10EmbeddedSpellData,"version",.772);let Migration772V10EmbeddedSpellData=_Migration772V10EmbeddedSpellData;const _Migration773ReligiousSymbolUsage=class extends MigrationBase{static{__name(this,"_Migration773ReligiousSymbolUsage")}async updateItem(source){source.type==="equipment"&&source.system.slug?.startsWith("religious-symbol")&&(source.system.usage.value="held-in-one-hand")}};__name2(_Migration773ReligiousSymbolUsage,"Migration773ReligiousSymbolUsage"),__publicField(_Migration773ReligiousSymbolUsage,"version",.773);let Migration773ReligiousSymbolUsage=_Migration773ReligiousSymbolUsage;const _Migration774UnpersistCraftingEntries=class extends MigrationBase{static{__name(this,"_Migration774UnpersistCraftingEntries")}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}`)}))}}};__name2(_Migration774UnpersistCraftingEntries,"Migration774UnpersistCraftingEntries"),__publicField(_Migration774UnpersistCraftingEntries,"version",.774);let Migration774UnpersistCraftingEntries=_Migration774UnpersistCraftingEntries;const _Migration775AgileFinesseRanged=class extends MigrationBase{static{__name(this,"_Migration775AgileFinesseRanged")}constructor(){super(...arguments),__privateAdd(this,_findDamageDiceRE),__privateAdd(this,_isClassFeature4),__privateAdd(this,_athleticStrategist),__privateAdd(this,_deviseAStratagem),__privateAdd(this,_ruffianPredicate),__privateAdd(this,_sneakAttackPredicate)}async updateItem(source){switch(source.type){case"action":{if(source.system.slug==="sneak-attack"){const damageDiceRE=__privateMethod(this,_findDamageDiceRE,findDamageDiceRE_fn).call(this,source);isObject(damageDiceRE)&&damageDiceRE.predicate&&Array.isArray(damageDiceRE.predicate.all)&&damageDiceRE.predicate.all.some(s=>s instanceof Object&&"or"in s)&&(damageDiceRE.predicate=__privateGet(this,_sneakAttackPredicate,sneakAttackPredicate_get))}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]=__privateGet(this,_athleticStrategist,athleticStrategist_get));break}case"devise-a-stratagem":{const index=source.system.rules.findIndex(r=>r.key==="FlatModifier");index!==-1&&(source.system.rules[index]=__privateGet(this,_deviseAStratagem,deviseAStratagem_get));break}case"ruffian":{const damageDiceRE=__privateMethod(this,_findDamageDiceRE,findDamageDiceRE_fn).call(this,source);damageDiceRE&&(damageDiceRE.predicate=__privateGet(this,_ruffianPredicate,ruffianPredicate_get));break}case"shadow-sneak-attack":case"sneak-attack":case"sneak-attacker":{const damageDiceRE=__privateMethod(this,_findDamageDiceRE,findDamageDiceRE_fn).call(this,source);if(damageDiceRE){const predicate=__privateGet(this,_sneakAttackPredicate,sneakAttackPredicate_get);__privateMethod(this,_isClassFeature4,isClassFeature_fn4).call(this,source)&&predicate.all?.unshift("class:rogue"),damageDiceRE.predicate=predicate}break}}}}};_findDamageDiceRE=new WeakSet,findDamageDiceRE_fn=__name2(function(source){return source.system.rules.find(r=>r.key==="DamageDice")??null},"#findDamageDiceRE"),_isClassFeature4=new WeakSet,isClassFeature_fn4=__name2(function(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"},"#isClassFeature"),_athleticStrategist=new WeakSet,athleticStrategist_get=__name2(function(){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"}},"#athleticStrategist"),_deviseAStratagem=new WeakSet,deviseAStratagem_get=__name2(function(){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"}},"#deviseAStratagem"),_ruffianPredicate=new WeakSet,ruffianPredicate_get=__name2(function(){return{all:["target:condition:flat-footed","weapon:category:simple",{nor:[{and:["weapon:ranged",{not:"weapon:thrown-melee"}]},"weapon:trait:agile","weapon:trait:finesse"]}]}},"#ruffianPredicate"),_sneakAttackPredicate=new WeakSet,sneakAttackPredicate_get=__name2(function(){return{all:["target:condition:flat-footed"],any:["weapon:trait:agile","weapon:trait:finesse",{and:["weapon:ranged",{not:"weapon:thrown-melee"}]}]}},"#sneakAttackPredicate"),__name2(_Migration775AgileFinesseRanged,"Migration775AgileFinesseRanged"),__publicField(_Migration775AgileFinesseRanged,"version",.775);let Migration775AgileFinesseRanged=_Migration775AgileFinesseRanged;const _Migration776SlugifyConditionOverrides=class extends MigrationBase{static{__name(this,"_Migration776SlugifyConditionOverrides")}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)))}};__name2(_Migration776SlugifyConditionOverrides,"Migration776SlugifyConditionOverrides"),__publicField(_Migration776SlugifyConditionOverrides,"version",.776);let Migration776SlugifyConditionOverrides=_Migration776SlugifyConditionOverrides;const _Migration777HandOfTheApprentice=class extends MigrationBase{static{__name(this,"_Migration777HandOfTheApprentice")}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]}}};__name2(_Migration777HandOfTheApprentice,"Migration777HandOfTheApprentice"),__publicField(_Migration777HandOfTheApprentice,"version",.777);let Migration777HandOfTheApprentice=_Migration777HandOfTheApprentice;const _Migration778RenameRetiredPackRefs=class extends MigrationBase{static{__name(this,"_Migration778RenameRetiredPackRefs")}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)}};__name2(_Migration778RenameRetiredPackRefs,"Migration778RenameRetiredPackRefs"),__publicField(_Migration778RenameRetiredPackRefs,"version",.778);let Migration778RenameRetiredPackRefs=_Migration778RenameRetiredPackRefs;const _Migration779EliteWeak=class extends MigrationBase{static{__name(this,"_Migration779EliteWeak")}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"))}};__name2(_Migration779EliteWeak,"Migration779EliteWeak"),__publicField(_Migration779EliteWeak,"version",.779);let Migration779EliteWeak=_Migration779EliteWeak;const _Migration780NumifySpeeds=class extends MigrationBase{static{__name(this,"_Migration780NumifySpeeds")}constructor(){super(...arguments),__privateAdd(this,_updateSpeed)}async updateActor(source){if(source.type!=="npc"&&source.type!=="character")return;const speeds=source.system.attributes.speed;speeds.value=__privateMethod(this,_updateSpeed,updateSpeed_fn).call(this,speeds.value),Array.isArray(speeds.otherSpeeds)||(speeds.otherSpeeds=[]);for(const movementType of speeds.otherSpeeds)movementType.value=__privateMethod(this,_updateSpeed,updateSpeed_fn).call(this,movementType.value)}};_updateSpeed=new WeakSet,updateSpeed_fn=__name2(function(speed){const numifiedValue=parseInt(String(speed),10);return Number.isNaN(numifiedValue)?25:numifiedValue},"#updateSpeed"),__name2(_Migration780NumifySpeeds,"Migration780NumifySpeeds"),__publicField(_Migration780NumifySpeeds,"version",.78);let Migration780NumifySpeeds=_Migration780NumifySpeeds;const _Migration781SuppressNoCrowbar=class extends MigrationBase{static{__name(this,"_Migration781SuppressNoCrowbar")}constructor(){super(...arguments),__privateAdd(this,_suppressNoCrowbar)}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(__privateGet(this,_suppressNoCrowbar,suppressNoCrowbar_get))}};_suppressNoCrowbar=new WeakSet,suppressNoCrowbar_get=__name2(function(){return{key:"AdjustModifier",selector:"athletics",slug:"no-crowbar",suppress:!0}},"#suppressNoCrowbar"),__name2(_Migration781SuppressNoCrowbar,"Migration781SuppressNoCrowbar"),__publicField(_Migration781SuppressNoCrowbar,"version",.781);let Migration781SuppressNoCrowbar=_Migration781SuppressNoCrowbar;const _Migration782UnnestActorTraits=class extends MigrationBase{static{__name(this,"_Migration782UnnestActorTraits")}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)}};__name2(_Migration782UnnestActorTraits,"Migration782UnnestActorTraits"),__publicField(_Migration782UnnestActorTraits,"version",.782);let Migration782UnnestActorTraits=_Migration782UnnestActorTraits;const _Migration783RemoveClassSkillAELikes=class extends MigrationBase{static{__name(this,"_Migration783RemoveClassSkillAELikes")}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)))}};__name2(_Migration783RemoveClassSkillAELikes,"Migration783RemoveClassSkillAELikes"),__publicField(_Migration783RemoveClassSkillAELikes,"version",.783);let Migration783RemoveClassSkillAELikes=_Migration783RemoveClassSkillAELikes;const _Migration784CompBrowserPackSetting=class extends MigrationBase{static{__name(this,"_Migration784CompBrowserPackSetting")}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())}}};__name2(_Migration784CompBrowserPackSetting,"Migration784CompBrowserPackSetting"),__publicField(_Migration784CompBrowserPackSetting,"version",.784);let Migration784CompBrowserPackSetting=_Migration784CompBrowserPackSetting;const _Migration785ABCKitItemUUIDs=class extends MigrationBase{static{__name(this,"_Migration785ABCKitItemUUIDs")}constructor(){super(...arguments),__privateAdd(this,_convertToUUIDs)}async updateItem(source){switch(source.type){case"ancestry":case"background":case"class":case"kit":__privateMethod(this,_convertToUUIDs,convertToUUIDs_fn).call(this,Object.values(source.system.items))}}};_convertToUUIDs=new WeakSet,convertToUUIDs_fn=__name2(function(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&&__privateMethod(this,_convertToUUIDs,convertToUUIDs_fn).call(this,Object.values(reference.items))},"#convertToUUIDs"),__name2(_Migration785ABCKitItemUUIDs,"Migration785ABCKitItemUUIDs"),__publicField(_Migration785ABCKitItemUUIDs,"version",.785);let Migration785ABCKitItemUUIDs=_Migration785ABCKitItemUUIDs;const _Migration786RemoveIdentifiedData=class extends MigrationBase{static{__name(this,"_Migration786RemoveIdentifiedData")}async updateItem(source){if(!isPhysicalData(source))return;const identification=source.system.identification??{};identification.identified&&(identification["-=identified"]=null)}};__name2(_Migration786RemoveIdentifiedData,"Migration786RemoveIdentifiedData"),__publicField(_Migration786RemoveIdentifiedData,"version",.786);let Migration786RemoveIdentifiedData=_Migration786RemoveIdentifiedData;const _Migration787ResolvablesToSystem=class extends MigrationBase{static{__name(this,"_Migration787ResolvablesToSystem")}async updateItem(source){source.system=recursiveReplaceString(source.system,value=>value.replace(/@(weapon|spell)\.data\.data./g,"@$1.system.").replace(/@(weapon|spell)\.data./g,"@$1."))}};__name2(_Migration787ResolvablesToSystem,"Migration787ResolvablesToSystem"),__publicField(_Migration787ResolvablesToSystem,"version",.787);let Migration787ResolvablesToSystem=_Migration787ResolvablesToSystem;const _Migration788UpdateTanglefootBags=class extends MigrationBase{static{__name(this,"_Migration788UpdateTanglefootBags")}constructor(){super(...arguments),__privateAdd(this,_getRules)}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=__privateMethod(this,_getRules,getRules_fn).call(this,"Lesser");return}case"tanglefoot-bag-moderate":{source.system.rules=__privateMethod(this,_getRules,getRules_fn).call(this,"Moderate");return}case"tanglefoot-bag-greater":{source.system.rules=__privateMethod(this,_getRules,getRules_fn).call(this,"Greater");return}case"tanglefoot-bag-major":{source.system.rules=__privateMethod(this,_getRules,getRules_fn).call(this,"Major");return}}}};_getRules=new WeakSet,getRules_fn=__name2(function(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"}]},"#getRules"),__name2(_Migration788UpdateTanglefootBags,"Migration788UpdateTanglefootBags"),__publicField(_Migration788UpdateTanglefootBags,"version",.788);let Migration788UpdateTanglefootBags=_Migration788UpdateTanglefootBags;const _Migration789UpdatePreciseStrike=class extends MigrationBase{static{__name(this,"_Migration789UpdatePreciseStrike")}constructor(){super(...arguments),__privateAdd(this,_preciseStrikeRules),__privateAdd(this,_finishingPrecisionRules)}async updateItem(source){if(source.type==="feat"){if(source.system.slug==="precise-strike")source.system.rules=__privateGet(this,_preciseStrikeRules,preciseStrikeRules_get);else if(source.system.slug==="finishing-precision"){const rules=source.system.rules.filter(r=>r.key==="GrantItem");source.system.rules=[...rules,...__privateGet(this,_finishingPrecisionRules,finishingPrecisionRules_get)]}}}};_preciseStrikeRules=new WeakSet,preciseStrikeRules_get=__name2(function(){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}}]}}]},"#preciseStrikeRules"),_finishingPrecisionRules=new WeakSet,finishingPrecisionRules_get=__name2(function(){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"}]},"#finishingPrecisionRules"),__name2(_Migration789UpdatePreciseStrike,"Migration789UpdatePreciseStrike"),__publicField(_Migration789UpdatePreciseStrike,"version",.789);let Migration789UpdatePreciseStrike=_Migration789UpdatePreciseStrike;const _Migration790MultipleClassDCs=class extends MigrationBase{static{__name(this,"_Migration790MultipleClassDCs")}constructor(){super(...arguments),__privateAdd(this,_isClassFeature5),__privateAdd(this,_otherClassDCs,new Map([["call-implement","thaumaturge"],["eerie-proclamation","ranger"],["stunning-fist","monk"],["ring-bell","thaumaturge"]]))}async updateActor(source){if(source.type!=="character")return;const customModifiers=source.system.customModifiers??{};customModifiers?.class&&(customModifiers["-=class"]=null)}async updateItem(source){if(__privateMethod(this,_isClassFeature5,isClassFeature_fn5).call(this,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(__privateGet(this,_otherClassDCs).has(itemSlug)){const oldClassDCPattern=/\bsystem\.attributes\.classDC\b/,classSlug=__privateGet(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}`)}}};_otherClassDCs=new WeakMap,_isClassFeature5=new WeakSet,isClassFeature_fn5=__name2(function(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"},"#isClassFeature"),__name2(_Migration790MultipleClassDCs,"Migration790MultipleClassDCs"),__publicField(_Migration790MultipleClassDCs,"version",.79);let Migration790MultipleClassDCs=_Migration790MultipleClassDCs;const _Migration791RuffianHands=class extends MigrationBase{static{__name(this,"_Migration791RuffianHands")}constructor(){super(...arguments),__privateAdd(this,_critSpec),__privateAdd(this,_hands)}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(__privateGet(this,_critSpec,critSpec_get));break}case"healing-hands":{const hands=__privateGet(this,_hands,hands_get);hands.predicate={all:["item:slug:heal"]},source.system.rules=[hands];break}case"harming-hands":{const hands=__privateGet(this,_hands,hands_get);hands.predicate={all:["item:slug:harm"]},source.system.rules=[hands];break}}}};_critSpec=new WeakSet,critSpec_get=__name2(function(){return{key:"CriticalSpecialization",predicate:{all:["target:condition:flat-footed","weapon:category:simple",{lte:["weapon:damage:die:faces",8]}]}}},"#critSpec"),_hands=new WeakSet,hands_get=__name2(function(){return{key:"DamageDice",override:{dieSize:"d10"},selector:"spell-damage"}},"#hands"),__name2(_Migration791RuffianHands,"Migration791RuffianHands"),__publicField(_Migration791RuffianHands,"version",.791);let Migration791RuffianHands=_Migration791RuffianHands;const _Migration792RemoveTokenAELikes=class extends MigrationBase{static{__name(this,"_Migration792RemoveTokenAELikes")}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)}};__name2(_Migration792RemoveTokenAELikes,"Migration792RemoveTokenAELikes"),__publicField(_Migration792RemoveTokenAELikes,"version",.792);let Migration792RemoveTokenAELikes=_Migration792RemoveTokenAELikes;const _Migration793MakePredicatesArrays=class extends MigrationBase{static{__name(this,"_Migration793MakePredicatesArrays")}constructor(){super(...arguments),__privateAdd(this,_convertLegacyData),__privateAdd(this,_isOldRawPredicate),__privateAdd(this,_isArrayChoiceSet),__privateAdd(this,_isObjectChoiceSet)}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(__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.predicate)&&(rule.predicate=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.predicate)),__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.definition)&&(rule.definition=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.definition)),__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.allowedDrops)&&(rule.allowedDrops={label:rule.allowedDrops.label??void 0,predicate:__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.allowedDrops)}),__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.predicate)&&(rule.predicate=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.predicate)),__privateMethod(this,_isArrayChoiceSet,isArrayChoiceSet_fn).call(this,rule))for(const choice of rule.choices)__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,choice.predicate)&&(choice.predicate=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,choice.predicate));else __privateMethod(this,_isObjectChoiceSet,isObjectChoiceSet_fn).call(this,rule)?(__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.choices.predicate)&&(rule.choices.predicate=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.choices.predicate)),__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.choices.postFilter)&&(rule.choices.postFilter=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.choices.postFilter))):__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.craftableItems)&&(rule.craftableItems=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.craftableItems));__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.disabledIf)&&(rule.disabledIf=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.disabledIf))}}};_convertLegacyData=new WeakSet,convertLegacyData_fn=__name2(function(predicate){const keys2=Object.keys(predicate);return keys2.length===0?[]:keys2.length===1&&Array.isArray(predicate.all)?deepClone(predicate.all):keys2.length===1&&Array.isArray(predicate.any)&&predicate.any.length===1?deepClone(predicate.any):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())},"#convertLegacyData"),_isOldRawPredicate=new WeakSet,isOldRawPredicate_fn=__name2(function(predicate){return!predicate||Array.isArray(predicate)||isObject(predicate)&&Array.isArray(predicate.predicate)?!1:predicate instanceof Object},"#isOldRawPredicate"),_isArrayChoiceSet=new WeakSet,isArrayChoiceSet_fn=__name2(function(rule){return rule.key==="ChoiceSet"&&Array.isArray(rule.choices)},"#isArrayChoiceSet"),_isObjectChoiceSet=new WeakSet,isObjectChoiceSet_fn=__name2(function(rule){return rule.key==="ChoiceSet"&&isObject(rule.choices)&&!Array.isArray(rule.choices)},"#isObjectChoiceSet"),__name2(_Migration793MakePredicatesArrays,"Migration793MakePredicatesArrays"),__publicField(_Migration793MakePredicatesArrays,"version",.793);let Migration793MakePredicatesArrays=_Migration793MakePredicatesArrays;const _Migration794AddWildShapeChoices=class extends MigrationBase{static{__name(this,"_Migration794AddWildShapeChoices")}constructor(){super(...arguments),__privateAdd(this,_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&&__privateGet(this,_shapeFeats).has(sourceId)){const fromPack=await fromUuid(sourceId);fromPack instanceof FeatPF2e&&(source.system.rules=fromPack.toObject().system.rules)}}};_shapeFeats=new WeakMap,__name2(_Migration794AddWildShapeChoices,"Migration794AddWildShapeChoices"),__publicField(_Migration794AddWildShapeChoices,"version",.794);let Migration794AddWildShapeChoices=_Migration794AddWildShapeChoices;const _Migration795CleanupFlatFootedToggle=class extends MigrationBase{static{__name(this,"_Migration795CleanupFlatFootedToggle")}constructor(){super(...arguments),__privateAdd(this,_flatFootedToggle),__privateAdd(this,_isFlatFootedToggle)}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=>__privateMethod(this,_isFlatFootedToggle,isFlatFootedToggle_fn).call(this,r))||source.system.rules.push(__privateGet(this,_flatFootedToggle,flatFootedToggle_get))}}};_flatFootedToggle=new WeakSet,flatFootedToggle_get=__name2(function(){return{key:"RollOption",domain:"all",label:"PF2E.SpecificRule.TOTMToggle.FlatFooted",option:"target:condition:flat-footed",toggleable:"totm"}},"#flatFootedToggle"),_isFlatFootedToggle=new WeakSet,isFlatFootedToggle_fn=__name2(function(rule){return rule.key==="RollOption"&&rule.option==="target:condition:flat-footed"&&rule.toggleable==="totm"},"#isFlatFootedToggle"),__name2(_Migration795CleanupFlatFootedToggle,"Migration795CleanupFlatFootedToggle"),__publicField(_Migration795CleanupFlatFootedToggle,"version",.795);let Migration795CleanupFlatFootedToggle=_Migration795CleanupFlatFootedToggle;const _Migration796ItemGrantsToObjects=class extends MigrationBase{static{__name(this,"_Migration796ItemGrantsToObjects")}constructor(){super(...arguments),__privateAdd(this,_convertToEntry),__privateAdd(this,_modifyFlag)}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]=__privateMethod(this,_convertToEntry,convertToEntry_fn).call(this,source,item,grant);if(flag!==null){const modifiedFlag=__privateMethod(this,_modifyFlag,modifyFlag_fn).call(this,grantsObject,flag);grantsObject[modifiedFlag]=grantSource}}return grantsObject},{}))}}};_convertToEntry=new WeakSet,convertToEntry_fn=__name2(function(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]},"#convertToEntry"),_modifyFlag=new WeakSet,modifyFlag_fn=__name2(function(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}`},"#modifyFlag"),__name2(_Migration796ItemGrantsToObjects,"Migration796ItemGrantsToObjects"),__publicField(_Migration796ItemGrantsToObjects,"version",.796);let Migration796ItemGrantsToObjects=_Migration796ItemGrantsToObjects;const _Migration797MetagameSetting=class extends MigrationBase{static{__name(this,"_Migration797MetagameSetting")}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)}}}};__name2(_Migration797MetagameSetting,"Migration797MetagameSetting"),__publicField(_Migration797MetagameSetting,"version",.797);let Migration797MetagameSetting=_Migration797MetagameSetting;const _Migration798WeaponToItemStatements=class extends MigrationBase{static{__name(this,"_Migration798WeaponToItemStatements")}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:")))}}};__name2(_Migration798WeaponToItemStatements,"Migration798WeaponToItemStatements"),__publicField(_Migration798WeaponToItemStatements,"version",.798);let Migration798WeaponToItemStatements=_Migration798WeaponToItemStatements;const _Migration799RMRecallKnowledgeDuplicates=class extends MigrationBase{static{__name(this,"_Migration799RMRecallKnowledgeDuplicates")}constructor(){super(...arguments),__privateAdd(this,_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(__privateGet(this,_oldIdsPattern),"pf2e.actionspf2e.1OagaWtBpVXExToo")}};_oldIdsPattern=new WeakMap,__name2(_Migration799RMRecallKnowledgeDuplicates,"Migration799RMRecallKnowledgeDuplicates"),__publicField(_Migration799RMRecallKnowledgeDuplicates,"version",.799);let Migration799RMRecallKnowledgeDuplicates=_Migration799RMRecallKnowledgeDuplicates;const _Migration800SelfEffectPanacheRage=class extends MigrationBase{static{__name(this,"_Migration800SelfEffectPanacheRage")}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")))}};__name2(_Migration800SelfEffectPanacheRage,"Migration800SelfEffectPanacheRage"),__publicField(_Migration800SelfEffectPanacheRage,"version",.8);let Migration800SelfEffectPanacheRage=_Migration800SelfEffectPanacheRage;const _Migration801ColorDarkvision=class extends MigrationBase{static{__name(this,"_Migration801ColorDarkvision")}constructor(){super(...arguments),__privateAdd(this,_colorDarkvision)}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(__privateGet(this,_colorDarkvision,colorDarkvision_get))}};_colorDarkvision=new WeakSet,colorDarkvision_get=__name2(function(){return{key:"ActiveEffectLike",path:"flags.pf2e.colorDarkvision",mode:"override",value:!0}},"#colorDarkvision"),__name2(_Migration801ColorDarkvision,"Migration801ColorDarkvision"),__publicField(_Migration801ColorDarkvision,"version",.801);let Migration801ColorDarkvision=_Migration801ColorDarkvision;const _Migration802StripFeatActionCategory=class extends MigrationBase{static{__name(this,"_Migration802StripFeatActionCategory")}async updateItem(source){if(source.type!=="feat")return;const feat=source.system;feat.actionCategory&&(delete feat.actionCategory,feat["-=actionCategory"]=null)}};__name2(_Migration802StripFeatActionCategory,"Migration802StripFeatActionCategory"),__publicField(_Migration802StripFeatActionCategory,"version",.802);let Migration802StripFeatActionCategory=_Migration802StripFeatActionCategory;const _Migration803NormalizeSpellArea=class extends MigrationBase{static{__name(this,"_Migration803NormalizeSpellArea")}constructor(){super(...arguments),__privateAdd(this,_isAreaType),__privateAdd(this,_hasDetails),__privateAdd(this,_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&&__privateMethod(this,_isAreaType,isAreaType_fn).call(this,area.areaType)&&(area.type=area.areaType,delete area.areaType,area["-=areaType"]=null)),area?.value&&__privateMethod(this,_isAreaType,isAreaType_fn).call(this,area.type)||(source.system.area=null),"areasize"in source.system&&isObject(source.system.areasize)&&(__privateMethod(this,_hasDetails,hasDetails_fn).call(this,source.system.areasize.value)&&area&&(area.details=source.system.areasize.value),delete source.system.areasize,source.system["-=areasize"]=null)}};_AREA_TYPES=new WeakMap,_isAreaType=new WeakSet,isAreaType_fn=__name2(function(areaType){return typeof areaType=="string"&&areaType.length>0&&__privateGet(this,_AREA_TYPES).has(areaType)},"#isAreaType"),_hasDetails=new WeakSet,hasDetails_fn=__name2(function(details){return typeof details=="string"&&details.trim().length>0&&!/^\d+-foot (?:burst|cone|cube|emanation|line|square)$/.test(details)},"#hasDetails"),__name2(_Migration803NormalizeSpellArea,"Migration803NormalizeSpellArea"),__publicField(_Migration803NormalizeSpellArea,"version",.803);let Migration803NormalizeSpellArea=_Migration803NormalizeSpellArea;const _Migration804RemoveConsumableProperties=class extends MigrationBase{static{__name(this,"_Migration804RemoveConsumableProperties")}async updateItem(source){if(source.type!=="consumable")return;const system=source.system;system.uses&&(delete system.uses,system["-=uses"]=null),system.autoUse&&(delete system.autoUse,system["-=autoUse"]=null),"_deprecated"in system.charges&&(delete system.charges._deprecated,system.charges["-=deprecated"]=null),"_deprecated"in system.consume&&(delete system.consume._deprecated,system.consume["-=deprecated"]=null)}};__name2(_Migration804RemoveConsumableProperties,"Migration804RemoveConsumableProperties"),__publicField(_Migration804RemoveConsumableProperties,"version",.804);let Migration804RemoveConsumableProperties=_Migration804RemoveConsumableProperties;const _Migration805InlineDamageRolls=class extends MigrationBase{static{__name(this,"_Migration805InlineDamageRolls")}constructor(){super(...arguments),__privateAdd(this,_updateDamageFormula),__privateAdd(this,_pattern,/\[\[\/r .+?\]\]\]?(?:\{[^}]+\})?/g),__privateAdd(this,_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")})())}async updateActor(source){source.system=recursiveReplaceString(source.system,s=>__privateMethod(this,_updateDamageFormula,updateDamageFormula_fn).call(this,s))}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>__privateMethod(this,_updateDamageFormula,updateDamageFormula_fn).call(this,s))}async updateJournalEntry(source){source.pages=recursiveReplaceString(source.pages,s=>__privateMethod(this,_updateDamageFormula,updateDamageFormula_fn).call(this,s))}};_pattern=new WeakMap,_damageTypeLabelPattern=new WeakMap,_updateDamageFormula=new WeakSet,updateDamageFormula_fn=__name2(function(text){const skipStrings=["splash","precision","persistent","d20","#"];return text.replace(__privateGet(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&&!__privateGet(this,_damageTypeLabelPattern).test(customLabel)?`${reassembled}{${customLabel}}`:labelEndsWithDamage?`${reassembled} damage`:reassembled})},"#updateDamageFormula"),__name2(_Migration805InlineDamageRolls,"Migration805InlineDamageRolls"),__publicField(_Migration805InlineDamageRolls,"version",.805);let Migration805InlineDamageRolls=_Migration805InlineDamageRolls;const _Migration806TorchImprovisedOtherTags=class extends MigrationBase{static{__name(this,"_Migration806TorchImprovisedOtherTags")}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"])}}};__name2(_Migration806TorchImprovisedOtherTags,"Migration806TorchImprovisedOtherTags"),__publicField(_Migration806TorchImprovisedOtherTags,"version",.806);let Migration806TorchImprovisedOtherTags=_Migration806TorchImprovisedOtherTags;const _Migration807RMActivatedEffectFields=class extends MigrationBase{static{__name(this,"_Migration807RMActivatedEffectFields")}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)}};__name2(_Migration807RMActivatedEffectFields,"Migration807RMActivatedEffectFields"),__publicField(_Migration807RMActivatedEffectFields,"version",.807);let Migration807RMActivatedEffectFields=_Migration807RMActivatedEffectFields;const _Migration808CountDamageDice=class extends MigrationBase{static{__name(this,"_Migration808CountDamageDice")}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>s.replace(/\(?\b1\s*\+\s*@(item|weapon)(?:.system)?.runes.striking\)?/g,"@$1.system.damage.dice"))}};__name2(_Migration808CountDamageDice,"Migration808CountDamageDice"),__publicField(_Migration808CountDamageDice,"version",.808);let Migration808CountDamageDice=_Migration808CountDamageDice;const _Migration809AutomatonEnhancements=class extends MigrationBase{static{__name(this,"_Migration809AutomatonEnhancements")}constructor(){super(...arguments),__privateAdd(this,_automatonEnhancements)}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(__privateGet(this,_automatonEnhancements,automatonEnhancements_get))}};_automatonEnhancements=new WeakSet,automatonEnhancements_get=__name2(function(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.automaton.enhancements",priority:10,value:{greater:[],lesser:[]}}},"#automatonEnhancements"),__name2(_Migration809AutomatonEnhancements,"Migration809AutomatonEnhancements"),__publicField(_Migration809AutomatonEnhancements,"version",.809);let Migration809AutomatonEnhancements=_Migration809AutomatonEnhancements;const _Migration810LootDescriptionValue=class extends MigrationBase{static{__name(this,"_Migration810LootDescriptionValue")}async updateActor(source){if(source.type==="loot"){const details=source.system.details;details.description instanceof Object&&(details.description=String(details.description.value??""))}}};__name2(_Migration810LootDescriptionValue,"Migration810LootDescriptionValue"),__publicField(_Migration810LootDescriptionValue,"version",.81);let Migration810LootDescriptionValue=_Migration810LootDescriptionValue;const _Migration811InlineDamageRollsPersistent=class extends MigrationBase{static{__name(this,"_Migration811InlineDamageRollsPersistent")}constructor(){super(...arguments),__privateAdd(this,_updateDamageFormula2),__privateAdd(this,_conditionPattern,/(?<=\]\]|})(\s*@(?:UUID|Compendium)\[(?:Compendium\.)?pf2e\.conditionitems\.(?:Persistent Damage|lDVqvLKA6eF3Df60)\]\{[^}]+})/g),__privateAdd(this,_pattern2,/\[\[\/r ([^[\]]+(\[.*?\])?)\]\](\{\dd\d[^{}]*\})?/g)}async updateActor(source){source.system=recursiveReplaceString(source.system,s=>__privateMethod(this,_updateDamageFormula2,updateDamageFormula_fn2).call(this,s))}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>__privateMethod(this,_updateDamageFormula2,updateDamageFormula_fn2).call(this,s))}async updateJournalEntry(source){source.pages=recursiveReplaceString(source.pages,s=>__privateMethod(this,_updateDamageFormula2,updateDamageFormula_fn2).call(this,s))}};_conditionPattern=new WeakMap,_pattern2=new WeakMap,_updateDamageFormula2=new WeakSet,updateDamageFormula_fn2=__name2(function(text){return text.replace(__privateGet(this,_conditionPattern)," damage").replace(__privateGet(this,_pattern2),(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})},"#updateDamageFormula"),__name2(_Migration811InlineDamageRollsPersistent,"Migration811InlineDamageRollsPersistent"),__publicField(_Migration811InlineDamageRollsPersistent,"version",.811);let Migration811InlineDamageRollsPersistent=_Migration811InlineDamageRollsPersistent;const _Migration812RestructureIWR=class extends MigrationBase{static{__name(this,"_Migration812RestructureIWR")}constructor(){super(...arguments),__privateAdd(this,_getWR),__privateAdd(this,_parseExceptions),__privateAdd(this,_normalizeType),__privateAdd(this,_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"})}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(oldData)&&"value"in oldData&&Array.isArray(oldData.value)&&oldData.value.length>0){const immunities=oldData.value.map(i=>__privateMethod(this,_normalizeType,normalizeType_fn).call(this,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=__privateMethod(this,_getWR,getWR_fn).call(this,oldData,WEAKNESS_TYPES).map(data=>{const weakness=pick(data,["type","value"]),exceptions=__privateMethod(this,_parseExceptions,parseExceptions_fn).call(this,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=__privateMethod(this,_getWR,getWR_fn).call(this,oldData,RESISTANCE_TYPES).map(data=>{const resistance=pick(data,["type","value"]),parsed=__privateMethod(this,_parseExceptions,parseExceptions_fn).call(this,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:__privateMethod(this,_normalizeType,normalizeType_fn).call(this,rule.type),typeof rule.except=="string"){const exceptions=__privateMethod(this,_parseExceptions,parseExceptions_fn).call(this,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:__privateMethod(this,_normalizeType,normalizeType_fn).call(this,rule.value)}};_getWR=new WeakSet,getWR_fn=__name2(function(maybeWR,typeSet){return maybeWR.filter(r=>isObject(r)&&typeof r.type=="string"&&typeof r.value=="number").map(wr=>(wr.type=__privateMethod(this,_normalizeType,normalizeType_fn).call(this,wr.type),wr.value=Math.abs(wr.value),wr)).filter(r=>setHasElement(typeSet,r.type))},"#getWR"),_oldENmappings=new WeakMap,_parseExceptions=new WeakSet,parseExceptions_fn=__name2(function(text){const normalized=(__privateGet(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}},"#parseExceptions"),_normalizeType=new WeakSet,normalizeType_fn=__name2(function(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)}},"#normalizeType"),__name2(_Migration812RestructureIWR,"Migration812RestructureIWR"),__publicField(_Migration812RestructureIWR,"version",.812);let Migration812RestructureIWR=_Migration812RestructureIWR;const _Migration813NormalizeColdIron=class extends MigrationBase{static{__name(this,"_Migration813NormalizeColdIron")}constructor(){super(...arguments),__privateAdd(this,_updateWeaponMaterialData),__privateAdd(this,_updateChoiceSet)}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"&&__privateMethod(this,_updateWeaponMaterialData,updateWeaponMaterialData_fn).call(this,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)__privateMethod(this,_updateChoiceSet,updateChoiceSet_fn).call(this,choiceSet)}};_updateWeaponMaterialData=new WeakSet,updateWeaponMaterialData_fn=__name2(function(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)},"#updateWeaponMaterialData"),_updateChoiceSet=new WeakSet,updateChoiceSet_fn=__name2(function(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")},"#updateChoiceSet"),__name2(_Migration813NormalizeColdIron,"Migration813NormalizeColdIron"),__publicField(_Migration813NormalizeColdIron,"version",.813);let Migration813NormalizeColdIron=_Migration813NormalizeColdIron;const _Migration814CalculatedExpandedSplash=class extends MigrationBase{static{__name(this,"_Migration814CalculatedExpandedSplash")}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}}}};__name2(_Migration814CalculatedExpandedSplash,"Migration814CalculatedExpandedSplash"),__publicField(_Migration814CalculatedExpandedSplash,"version",.814);let Migration814CalculatedExpandedSplash=_Migration814CalculatedExpandedSplash;const _Migration815ConsumableDataCleanup=class extends MigrationBase{static{__name(this,"_Migration815ConsumableDataCleanup")}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)}}};__name2(_Migration815ConsumableDataCleanup,"Migration815ConsumableDataCleanup"),__publicField(_Migration815ConsumableDataCleanup,"version",.815);let Migration815ConsumableDataCleanup=_Migration815ConsumableDataCleanup;const _Migration816AlchemistResearchFields=class extends MigrationBase{static{__name(this,"_Migration816AlchemistResearchFields")}constructor(){super(...arguments),__privateAdd(this,_bomberSetFlags),__privateAdd(this,_chirurgeonSetFlags),__privateAdd(this,_mutagenistSetFlags),__privateAdd(this,_toxicologistSetFlags)}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(__privateGet(this,_bomberSetFlags,bomberSetFlags_get));break}case"chirurgeon":{source.system.rules.push(__privateGet(this,_chirurgeonSetFlags,chirurgeonSetFlags_get));break}case"mutagenist":{source.system.rules.push(__privateGet(this,_mutagenistSetFlags,mutagenistSetFlags_get));break}case"toxicologist":{source.system.rules.push(__privateGet(this,_toxicologistSetFlags,toxicologistSetFlags_get));break}}}};_bomberSetFlags=new WeakSet,bomberSetFlags_get=__name2(function(){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"}}},"#bomberSetFlags"),_chirurgeonSetFlags=new WeakSet,chirurgeonSetFlags_get=__name2(function(){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"}}},"#chirurgeonSetFlags"),_mutagenistSetFlags=new WeakSet,mutagenistSetFlags_get=__name2(function(){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"}}},"#mutagenistSetFlags"),_toxicologistSetFlags=new WeakSet,toxicologistSetFlags_get=__name2(function(){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"}}},"#toxicologistSetFlags"),__name2(_Migration816AlchemistResearchFields,"Migration816AlchemistResearchFields"),__publicField(_Migration816AlchemistResearchFields,"version",.816);let Migration816AlchemistResearchFields=_Migration816AlchemistResearchFields;const _Migration817FieldDiscoveryPredicates=class extends MigrationBase{static{__name(this,"_Migration817FieldDiscoveryPredicates")}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}`]}}};__name2(_Migration817FieldDiscoveryPredicates,"Migration817FieldDiscoveryPredicates"),__publicField(_Migration817FieldDiscoveryPredicates,"version",.817);let Migration817FieldDiscoveryPredicates=_Migration817FieldDiscoveryPredicates;const _Migration818BasicUndeadNegativeHealing=class extends MigrationBase{static{__name(this,"_Migration818BasicUndeadNegativeHealing")}constructor(){super(...arguments),__privateAdd(this,_needsRE)}async updateItem(source){if(source.type==="feat"&&__privateMethod(this,_needsRE,needsRE_fn).call(this,source)){const rule={key:"ActiveEffectLike",mode:"override",path:"system.attributes.hp.negativeHealing",value:!0};source.system.rules.push(rule)}}};_needsRE=new WeakSet,needsRE_fn=__name2(function(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")},"#needsRE"),__name2(_Migration818BasicUndeadNegativeHealing,"Migration818BasicUndeadNegativeHealing"),__publicField(_Migration818BasicUndeadNegativeHealing,"version",.818);let Migration818BasicUndeadNegativeHealing=_Migration818BasicUndeadNegativeHealing;const _Migration819SpinTaleAdventureSpecific=class extends MigrationBase{static{__name(this,"_Migration819SpinTaleAdventureSpecific")}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)}}};__name2(_Migration819SpinTaleAdventureSpecific,"Migration819SpinTaleAdventureSpecific"),__publicField(_Migration819SpinTaleAdventureSpecific,"version",.819);let Migration819SpinTaleAdventureSpecific=_Migration819SpinTaleAdventureSpecific;const _Migration820RemoveUnusedTraitsData=class extends MigrationBase{static{__name(this,"_Migration820RemoveUnusedTraitsData")}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))}};__name2(_Migration820RemoveUnusedTraitsData,"Migration820RemoveUnusedTraitsData"),__publicField(_Migration820RemoveUnusedTraitsData,"version",.82);let Migration820RemoveUnusedTraitsData=_Migration820RemoveUnusedTraitsData;const _Migration821InlineDamageRolls=class extends MigrationBase{static{__name(this,"_Migration821InlineDamageRolls")}constructor(){super(...arguments),__privateAdd(this,_cleanFormula),__privateAdd(this,_buildSplashFormula),__privateAdd(this,_buildDamageFormula),__privateAdd(this,_updateDamageFormula3),__privateAdd(this,_splashPattern1,/\[\[(\/b?r)\s*{([^}]*)}\[splash,\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g),__privateAdd(this,_splashPattern2,/\[\[(\/b?r)\s*([^[]*)\[splash,\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g),__privateAdd(this,_damagePatternSingle,/\[\[(\/b?r)\s*{([^}]*)}\[\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g),__privateAdd(this,_damagePatternPair,/\[\[(\/b?r)\s*{([^}]*)}\[\s*([^\]]*)\]\s*[+,]\s*{([^}]*)}\[\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g)}async updateActor(source){source.system=recursiveReplaceString(source.system,s=>__privateMethod(this,_updateDamageFormula3,updateDamageFormula_fn3).call(this,s))}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>__privateMethod(this,_updateDamageFormula3,updateDamageFormula_fn3).call(this,s))}async updateJournalEntry(source){source.pages=recursiveReplaceString(source.pages,s=>__privateMethod(this,_updateDamageFormula3,updateDamageFormula_fn3).call(this,s))}};_splashPattern1=new WeakMap,_splashPattern2=new WeakMap,_damagePatternSingle=new WeakMap,_damagePatternPair=new WeakMap,_cleanFormula=new WeakSet,cleanFormula_fn=__name2(function(formula){return formula=formula.replace(/\s+/g,""),["+","-","*","/"].some(o=>formula.includes(o))?`(${formula})`:formula},"#cleanFormula"),_buildSplashFormula=new WeakSet,buildSplashFormula_fn=__name2(function(roll,formula,damage,tag){return formula=__privateMethod(this,_cleanFormula,cleanFormula_fn).call(this,formula),damage=damage.trim(),tag=tag?.trim()??"",tag.length>0?`[[${roll} (${formula}[splash])[${damage}] ${tag}]]`:`[[${roll} (${formula}[splash])[${damage}]]]`},"#buildSplashFormula"),_buildDamageFormula=new WeakSet,buildDamageFormula_fn=__name2(function(roll,parts,tag){if(tag=tag?.trim()??"",parts.length===1){const formula=__privateMethod(this,_cleanFormula,cleanFormula_fn).call(this,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=__privateMethod(this,_cleanFormula,cleanFormula_fn).call(this,p.formula),damage=p.damage.trim();return`${formula}[${damage}]`}).join(",");return tag.length>0?`[[${roll} {${assembled}} ${tag}]]`:`[[${roll} {${assembled}}]]`}else return""},"#buildDamageFormula"),_updateDamageFormula3=new WeakSet,updateDamageFormula_fn3=__name2(function(text){return text=text.replace(__privateGet(this,_splashPattern1),(_,roll,formula,damage,tag)=>__privateMethod(this,_buildSplashFormula,buildSplashFormula_fn).call(this,roll,formula,damage,tag)),text=text.replace(__privateGet(this,_splashPattern2),(_,roll,formula,damage,tag)=>__privateMethod(this,_buildSplashFormula,buildSplashFormula_fn).call(this,roll,formula,damage,tag)),text=text.replace(__privateGet(this,_damagePatternSingle),(_,roll,formula,damage,tag)=>__privateMethod(this,_buildDamageFormula,buildDamageFormula_fn).call(this,roll,[{formula,damage}],tag)),text=text.replace(__privateGet(this,_damagePatternPair),(_,roll,formula1,damage1,formula2,damage2,tag)=>__privateMethod(this,_buildDamageFormula,buildDamageFormula_fn).call(this,roll,[{formula:formula1,damage:damage1},{formula:formula2,damage:damage2}],tag)),text},"#updateDamageFormula"),__name2(_Migration821InlineDamageRolls,"Migration821InlineDamageRolls"),__publicField(_Migration821InlineDamageRolls,"version",.821);let Migration821InlineDamageRolls=_Migration821InlineDamageRolls;const _Migration822BladeAllyConsolidation=class extends MigrationBase{static{__name(this,"_Migration822BladeAllyConsolidation")}constructor(){super(...arguments),__privateAdd(this,_rename)}async updateItem(source){source.system.description.value.includes("feat-effects")&&(source.system.description.value=__privateMethod(this,_rename,rename_fn).call(this,source.system.description.value))}};_rename=new WeakSet,rename_fn=__name2(function(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")},"#rename"),__name2(_Migration822BladeAllyConsolidation,"Migration822BladeAllyConsolidation"),__publicField(_Migration822BladeAllyConsolidation,"version",.822);let Migration822BladeAllyConsolidation=_Migration822BladeAllyConsolidation;const _Migration823HeritageAncestrySlug=class extends MigrationBase{static{__name(this,"_Migration823HeritageAncestrySlug")}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)}};__name2(_Migration823HeritageAncestrySlug,"Migration823HeritageAncestrySlug"),__publicField(_Migration823HeritageAncestrySlug,"version",.823);let Migration823HeritageAncestrySlug=_Migration823HeritageAncestrySlug;const _Migration824SneakAttackDamageSource=class extends MigrationBase{static{__name(this,"_Migration824SneakAttackDamageSource")}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}}}};__name2(_Migration824SneakAttackDamageSource,"Migration824SneakAttackDamageSource"),__publicField(_Migration824SneakAttackDamageSource,"version",.824);let Migration824SneakAttackDamageSource=_Migration824SneakAttackDamageSource;const _Migration825KhakkharaFengHuoLun=class extends MigrationBase{static{__name(this,"_Migration825KhakkharaFengHuoLun")}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")}}};__name2(_Migration825KhakkharaFengHuoLun,"Migration825KhakkharaFengHuoLun"),__publicField(_Migration825KhakkharaFengHuoLun,"version",.825);let Migration825KhakkharaFengHuoLun=_Migration825KhakkharaFengHuoLun;const _Migration826GutConditionData=class extends MigrationBase{static{__name(this,"_Migration826GutConditionData")}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}};__name2(_Migration826GutConditionData,"Migration826GutConditionData"),__publicField(_Migration826GutConditionData,"version",.826);let Migration826GutConditionData=_Migration826GutConditionData;const _Migration827FixTVShieldTraits=class extends MigrationBase{static{__name(this,"_Migration827FixTVShieldTraits")}async updateItem(source){const traits=source.system.traits;if(isObject(traits)&&"value"in traits&&!Array.isArray(traits.value)&&(traits.value=[]),source.type==="armor")switch(source.system.slug){case"dart-shield":{source.system.traits.value=["launching-dart"];return}case"klar":{source.system.traits.value=["integrated-1d6-s-versatile-p"];return}case"meteor-shield":{source.system.traits.value=["shield-throw-30"];return}case"razor-disc":{source.system.traits.value=["integrated-1d6-s","shield-throw-20"];return}}}};__name2(_Migration827FixTVShieldTraits,"Migration827FixTVShieldTraits"),__publicField(_Migration827FixTVShieldTraits,"version",.827);let Migration827FixTVShieldTraits=_Migration827FixTVShieldTraits;const _Migration828PruneInvalidTraits=class extends MigrationBase{static{__name(this,"_Migration828PruneInvalidTraits")}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)switch(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 in actionTraits);return}case"affliction":case"effect":{traits.value=traits.value.filter(t=>t in actionTraits||t in spellTraits);return}case"ancestry":{traits.value=traits.value.filter(t=>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 in armorTraits);return}case"backpack":case"equipment":{traits.value=traits.value.filter(t=>t in equipmentTraits);return}case"consumable":{traits.value=traits.value.filter(t=>t in consumableTraits);return}case"class":{traits.value=traits.value.filter(t=>t in classTraits);return}case"feat":{traits.value=traits.value.filter(t=>t in featTraits);return}case"melee":{traits.value=traits.value.filter(t=>t in npcAttackTraits);return}case"spell":{traits.value=traits.value.map(t=>t.replace(/^audible$/,"auditory")).filter(t=>t in spellTraits);return}case"weapon":{traits.value=traits.value.filter(t=>t in weaponTraits);return}}}};__name2(_Migration828PruneInvalidTraits,"Migration828PruneInvalidTraits"),__publicField(_Migration828PruneInvalidTraits,"version",.828);let Migration828PruneInvalidTraits=_Migration828PruneInvalidTraits;const _Migration829RMRitualEntries=class extends MigrationBase{static{__name(this,"_Migration829RMRitualEntries")}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){source.type==="spell"&&source.system.category.value==="ritual"&&source.system.location&&(source.system.location.value=null)}};__name2(_Migration829RMRitualEntries,"Migration829RMRitualEntries"),__publicField(_Migration829RMRitualEntries,"version",.829);let Migration829RMRitualEntries=_Migration829RMRitualEntries;const _Migration830BarbarianRework=class extends MigrationBase{static{__name(this,"_Migration830BarbarianRework")}constructor(){super(...arguments),__privateAdd(this,_removeLinks)}async updateItem(source){source.system.description.value=__privateMethod(this,_removeLinks,removeLinks_fn).call(this,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=new WeakSet,removeLinks_fn=__name2(function(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")},"#removeLinks"),__name2(_Migration830BarbarianRework,"Migration830BarbarianRework"),__publicField(_Migration830BarbarianRework,"version",.83);let Migration830BarbarianRework=_Migration830BarbarianRework;const _Migration831ClericDoctrines=class extends MigrationBase{static{__name(this,"_Migration831ClericDoctrines")}constructor(){super(...arguments),__privateAdd(this,_cloisteredClericSetFlags),__privateAdd(this,_warpriestSetFlags)}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(__privateGet(this,_cloisteredClericSetFlags,cloisteredClericSetFlags_get));break}case"warpriest":{source.system.rules.push(__privateGet(this,_warpriestSetFlags,warpriestSetFlags_get));break}}}};_cloisteredClericSetFlags=new WeakSet,cloisteredClericSetFlags_get=__name2(function(){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"}}},"#cloisteredClericSetFlags"),_warpriestSetFlags=new WeakSet,warpriestSetFlags_get=__name2(function(){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"}}},"#warpriestSetFlags"),__name2(_Migration831ClericDoctrines,"Migration831ClericDoctrines"),__publicField(_Migration831ClericDoctrines,"version",.831);let Migration831ClericDoctrines=_Migration831ClericDoctrines;const _Migration832ChoiceSetFlags=class extends MigrationBase{static{__name(this,"_Migration832ChoiceSetFlags")}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}`)))}}}};__name2(_Migration832ChoiceSetFlags,"Migration832ChoiceSetFlags"),__publicField(_Migration832ChoiceSetFlags,"version",.832);let Migration832ChoiceSetFlags=_Migration832ChoiceSetFlags;const _Migration833AddRogueToysFixPrecision=class extends MigrationBase{static{__name(this,"_Migration833AddRogueToysFixPrecision")}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}}}};__name2(_Migration833AddRogueToysFixPrecision,"Migration833AddRogueToysFixPrecision"),__publicField(_Migration833AddRogueToysFixPrecision,"version",.833);let Migration833AddRogueToysFixPrecision=_Migration833AddRogueToysFixPrecision;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"]),_Migration834FeatCategories=class extends MigrationBase{static{__name(this,"_Migration834FeatCategories")}constructor(){super(...arguments),__privateAdd(this,_updateCategoryData)}async updateItem(source){source.type==="feat"&&__privateMethod(this,_updateCategoryData,updateCategoryData_fn).call(this,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"))}};_updateCategoryData=new WeakSet,updateCategoryData_fn=__name2(function(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())},"#updateCategoryData"),__name2(_Migration834FeatCategories,"Migration834FeatCategories"),__publicField(_Migration834FeatCategories,"version",.834);let Migration834FeatCategories=_Migration834FeatCategories;const _Migration835InitiativeLongform=class extends MigrationBase{static{__name(this,"_Migration835InitiativeLongform")}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}};__name2(_Migration835InitiativeLongform,"Migration835InitiativeLongform"),__publicField(_Migration835InitiativeLongform,"version",.835);let Migration835InitiativeLongform=_Migration835InitiativeLongform;const _Migration836EnergizingConsolidation=class extends MigrationBase{static{__name(this,"_Migration836EnergizingConsolidation")}constructor(){super(...arguments),__privateAdd(this,_rename2)}async updateItem(source){source.system.description.value.includes("equipment-effects")&&(source.system.description.value=__privateMethod(this,_rename2,rename_fn2).call(this,source.system.description.value))}};_rename2=new WeakSet,rename_fn2=__name2(function(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)},"#rename"),__name2(_Migration836EnergizingConsolidation,"Migration836EnergizingConsolidation"),__publicField(_Migration836EnergizingConsolidation,"version",.836);let Migration836EnergizingConsolidation=_Migration836EnergizingConsolidation;const _Migration837MoveHazardBookSources=class extends MigrationBase{static{__name(this,"_Migration837MoveHazardBookSources")}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}}};__name2(_Migration837MoveHazardBookSources,"Migration837MoveHazardBookSources"),__publicField(_Migration837MoveHazardBookSources,"version",.837);let Migration837MoveHazardBookSources=_Migration837MoveHazardBookSources;const _Migration838StrikeAttackRollSelector=class extends MigrationBase{static{__name(this,"_Migration838StrikeAttackRollSelector")}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)))}};__name2(_Migration838StrikeAttackRollSelector,"Migration838StrikeAttackRollSelector"),__publicField(_Migration838StrikeAttackRollSelector,"version",.838);let Migration838StrikeAttackRollSelector=_Migration838StrikeAttackRollSelector;const _Migration839ActionCategories=class extends MigrationBase{static{__name(this,"_Migration839ActionCategories")}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}}};__name2(_Migration839ActionCategories,"Migration839ActionCategories"),__publicField(_Migration839ActionCategories,"version",.839);let Migration839ActionCategories=_Migration839ActionCategories;const _Migration840ArrayWrapPredicates=class extends MigrationBase{static{__name(this,"_Migration840ArrayWrapPredicates")}constructor(){super(...arguments),__privateAdd(this,_wrapPredicate)}async updateItem(source){for(const rule of source.system.rules)"predicate"in rule&&(rule.predicate=__privateMethod(this,_wrapPredicate,wrapPredicate_fn).call(this,rule.predicate)),"definition"in rule&&(rule.definition=__privateMethod(this,_wrapPredicate,wrapPredicate_fn).call(this,rule.definition))}};_wrapPredicate=new WeakSet,wrapPredicate_fn=__name2(function(predicate){if(Array.isArray(predicate))return predicate;const arrayWrapped=[predicate];return predicate&&PredicatePF2e.isValid(arrayWrapped)?arrayWrapped:void 0},"#wrapPredicate"),__name2(_Migration840ArrayWrapPredicates,"Migration840ArrayWrapPredicates"),__publicField(_Migration840ArrayWrapPredicates,"version",.84);let Migration840ArrayWrapPredicates=_Migration840ArrayWrapPredicates;const _Migration841V11UUIDFormat=class extends MigrationBase{static{__name(this,"_Migration841V11UUIDFormat")}constructor(){super(...arguments),__privateAdd(this,_replaceUUID),__privateAdd(this,_replaceUUIDsInLinks)}async updateActor(source){if(source.flags.core?.sourceId&&(source.flags.core.sourceId=__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,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=__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,formula.uuid,"Item")}else if(source.type==="npc"){const{details}=source.system;details.publicNotes&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,details.publicNotes),details.privateNotes&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,details.privateNotes)}else if(source.type==="hazard"){const{details}=source.system;details.reset&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,details.reset),details.description&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,details.description),details.routine&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,details.routine),details.disable&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,details.disable)}}async updateItem(source){if(source.flags.core?.sourceId&&(source.flags.core.sourceId=__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,source.flags.core.sourceId,"Item")),source.system.rules=source.system.rules.map(rule=>("text"in rule&&typeof rule.text=="string"&&(rule.text=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,rule.text)),recursiveReplaceString(rule,s=>__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,s,"Item")))),itemIsOfType(source,"ancestry","background","class","kit")){const items=source.system.items;for(const entry of Object.values(items))if(entry.uuid=__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,entry.uuid,"Item"),isObject(entry.items))for(const subentry of Object.values(entry.items))subentry.uuid=__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,subentry.uuid,"Item")}else if(source.type==="heritage")source.system.ancestry?.uuid&&(source.system.ancestry.uuid=__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,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)]=__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,spell);const{description}=source.system;description.value??="",description.value=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,description.value),description.value=description.value.replace(/Compendium\.pf2e\.journals\.(?!JournalEntry)/g,"Compendium.pf2e.journals.JournalEntry."),description.gm&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,description.gm)}async updateJournalEntry(source){for(const page of source.pages)page.text.content&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,page.text.content)}};_replaceUUID=new WeakSet,replaceUUID_fn=__name2(function(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}`},"#replaceUUID"),_replaceUUIDsInLinks=new WeakSet,replaceUUIDsInLinks_fn=__name2(function(text){return typeof text!="string"?text:Array.from(text.matchAll(/(?<=@UUID\[)[^\]]+(?=\])/g)).reduce((replaced,[link])=>replaced.replace(link,s=>__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,s)),text)},"#replaceUUIDsInLinks"),__name2(_Migration841V11UUIDFormat,"Migration841V11UUIDFormat"),__publicField(_Migration841V11UUIDFormat,"version",.841);let Migration841V11UUIDFormat=_Migration841V11UUIDFormat;const _Migration842NumifyNumericSettings=class extends MigrationBase{static{__name(this,"_Migration842NumifyNumericSettings")}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))}}};__name2(_Migration842NumifyNumericSettings,"Migration842NumifyNumericSettings"),__publicField(_Migration842NumifyNumericSettings,"version",.842);let Migration842NumifyNumericSettings=_Migration842NumifyNumericSettings;const _Migration843RMArmorCustomModifiers=class extends MigrationBase{static{__name(this,"_Migration843RMArmorCustomModifiers")}async updateActor(source){if(source.type==="character"&&source.system.customModifiers?.armor){const customModifiers=source.system.customModifiers;customModifiers["-=armor"]=null}}};__name2(_Migration843RMArmorCustomModifiers,"Migration843RMArmorCustomModifiers"),__publicField(_Migration843RMArmorCustomModifiers,"version",.843);let Migration843RMArmorCustomModifiers=_Migration843RMArmorCustomModifiers;const _Migration844DeityDomainUUIDs=class extends MigrationBase{static{__name(this,"_Migration844DeityDomainUUIDs")}constructor(){super(...arguments),__privateAdd(this,_updateUUIDs),__privateAdd(this,_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"}])}async updateActor(source){source.type==="npc"&&(source.system.details.publicNotes&&=__privateMethod(this,_updateUUIDs,updateUUIDs_fn).call(this,source.system.details.publicNotes))}async updateItem(source){source.system.description.gm&&=__privateMethod(this,_updateUUIDs,updateUUIDs_fn).call(this,source.system.description.gm),source.system.description.value&&=__privateMethod(this,_updateUUIDs,updateUUIDs_fn).call(this,source.system.description.value)}};_updateUUIDs=new WeakSet,updateUUIDs_fn=__name2(function(text){return __privateGet(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)},"#updateUUIDs"),_idMap=new WeakMap,__name2(_Migration844DeityDomainUUIDs,"Migration844DeityDomainUUIDs"),__publicField(_Migration844DeityDomainUUIDs,"version",.844);let Migration844DeityDomainUUIDs=_Migration844DeityDomainUUIDs;const _Migration845EmptySpellConsumables=class extends MigrationBase{static{__name(this,"_Migration845EmptySpellConsumables")}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)}}};__name2(_Migration845EmptySpellConsumables,"Migration845EmptySpellConsumables"),__publicField(_Migration845EmptySpellConsumables,"version",.845);let Migration845EmptySpellConsumables=_Migration845EmptySpellConsumables;const _Migration846SpellSchoolOptional=class extends MigrationBase{static{__name(this,"_Migration846SpellSchoolOptional")}async updateItem(source){if(source.type!=="spell")return;const system=source.system;system.school&&(source.system.traits.value=uniq(compact([...source.system.traits.value,system.school.value])),system["-=school"]=null,delete system.school)}};__name2(_Migration846SpellSchoolOptional,"Migration846SpellSchoolOptional"),__publicField(_Migration846SpellSchoolOptional,"version",.846);let Migration846SpellSchoolOptional=_Migration846SpellSchoolOptional;const _Migration847TempHPRuleEvents=class extends MigrationBase{static{__name(this,"_Migration847TempHPRuleEvents")}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)}};__name2(_Migration847TempHPRuleEvents,"Migration847TempHPRuleEvents"),__publicField(_Migration847TempHPRuleEvents,"version",.847);let Migration847TempHPRuleEvents=_Migration847TempHPRuleEvents;const _Migration848NumericArmorProperties=class extends MigrationBase{static{__name(this,"_Migration848NumericArmorProperties")}constructor(){super(...arguments),__privateAdd(this,_oldToNew,[["armor","acBonus"],["dex","dexCap"],["check","checkPenalty"],["speed","speedPenalty"],["strength","strength"]])}async updateItem(source){if(source.type==="armor")for(const[oldKey,newKey]of __privateGet(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)||null,source.system[`-=${oldKey}`]=null):(source.system[newKey]=Number(oldProperty.value)||0,source.system[`-=${oldKey}`]=null)}}};_oldToNew=new WeakMap,__name2(_Migration848NumericArmorProperties,"Migration848NumericArmorProperties"),__publicField(_Migration848NumericArmorProperties,"version",.848);let Migration848NumericArmorProperties=_Migration848NumericArmorProperties;const _Migration849DeleteBrokenThreshold=class extends MigrationBase{static{__name(this,"_Migration849DeleteBrokenThreshold")}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)}};__name2(_Migration849DeleteBrokenThreshold,"Migration849DeleteBrokenThreshold"),__publicField(_Migration849DeleteBrokenThreshold,"version",.849);let Migration849DeleteBrokenThreshold=_Migration849DeleteBrokenThreshold;const _Migration850FlatFootedToOffGuard=class extends MigrationBase{static{__name(this,"_Migration850FlatFootedToOffGuard")}constructor(){super(...arguments),__privateAdd(this,_replace),__privateAdd(this,_oldNamePattern,new RegExp(/\bFlat-Footed\b/g)),__privateAdd(this,_newName,"Off-Guard"),__privateAdd(this,_imgPattern,/(?<=systems\/pf2e\/icons\/conditions(?:-2)?\/)flat-?footed.webp$/i),__privateAdd(this,_aToAnUUIDPatern,/\ba(?= @UUID\[Compendium\.pf2e\.conditionitems\.Item\.(?:Flat-Footed|AJh5ex99aV6VTggg)\])/g)}async updateActor(source){source.type==="hazard"&&(source.system.details.routine&&=__privateMethod(this,_replace,replace_fn).call(this,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=>__privateMethod(this,_replace,replace_fn).call(this,s)))}async updateItem(source){source.name=source.name.replace(__privateGet(this,_oldNamePattern),__privateGet(this,_newName)),source.img=source.img.replace(__privateGet(this,_imgPattern),"off-guard.webp"),source.system=recursiveReplaceString(source.system,s=>__privateMethod(this,_replace,replace_fn).call(this,s))}async updateJournalEntry(source){source.name!=="Remaster Changes"&&(source.name=source.name.replace(__privateGet(this,_oldNamePattern),__privateGet(this,_newName)),"img"in source&&typeof source.img=="string"&&(source.img=source.img.replace(__privateGet(this,_imgPattern),"off-guard.webp")),source.pages=recursiveReplaceString(source.pages,s=>__privateMethod(this,_replace,replace_fn).call(this,s)),"content"in source&&typeof source.content=="string"&&(source.content=__privateMethod(this,_replace,replace_fn).call(this,source.content)))}};_oldNamePattern=new WeakMap,_newName=new WeakMap,_imgPattern=new WeakMap,_aToAnUUIDPatern=new WeakMap,_replace=new WeakSet,replace_fn=__name2(function(text){return text.replace(__privateGet(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(__privateGet(this,_oldNamePattern),"Off-Guard").replace(/\bflatfooted\b/g,"flat-footed").replace(/\ba flat-footed\b/g,"an off-guard").replace(__privateGet(this,_aToAnUUIDPatern),"an").replace(/\bFlat-footed\b/g,"Off-guard").replace(/\bflat-footed\b/g,"off-guard")},"#replace"),__name2(_Migration850FlatFootedToOffGuard,"Migration850FlatFootedToOffGuard"),__publicField(_Migration850FlatFootedToOffGuard,"version",.85);let Migration850FlatFootedToOffGuard=_Migration850FlatFootedToOffGuard;const _Migration851JustInnovationId=class extends MigrationBase{static{__name(this,"_Migration851JustInnovationId")}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)}}};__name2(_Migration851JustInnovationId,"Migration851JustInnovationId"),__publicField(_Migration851JustInnovationId,"version",.851);let Migration851JustInnovationId=_Migration851JustInnovationId;const _Migration852AbilityScoresToModifiers=class extends MigrationBase{static{__name(this,"_Migration852AbilityScoresToModifiers")}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)}}};__name2(_Migration852AbilityScoresToModifiers,"Migration852AbilityScoresToModifiers"),__publicField(_Migration852AbilityScoresToModifiers,"version",.852);let Migration852AbilityScoresToModifiers=_Migration852AbilityScoresToModifiers;const _Migration853RemasterLanguages=class extends MigrationBase{static{__name(this,"_Migration853RemasterLanguages")}constructor(){super(...arguments),__privateAdd(this,_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=>__privateGet(this,_OLD_TO_NEW_LANGUAGES).get(l)??l).sort())}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>__privateGet(this,_OLD_TO_NEW_LANGUAGES).get(s)??s),source.type==="ancestry"&&Array.isArray(source.system.additionalLanguages?.value)&&source.system.additionalLanguages.value.sort()}};_OLD_TO_NEW_LANGUAGES=new WeakMap,__name2(_Migration853RemasterLanguages,"Migration853RemasterLanguages"),__publicField(_Migration853RemasterLanguages,"version",.853);let Migration853RemasterLanguages=_Migration853RemasterLanguages;const _Migration854BracketedAbilityScoresToModifiers=class extends MigrationBase{static{__name(this,"_Migration854BracketedAbilityScoresToModifiers")}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}}};__name2(_Migration854BracketedAbilityScoresToModifiers,"Migration854BracketedAbilityScoresToModifiers"),__publicField(_Migration854BracketedAbilityScoresToModifiers,"version",.854);let Migration854BracketedAbilityScoresToModifiers=_Migration854BracketedAbilityScoresToModifiers;const _Migration855ApexEquipmentSystemData=class extends MigrationBase{static{__name(this,"_Migration855ApexEquipmentSystemData")}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)))}};__name2(_Migration855ApexEquipmentSystemData,"Migration855ApexEquipmentSystemData"),__publicField(_Migration855ApexEquipmentSystemData,"version",.855);let Migration855ApexEquipmentSystemData=_Migration855ApexEquipmentSystemData;const _Migration856NoSystemDotCustom=class extends MigrationBase{static{__name(this,"_Migration856NoSystemDotCustom")}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"})}`)))}};__name2(_Migration856NoSystemDotCustom,"Migration856NoSystemDotCustom"),__publicField(_Migration856NoSystemDotCustom,"version",.856);let Migration856NoSystemDotCustom=_Migration856NoSystemDotCustom;const _Migration857WeaponSpecializationRE=class extends MigrationBase{static{__name(this,"_Migration857WeaponSpecializationRE")}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}))}};__name2(_Migration857WeaponSpecializationRE,"Migration857WeaponSpecializationRE"),__publicField(_Migration857WeaponSpecializationRE,"version",.857);let Migration857WeaponSpecializationRE=_Migration857WeaponSpecializationRE;const _Migration858FakeWeaponSpecialization=class extends MigrationBase{static{__name(this,"_Migration858FakeWeaponSpecialization")}constructor(){super(...arguments),__privateAdd(this,_testHasOption)}async updateItem(source){if(source.type!=="feat")return;const slug=source.system.slug??sluggify(source.name);slug==="greater-weapon-specialization-barbarian"&&!__privateMethod(this,_testHasOption,testHasOption_fn).call(this,source)?source.system.rules.push({domain:"all",key:"RollOption",option:"feature:greater-weapon-specialization"}):slug==="psychic-weapon-specialization"&&!__privateMethod(this,_testHasOption,testHasOption_fn).call(this,source)&&source.system.rules.push({domain:"all",key:"RollOption",option:"feature:weapon-specialization"})}};_testHasOption=new WeakSet,testHasOption_fn=__name2(function(source){return source.system.rules.some(r=>r.key==="RollOption"&&"option"in r&&["feature:greater-weapon-specialization","feature:weapon-specialization"].includes(String(r.option)))},"#testHasOption"),__name2(_Migration858FakeWeaponSpecialization,"Migration858FakeWeaponSpecialization"),__publicField(_Migration858FakeWeaponSpecialization,"version",.858);let Migration858FakeWeaponSpecialization=_Migration858FakeWeaponSpecialization;const _Migration859MaterialTypeGrade=class extends MigrationBase{static{__name(this,"_Migration859MaterialTypeGrade")}constructor(){super(...arguments),__privateAdd(this,_hasOldMaterialData)}async updateItem(source){if(itemIsOfType(source,"physical")&&__privateMethod(this,_hasOldMaterialData,hasOldMaterialData_fn).call(this,source)){const{preciousMaterial,preciousMaterialGrade}=source.system,type=setHasElement(PRECIOUS_MATERIAL_TYPES,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)}}};_hasOldMaterialData=new WeakSet,hasOldMaterialData_fn=__name2(function(source){return"preciousMaterial"in source.system&&isObject(source.system.preciousMaterial)&&"preciousMaterialGrade"in source.system&&isObject(source.system.preciousMaterialGrade)},"#hasOldMaterialData"),__name2(_Migration859MaterialTypeGrade,"Migration859MaterialTypeGrade"),__publicField(_Migration859MaterialTypeGrade,"version",.859);let Migration859MaterialTypeGrade=_Migration859MaterialTypeGrade;const _Migration860RMGroup=class extends MigrationBase{static{__name(this,"_Migration860RMGroup")}async updateItem(source){itemIsOfType(source,"armor","condition","weapon")||!("group"in source.system)||("game"in globalThis?source.system["-=group"]=null:delete source.system.group)}};__name2(_Migration860RMGroup,"Migration860RMGroup"),__publicField(_Migration860RMGroup,"version",.86);let Migration860RMGroup=_Migration860RMGroup;const _Migration861AuraColorsToAppearance=class extends MigrationBase{static{__name(this,"_Migration861AuraColorsToAppearance")}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}};__name2(_Migration861AuraColorsToAppearance,"Migration861AuraColorsToAppearance"),__publicField(_Migration861AuraColorsToAppearance,"version",.861);let Migration861AuraColorsToAppearance=_Migration861AuraColorsToAppearance;const _Migration862SpecificMagicArmor=class extends MigrationBase{static{__name(this,"_Migration862SpecificMagicArmor")}constructor(){super(...arguments),__privateAdd(this,_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=!!(source.system.potencyRune.value||source.system.resiliencyRune.value),hasBaseAndSlug=!!(source.system.baseItem&&source.system.slug);isMagical&&hasBaseAndSlug&&source.system.baseItem!==source.system.slug&&(source.system.specific??={value:!0,material:source.system.material??null,runes:{potency:source.system.potencyRune?.value||1,resilient:__privateGet(this,_resilientRuneValues).get(source.system.resiliencyRune?.value??"")||0}})}};_resilientRuneValues=new WeakMap,__name2(_Migration862SpecificMagicArmor,"Migration862SpecificMagicArmor"),__publicField(_Migration862SpecificMagicArmor,"version",.862);let Migration862SpecificMagicArmor=_Migration862SpecificMagicArmor;const _Migration863FixMisspelledOrganaizationsProperty=class extends MigrationBase{static{__name(this,"_Migration863FixMisspelledOrganaizationsProperty")}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)}};__name2(_Migration863FixMisspelledOrganaizationsProperty,"Migration863FixMisspelledOrganaizationsProperty"),__publicField(_Migration863FixMisspelledOrganaizationsProperty,"version",.863);let Migration863FixMisspelledOrganaizationsProperty=_Migration863FixMisspelledOrganaizationsProperty;const _Migration864RemoveWeaponMAP=class extends MigrationBase{static{__name(this,"_Migration864RemoveWeaponMAP")}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}}};__name2(_Migration864RemoveWeaponMAP,"Migration864RemoveWeaponMAP"),__publicField(_Migration864RemoveWeaponMAP,"version",.864);let Migration864RemoveWeaponMAP=_Migration864RemoveWeaponMAP;const _Migration865VitalityVoid=class extends MigrationBase{static{__name(this,"_Migration865VitalityVoid")}constructor(){super(...arguments),__privateAdd(this,_replaceStrings)}async updateActor(source){source.system=__privateMethod(this,_replaceStrings,replaceStrings_fn).call(this,source.system),source.flags=__privateMethod(this,_replaceStrings,replaceStrings_fn).call(this,source.flags)}async updateItem(source){source.system=__privateMethod(this,_replaceStrings,replaceStrings_fn).call(this,source.system),source.flags=__privateMethod(this,_replaceStrings,replaceStrings_fn).call(this,source.flags)}};_replaceStrings=new WeakSet,replaceStrings_fn=__name2(function(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"))},"#replaceStrings"),__name2(_Migration865VitalityVoid,"Migration865VitalityVoid"),__publicField(_Migration865VitalityVoid,"version",.865);let Migration865VitalityVoid=_Migration865VitalityVoid;const _Migration866LinkToActorSizeAgain=class extends MigrationBase{static{__name(this,"_Migration866LinkToActorSizeAgain")}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)||mergeObject(tokenSource.flags,{pf2e:{linkToActorSize:!1,autoscale:!1}})}};__name2(_Migration866LinkToActorSizeAgain,"Migration866LinkToActorSizeAgain"),__publicField(_Migration866LinkToActorSizeAgain,"version",.866);let Migration866LinkToActorSizeAgain=_Migration866LinkToActorSizeAgain;const _Migration867DamageRollDomainFix=class extends MigrationBase{static{__name(this,"_Migration867DamageRollDomainFix")}async updateItem(source){for(const rule of source.system.rules??[])"domain"in rule&&rule.domain==="damage-roll"&&(rule.domain="damage")}};__name2(_Migration867DamageRollDomainFix,"Migration867DamageRollDomainFix"),__publicField(_Migration867DamageRollDomainFix,"version",.867);let Migration867DamageRollDomainFix=_Migration867DamageRollDomainFix;const _Migration868StrikeRERange=class extends MigrationBase{static{__name(this,"_Migration868StrikeRERange")}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}};__name2(_Migration868StrikeRERange,"Migration868StrikeRERange"),__publicField(_Migration868StrikeRERange,"version",.868);let Migration868StrikeRERange=_Migration868StrikeRERange;const _Migration869RefreshMightyBulwark=class extends MigrationBase{static{__name(this,"_Migration869RefreshMightyBulwark")}constructor(){super(...arguments),__privateAdd(this,_mightyBulwarkRules)}async updateItem(source){if(source.type==="feat"&&source.system.slug==="mighty-bulwark")source.system.rules=__privateGet(this,_mightyBulwarkRules,mightyBulwarkRules_get);else for(const rule of source.system.rules)"option"in rule&&rule.option==="self:armor:strength-requirement-met"&&(rule.option="armor:strength-requirement-met")}};_mightyBulwarkRules=new WeakSet,mightyBulwarkRules_get=__name2(function(){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}]},"#mightyBulwarkRules"),__name2(_Migration869RefreshMightyBulwark,"Migration869RefreshMightyBulwark"),__publicField(_Migration869RefreshMightyBulwark,"version",.869);let Migration869RefreshMightyBulwark=_Migration869RefreshMightyBulwark;const _Migration870MartialToProficiencies=class extends MigrationBase{static{__name(this,"_Migration870MartialToProficiencies")}constructor(){super(...arguments),__privateAdd(this,_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=__privateGet(this,_defensePathPattern).test(text)?"defenses":"attacks";return text.replace(/\bsystem\.martial\./g,`system.proficiencies.${key}.`)}))}};_defensePathPattern=new WeakMap,__name2(_Migration870MartialToProficiencies,"Migration870MartialToProficiencies"),__publicField(_Migration870MartialToProficiencies,"version",.87);let Migration870MartialToProficiencies=_Migration870MartialToProficiencies;const _Migration871MigrateRollActionMacroParams=class extends MigrationBase{static{__name(this,"_Migration871MigrateRollActionMacroParams")}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}" })`)}}};__name2(_Migration871MigrateRollActionMacroParams,"Migration871MigrateRollActionMacroParams"),__publicField(_Migration871MigrateRollActionMacroParams,"version",.871);let Migration871MigrateRollActionMacroParams=_Migration871MigrateRollActionMacroParams;const _Migration872MoveSchemaProperty=class extends MigrationBase{static{__name(this,"_Migration872MoveSchemaProperty")}constructor(){super(...arguments),__privateAdd(this,_mvSchema)}async updateActor(source){__privateMethod(this,_mvSchema,mvSchema_fn).call(this,source.system)}async updateItem(source){__privateMethod(this,_mvSchema,mvSchema_fn).call(this,source.system)}};_mvSchema=new WeakSet,mvSchema_fn=__name2(function(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))},"#mvSchema"),__name2(_Migration872MoveSchemaProperty,"Migration872MoveSchemaProperty"),__publicField(_Migration872MoveSchemaProperty,"version",.872);let Migration872MoveSchemaProperty=_Migration872MoveSchemaProperty;const _Migration873RemoveBonusBulkLimit=class extends MigrationBase{static{__name(this,"_Migration873RemoveBonusBulkLimit")}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"))}};__name2(_Migration873RemoveBonusBulkLimit,"Migration873RemoveBonusBulkLimit"),__publicField(_Migration873RemoveBonusBulkLimit,"version",.873);let Migration873RemoveBonusBulkLimit=_Migration873RemoveBonusBulkLimit;const _Migration874MoveStaminaStuff=class extends MigrationBase{static{__name(this,"_Migration874MoveStaminaStuff")}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)}};__name2(_Migration874MoveStaminaStuff,"Migration874MoveStaminaStuff"),__publicField(_Migration874MoveStaminaStuff,"version",.874);let Migration874MoveStaminaStuff=_Migration874MoveStaminaStuff;const _Migration875SetInnovationIdEarly=class extends MigrationBase{static{__name(this,"_Migration875SetInnovationIdEarly")}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)}};__name2(_Migration875SetInnovationIdEarly,"Migration875SetInnovationIdEarly"),__publicField(_Migration875SetInnovationIdEarly,"version",.875);let Migration875SetInnovationIdEarly=_Migration875SetInnovationIdEarly;const _Migration876FeatLevelTaken=class extends MigrationBase{static{__name(this,"_Migration876FeatLevelTaken")}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()}};__name2(_Migration876FeatLevelTaken,"Migration876FeatLevelTaken"),__publicField(_Migration876FeatLevelTaken,"version",.876);let Migration876FeatLevelTaken=_Migration876FeatLevelTaken;const _Migration877PublicationData=class extends MigrationBase{static{__name(this,"_Migration877PublicationData")}constructor(){super(...arguments),__privateAdd(this,_setPublicationData)}async updateActor(source){source.type!=="hazard"&&source.type!=="npc"&&source.type!=="vehicle"||(source.type==="vehicle"&&isObject$1(source.system.source)?(__privateMethod(this,_setPublicationData,setPublicationData_fn).call(this,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)&&(__privateMethod(this,_setPublicationData,setPublicationData_fn).call(this,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)?(__privateMethod(this,_setPublicationData,setPublicationData_fn).call(this,source.system,source.system.source),"game"in globalThis?source.system["-=source"]=null:delete source.system.source):!source.system.publication&&!("game"in globalThis)&&__privateMethod(this,_setPublicationData,setPublicationData_fn).call(this,source.system,{})}};_setPublicationData=new WeakSet,setPublicationData_fn=__name2(function(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},"#setPublicationData"),__name2(_Migration877PublicationData,"Migration877PublicationData"),__publicField(_Migration877PublicationData,"version",.877);let Migration877PublicationData=_Migration877PublicationData;const _Migration878TakeABreather=class extends MigrationBase{static{__name(this,"_Migration878TakeABreather")}async updateMacro(source){source.type==="script"&&source.command.includes("console.log(resolve, sp)")&&(source.command="game.pf2e.actions.takeABreather();")}};__name2(_Migration878TakeABreather,"Migration878TakeABreather"),__publicField(_Migration878TakeABreather,"version",.878);let Migration878TakeABreather=_Migration878TakeABreather;const Migrations=Object.freeze(Object.defineProperty({__proto__:null,Migration600Reach,Migration601SplitEffectCompendia,Migration602UpdateDiehardFeat,Migration603ResetQuickRollDefault,Migration604FixClassItem,Migration605CatchUpToTemplateJSON,Migration606SignatureSpells,Migration607MeleeItemDamageRolls,Migration608DeletePersistedKits,Migration609LootActorTraits,Migration610SetHeritageFeatType,Migration611UpdateToughnessMountainsStoutness,Migration612NormalizeRarities,Migration613RemoveAmmoCharges,Migration614NumifyMeleeBonuses,Migration615RemoveInstinctTrait,Migration616MigrateFeatPrerequisites,Migration617FixUserFlags,Migration618MigrateItemImagePaths,Migration619TraditionLowercaseAndRemoveWandScroll,Migration620RenameToWebp,Migration621RemoveConfigSpellSchools,Migration623NumifyPotencyRunes,Migration624RemoveTokenEffectIconFlags,Migration625EnsurePresenceOfSaves,Migration626UpdateSpellCategory,Migration627LowerCaseSpellSaves,Migration629SetBaseItems,Migration630FixTalismanSpelling,Migration631FixSenseRuleElementSelector,Migration632DeleteOrphanedSpells,Migration633DeleteUnidentifiedTraits,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},Symbol.toStringTag,{value:"Module"})),_MigrationList=class{static{__name(this,"_MigrationList")}static get latestVersion(){return Math.max(...__privateGet(this,_list).map(M=>M.version))}static constructAll(){return __privateGet(this,_list).map(M=>new M)}static constructFromVersion(version){const minVersion=Number(version)||MigrationRunner.RECOMMENDED_SAFE_VERSION;return __privateGet(this,_list).filter(M=>M.version>minVersion).map(M=>new M)}static constructRange(min,max=1/0){return __privateGet(this,_list).filter(M=>M.version>=min&&M.version<=max).map(M=>new M)}};_list=new WeakMap,__name2(_MigrationList,"MigrationList"),__privateAdd(_MigrationList,_list,Object.values(Migrations));let MigrationList=_MigrationList;const _WeaponDamagePF2e=class _WeaponDamagePF2e2{static{__name(this,"_WeaponDamagePF2e")}static async fromNPCAttack({attack,actor,actionTraits:actionTraits2=[],context}){const secondaryInstances=Object.values(attack.system.damageRolls).slice(1).map(this.npcDamageToWeaponDamage),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 _WeaponDamagePF2e2.calculate({weapon:attack,actor,damageDice,modifiers,actionTraits:actionTraits2,context})}static async calculate({weapon,actor,damageDice=[],modifiers=[],actionTraits:actionTraits2=[],weaponPotency=null,context}){var _a;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","npc")){const strengthModValue=actor.abilities.str.mod,modifierValue=__privateMethod(_a=_WeaponDamagePF2e2,_strengthModToDamage2,strengthModToDamage_fn2).call(_a,weapon,domains.includes("str-damage"))?strengthModValue:weaponTraits2.some(t=>t==="propulsive")?strengthModValue<0?strengthModValue:Math.floor(strengthModValue/2):null;if(weapon.isOfType("weapon")&&typeof modifierValue=="number"){const strModifier=new ModifierPF2e({slug:"str",label:CONFIG.PF2E.abilities.str,ability:"str",modifier:modifierValue,type:"ability",adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"str")});modifiers.push(strModifier)}}for(const rule of actor.rules.filter(r=>!r.ignored))rule.beforeRoll?.(domains,options);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");handsHeld===2&&setHasElement(DAMAGE_DIE_FACES,twoHandSize)&&twoHandFaces>baseDieFaces&&(baseDamage.die=twoHandSize);const splashDamage=Number(weapon.system.splashDamage?.value);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(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)),baseDamage.persistent?.faces?damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug:"weapon-persistent",label:"PF2E.ConditionTypePersistent",diceNumber:baseDamage.persistent.number,dieSize:`d${baseDamage.persistent.faces}`,damageType:baseDamage.persistent.type,category:"persistent"})):baseDamage.persistent?.number&&modifiers.push(new ModifierPF2e({slug:"weapon-persistent",label:"PF2E.ConditionTypePersistent",modifier:baseDamage.persistent.number,damageType:baseDamage.persistent.type,damageCategory:"persistent"}));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.isOfType("weapon")?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),extractedAdjustments=extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,modifier.slug);modifier.adjustments.push(...propRuneAdjustments,...extractedAdjustments)}const base={diceNumber:baseDamage.die?baseDamage.dice:0,dieSize:baseDamage.die,modifier:baseDamage.modifier,damageType:baseDamage.damageType,category:"category"in baseDamage&&baseDamage.category==="persistent"?"persistent":null,materials:Array.from(materials)},extractOptions={test:options,resolvables:{weapon},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:[base],dice:damageDice,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;__privateMethod(this,_excludeDamage,excludeDamage_fn).call(this,{actor,weapon:excludeFrom,modifiers:[...modifiers,...damageDice],options});const computedFormulas={criticalFailure:null,failure:__privateMethod(this,_finalizeDamage,finalizeDamage_fn).call(this,formulaData,DEGREE_OF_SUCCESS.FAILURE),success:__privateMethod(this,_finalizeDamage,finalizeDamage_fn).call(this,formulaData,DEGREE_OF_SUCCESS.SUCCESS),criticalSuccess:__privateMethod(this,_finalizeDamage,finalizeDamage_fn).call(this,formulaData,DEGREE_OF_SUCCESS.CRITICAL_SUCCESS)};return{name:`${game.i18n.localize("PF2E.DamageRoll")}: ${weapon.name}`,traits:(actionTraits2??[]).map(t=>t.name),materials:Array.from(materials),modifiers:[...modifiers,...damageDice],damage:{...formulaData,formula:mapValues(computedFormulas,formula=>formula?.formula??null),breakdown:mapValues(computedFormulas,formula=>formula?.breakdown??[])}}}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}}};_finalizeDamage=new WeakSet,finalizeDamage_fn=__name2(function(damage,degree){damage=deepClone(damage);const base=damage.base.at(0),critical=degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS;if(!base)return null;const outcomeMatches=__name2(m=>m.critical===null||critical&&m.critical||!critical&&!m.critical,"outcomeMatches"),hasUpgrade=damage.dice.some(d=>d.enabled&&d.override?.upgrade&&outcomeMatches(d)),hasDowngrade=damage.dice.some(d=>d.enabled&&d.override?.downgrade&&(critical||!d.critical));base.dieSize&&hasUpgrade&&!hasDowngrade?base.dieSize=nextDamageDieSize({upgrade:base.dieSize}):base.dieSize&&hasDowngrade&&!hasUpgrade&&(base.dieSize=nextDamageDieSize({downgrade:base.dieSize}));const damageOverrides=damage.dice.filter(d=>!!(d.enabled&&d.override));for(const override of damageOverrides)if(critical&&override.critical!==!1||!critical&&!override.critical){base.dieSize=override.override?.dieSize??base.dieSize,base.damageType=override.override?.damageType??base.damageType,base.diceNumber=override.override?.diceNumber??base.diceNumber;for(const die of damage.dice.filter(d=>/^(?:deadly|fatal)-/.test(d.slug)))die.damageType=override.override?.damageType??die.damageType}return createDamageFormula(damage,degree)},"#finalizeDamage"),_excludeDamage=new WeakSet,excludeDamage_fn=__name2(function({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)},"#excludeDamage"),_strengthModToDamage2=new WeakSet,strengthModToDamage_fn2=__name2(function(weapon,strengthBased){return weapon.isOfType("weapon")&&strengthBased&&!weapon.traits.has("propulsive")},"#strengthModToDamage"),__privateAdd(_WeaponDamagePF2e,_finalizeDamage),__privateAdd(_WeaponDamagePF2e,_excludeDamage),__privateAdd(_WeaponDamagePF2e,_strengthModToDamage2),__name2(_WeaponDamagePF2e,"WeaponDamagePF2e");let WeaponDamagePF2e=_WeaponDamagePF2e;async function resetActors(actors,{rerender=!0}={}){actors??=[game.actors.contents,game.scenes.contents.flatMap(s=>s.tokens.contents).flatMap(t=>t.actor??[])].flat();for(const actor of actors)actor.reset(),rerender&&actor.render();if(game.pf2e.effectPanel.refresh(),game.settings.get("pf2e","automation.effectExpiration")&&!game.settings.get("pf2e","automation.removeExpiredEffects")){const scenes=new Set(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)}}__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=deepClone(game.settings.get("core","defaultToken")),actor=new ActorProxyPF2e(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){if(!target?.isOfType("creature"))return!1;const{flanking}=target.attributes;return flanking.flankable?typeof flanking.offGuardable=="number"?origin.level>flanking.offGuardable:flanking.offGuardable:!1}__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]}-damage`)}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(),attributeModifier=[defaultAttributeModifier,...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).sort()}__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.type==="ability")].reduce((best,candidate)=>candidate&&best?candidate.value>best.value?candidate:best:candidate??best);attributeModifier&&domains.push(`${attributeModifier.ability}-damage`)}return uniq(domains).sort()}__name(getStrikeDamageDomains,"getStrikeDamageDomains"),__name2(getStrikeDamageDomains,"getStrikeDamageDomains");function strikeFromMeleeItem(item){const{actor,isMelee,isThrown}=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([isThrown?"thrown":null,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 notes=extractNotes(synthetics.rollNotes,domains),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),traitObjects=item.system.traits.value.map(t=>({name:t,label:CONFIG.PF2E.npcAttackTraits[t]??t,description:CONFIG.PF2E.traitsDescriptions[t]})),strike=mergeObject(statistic,{label:item.name,type:"strike",glyph:getActionGlyph({type:"action",value:1}),description:item.description,imageUrl:getActionIcon({type:"action",value:1}),sourceId:item.id,attackRollType:item.isRanged?"PF2E.NPCAttackRanged":"PF2E.NPCAttackMelee",additionalEffects,item,weapon:item,traits:traitObjects,options:Array.from(baseOptions),variants:[],ready:!0,success:"",criticalSuccess:""});strike.breakdown=strike.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${signedInteger(m.value)}`).join(", ");const attackTrait={name:"attack",label:CONFIG.PF2E.featTraits.attack,description:CONFIG.PF2E.traitsDescriptions.attack},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={})=>{const attackEffects2=actor.isOfType("npc")?await actor.getAttackEffects(item):[],rollNotes=notes.concat(attackEffects2);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])});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}),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:item.dealsDamage,domains,options:context.options,traits:[attackTrait],notes:rollNotes,dc:params.dc??context.dc,mapIncreases,rollTwice:extractRollTwice(synthetics.rollTwice,domains,context.options),substitutions:extractRollSubstitutions(synthetics.rollSubstitutions,domains,context.options),dosAdjustments:extractDegreeOfSuccessAdjustments(synthetics,domains)},roll=await CheckPF2e.roll(check,checkContext,params.event);if(roll)for(const rule of 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,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,...eventToRollParams(params.event)};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,actionTraits:[attackTrait],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");const _Statistic=class _Statistic2 extends BaseStatistic{static{__name(this,"_Statistic")}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,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),__publicField(this,"attribute",null),__publicField(this,"rank",null),__publicField(this,"proficient",!0),__publicField(this,"base",null),__publicField(this,"lore"),__publicField(this,"config"),__privateAdd(this,_check,void 0),__privateAdd(this,_dc,void 0),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 __privateGet(this,_check)??__privateSet(this,_check,new StatisticCheck(this,this.data,this.config))}get dc(){return __privateGet(this,_dc)??__privateSet(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.sort())}withRollOptions(options){const newOptions=mergeObject(this.config??{},options??{},{inplace:!1});return new _Statistic2(this.actor,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=mergeObject(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 _Statistic2(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())}}};_check=new WeakMap,_dc=new WeakMap,__name2(_Statistic,"Statistic");let Statistic=_Statistic;const _StatisticCheck=class{static{__name(this,"_StatisticCheck")}constructor(parent,data,config={}){__privateAdd(this,_determineLabel),__publicField(this,"parent"),__publicField(this,"type"),__publicField(this,"label"),__publicField(this,"domains"),__publicField(this,"mod"),__publicField(this,"modifiers"),this.parent=parent,this.type=data.check?.type??"check",data.check=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).sort(),this.domains=uniq(compact([data.domains,data.check.domains].flat())).sort(),this.label=__privateMethod(this,_determineLabel,determineLabel_fn).call(this,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}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 event=args.event?.originalEvent??args.event;if(event instanceof MouseEvent){const{rollMode:rollMode2,skipDialog:skipDialog2}=args;return mergeObject({rollMode:rollMode2,skipDialog:skipDialog2},eventToRollParams(event))}}return args})(),{actor,domains}=this,token=args.token??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("creature"))??null,rollContext=await(()=>{const isValidAttacker=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","feat","weapon"));return isValidAttacker&&isTargetedCheck?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})(),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(actor.synthetics.rollNotes,domains),...args.extraRollNotes??[]];for(const rule of actor.rules.filter(r=>!r.ignored))rule.beforeRoll?.(domains,options);const dosAdjustments=dc?extractDegreeOfSuccessAdjustments(actor.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??actor.level,amount=this.type==="saving-throw"&&actor.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"?traitSlugToObject(t,CONFIG.PF2E.actionTraits):t);for(const trait of traits??[])options.add(trait.name);const context={actor,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(actor.synthetics.rollTwice,domains,options),substitutions:extractRollSubstitutions(actor.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 actor.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(", ")}};_determineLabel=new WeakSet,determineLabel_fn=__name2(function(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}},"#determineLabel"),__name2(_StatisticCheck,"StatisticCheck");let StatisticCheck=_StatisticCheck;const _StatisticDifficultyClass=class{static{__name(this,"_StatisticDifficultyClass")}parent;domains;label;modifiers;options;constructor(parent,data,options={}){this.parent=parent,this.domains=uniq(compact([data.domains,data.dc?.domains].flat())).sort(),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)}};__name2(_StatisticDifficultyClass,"StatisticDifficultyClass");let StatisticDifficultyClass=_StatisticDifficultyClass;const _ArmorStatistic=class extends Statistic{static{__name(this,"_ArmorStatistic")}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),__privateAdd(this,_createBonusesAndPenalties),__privateAdd(this,_createShieldBonus),__publicField(this,"details"),this.details=data.details??"";const dcModifiers=[...this.dc.modifiers,...__privateMethod(this,_createBonusesAndPenalties,createBonusesAndPenalties_fn).call(this)].map(m=>m.clone());this.dc.modifiers=[...new StatisticModifier("",dcModifiers,this.dc.options).modifiers]}get item(){return this.actor.isOfType("character")?this.actor.wornArmor:null}getTraceData(){return{...super.getTraceData({value:"dc"}),details:this.details,breakdown:this.dc.breakdown}}};_createBonusesAndPenalties=new WeakSet,createBonusesAndPenalties_fn=__name2(function(){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),__privateMethod(this,_createShieldBonus,createShieldBonus_fn).call(this)])},"#createBonusesAndPenalties"),_createShieldBonus=new WeakSet,createShieldBonus_fn=__name2(function(){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},"#createShieldBonus"),__name2(_ArmorStatistic,"ArmorStatistic");let ArmorStatistic=_ArmorStatistic;const _HitPointsStatistic=class extends BaseStatistic{static{__name(this,"_HitPointsStatistic")}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}),__publicField(this,"value"),__publicField(this,"max"),__privateAdd(this,_baseMax,void 0),__publicField(this,"temp"),__publicField(this,"negativeHealing"),__publicField(this,"unrecoverable"),__publicField(this,"details"),__privateSet(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([__privateGet(this,_baseMax)>0?game.i18n.format("PF2E.MaxHitPointsBaseLabel",{base:__privateGet(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())}}};_baseMax=new WeakMap,__name2(_HitPointsStatistic,"HitPointsStatistic");let HitPointsStatistic=_HitPointsStatistic;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"},_TrickMagicItemEntry=class{static{__name(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:[],spellPrepList:null}}};__name2(_TrickMagicItemEntry,"TrickMagicItemEntry");let TrickMagicItemEntry=_TrickMagicItemEntry;const _ChatInspectRoll=class extends Application{static{__name(this,"_ChatInspectRoll")}constructor(message,options={}){super(options),__privateAdd(this,_currentFilter,""),this.message=message}static get defaultOptions(){const options=super.defaultOptions;return options.title="PF2E.ChatRollDetails.Title",options.template="systems/pf2e/templates/chat/chat-inspect-roll.hbs",options.classes=["chat-inspect-roll"],options.resizable=!0,options.width=600,options.height=420,options}getData(){const{context}=this.message.flags.pf2e,domains=context?.domains?.sort(),modifiers=this.prepareModifiers();return{context,domains,modifiers:modifiers??[],hasModifiers:!!modifiers}}prepareModifiers(){return this.message.flags.pf2e.modifiers?.map(mod=>{const value="dieSize"in mod?`+${mod.diceNumber}${mod.dieSize}`:addSign(mod.modifier??0);return{...mod,value,critical:mod.critical!==null?game.i18n.localize(`PF2E.RuleEditor.General.CriticalBehavior.${mod.critical}`):null}})??null}activateListeners($html){super.activateListeners($html);const html=$html[0];this.filterOptions(__privateGet(this,_currentFilter));const filterInput=htmlQuery(html,"input.filter");filterInput?.addEventListener("input",()=>{__privateSet(this,_currentFilter,filterInput.value?.trim()),this.filterOptions(__privateGet(this,_currentFilter))})}filterOptions(filter2){const html=this.element[0],{context}=this.message.flags.pf2e,allOptions=context?.options??[],topLevelOptions=allOptions.filter(option=>!option.includes(":")),remainingOptions=allOptions.filter(option=>option.includes(":")),rollOptions=[...topLevelOptions.sort(),...remainingOptions.sort()],filteredOptions=filter2?rollOptions.filter(r=>r.includes(filter2)):rollOptions,template=htmlQuery(html,"template.roll-option-template")?.innerHTML,content=Handlebars.compile(template)({rollOptions:filteredOptions}),destination=htmlQuery(html,".roll-option-lists");destination&&(destination.innerHTML=content)}};_currentFilter=new WeakMap,__name2(_ChatInspectRoll,"ChatInspectRoll");let ChatInspectRoll=_ChatInspectRoll;const _CriticalHitAndFumbleCards=class{static{__name(this,"_CriticalHitAndFumbleCards")}static handleDraw(message){if(message.isAuthor&&message.isContentVisible){const type=message.flags.pf2e.context?.type??"",firstDie=message.rolls.at(0)?.dice[0];firstDie&&firstDie.faces===20&&this.rollTypes.includes(type)&&(firstDie.total===20?this.automaticDraw("critTable"):firstDie.total===1&&this.automaticDraw("fumbleTable"))}}static automaticDraw(table){this.diceSoNice??=!!game.modules.get("dice-so-nice")?.active,this.diceSoNice?Hooks.once("diceSoNiceRollComplete",()=>{this.drawFromTable(table,!0)}):this.drawFromTable(table,!0)}static drawFromTable(table,automatic=!1){const tableId=table==="critTable"?"FTEpsIWWVrDj0jNG":"WzMGWMIrrPvSp75D";game.packs.get("pf2e.rollable-tables",{strict:!0}).getDocument(tableId).then(rollTable=>{rollTable.draw({displayChat:!1}).then(draw=>{const data={roll:draw.roll,messageData:{}};automatic&&!this.diceSoNice&&(data.messageData.sound=void 0),rollTable.toMessage(draw.results,data)})})}static appendButtons(message,$html){if(this.appendButtonsOption??=game.settings.get("pf2e","critFumbleButtons"),this.appendButtonsOption&&(message.isAuthor||game.user.isGM)&&message.isContentVisible){const type=message.flags.pf2e.context?.type??"";if(this.rollTypes.includes(type)){const critButton=$(``),fumbleButton=$(``),btnContainer1=$('');btnContainer1.append(critButton),btnContainer1.append(fumbleButton),critButton.on("click",event=>{event.stopPropagation(),this.drawFromTable("critTable"),event.currentTarget.blur()}),fumbleButton.on("click",event=>{event.stopPropagation(),this.drawFromTable("fumbleTable"),event.currentTarget.blur()}),$html.find(".dice-total").wrapInner('').append(btnContainer1)}}}};__name2(_CriticalHitAndFumbleCards,"CriticalHitAndFumbleCards"),__publicField(_CriticalHitAndFumbleCards,"rollTypes",["attack-roll","spell-attack-roll"]),__publicField(_CriticalHitAndFumbleCards,"diceSoNice"),__publicField(_CriticalHitAndFumbleCards,"appendButtonsOption");let CriticalHitAndFumbleCards=_CriticalHitAndFumbleCards;async function repair(options){const item=options.item??(options.uuid?await fromUuid(options.uuid):await SelectItemDialog.getItem("repair"));if(item&&!(item instanceof PhysicalItemPF2e)){ui.notifications.warn(game.i18n.format("PF2E.Actions.Repair.Warning.NotPhysicalItem",{item:item.name??""}));return}const dc=options.difficultyClass??(()=>{if(item){const proficiencyWithoutLevel=game.settings.get("pf2e","proficiencyVariant");return{label:game.i18n.format("PF2E.Actions.Repair.Labels.ItemLevelRepairDC",{level:item.level}),value:calculateDC(item.level,{proficiencyWithoutLevel}),visibility:"all"}}})(),targetItemOptions=Array.from(item?.traits??[]).map(trait=>`target:trait:${trait}`),slug=options?.skill??"crafting",rollOptions=["action:repair",...targetItemOptions],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.Repair.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),content:async title=>{if(item){const templatePath="systems/pf2e/templates/system/actions/repair/item-heading-partial.hbs",templateData={item},content=await renderTemplate(templatePath,templateData);return title+content}},traits:["exploration","manipulate"],event:options.event,difficultyClass:dc,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Repair","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Repair","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Repair","criticalFailure")],createMessage:!1,callback:async result=>{const{actor}=result;if(item&&result.message instanceof ChatMessagePF2e&&actor.isOfType("creature")){const messageSource=result.message.toObject(),flavor=await(async()=>{const proficiencyRank=actor.skills.crafting.rank??0;if(result.outcome==="criticalSuccess"){const label="PF2E.Actions.Repair.Labels.RestoreItemHitPoints",restored=String(10+proficiencyRank*10);return renderRepairResult(item,"restore",label,restored)}else if(result.outcome==="success"){const label="PF2E.Actions.Repair.Labels.RestoreItemHitPoints",restored=String(5+proficiencyRank*5);return renderRepairResult(item,"restore",label,restored)}else if(result.outcome==="criticalFailure")return renderRepairResult(item,"roll-damage","PF2E.Actions.Repair.Labels.RollItemDamage","2d6");return""})();flavor&&(messageSource.flavor+=flavor),await ChatMessage.create(messageSource)}}}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(repair,"repair"),__name2(repair,"repair");async function onRepairChatCardEvent(event,message,card){const itemUuid=card.dataset.itemUuid,item=await fromUuid(itemUuid??""),button=event.currentTarget;if(!(item instanceof PhysicalItemPF2e)||!(button instanceof HTMLElement))return;const repair2=button.dataset.repair,speaker=message&&ChatMessagePF2e.getSpeaker({actor:message.actor,alias:message.alias,token:message.token});if(repair2==="restore"){const value=Number(button.dataset.repairValue)||0,beforeRepair=item.system.hp.value,afterRepair=Math.min(item.system.hp.max,beforeRepair+value);await item.update({"system.hp.value":afterRepair});const content=game.i18n.format("PF2E.Actions.Repair.Chat.ItemRepaired",{itemName:item.name,repairedDamage:afterRepair-beforeRepair,afterRepairHitPoints:afterRepair,maximumHitPoints:item.system.hp.max});await ChatMessage.create({content,speaker})}else if(repair2==="roll-damage"){const roll=await Roll.create("2d6").evaluate({async:!0}),templatePath="systems/pf2e/templates/system/actions/repair/roll-damage-chat-message.hbs",flavor=await renderTemplate(templatePath,{damage:{dealt:Math.max(0,roll.total-item.system.hardness),rolled:roll.total},item});await roll.toMessage({flags:{pf2e:{suppressDamageButtons:!0}},flavor,speaker})}else if(repair2==="damage"){const hardness=Math.max(0,item.system.hardness),damage=(message?.rolls.at(0)?.total??0)-hardness;if(damage>0){const beforeDamage=item.system.hp.value,afterDamage=Math.max(0,item.system.hp.value-damage);await item.update({"system.hp.value":afterDamage});const content=game.i18n.format("PF2E.Actions.Repair.Chat.ItemDamaged",{itemName:item.name,damageDealt:beforeDamage-afterDamage,afterDamageHitPoints:afterDamage,maximumHitPoints:item.system.hp.max});await ChatMessage.create({content,speaker})}else{const templatePath="systems/pf2e/templates/system/actions/repair/roll-damage-chat-message.hbs",content=await renderTemplate(templatePath,{damage:{dealt:0,rolled:message?.rolls.at(0)?.total??0},item});await ChatMessage.create({content,speaker})}}}__name(onRepairChatCardEvent,"onRepairChatCardEvent"),__name2(onRepairChatCardEvent,"onRepairChatCardEvent");async function renderRepairResult(item,result,buttonLabel,value){const templatePath="systems/pf2e/templates/system/actions/repair/repair-result-partial.hbs",label=game.i18n.format(buttonLabel,{value});return renderTemplate(templatePath,{item,label,result,value})}__name(renderRepairResult,"renderRepairResult"),__name2(renderRepairResult,"renderRepairResult");const _ChatCards=class{static{__name(this,"_ChatCards")}static listen(message,html){const selector=["a[data-action], button[data-action]"].join(",");for(const button of htmlQueryAll(html,selector))button.addEventListener("click",async event=>__privateMethod(this,_onClickButton,onClickButton_fn).call(this,{message,event,html,button}))}};_lastClick=new WeakMap,_onClickButton=new WeakSet,onClickButton_fn=__name2(async function({message,event,html,button}){const currentTime=Date.now();if(currentTime-__privateGet(this,_lastClick)<500)return;__privateSet(this,_lastClick,currentTime);const action2=button.dataset.action??"",item=message.item,actor=item?.actor??message.actor;if(!actor||!game.user.isGM&&!actor.isOwner&&!["spell-save","expand-description"].includes(action2))return;const strikeAction=message._strike;if(strikeAction&&action2?.startsWith("strike-")){const context=message.rolls.some(r=>r instanceof CheckRoll)?message.flags.pf2e.context??null:null,mapIncreases=context&&"mapIncreases"in context&&tupleHasValue([0,1,2],context.mapIncreases)?context.mapIncreases:null,altUsage=context&&"altUsage"in context?context.altUsage:null,target=message.target?.token?.object??null,rollArgs={event,altUsage,mapIncreases,checkContext:context,target};switch(sluggify(action2??"")){case"strike-attack":strikeAction.variants[0].roll(rollArgs);return;case"strike-attack2":strikeAction.variants[1].roll(rollArgs);return;case"strike-attack3":strikeAction.variants[2].roll(rollArgs);return;case"strike-damage":{const method=button.dataset.outcome==="success"?"damage":"critical";strikeAction[method]?.(rollArgs);return}}}if(item){const spell=item.isOfType("spell")?item:item.isOfType("consumable")?item.embeddedSpell:null;switch(action2){case"spell-attack":return spell?.rollAttack(event);case"spell-attack-2":return spell?.rollAttack(event,2);case"spell-attack-3":return spell?.rollAttack(event,3);case"spell-damage":spell?.rollDamage(event);return;case"spell-save":return __privateMethod(this,_rollActorSaves,rollActorSaves_fn).call(this,{event,button,actor,item});case"affliction-save":item?.isOfType("affliction")&&item.rollRecovery();return;case"spell-counteract":spell?.rollCounteract(event);return;case"spell-template":return spell?.placeTemplate(message);case"spell-template-clear":{const templateIds=canvas.scene?.templates.filter(t=>t.message===message).map(t=>t.id)??[];button.disabled=!0,await canvas.scene?.deleteEmbeddedDocuments("MeasuredTemplate",templateIds),button.disabled=!1;return}case"spell-variant":{const castLevel=Number(htmlQuery(html,"div.chat-card")?.dataset.castLevel)||1,overlayIds=button.dataset.overlayIds?.split(",").map(id=>id.trim());if(overlayIds){const variantSpell=spell?.loadVariant({overlayIds,castLevel});if(variantSpell){const variantMessage=await variantSpell.toMessage(void 0,{create:!1,data:{castLevel}});if(variantMessage){const messageSource=variantMessage.toObject();await message.update(messageSource)}}}else if(spell){const originalMessage=await(spell?.original??spell).toMessage(void 0,{create:!1,data:{castLevel}});originalMessage&&await message.update(originalMessage.toObject())}return}case"consume":{if(item.isOfType("consumable"))item.consume();else if(item.isOfType("melee")){const consumable=actor.items.get(button.dataset.item??"");if(consumable?.isOfType("consumable")){const oldQuant=consumable.quantity,consumableString=game.i18n.localize("TYPES.Item.consumable"),toReplace=`${consumable.name} - ${consumableString} (${oldQuant})`;await consumable.consume();const currentQuant=oldQuant===1?0:consumable.quantity;let flavor=message.flavor.replace(toReplace,`${consumable.name} - ${consumableString} (${currentQuant})`);if(currentQuant===0){const buttonStr=`>${game.i18n.localize("PF2E.ConsumableUseLabel")}`;flavor=flavor?.replace(buttonStr," disabled"+buttonStr)}await message.update({flavor}),message.render(!0)}}return}case"expand-description":{const{description}=item,element=htmlClosest(button,".description");element&&(element.innerHTML=await TextEditor.enrichHTML(description,{async:!0,rollData:actor.getRollData()}),element.scrollIntoView({behavior:"smooth",block:"center"}));break}case"apply-effect":{button.disabled=!0;const target=fromUuidSync(button.dataset.targets??""),effect=item.isOfType("action","feat")&&item.system.selfEffect?await fromUuid(item.system.selfEffect.uuid):null;if(target instanceof ActorPF2e&&effect instanceof ItemPF2e&&effect.isOfType("effect")){await target.createEmbeddedDocuments("Item",[effect.clone().toObject()]);const parsedMessageContent=(()=>{const container=document.createElement("div");return container.innerHTML=message.content,container})(),buttons=htmlQuery(parsedMessageContent,".message-buttons");if(buttons){const span=createHTMLElement("span",{classes:["effect-applied"]}),anchor=effect.toAnchor({attrs:{draggable:"true"}}),locKey="PF2E.Item.Action.SelfAppliedEffect.Applied",statement=game.i18n.format(locKey,{effect:anchor.outerHTML});span.innerHTML=statement,buttons.replaceChildren(span),await message.update({content:parsedMessageContent.innerHTML})}}break}case"elemental-blast-damage":{if(!actor.isOfType("character"))return;const roll=message.rolls.find(r=>r instanceof CheckRoll&&r.options.action==="elemental-blast"),checkContext=roll?message.flags.pf2e.context??null:null,outcome=button.dataset.outcome==="success"?"success":"criticalSuccess",[element,damageType,meleeOrRanged,actionCost]=roll?.options.identifier?.split(".")??[];objectHasKey(elementTraits,element)&&objectHasKey(CONFIG.PF2E.damageTypes,damageType)&&await new ElementalBlast(actor).damage({element,damageType,melee:meleeOrRanged==="melee",actionCost:Number(actionCost)||1,checkContext,outcome,event})}}}else if(action2&&actor.isOfType("character","npc")){const buttonGroup=htmlClosest(button,".chat-card, .message-buttons"),physicalItem=await(async()=>{const itemUuid=buttonGroup?.dataset.itemUuid??"",maybeItem=await fromUuid(itemUuid);return maybeItem instanceof PhysicalItemPF2e?maybeItem:null})(),quantity=Number(buttonGroup?.dataset.craftingQuantity)||1;if(action2==="repair-item"&&buttonGroup)await onRepairChatCardEvent(event,message,buttonGroup);else if(physicalItem&&action2==="pay-crafting-costs"){const quantity2=Number(buttonGroup?.dataset.craftingQuantity)||1,craftingCost=CoinsPF2e.fromPrice(physicalItem.price,quantity2),coinsToRemove=button.classList.contains("full")?craftingCost:craftingCost.scale(.5);if(!await actor.inventory.removeCoins(coinsToRemove)){ui.notifications.warn(game.i18n.localize("PF2E.Actions.Craft.Warning.InsufficientCoins"));return}if(isSpellConsumable(physicalItem.id)&&physicalItem.isOfType("consumable")){craftSpellConsumable(physicalItem,quantity2,actor),ChatMessagePF2e.create({user:game.user.id,content:game.i18n.format("PF2E.Actions.Craft.Information.PayAndReceive",{actorName:actor.name,cost:coinsToRemove.toString(),quantity:quantity2,itemName:physicalItem.name}),speaker:{alias:actor.name}});return}const itemObject=physicalItem.toObject();if(itemObject.system.quantity=quantity2,!await actor.addToInventory(itemObject,void 0)){ui.notifications.warn(game.i18n.localize("PF2E.Actions.Craft.Warning.CantAddItem"));return}ChatMessagePF2e.create({user:game.user.id,content:game.i18n.format("PF2E.Actions.Craft.Information.LoseMaterials",{actorName:actor.name,cost:coinsToRemove.toString(),quantity:quantity2,itemName:physicalItem.name}),speaker:{alias:actor.name}})}else if(physicalItem&&action2==="lose-materials"){const coinsToRemove=CoinsPF2e.fromPrice(physicalItem.price,quantity).scale(.5).scale(.1);await actor.inventory.removeCoins(coinsToRemove)?ChatMessagePF2e.create({user:game.user.id,content:game.i18n.format("PF2E.Actions.Craft.Information.PayAndReceive",{actorName:actor.name,cost:coinsToRemove.toString()}),speaker:{alias:actor.name}}):ui.notifications.warn(game.i18n.localize("PF2E.Actions.Craft.Warning.InsufficientCoins"))}else if(action2==="receieve-crafting-item"&&physicalItem)return isSpellConsumable(physicalItem.id)&&physicalItem.isOfType("consumable")?craftSpellConsumable(physicalItem,quantity,actor):craftItem(physicalItem,quantity,actor)}},"#onClickButton"),_rollActorSaves=new WeakSet,rollActorSaves_fn=__name2(async function({event,button,actor,item}){if(canvas.tokens.controlled.length>0){const saveType=button.dataset.save;if(!tupleHasValue(SAVE_TYPES,saveType))throw ErrorPF2e(`"${saveType}" is not a recognized save type`);const dc=Number(button.dataset.dc??"NaN");for(const token of canvas.tokens.controlled){const save=token.actor?.saves?.[saveType];if(!save)return;save.check.roll({...eventToRollParams(event),dc:Number.isInteger(dc)?{value:Number(dc)}:null,item,origin:actor})}}else ui.notifications.error(game.i18n.localize("PF2E.UI.errorTargetToken"))},"#rollActorSaves"),__privateAdd(_ChatCards,_onClickButton),__privateAdd(_ChatCards,_rollActorSaves),__name2(_ChatCards,"ChatCards"),__privateAdd(_ChatCards,_lastClick,0);let ChatCards=_ChatCards;const DamageTaken={listen:async(message,html)=>{const damageTakenCard=htmlQuery(html,".damage-taken");if(!damageTakenCard)return;const settingEnabled=game.settings.get("pf2e","metagame_tokenSetsNameVisibility");if(!game.user.isGM&&settingEnabled&&message.token&&!message.token.playersCanSeeName){const nameElem=htmlQuery(damageTakenCard,".target-name");nameElem&&(nameElem.innerText=game.i18n.localize("PF2E.Actor.ApplyDamage.TheTarget"))}const iwrInfo=htmlQuery(damageTakenCard,".iwr");if(!iwrInfo)return;const iwrApplications=(()=>{try{const parsed=JSON.parse(iwrInfo?.dataset.applications??"null");return Array.isArray(parsed)&&parsed.every(a=>a instanceof Object&&"category"in a&&typeof a.category=="string"&&"type"in a&&typeof a.type=="string"&&"adjustment"in a&&typeof a.adjustment=="number")?parsed:null}catch{return null}})();iwrApplications&&$(iwrInfo).tooltipster({theme:"crb-hover",maxWidth:400,content:await renderTemplate("systems/pf2e/templates/chat/damage/iwr-breakdown.hbs",{applications:iwrApplications}),contentAsHTML:!0})}},DegreeOfSuccessHighlights={listen:(message,html)=>{if(htmlQueryAll(html,".pf2e-reroll-indicator").length>0)return;const firstRoll=message.rolls.at(0);if(!firstRoll||message.isDamageRoll)return;const firstDice=firstRoll.dice.at(0);if(!(firstDice instanceof Die&&firstDice.faces===20&&message.isContentVisible))return;const diceTotal=htmlQuery(html,".dice-total"),results=firstDice.results.filter(r=>r.active);results.every(r=>r.result===20)?diceTotal?.classList.add("success"):results.every(r=>r.result===1)&&diceTotal?.classList.add("failure")}},SetAsInitiative={listen:li=>{const message=game.messages.get(li.dataset.messageId??"",{strict:!0}),{context}=message.flags.pf2e;if(message.token&&(message.isAuthor&&!message.blind||game.user.isGM)&&(context?.type==="skill-check"||context?.type==="perception-check")){const btnContainer=document.createElement("span");btnContainer.classList.add("dmgBtn-container"),Object.assign(btnContainer.style,{position:"absolute",right:"0",bottom:"1px"});const setInitiativeButton=document.createElement("button");setInitiativeButton.classList.add("dice-total-setInitiative-btn"),Object.assign(setInitiativeButton.style,{width:"22px",height:"22px",fontSize:"10px",lineHeight:"1px"}),setInitiativeButton.title=game.i18n.localize("PF2E.ClickToSetInitiative"),setInitiativeButton.appendChild(fontAwesomeIcon("fa-swords",{style:"solid"})),btnContainer.appendChild(setInitiativeButton);const selector=message.isReroll?".pf2e-reroll-second .dice-total":".dice-total";li.querySelector(selector)?.appendChild(btnContainer),setInitiativeButton.addEventListener("click",async event=>{event.stopPropagation();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:actor.name,initiative:value}))})}}},MessageTooltips={listen:html=>{const targetDC=htmlQuery(html,".target-dc");targetDC?.innerHTML.trim()===""&&targetDC.remove();const dcResult=htmlQuery(html,".dc-result");dcResult?.innerHTML.trim()===""&&dcResult.remove();try{const adjustedDCLabel=htmlQuery(html,".adjusted[data-circumstances]");if(adjustedDCLabel){const circumstances=JSON.parse(adjustedDCLabel.dataset.circumstances??"");if(!Array.isArray(circumstances))throw ErrorPF2e("Malformed adjustments array");const content=circumstances.map(a=>{const sign=a.value>=0?"+":"";return $("
").text(`${a.label}: ${sign}${a.value}`)}).reduce(($concatted,$a)=>$concatted.append($a),$("
")).prop("outerHTML");$(adjustedDCLabel).tooltipster({content,contentAsHTML:!0,theme:"crb-hover"})}}catch(error){error instanceof Error&&console.error(error.message)}const dosLabel=htmlQuery(html,".degree-of-success .adjusted");dosLabel?.dataset.adjustment&&$(dosLabel).tooltipster({content:game.i18n.localize(dosLabel.dataset.adjustment),contentAsHTML:!0,theme:"crb-hover"});for(const tag of htmlQueryAll(html,".tag[data-material], .tag[data-slug], .tag[data-trait]")){const description=tag.dataset.description;description&&$(tag).tooltipster({content:game.i18n.localize(description),maxWidth:400,theme:"crb-hover"})}}},_ChatMessagePF2e=class _ChatMessagePF2e2 extends ChatMessage{static{__name(this,"_ChatMessagePF2e")}constructor(data={},context={}){const expandedFlags=expandObject(data.flags??{});data.flags=mergeObject(expandedFlags,{core:{canPopout:expandedFlags.core?.canPopout??!0},pf2e:{}}),super(data,context),__privateAdd(this,_onHoverIn),__privateAdd(this,_onHoverOut)}get isDamageRoll(){const firstRoll=this.rolls.at(0);if(!firstRoll||firstRoll.terms.some(t=>t instanceof FateDie||t instanceof Coin))return!1;if(this.flags.pf2e.context?.type==="damage-roll")return!0;const isCheck=firstRoll instanceof CheckRoll||firstRoll.dice[0]?.faces===20,fromRollTable=!!this.flags.core.RollTable;return!(isCheck||fromRollTable)}get actor(){return _ChatMessagePF2e2.getSpeakerActor(this.speaker)}get target(){const context=this.flags.pf2e.context;if(!context)return null;const targetUUID="target"in context?context.target?.token:null;if(!targetUUID)return null;const match=/^Scene\.(\w+)\.Token\.(\w+)$/.exec(targetUUID??"")??[],token=game.scenes.get(match[1]??"")?.tokens.get(match[2]??""),actor=token?.actor;return actor?{actor,token}:null}get journalEntry(){const uuid=this.flags.pf2e.journalEntry;if(!uuid)return null;const entryId=/^JournalEntry.([A-Za-z0-9]{16})$/.exec(uuid)?.at(1);return game.journal.get(entryId??"")??null}get isCheckRoll(){return this.rolls[0]instanceof CheckRoll}get isReroll(){const context=this.flags.pf2e.context;return!!context&&"isReroll"in context&&!!context.isReroll}get isRerollable(){const roll=this.rolls[0];return!!(this.actor?.isOwner&&(this.isAuthor||this.isOwner)&&roll instanceof CheckRoll&&roll.isRerollable)}get item(){if(this.flags.pf2e.context?.type==="self-effect")return this.actor?.items.get(this.flags.pf2e.context.item)??null;const strike=this._strike;if(strike?.item)return strike.item;const item=(()=>{const domItem=this.getItemFromDOM();if(domItem)return domItem;const origin=this.flags.pf2e?.origin??null,match=/Item\.(\w+)/.exec(origin?.uuid??"")??[];return this.actor?.items.get(match?.[1]??"")??null})();if(!item)return null;const{tradition}=this.flags.pf2e?.casting??{},isCharacter=item.actor.isOfType("character");if(tradition&&item.isOfType("spell")&&!item.spellcasting&&isCharacter){const trick=new TrickMagicItemEntry(item.actor,traditionSkills[tradition]);item.trickMagicEntry=trick}if(item?.isOfType("spell")){const overlayIds=this.flags.pf2e.origin?.variant?.overlays,castLevel=this.flags.pf2e.origin?.castLevel??item.rank;return item.loadVariant({overlayIds,castLevel})??item}return item}get _strike(){const{actor}=this,identifier=this.rolls.find(r=>r instanceof CheckRoll)?.options.identifier??htmlQuery(document.body,`li.message[data-message-id="${this.id}"] [data-identifier]`)?.dataset.identifier,[itemId,slug,meleeOrRanged]=identifier?.split(".")??[null,null,null];if(!meleeOrRanged||!["melee","ranged"].includes(meleeOrRanged))return null;const strikeData=actor?.system.actions?.find(s=>s.slug===slug&&s.item.id===itemId),itemMeleeOrRanged=strikeData?.item.isMelee?"melee":"ranged";return meleeOrRanged===itemMeleeOrRanged?strikeData??null:strikeData?.altUsages?.find(u=>{const altUsageMeleeOrRanged=u.item.isMelee?"melee":"ranged";return meleeOrRanged===altUsageMeleeOrRanged})??null}getItemFromDOM(){const html=ui.chat.element[0],messageElem=htmlQuery(html,`#chat-log > li[data-message-id="${this.id}"]`),sourceString=htmlQuery(messageElem,".pf2e.item-card")?.dataset.embeddedItem??"null";try{const itemSource=JSON.parse(sourceString);return itemSource?new ItemProxyPF2e(itemSource,{parent:this.actor,fromConsumable:this.flags?.pf2e?.isFromConsumable}):null}catch{return null}}async showDetails(){this.flags.pf2e.context&&new ChatInspectRoll(this).render(!0)}get token(){if(!game.scenes)return null;const sceneId=this.speaker.scene??"",tokenId=this.speaker.token??"";return game.scenes.get(sceneId)?.tokens.get(tokenId)??null}getRollData(){const{actor,item}=this;return{...actor?.getRollData(),...item?.getRollData()}}async getHTML(){const{actor}=this;if(this.isContentVisible){const rollData=this.getRollData();this.flavor=await TextEditorPF2e.enrichHTML(this.flavor,{async:!0,rollData,processVisibility:!1})}const $html=await super.getHTML(),html=$html[0];!this.flags.pf2e.suppressDamageButtons&&this.isDamageRoll&&htmlQueryAll(html,".damage-application").forEach((buttons,index)=>{buttons.dataset.rollIndex=index.toString()}),UserVisibilityPF2e.process(html,{message:this}),await DamageTaken.listen(this,html),CriticalHitAndFumbleCards.appendButtons(this,$html),ChatCards.listen(this,html),InlineRollLinks.listen(html,this),DegreeOfSuccessHighlights.listen(this,html),MessageTooltips.listen(html),canvas.ready&&SetAsInitiative.listen(html);const roll=this.rolls[0];if(actor?.isOwner&&roll instanceof DamageRoll&&roll.options.evaluatePersistent){const damageType=roll.instances.find(i=>i.persistent)?.type;if(damageType?this.actor?.getCondition(`persistent-damage-${damageType}`):null){const template="systems/pf2e/templates/chat/persistent-damage-recovery.hbs",section=parseHTML(await renderTemplate(template));html.querySelector(".message-content")?.append(section),html.dataset.actorIsTarget="true"}htmlQuery(html,"[data-action=recover-persistent-damage]")?.addEventListener("click",()=>{const{actor:actor2}=this;if(!actor2)return;const damageType2=roll.instances.find(i=>i.persistent)?.type;if(!damageType2)return;const condition2=actor2.getCondition(`persistent-damage-${damageType2}`);if(!condition2?.system.persistent){const damageTypeLocalized=game.i18n.localize(CONFIG.PF2E.damageTypes[damageType2]??damageType2),message=game.i18n.format("PF2E.Item.Condition.PersistentDamage.Error.DoesNotExist",{damageType:damageTypeLocalized});ui.notifications.warn(message);return}condition2.rollRecovery()})}return this.flags.pf2e.appliedDamage?.isReverted||this.actor?.isOwner||htmlQuery(html,"button[data-action=revert-damage]")?.remove(),html.addEventListener("mouseenter",event=>__privateMethod(this,_onHoverIn,onHoverIn_fn).call(this,event)),html.addEventListener("mouseleave",event=>__privateMethod(this,_onHoverOut,onHoverOut_fn).call(this,event)),UserVisibilityPF2e.processMessageSender(this,html),!actor&&this.content&&UserVisibilityPF2e.process(html,{document:this}),$html}_onCreate(data,options,userId){super._onCreate(data,options,userId),this.isRoll&&game.settings.get("pf2e","drawCritFumble")&&CriticalHitAndFumbleCards.handleDraw(this)}};_onHoverIn=new WeakSet,onHoverIn_fn=__name2(function(nativeEvent){if(!canvas.ready)return;const token=this.token?.object;token?.isVisible&&!token.controlled&&token.emitHoverIn(nativeEvent)},"#onHoverIn"),_onHoverOut=new WeakSet,onHoverOut_fn=__name2(function(nativeEvent){canvas.ready&&this.token?.object?.emitHoverOut(nativeEvent)},"#onHoverOut"),__name2(_ChatMessagePF2e,"ChatMessagePF2e");let ChatMessagePF2e=_ChatMessagePF2e;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");const _ItemPF2e=class _ItemPF2e2 extends Item{static{__name(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 _ItemPF2e2&&item.parent&&!item.sourceId&&(item._source.flags=mergeObject(item._source.flags,{core:{sourceId:item.uuid}}),item.flags=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.sort()}getRollData(){return{...this.actor?.getRollData()??{actor:null},item:this}}async toMessage(event,{rollMode=void 0,create=!0,data={}}={}){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=event?.currentTarget.closest(".item")??{},contextualData=Object.keys(data).length>0?data:nearestItem.dataset||{},templateData={actor:this.actor,tokenId:token?`${token.parent?.id}.${token.id}`:null,item:this,data:await this.getChatData(void 0,contextualData)},chatData={speaker:ChatMessagePF2e.getSpeaker({actor:this.actor,token:this.actor.getActiveTokens(!1,!0)[0]??null}),flags:{pf2e:{origin:this.getOriginData()}},type:CONST.CHAT_MESSAGE_TYPES.OTHER};return rollMode??=event?.ctrlKey||event?.metaKey?"blindroll":game.settings.get("core","rollMode"),["gmroll","blindroll"].includes(rollMode)&&(chatData.whisper=ChatMessagePF2e.getWhisperRecipients("GM").map(u=>u.id)),rollMode==="blindroll"&&(chatData.blind=!0),chatData.content=await renderTemplate(template,templateData),create?ChatMessagePF2e.create(chatData,{renderSheet:!1}):new ChatMessagePF2e(chatData)}async toChat(event){return this.toMessage(event,{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=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={}){if(!this.isOwned){ui.notifications.error("This utility may only be used on owned items");return}if(!this.sourceId?.startsWith("Compendium.")){ui.notifications.warn(`Item "${this.name}" has no compendium source.`);return}options.name??=!1;const currentSource=this.toObject(),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(`The compendium source for "${this.name}" (source ID: ${this.sourceId}) was not found.`);return}const updates={img:currentSource.img.endsWith(".svg")?latestSource.img:currentSource.img,system:latestSource.system};if(options.name&&(updates.name=latestSource.name),isPhysicalData(currentSource)){const{containerId,quantity}=currentSource.system;mergeObject(updates,expandObject({"system.containerId":containerId,"system.quantity":quantity}))}else(currentSource.type==="feat"||currentSource.type==="spell")&&mergeObject(updates,expandObject({"system.location":currentSource.system.location}));if(currentSource.type==="weapon"||currentSource.type==="armor"){const materialAndRunes={"system.material":currentSource.system.material,"system.potencyRune":currentSource.system.potencyRune,"system.propertyRune1":currentSource.system.propertyRune1,"system.propertyRune2":currentSource.system.propertyRune2,"system.propertyRune3":currentSource.system.propertyRune3,"system.propertyRune4":currentSource.system.propertyRune4};currentSource.type==="weapon"?materialAndRunes["system.strikingRune"]=currentSource.system.strikingRune:materialAndRunes["system.resiliencyRune"]=currentSource.system.resiliencyRune,mergeObject(updates,expandObject(materialAndRunes))}await this.update(updates,{diff:!1,recursive:!1}),ui.notifications.info(`Item "${this.name}" has been refreshed.`)}getOriginData(){return{uuid:this.uuid,type:this.type}}async processChatData(htmlOptions={},data){if(data.properties=data.properties?.filter(property=>property!==null)??[],isItemSystemData(data)){const chatData=duplicate(data);return htmlOptions.rollData=mergeObject(this.getRollData(),htmlOptions.rollData??{}),chatData.description.value=await TextEditor.enrichHTML(chatData.description.value,{...htmlOptions,async:!0}),chatData}return data}async getChatData(htmlOptions={},_rollOptions2={}){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,deepClone(systemData))}traitChatData(dictionary={}){return[...this.system.traits?.value??[]].sort().map(trait=>{const label=dictionary[trait]??trait,traitDescriptions2=CONFIG.PF2E.traitsDescriptions;return{value:trait,label,description:traitDescriptions2[trait]}})}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 _ItemPF2e2?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);const validTypes=actor.allowedItemTypes;validTypes.includes("physical")&&validTypes.push(...PHYSICAL_ITEM_TYPES,"kit");for(const source of sources)if(!validTypes.includes(source.type))return ui.notifications.error(game.i18n.format("PF2E.Item.CannotAddType",{type:game.i18n.localize(CONFIG.Item.typeLabels[source.type]??source.type.titleCase())})),[];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](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=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,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&&mergeObject(actorUpdates,{items:itemUpdates})}}const updateKeys=Object.keys(actorUpdates);updateKeys.length>0&&!updateKeys.every(k=>k==="_id")&&this.actor.update(actorUpdates)}};__name2(_ItemPF2e,"ItemPF2e");let ItemPF2e=_ItemPF2e;const ItemProxyPF2e=new Proxy(ItemPF2e,{construct(_target2,args){const ItemClass=CONFIG.PF2E.Item.documentClasses[args[0]?.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"&&expiry==="turn-end"?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,isEffectTurnStart=startInitiative===currentInitiative&&combatant.actor===(effect.origin??fightyActor);result.expired=isEffectTurnStart?expiry==="turn-start":currentInitiative`${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 _AbstractEffectPF2e2&&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()}}};__name2(_AbstractEffectPF2e,"AbstractEffectPF2e");let AbstractEffectPF2e=_AbstractEffectPF2e;const _ConditionManager=class _ConditionManager2{static{__name(this,"_ConditionManager")}static get conditionsSlugs(){return[...this.conditions.keys()].filter(k=>!k.startsWith("Compendium."))}static async initialize(force=!1){if(__privateGet(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),(!__privateGet(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`)}__privateSet(this,_initialized,!0)}static getCondition(slug,modifications={}){if(slug=sluggify(slug),!setHasElement(CONDITION_SLUGS,slug))return null;const condition=_ConditionManager2.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})))}};_initialized=new WeakMap,__name2(_ConditionManager,"ConditionManager"),__privateAdd(_ConditionManager,_initialized,!1),__publicField(_ConditionManager,"conditions",new Map),__publicField(_ConditionManager,"CONDITION_SOURCES",[{_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 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:.878,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.

+}`)}};__name2(_Migration723CumulativeItemBonuses,"Migration723CumulativeItemBonuses"),__publicField(_Migration723CumulativeItemBonuses,"version",.723);let Migration723CumulativeItemBonuses=_Migration723CumulativeItemBonuses;const _Migration724CraftingMaxItemLevel=class extends MigrationBase{static{__name(this,"_Migration724CraftingMaxItemLevel")}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=mergeObject({all:[]},isObject(rule.predicate)?rule.predicate:{}),slug=sluggify(selector);predicate.all=Array.from(new Set([...predicate.all,`crafting:entry:${slug}`]))}}}};__name2(_Migration724CraftingMaxItemLevel,"Migration724CraftingMaxItemLevel"),__publicField(_Migration724CraftingMaxItemLevel,"version",.724);let Migration724CraftingMaxItemLevel=_Migration724CraftingMaxItemLevel;const _Migration725QuickClimbREs=class extends MigrationBase{static{__name(this,"_Migration725QuickClimbREs")}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:'

{item|name} You move 5 more feet on a success, and 10 more feet on a critical success.

'}];async updateItem(source){source.type==="feat"&&source.system.slug==="quick-climb"&&(source.system.rules=deepClone(this.quickClimb))}};__name2(_Migration725QuickClimbREs,"Migration725QuickClimbREs"),__publicField(_Migration725QuickClimbREs,"version",.725);let Migration725QuickClimbREs=_Migration725QuickClimbREs;const _Migration726JournalSetting=class extends MigrationBase{static{__name(this,"_Migration726JournalSetting")}async migrate(){const sheetClasses=game.settings.get("core","sheetClasses");if(isObject(sheetClasses)&&sheetClasses.JournalEntry?.base)return;const theme=game.settings.storage.get("world").getItem("pf2e.journalEntryTheme");if(!theme)return;const base=theme==="pf2eTheme"?"pf2e.JournalSheetStyledPF2e":"pf2e.JournalSheetPF2e";DocumentSheetConfig.updateDefaultSheets({JournalEntry:{base}})}};__name2(_Migration726JournalSetting,"Migration726JournalSetting"),__publicField(_Migration726JournalSetting,"version",.726);let Migration726JournalSetting=_Migration726JournalSetting;const _Migration727TrimSelfRollOptions=class extends MigrationBase{static{__name(this,"_Migration727TrimSelfRollOptions")}optionPattern=/^self:(ability|class|feat(?:ure)?|perception|skill):/;optionReplacement="$1:";trimRollOption(option){return option.replace(this.optionPattern,this.optionReplacement)}trimPredicates(obj){for(const[key,value]of Object.entries(obj))typeof value=="string"?obj[key]=this.trimRollOption(value):Array.isArray(value)?obj[key]=value.map(e=>typeof e=="string"?this.trimRollOption(e):isObject(e)?this.trimPredicates(e):e):isObject(value)&&(obj[key]=this.trimPredicates(value));return obj}async updateItem(source){source.system.rules=source.system.rules.map(r=>this.trimPredicates(r))}};__name2(_Migration727TrimSelfRollOptions,"Migration727TrimSelfRollOptions"),__publicField(_Migration727TrimSelfRollOptions,"version",.727);let Migration727TrimSelfRollOptions=_Migration727TrimSelfRollOptions;const _Migration728FlattenPhysicalProperties=class extends MigrationBase{static{__name(this,"_Migration728FlattenPhysicalProperties")}booleanKeys=["temporary","collapsed"];numericKeys=["quantity","hardness"];stringKeys=["stackGroup","containerId"];async updateItem(source){if(!isPhysicalData(source))return;const systemSource=source.system;if(systemSource.currency&&(delete systemSource.currency,systemSource["-=currency"]=null),systemSource.hands&&(delete systemSource.hands,systemSource["-=hands"]=null),systemSource.equipped&&systemSource.invested instanceof Object){const value=systemSource.invested.value;if(typeof value=="boolean"||value===null){const shouldBeBoolean=source.system.traits.value.includes("invested")||source.type==="armor"&&(source.system.potencyRune.value??0)>0;systemSource.equipped.invested=shouldBeBoolean?!!value:null}}if(delete systemSource.invested,systemSource["-=invested"]=null,systemSource.capacity&&source.type!=="book"&&(delete systemSource.capacity,systemSource["-=capacity"]=null),source.type!=="backpack"&&(delete systemSource.bulkCapacity,systemSource["-=bulkCapacity"]=null,delete systemSource.collapsed,systemSource["-=collapsed"]=null),systemSource.size instanceof Object){const size=SIZES.includes(systemSource.size.value)?systemSource.size.value:"med";systemSource.size=size}"brokenThreshold"in systemSource&&(systemSource.brokenThreshold instanceof Object&&(systemSource.hp.brokenThreshold=Number(systemSource.brokenThreshold.value)),delete systemSource.brokenThreshold,systemSource["-=brokenThreshold"]=null),systemSource.hp.value=Number(systemSource.hp.value),systemSource.maxHp instanceof Object&&(systemSource.hp.max=Number(systemSource.maxHp.value)||0,delete systemSource.maxHp,systemSource["-=maxHp"]=null);for(const key of this.booleanKeys){const value=systemSource[key];value instanceof Object&&(systemSource[key]=value.value)}for(const key of this.numericKeys){const value=systemSource[key];value instanceof Object&&(systemSource[key]=Number(value.value)||0)}for(const key of this.stringKeys){const value=systemSource[key];value instanceof Object&&(systemSource[key]=String(value.value)||null)}}};__name2(_Migration728FlattenPhysicalProperties,"Migration728FlattenPhysicalProperties"),__publicField(_Migration728FlattenPhysicalProperties,"version",.728);let Migration728FlattenPhysicalProperties=_Migration728FlattenPhysicalProperties;const _Migration729CumulativeItemBonusCleanup=class extends MigrationBase{static{__name(this,"_Migration729CumulativeItemBonusCleanup")}constructor(){super(...arguments),__privateAdd(this,_explorersClothingVariants,new Set(["clothing-explorers","robe-of-the-arch-magi","robe-of-the-arch-magi-greater","sarkorian-god-caller-garb"]))}isExplorersClothing(source){return source.type==="armor"&&__privateGet(this,_explorersClothingVariants).has(source.system.slug??"")}isStanceEffectOrAnimalSkinFeat(source){return source.type==="effect"&&source.system.slug==="stance-mountain-stance"||source.type==="feat"&&source.system.slug==="animal-skin"}async updateItem(source){if(this.isExplorersClothing(source))source.system.category="unarmored",source.system.group="cloth",source.system.baseItem="explorers-clothing",source.system.traits.value.includes("comfort")||source.system.traits.value.push("comfort");else if(this.isStanceEffectOrAnimalSkinFeat(source)){const rule=source.system.rules.find(r=>r.key==="AdjustModifier"&&r.slug==="clothing-explorers");rule&&(rule.slug="explorers-clothing")}else if(source.type==="equipment"){const isBracers=!!source.system.slug?.startsWith("bracers-of-armor-");for(const rule of source.system.rules)rule.key==="FlatModifier"&&rule.slug==="bracers-of-armor"&&!isBracers&&(source.system.slug==="metuaks-pendant"?rule.slug="metuaks-pendant":delete rule.slug)}}};_explorersClothingVariants=new WeakMap,__name2(_Migration729CumulativeItemBonusCleanup,"Migration729CumulativeItemBonusCleanup"),__publicField(_Migration729CumulativeItemBonusCleanup,"version",.729);let Migration729CumulativeItemBonusCleanup=_Migration729CumulativeItemBonusCleanup;const _Migration730DeruneHandwraps=class extends MigrationBase{static{__name(this,"_Migration730DeruneHandwraps")}async updateItem(source){if(source.type==="weapon"&&source.system.slug==="handwraps-of-mighty-blows"){const{rules}=source.system;for(const rule of[...rules])["Striking","WeaponPotency"].includes(String(rule.key))&&source.system.rules.splice(rules.indexOf(rule),1)}}};__name2(_Migration730DeruneHandwraps,"Migration730DeruneHandwraps"),__publicField(_Migration730DeruneHandwraps,"version",.73);let Migration730DeruneHandwraps=_Migration730DeruneHandwraps;const _Migration731TogglePropertyToRollOption=class extends Migration727TrimSelfRollOptions{static{__name(this,"_Migration731TogglePropertyToRollOption")}constructor(){super(...arguments),__publicField(this,"optionPattern",/^target:flatFooted$/),__publicField(this,"optionReplacement","target:condition:flat-footed"),__privateAdd(this,_pathPattern,/^flags\.pf2e\.rollOptions\.([^.]+)\.([^.]+)$/)}async updateItem(source){source.system.rules=source.system.rules.map(r=>this.trimPredicates(r));const rules=source.system.rules;for(const rule of[...rules]){if(rule.key!=="ToggleProperty")continue;const match=__privateGet(this,_pathPattern).exec(rule.property?.trim()??"");if(!(match?.length===3&&match[1].length>=2&&match[2].length>=1)){rules.splice(rules.indexOf(rule),1);continue}rule.key="RollOption",rule.domain=match[1],rule.option=match[2],rule.toggleable=!0,delete rule.property,typeof rule.default=="boolean"&&(rule.value=rule.default,delete rule.default),sluggify(String(rule.label??""))===source.system.slug&&delete rule.label}}async updateActor(source){source.flags.pf2e?.rollOptions?.all&&(source.flags.pf2e.rollOptions.all["-=panache"]=!1,source.flags.pf2e.rollOptions.all["-=rage"]=!1,source.flags.pf2e.rollOptions.all["-=target:flatFooted"]=!1)}};_pathPattern=new WeakMap,__name2(_Migration731TogglePropertyToRollOption,"Migration731TogglePropertyToRollOption"),__publicField(_Migration731TogglePropertyToRollOption,"version",.731);let Migration731TogglePropertyToRollOption=_Migration731TogglePropertyToRollOption;const _Migration732FixDedicationFeatTypes=class extends MigrationBase{static{__name(this,"_Migration732FixDedicationFeatTypes")}constructor(){super(...arguments),__privateAdd(this,_hasWellFormedFeatType)}async updateItem(source){if(source.type==="feat"){const system=source.system;if(!__privateMethod(this,_hasWellFormedFeatType,hasWellFormedFeatType_fn).call(this,system))system.featType={value:"bonus"};else{const{featType}=system;(featType.value==="dedication"||featType.value==="class"&&source.system.slug?.endsWith("-dedication"))&&(featType.value="archetype")}}}};_hasWellFormedFeatType=new WeakSet,hasWellFormedFeatType_fn=__name2(function(system){return"featType"in system&&isObject(system.featType)&&"value"in system.featType&&typeof system.featType=="string"},"#hasWellFormedFeatType"),__name2(_Migration732FixDedicationFeatTypes,"Migration732FixDedicationFeatTypes"),__publicField(_Migration732FixDedicationFeatTypes,"version",.732);let Migration732FixDedicationFeatTypes=_Migration732FixDedicationFeatTypes;const _Migration733ItemBonusFromEquipment=class extends MigrationBase{static{__name(this,"_Migration733ItemBonusFromEquipment")}slugs=new Set(["animal-skin","stance-mountain-stance","spell-effect-mage-armor"]);async updateItem(source){const compendiumItem=this.slugs.has(source.system.slug??""),homebrewItem=!compendiumItem&&source.type==="feat";if(!(compendiumItem||homebrewItem))return;const rules=source.system.rules;for(const rule of rules)rule.key==="FlatModifier"&&rule.type==="item"&&(rule.fromEquipment=!1)}};__name2(_Migration733ItemBonusFromEquipment,"Migration733ItemBonusFromEquipment"),__publicField(_Migration733ItemBonusFromEquipment,"version",.733);let Migration733ItemBonusFromEquipment=_Migration733ItemBonusFromEquipment;const _Migration734SpellLocationPropsAndSignature=class extends MigrationBase{static{__name(this,"_Migration734SpellLocationPropsAndSignature")}async updateActor(actor){const entries=actor.items.filter(item=>item.type==="spellcastingEntry"),spells=actor.items.filter(item=>item.type==="spell");for(const spellSource of spells){const spellData=spellSource.system,entrySource=entries.find(entry=>entry._id===spellData.location.value);if(!entrySource)continue;const entryData=entrySource.system;if(!entryData.signatureSpells)continue;entryData.signatureSpells.value.includes(spellSource._id??"")&&(spellData.location.signature=!0)}}async updateItem(source,actor){if(source.type==="spellcastingEntry"){const data=source.system;data.signatureSpells&&(delete data.signatureSpells,"game"in globalThis&&(data["-=signatureSpells"]=null))}if(source.type==="spell"){const data=source.system;(data.heightenedLevel||data.autoHeightenLevel)&&(actor&&(data.location.heightenedLevel=data.heightenedLevel?.value??void 0,data.location.autoHeightenLevel=data.autoHeightenLevel?.value??void 0),delete data.autoHeightenLevel,delete data.heightenedLevel,"game"in globalThis&&(data["-=autoHeightenLevel"]=null,data["-=heightenedLevel"]=null))}}};__name2(_Migration734SpellLocationPropsAndSignature,"Migration734SpellLocationPropsAndSignature"),__publicField(_Migration734SpellLocationPropsAndSignature,"version",.734);let Migration734SpellLocationPropsAndSignature=_Migration734SpellLocationPropsAndSignature;const _Migration735FirearmAmmoAlchemical=class extends MigrationBase{static{__name(this,"_Migration735FirearmAmmoAlchemical")}constructor(){super(...arguments),__privateAdd(this,_needsTrait)}async updateItem(source){source.type==="consumable"&&__privateMethod(this,_needsTrait,needsTrait_fn).call(this,source)&&source.system.traits.value.unshift("alchemical")}};_needsTrait=new WeakSet,needsTrait_fn=__name2(function(source){return source.system.consumableType.value==="ammo"&&!!source.system.stackGroup?.startsWith("rounds")&&source.system.slug!=="cutlery"&&!source.system.traits.value.includes("alchemical")},"#needsTrait"),__name2(_Migration735FirearmAmmoAlchemical,"Migration735FirearmAmmoAlchemical"),__publicField(_Migration735FirearmAmmoAlchemical,"version",.735);let Migration735FirearmAmmoAlchemical=_Migration735FirearmAmmoAlchemical;const _Migration736RemoveBrokenThreshold=class extends MigrationBase{static{__name(this,"_Migration736RemoveBrokenThreshold")}constructor(){super(...arguments),__privateAdd(this,_hasBrokenThreshold)}async updateItem(source){__privateMethod(this,_hasBrokenThreshold,hasBrokenThreshold_fn).call(this,source)&&(delete source.system.brokenThreshold,source.system["-=brokenThreshold"]=null)}};_hasBrokenThreshold=new WeakSet,hasBrokenThreshold_fn=__name2(function(source){return isPhysicalData(source)&&"brokenThreshold"in source.system},"#hasBrokenThreshold"),__name2(_Migration736RemoveBrokenThreshold,"Migration736RemoveBrokenThreshold"),__publicField(_Migration736RemoveBrokenThreshold,"version",.736);let Migration736RemoveBrokenThreshold=_Migration736RemoveBrokenThreshold;const _Migration737NormalizeRuleElementKeys=class extends Migration731TogglePropertyToRollOption{static{__name(this,"_Migration737NormalizeRuleElementKeys")}async updateItem(source){const rules=source.system.rules;for(const rule of[...rules]){if(!isObject(rule)||typeof rule.key!="string"){rules.splice(rules.indexOf(rule),1);continue}rule.key=rule.key.trim().replace(/^PF2E\.RuleElement\./,"")}return super.updateItem(source)}};__name2(_Migration737NormalizeRuleElementKeys,"Migration737NormalizeRuleElementKeys"),__publicField(_Migration737NormalizeRuleElementKeys,"version",.737);let Migration737NormalizeRuleElementKeys=_Migration737NormalizeRuleElementKeys;const _Migration738UpdateLaughingShadow=class extends MigrationBase{static{__name(this,"_Migration738UpdateLaughingShadow")}constructor(){super(...arguments),__privateAdd(this,_shadowPromise,fromUuid("Compendium.pf2e.classfeatures.3gVDqDPSz4fB5T9G")),__privateAdd(this,_cascadePromise,fromUuid("Compendium.pf2e.feature-effects.fsjO5oTKttsbpaKl"))}async updateActor(source){const rollOptionsAll=source.flags.pf2e?.rollOptions?.all;rollOptionsAll instanceof Object&&"feature:laughing-shadow:damage"in rollOptionsAll&&(rollOptionsAll["-=feature:laughing-shadow:damage"]=!1)}async updateItem(source){if(source.type==="feat"&&source.system.slug==="laughing-shadow"){const laughingShadow=await __privateGet(this,_shadowPromise);if(!(laughingShadow instanceof ItemPF2e))return;source.system.rules=deepClone(laughingShadow._source.system.rules)}else if(source.type==="effect"&&source.system.slug==="stance-arcane-cascade"){const arcaneCascade=await __privateGet(this,_cascadePromise);if(!(arcaneCascade instanceof ItemPF2e))return;const newRules=deepClone(arcaneCascade._source.system.rules),withSelection=source.system.rules.find(r=>r.key==="ChoiceSet"&&typeof r.selection=="string");if(withSelection){const unselected=newRules.find(r=>r.key==="ChoiceSet");unselected&&(unselected.selection=withSelection.selection)}source.system.rules=newRules}}};_shadowPromise=new WeakMap,_cascadePromise=new WeakMap,__name2(_Migration738UpdateLaughingShadow,"Migration738UpdateLaughingShadow"),__publicField(_Migration738UpdateLaughingShadow,"version",.738);let Migration738UpdateLaughingShadow=_Migration738UpdateLaughingShadow;const _Migration739RecoveryCheckDC=class extends MigrationBase{static{__name(this,"_Migration739RecoveryCheckDC")}toughness=[{key:"FlatModifier",selector:"hp",value:"@actor.level"},{key:"ActiveEffectLike",mode:"downgrade",path:"system.attributes.dying.recoveryDC",value:9}];defyDeath=[{key:"ActiveEffectLike",mode:"downgrade",predicate:{not:["feat:toughness"]},path:"system.attributes.dying.recoveryDC",value:9},{key:"ActiveEffectLike",mode:"downgrade",predicate:{all:["feat:toughness"]},path:"system.attributes.dying.recoveryDC",value:8}];mountainsStoutness=[{key:"FlatModifier",selector:"hp",type:"untyped",value:"@actor.level"},{key:"ActiveEffectLike",mode:"downgrade",predicate:{not:["feat:toughness"]},path:"system.attributes.dying.recoveryDC",value:9},{key:"ActiveEffectLike",mode:"downgrade",predicate:{all:["feat:toughness"]},path:"system.attributes.dying.recoveryDC",value:6}];async updateItem(source){if(source.type!=="feat")return;if(source.system.slug==="toughness"){source.system.rules=this.toughness;return}else if(source.system.slug==="defy-death"){source.system.rules=this.defyDeath;return}else if(source.system.slug==="mountains-stoutness"){source.system.rules=this.mountainsStoutness;return}const{rules}=source.system;for(const rule of[...rules])rule.key==="RecoveryCheckDC"&&source.system.rules.splice(rules.indexOf(rule),1)}};__name2(_Migration739RecoveryCheckDC,"Migration739RecoveryCheckDC"),__publicField(_Migration739RecoveryCheckDC,"version",.739);let Migration739RecoveryCheckDC=_Migration739RecoveryCheckDC;const _Migration740MaxTakable=class extends MigrationBase{static{__name(this,"_Migration740MaxTakable")}async updateItem(source){if(source.type!=="feat")return;const systemData=source.system;"maxTaken"in systemData&&(typeof systemData.maxTaken=="number"&&typeof systemData.maxTakable!="number"&&(systemData.maxTakable=systemData.maxTaken),delete systemData.maxTaken,systemData["-=maxTaken"]=null),"maxTakable"in systemData&&typeof systemData.maxTakable!="number"&&(systemData.maxTakable=null)}};__name2(_Migration740MaxTakable,"Migration740MaxTakable"),__publicField(_Migration740MaxTakable,"version",.74);let Migration740MaxTakable=_Migration740MaxTakable;const _Migration741RollOptionToggleToItem=class extends MigrationBase{static{__name(this,"_Migration741RollOptionToggleToItem")}async updateActor(source){if(!(source.flags.pf2e?.rollOptions instanceof Object))return;const rules=source.items.flatMap(i=>i.system.rules).filter(r=>!!r.toggleable&&r.key==="RollOption"&&typeof r.domain=="string"&&r.domain.length>0&&typeof r.option=="string"&&r.option.length>0),{rollOptions}=source.flags.pf2e;for(const rule of rules){const domain=rollOptions[rule.domain];domain instanceof Object&&rule.option in domain&&(domain[`-=${rule.option}`]=!1,rule.value=!!domain[rule.option])}}};__name2(_Migration741RollOptionToggleToItem,"Migration741RollOptionToggleToItem"),__publicField(_Migration741RollOptionToggleToItem,"version",.741);let Migration741RollOptionToggleToItem=_Migration741RollOptionToggleToItem;const _Migration742RMAbilityBoostLevels=class extends MigrationBase{static{__name(this,"_Migration742RMAbilityBoostLevels")}async updateItem(source){if(source.type!=="class")return;const systemData=source.system;"abilityBoostLevels"in source.system&&(delete systemData.abilityBoostLevels,systemData["-=abilityBoostLevels"]=null)}};__name2(_Migration742RMAbilityBoostLevels,"Migration742RMAbilityBoostLevels"),__publicField(_Migration742RMAbilityBoostLevels,"version",.742);let Migration742RMAbilityBoostLevels=_Migration742RMAbilityBoostLevels;const _Migration743FixWeaknessStructure=class extends MigrationBase{static{__name(this,"_Migration743FixWeaknessStructure")}async updateActor(source){if(source.type!=="character"&&source.type!=="npc")return;const traits=source.system.traits;Array.isArray(traits.dv)||(traits.dv=[]),Array.isArray(traits.dr)||(traits.dr=[])}};__name2(_Migration743FixWeaknessStructure,"Migration743FixWeaknessStructure"),__publicField(_Migration743FixWeaknessStructure,"version",.743);let Migration743FixWeaknessStructure=_Migration743FixWeaknessStructure;const _Migration744MigrateSpellHeighten=class extends MigrationBase{static{__name(this,"_Migration744MigrateSpellHeighten")}async updateItem(source){if(source.type!=="spell")return;const system=source.system;system.scaling&&(system.heightening={type:"interval",interval:system.scaling.interval,damage:system.scaling.damage},delete system.scaling,system["-=scaling"]=null)}};__name2(_Migration744MigrateSpellHeighten,"Migration744MigrateSpellHeighten"),__publicField(_Migration744MigrateSpellHeighten,"version",.744);let Migration744MigrateSpellHeighten=_Migration744MigrateSpellHeighten;const _Migration745EffectTargetToChoiceSet=class extends MigrationBase{static{__name(this,"_Migration745EffectTargetToChoiceSet")}constructor(){super(...arguments),__privateAdd(this,_isEffectTargetRE),__privateAdd(this,_toChoiceSet)}async updateItem(source,actorSource){const{rules}=source.system;for(const rule of rules)if(__privateMethod(this,_isEffectTargetRE,isEffectTargetRE_fn).call(this,rule)){rules[rules.indexOf(rule)]=__privateMethod(this,_toChoiceSet,toChoiceSet_fn).call(this,rule,source,actorSource??null);const otherRules=rules.filter(r=>typeof r.selector=="string"&&/item\|data\.target/.test(r.selector));for(const other of otherRules){const flag=sluggify(source.system.slug??source.name,{camel:"dromedary"});other.selector=other.selector.replace(/\bdata\.target\b/,`flags.pf2e.rulesSelections.${flag}`)}}}};_isEffectTargetRE=new WeakSet,isEffectTargetRE_fn=__name2(function(rule){return rule.key==="EffectTarget"},"#isEffectTargetRE"),_toChoiceSet=new WeakSet,toChoiceSet_fn=__name2(function(rule,itemSource,actorSource){const newRE={key:"ChoiceSet",choices:{ownedItems:!0,types:["weapon"]},prompt:"PF2E.SpecificRule.Prompt.Weapon"};if(typeof rule.targetId=="string"&&actorSource){const weapon=actorSource.items.find(i=>i.type==="weapon"&&i._id===rule.targetId);weapon&&(newRE.selection=weapon.system.slug??sluggify(weapon.name))}return itemSource.system.slug?.includes("blade-ally")?newRE.choices.includeHandwraps=!0:itemSource.system.slug?.includes("weapon-surge")?newRE.choices.predicate={all:["item:equipped"]}:itemSource.system.slug==="shillelagh"?(newRE.adjustName=!1,newRE.prompt="PF2E.SpecificRule.Prompt.Shillelagh",newRE.choices.predicate={all:["item:equipped"],any:["item:base:club","item:base:staff"]}):isObject(rule.predicate)&&(newRE.choices.predicate=deepClone(rule.predicate)),newRE},"#toChoiceSet"),__name2(_Migration745EffectTargetToChoiceSet,"Migration745EffectTargetToChoiceSet"),__publicField(_Migration745EffectTargetToChoiceSet,"version",.745);let Migration745EffectTargetToChoiceSet=_Migration745EffectTargetToChoiceSet;const _Migration746StandardizePricing=class extends MigrationBase{static{__name(this,"_Migration746StandardizePricing")}async updateItem(item){if(!(!isPhysicalData(item)&&item.type!=="kit"))if(isObject(item.system.price)||(item.system.price={value:CoinsPF2e.fromString(String(item.system.price)).toObject()}),item.type==="treasure"){const systemData=item.system;if(systemData.denomination||systemData.value){const value=systemData.value?.value??0,denomination=systemData.denomination?.value??"gp";systemData.price={value:{[denomination]:value}},systemData["-=denomination"]=null,delete systemData.denomination,systemData["-=value"]=null,delete systemData.value}}else isObject(item.system.price.value)||(item.system.price.value=CoinsPF2e.fromString(String(item.system.price.value)).toObject())}};__name2(_Migration746StandardizePricing,"Migration746StandardizePricing"),__publicField(_Migration746StandardizePricing,"version",.746);let Migration746StandardizePricing=_Migration746StandardizePricing;const _Migration747FixedHeightening=class extends MigrationBase{static{__name(this,"_Migration747FixedHeightening")}constructor(){super(...arguments),__privateAdd(this,_loadedSpells,void 0),__publicField(this,"fixedHeightenSpells",new Set(["Compendium.pf2e.spells-srd.0fKHBh5goe2eiFYL","Compendium.pf2e.spells-srd.10VcmSYNBrvBphu1","Compendium.pf2e.spells-srd.2gQYrCPwBmwau26O","Compendium.pf2e.spells-srd.2iQKhCQBijhj5Rf3","Compendium.pf2e.spells-srd.4koZzrnMXhhosn0D","Compendium.pf2e.spells-srd.5WM3WjshXgrkVCg6","Compendium.pf2e.spells-srd.7CUgqHunmHfW2lC5","Compendium.pf2e.spells-srd.7OFKYR1VY6EXDuiR","Compendium.pf2e.spells-srd.9s5tqqXNzcoKamWx","Compendium.pf2e.spells-srd.BCuHKrDeJ4eq53M6","Compendium.pf2e.spells-srd.CxpFy4HJHf4ACbxF","Compendium.pf2e.spells-srd.D2nPKbIS67m9199U","Compendium.pf2e.spells-srd.DCQHaLrYXMI37dvW","Compendium.pf2e.spells-srd.DgcSiOCR1uDXGaEA","Compendium.pf2e.spells-srd.EfFMLVbmkBWmzoLF","Compendium.pf2e.spells-srd.Et8RSCLx8w7uOLvo","Compendium.pf2e.spells-srd.F23T5tHPo3WsFiHW","Compendium.pf2e.spells-srd.FhOaQDTSnsY7tiam","Compendium.pf2e.spells-srd.Fr58LDSrbndgld9n","Compendium.pf2e.spells-srd.GaRQlC9Yw1BGKHfN","Compendium.pf2e.spells-srd.HGmBY8KjgLV97nUp","Compendium.pf2e.spells-srd.HHGUBGle4OjoxvNR","Compendium.pf2e.spells-srd.HTou8cG05yuSkesj","Compendium.pf2e.spells-srd.HWrNMQENi9WSGbnF","Compendium.pf2e.spells-srd.HcIAQZjNXHemoXSU","Compendium.pf2e.spells-srd.Ifc2b6bNVdjKV7Si","Compendium.pf2e.spells-srd.JHntYF0SbaWKq7wR","Compendium.pf2e.spells-srd.LQzlKbYjZSMFQawP","Compendium.pf2e.spells-srd.LiGbewa9pO0yjbsY","Compendium.pf2e.spells-srd.Llx0xKvtu8S4z6TI","Compendium.pf2e.spells-srd.Mkbq9xlAUxHUHyR2","Compendium.pf2e.spells-srd.OAt2ZEns1gIOCgrn","Compendium.pf2e.spells-srd.OhD2Z6rIGGD5ocZA","Compendium.pf2e.spells-srd.PRrZ7anETWPm90YY","Compendium.pf2e.spells-srd.PjhUmyKnq6K5uDby","Compendium.pf2e.spells-srd.Popa5umI3H33levx","Compendium.pf2e.spells-srd.Pwq6T7xpfAJXV5aj","Compendium.pf2e.spells-srd.Q7QQ91vQtyi1Ux36","Compendium.pf2e.spells-srd.Seaah9amXg70RKw2","Compendium.pf2e.spells-srd.U58aQWJ47VrI36yP","Compendium.pf2e.spells-srd.UmXhuKrYZR3W16mQ","Compendium.pf2e.spells-srd.VTb0yI6P1bLkzuRr","Compendium.pf2e.spells-srd.VlNcjmYyu95vOUe8","Compendium.pf2e.spells-srd.W02bHXylIpoXbO4e","Compendium.pf2e.spells-srd.WsUwpfmhKrKwoIe3","Compendium.pf2e.spells-srd.Wt94cw03L77sbud7","Compendium.pf2e.spells-srd.XhgMx9WC6NfXd9RP","Compendium.pf2e.spells-srd.ZAX0OOcKtYMQlquR","Compendium.pf2e.spells-srd.ZqmP9gijBmK7y8Xy","Compendium.pf2e.spells-srd.aIHY2DArKFweIrpf","Compendium.pf2e.spells-srd.atlgGNI1E1Ox3O3a","Compendium.pf2e.spells-srd.bay4AfSu2iIozNNW","Compendium.pf2e.spells-srd.czO0wbT1i320gcu9","Compendium.pf2e.spells-srd.dINQzhqGmIsqGMUY","Compendium.pf2e.spells-srd.drmvQJETA3WZzXyw","Compendium.pf2e.spells-srd.e36Z2t6tLdW3RUzZ","Compendium.pf2e.spells-srd.fprqWKUc0jnMIyGU","Compendium.pf2e.spells-srd.gISYsBFby1TiXfBt","Compendium.pf2e.spells-srd.ivKnEtI1z4UqEKIA","Compendium.pf2e.spells-srd.kuoYff1csM5eAcAP","Compendium.pf2e.spells-srd.lbrWMnS2pecKaSVB","Compendium.pf2e.spells-srd.lsR3RLEdBG4rcSzd","Compendium.pf2e.spells-srd.nXmC2Xx9WmS5NsAo","Compendium.pf2e.spells-srd.o6YCGx4lycsYpww4","Compendium.pf2e.spells-srd.pZTqGY1MLRjgKasV","Compendium.pf2e.spells-srd.pt3gEnzA159uHcJC","Compendium.pf2e.spells-srd.pwzdSlJgYqN7bs2w","Compendium.pf2e.spells-srd.q5qmNn144ZJGxnvJ","Compendium.pf2e.spells-srd.qTr2oCgIXl703Whb","Compendium.pf2e.spells-srd.qwlh6aDgi86U3Q7H","Compendium.pf2e.spells-srd.r4HLQcYwB62bTayl","Compendium.pf2e.spells-srd.sFwoKj0TsacsmoWj","Compendium.pf2e.spells-srd.vLA0q0WOK2YPuJs6","Compendium.pf2e.spells-srd.vLzFcIaSXs7YTIqJ","Compendium.pf2e.spells-srd.vTQvfYu2llKQedmY","Compendium.pf2e.spells-srd.vctIUOOgSmxAF0KG","Compendium.pf2e.spells-srd.wzctak6BxOW8xvFV","Compendium.pf2e.spells-srd.x5rGOmhDRDVQPrnW","Compendium.pf2e.spells-srd.x7SPrsRxGb2Vy2nu","Compendium.pf2e.spells-srd.x9RIFhquazom4p02","Compendium.pf2e.spells-srd.xRgU9rrhmGAgG4Rc","Compendium.pf2e.spells-srd.yH13KXUK2x093NUv","Compendium.pf2e.spells-srd.yM3KTTSAIHhyuP14","Compendium.pf2e.spells-srd.zlnXpME1T2uvn8Lr","Compendium.pf2e.spells-srd.zul5cBTfr7NXHBZf"]))}async updateItem(item){if(item.type!=="spell")return;const isAcidSplash=(item.system.slug??sluggify(item.name))==="acid-splash";if(item.system.heightening?.type==="fixed"&&!isAcidSplash)return;const sourceId=item.flags.core?.sourceId;if(sourceId&&this.fixedHeightenSpells.has(sourceId)){const spell=(await this.loadSpells())[sourceId];spell&&spell.system.heightening?.type==="fixed"&&(item.system.heightening=spell.system.heightening,this.overwriteDamage(item,spell))}}overwriteDamage(spell,newSpell){const newDamage=newSpell.system.damage,newKeys=new Set(Object.keys(newDamage.value)),diff=Object.keys(spell.system.damage.value).filter(key=>!newKeys.has(key)),damage=spell.system.damage;damage.value=newDamage.value;for(const deleteKey of diff)damage.value[`-=${deleteKey}`]=null}async loadSpells(){if(__privateGet(this,_loadedSpells))return __privateGet(this,_loadedSpells);const spells=await UUIDUtils.fromUUIDs([...this.fixedHeightenSpells]);return __privateSet(this,_loadedSpells,spells.reduce((record,spell)=>({...record,[spell.uuid]:spell}),{})),__privateGet(this,_loadedSpells)}};_loadedSpells=new WeakMap,__name2(_Migration747FixedHeightening,"Migration747FixedHeightening"),__publicField(_Migration747FixedHeightening,"version",.747);let Migration747FixedHeightening=_Migration747FixedHeightening;const _Migration748BatchConsumablePricing=class extends MigrationBase{static{__name(this,"_Migration748BatchConsumablePricing")}async updateItem(item){if(!isPhysicalData(item))return;const slug=item.system.slug??sluggify(item.name);batched_5.has(slug)&&(item.system.price.per=5),batched_10.has(slug)&&(item.system.price.per=10)}};__name2(_Migration748BatchConsumablePricing,"Migration748BatchConsumablePricing"),__publicField(_Migration748BatchConsumablePricing,"version",.748);let Migration748BatchConsumablePricing=_Migration748BatchConsumablePricing;const batched_5=new Set(["rounds-harmona-gun","rounds-dwarven-scattergun","rounds-flingflenser","rounds-explosive-dogslicer"]),batched_10=new Set(["rounds-three-peaked-tree","rounds-dragon-mouth-pistol","rounds-pepperbox","rounds-fire-lance","rounds-flintlock-pistol","rounds-clan-pistol","bolts","rounds-hand-cannon","sun-shot","rounds-dagger-pistol","rounds-dueling-pistol","rounds-flintlock-musket","rounds-hammer-gun","rounds-black-powder-knuckle-dusters","rounds-slide-pistol","sling-bullets","rounds-double-barreled-musket","rounds-mace-multipistol","rounds-gnome-amalgam-musket","cutlery","rounds-axe-musket","rounds-mithral-tree","wooden-taws","rounds-gun-sword","rounds-blunderbuss","rounds-jezail","rounds-double-barreled-pistol","rounds-arquebus","rounds-cane-pistol","rounds-rapier-pistol","rounds-coat-pistol","rounds-piercing-wind","blowgun-darts","arrows","light-writer-plates","practice-target"]),_Migration749AssuranceREs=class extends MigrationBase{static{__name(this,"_Migration749AssuranceREs")}constructor(){super(...arguments),__privateAdd(this,_isChoiceSetWithSelection),__privateAdd(this,_newRules)}async updateItem(source){const{slug,rules}=source.system;if(!(source.type==="feat"&&slug?.startsWith("assurance")))return;const firstRule=rules.at(0);if(slug==="assurance"&&firstRule&&rules.length===1&&__privateMethod(this,_isChoiceSetWithSelection,isChoiceSetWithSelection_fn).call(this,firstRule))firstRule.flag="assurance",rules.push(...__privateMethod(this,_newRules,newRules_fn).call(this,"choice"));else if(rules.length===0){const skill=/^assurance-([a-z]+)$/.exec(slug)?.at(1);setHasElement(SKILL_LONG_FORMS,skill)&&rules.push(...__privateMethod(this,_newRules,newRules_fn).call(this,skill))}}};_isChoiceSetWithSelection=new WeakSet,isChoiceSetWithSelection_fn=__name2(function(rule){return rule.key==="ChoiceSet"},"#isChoiceSetWithSelection"),_newRules=new WeakSet,newRules_fn=__name2(function(skill){const selector=skill==="choice"?"{item|flags.pf2e.rulesSelections.assurance}":skill;return[{key:"SubstituteRoll",label:"PF2E.SpecificRule.SubstituteRoll.Assurance",selector,slug:"assurance",value:10},{key:"AdjustModifier",predicate:{all:["substitute:assurance"],not:["bonus:type:proficiency"]},selector,suppress:!0}]},"#newRules"),__name2(_Migration749AssuranceREs,"Migration749AssuranceREs"),__publicField(_Migration749AssuranceREs,"version",.749);let Migration749AssuranceREs=_Migration749AssuranceREs;const _Migration750FixCorruptedPrice=class extends MigrationBase{static{__name(this,"_Migration750FixCorruptedPrice")}async updateItem(item){!isPhysicalData(item)&&item.type!=="kit"||typeof item.system.price=="string"&&(item.system.price={value:CoinsPF2e.fromString(item.system.price).toObject()})}};__name2(_Migration750FixCorruptedPrice,"Migration750FixCorruptedPrice"),__publicField(_Migration750FixCorruptedPrice,"version",.75);let Migration750FixCorruptedPrice=_Migration750FixCorruptedPrice;const _Migration751ResetRollOptions=class extends MigrationBase{static{__name(this,"_Migration751ResetRollOptions")}async updateActor(source){isObject(source.flags.pf2e)&&"rollOptions"in source.flags.pf2e&&(source.flags.pf2e["-=rollOptions"]=null)}};__name2(_Migration751ResetRollOptions,"Migration751ResetRollOptions"),__publicField(_Migration751ResetRollOptions,"version",.751);let Migration751ResetRollOptions=_Migration751ResetRollOptions;const _Migration752StrikeVsWeaponTraits=class extends MigrationBase{static{__name(this,"_Migration752StrikeVsWeaponTraits")}constructor(){super(...arguments),__privateAdd(this,_toSkip,new Set(["ghost-hunter","stance-arcane-cascade","spirit-strikes"]))}async updateItem(source){if(__privateGet(this,_toSkip).has(source.system.slug??""))return;const rules=source.system.rules.filter(r=>r.key==="AdjustStrike"&&r.property==="traits");for(const rule of rules)objectHasKey(weaponTraits,rule.value)&&(rule.property="weapon-traits")}};_toSkip=new WeakMap,__name2(_Migration752StrikeVsWeaponTraits,"Migration752StrikeVsWeaponTraits"),__publicField(_Migration752StrikeVsWeaponTraits,"version",.752);let Migration752StrikeVsWeaponTraits=_Migration752StrikeVsWeaponTraits;const _Migration753WeaponReloadTimes=class extends MigrationBase{static{__name(this,"_Migration753WeaponReloadTimes")}constructor(){super(...arguments),__privateAdd(this,_hasThrownTrait)}async updateItem(source){if(source.type!=="weapon")return;const slug=source.system.slug??"";["backpack-catapult","backpack-catapult"].includes(slug)?source.system.reload.value="10":(source.system.baseItem==="alchemical-bomb"||__privateMethod(this,_hasThrownTrait,hasThrownTrait_fn).call(this,source))&&(source.system.reload.value="-")}};_hasThrownTrait=new WeakSet,hasThrownTrait_fn=__name2(function(source){return source.system.traits.value.some(t=>t.startsWith("thrown"))},"#hasThrownTrait"),__name2(_Migration753WeaponReloadTimes,"Migration753WeaponReloadTimes"),__publicField(_Migration753WeaponReloadTimes,"version",.753);let Migration753WeaponReloadTimes=_Migration753WeaponReloadTimes;const _Migration754MightyBulwarkAdjustModifiers=class extends MigrationBase{static{__name(this,"_Migration754MightyBulwarkAdjustModifiers")}async updateItem(source){if(!(source.type==="feat"&&source.system.slug==="mighty-bulwark"))return;const newRules=[{key:"FlatModifier",predicate:{all:["self:armor:trait:bulwark"]},selector:"reflex",type:"untyped",value:4},{key:"AdjustModifier",predicate:{all:["self:armor:trait:bulwark"]},selector:"reflex",slug:"dex",suppress:!0},{key:"AdjustModifier",selector:"reflex",slug:"bulwark",suppress:!0}];source.system.rules=newRules}};__name2(_Migration754MightyBulwarkAdjustModifiers,"Migration754MightyBulwarkAdjustModifiers"),__publicField(_Migration754MightyBulwarkAdjustModifiers,"version",.754);let Migration754MightyBulwarkAdjustModifiers=_Migration754MightyBulwarkAdjustModifiers;const _Migration755GrantIdsToData=class extends MigrationBase{static{__name(this,"_Migration755GrantIdsToData")}async updateActor(source){for(const item of source.items){if(!item.flags.pf2e)continue;const systemFlags=item.flags.pf2e,{grantedBy,itemGrants}=systemFlags;typeof grantedBy=="string"&&(source.items.find(i=>i._id===grantedBy)?systemFlags.grantedBy={id:grantedBy}:systemFlags["-=grantedBy"]=null),Array.isArray(itemGrants)&&(systemFlags.itemGrants=itemGrants.flatMap(grant=>typeof grant=="string"?source.items.find(i=>i._id===grant)?{id:grant}:[]:grant))}}};__name2(_Migration755GrantIdsToData,"Migration755GrantIdsToData"),__publicField(_Migration755GrantIdsToData,"version",.755);let Migration755GrantIdsToData=_Migration755GrantIdsToData;const _Migration756RMStoredResourceMaxes=class extends MigrationBase{static{__name(this,"_Migration756RMStoredResourceMaxes")}async updateActor(source){source.type==="character"&&(source["system.resources.focus.-=max"]=null,source["system.resources.crafting.infusedReagents.-=max"]=null,source["system.resources.-=investiture"]=null)}};__name2(_Migration756RMStoredResourceMaxes,"Migration756RMStoredResourceMaxes"),__publicField(_Migration756RMStoredResourceMaxes,"version",.756);let Migration756RMStoredResourceMaxes=_Migration756RMStoredResourceMaxes;const _Migration757HillockHalfling=class extends MigrationBase{static{__name(this,"_Migration757HillockHalfling")}async updateItem(itemSource){if(itemSource.type!=="heritage"||(itemSource.system.slug??sluggify(itemSource.name))!=="hillock-halfling")return;const rules=itemSource.system.rules;if(!rules.some(rule=>"path"in rule&&rule.path==="system.attributes.hp.recoveryAddend")){const element={key:"ActiveEffectLike",mode:"add",path:"system.attributes.hp.recoveryAddend",value:"@actor.level"};rules.push(element)}}};__name2(_Migration757HillockHalfling,"Migration757HillockHalfling"),__publicField(_Migration757HillockHalfling,"version",.757);let Migration757HillockHalfling=_Migration757HillockHalfling;const _Migration758PrunePCAttributes=class extends MigrationBase{static{__name(this,"_Migration758PrunePCAttributes")}toDelete=["-=ac","-=ancestryhp","-=battleForm","-=classDC","-=classOrSpellDC","-=classhp","-=dexCap","-=doomed","-=dying","-=familiarAbilities","-=flanking","-=flatbonushp","-=flatbonussp","-=handsFree","-=hardness","hp.-=breakdown","hp.-=details","hp.-=max","hp.-=name","hp.-=negativeHealing","hp.-=recoveryMultiplier","hp.-=totalModifier","hp.-=tempsource","hp.-=_modifiers","initiative.-=_modifiers","initiative.-=breakdown","initiative.-=label","initiative.-=name","initiative.-=roll","initiative.-=tiebreakPriority","initiative.-=totalModifier","-=levelbonushp","-=levelbonussp","-=perception","-=polymorphed","-=reach","-=shield","speed.-=_modifiers","speed.-=breakdown","speed.-=name","speed.-=total","speed.-=totalModifier","speed.-=type","-=spellDC","-=wounded"];async updateActor(source){if(source.type==="character")for(const key of this.toDelete)source[`system.attributes.${key}`]=null}};__name2(_Migration758PrunePCAttributes,"Migration758PrunePCAttributes"),__publicField(_Migration758PrunePCAttributes,"version",.758);let Migration758PrunePCAttributes=_Migration758PrunePCAttributes;const _Migration759CritSpecRE=class extends MigrationBase{static{__name(this,"_Migration759CritSpecRE")}async updateItem(source){if(!["feat","weapon"].includes(source.type))return;const critSpecKey="CriticalSpecialization";if(!source.system.rules.some(r=>r.key===critSpecKey))switch(source.system.slug){case"archer-dedication":{source.system.rules.push({key:critSpecKey,predicate:{all:["weapon:group:bow",{gte:["weapon:proficiency:rank",2]}]}});return}case"azarketi-weapon-aptitude":{source.system.rules=[{key:critSpecKey,predicate:{any:["weapon:trait:azarketi","weapon:base:crossbow","weapon:base:hand-crossbow","weapon:base:longspear","weapon:base:spear","weapon:base:trident"]}}];return}case"brawling-focus":{source.system.rules=[{key:critSpecKey,predicate:{any:["weapon:group:brawling",{and:["feat:monastic-weaponry","weapon:trait:monk",{not:"weapon:category:unarmed"},{gte:["weapon:proficiency:rank",1]}]}]}}];return}case"brutality":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{all:["self:effect:rage","weapon:melee"]}});return}case"catfolk-weapon-rake":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:catfolk","weapon:base:hatchet","weapon:base:kama","weapon:base:kukri","weapon:base:scimitar","weapon:base:sickle"]}}];return}case"conrasu-weapon-understanding":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:conrasu","weapon:base:glaive","weapon:base:longspear","weapon:base:longsword","weapon:base:shortbow","weapon:base:spear"]}}];return}case"dwarven-weapon-cunning":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:dwarf","weapon:base:battle-axe","weapon:base:pick","weapon:base:warhammer"]}}];return}case"elven-weapon-elegance":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:elf","weapon:base:longbow","weapon:base:longsword","weapon:base:rapier","weapon:base:shortbow"]}}];return}case"fighter-weapon-mastery":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{all:[{gte:["weapon:proficiency:rank",3]}]}});return}case"genie-weapon-flourish":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:geniekin","weapon:base:falchion","weapon:base:ranseur","weapon:base:scimitar","weapon:base:trident"]}}];return}case"gnoll-weapon-practicality":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:gnoll","weapon:base:flail","weapon:base:khopesh","weapon:base:mambele","weapon:base:spear","weapon:base:war-flail"]}}];return}case"gnome-weapon-innovator":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:gnome","weapon:base:glaive","weapon:base:kukri"]}}];return}case"goblin-weapon-frenzy":{source.system.rules=[{key:"CriticalSpecialization",predicate:{all:["weapon:trait:goblin"]}}];return}case"grippli-weapon-innovator":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:grippli","weapon:base:blowgun","weapon:base:hatchet","weapon:base:scythe","weapon:base:shortbow"]}}];return}case"gunslinger-weapon-mastery":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{any:["weapon:group:firearm","weapon:tag:crossbow"]}});return}case"halfling-weapon-trickster":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:halfling","weapon:base:shortsword","weapon:base:sling"]}}];return}case"hobgoblin-weapon-discipline":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:group:polearm","weapon:group:spear","weapon:group:sword"]}}];return}case"improvised-critical":{source.system.rules=[{key:critSpecKey,predicate:{all:["weapon:tag:improvised"]}}];return}case"kobold-weapon-innovator":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:kobold","weapon:base:crossbow","weapon:base:greatpick","weapon:base:light-pick","weapon:base:pick","weapon:base:spear"]}}];return}case"mauler-dedication":{source.system.rules.push({key:"CriticalSpecialization",predicate:{all:["weapon:melee",{or:["weapon:category:simple","weapon:category:martial"]},{or:["weapon:usage:hands:2","weapon:trait:two-hand-d6","weapon:trait:two-hand-d8","weapon:trait:two-hand-d10","weapon:trait:two-hand-d12"]}]}});return}case"orc-weapon-carnage":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:orc","weapon:base:falchion","weapon:base:greataxe"]}}];return}case"ranger-weapon-expertise":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{all:["hunted-prey"],any:["weapon:category:simple","weapon:category:martial"]}});return}case"spike-launcher":{const rule={key:critSpecKey,alternate:!0,predicate:{all:["weapon:id:{item|_id}"]},text:"PF2E.Item.Weapon.CriticalSpecialization.bow"};source.system.rules.push(rule);return}case"student-of-the-staff":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.unshift({key:critSpecKey,predicate:{all:["weapon:base:staff"]}});return}case"sun-sling":{source.system.rules.push({key:critSpecKey,predicate:{all:["weapon:id:{item|_id}","feat:suns-fury"]}});return}case"suns-fury":{source.system.rules=[];return}case"third-doctrine-warpriest":{source.system.rules.push({key:critSpecKey,predicate:{all:["weapon:deity-favored"]}});return}case"vanths-weapon-execution":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:base:bo-staff","weapon:base:longbow","weapon:base:scythe","weapon:base:staff"]}}];return}case"weapon-expertise-swashbuckler":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{all:[{gte:["weapon:proficiency:rank",2]}]}});return}case"weapon-tricks":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{all:["target:condition:flat-footed"],any:[{and:[{or:["weapon:trait:agile","weapon:trait:finesse"]},{or:["weapon:category:simple","weapon:category:unarmed"]}]},"weapon:base:rapier","weapon:base:sap","weapon:base:shortbow","weapon:base:shortsword"]}});return}}}};__name2(_Migration759CritSpecRE,"Migration759CritSpecRE"),__publicField(_Migration759CritSpecRE,"version",.759);let Migration759CritSpecRE=_Migration759CritSpecRE;const _Migration760SeparateNoteTitle=class extends MigrationBase{static{__name(this,"_Migration760SeparateNoteTitle")}constructor(){super(...arguments),__privateAdd(this,_cleanText)}async updateItem(source){const notes=source.system.rules.filter(r=>r.key==="Note"&&typeof r.text=="string"&&!("title"in r));for(const note of notes){if(note.text=note.text.trim(),!note.text.startsWith("{const text=note.text.includes("

")?note.text:`${note.text}

`;try{const fragment=document.createElement("template");fragment.innerHTML=text;const children2=Array.from(fragment.content.childNodes);if(children2.length===1&&children2[0]instanceof HTMLElement)return children2[0];if(children2.length===2&&children2[0]instanceof HTMLParagraphElement&&children2[1]instanceof Text){const[first,second]=children2;return first.append(second),first}else return null}catch{return null}})();if(pElement?.nodeName!=="P")continue;const children=Array.from(pElement.childNodes);if(children.length===1&&children[0]instanceof Text){note.text=__privateMethod(this,_cleanText,cleanText_fn).call(this,children[0].textContent??""),pElement.dataset.visibility&&["gm","owner"].includes(pElement.dataset.visibility)&&(note.visibility=pElement.dataset.visibility);continue}if(children.length!==2||!(children[0]instanceof HTMLElement)||children[0].nodeName!=="STRONG"||!(children[1]instanceof Text))continue;const strongElement=children[0];strongElement.remove();const newText=pElement.innerHTML.trim();if(newText===""||note.text.includes("typeof group=="string"?`PF2E.Item.Weapon.CriticalSpecialization.${group.toLowerCase()}`:substring)},"#cleanText"),__name2(_Migration760SeparateNoteTitle,"Migration760SeparateNoteTitle"),__publicField(_Migration760SeparateNoteTitle,"version",.76);let Migration760SeparateNoteTitle=_Migration760SeparateNoteTitle;const _Migration761ShotRules=class extends MigrationBase{static{__name(this,"_Migration761ShotRules")}constructor(){super(...arguments),__privateAdd(this,_updateEffect),__privateAdd(this,_updateFeat)}async updateItem(source){switch(source.type){case"effect":__privateMethod(this,_updateEffect,updateEffect_fn).call(this,source);break;case"feat":__privateMethod(this,_updateFeat,updateFeat_fn).call(this,source);break}}};_updateEffect=new WeakSet,updateEffect_fn=__name2(function(source){if(source.system.slug==="stance-multishot-stance"){const newRules=[{key:"AdjustModifier",mode:"add",predicate:{all:["double-shot"]},relabel:"{item|name}",selector:"ranged-attack-roll",slug:"double-shot",value:1},{key:"AdjustModifier",mode:"add",predicate:{all:["triple-shot"]},relabel:"{item|name}",selector:"ranged-attack-roll",slug:"double-shot",value:1}];source.system.rules=newRules}},"#updateEffect"),_updateFeat=new WeakSet,updateFeat_fn=__name2(function(source){switch(source.system.slug){case"double-shot":{const newRules=[{domain:"ranged-attack-roll",key:"RollOption",option:"double-shot",toggleable:!0},{key:"FlatModifier",predicate:{all:["double-shot","weapon:reload:0"]},selector:"ranged-attack-roll",slug:"double-shot",value:-2}];source.system.rules=newRules;break}case"triple-shot":{const newRules=[{domain:"ranged-attack-roll",disabledIf:{not:["double-shot"]},key:"RollOption",option:"triple-shot",priority:51,toggleable:!0},{key:"AdjustModifier",mode:"override",predicate:{all:["double-shot","triple-shot"]},relabel:"{item|name}",selector:"ranged-attack-roll",slug:"double-shot",value:-4}];source.system.rules=newRules;break}}},"#updateFeat"),__name2(_Migration761ShotRules,"Migration761ShotRules"),__publicField(_Migration761ShotRules,"version",.761);let Migration761ShotRules=_Migration761ShotRules;const _Migration762UpdateBackgroundItems=class extends MigrationBase{static{__name(this,"_Migration762UpdateBackgroundItems")}async updateItem(source){source.type==="background"&&(source.system.slug==="amnesiac"||source.system.slug==="discarded-duplicate")&&Object.values(source.system.boosts).length!==3&&(source.system.boosts[2]={value:["cha","con","dex","int","str","wis"],selected:null})}};__name2(_Migration762UpdateBackgroundItems,"Migration762UpdateBackgroundItems"),__publicField(_Migration762UpdateBackgroundItems,"version",.762);let Migration762UpdateBackgroundItems=_Migration762UpdateBackgroundItems;const _Migration763RestoreAnimalStrikeOptions=class extends MigrationBase{static{__name(this,"_Migration763RestoreAnimalStrikeOptions")}async updateItem(source){if(source.type!=="feat"||!/^[a-z]+-animal-instinct$/.test(source.system.slug??""))return;const strikeRE=source.system.rules.find(r=>r.key==="Strike"&&!Array.isArray(r.options));strikeRE&&(strikeRE.options=["animal-instinct"])}};__name2(_Migration763RestoreAnimalStrikeOptions,"Migration763RestoreAnimalStrikeOptions"),__publicField(_Migration763RestoreAnimalStrikeOptions,"version",.763);let Migration763RestoreAnimalStrikeOptions=_Migration763RestoreAnimalStrikeOptions;const _Migration764PanacheVivaciousREs=class extends MigrationBase{static{__name(this,"_Migration764PanacheVivaciousREs")}constructor(){super(...arguments),__privateAdd(this,_vivaciousRules)}async updateItem(source){source.type==="feat"&&(source.system.slug==="panache"?source.system.rules=[]:source.system.slug==="vivacious-speed"&&(source.system.rules=__privateGet(this,_vivaciousRules,vivaciousRules_get)))}};_vivaciousRules=new WeakSet,vivaciousRules_get=__name2(function(){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}]}}]},"#vivaciousRules"),__name2(_Migration764PanacheVivaciousREs,"Migration764PanacheVivaciousREs"),__publicField(_Migration764PanacheVivaciousREs,"version",.764);let Migration764PanacheVivaciousREs=_Migration764PanacheVivaciousREs;const _Migration765ChoiceOwnedItemTypes=class extends MigrationBase{static{__name(this,"_Migration765ChoiceOwnedItemTypes")}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"])}};__name2(_Migration765ChoiceOwnedItemTypes,"Migration765ChoiceOwnedItemTypes"),__publicField(_Migration765ChoiceOwnedItemTypes,"version",.765);let Migration765ChoiceOwnedItemTypes=_Migration765ChoiceOwnedItemTypes;const _Migration766WipeURLSources=class extends MigrationBase{static{__name(this,"_Migration766WipeURLSources")}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="")}};__name2(_Migration766WipeURLSources,"Migration766WipeURLSources"),__publicField(_Migration766WipeURLSources,"version",.766);let Migration766WipeURLSources=_Migration766WipeURLSources;const _Migration767ConvertVoluntaryFlaws=class extends MigrationBase{static{__name(this,"_Migration767ConvertVoluntaryFlaws")}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)}};__name2(_Migration767ConvertVoluntaryFlaws,"Migration767ConvertVoluntaryFlaws"),__publicField(_Migration767ConvertVoluntaryFlaws,"version",.767);let Migration767ConvertVoluntaryFlaws=_Migration767ConvertVoluntaryFlaws;const _Migration768AddNewAuras=class extends MigrationBase{static{__name(this,"_Migration768AddNewAuras")}constructor(){super(...arguments),__privateAdd(this,_auraOfLife,{effects:[{affects:"allies",events:["enter"],uuid:"Compendium.pf2e.feat-effects.FPuICuxBLiDaEbDX"}],key:"Aura",radius:15,slug:"aura-of-life"}),__privateAdd(this,_enlightenedPresence,{effects:[{affects:"allies",events:["enter"],uuid:"Compendium.pf2e.feat-effects.XM1AA8z5cHm8sJXM"}],key:"Aura",radius:15,slug:"enlightened-presence",traits:["emotion","mental"]}),__privateAdd(this,_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"]}]),__privateAdd(this,_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=[deepClone(__privateGet(this,_auraOfLife))];break;case"enlightened-presence":source.system.rules=[deepClone(__privateGet(this,_enlightenedPresence))];break;case"eternal-blessing":source.system.rules=deepClone(__privateGet(this,_eternalBlessing));break;case"marshal-dedication":source.system.rules=[deepClone(__privateGet(this,_marshalsAura))];break}}};_auraOfLife=new WeakMap,_enlightenedPresence=new WeakMap,_eternalBlessing=new WeakMap,_marshalsAura=new WeakMap,__name2(_Migration768AddNewAuras,"Migration768AddNewAuras"),__publicField(_Migration768AddNewAuras,"version",.768);let Migration768AddNewAuras=_Migration768AddNewAuras;const _Migration769NoUniversalistFocusPool=class extends MigrationBase{static{__name(this,"_Migration769NoUniversalistFocusPool")}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"]})}}};__name2(_Migration769NoUniversalistFocusPool,"Migration769NoUniversalistFocusPool"),__publicField(_Migration769NoUniversalistFocusPool,"version",.769);let Migration769NoUniversalistFocusPool=_Migration769NoUniversalistFocusPool;const _Migration770REDataToSystem=class extends MigrationBase{static{__name(this,"_Migration770REDataToSystem")}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."))}};__name2(_Migration770REDataToSystem,"Migration770REDataToSystem"),__publicField(_Migration770REDataToSystem,"version",.77);let Migration770REDataToSystem=_Migration770REDataToSystem;const _Migration771SpellVariantsToSystem=class extends MigrationBase{static{__name(this,"_Migration771SpellVariantsToSystem")}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)}}}};__name2(_Migration771SpellVariantsToSystem,"Migration771SpellVariantsToSystem"),__publicField(_Migration771SpellVariantsToSystem,"version",.771);let Migration771SpellVariantsToSystem=_Migration771SpellVariantsToSystem;const _Migration772V10EmbeddedSpellData=class extends MigrationBase{static{__name(this,"_Migration772V10EmbeddedSpellData")}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)}}};__name2(_Migration772V10EmbeddedSpellData,"Migration772V10EmbeddedSpellData"),__publicField(_Migration772V10EmbeddedSpellData,"version",.772);let Migration772V10EmbeddedSpellData=_Migration772V10EmbeddedSpellData;const _Migration773ReligiousSymbolUsage=class extends MigrationBase{static{__name(this,"_Migration773ReligiousSymbolUsage")}async updateItem(source){source.type==="equipment"&&source.system.slug?.startsWith("religious-symbol")&&(source.system.usage.value="held-in-one-hand")}};__name2(_Migration773ReligiousSymbolUsage,"Migration773ReligiousSymbolUsage"),__publicField(_Migration773ReligiousSymbolUsage,"version",.773);let Migration773ReligiousSymbolUsage=_Migration773ReligiousSymbolUsage;const _Migration774UnpersistCraftingEntries=class extends MigrationBase{static{__name(this,"_Migration774UnpersistCraftingEntries")}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}`)}))}}};__name2(_Migration774UnpersistCraftingEntries,"Migration774UnpersistCraftingEntries"),__publicField(_Migration774UnpersistCraftingEntries,"version",.774);let Migration774UnpersistCraftingEntries=_Migration774UnpersistCraftingEntries;const _Migration775AgileFinesseRanged=class extends MigrationBase{static{__name(this,"_Migration775AgileFinesseRanged")}constructor(){super(...arguments),__privateAdd(this,_findDamageDiceRE),__privateAdd(this,_isClassFeature4),__privateAdd(this,_athleticStrategist),__privateAdd(this,_deviseAStratagem),__privateAdd(this,_ruffianPredicate),__privateAdd(this,_sneakAttackPredicate)}async updateItem(source){switch(source.type){case"action":{if(source.system.slug==="sneak-attack"){const damageDiceRE=__privateMethod(this,_findDamageDiceRE,findDamageDiceRE_fn).call(this,source);isObject(damageDiceRE)&&damageDiceRE.predicate&&Array.isArray(damageDiceRE.predicate.all)&&damageDiceRE.predicate.all.some(s=>s instanceof Object&&"or"in s)&&(damageDiceRE.predicate=__privateGet(this,_sneakAttackPredicate,sneakAttackPredicate_get))}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]=__privateGet(this,_athleticStrategist,athleticStrategist_get));break}case"devise-a-stratagem":{const index=source.system.rules.findIndex(r=>r.key==="FlatModifier");index!==-1&&(source.system.rules[index]=__privateGet(this,_deviseAStratagem,deviseAStratagem_get));break}case"ruffian":{const damageDiceRE=__privateMethod(this,_findDamageDiceRE,findDamageDiceRE_fn).call(this,source);damageDiceRE&&(damageDiceRE.predicate=__privateGet(this,_ruffianPredicate,ruffianPredicate_get));break}case"shadow-sneak-attack":case"sneak-attack":case"sneak-attacker":{const damageDiceRE=__privateMethod(this,_findDamageDiceRE,findDamageDiceRE_fn).call(this,source);if(damageDiceRE){const predicate=__privateGet(this,_sneakAttackPredicate,sneakAttackPredicate_get);__privateMethod(this,_isClassFeature4,isClassFeature_fn4).call(this,source)&&predicate.all?.unshift("class:rogue"),damageDiceRE.predicate=predicate}break}}}}};_findDamageDiceRE=new WeakSet,findDamageDiceRE_fn=__name2(function(source){return source.system.rules.find(r=>r.key==="DamageDice")??null},"#findDamageDiceRE"),_isClassFeature4=new WeakSet,isClassFeature_fn4=__name2(function(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"},"#isClassFeature"),_athleticStrategist=new WeakSet,athleticStrategist_get=__name2(function(){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"}},"#athleticStrategist"),_deviseAStratagem=new WeakSet,deviseAStratagem_get=__name2(function(){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"}},"#deviseAStratagem"),_ruffianPredicate=new WeakSet,ruffianPredicate_get=__name2(function(){return{all:["target:condition:flat-footed","weapon:category:simple",{nor:[{and:["weapon:ranged",{not:"weapon:thrown-melee"}]},"weapon:trait:agile","weapon:trait:finesse"]}]}},"#ruffianPredicate"),_sneakAttackPredicate=new WeakSet,sneakAttackPredicate_get=__name2(function(){return{all:["target:condition:flat-footed"],any:["weapon:trait:agile","weapon:trait:finesse",{and:["weapon:ranged",{not:"weapon:thrown-melee"}]}]}},"#sneakAttackPredicate"),__name2(_Migration775AgileFinesseRanged,"Migration775AgileFinesseRanged"),__publicField(_Migration775AgileFinesseRanged,"version",.775);let Migration775AgileFinesseRanged=_Migration775AgileFinesseRanged;const _Migration776SlugifyConditionOverrides=class extends MigrationBase{static{__name(this,"_Migration776SlugifyConditionOverrides")}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)))}};__name2(_Migration776SlugifyConditionOverrides,"Migration776SlugifyConditionOverrides"),__publicField(_Migration776SlugifyConditionOverrides,"version",.776);let Migration776SlugifyConditionOverrides=_Migration776SlugifyConditionOverrides;const _Migration777HandOfTheApprentice=class extends MigrationBase{static{__name(this,"_Migration777HandOfTheApprentice")}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]}}};__name2(_Migration777HandOfTheApprentice,"Migration777HandOfTheApprentice"),__publicField(_Migration777HandOfTheApprentice,"version",.777);let Migration777HandOfTheApprentice=_Migration777HandOfTheApprentice;const _Migration778RenameRetiredPackRefs=class extends MigrationBase{static{__name(this,"_Migration778RenameRetiredPackRefs")}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)}};__name2(_Migration778RenameRetiredPackRefs,"Migration778RenameRetiredPackRefs"),__publicField(_Migration778RenameRetiredPackRefs,"version",.778);let Migration778RenameRetiredPackRefs=_Migration778RenameRetiredPackRefs;const _Migration779EliteWeak=class extends MigrationBase{static{__name(this,"_Migration779EliteWeak")}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"))}};__name2(_Migration779EliteWeak,"Migration779EliteWeak"),__publicField(_Migration779EliteWeak,"version",.779);let Migration779EliteWeak=_Migration779EliteWeak;const _Migration780NumifySpeeds=class extends MigrationBase{static{__name(this,"_Migration780NumifySpeeds")}constructor(){super(...arguments),__privateAdd(this,_updateSpeed)}async updateActor(source){if(source.type!=="npc"&&source.type!=="character")return;const speeds=source.system.attributes.speed;speeds.value=__privateMethod(this,_updateSpeed,updateSpeed_fn).call(this,speeds.value),Array.isArray(speeds.otherSpeeds)||(speeds.otherSpeeds=[]);for(const movementType of speeds.otherSpeeds)movementType.value=__privateMethod(this,_updateSpeed,updateSpeed_fn).call(this,movementType.value)}};_updateSpeed=new WeakSet,updateSpeed_fn=__name2(function(speed){const numifiedValue=parseInt(String(speed),10);return Number.isNaN(numifiedValue)?25:numifiedValue},"#updateSpeed"),__name2(_Migration780NumifySpeeds,"Migration780NumifySpeeds"),__publicField(_Migration780NumifySpeeds,"version",.78);let Migration780NumifySpeeds=_Migration780NumifySpeeds;const _Migration781SuppressNoCrowbar=class extends MigrationBase{static{__name(this,"_Migration781SuppressNoCrowbar")}constructor(){super(...arguments),__privateAdd(this,_suppressNoCrowbar)}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(__privateGet(this,_suppressNoCrowbar,suppressNoCrowbar_get))}};_suppressNoCrowbar=new WeakSet,suppressNoCrowbar_get=__name2(function(){return{key:"AdjustModifier",selector:"athletics",slug:"no-crowbar",suppress:!0}},"#suppressNoCrowbar"),__name2(_Migration781SuppressNoCrowbar,"Migration781SuppressNoCrowbar"),__publicField(_Migration781SuppressNoCrowbar,"version",.781);let Migration781SuppressNoCrowbar=_Migration781SuppressNoCrowbar;const _Migration782UnnestActorTraits=class extends MigrationBase{static{__name(this,"_Migration782UnnestActorTraits")}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)}};__name2(_Migration782UnnestActorTraits,"Migration782UnnestActorTraits"),__publicField(_Migration782UnnestActorTraits,"version",.782);let Migration782UnnestActorTraits=_Migration782UnnestActorTraits;const _Migration783RemoveClassSkillAELikes=class extends MigrationBase{static{__name(this,"_Migration783RemoveClassSkillAELikes")}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)))}};__name2(_Migration783RemoveClassSkillAELikes,"Migration783RemoveClassSkillAELikes"),__publicField(_Migration783RemoveClassSkillAELikes,"version",.783);let Migration783RemoveClassSkillAELikes=_Migration783RemoveClassSkillAELikes;const _Migration784CompBrowserPackSetting=class extends MigrationBase{static{__name(this,"_Migration784CompBrowserPackSetting")}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())}}};__name2(_Migration784CompBrowserPackSetting,"Migration784CompBrowserPackSetting"),__publicField(_Migration784CompBrowserPackSetting,"version",.784);let Migration784CompBrowserPackSetting=_Migration784CompBrowserPackSetting;const _Migration785ABCKitItemUUIDs=class extends MigrationBase{static{__name(this,"_Migration785ABCKitItemUUIDs")}constructor(){super(...arguments),__privateAdd(this,_convertToUUIDs)}async updateItem(source){switch(source.type){case"ancestry":case"background":case"class":case"kit":__privateMethod(this,_convertToUUIDs,convertToUUIDs_fn).call(this,Object.values(source.system.items))}}};_convertToUUIDs=new WeakSet,convertToUUIDs_fn=__name2(function(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&&__privateMethod(this,_convertToUUIDs,convertToUUIDs_fn).call(this,Object.values(reference.items))},"#convertToUUIDs"),__name2(_Migration785ABCKitItemUUIDs,"Migration785ABCKitItemUUIDs"),__publicField(_Migration785ABCKitItemUUIDs,"version",.785);let Migration785ABCKitItemUUIDs=_Migration785ABCKitItemUUIDs;const _Migration786RemoveIdentifiedData=class extends MigrationBase{static{__name(this,"_Migration786RemoveIdentifiedData")}async updateItem(source){if(!isPhysicalData(source))return;const identification=source.system.identification??{};identification.identified&&(identification["-=identified"]=null)}};__name2(_Migration786RemoveIdentifiedData,"Migration786RemoveIdentifiedData"),__publicField(_Migration786RemoveIdentifiedData,"version",.786);let Migration786RemoveIdentifiedData=_Migration786RemoveIdentifiedData;const _Migration787ResolvablesToSystem=class extends MigrationBase{static{__name(this,"_Migration787ResolvablesToSystem")}async updateItem(source){source.system=recursiveReplaceString(source.system,value=>value.replace(/@(weapon|spell)\.data\.data./g,"@$1.system.").replace(/@(weapon|spell)\.data./g,"@$1."))}};__name2(_Migration787ResolvablesToSystem,"Migration787ResolvablesToSystem"),__publicField(_Migration787ResolvablesToSystem,"version",.787);let Migration787ResolvablesToSystem=_Migration787ResolvablesToSystem;const _Migration788UpdateTanglefootBags=class extends MigrationBase{static{__name(this,"_Migration788UpdateTanglefootBags")}constructor(){super(...arguments),__privateAdd(this,_getRules)}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=__privateMethod(this,_getRules,getRules_fn).call(this,"Lesser");return}case"tanglefoot-bag-moderate":{source.system.rules=__privateMethod(this,_getRules,getRules_fn).call(this,"Moderate");return}case"tanglefoot-bag-greater":{source.system.rules=__privateMethod(this,_getRules,getRules_fn).call(this,"Greater");return}case"tanglefoot-bag-major":{source.system.rules=__privateMethod(this,_getRules,getRules_fn).call(this,"Major");return}}}};_getRules=new WeakSet,getRules_fn=__name2(function(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"}]},"#getRules"),__name2(_Migration788UpdateTanglefootBags,"Migration788UpdateTanglefootBags"),__publicField(_Migration788UpdateTanglefootBags,"version",.788);let Migration788UpdateTanglefootBags=_Migration788UpdateTanglefootBags;const _Migration789UpdatePreciseStrike=class extends MigrationBase{static{__name(this,"_Migration789UpdatePreciseStrike")}constructor(){super(...arguments),__privateAdd(this,_preciseStrikeRules),__privateAdd(this,_finishingPrecisionRules)}async updateItem(source){if(source.type==="feat"){if(source.system.slug==="precise-strike")source.system.rules=__privateGet(this,_preciseStrikeRules,preciseStrikeRules_get);else if(source.system.slug==="finishing-precision"){const rules=source.system.rules.filter(r=>r.key==="GrantItem");source.system.rules=[...rules,...__privateGet(this,_finishingPrecisionRules,finishingPrecisionRules_get)]}}}};_preciseStrikeRules=new WeakSet,preciseStrikeRules_get=__name2(function(){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}}]}}]},"#preciseStrikeRules"),_finishingPrecisionRules=new WeakSet,finishingPrecisionRules_get=__name2(function(){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"}]},"#finishingPrecisionRules"),__name2(_Migration789UpdatePreciseStrike,"Migration789UpdatePreciseStrike"),__publicField(_Migration789UpdatePreciseStrike,"version",.789);let Migration789UpdatePreciseStrike=_Migration789UpdatePreciseStrike;const _Migration790MultipleClassDCs=class extends MigrationBase{static{__name(this,"_Migration790MultipleClassDCs")}constructor(){super(...arguments),__privateAdd(this,_isClassFeature5),__privateAdd(this,_otherClassDCs,new Map([["call-implement","thaumaturge"],["eerie-proclamation","ranger"],["stunning-fist","monk"],["ring-bell","thaumaturge"]]))}async updateActor(source){if(source.type!=="character")return;const customModifiers=source.system.customModifiers??{};customModifiers?.class&&(customModifiers["-=class"]=null)}async updateItem(source){if(__privateMethod(this,_isClassFeature5,isClassFeature_fn5).call(this,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(__privateGet(this,_otherClassDCs).has(itemSlug)){const oldClassDCPattern=/\bsystem\.attributes\.classDC\b/,classSlug=__privateGet(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}`)}}};_otherClassDCs=new WeakMap,_isClassFeature5=new WeakSet,isClassFeature_fn5=__name2(function(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"},"#isClassFeature"),__name2(_Migration790MultipleClassDCs,"Migration790MultipleClassDCs"),__publicField(_Migration790MultipleClassDCs,"version",.79);let Migration790MultipleClassDCs=_Migration790MultipleClassDCs;const _Migration791RuffianHands=class extends MigrationBase{static{__name(this,"_Migration791RuffianHands")}constructor(){super(...arguments),__privateAdd(this,_critSpec),__privateAdd(this,_hands)}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(__privateGet(this,_critSpec,critSpec_get));break}case"healing-hands":{const hands=__privateGet(this,_hands,hands_get);hands.predicate={all:["item:slug:heal"]},source.system.rules=[hands];break}case"harming-hands":{const hands=__privateGet(this,_hands,hands_get);hands.predicate={all:["item:slug:harm"]},source.system.rules=[hands];break}}}};_critSpec=new WeakSet,critSpec_get=__name2(function(){return{key:"CriticalSpecialization",predicate:{all:["target:condition:flat-footed","weapon:category:simple",{lte:["weapon:damage:die:faces",8]}]}}},"#critSpec"),_hands=new WeakSet,hands_get=__name2(function(){return{key:"DamageDice",override:{dieSize:"d10"},selector:"spell-damage"}},"#hands"),__name2(_Migration791RuffianHands,"Migration791RuffianHands"),__publicField(_Migration791RuffianHands,"version",.791);let Migration791RuffianHands=_Migration791RuffianHands;const _Migration792RemoveTokenAELikes=class extends MigrationBase{static{__name(this,"_Migration792RemoveTokenAELikes")}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)}};__name2(_Migration792RemoveTokenAELikes,"Migration792RemoveTokenAELikes"),__publicField(_Migration792RemoveTokenAELikes,"version",.792);let Migration792RemoveTokenAELikes=_Migration792RemoveTokenAELikes;const _Migration793MakePredicatesArrays=class extends MigrationBase{static{__name(this,"_Migration793MakePredicatesArrays")}constructor(){super(...arguments),__privateAdd(this,_convertLegacyData),__privateAdd(this,_isOldRawPredicate),__privateAdd(this,_isArrayChoiceSet),__privateAdd(this,_isObjectChoiceSet)}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(__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.predicate)&&(rule.predicate=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.predicate)),__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.definition)&&(rule.definition=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.definition)),__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.allowedDrops)&&(rule.allowedDrops={label:rule.allowedDrops.label??void 0,predicate:__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.allowedDrops)}),__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.predicate)&&(rule.predicate=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.predicate)),__privateMethod(this,_isArrayChoiceSet,isArrayChoiceSet_fn).call(this,rule))for(const choice of rule.choices)__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,choice.predicate)&&(choice.predicate=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,choice.predicate));else __privateMethod(this,_isObjectChoiceSet,isObjectChoiceSet_fn).call(this,rule)?(__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.choices.predicate)&&(rule.choices.predicate=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.choices.predicate)),__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.choices.postFilter)&&(rule.choices.postFilter=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.choices.postFilter))):__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.craftableItems)&&(rule.craftableItems=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.craftableItems));__privateMethod(this,_isOldRawPredicate,isOldRawPredicate_fn).call(this,rule.disabledIf)&&(rule.disabledIf=__privateMethod(this,_convertLegacyData,convertLegacyData_fn).call(this,rule.disabledIf))}}};_convertLegacyData=new WeakSet,convertLegacyData_fn=__name2(function(predicate){const keys2=Object.keys(predicate);return keys2.length===0?[]:keys2.length===1&&Array.isArray(predicate.all)?deepClone(predicate.all):keys2.length===1&&Array.isArray(predicate.any)&&predicate.any.length===1?deepClone(predicate.any):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())},"#convertLegacyData"),_isOldRawPredicate=new WeakSet,isOldRawPredicate_fn=__name2(function(predicate){return!predicate||Array.isArray(predicate)||isObject(predicate)&&Array.isArray(predicate.predicate)?!1:predicate instanceof Object},"#isOldRawPredicate"),_isArrayChoiceSet=new WeakSet,isArrayChoiceSet_fn=__name2(function(rule){return rule.key==="ChoiceSet"&&Array.isArray(rule.choices)},"#isArrayChoiceSet"),_isObjectChoiceSet=new WeakSet,isObjectChoiceSet_fn=__name2(function(rule){return rule.key==="ChoiceSet"&&isObject(rule.choices)&&!Array.isArray(rule.choices)},"#isObjectChoiceSet"),__name2(_Migration793MakePredicatesArrays,"Migration793MakePredicatesArrays"),__publicField(_Migration793MakePredicatesArrays,"version",.793);let Migration793MakePredicatesArrays=_Migration793MakePredicatesArrays;const _Migration794AddWildShapeChoices=class extends MigrationBase{static{__name(this,"_Migration794AddWildShapeChoices")}constructor(){super(...arguments),__privateAdd(this,_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&&__privateGet(this,_shapeFeats).has(sourceId)){const fromPack=await fromUuid(sourceId);fromPack instanceof FeatPF2e&&(source.system.rules=fromPack.toObject().system.rules)}}};_shapeFeats=new WeakMap,__name2(_Migration794AddWildShapeChoices,"Migration794AddWildShapeChoices"),__publicField(_Migration794AddWildShapeChoices,"version",.794);let Migration794AddWildShapeChoices=_Migration794AddWildShapeChoices;const _Migration795CleanupFlatFootedToggle=class extends MigrationBase{static{__name(this,"_Migration795CleanupFlatFootedToggle")}constructor(){super(...arguments),__privateAdd(this,_flatFootedToggle),__privateAdd(this,_isFlatFootedToggle)}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=>__privateMethod(this,_isFlatFootedToggle,isFlatFootedToggle_fn).call(this,r))||source.system.rules.push(__privateGet(this,_flatFootedToggle,flatFootedToggle_get))}}};_flatFootedToggle=new WeakSet,flatFootedToggle_get=__name2(function(){return{key:"RollOption",domain:"all",label:"PF2E.SpecificRule.TOTMToggle.FlatFooted",option:"target:condition:flat-footed",toggleable:"totm"}},"#flatFootedToggle"),_isFlatFootedToggle=new WeakSet,isFlatFootedToggle_fn=__name2(function(rule){return rule.key==="RollOption"&&rule.option==="target:condition:flat-footed"&&rule.toggleable==="totm"},"#isFlatFootedToggle"),__name2(_Migration795CleanupFlatFootedToggle,"Migration795CleanupFlatFootedToggle"),__publicField(_Migration795CleanupFlatFootedToggle,"version",.795);let Migration795CleanupFlatFootedToggle=_Migration795CleanupFlatFootedToggle;const _Migration796ItemGrantsToObjects=class extends MigrationBase{static{__name(this,"_Migration796ItemGrantsToObjects")}constructor(){super(...arguments),__privateAdd(this,_convertToEntry),__privateAdd(this,_modifyFlag)}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]=__privateMethod(this,_convertToEntry,convertToEntry_fn).call(this,source,item,grant);if(flag!==null){const modifiedFlag=__privateMethod(this,_modifyFlag,modifyFlag_fn).call(this,grantsObject,flag);grantsObject[modifiedFlag]=grantSource}}return grantsObject},{}))}}};_convertToEntry=new WeakSet,convertToEntry_fn=__name2(function(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]},"#convertToEntry"),_modifyFlag=new WeakSet,modifyFlag_fn=__name2(function(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}`},"#modifyFlag"),__name2(_Migration796ItemGrantsToObjects,"Migration796ItemGrantsToObjects"),__publicField(_Migration796ItemGrantsToObjects,"version",.796);let Migration796ItemGrantsToObjects=_Migration796ItemGrantsToObjects;const _Migration797MetagameSetting=class extends MigrationBase{static{__name(this,"_Migration797MetagameSetting")}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)}}}};__name2(_Migration797MetagameSetting,"Migration797MetagameSetting"),__publicField(_Migration797MetagameSetting,"version",.797);let Migration797MetagameSetting=_Migration797MetagameSetting;const _Migration798WeaponToItemStatements=class extends MigrationBase{static{__name(this,"_Migration798WeaponToItemStatements")}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:")))}}};__name2(_Migration798WeaponToItemStatements,"Migration798WeaponToItemStatements"),__publicField(_Migration798WeaponToItemStatements,"version",.798);let Migration798WeaponToItemStatements=_Migration798WeaponToItemStatements;const _Migration799RMRecallKnowledgeDuplicates=class extends MigrationBase{static{__name(this,"_Migration799RMRecallKnowledgeDuplicates")}constructor(){super(...arguments),__privateAdd(this,_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(__privateGet(this,_oldIdsPattern),"pf2e.actionspf2e.1OagaWtBpVXExToo")}};_oldIdsPattern=new WeakMap,__name2(_Migration799RMRecallKnowledgeDuplicates,"Migration799RMRecallKnowledgeDuplicates"),__publicField(_Migration799RMRecallKnowledgeDuplicates,"version",.799);let Migration799RMRecallKnowledgeDuplicates=_Migration799RMRecallKnowledgeDuplicates;const _Migration800SelfEffectPanacheRage=class extends MigrationBase{static{__name(this,"_Migration800SelfEffectPanacheRage")}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")))}};__name2(_Migration800SelfEffectPanacheRage,"Migration800SelfEffectPanacheRage"),__publicField(_Migration800SelfEffectPanacheRage,"version",.8);let Migration800SelfEffectPanacheRage=_Migration800SelfEffectPanacheRage;const _Migration801ColorDarkvision=class extends MigrationBase{static{__name(this,"_Migration801ColorDarkvision")}constructor(){super(...arguments),__privateAdd(this,_colorDarkvision)}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(__privateGet(this,_colorDarkvision,colorDarkvision_get))}};_colorDarkvision=new WeakSet,colorDarkvision_get=__name2(function(){return{key:"ActiveEffectLike",path:"flags.pf2e.colorDarkvision",mode:"override",value:!0}},"#colorDarkvision"),__name2(_Migration801ColorDarkvision,"Migration801ColorDarkvision"),__publicField(_Migration801ColorDarkvision,"version",.801);let Migration801ColorDarkvision=_Migration801ColorDarkvision;const _Migration802StripFeatActionCategory=class extends MigrationBase{static{__name(this,"_Migration802StripFeatActionCategory")}async updateItem(source){if(source.type!=="feat")return;const feat=source.system;feat.actionCategory&&(delete feat.actionCategory,feat["-=actionCategory"]=null)}};__name2(_Migration802StripFeatActionCategory,"Migration802StripFeatActionCategory"),__publicField(_Migration802StripFeatActionCategory,"version",.802);let Migration802StripFeatActionCategory=_Migration802StripFeatActionCategory;const _Migration803NormalizeSpellArea=class extends MigrationBase{static{__name(this,"_Migration803NormalizeSpellArea")}constructor(){super(...arguments),__privateAdd(this,_isAreaType),__privateAdd(this,_hasDetails),__privateAdd(this,_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&&__privateMethod(this,_isAreaType,isAreaType_fn).call(this,area.areaType)&&(area.type=area.areaType,delete area.areaType,area["-=areaType"]=null)),area?.value&&__privateMethod(this,_isAreaType,isAreaType_fn).call(this,area.type)||(source.system.area=null),"areasize"in source.system&&isObject(source.system.areasize)&&(__privateMethod(this,_hasDetails,hasDetails_fn).call(this,source.system.areasize.value)&&area&&(area.details=source.system.areasize.value),delete source.system.areasize,source.system["-=areasize"]=null)}};_AREA_TYPES=new WeakMap,_isAreaType=new WeakSet,isAreaType_fn=__name2(function(areaType){return typeof areaType=="string"&&areaType.length>0&&__privateGet(this,_AREA_TYPES).has(areaType)},"#isAreaType"),_hasDetails=new WeakSet,hasDetails_fn=__name2(function(details){return typeof details=="string"&&details.trim().length>0&&!/^\d+-foot (?:burst|cone|cube|emanation|line|square)$/.test(details)},"#hasDetails"),__name2(_Migration803NormalizeSpellArea,"Migration803NormalizeSpellArea"),__publicField(_Migration803NormalizeSpellArea,"version",.803);let Migration803NormalizeSpellArea=_Migration803NormalizeSpellArea;const _Migration804RemoveConsumableProperties=class extends MigrationBase{static{__name(this,"_Migration804RemoveConsumableProperties")}async updateItem(source){if(source.type!=="consumable")return;const system=source.system;system.uses&&(delete system.uses,system["-=uses"]=null),system.autoUse&&(delete system.autoUse,system["-=autoUse"]=null),"_deprecated"in system.charges&&(delete system.charges._deprecated,system.charges["-=deprecated"]=null),"_deprecated"in system.consume&&(delete system.consume._deprecated,system.consume["-=deprecated"]=null)}};__name2(_Migration804RemoveConsumableProperties,"Migration804RemoveConsumableProperties"),__publicField(_Migration804RemoveConsumableProperties,"version",.804);let Migration804RemoveConsumableProperties=_Migration804RemoveConsumableProperties;const _Migration805InlineDamageRolls=class extends MigrationBase{static{__name(this,"_Migration805InlineDamageRolls")}constructor(){super(...arguments),__privateAdd(this,_updateDamageFormula),__privateAdd(this,_pattern,/\[\[\/r .+?\]\]\]?(?:\{[^}]+\})?/g),__privateAdd(this,_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")})())}async updateActor(source){source.system=recursiveReplaceString(source.system,s=>__privateMethod(this,_updateDamageFormula,updateDamageFormula_fn).call(this,s))}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>__privateMethod(this,_updateDamageFormula,updateDamageFormula_fn).call(this,s))}async updateJournalEntry(source){source.pages=recursiveReplaceString(source.pages,s=>__privateMethod(this,_updateDamageFormula,updateDamageFormula_fn).call(this,s))}};_pattern=new WeakMap,_damageTypeLabelPattern=new WeakMap,_updateDamageFormula=new WeakSet,updateDamageFormula_fn=__name2(function(text){const skipStrings=["splash","precision","persistent","d20","#"];return text.replace(__privateGet(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&&!__privateGet(this,_damageTypeLabelPattern).test(customLabel)?`${reassembled}{${customLabel}}`:labelEndsWithDamage?`${reassembled} damage`:reassembled})},"#updateDamageFormula"),__name2(_Migration805InlineDamageRolls,"Migration805InlineDamageRolls"),__publicField(_Migration805InlineDamageRolls,"version",.805);let Migration805InlineDamageRolls=_Migration805InlineDamageRolls;const _Migration806TorchImprovisedOtherTags=class extends MigrationBase{static{__name(this,"_Migration806TorchImprovisedOtherTags")}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"])}}};__name2(_Migration806TorchImprovisedOtherTags,"Migration806TorchImprovisedOtherTags"),__publicField(_Migration806TorchImprovisedOtherTags,"version",.806);let Migration806TorchImprovisedOtherTags=_Migration806TorchImprovisedOtherTags;const _Migration807RMActivatedEffectFields=class extends MigrationBase{static{__name(this,"_Migration807RMActivatedEffectFields")}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)}};__name2(_Migration807RMActivatedEffectFields,"Migration807RMActivatedEffectFields"),__publicField(_Migration807RMActivatedEffectFields,"version",.807);let Migration807RMActivatedEffectFields=_Migration807RMActivatedEffectFields;const _Migration808CountDamageDice=class extends MigrationBase{static{__name(this,"_Migration808CountDamageDice")}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>s.replace(/\(?\b1\s*\+\s*@(item|weapon)(?:.system)?.runes.striking\)?/g,"@$1.system.damage.dice"))}};__name2(_Migration808CountDamageDice,"Migration808CountDamageDice"),__publicField(_Migration808CountDamageDice,"version",.808);let Migration808CountDamageDice=_Migration808CountDamageDice;const _Migration809AutomatonEnhancements=class extends MigrationBase{static{__name(this,"_Migration809AutomatonEnhancements")}constructor(){super(...arguments),__privateAdd(this,_automatonEnhancements)}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(__privateGet(this,_automatonEnhancements,automatonEnhancements_get))}};_automatonEnhancements=new WeakSet,automatonEnhancements_get=__name2(function(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.automaton.enhancements",priority:10,value:{greater:[],lesser:[]}}},"#automatonEnhancements"),__name2(_Migration809AutomatonEnhancements,"Migration809AutomatonEnhancements"),__publicField(_Migration809AutomatonEnhancements,"version",.809);let Migration809AutomatonEnhancements=_Migration809AutomatonEnhancements;const _Migration810LootDescriptionValue=class extends MigrationBase{static{__name(this,"_Migration810LootDescriptionValue")}async updateActor(source){if(source.type==="loot"){const details=source.system.details;details.description instanceof Object&&(details.description=String(details.description.value??""))}}};__name2(_Migration810LootDescriptionValue,"Migration810LootDescriptionValue"),__publicField(_Migration810LootDescriptionValue,"version",.81);let Migration810LootDescriptionValue=_Migration810LootDescriptionValue;const _Migration811InlineDamageRollsPersistent=class extends MigrationBase{static{__name(this,"_Migration811InlineDamageRollsPersistent")}constructor(){super(...arguments),__privateAdd(this,_updateDamageFormula2),__privateAdd(this,_conditionPattern,/(?<=\]\]|})(\s*@(?:UUID|Compendium)\[(?:Compendium\.)?pf2e\.conditionitems\.(?:Persistent Damage|lDVqvLKA6eF3Df60)\]\{[^}]+})/g),__privateAdd(this,_pattern2,/\[\[\/r ([^[\]]+(\[.*?\])?)\]\](\{\dd\d[^{}]*\})?/g)}async updateActor(source){source.system=recursiveReplaceString(source.system,s=>__privateMethod(this,_updateDamageFormula2,updateDamageFormula_fn2).call(this,s))}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>__privateMethod(this,_updateDamageFormula2,updateDamageFormula_fn2).call(this,s))}async updateJournalEntry(source){source.pages=recursiveReplaceString(source.pages,s=>__privateMethod(this,_updateDamageFormula2,updateDamageFormula_fn2).call(this,s))}};_conditionPattern=new WeakMap,_pattern2=new WeakMap,_updateDamageFormula2=new WeakSet,updateDamageFormula_fn2=__name2(function(text){return text.replace(__privateGet(this,_conditionPattern)," damage").replace(__privateGet(this,_pattern2),(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})},"#updateDamageFormula"),__name2(_Migration811InlineDamageRollsPersistent,"Migration811InlineDamageRollsPersistent"),__publicField(_Migration811InlineDamageRollsPersistent,"version",.811);let Migration811InlineDamageRollsPersistent=_Migration811InlineDamageRollsPersistent;const _Migration812RestructureIWR=class extends MigrationBase{static{__name(this,"_Migration812RestructureIWR")}constructor(){super(...arguments),__privateAdd(this,_getWR),__privateAdd(this,_parseExceptions),__privateAdd(this,_normalizeType),__privateAdd(this,_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"})}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(oldData)&&"value"in oldData&&Array.isArray(oldData.value)&&oldData.value.length>0){const immunities=oldData.value.map(i=>__privateMethod(this,_normalizeType,normalizeType_fn).call(this,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=__privateMethod(this,_getWR,getWR_fn).call(this,oldData,WEAKNESS_TYPES).map(data=>{const weakness=pick(data,["type","value"]),exceptions=__privateMethod(this,_parseExceptions,parseExceptions_fn).call(this,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=__privateMethod(this,_getWR,getWR_fn).call(this,oldData,RESISTANCE_TYPES).map(data=>{const resistance=pick(data,["type","value"]),parsed=__privateMethod(this,_parseExceptions,parseExceptions_fn).call(this,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:__privateMethod(this,_normalizeType,normalizeType_fn).call(this,rule.type),typeof rule.except=="string"){const exceptions=__privateMethod(this,_parseExceptions,parseExceptions_fn).call(this,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:__privateMethod(this,_normalizeType,normalizeType_fn).call(this,rule.value)}};_getWR=new WeakSet,getWR_fn=__name2(function(maybeWR,typeSet){return maybeWR.filter(r=>isObject(r)&&typeof r.type=="string"&&typeof r.value=="number").map(wr=>(wr.type=__privateMethod(this,_normalizeType,normalizeType_fn).call(this,wr.type),wr.value=Math.abs(wr.value),wr)).filter(r=>setHasElement(typeSet,r.type))},"#getWR"),_oldENmappings=new WeakMap,_parseExceptions=new WeakSet,parseExceptions_fn=__name2(function(text){const normalized=(__privateGet(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}},"#parseExceptions"),_normalizeType=new WeakSet,normalizeType_fn=__name2(function(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)}},"#normalizeType"),__name2(_Migration812RestructureIWR,"Migration812RestructureIWR"),__publicField(_Migration812RestructureIWR,"version",.812);let Migration812RestructureIWR=_Migration812RestructureIWR;const _Migration813NormalizeColdIron=class extends MigrationBase{static{__name(this,"_Migration813NormalizeColdIron")}constructor(){super(...arguments),__privateAdd(this,_updateWeaponMaterialData),__privateAdd(this,_updateChoiceSet)}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"&&__privateMethod(this,_updateWeaponMaterialData,updateWeaponMaterialData_fn).call(this,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)__privateMethod(this,_updateChoiceSet,updateChoiceSet_fn).call(this,choiceSet)}};_updateWeaponMaterialData=new WeakSet,updateWeaponMaterialData_fn=__name2(function(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)},"#updateWeaponMaterialData"),_updateChoiceSet=new WeakSet,updateChoiceSet_fn=__name2(function(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")},"#updateChoiceSet"),__name2(_Migration813NormalizeColdIron,"Migration813NormalizeColdIron"),__publicField(_Migration813NormalizeColdIron,"version",.813);let Migration813NormalizeColdIron=_Migration813NormalizeColdIron;const _Migration814CalculatedExpandedSplash=class extends MigrationBase{static{__name(this,"_Migration814CalculatedExpandedSplash")}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}}}};__name2(_Migration814CalculatedExpandedSplash,"Migration814CalculatedExpandedSplash"),__publicField(_Migration814CalculatedExpandedSplash,"version",.814);let Migration814CalculatedExpandedSplash=_Migration814CalculatedExpandedSplash;const _Migration815ConsumableDataCleanup=class extends MigrationBase{static{__name(this,"_Migration815ConsumableDataCleanup")}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)}}};__name2(_Migration815ConsumableDataCleanup,"Migration815ConsumableDataCleanup"),__publicField(_Migration815ConsumableDataCleanup,"version",.815);let Migration815ConsumableDataCleanup=_Migration815ConsumableDataCleanup;const _Migration816AlchemistResearchFields=class extends MigrationBase{static{__name(this,"_Migration816AlchemistResearchFields")}constructor(){super(...arguments),__privateAdd(this,_bomberSetFlags),__privateAdd(this,_chirurgeonSetFlags),__privateAdd(this,_mutagenistSetFlags),__privateAdd(this,_toxicologistSetFlags)}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(__privateGet(this,_bomberSetFlags,bomberSetFlags_get));break}case"chirurgeon":{source.system.rules.push(__privateGet(this,_chirurgeonSetFlags,chirurgeonSetFlags_get));break}case"mutagenist":{source.system.rules.push(__privateGet(this,_mutagenistSetFlags,mutagenistSetFlags_get));break}case"toxicologist":{source.system.rules.push(__privateGet(this,_toxicologistSetFlags,toxicologistSetFlags_get));break}}}};_bomberSetFlags=new WeakSet,bomberSetFlags_get=__name2(function(){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"}}},"#bomberSetFlags"),_chirurgeonSetFlags=new WeakSet,chirurgeonSetFlags_get=__name2(function(){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"}}},"#chirurgeonSetFlags"),_mutagenistSetFlags=new WeakSet,mutagenistSetFlags_get=__name2(function(){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"}}},"#mutagenistSetFlags"),_toxicologistSetFlags=new WeakSet,toxicologistSetFlags_get=__name2(function(){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"}}},"#toxicologistSetFlags"),__name2(_Migration816AlchemistResearchFields,"Migration816AlchemistResearchFields"),__publicField(_Migration816AlchemistResearchFields,"version",.816);let Migration816AlchemistResearchFields=_Migration816AlchemistResearchFields;const _Migration817FieldDiscoveryPredicates=class extends MigrationBase{static{__name(this,"_Migration817FieldDiscoveryPredicates")}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}`]}}};__name2(_Migration817FieldDiscoveryPredicates,"Migration817FieldDiscoveryPredicates"),__publicField(_Migration817FieldDiscoveryPredicates,"version",.817);let Migration817FieldDiscoveryPredicates=_Migration817FieldDiscoveryPredicates;const _Migration818BasicUndeadNegativeHealing=class extends MigrationBase{static{__name(this,"_Migration818BasicUndeadNegativeHealing")}constructor(){super(...arguments),__privateAdd(this,_needsRE)}async updateItem(source){if(source.type==="feat"&&__privateMethod(this,_needsRE,needsRE_fn).call(this,source)){const rule={key:"ActiveEffectLike",mode:"override",path:"system.attributes.hp.negativeHealing",value:!0};source.system.rules.push(rule)}}};_needsRE=new WeakSet,needsRE_fn=__name2(function(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")},"#needsRE"),__name2(_Migration818BasicUndeadNegativeHealing,"Migration818BasicUndeadNegativeHealing"),__publicField(_Migration818BasicUndeadNegativeHealing,"version",.818);let Migration818BasicUndeadNegativeHealing=_Migration818BasicUndeadNegativeHealing;const _Migration819SpinTaleAdventureSpecific=class extends MigrationBase{static{__name(this,"_Migration819SpinTaleAdventureSpecific")}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)}}};__name2(_Migration819SpinTaleAdventureSpecific,"Migration819SpinTaleAdventureSpecific"),__publicField(_Migration819SpinTaleAdventureSpecific,"version",.819);let Migration819SpinTaleAdventureSpecific=_Migration819SpinTaleAdventureSpecific;const _Migration820RemoveUnusedTraitsData=class extends MigrationBase{static{__name(this,"_Migration820RemoveUnusedTraitsData")}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))}};__name2(_Migration820RemoveUnusedTraitsData,"Migration820RemoveUnusedTraitsData"),__publicField(_Migration820RemoveUnusedTraitsData,"version",.82);let Migration820RemoveUnusedTraitsData=_Migration820RemoveUnusedTraitsData;const _Migration821InlineDamageRolls=class extends MigrationBase{static{__name(this,"_Migration821InlineDamageRolls")}constructor(){super(...arguments),__privateAdd(this,_cleanFormula),__privateAdd(this,_buildSplashFormula),__privateAdd(this,_buildDamageFormula),__privateAdd(this,_updateDamageFormula3),__privateAdd(this,_splashPattern1,/\[\[(\/b?r)\s*{([^}]*)}\[splash,\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g),__privateAdd(this,_splashPattern2,/\[\[(\/b?r)\s*([^[]*)\[splash,\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g),__privateAdd(this,_damagePatternSingle,/\[\[(\/b?r)\s*{([^}]*)}\[\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g),__privateAdd(this,_damagePatternPair,/\[\[(\/b?r)\s*{([^}]*)}\[\s*([^\]]*)\]\s*[+,]\s*{([^}]*)}\[\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g)}async updateActor(source){source.system=recursiveReplaceString(source.system,s=>__privateMethod(this,_updateDamageFormula3,updateDamageFormula_fn3).call(this,s))}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>__privateMethod(this,_updateDamageFormula3,updateDamageFormula_fn3).call(this,s))}async updateJournalEntry(source){source.pages=recursiveReplaceString(source.pages,s=>__privateMethod(this,_updateDamageFormula3,updateDamageFormula_fn3).call(this,s))}};_splashPattern1=new WeakMap,_splashPattern2=new WeakMap,_damagePatternSingle=new WeakMap,_damagePatternPair=new WeakMap,_cleanFormula=new WeakSet,cleanFormula_fn=__name2(function(formula){return formula=formula.replace(/\s+/g,""),["+","-","*","/"].some(o=>formula.includes(o))?`(${formula})`:formula},"#cleanFormula"),_buildSplashFormula=new WeakSet,buildSplashFormula_fn=__name2(function(roll,formula,damage,tag){return formula=__privateMethod(this,_cleanFormula,cleanFormula_fn).call(this,formula),damage=damage.trim(),tag=tag?.trim()??"",tag.length>0?`[[${roll} (${formula}[splash])[${damage}] ${tag}]]`:`[[${roll} (${formula}[splash])[${damage}]]]`},"#buildSplashFormula"),_buildDamageFormula=new WeakSet,buildDamageFormula_fn=__name2(function(roll,parts,tag){if(tag=tag?.trim()??"",parts.length===1){const formula=__privateMethod(this,_cleanFormula,cleanFormula_fn).call(this,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=__privateMethod(this,_cleanFormula,cleanFormula_fn).call(this,p.formula),damage=p.damage.trim();return`${formula}[${damage}]`}).join(",");return tag.length>0?`[[${roll} {${assembled}} ${tag}]]`:`[[${roll} {${assembled}}]]`}else return""},"#buildDamageFormula"),_updateDamageFormula3=new WeakSet,updateDamageFormula_fn3=__name2(function(text){return text=text.replace(__privateGet(this,_splashPattern1),(_,roll,formula,damage,tag)=>__privateMethod(this,_buildSplashFormula,buildSplashFormula_fn).call(this,roll,formula,damage,tag)),text=text.replace(__privateGet(this,_splashPattern2),(_,roll,formula,damage,tag)=>__privateMethod(this,_buildSplashFormula,buildSplashFormula_fn).call(this,roll,formula,damage,tag)),text=text.replace(__privateGet(this,_damagePatternSingle),(_,roll,formula,damage,tag)=>__privateMethod(this,_buildDamageFormula,buildDamageFormula_fn).call(this,roll,[{formula,damage}],tag)),text=text.replace(__privateGet(this,_damagePatternPair),(_,roll,formula1,damage1,formula2,damage2,tag)=>__privateMethod(this,_buildDamageFormula,buildDamageFormula_fn).call(this,roll,[{formula:formula1,damage:damage1},{formula:formula2,damage:damage2}],tag)),text},"#updateDamageFormula"),__name2(_Migration821InlineDamageRolls,"Migration821InlineDamageRolls"),__publicField(_Migration821InlineDamageRolls,"version",.821);let Migration821InlineDamageRolls=_Migration821InlineDamageRolls;const _Migration822BladeAllyConsolidation=class extends MigrationBase{static{__name(this,"_Migration822BladeAllyConsolidation")}constructor(){super(...arguments),__privateAdd(this,_rename)}async updateItem(source){source.system.description.value.includes("feat-effects")&&(source.system.description.value=__privateMethod(this,_rename,rename_fn).call(this,source.system.description.value))}};_rename=new WeakSet,rename_fn=__name2(function(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")},"#rename"),__name2(_Migration822BladeAllyConsolidation,"Migration822BladeAllyConsolidation"),__publicField(_Migration822BladeAllyConsolidation,"version",.822);let Migration822BladeAllyConsolidation=_Migration822BladeAllyConsolidation;const _Migration823HeritageAncestrySlug=class extends MigrationBase{static{__name(this,"_Migration823HeritageAncestrySlug")}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)}};__name2(_Migration823HeritageAncestrySlug,"Migration823HeritageAncestrySlug"),__publicField(_Migration823HeritageAncestrySlug,"version",.823);let Migration823HeritageAncestrySlug=_Migration823HeritageAncestrySlug;const _Migration824SneakAttackDamageSource=class extends MigrationBase{static{__name(this,"_Migration824SneakAttackDamageSource")}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}}}};__name2(_Migration824SneakAttackDamageSource,"Migration824SneakAttackDamageSource"),__publicField(_Migration824SneakAttackDamageSource,"version",.824);let Migration824SneakAttackDamageSource=_Migration824SneakAttackDamageSource;const _Migration825KhakkharaFengHuoLun=class extends MigrationBase{static{__name(this,"_Migration825KhakkharaFengHuoLun")}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")}}};__name2(_Migration825KhakkharaFengHuoLun,"Migration825KhakkharaFengHuoLun"),__publicField(_Migration825KhakkharaFengHuoLun,"version",.825);let Migration825KhakkharaFengHuoLun=_Migration825KhakkharaFengHuoLun;const _Migration826GutConditionData=class extends MigrationBase{static{__name(this,"_Migration826GutConditionData")}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}};__name2(_Migration826GutConditionData,"Migration826GutConditionData"),__publicField(_Migration826GutConditionData,"version",.826);let Migration826GutConditionData=_Migration826GutConditionData;const _Migration827FixTVShieldTraits=class extends MigrationBase{static{__name(this,"_Migration827FixTVShieldTraits")}async updateItem(source){const traits=source.system.traits;if(isObject(traits)&&"value"in traits&&!Array.isArray(traits.value)&&(traits.value=[]),source.type==="armor")switch(source.system.slug){case"dart-shield":{source.system.traits.value=["launching-dart"];return}case"klar":{source.system.traits.value=["integrated-1d6-s-versatile-p"];return}case"meteor-shield":{source.system.traits.value=["shield-throw-30"];return}case"razor-disc":{source.system.traits.value=["integrated-1d6-s","shield-throw-20"];return}}}};__name2(_Migration827FixTVShieldTraits,"Migration827FixTVShieldTraits"),__publicField(_Migration827FixTVShieldTraits,"version",.827);let Migration827FixTVShieldTraits=_Migration827FixTVShieldTraits;const _Migration828PruneInvalidTraits=class extends MigrationBase{static{__name(this,"_Migration828PruneInvalidTraits")}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)switch(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 in actionTraits);return}case"affliction":case"effect":{traits.value=traits.value.filter(t=>t in actionTraits||t in spellTraits);return}case"ancestry":{traits.value=traits.value.filter(t=>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 in armorTraits);return}case"backpack":case"equipment":{traits.value=traits.value.filter(t=>t in equipmentTraits);return}case"consumable":{traits.value=traits.value.filter(t=>t in consumableTraits);return}case"class":{traits.value=traits.value.filter(t=>t in classTraits);return}case"feat":{traits.value=traits.value.filter(t=>t in featTraits);return}case"melee":{traits.value=traits.value.filter(t=>t in npcAttackTraits);return}case"spell":{traits.value=traits.value.map(t=>t.replace(/^audible$/,"auditory")).filter(t=>t in spellTraits);return}case"weapon":{traits.value=traits.value.filter(t=>t in weaponTraits);return}}}};__name2(_Migration828PruneInvalidTraits,"Migration828PruneInvalidTraits"),__publicField(_Migration828PruneInvalidTraits,"version",.828);let Migration828PruneInvalidTraits=_Migration828PruneInvalidTraits;const _Migration829RMRitualEntries=class extends MigrationBase{static{__name(this,"_Migration829RMRitualEntries")}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){source.type==="spell"&&source.system.category.value==="ritual"&&source.system.location&&(source.system.location.value=null)}};__name2(_Migration829RMRitualEntries,"Migration829RMRitualEntries"),__publicField(_Migration829RMRitualEntries,"version",.829);let Migration829RMRitualEntries=_Migration829RMRitualEntries;const _Migration830BarbarianRework=class extends MigrationBase{static{__name(this,"_Migration830BarbarianRework")}constructor(){super(...arguments),__privateAdd(this,_removeLinks)}async updateItem(source){source.system.description.value=__privateMethod(this,_removeLinks,removeLinks_fn).call(this,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=new WeakSet,removeLinks_fn=__name2(function(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")},"#removeLinks"),__name2(_Migration830BarbarianRework,"Migration830BarbarianRework"),__publicField(_Migration830BarbarianRework,"version",.83);let Migration830BarbarianRework=_Migration830BarbarianRework;const _Migration831ClericDoctrines=class extends MigrationBase{static{__name(this,"_Migration831ClericDoctrines")}constructor(){super(...arguments),__privateAdd(this,_cloisteredClericSetFlags),__privateAdd(this,_warpriestSetFlags)}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(__privateGet(this,_cloisteredClericSetFlags,cloisteredClericSetFlags_get));break}case"warpriest":{source.system.rules.push(__privateGet(this,_warpriestSetFlags,warpriestSetFlags_get));break}}}};_cloisteredClericSetFlags=new WeakSet,cloisteredClericSetFlags_get=__name2(function(){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"}}},"#cloisteredClericSetFlags"),_warpriestSetFlags=new WeakSet,warpriestSetFlags_get=__name2(function(){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"}}},"#warpriestSetFlags"),__name2(_Migration831ClericDoctrines,"Migration831ClericDoctrines"),__publicField(_Migration831ClericDoctrines,"version",.831);let Migration831ClericDoctrines=_Migration831ClericDoctrines;const _Migration832ChoiceSetFlags=class extends MigrationBase{static{__name(this,"_Migration832ChoiceSetFlags")}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}`)))}}}};__name2(_Migration832ChoiceSetFlags,"Migration832ChoiceSetFlags"),__publicField(_Migration832ChoiceSetFlags,"version",.832);let Migration832ChoiceSetFlags=_Migration832ChoiceSetFlags;const _Migration833AddRogueToysFixPrecision=class extends MigrationBase{static{__name(this,"_Migration833AddRogueToysFixPrecision")}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}}}};__name2(_Migration833AddRogueToysFixPrecision,"Migration833AddRogueToysFixPrecision"),__publicField(_Migration833AddRogueToysFixPrecision,"version",.833);let Migration833AddRogueToysFixPrecision=_Migration833AddRogueToysFixPrecision;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"]),_Migration834FeatCategories=class extends MigrationBase{static{__name(this,"_Migration834FeatCategories")}constructor(){super(...arguments),__privateAdd(this,_updateCategoryData)}async updateItem(source){source.type==="feat"&&__privateMethod(this,_updateCategoryData,updateCategoryData_fn).call(this,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"))}};_updateCategoryData=new WeakSet,updateCategoryData_fn=__name2(function(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())},"#updateCategoryData"),__name2(_Migration834FeatCategories,"Migration834FeatCategories"),__publicField(_Migration834FeatCategories,"version",.834);let Migration834FeatCategories=_Migration834FeatCategories;const _Migration835InitiativeLongform=class extends MigrationBase{static{__name(this,"_Migration835InitiativeLongform")}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}};__name2(_Migration835InitiativeLongform,"Migration835InitiativeLongform"),__publicField(_Migration835InitiativeLongform,"version",.835);let Migration835InitiativeLongform=_Migration835InitiativeLongform;const _Migration836EnergizingConsolidation=class extends MigrationBase{static{__name(this,"_Migration836EnergizingConsolidation")}constructor(){super(...arguments),__privateAdd(this,_rename2)}async updateItem(source){source.system.description.value.includes("equipment-effects")&&(source.system.description.value=__privateMethod(this,_rename2,rename_fn2).call(this,source.system.description.value))}};_rename2=new WeakSet,rename_fn2=__name2(function(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)},"#rename"),__name2(_Migration836EnergizingConsolidation,"Migration836EnergizingConsolidation"),__publicField(_Migration836EnergizingConsolidation,"version",.836);let Migration836EnergizingConsolidation=_Migration836EnergizingConsolidation;const _Migration837MoveHazardBookSources=class extends MigrationBase{static{__name(this,"_Migration837MoveHazardBookSources")}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}}};__name2(_Migration837MoveHazardBookSources,"Migration837MoveHazardBookSources"),__publicField(_Migration837MoveHazardBookSources,"version",.837);let Migration837MoveHazardBookSources=_Migration837MoveHazardBookSources;const _Migration838StrikeAttackRollSelector=class extends MigrationBase{static{__name(this,"_Migration838StrikeAttackRollSelector")}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)))}};__name2(_Migration838StrikeAttackRollSelector,"Migration838StrikeAttackRollSelector"),__publicField(_Migration838StrikeAttackRollSelector,"version",.838);let Migration838StrikeAttackRollSelector=_Migration838StrikeAttackRollSelector;const _Migration839ActionCategories=class extends MigrationBase{static{__name(this,"_Migration839ActionCategories")}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}}};__name2(_Migration839ActionCategories,"Migration839ActionCategories"),__publicField(_Migration839ActionCategories,"version",.839);let Migration839ActionCategories=_Migration839ActionCategories;const _Migration840ArrayWrapPredicates=class extends MigrationBase{static{__name(this,"_Migration840ArrayWrapPredicates")}constructor(){super(...arguments),__privateAdd(this,_wrapPredicate)}async updateItem(source){for(const rule of source.system.rules)"predicate"in rule&&(rule.predicate=__privateMethod(this,_wrapPredicate,wrapPredicate_fn).call(this,rule.predicate)),"definition"in rule&&(rule.definition=__privateMethod(this,_wrapPredicate,wrapPredicate_fn).call(this,rule.definition))}};_wrapPredicate=new WeakSet,wrapPredicate_fn=__name2(function(predicate){if(Array.isArray(predicate))return predicate;const arrayWrapped=[predicate];return predicate&&PredicatePF2e.isValid(arrayWrapped)?arrayWrapped:void 0},"#wrapPredicate"),__name2(_Migration840ArrayWrapPredicates,"Migration840ArrayWrapPredicates"),__publicField(_Migration840ArrayWrapPredicates,"version",.84);let Migration840ArrayWrapPredicates=_Migration840ArrayWrapPredicates;const _Migration841V11UUIDFormat=class extends MigrationBase{static{__name(this,"_Migration841V11UUIDFormat")}constructor(){super(...arguments),__privateAdd(this,_replaceUUID),__privateAdd(this,_replaceUUIDsInLinks)}async updateActor(source){if(source.flags.core?.sourceId&&(source.flags.core.sourceId=__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,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=__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,formula.uuid,"Item")}else if(source.type==="npc"){const{details}=source.system;details.publicNotes&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,details.publicNotes),details.privateNotes&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,details.privateNotes)}else if(source.type==="hazard"){const{details}=source.system;details.reset&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,details.reset),details.description&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,details.description),details.routine&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,details.routine),details.disable&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,details.disable)}}async updateItem(source){if(source.flags.core?.sourceId&&(source.flags.core.sourceId=__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,source.flags.core.sourceId,"Item")),source.system.rules=source.system.rules.map(rule=>("text"in rule&&typeof rule.text=="string"&&(rule.text=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,rule.text)),recursiveReplaceString(rule,s=>__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,s,"Item")))),itemIsOfType(source,"ancestry","background","class","kit")){const items=source.system.items;for(const entry of Object.values(items))if(entry.uuid=__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,entry.uuid,"Item"),isObject(entry.items))for(const subentry of Object.values(entry.items))subentry.uuid=__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,subentry.uuid,"Item")}else if(source.type==="heritage")source.system.ancestry?.uuid&&(source.system.ancestry.uuid=__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,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)]=__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,spell);const{description}=source.system;description.value??="",description.value=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,description.value),description.value=description.value.replace(/Compendium\.pf2e\.journals\.(?!JournalEntry)/g,"Compendium.pf2e.journals.JournalEntry."),description.gm&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,description.gm)}async updateJournalEntry(source){for(const page of source.pages)page.text.content&&=__privateMethod(this,_replaceUUIDsInLinks,replaceUUIDsInLinks_fn).call(this,page.text.content)}};_replaceUUID=new WeakSet,replaceUUID_fn=__name2(function(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}`},"#replaceUUID"),_replaceUUIDsInLinks=new WeakSet,replaceUUIDsInLinks_fn=__name2(function(text){return typeof text!="string"?text:Array.from(text.matchAll(/(?<=@UUID\[)[^\]]+(?=\])/g)).reduce((replaced,[link])=>replaced.replace(link,s=>__privateMethod(this,_replaceUUID,replaceUUID_fn).call(this,s)),text)},"#replaceUUIDsInLinks"),__name2(_Migration841V11UUIDFormat,"Migration841V11UUIDFormat"),__publicField(_Migration841V11UUIDFormat,"version",.841);let Migration841V11UUIDFormat=_Migration841V11UUIDFormat;const _Migration842NumifyNumericSettings=class extends MigrationBase{static{__name(this,"_Migration842NumifyNumericSettings")}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))}}};__name2(_Migration842NumifyNumericSettings,"Migration842NumifyNumericSettings"),__publicField(_Migration842NumifyNumericSettings,"version",.842);let Migration842NumifyNumericSettings=_Migration842NumifyNumericSettings;const _Migration843RMArmorCustomModifiers=class extends MigrationBase{static{__name(this,"_Migration843RMArmorCustomModifiers")}async updateActor(source){if(source.type==="character"&&source.system.customModifiers?.armor){const customModifiers=source.system.customModifiers;customModifiers["-=armor"]=null}}};__name2(_Migration843RMArmorCustomModifiers,"Migration843RMArmorCustomModifiers"),__publicField(_Migration843RMArmorCustomModifiers,"version",.843);let Migration843RMArmorCustomModifiers=_Migration843RMArmorCustomModifiers;const _Migration844DeityDomainUUIDs=class extends MigrationBase{static{__name(this,"_Migration844DeityDomainUUIDs")}constructor(){super(...arguments),__privateAdd(this,_updateUUIDs),__privateAdd(this,_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"}])}async updateActor(source){source.type==="npc"&&(source.system.details.publicNotes&&=__privateMethod(this,_updateUUIDs,updateUUIDs_fn).call(this,source.system.details.publicNotes))}async updateItem(source){source.system.description.gm&&=__privateMethod(this,_updateUUIDs,updateUUIDs_fn).call(this,source.system.description.gm),source.system.description.value&&=__privateMethod(this,_updateUUIDs,updateUUIDs_fn).call(this,source.system.description.value)}};_updateUUIDs=new WeakSet,updateUUIDs_fn=__name2(function(text){return __privateGet(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)},"#updateUUIDs"),_idMap=new WeakMap,__name2(_Migration844DeityDomainUUIDs,"Migration844DeityDomainUUIDs"),__publicField(_Migration844DeityDomainUUIDs,"version",.844);let Migration844DeityDomainUUIDs=_Migration844DeityDomainUUIDs;const _Migration845EmptySpellConsumables=class extends MigrationBase{static{__name(this,"_Migration845EmptySpellConsumables")}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)}}};__name2(_Migration845EmptySpellConsumables,"Migration845EmptySpellConsumables"),__publicField(_Migration845EmptySpellConsumables,"version",.845);let Migration845EmptySpellConsumables=_Migration845EmptySpellConsumables;const _Migration846SpellSchoolOptional=class extends MigrationBase{static{__name(this,"_Migration846SpellSchoolOptional")}async updateItem(source){if(source.type!=="spell")return;const system=source.system;system.school&&(source.system.traits.value=uniq(compact([...source.system.traits.value,system.school.value])),system["-=school"]=null,delete system.school)}};__name2(_Migration846SpellSchoolOptional,"Migration846SpellSchoolOptional"),__publicField(_Migration846SpellSchoolOptional,"version",.846);let Migration846SpellSchoolOptional=_Migration846SpellSchoolOptional;const _Migration847TempHPRuleEvents=class extends MigrationBase{static{__name(this,"_Migration847TempHPRuleEvents")}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)}};__name2(_Migration847TempHPRuleEvents,"Migration847TempHPRuleEvents"),__publicField(_Migration847TempHPRuleEvents,"version",.847);let Migration847TempHPRuleEvents=_Migration847TempHPRuleEvents;const _Migration848NumericArmorProperties=class extends MigrationBase{static{__name(this,"_Migration848NumericArmorProperties")}constructor(){super(...arguments),__privateAdd(this,_oldToNew,[["armor","acBonus"],["dex","dexCap"],["check","checkPenalty"],["speed","speedPenalty"],["strength","strength"]])}async updateItem(source){if(source.type==="armor")for(const[oldKey,newKey]of __privateGet(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)||null,source.system[`-=${oldKey}`]=null):(source.system[newKey]=Number(oldProperty.value)||0,source.system[`-=${oldKey}`]=null)}}};_oldToNew=new WeakMap,__name2(_Migration848NumericArmorProperties,"Migration848NumericArmorProperties"),__publicField(_Migration848NumericArmorProperties,"version",.848);let Migration848NumericArmorProperties=_Migration848NumericArmorProperties;const _Migration849DeleteBrokenThreshold=class extends MigrationBase{static{__name(this,"_Migration849DeleteBrokenThreshold")}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)}};__name2(_Migration849DeleteBrokenThreshold,"Migration849DeleteBrokenThreshold"),__publicField(_Migration849DeleteBrokenThreshold,"version",.849);let Migration849DeleteBrokenThreshold=_Migration849DeleteBrokenThreshold;const _Migration850FlatFootedToOffGuard=class extends MigrationBase{static{__name(this,"_Migration850FlatFootedToOffGuard")}constructor(){super(...arguments),__privateAdd(this,_replace),__privateAdd(this,_oldNamePattern,new RegExp(/\bFlat-Footed\b/g)),__privateAdd(this,_newName,"Off-Guard"),__privateAdd(this,_imgPattern,/(?<=systems\/pf2e\/icons\/conditions(?:-2)?\/)flat-?footed.webp$/i),__privateAdd(this,_aToAnUUIDPatern,/\ba(?= @UUID\[Compendium\.pf2e\.conditionitems\.Item\.(?:Flat-Footed|AJh5ex99aV6VTggg)\])/g)}async updateActor(source){source.type==="hazard"&&(source.system.details.routine&&=__privateMethod(this,_replace,replace_fn).call(this,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=>__privateMethod(this,_replace,replace_fn).call(this,s)))}async updateItem(source){source.name=source.name.replace(__privateGet(this,_oldNamePattern),__privateGet(this,_newName)),source.img=source.img.replace(__privateGet(this,_imgPattern),"off-guard.webp"),source.system=recursiveReplaceString(source.system,s=>__privateMethod(this,_replace,replace_fn).call(this,s))}async updateJournalEntry(source){source.name!=="Remaster Changes"&&(source.name=source.name.replace(__privateGet(this,_oldNamePattern),__privateGet(this,_newName)),"img"in source&&typeof source.img=="string"&&(source.img=source.img.replace(__privateGet(this,_imgPattern),"off-guard.webp")),source.pages=recursiveReplaceString(source.pages,s=>__privateMethod(this,_replace,replace_fn).call(this,s)),"content"in source&&typeof source.content=="string"&&(source.content=__privateMethod(this,_replace,replace_fn).call(this,source.content)))}};_oldNamePattern=new WeakMap,_newName=new WeakMap,_imgPattern=new WeakMap,_aToAnUUIDPatern=new WeakMap,_replace=new WeakSet,replace_fn=__name2(function(text){return text.replace(__privateGet(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(__privateGet(this,_oldNamePattern),"Off-Guard").replace(/\bflatfooted\b/g,"flat-footed").replace(/\ba flat-footed\b/g,"an off-guard").replace(__privateGet(this,_aToAnUUIDPatern),"an").replace(/\bFlat-footed\b/g,"Off-guard").replace(/\bflat-footed\b/g,"off-guard")},"#replace"),__name2(_Migration850FlatFootedToOffGuard,"Migration850FlatFootedToOffGuard"),__publicField(_Migration850FlatFootedToOffGuard,"version",.85);let Migration850FlatFootedToOffGuard=_Migration850FlatFootedToOffGuard;const _Migration851JustInnovationId=class extends MigrationBase{static{__name(this,"_Migration851JustInnovationId")}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)}}};__name2(_Migration851JustInnovationId,"Migration851JustInnovationId"),__publicField(_Migration851JustInnovationId,"version",.851);let Migration851JustInnovationId=_Migration851JustInnovationId;const _Migration852AbilityScoresToModifiers=class extends MigrationBase{static{__name(this,"_Migration852AbilityScoresToModifiers")}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)}}};__name2(_Migration852AbilityScoresToModifiers,"Migration852AbilityScoresToModifiers"),__publicField(_Migration852AbilityScoresToModifiers,"version",.852);let Migration852AbilityScoresToModifiers=_Migration852AbilityScoresToModifiers;const _Migration853RemasterLanguages=class extends MigrationBase{static{__name(this,"_Migration853RemasterLanguages")}constructor(){super(...arguments),__privateAdd(this,_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=>__privateGet(this,_OLD_TO_NEW_LANGUAGES).get(l)??l).sort())}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>__privateGet(this,_OLD_TO_NEW_LANGUAGES).get(s)??s),source.type==="ancestry"&&Array.isArray(source.system.additionalLanguages?.value)&&source.system.additionalLanguages.value.sort()}};_OLD_TO_NEW_LANGUAGES=new WeakMap,__name2(_Migration853RemasterLanguages,"Migration853RemasterLanguages"),__publicField(_Migration853RemasterLanguages,"version",.853);let Migration853RemasterLanguages=_Migration853RemasterLanguages;const _Migration854BracketedAbilityScoresToModifiers=class extends MigrationBase{static{__name(this,"_Migration854BracketedAbilityScoresToModifiers")}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}}};__name2(_Migration854BracketedAbilityScoresToModifiers,"Migration854BracketedAbilityScoresToModifiers"),__publicField(_Migration854BracketedAbilityScoresToModifiers,"version",.854);let Migration854BracketedAbilityScoresToModifiers=_Migration854BracketedAbilityScoresToModifiers;const _Migration855ApexEquipmentSystemData=class extends MigrationBase{static{__name(this,"_Migration855ApexEquipmentSystemData")}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)))}};__name2(_Migration855ApexEquipmentSystemData,"Migration855ApexEquipmentSystemData"),__publicField(_Migration855ApexEquipmentSystemData,"version",.855);let Migration855ApexEquipmentSystemData=_Migration855ApexEquipmentSystemData;const _Migration856NoSystemDotCustom=class extends MigrationBase{static{__name(this,"_Migration856NoSystemDotCustom")}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"})}`)))}};__name2(_Migration856NoSystemDotCustom,"Migration856NoSystemDotCustom"),__publicField(_Migration856NoSystemDotCustom,"version",.856);let Migration856NoSystemDotCustom=_Migration856NoSystemDotCustom;const _Migration857WeaponSpecializationRE=class extends MigrationBase{static{__name(this,"_Migration857WeaponSpecializationRE")}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}))}};__name2(_Migration857WeaponSpecializationRE,"Migration857WeaponSpecializationRE"),__publicField(_Migration857WeaponSpecializationRE,"version",.857);let Migration857WeaponSpecializationRE=_Migration857WeaponSpecializationRE;const _Migration858FakeWeaponSpecialization=class extends MigrationBase{static{__name(this,"_Migration858FakeWeaponSpecialization")}constructor(){super(...arguments),__privateAdd(this,_testHasOption)}async updateItem(source){if(source.type!=="feat")return;const slug=source.system.slug??sluggify(source.name);slug==="greater-weapon-specialization-barbarian"&&!__privateMethod(this,_testHasOption,testHasOption_fn).call(this,source)?source.system.rules.push({domain:"all",key:"RollOption",option:"feature:greater-weapon-specialization"}):slug==="psychic-weapon-specialization"&&!__privateMethod(this,_testHasOption,testHasOption_fn).call(this,source)&&source.system.rules.push({domain:"all",key:"RollOption",option:"feature:weapon-specialization"})}};_testHasOption=new WeakSet,testHasOption_fn=__name2(function(source){return source.system.rules.some(r=>r.key==="RollOption"&&"option"in r&&["feature:greater-weapon-specialization","feature:weapon-specialization"].includes(String(r.option)))},"#testHasOption"),__name2(_Migration858FakeWeaponSpecialization,"Migration858FakeWeaponSpecialization"),__publicField(_Migration858FakeWeaponSpecialization,"version",.858);let Migration858FakeWeaponSpecialization=_Migration858FakeWeaponSpecialization;const _Migration859MaterialTypeGrade=class extends MigrationBase{static{__name(this,"_Migration859MaterialTypeGrade")}constructor(){super(...arguments),__privateAdd(this,_hasOldMaterialData)}async updateItem(source){if(itemIsOfType(source,"physical")&&__privateMethod(this,_hasOldMaterialData,hasOldMaterialData_fn).call(this,source)){const{preciousMaterial,preciousMaterialGrade}=source.system,type=setHasElement(PRECIOUS_MATERIAL_TYPES,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)}}};_hasOldMaterialData=new WeakSet,hasOldMaterialData_fn=__name2(function(source){return"preciousMaterial"in source.system&&isObject(source.system.preciousMaterial)&&"preciousMaterialGrade"in source.system&&isObject(source.system.preciousMaterialGrade)},"#hasOldMaterialData"),__name2(_Migration859MaterialTypeGrade,"Migration859MaterialTypeGrade"),__publicField(_Migration859MaterialTypeGrade,"version",.859);let Migration859MaterialTypeGrade=_Migration859MaterialTypeGrade;const _Migration860RMGroup=class extends MigrationBase{static{__name(this,"_Migration860RMGroup")}async updateItem(source){itemIsOfType(source,"armor","condition","weapon")||!("group"in source.system)||("game"in globalThis?source.system["-=group"]=null:delete source.system.group)}};__name2(_Migration860RMGroup,"Migration860RMGroup"),__publicField(_Migration860RMGroup,"version",.86);let Migration860RMGroup=_Migration860RMGroup;const _Migration861AuraColorsToAppearance=class extends MigrationBase{static{__name(this,"_Migration861AuraColorsToAppearance")}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}};__name2(_Migration861AuraColorsToAppearance,"Migration861AuraColorsToAppearance"),__publicField(_Migration861AuraColorsToAppearance,"version",.861);let Migration861AuraColorsToAppearance=_Migration861AuraColorsToAppearance;const _Migration862SpecificMagicArmor=class extends MigrationBase{static{__name(this,"_Migration862SpecificMagicArmor")}constructor(){super(...arguments),__privateAdd(this,_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=!!(source.system.potencyRune.value||source.system.resiliencyRune.value),hasBaseAndSlug=!!(source.system.baseItem&&source.system.slug);isMagical&&hasBaseAndSlug&&source.system.baseItem!==source.system.slug&&(source.system.specific??={value:!0,material:source.system.material??null,runes:{potency:source.system.potencyRune?.value||1,resilient:__privateGet(this,_resilientRuneValues).get(source.system.resiliencyRune?.value??"")||0}})}};_resilientRuneValues=new WeakMap,__name2(_Migration862SpecificMagicArmor,"Migration862SpecificMagicArmor"),__publicField(_Migration862SpecificMagicArmor,"version",.862);let Migration862SpecificMagicArmor=_Migration862SpecificMagicArmor;const _Migration863FixMisspelledOrganaizationsProperty=class extends MigrationBase{static{__name(this,"_Migration863FixMisspelledOrganaizationsProperty")}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)}};__name2(_Migration863FixMisspelledOrganaizationsProperty,"Migration863FixMisspelledOrganaizationsProperty"),__publicField(_Migration863FixMisspelledOrganaizationsProperty,"version",.863);let Migration863FixMisspelledOrganaizationsProperty=_Migration863FixMisspelledOrganaizationsProperty;const _Migration864RemoveWeaponMAP=class extends MigrationBase{static{__name(this,"_Migration864RemoveWeaponMAP")}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}}};__name2(_Migration864RemoveWeaponMAP,"Migration864RemoveWeaponMAP"),__publicField(_Migration864RemoveWeaponMAP,"version",.864);let Migration864RemoveWeaponMAP=_Migration864RemoveWeaponMAP;const _Migration865VitalityVoid=class extends MigrationBase{static{__name(this,"_Migration865VitalityVoid")}constructor(){super(...arguments),__privateAdd(this,_replaceStrings)}async updateActor(source){source.system=__privateMethod(this,_replaceStrings,replaceStrings_fn).call(this,source.system),source.flags=__privateMethod(this,_replaceStrings,replaceStrings_fn).call(this,source.flags)}async updateItem(source){source.system=__privateMethod(this,_replaceStrings,replaceStrings_fn).call(this,source.system),source.flags=__privateMethod(this,_replaceStrings,replaceStrings_fn).call(this,source.flags)}};_replaceStrings=new WeakSet,replaceStrings_fn=__name2(function(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"))},"#replaceStrings"),__name2(_Migration865VitalityVoid,"Migration865VitalityVoid"),__publicField(_Migration865VitalityVoid,"version",.865);let Migration865VitalityVoid=_Migration865VitalityVoid;const _Migration866LinkToActorSizeAgain=class extends MigrationBase{static{__name(this,"_Migration866LinkToActorSizeAgain")}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)||mergeObject(tokenSource.flags,{pf2e:{linkToActorSize:!1,autoscale:!1}})}};__name2(_Migration866LinkToActorSizeAgain,"Migration866LinkToActorSizeAgain"),__publicField(_Migration866LinkToActorSizeAgain,"version",.866);let Migration866LinkToActorSizeAgain=_Migration866LinkToActorSizeAgain;const _Migration867DamageRollDomainFix=class extends MigrationBase{static{__name(this,"_Migration867DamageRollDomainFix")}async updateItem(source){for(const rule of source.system.rules??[])"domain"in rule&&rule.domain==="damage-roll"&&(rule.domain="damage")}};__name2(_Migration867DamageRollDomainFix,"Migration867DamageRollDomainFix"),__publicField(_Migration867DamageRollDomainFix,"version",.867);let Migration867DamageRollDomainFix=_Migration867DamageRollDomainFix;const _Migration868StrikeRERange=class extends MigrationBase{static{__name(this,"_Migration868StrikeRERange")}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}};__name2(_Migration868StrikeRERange,"Migration868StrikeRERange"),__publicField(_Migration868StrikeRERange,"version",.868);let Migration868StrikeRERange=_Migration868StrikeRERange;const _Migration869RefreshMightyBulwark=class extends MigrationBase{static{__name(this,"_Migration869RefreshMightyBulwark")}constructor(){super(...arguments),__privateAdd(this,_mightyBulwarkRules)}async updateItem(source){if(source.type==="feat"&&source.system.slug==="mighty-bulwark")source.system.rules=__privateGet(this,_mightyBulwarkRules,mightyBulwarkRules_get);else for(const rule of source.system.rules)"option"in rule&&rule.option==="self:armor:strength-requirement-met"&&(rule.option="armor:strength-requirement-met")}};_mightyBulwarkRules=new WeakSet,mightyBulwarkRules_get=__name2(function(){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}]},"#mightyBulwarkRules"),__name2(_Migration869RefreshMightyBulwark,"Migration869RefreshMightyBulwark"),__publicField(_Migration869RefreshMightyBulwark,"version",.869);let Migration869RefreshMightyBulwark=_Migration869RefreshMightyBulwark;const _Migration870MartialToProficiencies=class extends MigrationBase{static{__name(this,"_Migration870MartialToProficiencies")}constructor(){super(...arguments),__privateAdd(this,_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=__privateGet(this,_defensePathPattern).test(text)?"defenses":"attacks";return text.replace(/\bsystem\.martial\./g,`system.proficiencies.${key}.`)}))}};_defensePathPattern=new WeakMap,__name2(_Migration870MartialToProficiencies,"Migration870MartialToProficiencies"),__publicField(_Migration870MartialToProficiencies,"version",.87);let Migration870MartialToProficiencies=_Migration870MartialToProficiencies;const _Migration871MigrateRollActionMacroParams=class extends MigrationBase{static{__name(this,"_Migration871MigrateRollActionMacroParams")}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}" })`)}}};__name2(_Migration871MigrateRollActionMacroParams,"Migration871MigrateRollActionMacroParams"),__publicField(_Migration871MigrateRollActionMacroParams,"version",.871);let Migration871MigrateRollActionMacroParams=_Migration871MigrateRollActionMacroParams;const _Migration872MoveSchemaProperty=class extends MigrationBase{static{__name(this,"_Migration872MoveSchemaProperty")}constructor(){super(...arguments),__privateAdd(this,_mvSchema)}async updateActor(source){__privateMethod(this,_mvSchema,mvSchema_fn).call(this,source.system)}async updateItem(source){__privateMethod(this,_mvSchema,mvSchema_fn).call(this,source.system)}};_mvSchema=new WeakSet,mvSchema_fn=__name2(function(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))},"#mvSchema"),__name2(_Migration872MoveSchemaProperty,"Migration872MoveSchemaProperty"),__publicField(_Migration872MoveSchemaProperty,"version",.872);let Migration872MoveSchemaProperty=_Migration872MoveSchemaProperty;const _Migration873RemoveBonusBulkLimit=class extends MigrationBase{static{__name(this,"_Migration873RemoveBonusBulkLimit")}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"))}};__name2(_Migration873RemoveBonusBulkLimit,"Migration873RemoveBonusBulkLimit"),__publicField(_Migration873RemoveBonusBulkLimit,"version",.873);let Migration873RemoveBonusBulkLimit=_Migration873RemoveBonusBulkLimit;const _Migration874MoveStaminaStuff=class extends MigrationBase{static{__name(this,"_Migration874MoveStaminaStuff")}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)}};__name2(_Migration874MoveStaminaStuff,"Migration874MoveStaminaStuff"),__publicField(_Migration874MoveStaminaStuff,"version",.874);let Migration874MoveStaminaStuff=_Migration874MoveStaminaStuff;const _Migration875SetInnovationIdEarly=class extends MigrationBase{static{__name(this,"_Migration875SetInnovationIdEarly")}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)}};__name2(_Migration875SetInnovationIdEarly,"Migration875SetInnovationIdEarly"),__publicField(_Migration875SetInnovationIdEarly,"version",.875);let Migration875SetInnovationIdEarly=_Migration875SetInnovationIdEarly;const _Migration876FeatLevelTaken=class extends MigrationBase{static{__name(this,"_Migration876FeatLevelTaken")}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()}};__name2(_Migration876FeatLevelTaken,"Migration876FeatLevelTaken"),__publicField(_Migration876FeatLevelTaken,"version",.876);let Migration876FeatLevelTaken=_Migration876FeatLevelTaken;const _Migration877PublicationData=class extends MigrationBase{static{__name(this,"_Migration877PublicationData")}constructor(){super(...arguments),__privateAdd(this,_setPublicationData)}async updateActor(source){source.type!=="hazard"&&source.type!=="npc"&&source.type!=="vehicle"||(source.type==="vehicle"&&isObject$1(source.system.source)?(__privateMethod(this,_setPublicationData,setPublicationData_fn).call(this,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)&&(__privateMethod(this,_setPublicationData,setPublicationData_fn).call(this,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)?(__privateMethod(this,_setPublicationData,setPublicationData_fn).call(this,source.system,source.system.source),"game"in globalThis?source.system["-=source"]=null:delete source.system.source):!source.system.publication&&!("game"in globalThis)&&__privateMethod(this,_setPublicationData,setPublicationData_fn).call(this,source.system,{})}};_setPublicationData=new WeakSet,setPublicationData_fn=__name2(function(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},"#setPublicationData"),__name2(_Migration877PublicationData,"Migration877PublicationData"),__publicField(_Migration877PublicationData,"version",.877);let Migration877PublicationData=_Migration877PublicationData;const _Migration878TakeABreather=class extends MigrationBase{static{__name(this,"_Migration878TakeABreather")}async updateMacro(source){source.type==="script"&&source.command.includes("console.log(resolve, sp)")&&(source.command="game.pf2e.actions.takeABreather();")}};__name2(_Migration878TakeABreather,"Migration878TakeABreather"),__publicField(_Migration878TakeABreather,"version",.878);let Migration878TakeABreather=_Migration878TakeABreather;const Migrations=Object.freeze(Object.defineProperty({__proto__:null,Migration600Reach,Migration601SplitEffectCompendia,Migration602UpdateDiehardFeat,Migration603ResetQuickRollDefault,Migration604FixClassItem,Migration605CatchUpToTemplateJSON,Migration606SignatureSpells,Migration607MeleeItemDamageRolls,Migration608DeletePersistedKits,Migration609LootActorTraits,Migration610SetHeritageFeatType,Migration611UpdateToughnessMountainsStoutness,Migration612NormalizeRarities,Migration613RemoveAmmoCharges,Migration614NumifyMeleeBonuses,Migration615RemoveInstinctTrait,Migration616MigrateFeatPrerequisites,Migration617FixUserFlags,Migration618MigrateItemImagePaths,Migration619TraditionLowercaseAndRemoveWandScroll,Migration620RenameToWebp,Migration621RemoveConfigSpellSchools,Migration623NumifyPotencyRunes,Migration624RemoveTokenEffectIconFlags,Migration625EnsurePresenceOfSaves,Migration626UpdateSpellCategory,Migration627LowerCaseSpellSaves,Migration629SetBaseItems,Migration630FixTalismanSpelling,Migration631FixSenseRuleElementSelector,Migration632DeleteOrphanedSpells,Migration633DeleteUnidentifiedTraits,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},Symbol.toStringTag,{value:"Module"})),_MigrationList=class{static{__name(this,"_MigrationList")}static get latestVersion(){return Math.max(...__privateGet(this,_list).map(M=>M.version))}static constructAll(){return __privateGet(this,_list).map(M=>new M)}static constructFromVersion(version){const minVersion=Number(version)||MigrationRunner.RECOMMENDED_SAFE_VERSION;return __privateGet(this,_list).filter(M=>M.version>minVersion).map(M=>new M)}static constructRange(min,max=1/0){return __privateGet(this,_list).filter(M=>M.version>=min&&M.version<=max).map(M=>new M)}};_list=new WeakMap,__name2(_MigrationList,"MigrationList"),__privateAdd(_MigrationList,_list,Object.values(Migrations));let MigrationList=_MigrationList;const _WeaponDamagePF2e=class _WeaponDamagePF2e2{static{__name(this,"_WeaponDamagePF2e")}static async fromNPCAttack({attack,actor,actionTraits:actionTraits2=[],context}){const secondaryInstances=Object.values(attack.system.damageRolls).slice(1).map(this.npcDamageToWeaponDamage),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 _WeaponDamagePF2e2.calculate({weapon:attack,actor,damageDice,modifiers,actionTraits:actionTraits2,context})}static async calculate({weapon,actor,damageDice=[],modifiers=[],actionTraits:actionTraits2=[],weaponPotency=null,context}){var _a;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","npc")){const strengthModValue=actor.abilities.str.mod,modifierValue=__privateMethod(_a=_WeaponDamagePF2e2,_strengthModToDamage2,strengthModToDamage_fn2).call(_a,weapon,domains.includes("str-damage"))?strengthModValue:weaponTraits2.some(t=>t==="propulsive")?strengthModValue<0?strengthModValue:Math.floor(strengthModValue/2):null;if(weapon.isOfType("weapon")&&typeof modifierValue=="number"){const strModifier=new ModifierPF2e({slug:"str",label:CONFIG.PF2E.abilities.str,ability:"str",modifier:modifierValue,type:"ability",adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"str")});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.isOfType("weapon")?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),extractedAdjustments=extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,modifier.slug);modifier.adjustments.push(...propRuneAdjustments,...extractedAdjustments)}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,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;__privateMethod(this,_excludeDamage,excludeDamage_fn).call(this,{actor,weapon:excludeFrom,modifiers:[...modifiers,...damageDice],options});const computedFormulas={criticalFailure:null,failure:__privateMethod(this,_finalizeDamage,finalizeDamage_fn).call(this,formulaData,DEGREE_OF_SUCCESS.FAILURE),success:__privateMethod(this,_finalizeDamage,finalizeDamage_fn).call(this,formulaData,DEGREE_OF_SUCCESS.SUCCESS),criticalSuccess:__privateMethod(this,_finalizeDamage,finalizeDamage_fn).call(this,formulaData,DEGREE_OF_SUCCESS.CRITICAL_SUCCESS)};return{name:`${game.i18n.localize("PF2E.DamageRoll")}: ${weapon.name}`,traits:(actionTraits2??[]).map(t=>t.name),materials:Array.from(materials),modifiers:[...modifiers,...damageDice],damage:{...formulaData,formula:mapValues(computedFormulas,formula=>formula?.formula??null),breakdown:mapValues(computedFormulas,formula=>formula?.breakdown??[])}}}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}}};_finalizeDamage=new WeakSet,finalizeDamage_fn=__name2(function(damage,degree){damage=deepClone(damage);for(const base of damage.base){const critical=degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS,outcomeMatches=__name2(m=>m.critical===null||critical&&m.critical||!critical&&!m.critical,"outcomeMatches"),hasUpgrade=damage.dice.some(d=>d.enabled&&d.override?.upgrade&&outcomeMatches(d)),hasDowngrade=damage.dice.some(d=>d.enabled&&d.override?.downgrade&&(critical||!d.critical));base.dieSize&&hasUpgrade&&!hasDowngrade?base.dieSize=nextDamageDieSize({upgrade:base.dieSize}):base.dieSize&&hasDowngrade&&!hasUpgrade&&(base.dieSize=nextDamageDieSize({downgrade:base.dieSize}));const damageOverrides=damage.dice.filter(d=>!!(d.enabled&&d.override));for(const override of damageOverrides)if(critical&&override.critical!==!1||!critical&&!override.critical){base.dieSize=override.override?.dieSize??base.dieSize,base.damageType=override.override?.damageType??base.damageType,base.diceNumber=override.override?.diceNumber??base.diceNumber;for(const die of damage.dice.filter(d=>/^(?:deadly|fatal)-/.test(d.slug)))die.damageType=override.override?.damageType??die.damageType}}return createDamageFormula(damage,degree)},"#finalizeDamage"),_excludeDamage=new WeakSet,excludeDamage_fn=__name2(function({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)},"#excludeDamage"),_strengthModToDamage2=new WeakSet,strengthModToDamage_fn2=__name2(function(weapon,strengthBased){return weapon.isOfType("weapon")&&strengthBased&&!weapon.traits.has("propulsive")},"#strengthModToDamage"),__privateAdd(_WeaponDamagePF2e,_finalizeDamage),__privateAdd(_WeaponDamagePF2e,_excludeDamage),__privateAdd(_WeaponDamagePF2e,_strengthModToDamage2),__name2(_WeaponDamagePF2e,"WeaponDamagePF2e");let WeaponDamagePF2e=_WeaponDamagePF2e;async function resetActors(actors,{rerender=!0}={}){actors??=[game.actors.contents,game.scenes.contents.flatMap(s=>s.tokens.contents).flatMap(t=>t.actor??[])].flat();for(const actor of actors)actor.reset(),rerender&&actor.render();if(game.pf2e.effectPanel.refresh(),game.settings.get("pf2e","automation.effectExpiration")&&!game.settings.get("pf2e","automation.removeExpiredEffects")){const scenes=new Set(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)}}__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=deepClone(game.settings.get("core","defaultToken")),actor=new ActorProxyPF2e(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){if(!target?.isOfType("creature"))return!1;const{flanking}=target.attributes;return flanking.flankable?typeof flanking.offGuardable=="number"?origin.level>flanking.offGuardable:flanking.offGuardable:!1}__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]}-damage`)}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(),attributeModifier=[defaultAttributeModifier,...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).sort()}__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).sort()}__name(getStrikeDamageDomains,"getStrikeDamageDomains"),__name2(getStrikeDamageDomains,"getStrikeDamageDomains");function strikeFromMeleeItem(item){const{actor,isMelee,isThrown}=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([isThrown?"thrown":null,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 notes=extractNotes(synthetics.rollNotes,domains),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),traitObjects=item.system.traits.value.map(t=>({name:t,label:CONFIG.PF2E.npcAttackTraits[t]??t,description:CONFIG.PF2E.traitsDescriptions[t]})),strike=mergeObject(statistic,{label:item.name,type:"strike",glyph:getActionGlyph({type:"action",value:1}),description:item.description,imageUrl:getActionIcon({type:"action",value:1}),sourceId:item.id,attackRollType:item.isRanged?"PF2E.NPCAttackRanged":"PF2E.NPCAttackMelee",additionalEffects,item,weapon:item,traits:traitObjects,options:Array.from(baseOptions),variants:[],ready:!0,success:"",criticalSuccess:""});strike.breakdown=strike.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${signedInteger(m.value)}`).join(", ");const attackTrait={name:"attack",label:CONFIG.PF2E.featTraits.attack,description:CONFIG.PF2E.traitsDescriptions.attack},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={})=>{const attackEffects2=actor.isOfType("npc")?await actor.getAttackEffects(item):[],rollNotes=notes.concat(attackEffects2);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])});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}),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:item.dealsDamage,domains,options:context.options,traits:[attackTrait],notes:rollNotes,dc:params.dc??context.dc,mapIncreases,rollTwice:extractRollTwice(synthetics.rollTwice,domains,context.options),substitutions:extractRollSubstitutions(synthetics.rollSubstitutions,domains,context.options),dosAdjustments:extractDegreeOfSuccessAdjustments(synthetics,domains)},roll=await CheckPF2e.roll(check,checkContext,params.event);if(roll)for(const rule of 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,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,...eventToRollParams(params.event)};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,actionTraits:[attackTrait],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");const _Statistic=class _Statistic2 extends BaseStatistic{static{__name(this,"_Statistic")}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,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),__publicField(this,"attribute",null),__publicField(this,"rank",null),__publicField(this,"proficient",!0),__publicField(this,"base",null),__publicField(this,"lore"),__publicField(this,"config"),__privateAdd(this,_check,void 0),__privateAdd(this,_dc,void 0),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 __privateGet(this,_check)??__privateSet(this,_check,new StatisticCheck(this,this.data,this.config))}get dc(){return __privateGet(this,_dc)??__privateSet(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.sort())}withRollOptions(options){const newOptions=mergeObject(this.config??{},options??{},{inplace:!1});return new _Statistic2(this.actor,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=mergeObject(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 _Statistic2(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())}}};_check=new WeakMap,_dc=new WeakMap,__name2(_Statistic,"Statistic");let Statistic=_Statistic;const _StatisticCheck=class{static{__name(this,"_StatisticCheck")}constructor(parent,data,config={}){__privateAdd(this,_determineLabel),__publicField(this,"parent"),__publicField(this,"type"),__publicField(this,"label"),__publicField(this,"domains"),__publicField(this,"mod"),__publicField(this,"modifiers"),this.parent=parent,this.type=data.check?.type??"check",data.check=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).sort(),this.domains=uniq(compact([data.domains,data.check.domains].flat())).sort(),this.label=__privateMethod(this,_determineLabel,determineLabel_fn).call(this,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}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 event=args.event?.originalEvent??args.event;if(event instanceof MouseEvent){const{rollMode:rollMode2,skipDialog:skipDialog2}=args;return mergeObject({rollMode:rollMode2,skipDialog:skipDialog2},eventToRollParams(event))}}return args})(),{actor,domains}=this,token=args.token??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("creature"))??null,rollContext=await(()=>{const isValidAttacker=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","feat","weapon"));return isValidAttacker&&isTargetedCheck?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})(),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(actor.synthetics.rollNotes,domains),...args.extraRollNotes??[]];for(const rule of actor.rules.filter(r=>!r.ignored))rule.beforeRoll?.(domains,options);const dosAdjustments=dc?extractDegreeOfSuccessAdjustments(actor.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??actor.level,amount=this.type==="saving-throw"&&actor.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"?traitSlugToObject(t,CONFIG.PF2E.actionTraits):t);for(const trait of traits??[])options.add(trait.name);const context={actor,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(actor.synthetics.rollTwice,domains,options),substitutions:extractRollSubstitutions(actor.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 actor.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(", ")}};_determineLabel=new WeakSet,determineLabel_fn=__name2(function(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}},"#determineLabel"),__name2(_StatisticCheck,"StatisticCheck");let StatisticCheck=_StatisticCheck;const _StatisticDifficultyClass=class{static{__name(this,"_StatisticDifficultyClass")}parent;domains;label;modifiers;options;constructor(parent,data,options={}){this.parent=parent,this.domains=uniq(compact([data.domains,data.dc?.domains].flat())).sort(),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)}};__name2(_StatisticDifficultyClass,"StatisticDifficultyClass");let StatisticDifficultyClass=_StatisticDifficultyClass;const _ArmorStatistic=class extends Statistic{static{__name(this,"_ArmorStatistic")}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),__privateAdd(this,_createBonusesAndPenalties),__privateAdd(this,_createShieldBonus),__publicField(this,"details"),this.details=data.details??"";const dcModifiers=[...this.dc.modifiers,...__privateMethod(this,_createBonusesAndPenalties,createBonusesAndPenalties_fn).call(this)].map(m=>m.clone());this.dc.modifiers=[...new StatisticModifier("",dcModifiers,this.dc.options).modifiers]}get item(){return this.actor.isOfType("character")?this.actor.wornArmor:null}getTraceData(){return{...super.getTraceData({value:"dc"}),details:this.details,breakdown:this.dc.breakdown}}};_createBonusesAndPenalties=new WeakSet,createBonusesAndPenalties_fn=__name2(function(){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),__privateMethod(this,_createShieldBonus,createShieldBonus_fn).call(this)])},"#createBonusesAndPenalties"),_createShieldBonus=new WeakSet,createShieldBonus_fn=__name2(function(){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},"#createShieldBonus"),__name2(_ArmorStatistic,"ArmorStatistic");let ArmorStatistic=_ArmorStatistic;const _HitPointsStatistic=class extends BaseStatistic{static{__name(this,"_HitPointsStatistic")}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}),__publicField(this,"value"),__publicField(this,"max"),__privateAdd(this,_baseMax,void 0),__publicField(this,"temp"),__publicField(this,"negativeHealing"),__publicField(this,"unrecoverable"),__publicField(this,"details"),__privateSet(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([__privateGet(this,_baseMax)>0?game.i18n.format("PF2E.MaxHitPointsBaseLabel",{base:__privateGet(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())}}};_baseMax=new WeakMap,__name2(_HitPointsStatistic,"HitPointsStatistic");let HitPointsStatistic=_HitPointsStatistic;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"},_TrickMagicItemEntry=class{static{__name(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:[],spellPrepList:null}}};__name2(_TrickMagicItemEntry,"TrickMagicItemEntry");let TrickMagicItemEntry=_TrickMagicItemEntry;const _ChatInspectRoll=class extends Application{static{__name(this,"_ChatInspectRoll")}constructor(message,options={}){super(options),__privateAdd(this,_currentFilter,""),this.message=message}static get defaultOptions(){const options=super.defaultOptions;return options.title="PF2E.ChatRollDetails.Title",options.template="systems/pf2e/templates/chat/chat-inspect-roll.hbs",options.classes=["chat-inspect-roll"],options.resizable=!0,options.width=600,options.height=420,options}getData(){const{context}=this.message.flags.pf2e,domains=context?.domains?.sort(),modifiers=this.prepareModifiers();return{context,domains,modifiers:modifiers??[],hasModifiers:!!modifiers}}prepareModifiers(){return this.message.flags.pf2e.modifiers?.map(mod=>{const value="dieSize"in mod?`+${mod.diceNumber}${mod.dieSize}`:addSign(mod.modifier??0);return{...mod,value,critical:mod.critical!==null?game.i18n.localize(`PF2E.RuleEditor.General.CriticalBehavior.${mod.critical}`):null}})??null}activateListeners($html){super.activateListeners($html);const html=$html[0];this.filterOptions(__privateGet(this,_currentFilter));const filterInput=htmlQuery(html,"input.filter");filterInput?.addEventListener("input",()=>{__privateSet(this,_currentFilter,filterInput.value?.trim()),this.filterOptions(__privateGet(this,_currentFilter))})}filterOptions(filter2){const html=this.element[0],{context}=this.message.flags.pf2e,allOptions=context?.options??[],topLevelOptions=allOptions.filter(option=>!option.includes(":")),remainingOptions=allOptions.filter(option=>option.includes(":")),rollOptions=[...topLevelOptions.sort(),...remainingOptions.sort()],filteredOptions=filter2?rollOptions.filter(r=>r.includes(filter2)):rollOptions,template=htmlQuery(html,"template.roll-option-template")?.innerHTML,content=Handlebars.compile(template)({rollOptions:filteredOptions}),destination=htmlQuery(html,".roll-option-lists");destination&&(destination.innerHTML=content)}};_currentFilter=new WeakMap,__name2(_ChatInspectRoll,"ChatInspectRoll");let ChatInspectRoll=_ChatInspectRoll;const _CriticalHitAndFumbleCards=class{static{__name(this,"_CriticalHitAndFumbleCards")}static handleDraw(message){if(message.isAuthor&&message.isContentVisible){const type=message.flags.pf2e.context?.type??"",firstDie=message.rolls.at(0)?.dice[0];firstDie&&firstDie.faces===20&&this.rollTypes.includes(type)&&(firstDie.total===20?this.automaticDraw("critTable"):firstDie.total===1&&this.automaticDraw("fumbleTable"))}}static automaticDraw(table){this.diceSoNice??=!!game.modules.get("dice-so-nice")?.active,this.diceSoNice?Hooks.once("diceSoNiceRollComplete",()=>{this.drawFromTable(table,!0)}):this.drawFromTable(table,!0)}static drawFromTable(table,automatic=!1){const tableId=table==="critTable"?"FTEpsIWWVrDj0jNG":"WzMGWMIrrPvSp75D";game.packs.get("pf2e.rollable-tables",{strict:!0}).getDocument(tableId).then(rollTable=>{rollTable.draw({displayChat:!1}).then(draw=>{const data={roll:draw.roll,messageData:{}};automatic&&!this.diceSoNice&&(data.messageData.sound=void 0),rollTable.toMessage(draw.results,data)})})}static appendButtons(message,$html){if(this.appendButtonsOption??=game.settings.get("pf2e","critFumbleButtons"),this.appendButtonsOption&&(message.isAuthor||game.user.isGM)&&message.isContentVisible){const type=message.flags.pf2e.context?.type??"";if(this.rollTypes.includes(type)){const critButton=$(``),fumbleButton=$(``),btnContainer1=$('');btnContainer1.append(critButton),btnContainer1.append(fumbleButton),critButton.on("click",event=>{event.stopPropagation(),this.drawFromTable("critTable"),event.currentTarget.blur()}),fumbleButton.on("click",event=>{event.stopPropagation(),this.drawFromTable("fumbleTable"),event.currentTarget.blur()}),$html.find(".dice-total").wrapInner('').append(btnContainer1)}}}};__name2(_CriticalHitAndFumbleCards,"CriticalHitAndFumbleCards"),__publicField(_CriticalHitAndFumbleCards,"rollTypes",["attack-roll","spell-attack-roll"]),__publicField(_CriticalHitAndFumbleCards,"diceSoNice"),__publicField(_CriticalHitAndFumbleCards,"appendButtonsOption");let CriticalHitAndFumbleCards=_CriticalHitAndFumbleCards;async function repair(options){const item=options.item??(options.uuid?await fromUuid(options.uuid):await SelectItemDialog.getItem("repair"));if(item&&!(item instanceof PhysicalItemPF2e)){ui.notifications.warn(game.i18n.format("PF2E.Actions.Repair.Warning.NotPhysicalItem",{item:item.name??""}));return}const dc=options.difficultyClass??(()=>{if(item){const proficiencyWithoutLevel=game.settings.get("pf2e","proficiencyVariant");return{label:game.i18n.format("PF2E.Actions.Repair.Labels.ItemLevelRepairDC",{level:item.level}),value:calculateDC(item.level,{proficiencyWithoutLevel}),visibility:"all"}}})(),targetItemOptions=Array.from(item?.traits??[]).map(trait=>`target:trait:${trait}`),slug=options?.skill??"crafting",rollOptions=["action:repair",...targetItemOptions],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.Repair.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),content:async title=>{if(item){const templatePath="systems/pf2e/templates/system/actions/repair/item-heading-partial.hbs",templateData={item},content=await renderTemplate(templatePath,templateData);return title+content}},traits:["exploration","manipulate"],event:options.event,difficultyClass:dc,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Repair","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Repair","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Repair","criticalFailure")],createMessage:!1,callback:async result=>{const{actor}=result;if(item&&result.message instanceof ChatMessagePF2e&&actor.isOfType("creature")){const messageSource=result.message.toObject(),flavor=await(async()=>{const proficiencyRank=actor.skills.crafting.rank??0;if(result.outcome==="criticalSuccess"){const label="PF2E.Actions.Repair.Labels.RestoreItemHitPoints",restored=String(10+proficiencyRank*10);return renderRepairResult(item,"restore",label,restored)}else if(result.outcome==="success"){const label="PF2E.Actions.Repair.Labels.RestoreItemHitPoints",restored=String(5+proficiencyRank*5);return renderRepairResult(item,"restore",label,restored)}else if(result.outcome==="criticalFailure")return renderRepairResult(item,"roll-damage","PF2E.Actions.Repair.Labels.RollItemDamage","2d6");return""})();flavor&&(messageSource.flavor+=flavor),await ChatMessage.create(messageSource)}}}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(repair,"repair"),__name2(repair,"repair");async function onRepairChatCardEvent(event,message,card){const itemUuid=card.dataset.itemUuid,item=await fromUuid(itemUuid??""),button=event.currentTarget;if(!(item instanceof PhysicalItemPF2e)||!(button instanceof HTMLElement))return;const repair2=button.dataset.repair,speaker=message&&ChatMessagePF2e.getSpeaker({actor:message.actor,alias:message.alias,token:message.token});if(repair2==="restore"){const value=Number(button.dataset.repairValue)||0,beforeRepair=item.system.hp.value,afterRepair=Math.min(item.system.hp.max,beforeRepair+value);await item.update({"system.hp.value":afterRepair});const content=game.i18n.format("PF2E.Actions.Repair.Chat.ItemRepaired",{itemName:item.name,repairedDamage:afterRepair-beforeRepair,afterRepairHitPoints:afterRepair,maximumHitPoints:item.system.hp.max});await ChatMessage.create({content,speaker})}else if(repair2==="roll-damage"){const roll=await Roll.create("2d6").evaluate({async:!0}),templatePath="systems/pf2e/templates/system/actions/repair/roll-damage-chat-message.hbs",flavor=await renderTemplate(templatePath,{damage:{dealt:Math.max(0,roll.total-item.system.hardness),rolled:roll.total},item});await roll.toMessage({flags:{pf2e:{suppressDamageButtons:!0}},flavor,speaker})}else if(repair2==="damage"){const hardness=Math.max(0,item.system.hardness),damage=(message?.rolls.at(0)?.total??0)-hardness;if(damage>0){const beforeDamage=item.system.hp.value,afterDamage=Math.max(0,item.system.hp.value-damage);await item.update({"system.hp.value":afterDamage});const content=game.i18n.format("PF2E.Actions.Repair.Chat.ItemDamaged",{itemName:item.name,damageDealt:beforeDamage-afterDamage,afterDamageHitPoints:afterDamage,maximumHitPoints:item.system.hp.max});await ChatMessage.create({content,speaker})}else{const templatePath="systems/pf2e/templates/system/actions/repair/roll-damage-chat-message.hbs",content=await renderTemplate(templatePath,{damage:{dealt:0,rolled:message?.rolls.at(0)?.total??0},item});await ChatMessage.create({content,speaker})}}}__name(onRepairChatCardEvent,"onRepairChatCardEvent"),__name2(onRepairChatCardEvent,"onRepairChatCardEvent");async function renderRepairResult(item,result,buttonLabel,value){const templatePath="systems/pf2e/templates/system/actions/repair/repair-result-partial.hbs",label=game.i18n.format(buttonLabel,{value});return renderTemplate(templatePath,{item,label,result,value})}__name(renderRepairResult,"renderRepairResult"),__name2(renderRepairResult,"renderRepairResult");const _ChatCards=class{static{__name(this,"_ChatCards")}static listen(message,html){const selector=["a[data-action], button[data-action]"].join(",");for(const button of htmlQueryAll(html,selector))button.addEventListener("click",async event=>__privateMethod(this,_onClickButton,onClickButton_fn).call(this,{message,event,html,button}))}};_lastClick=new WeakMap,_onClickButton=new WeakSet,onClickButton_fn=__name2(async function({message,event,html,button}){const currentTime=Date.now();if(currentTime-__privateGet(this,_lastClick)<500)return;__privateSet(this,_lastClick,currentTime);const action2=button.dataset.action??"",item=message.item,actor=item?.actor??message.actor;if(!actor||!game.user.isGM&&!actor.isOwner&&!["spell-save","expand-description"].includes(action2))return;const strikeAction=message._strike;if(strikeAction&&action2?.startsWith("strike-")){const context=message.rolls.some(r=>r instanceof CheckRoll)?message.flags.pf2e.context??null:null,mapIncreases=context&&"mapIncreases"in context&&tupleHasValue([0,1,2],context.mapIncreases)?context.mapIncreases:null,altUsage=context&&"altUsage"in context?context.altUsage:null,target=message.target?.token?.object??null,rollArgs={event,altUsage,mapIncreases,checkContext:context,target};switch(sluggify(action2??"")){case"strike-attack":strikeAction.variants[0].roll(rollArgs);return;case"strike-attack2":strikeAction.variants[1].roll(rollArgs);return;case"strike-attack3":strikeAction.variants[2].roll(rollArgs);return;case"strike-damage":{const method=button.dataset.outcome==="success"?"damage":"critical";strikeAction[method]?.(rollArgs);return}}}if(item){const spell=item.isOfType("spell")?item:item.isOfType("consumable")?item.embeddedSpell:null;switch(action2){case"spell-attack":return spell?.rollAttack(event);case"spell-attack-2":return spell?.rollAttack(event,2);case"spell-attack-3":return spell?.rollAttack(event,3);case"spell-damage":spell?.rollDamage(event);return;case"spell-save":return __privateMethod(this,_rollActorSaves,rollActorSaves_fn).call(this,{event,button,actor,item});case"affliction-save":item?.isOfType("affliction")&&item.rollRecovery();return;case"spell-counteract":spell?.rollCounteract(event);return;case"spell-template":return spell?.placeTemplate(message);case"spell-template-clear":{const templateIds=canvas.scene?.templates.filter(t=>t.message===message).map(t=>t.id)??[];button.disabled=!0,await canvas.scene?.deleteEmbeddedDocuments("MeasuredTemplate",templateIds),button.disabled=!1;return}case"spell-variant":{const castLevel=Number(htmlQuery(html,"div.chat-card")?.dataset.castLevel)||1,overlayIds=button.dataset.overlayIds?.split(",").map(id=>id.trim());if(overlayIds){const variantSpell=spell?.loadVariant({overlayIds,castLevel});if(variantSpell){const variantMessage=await variantSpell.toMessage(void 0,{create:!1,data:{castLevel}});if(variantMessage){const messageSource=variantMessage.toObject();await message.update(messageSource)}}}else if(spell){const originalMessage=await(spell?.original??spell).toMessage(void 0,{create:!1,data:{castLevel}});originalMessage&&await message.update(originalMessage.toObject())}return}case"consume":{if(item.isOfType("consumable"))item.consume();else if(item.isOfType("melee")){const consumable=actor.items.get(button.dataset.item??"");if(consumable?.isOfType("consumable")){const oldQuant=consumable.quantity,consumableString=game.i18n.localize("TYPES.Item.consumable"),toReplace=`${consumable.name} - ${consumableString} (${oldQuant})`;await consumable.consume();const currentQuant=oldQuant===1?0:consumable.quantity;let flavor=message.flavor.replace(toReplace,`${consumable.name} - ${consumableString} (${currentQuant})`);if(currentQuant===0){const buttonStr=`>${game.i18n.localize("PF2E.ConsumableUseLabel")}`;flavor=flavor?.replace(buttonStr," disabled"+buttonStr)}await message.update({flavor}),message.render(!0)}}return}case"expand-description":{const{description}=item,element=htmlClosest(button,".description");element&&(element.innerHTML=await TextEditor.enrichHTML(description,{async:!0,rollData:actor.getRollData()}),element.scrollIntoView({behavior:"smooth",block:"center"}));break}case"apply-effect":{button.disabled=!0;const target=fromUuidSync(button.dataset.targets??""),effect=item.isOfType("action","feat")&&item.system.selfEffect?await fromUuid(item.system.selfEffect.uuid):null;if(target instanceof ActorPF2e&&effect instanceof ItemPF2e&&effect.isOfType("effect")){await target.createEmbeddedDocuments("Item",[effect.clone().toObject()]);const parsedMessageContent=(()=>{const container=document.createElement("div");return container.innerHTML=message.content,container})(),buttons=htmlQuery(parsedMessageContent,".message-buttons");if(buttons){const span=createHTMLElement("span",{classes:["effect-applied"]}),anchor=effect.toAnchor({attrs:{draggable:"true"}}),locKey="PF2E.Item.Action.SelfAppliedEffect.Applied",statement=game.i18n.format(locKey,{effect:anchor.outerHTML});span.innerHTML=statement,buttons.replaceChildren(span),await message.update({content:parsedMessageContent.innerHTML})}}break}case"elemental-blast-damage":{if(!actor.isOfType("character"))return;const roll=message.rolls.find(r=>r instanceof CheckRoll&&r.options.action==="elemental-blast"),checkContext=roll?message.flags.pf2e.context??null:null,outcome=button.dataset.outcome==="success"?"success":"criticalSuccess",[element,damageType,meleeOrRanged,actionCost]=roll?.options.identifier?.split(".")??[];objectHasKey(elementTraits,element)&&objectHasKey(CONFIG.PF2E.damageTypes,damageType)&&await new ElementalBlast(actor).damage({element,damageType,melee:meleeOrRanged==="melee",actionCost:Number(actionCost)||1,checkContext,outcome,event})}}}else if(action2&&actor.isOfType("character","npc")){const buttonGroup=htmlClosest(button,".chat-card, .message-buttons"),physicalItem=await(async()=>{const itemUuid=buttonGroup?.dataset.itemUuid??"",maybeItem=await fromUuid(itemUuid);return maybeItem instanceof PhysicalItemPF2e?maybeItem:null})(),quantity=Number(buttonGroup?.dataset.craftingQuantity)||1;if(action2==="repair-item"&&buttonGroup)await onRepairChatCardEvent(event,message,buttonGroup);else if(physicalItem&&action2==="pay-crafting-costs"){const quantity2=Number(buttonGroup?.dataset.craftingQuantity)||1,craftingCost=CoinsPF2e.fromPrice(physicalItem.price,quantity2),coinsToRemove=button.classList.contains("full")?craftingCost:craftingCost.scale(.5);if(!await actor.inventory.removeCoins(coinsToRemove)){ui.notifications.warn(game.i18n.localize("PF2E.Actions.Craft.Warning.InsufficientCoins"));return}if(isSpellConsumable(physicalItem.id)&&physicalItem.isOfType("consumable")){craftSpellConsumable(physicalItem,quantity2,actor),ChatMessagePF2e.create({user:game.user.id,content:game.i18n.format("PF2E.Actions.Craft.Information.PayAndReceive",{actorName:actor.name,cost:coinsToRemove.toString(),quantity:quantity2,itemName:physicalItem.name}),speaker:{alias:actor.name}});return}const itemObject=physicalItem.toObject();if(itemObject.system.quantity=quantity2,!await actor.addToInventory(itemObject,void 0)){ui.notifications.warn(game.i18n.localize("PF2E.Actions.Craft.Warning.CantAddItem"));return}ChatMessagePF2e.create({user:game.user.id,content:game.i18n.format("PF2E.Actions.Craft.Information.LoseMaterials",{actorName:actor.name,cost:coinsToRemove.toString(),quantity:quantity2,itemName:physicalItem.name}),speaker:{alias:actor.name}})}else if(physicalItem&&action2==="lose-materials"){const coinsToRemove=CoinsPF2e.fromPrice(physicalItem.price,quantity).scale(.5).scale(.1);await actor.inventory.removeCoins(coinsToRemove)?ChatMessagePF2e.create({user:game.user.id,content:game.i18n.format("PF2E.Actions.Craft.Information.PayAndReceive",{actorName:actor.name,cost:coinsToRemove.toString()}),speaker:{alias:actor.name}}):ui.notifications.warn(game.i18n.localize("PF2E.Actions.Craft.Warning.InsufficientCoins"))}else if(action2==="receieve-crafting-item"&&physicalItem)return isSpellConsumable(physicalItem.id)&&physicalItem.isOfType("consumable")?craftSpellConsumable(physicalItem,quantity,actor):craftItem(physicalItem,quantity,actor)}},"#onClickButton"),_rollActorSaves=new WeakSet,rollActorSaves_fn=__name2(async function({event,button,actor,item}){if(canvas.tokens.controlled.length>0){const saveType=button.dataset.save;if(!tupleHasValue(SAVE_TYPES,saveType))throw ErrorPF2e(`"${saveType}" is not a recognized save type`);const dc=Number(button.dataset.dc??"NaN");for(const token of canvas.tokens.controlled){const save=token.actor?.saves?.[saveType];if(!save)return;save.check.roll({...eventToRollParams(event),dc:Number.isInteger(dc)?{value:Number(dc)}:null,item,origin:actor})}}else ui.notifications.error(game.i18n.localize("PF2E.UI.errorTargetToken"))},"#rollActorSaves"),__privateAdd(_ChatCards,_onClickButton),__privateAdd(_ChatCards,_rollActorSaves),__name2(_ChatCards,"ChatCards"),__privateAdd(_ChatCards,_lastClick,0);let ChatCards=_ChatCards;const DamageTaken={listen:async(message,html)=>{const damageTakenCard=htmlQuery(html,".damage-taken");if(!damageTakenCard)return;const settingEnabled=game.settings.get("pf2e","metagame_tokenSetsNameVisibility");if(!game.user.isGM&&settingEnabled&&message.token&&!message.token.playersCanSeeName){const nameElem=htmlQuery(damageTakenCard,".target-name");nameElem&&(nameElem.innerText=game.i18n.localize("PF2E.Actor.ApplyDamage.TheTarget"))}const iwrInfo=htmlQuery(damageTakenCard,".iwr");if(!iwrInfo)return;const iwrApplications=(()=>{try{const parsed=JSON.parse(iwrInfo?.dataset.applications??"null");return Array.isArray(parsed)&&parsed.every(a=>a instanceof Object&&"category"in a&&typeof a.category=="string"&&"type"in a&&typeof a.type=="string"&&"adjustment"in a&&typeof a.adjustment=="number")?parsed:null}catch{return null}})();iwrApplications&&$(iwrInfo).tooltipster({theme:"crb-hover",maxWidth:400,content:await renderTemplate("systems/pf2e/templates/chat/damage/iwr-breakdown.hbs",{applications:iwrApplications}),contentAsHTML:!0})}},DegreeOfSuccessHighlights={listen:(message,html)=>{if(htmlQueryAll(html,".pf2e-reroll-indicator").length>0)return;const firstRoll=message.rolls.at(0);if(!firstRoll||message.isDamageRoll)return;const firstDice=firstRoll.dice.at(0);if(!(firstDice instanceof Die&&firstDice.faces===20&&message.isContentVisible))return;const diceTotal=htmlQuery(html,".dice-total"),results=firstDice.results.filter(r=>r.active);results.every(r=>r.result===20)?diceTotal?.classList.add("success"):results.every(r=>r.result===1)&&diceTotal?.classList.add("failure")}},SetAsInitiative={listen:li=>{const message=game.messages.get(li.dataset.messageId??"",{strict:!0}),{context}=message.flags.pf2e;if(message.token&&(message.isAuthor&&!message.blind||game.user.isGM)&&(context?.type==="skill-check"||context?.type==="perception-check")){const btnContainer=document.createElement("span");btnContainer.classList.add("dmgBtn-container"),Object.assign(btnContainer.style,{position:"absolute",right:"0",bottom:"1px"});const setInitiativeButton=document.createElement("button");setInitiativeButton.classList.add("dice-total-setInitiative-btn"),Object.assign(setInitiativeButton.style,{width:"22px",height:"22px",fontSize:"10px",lineHeight:"1px"}),setInitiativeButton.title=game.i18n.localize("PF2E.ClickToSetInitiative"),setInitiativeButton.appendChild(fontAwesomeIcon("fa-swords",{style:"solid"})),btnContainer.appendChild(setInitiativeButton);const selector=message.isReroll?".pf2e-reroll-second .dice-total":".dice-total";li.querySelector(selector)?.appendChild(btnContainer),setInitiativeButton.addEventListener("click",async event=>{event.stopPropagation();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:actor.name,initiative:value}))})}}},_ChatMessagePF2e=class _ChatMessagePF2e2 extends ChatMessage{static{__name(this,"_ChatMessagePF2e")}constructor(data={},context={}){const expandedFlags=expandObject(data.flags??{});data.flags=mergeObject(expandedFlags,{core:{canPopout:expandedFlags.core?.canPopout??!0},pf2e:{}}),super(data,context),__privateAdd(this,_onHoverIn),__privateAdd(this,_onHoverOut)}get isDamageRoll(){const firstRoll=this.rolls.at(0);if(!firstRoll||firstRoll.terms.some(t=>t instanceof FateDie||t instanceof Coin))return!1;if(this.flags.pf2e.context?.type==="damage-roll")return!0;const isCheck=firstRoll instanceof CheckRoll||firstRoll.dice[0]?.faces===20,fromRollTable=!!this.flags.core.RollTable;return!(isCheck||fromRollTable)}get actor(){return _ChatMessagePF2e2.getSpeakerActor(this.speaker)}get target(){const context=this.flags.pf2e.context;if(!context)return null;const targetUUID="target"in context?context.target?.token:null;if(!targetUUID)return null;const match=/^Scene\.(\w+)\.Token\.(\w+)$/.exec(targetUUID??"")??[],token=game.scenes.get(match[1]??"")?.tokens.get(match[2]??""),actor=token?.actor;return actor?{actor,token}:null}get journalEntry(){const uuid=this.flags.pf2e.journalEntry;if(!uuid)return null;const entryId=/^JournalEntry.([A-Za-z0-9]{16})$/.exec(uuid)?.at(1);return game.journal.get(entryId??"")??null}get isCheckRoll(){return this.rolls[0]instanceof CheckRoll}get isReroll(){const context=this.flags.pf2e.context;return!!context&&"isReroll"in context&&!!context.isReroll}get isRerollable(){const roll=this.rolls[0];return!!(this.actor?.isOwner&&(this.isAuthor||this.isOwner)&&roll instanceof CheckRoll&&roll.isRerollable)}get item(){if(this.flags.pf2e.context?.type==="self-effect")return this.actor?.items.get(this.flags.pf2e.context.item)??null;const strike=this._strike;if(strike?.item)return strike.item;const item=(()=>{const domItem=this.getItemFromDOM();if(domItem)return domItem;const origin=this.flags.pf2e?.origin??null,match=/Item\.(\w+)/.exec(origin?.uuid??"")??[];return this.actor?.items.get(match?.[1]??"")??null})();if(!item)return null;const{tradition}=this.flags.pf2e?.casting??{},isCharacter=item.actor.isOfType("character");if(tradition&&item.isOfType("spell")&&!item.spellcasting&&isCharacter){const trick=new TrickMagicItemEntry(item.actor,traditionSkills[tradition]);item.trickMagicEntry=trick}if(item?.isOfType("spell")){const overlayIds=this.flags.pf2e.origin?.variant?.overlays,castLevel=this.flags.pf2e.origin?.castLevel??item.rank;return item.loadVariant({overlayIds,castLevel})??item}return item}get _strike(){const{actor}=this,identifier=this.rolls.find(r=>r instanceof CheckRoll)?.options.identifier??htmlQuery(document.body,`li.message[data-message-id="${this.id}"] [data-identifier]`)?.dataset.identifier,[itemId,slug,meleeOrRanged]=identifier?.split(".")??[null,null,null];if(!meleeOrRanged||!["melee","ranged"].includes(meleeOrRanged))return null;const strikeData=actor?.system.actions?.find(s=>s.slug===slug&&s.item.id===itemId),itemMeleeOrRanged=strikeData?.item.isMelee?"melee":"ranged";return meleeOrRanged===itemMeleeOrRanged?strikeData??null:strikeData?.altUsages?.find(u=>{const altUsageMeleeOrRanged=u.item.isMelee?"melee":"ranged";return meleeOrRanged===altUsageMeleeOrRanged})??null}getItemFromDOM(){const html=ui.chat.element[0],messageElem=htmlQuery(html,`#chat-log > li[data-message-id="${this.id}"]`),sourceString=htmlQuery(messageElem,".pf2e.item-card")?.dataset.embeddedItem??"null";try{const itemSource=JSON.parse(sourceString);return itemSource?new ItemProxyPF2e(itemSource,{parent:this.actor,fromConsumable:this.flags?.pf2e?.isFromConsumable}):null}catch{return null}}async showDetails(){this.flags.pf2e.context&&new ChatInspectRoll(this).render(!0)}get token(){if(!game.scenes)return null;const sceneId=this.speaker.scene??"",tokenId=this.speaker.token??"";return game.scenes.get(sceneId)?.tokens.get(tokenId)??null}getRollData(){const{actor,item}=this;return{...actor?.getRollData(),...item?.getRollData()}}async getHTML(){const{actor}=this;if(this.isContentVisible){const rollData=this.getRollData();this.flavor=await TextEditorPF2e.enrichHTML(this.flavor,{async:!0,rollData,processVisibility:!1})}const $html=await super.getHTML(),html=$html[0];!this.flags.pf2e.suppressDamageButtons&&this.isDamageRoll&&htmlQueryAll(html,".damage-application").forEach((buttons,index)=>{buttons.dataset.rollIndex=index.toString()}),UserVisibilityPF2e.process(html,{message:this}),await DamageTaken.listen(this,html),CriticalHitAndFumbleCards.appendButtons(this,$html),ChatCards.listen(this,html),InlineRollLinks.listen(html,this),DegreeOfSuccessHighlights.listen(this,html),canvas.ready&&SetAsInitiative.listen(html);const roll=this.rolls[0];if(actor?.isOwner&&roll instanceof DamageRoll&&roll.options.evaluatePersistent){const damageType=roll.instances.find(i=>i.persistent)?.type;if(damageType?this.actor?.getCondition(`persistent-damage-${damageType}`):null){const template="systems/pf2e/templates/chat/persistent-damage-recovery.hbs",section=parseHTML(await renderTemplate(template));html.querySelector(".message-content")?.append(section),html.dataset.actorIsTarget="true"}htmlQuery(html,"[data-action=recover-persistent-damage]")?.addEventListener("click",()=>{const{actor:actor2}=this;if(!actor2)return;const damageType2=roll.instances.find(i=>i.persistent)?.type;if(!damageType2)return;const condition2=actor2.getCondition(`persistent-damage-${damageType2}`);if(!condition2?.system.persistent){const damageTypeLocalized=game.i18n.localize(CONFIG.PF2E.damageTypes[damageType2]??damageType2),message=game.i18n.format("PF2E.Item.Condition.PersistentDamage.Error.DoesNotExist",{damageType:damageTypeLocalized});ui.notifications.warn(message);return}condition2.rollRecovery()})}return this.flags.pf2e.appliedDamage?.isReverted||this.actor?.isOwner||htmlQuery(html,"button[data-action=revert-damage]")?.remove(),html.addEventListener("mouseenter",event=>__privateMethod(this,_onHoverIn,onHoverIn_fn).call(this,event)),html.addEventListener("mouseleave",event=>__privateMethod(this,_onHoverOut,onHoverOut_fn).call(this,event)),UserVisibilityPF2e.processMessageSender(this,html),!actor&&this.content&&UserVisibilityPF2e.process(html,{document:this}),$html}_onCreate(data,options,userId){super._onCreate(data,options,userId),this.isRoll&&game.settings.get("pf2e","drawCritFumble")&&CriticalHitAndFumbleCards.handleDraw(this)}};_onHoverIn=new WeakSet,onHoverIn_fn=__name2(function(nativeEvent){if(!canvas.ready)return;const token=this.token?.object;token?.isVisible&&!token.controlled&&token.emitHoverIn(nativeEvent)},"#onHoverIn"),_onHoverOut=new WeakSet,onHoverOut_fn=__name2(function(nativeEvent){canvas.ready&&this.token?.object?.emitHoverOut(nativeEvent)},"#onHoverOut"),__name2(_ChatMessagePF2e,"ChatMessagePF2e");let ChatMessagePF2e=_ChatMessagePF2e;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");const _ItemPF2e=class _ItemPF2e2 extends Item{static{__name(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 _ItemPF2e2&&item.parent&&!item.sourceId&&(item._source.flags=mergeObject(item._source.flags,{core:{sourceId:item.uuid}}),item.flags=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.sort()}getRollData(){return{...this.actor?.getRollData()??{actor:null},item:this}}async toMessage(event,{rollMode=void 0,create=!0,data={}}={}){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=event?.currentTarget.closest(".item")??{},contextualData=Object.keys(data).length>0?data:nearestItem.dataset||{},templateData={actor:this.actor,tokenId:token?`${token.parent?.id}.${token.id}`:null,item:this,data:await this.getChatData(void 0,contextualData)},chatData={speaker:ChatMessagePF2e.getSpeaker({actor:this.actor,token:this.actor.getActiveTokens(!1,!0)[0]??null}),flags:{pf2e:{origin:this.getOriginData()}},type:CONST.CHAT_MESSAGE_TYPES.OTHER};return rollMode??=event?.ctrlKey||event?.metaKey?"blindroll":game.settings.get("core","rollMode"),["gmroll","blindroll"].includes(rollMode)&&(chatData.whisper=ChatMessagePF2e.getWhisperRecipients("GM").map(u=>u.id)),rollMode==="blindroll"&&(chatData.blind=!0),chatData.content=await renderTemplate(template,templateData),create?ChatMessagePF2e.create(chatData,{renderSheet:!1}):new ChatMessagePF2e(chatData)}async toChat(event){return this.toMessage(event,{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=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={}){if(!this.isOwned){ui.notifications.error("This utility may only be used on owned items");return}if(!this.sourceId?.startsWith("Compendium.")){ui.notifications.warn(`Item "${this.name}" has no compendium source.`);return}options.name??=!1;const currentSource=this.toObject(),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(`The compendium source for "${this.name}" (source ID: ${this.sourceId}) was not found.`);return}const updates={img:currentSource.img.endsWith(".svg")?latestSource.img:currentSource.img,system:latestSource.system};if(options.name&&(updates.name=latestSource.name),isPhysicalData(currentSource)){const{containerId,quantity}=currentSource.system;mergeObject(updates,expandObject({"system.containerId":containerId,"system.quantity":quantity}))}else(currentSource.type==="feat"||currentSource.type==="spell")&&mergeObject(updates,expandObject({"system.location":currentSource.system.location}));if(currentSource.type==="weapon"||currentSource.type==="armor"){const materialAndRunes={"system.material":currentSource.system.material,"system.potencyRune":currentSource.system.potencyRune,"system.propertyRune1":currentSource.system.propertyRune1,"system.propertyRune2":currentSource.system.propertyRune2,"system.propertyRune3":currentSource.system.propertyRune3,"system.propertyRune4":currentSource.system.propertyRune4};currentSource.type==="weapon"?materialAndRunes["system.strikingRune"]=currentSource.system.strikingRune:materialAndRunes["system.resiliencyRune"]=currentSource.system.resiliencyRune,mergeObject(updates,expandObject(materialAndRunes))}await this.update(updates,{diff:!1,recursive:!1}),ui.notifications.info(`Item "${this.name}" has been refreshed.`)}getOriginData(){return{uuid:this.uuid,type:this.type}}async processChatData(htmlOptions={},data){if(data.properties=data.properties?.filter(property=>property!==null)??[],isItemSystemData(data)){const chatData=duplicate(data);return htmlOptions.rollData=mergeObject(this.getRollData(),htmlOptions.rollData??{}),chatData.description.value=await TextEditor.enrichHTML(chatData.description.value,{...htmlOptions,async:!0}),chatData}return data}async getChatData(htmlOptions={},_rollOptions2={}){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,deepClone(systemData))}traitChatData(dictionary={}){return[...this.system.traits?.value??[]].sort().map(trait=>{const label=dictionary[trait]??trait,traitDescriptions2=CONFIG.PF2E.traitsDescriptions;return{value:trait,label,description:traitDescriptions2[trait]}})}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 _ItemPF2e2?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);const validTypes=actor.allowedItemTypes;validTypes.includes("physical")&&validTypes.push(...PHYSICAL_ITEM_TYPES,"kit");for(const source of sources)if(!validTypes.includes(source.type))return ui.notifications.error(game.i18n.format("PF2E.Item.CannotAddType",{type:game.i18n.localize(CONFIG.Item.typeLabels[source.type]??source.type.titleCase())})),[];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](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=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,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&&mergeObject(actorUpdates,{items:itemUpdates})}}const updateKeys=Object.keys(actorUpdates);updateKeys.length>0&&!updateKeys.every(k=>k==="_id")&&this.actor.update(actorUpdates)}};__name2(_ItemPF2e,"ItemPF2e");let ItemPF2e=_ItemPF2e;const ItemProxyPF2e=new Proxy(ItemPF2e,{construct(_target2,args){const ItemClass=CONFIG.PF2E.Item.documentClasses[args[0]?.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");const _AbstractEffectPF2e=class _AbstractEffectPF2e2 extends ItemPF2e{static{__name(this,"_AbstractEffectPF2e")}get origin(){const requiresActorConstructed=!!(this.actor?._id&&this.actor.isToken),requiresCanvasReady=!!this.system.context?.origin.actor.startsWith("Scene");if(requiresActorConstructed&&!this.actor?.constructed||requiresCanvasReady&&!canvas.ready)return null;const actorOrToken=this.system.context?.origin.actor?fromUuidSync(this.system.context.origin.actor):this.actor;return actorOrToken instanceof ActorPF2e?actorOrToken:actorOrToken instanceof TokenDocumentPF2e?actorOrToken.actor:this.actor}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 _AbstractEffectPF2e2&&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()}}};__name2(_AbstractEffectPF2e,"AbstractEffectPF2e");let AbstractEffectPF2e=_AbstractEffectPF2e;const _ConditionManager=class _ConditionManager2{static{__name(this,"_ConditionManager")}static get conditionsSlugs(){return[...this.conditions.keys()].filter(k=>!k.startsWith("Compendium."))}static async initialize(force=!1){if(__privateGet(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),(!__privateGet(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`)}__privateSet(this,_initialized,!0)}static getCondition(slug,modifications={}){if(slug=sluggify(slug),!setHasElement(CONDITION_SLUGS,slug))return null;const condition=_ConditionManager2.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})))}};_initialized=new WeakMap,__name2(_ConditionManager,"ConditionManager"),__privateAdd(_ConditionManager,_initialized,!1),__publicField(_ConditionManager,"conditions",new Map),__publicField(_ConditionManager,"CONDITION_SOURCES",[{_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 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:.878,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:.878,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:.878,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.

@@ -299,9 +301,9 @@ for (const actor of actors) {

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:.878,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:.878,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:.878,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:.878,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(){const label=game.i18n.format("PF2E.Item.Affliction.Stage",{stage:this.stage});return{type:"counter",value:this.stage,min:1,max:this.maxStage,label}}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,1,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}}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.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}:this.system.value.value?{type:"counter",min:1,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:.878,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}:this.system.value.value?{type:"counter",min:1,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} -${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);const html=$html[0];$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})});for(const hintHoverZone of htmlQueryAll(html,"i[data-action=hint-tooltip]"))$(hintHoverZone).tooltipster({maxWidth:Number(hintHoverZone.dataset.tooltipWidth)||350,theme:"crb-hover",content:game.i18n.localize(hintHoverZone.title)})}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=this.system.runes.property.map(p=>`rune:property:${sluggify(p)}`).reduce((statements,s)=>({...statements,[s]:!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,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()}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:{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)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{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}}};if(this.category!=="ammo"){const 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})}}const quantity=this.quantity;this.autoDestroy&&value<=1?quantity<=1?await this.delete():await this.update({"system.quantity":Math.max(quantity-1,0),"system.charges.value":max}):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.showRollDialogs,_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 instance=Object.values(this.system.damageRolls).shift();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};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,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}).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 range(){return null}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(damageOptions={skipDialog:!0}){if(!Object.keys(this.system.damage.value).length||!this.actor)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{actor,attribute}=this,checkStatistic=this.spellcasting?.statistic,domains=compact(["damage","spell-damage",`${this.id}-damage`,this.traits.has("attack")?["attack-damage","attack-spell-damage"]:null,checkStatistic?.base?`${checkStatistic?.base.slug}-damage`:null]).flat(),options=new Set([...actor?.getRollOptions(domains)??[],...damageOptions.target?.getSelfRollOptions("target")??[],...this.getRollOptions("item"),...this.traits]),context={type:"damage-roll",sourceType:this.isAttack?"attack":"save",outcome:this.isAttack?"success":null,domains,options,self:{actor:this.actor,item:this,statistic:null,token:this.actor.token,modifiers:[]},rollMode:damageOptions.rollMode},modifiers=[],damageDice=[];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},test:options},extracted=processDamageCategoryStacking(base,{modifiers:[attributeModifiers,extractModifiers(actor.synthetics,domains,extractOptions)].flat(),dice:extractDamageDice(actor.synthetics.damageDice,domains,extractOptions),test:options});modifiers.push(...extracted.modifiers),damageDice.push(...extracted.dice)}const formulaData={base,modifiers,dice:damageDice,ignoredResistances:[]};applyDamageDiceOverrides(base,damageDice);const{formula,breakdown}=createDamageFormula(formulaData),roll=new DamageRoll(formula);return{template:{name:this.name,damage:{roll,breakdown},materials: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})(),isHeal=systemData.spellType.value==="heal",damageLabel=localize(isHeal?"PF2E.SpellTypeHeal":"PF2E.DamageLabel"),[areaSize,areaType,areaUnit]=systemData.area?[Number(systemData.area.value),game.i18n.localize(CONFIG.PF2E.areaTypes[systemData.area.type]),game.i18n.localize("PF2E.Foot")]:[null,null,null],area=areaSize&&areaType&&areaUnit?game.i18n.format("PF2E.SpellArea",{areaSize,areaUnit,areaType}).trim():null,{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})})(),properties=[heightened?game.i18n.format("PF2E.SpellLevelBase",{level:ordinal(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,systemData.time.value?`${localize("PF2E.SpellTimeLabel")}: ${systemData.time.value}`:null,systemData.duration.value?`${localize("PF2E.SpellDurationLabel")}: ${systemData.duration.value}`:null].filter(p=>p!==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)),areaSize,areaType,areaUnit,item,variants}}async rollAttack(event,attackNumber=1,context={}){const statistic=this.spellcasting?.statistic;if(statistic)await statistic.check.roll({...eventToRollParams(event),...context,item:this,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"))??null,spellDamage=await this.getDamage({target:targetToken?.actor,...eventToRollParams(event)});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),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.SpellLevel",{level:ordinal(heightenedRank)}),baseLabel=game.i18n.format("PF2E.SpellLevel",{level:ordinal(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 targetLevelLabel=game.i18n.format("PF2E.SpellLevel",{level:ordinal(slotRank)}),baseLabel=game.i18n.format("PF2E.SpellLevel",{level:ordinal(spell.baseRank)});return ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.InvalidLevel",{name:spell.name,targetLevel:targetLevelLabel,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.TraitCantrip":CONFIG.PF2E.spellLevels[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=await Promise.all(cantrips.map(async spell=>({spell})));results.push({label:"PF2E.Actor.Creature.Spellcasting.Cantrips",level:0,isCantrip:!0,active})}if(leveled.length){const active=await Promise.all(leveled.map(async 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=await Promise.all(spells2.map(async 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.TraitCantrip":CONFIG.PF2E.spellLevels[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:await Promise.all(Array.from(groupedByRank.entries()).sort(([a],[b])=>a-b).map(async([level,spells])=>({label:CONFIG.PF2E.spellLevels[level],level,isCantrip:!1,active:await Promise.all(spells.map(async 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.localize(CONFIG.PF2E.spellLevels[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{static{__name(this,"_ActorConditions")}constructor(){__privateAdd(this,_idMap2,new Collection),__privateAdd(this,_slugMap,new Collection)}get active(){return __privateGet(this,_idMap2).filter(c=>c.active)}get stored(){return __privateGet(this,_idMap2).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}[Symbol.iterator](){return __privateGet(this,_idMap2).values()}get(key,{strict=!1,active=null,temporary=null}={}){const condition=__privateGet(this,_idMap2).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}has(id){return __privateGet(this,_idMap2).has(id)}set(id,condition){__privateGet(this,_idMap2).set(id,condition);const listBySlug=__privateGet(this,_slugMap).get(condition.slug)??[];return listBySlug.push(condition),__privateGet(this,_slugMap).set(condition.slug,listBySlug),this}filter(condition){return __privateGet(this,_idMap2).filter(condition)}some(condition){return __privateGet(this,_idMap2).some(condition)}every(condition){return __privateGet(this,_idMap2).contents.every(condition)}map(transformer){return __privateGet(this,_idMap2).map(transformer)}flatMap(transformer){return __privateGet(this,_idMap2).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})}};_idMap2=new WeakMap,_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){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"))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},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._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}=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))??[];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,...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","spell","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.includes("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();if(blockingShield&&shieldDamage>0&&await blockingShield.update({"system.hp.value":Math.max(blockingShield._source.system.hp.value-shieldDamage,0)},{render:hpDamage===0}),hpDamage!==0){const updated=await this.update(hpUpdate.updates,{damageTaken:hpDamage}),deadAtZero=["npcsOnly","both"].includes(game.settings.get("pf2e","automation.actorsDeadAtZero")),toggleDefeated=updated.isDead&&(hpDamage>=0&&!token.combatant?.isDefeated||hpDamage<0&&!!token.combatant?.isDefeated);updated.isOfType("npc")&&deadAtZero&&toggleDefeated&&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=[hpStatement,shieldStatement].filter(s=>!!s).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,applied=remaining>0?Math.min(hp.value,remaining):Math.max(hp.value-hp.max,remaining);return updates["system.attributes.hp.value"]=Math.max(hp.value-applied,0),applied})(),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 value=typeof condition.value=="number"?Math.max(condition.value-1,0):null;value!==null&&!forceRemove?await game.pf2e.ConditionManager.updateConditionValue(condition.id,this,value):await this.deleteEmbeddedDocuments("Item",[condition.id])}async increaseCondition(conditionSlug,{min,max=Number.MAX_SAFE_INTEGER,value}={}){if(value&&(min=max=value),conditionSlug==="persistent-damage")return await new PersistentDamageDialog(this).render(!0),null;const existing=(()=>{if(typeof conditionSlug!="string")return conditionSlug;const conditions=this.conditions.stored;return value?conditions.find(c=>c.slug===conditionSlug&&!c.isLocked):conditions.find(c=>c.slug===conditionSlug&&c.active)})();if(existing){const conditionValue=(()=>{if(existing.value===null)return null;if(min&&max&&min>max)throw ErrorPF2e(`min (${min}) > max (${max})`);return min&&max?Math.clamped(existing.value+1,min,max):max?Math.min(existing.value+1,max):existing.value+1})();return conditionValue===null||conditionValue>(max??0)?null:(await game.pf2e.ConditionManager.updateConditionValue(existing.id,this,conditionValue),existing)}else if(typeof conditionSlug=="string"){const conditionSource=game.pf2e.ConditionManager.getCondition(conditionSlug).toObject(),conditionValue=typeof conditionSource?.system.value.value=="number"&&min&&max?Math.clamped(conditionSource.system.value.value,min,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.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),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"]}),this.createGroup({id:"ancestry",label:"PF2E.FeatAncestryHeader",featFilter:actor.system.details.ancestry?.countsAs.map(t=>`traits-${t}`)??[],supported:["ancestry"],slots:classFeatSlots?.ancestry??[]});const classSlug=actor.class?actor.class.slug??sluggify(actor.class.name):null,classTrait=(classSlug??"")in CONFIG.PF2E.featTraits?classSlug:`hb_${classSlug}`in CONFIG.PF2E.featTraits?`hb_${classSlug}`: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.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=slot?.id??null,existing=this.actor.items.filter(i=>isFeatLike(i)).filter(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 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.clamped(focus.max,0,focus.cap),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)];return[itemTypes.weapon.filter(w=>w.slug!==handwrapsSlug),Array.from(synthetics.strikes.values()),basicUnarmed??[]].flat().map(w=>this.prepareStrike(w,{categories:offensiveCategories,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,options){const{synthetics}=this,modifiers=[],systemData=this.system,{categories}=options,ammos=options.ammos??[],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}`,...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]),attackRollNotes=extractNotes(synthetics.rollNotes,attackDomains),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"));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})),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"),ready2=weapon.isEquipped||weapon.isThrown&&weapon.reload==="0"&&weapon.isWorn&&this.handsReallyFree>0,action2=mergeObject(strikeStat,{label:weapon.name,imageUrl:weapon.img,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:[],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,rollTwice=params.rollTwice||extractRollTwice(synthetics.rollTwice,attackDomains,context.options),substitutions=extractRollSubstitutions(synthetics.rollSubstitutions,attackDomains,context.options),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:attackRollNotes,dc,traits:context.traits,rollTwice,substitutions,dosAdjustments:extractDegreeOfSuccessAdjustments(synthetics,attackDomains),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 this.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:options2}=context,damageContext={type:"damage-roll",sourceType:"attack",self,target,outcome,options:options2,domains,...eventToRollParams(params.event)};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(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.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=level.value,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;return!this.system.attributes.hasHealth&&damageType?!1: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))}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))})}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(){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,"notes"),__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],notes:args[6]}: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.notes=params.notes??"",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){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");function shiftAdjustDamage(message,multiplier,rollIndex){new Dialog({title:game.i18n.localize("PF2E.UI.shiftModifyDamageTitle"),content:`
+${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=this.system.runes.property.map(p=>`rune:property:${sluggify(p)}`).reduce((statements,s)=>({...statements,[s]:!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,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:{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)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{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}}};if(this.category!=="ammo"){const 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})}}const quantity=this.quantity;this.autoDestroy&&value<=1?quantity<=1?await this.delete():await this.update({"system.quantity":Math.max(quantity-1,0),"system.charges.value":max}):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.showRollDialogs,_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 instance=Object.values(this.system.damageRolls).shift();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};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,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}).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 range(){return null}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(damageOptions={skipDialog:!0}){if(!Object.keys(this.system.damage.value).length||!this.actor)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{actor,attribute}=this,checkStatistic=this.spellcasting?.statistic,domains=compact(["damage","spell-damage",`${this.id}-damage`,this.traits.has("attack")?["attack-damage","attack-spell-damage"]:null,checkStatistic?.base?`${checkStatistic?.base.slug}-damage`:null]).flat(),options=new Set([...actor?.getRollOptions(domains)??[],...damageOptions.target?.getSelfRollOptions("target")??[],...this.getRollOptions("item"),...this.traits]),context={type:"damage-roll",sourceType:this.isAttack?"attack":"save",outcome:this.isAttack?"success":null,domains,options,self:{actor:this.actor,item:this,statistic:null,token:this.actor.token,modifiers:[]},rollMode:damageOptions.rollMode},modifiers=[],damageDice=[];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:damageOptions.target??null},test:options},extracted=processDamageCategoryStacking(base,{modifiers:[attributeModifiers,extractModifiers(actor.synthetics,domains,extractOptions)].flat(),dice:extractDamageDice(actor.synthetics.damageDice,domains,extractOptions),test:options});modifiers.push(...extracted.modifiers),damageDice.push(...extracted.dice)}const formulaData={base,modifiers,dice:damageDice,ignoredResistances:[]};applyDamageDiceOverrides(base,damageDice);const{formula,breakdown}=createDamageFormula(formulaData),roll=new DamageRoll(formula);return{template:{name:this.name,damage:{roll,breakdown},materials: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})(),isHeal=systemData.spellType.value==="heal",damageLabel=localize(isHeal?"PF2E.SpellTypeHeal":"PF2E.DamageLabel"),[areaSize,areaType,areaUnit]=systemData.area?[Number(systemData.area.value),game.i18n.localize(CONFIG.PF2E.areaTypes[systemData.area.type]),game.i18n.localize("PF2E.Foot")]:[null,null,null],area=areaSize&&areaType&&areaUnit?game.i18n.format("PF2E.SpellArea",{areaSize,areaUnit,areaType}).trim():null,{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})})(),properties=[heightened?game.i18n.format("PF2E.SpellLevelBase",{level:ordinal(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,systemData.time.value?`${localize("PF2E.SpellTimeLabel")}: ${systemData.time.value}`:null,systemData.duration.value?`${localize("PF2E.SpellDurationLabel")}: ${systemData.duration.value}`:null].filter(p=>p!==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)),areaSize,areaType,areaUnit,item,variants}}async rollAttack(event,attackNumber=1,context={}){const statistic=this.spellcasting?.statistic;if(statistic)await statistic.check.roll({...eventToRollParams(event),...context,item:this,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"))??null,spellDamage=await this.getDamage({target:targetToken?.actor,...eventToRollParams(event)});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),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.SpellLevel",{level:ordinal(heightenedRank)}),baseLabel=game.i18n.format("PF2E.SpellLevel",{level:ordinal(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 targetLevelLabel=game.i18n.format("PF2E.SpellLevel",{level:ordinal(slotRank)}),baseLabel=game.i18n.format("PF2E.SpellLevel",{level:ordinal(spell.baseRank)});return ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.InvalidLevel",{name:spell.name,targetLevel:targetLevelLabel,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.TraitCantrip":CONFIG.PF2E.spellLevels[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.TraitCantrip":CONFIG.PF2E.spellLevels[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(([level,spells])=>({label:CONFIG.PF2E.spellLevels[level],level,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.localize(CONFIG.PF2E.spellLevels[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{static{__name(this,"_ActorConditions")}constructor(){__privateAdd(this,_idMap2,new Collection),__privateAdd(this,_slugMap,new Collection)}get active(){return __privateGet(this,_idMap2).filter(c=>c.active)}get stored(){return __privateGet(this,_idMap2).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}[Symbol.iterator](){return __privateGet(this,_idMap2).values()}get(key,{strict=!1,active=null,temporary=null}={}){const condition=__privateGet(this,_idMap2).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}has(id){return __privateGet(this,_idMap2).has(id)}set(id,condition){__privateGet(this,_idMap2).set(id,condition);const listBySlug=__privateGet(this,_slugMap).get(condition.slug)??[];return listBySlug.push(condition),__privateGet(this,_slugMap).set(condition.slug,listBySlug),this}filter(condition){return __privateGet(this,_idMap2).filter(condition)}some(condition){return __privateGet(this,_idMap2).some(condition)}every(condition){return __privateGet(this,_idMap2).contents.every(condition)}map(transformer){return __privateGet(this,_idMap2).map(transformer)}flatMap(transformer){return __privateGet(this,_idMap2).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})}};_idMap2=new WeakMap,_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){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"))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},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._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,...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","spell","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.includes("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();if(blockingShield&&shieldDamage>0&&await blockingShield.update({"system.hp.value":Math.max(blockingShield._source.system.hp.value-shieldDamage,0)},{render:hpDamage===0}),hpDamage!==0){const updated=await this.update(hpUpdate.updates,{damageTaken:hpDamage}),deadAtZero=["npcsOnly","both"].includes(game.settings.get("pf2e","automation.actorsDeadAtZero")),toggleDefeated=updated.isDead&&(hpDamage>=0&&!token.combatant?.isDefeated||hpDamage<0&&!!token.combatant?.isDefeated);updated.isOfType("npc")&&deadAtZero&&toggleDefeated&&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=[hpStatement,shieldStatement].filter(s=>!!s).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,applied=remaining>0?Math.min(hp.value,remaining):Math.max(hp.value-hp.max,remaining);return updates["system.attributes.hp.value"]=Math.max(hp.value-applied,0),applied})(),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 value=typeof condition.value=="number"?Math.max(condition.value-1,0):null;value!==null&&!forceRemove?await game.pf2e.ConditionManager.updateConditionValue(condition.id,this,value):await this.deleteEmbeddedDocuments("Item",[condition.id])}async increaseCondition(conditionSlug,{min,max=Number.MAX_SAFE_INTEGER,value}={}){if(value&&(min=max=value),conditionSlug==="persistent-damage")return await new PersistentDamageDialog(this).render(!0),null;const existing=(()=>{if(typeof conditionSlug!="string")return conditionSlug;const conditions=this.conditions.stored;return value?conditions.find(c=>c.slug===conditionSlug&&!c.isLocked):conditions.find(c=>c.slug===conditionSlug&&c.active)})();if(existing){const conditionValue=(()=>{if(existing.value===null)return null;if(min&&max&&min>max)throw ErrorPF2e(`min (${min}) > max (${max})`);return min&&max?Math.clamped(existing.value+1,min,max):max?Math.min(existing.value+1,max):existing.value+1})();return conditionValue===null||conditionValue>(max??0)?null:(await game.pf2e.ConditionManager.updateConditionValue(existing.id,this,conditionValue),existing)}else if(typeof conditionSlug=="string"){const conditionSource=game.pf2e.ConditionManager.getCondition(conditionSlug).toObject(),conditionValue=typeof conditionSource?.system.value.value=="number"&&min&&max?Math.clamped(conditionSource.system.value.value,min,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),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=slot?.id??null,existing=this.actor.items.filter(i=>isFeatLike(i)).filter(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)];return[itemTypes.weapon.filter(w=>w.slug!==handwrapsSlug),Array.from(synthetics.strikes.values()),basicUnarmed??[]].flat().map(w=>this.prepareStrike(w,{categories:offensiveCategories,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,options){const{synthetics}=this,modifiers=[],systemData=this.system,{categories}=options,ammos=options.ammos??[],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}`,...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]),attackRollNotes=extractNotes(synthetics.rollNotes,attackDomains),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})),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"),ready2=weapon.isEquipped||weapon.isThrown&&weapon.reload==="0"&&weapon.isWorn&&this.handsReallyFree>0,action2=mergeObject(strikeStat,{label:weapon.name,imageUrl:weapon.img,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:[],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,rollTwice=params.rollTwice||extractRollTwice(synthetics.rollTwice,attackDomains,context.options),substitutions=extractRollSubstitutions(synthetics.rollSubstitutions,attackDomains,context.options),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:attackRollNotes,dc,traits:context.traits,rollTwice,substitutions,dosAdjustments:extractDegreeOfSuccessAdjustments(synthetics,attackDomains),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 this.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:options2}=context,damageContext={type:"damage-roll",sourceType:"attack",self,target,outcome,options:options2,domains,...eventToRollParams(params.event)};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;return!this.system.attributes.hasHealth&&damageType?!1: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))}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))})}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");function shiftAdjustDamage(message,multiplier,rollIndex){new Dialog({title:game.i18n.localize("PF2E.UI.shiftModifyDamageTitle"),content:`
@@ -311,7 +313,7 @@ ${game.i18n.localize(trait.description)}`:gmNote}return traitData}async _preCrea $(function () { $(".form-group input").focus(); }); - <\/script>`,buttons:{ok:{label:"Ok",callback:async $dialog=>{const adjustment=(Number($dialog.find("[name=modifier]").val())||0)*Math.sign(multiplier);applyDamageFromMessage({message,multiplier,addend:adjustment,promptModifier:!1,rollIndex})}}},default:"ok",close:()=>{toggleOffShieldBlock(message.id)}}).render(!0)}__name(shiftAdjustDamage,"shiftAdjustDamage"),__name2(shiftAdjustDamage,"shiftAdjustDamage");function toggleOffShieldBlock(messageId){$(`#chat-log > li.chat-message[data-message-id="${messageId}"]`).find("button.shield-block").removeClass("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:ordinal(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=event.target.closest(".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}`);return item instanceof ItemPF2e?item.isOfType("condition","effect")?createToggleEffectMacro(item,slot):__privateMethod(_a=_HotbarPF2e2,_createItemMacro,createItemMacro_fn).call(_a,item,slot):void 0}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}"); + <\/script>`,buttons:{ok:{label:"Ok",callback:async $dialog=>{const adjustment=(Number($dialog.find("[name=modifier]").val())||0)*Math.sign(multiplier);applyDamageFromMessage({message,multiplier,addend:adjustment,promptModifier:!1,rollIndex})}}},default:"ok",close:()=>{toggleOffShieldBlock(message.id)}}).render(!0)}__name(shiftAdjustDamage,"shiftAdjustDamage"),__name2(shiftAdjustDamage,"shiftAdjustDamage");function toggleOffShieldBlock(messageId){$(`#chat-log > li.chat-message[data-message-id="${messageId}"]`).find("button.shield-block").removeClass("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:ordinal(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}"); if (!(item instanceof Item && item.isEmbedded && item.isOwner)) { ui.notifications.error("PF2E.MacroActionNoActorError", { localize: true }); } @@ -320,11 +322,11 @@ 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),__publicField(this,"extraFolders",{}),__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,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: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,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(),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",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")&&(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&&(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",!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}};_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];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.classList.contains("shield-block"))return __privateMethod(this,_onClickShieldBlock,onClickShieldBlock_fn).call(this,button,messageEl);const buttonClasses=["heal-damage","half-damage","full-damage","double-damage","triple-damage"];for(const cssClass of buttonClasses)if(button.classList.contains(cssClass)){const index=htmlClosest(button,".damage-application")?.dataset.rollIndex;return __privateMethod(this,_onClickDamageButton,onClickDamageButton_fn).call(this,message,cssClass,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,cssClass,shiftKey,index){const multiplier=(()=>{switch(cssClass){case"heal-damage":return-1;case"half-damage":return .5;case"full-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.ShieldHardnessLabel");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);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));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,spellOtherTraits,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"},spellLevels:{1:"PF2E.SpellLevel1",2:"PF2E.SpellLevel2",3:"PF2E.SpellLevel3",4:"PF2E.SpellLevel4",5:"PF2E.SpellLevel5",6:"PF2E.SpellLevel6",7:"PF2E.SpellLevel7",8:"PF2E.SpellLevel8",9:"PF2E.SpellLevel9",10:"PF2E.SpellLevel10"},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",pcsOnly:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.PCsOnly",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:ordinal(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)).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)),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/detail-item.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/spellcasting-spell-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/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/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/vehicle-details.hbs","systems/pf2e/templates/actors/vehicle/tabs/vehicle-actions.hbs","systems/pf2e/templates/actors/vehicle/tabs/vehicle-inventory.hbs","systems/pf2e/templates/actors/vehicle/tabs/vehicle-description.hbs","systems/pf2e/templates/actors/vehicle/tabs/vehicle-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,"loadedPacks",{Actor:{},Item:{}}),__publicField(this,"loadedSources",[]),__publicField(this,"sourcesSettings"),this.sourcesSettings=game.settings.get("pf2e","compendiumBrowserSources")}async*loadPacks(documentType,packs,indexFields){this.loadedPacks[documentType]??={};const localize=localizer("PF2E.ProgressBar"),sources=__privateMethod(this,_getSources,getSources_fn).call(this),progress=new Progress({max:packs.length});for(const packId of packs){let data=this.loadedPacks[documentType][packId];if(data){const{pack}=data;progress.advance({label:localize("LoadingPack",{pack:pack?.metadata.label??""})})}else{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),data={pack,index:filteredIndex},this.loadedPacks[documentType][packId]=data}else{ui.notifications.warn(game.i18n.format("PF2E.BrowserWarnPackNotLoaded",{pack:pack.collection}));continue}}else continue}yield data}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.loadedPacks={Actor:{},Item:{}},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.SpellCantripLabel",selected:!1},this.filterData.checkboxes.traditions.options=this.generateCheckboxOptions(CONFIG.PF2E.magicTraditions);for(let i=1;i<=10;i++)this.filterData.checkboxes.level.options[`${i}`]={label:game.i18n.localize(`PF2E.SpellLevel${i}`),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)},"#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),__publicField(this,"extraFolders",{}),__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,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: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,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(),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",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")&&(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&&(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",!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}};_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.classList.contains("shield-block"))return __privateMethod(this,_onClickShieldBlock,onClickShieldBlock_fn).call(this,button,messageEl);const buttonClasses=["heal-damage","half-damage","full-damage","double-damage","triple-damage"];for(const cssClass of buttonClasses)if(button.classList.contains(cssClass)){const index=htmlClosest(button,".damage-application")?.dataset.rollIndex;return __privateMethod(this,_onClickDamageButton,onClickDamageButton_fn).call(this,message,cssClass,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,cssClass,shiftKey,index){const multiplier=(()=>{switch(cssClass){case"heal-damage":return-1;case"half-damage":return .5;case"full-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.ShieldHardnessLabel");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);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));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"},spellLevels:{1:"PF2E.SpellLevel1",2:"PF2E.SpellLevel2",3:"PF2E.SpellLevel3",4:"PF2E.SpellLevel4",5:"PF2E.SpellLevel5",6:"PF2E.SpellLevel6",7:"PF2E.SpellLevel7",8:"PF2E.SpellLevel8",9:"PF2E.SpellLevel9",10:"PF2E.SpellLevel10"},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",pcsOnly:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.PCsOnly",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:ordinal(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)),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/detail-item.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/spellcasting-spell-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/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/vehicle-details.hbs","systems/pf2e/templates/actors/vehicle/tabs/vehicle-actions.hbs","systems/pf2e/templates/actors/vehicle/tabs/vehicle-inventory.hbs","systems/pf2e/templates/actors/vehicle/tabs/vehicle-description.hbs","systems/pf2e/templates/actors/vehicle/tabs/vehicle-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,"loadedPacks",{Actor:{},Item:{}}),__publicField(this,"loadedSources",[]),__publicField(this,"sourcesSettings"),this.sourcesSettings=game.settings.get("pf2e","compendiumBrowserSources")}async*loadPacks(documentType,packs,indexFields){this.loadedPacks[documentType]??={};const localize=localizer("PF2E.ProgressBar"),sources=__privateMethod(this,_getSources,getSources_fn).call(this),progress=new Progress({max:packs.length});for(const packId of packs){let data=this.loadedPacks[documentType][packId];if(data){const{pack}=data;progress.advance({label:localize("LoadingPack",{pack:pack?.metadata.label??""})})}else{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),data={pack,index:filteredIndex},this.loadedPacks[documentType][packId]=data}else{ui.notifications.warn(game.i18n.format("PF2E.BrowserWarnPackNotLoaded",{pack:pack.collection}));continue}}else continue}yield data}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.loadedPacks={Actor:{},Item:{}},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.SpellCantripLabel",selected:!1},this.filterData.checkboxes.traditions.options=this.generateCheckboxOptions(CONFIG.PF2E.magicTraditions);for(let i=1;i<=10;i++)this.filterData.checkboxes.level.options[`${i}`]={label:game.i18n.localize(`PF2E.SpellLevel${i}`),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:`

${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=>{if(!event.detail.event.target)return;const value=event.detail.data.value,selected=data.selected.find(s=>s.value===value);if(selected){const current=!!selected.not;selected.not=!current,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())})}}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=[];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:this.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 _onSubmit(event,options={}){return event.preventDefault(),super._onSubmit(event,options)}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,default:"npcsOnly",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()}}),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 A D T F R",inline:"span",classes:["pf2-icon"],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 _UserPF2e=class extends User{static{__name(this,"_UserPF2e")}prepareData(){super.prepareData(),canvas.ready&&canvas.tokens.controlled.length>0&&game.pf2e.effectPanel.refresh()}prepareBaseData(){super.prepareBaseData(),this.flags=mergeObject({pf2e:{settings:{showEffectPanel:!0,showRollDialogs:!0,searchPackContents:!1,monochromeDarkvision:!0}}},this.flags)}get settings(){return this.flags.pf2e.settings}clearTargets(){this.updateTokenTargets()}_onUpdate(changed,options,userId){if(super._onUpdate(changed,options,userId),game.user.id!==userId)return;const keys2=Object.keys(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))}};__name2(_UserPF2e,"UserPF2e");let UserPF2e=_UserPF2e;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")}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 _MigrationSummary2);if(existing)return existing.options=mergeObject(existing.options,options),existing}get template(){return"systems/pf2e/templates/system/migration-summary.hbs"}static get defaultOptions(){return{...super.defaultOptions,id:"migration-summary",width:400,height:"auto"}}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);$html.find(".docs-successful").text("...");try{this.isRemigrating=!0,this.options.troubleshoot=!1,$(event.currentTarget).prop("disabled",!0),await game.pf2e.system.remigrate({from:lowestSchemaVersion}),this.options.troubleshoot=!1,this.render(!1)}catch{return}}),$html.find("button[data-action=close]").on("click",()=>this.close())}};__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")]);resetActors(new Set(actorsToReprepare));const activeParty=game.actors.party;if(activeParty&&game.settings.get("pf2e","activePartyFolderState")&&(ui.actors.extraFolders[activeParty.id]=!0,ui.actors.render()),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))}),htmlQuery(html,".rollable[data-attack-roll]")?.addEventListener("click",event=>{this.actor.attackStatistic.roll(eventToRollParams(event))})}};__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)}),$html.find(".emits-sound i.hint").tooltipster({maxWidth:275,position:"right",theme:"crb-hover",content:game.i18n.localize("PF2E.Actor.Hazard.EmitsSound.Hint")}),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 _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 _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 _LootSheetPF2e=class extends ActorSheetPF2e{static{__name(this,"_LootSheetPF2e")}constructor(){super(...arguments),__privateAdd(this,_distributeCoins),__privateAdd(this,_lootNPCs)}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){super.activateListeners($html),this.isEditable&&($html.find(".split-coins").removeAttr("disabled").on("click",event=>__privateMethod(this,_distributeCoins,distributeCoins_fn).call(this,event)),$html.find(".loot-npcs").removeAttr("disabled").on("click",event=>__privateMethod(this,_lootNPCs,lootNPCs_fn).call(this,event)),$html.find("i.fa-info-circle.help[title]").tooltipster({maxWidth:275,position:"right",theme:"crb-hover",contentAsHTML:!0}))}async _onDropItem(event,itemData){return this.actor.id===itemData.actorId&&!this.actor.testUserPermission(game.user,"OWNER")?[]:super._onDropItem(event,itemData)}};_distributeCoins=new WeakSet,distributeCoins_fn=__name2(async function(event){event.preventDefault(),await new DistributeCoinsPopup(this.actor).render(!0)},"#distributeCoins"),_lootNPCs=new WeakSet,lootNPCs_fn=__name2(async function(event){event.preventDefault(),canvas.tokens.controlled.some(token=>token.actor?.id!==this.actor.id)?await new LootNPCsPopup(this.actor).render(!0):ui.notifications.warn("No tokens selected.")},"#lootNPCs"),__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(){const sheetData=await super.getData(),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(){const sheetData=await super.getData();(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)})}if(!this.isEditable)return;$html.find(".adjustment").on("click",event=>{const adjustment=String(event.target.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));$html.find(".item-control[data-action=generate-attack]").on("click",async event=>{const{actor}=this,itemId=event.currentTarget.closest(".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),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}),tagify$1(getInput("system.traits.otherTags"),{maxTags:6})}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={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,_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,spellLevels:CONFIG.PF2E.spellLevels,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}),$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=this.getOverlayFromEvent(event)?.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=this.getOverlayFromEvent(event),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=this.getOverlayFromEvent(event)?.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]:{}}}})}),$html.find("[data-action=overlay-delete]").on("click",async event=>{const overlay=this.getOverlayFromEvent(event);if(!overlay)return;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})}),$html.find("[data-action=overlay-add-property]").on("click",event=>{event.preventDefault();const overlay=this.getOverlayFromEvent(event),property=$(event.target).closest("[data-action=overlay-add-property]").attr("data-property");if(overlay&&overlay.system&&property&&!(property in overlay.system)){const value=(()=>{const scaling=this.item.getHeightenLayers().reverse();for(const entry of[...scaling,{system:this.item.system}])if(objectHasKey(entry.system,property))return entry.system[property]})();typeof value<"u"?this.item.update({[`${overlay.base}.${property}`]:value}):ui.notifications.warn(`PF2e System | Failed to initialize property ${property} for overlay`)}}),$html.find("[data-action=overlay-remove-property]").on("click",event=>{event.preventDefault();const overlayData=this.getOverlayFromEvent(event),property=$(event.target).closest("[data-action=overlay-remove-property]").attr("data-property");if(overlayData&&property){const updates={[`${overlayData.base}.-=${property}`]:null};property==="damage"&&(updates[`${overlayData.base}.-=heightening`]=null),this.item.update(updates)}}),$html.find("[data-action=change-level]").on("change",event=>{const overlay=this.getOverlayFromEvent(event);if(!overlay)return;const currentLevel=overlay.level,element=event.target,newLevel=Number(element.value),existingData=this.item.getHeightenLayers().find(layer=>layer.level===currentLevel);this.item.update({[`${overlay.collectionPath}.-=${currentLevel}`]:null,[`${overlay.collectionPath}.${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))}getOverlayFromEvent(event){const overlayEl=htmlClosest(event.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,collectionPath,base,dataPath:base,system}}};_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{level,system}=layer,collectionPath="system.heightening.levels",base=`${collectionPath}.${layer.level}`,missing=[];for(const[key,label]of Object.entries(spellOverridable))key in layer.system||missing.push({key,label});const heightenLevels=this.getAvailableHeightenLevels();return heightenLevels.push(level),heightenLevels.sort((a,b)=>a-b),{id:null,level,collectionPath,base,dataPath:base,type:"heighten",system,missing,heightenLevels}})},"#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 __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=>{if(!event.detail.event.target)return;const value=event.detail.data.value,selected=data.selected.find(s=>s.value===value);if(selected){const current=!!selected.not;selected.not=!current,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())})}}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=[];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:this.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 _onSubmit(event,options={}){return event.preventDefault(),super._onSubmit(event,options)}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,default:"npcsOnly",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()}}),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 _UserPF2e=class extends User{static{__name(this,"_UserPF2e")}prepareData(){super.prepareData(),canvas.ready&&canvas.tokens.controlled.length>0&&game.pf2e.effectPanel.refresh()}prepareBaseData(){super.prepareBaseData(),this.flags=mergeObject({pf2e:{settings:{showEffectPanel:!0,showRollDialogs:!0,searchPackContents:!1,monochromeDarkvision:!0}}},this.flags)}get settings(){return this.flags.pf2e.settings}clearTargets(){this.updateTokenTargets()}_onUpdate(changed,options,userId){if(super._onUpdate(changed,options,userId),game.user.id!==userId)return;const keys2=Object.keys(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))}};__name2(_UserPF2e,"UserPF2e");let UserPF2e=_UserPF2e;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")}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 _MigrationSummary2);if(existing)return existing.options=mergeObject(existing.options,options),existing}get template(){return"systems/pf2e/templates/system/migration-summary.hbs"}static get defaultOptions(){return{...super.defaultOptions,id:"migration-summary",width:400,height:"auto"}}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);$html.find(".docs-successful").text("...");try{this.isRemigrating=!0,this.options.troubleshoot=!1,$(event.currentTarget).prop("disabled",!0),await game.pf2e.system.remigrate({from:lowestSchemaVersion}),this.options.troubleshoot=!1,this.render(!1)}catch{return}}),$html.find("button[data-action=close]").on("click",()=>this.close())}};__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")]);resetActors(new Set(actorsToReprepare));const activeParty=game.actors.party;if(activeParty&&game.settings.get("pf2e","activePartyFolderState")&&(ui.actors.extraFolders[activeParty.id]=!0,ui.actors.render()),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))}),htmlQuery(html,".rollable[data-attack-roll]")?.addEventListener("click",event=>{this.actor.attackStatistic.roll(eventToRollParams(event))})}};__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)}),$html.find(".emits-sound i.hint").tooltipster({maxWidth:275,position:"right",theme:"crb-hover",content:game.i18n.localize("PF2E.Actor.Hazard.EmitsSound.Hint")}),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(){const sheetData=await super.getData(),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(){const sheetData=await super.getData();(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)})}if(!this.isEditable)return;$html.find(".adjustment").on("click",event=>{const adjustment=String(event.target.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));$html.find(".item-control[data-action=generate-attack]").on("click",async event=>{const{actor}=this,itemId=event.currentTarget.closest(".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),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={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,_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,spellLevels:CONFIG.PF2E.spellLevels,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}),$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=this.getOverlayFromEvent(event)?.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=this.getOverlayFromEvent(event),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=this.getOverlayFromEvent(event)?.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]:{}}}})}),$html.find("[data-action=overlay-delete]").on("click",async event=>{const overlay=this.getOverlayFromEvent(event);if(!overlay)return;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})}),$html.find("[data-action=overlay-add-property]").on("click",event=>{event.preventDefault();const overlay=this.getOverlayFromEvent(event),property=$(event.target).closest("[data-action=overlay-add-property]").attr("data-property");if(overlay&&overlay.system&&property&&!(property in overlay.system)){const value=(()=>{const scaling=this.item.getHeightenLayers().reverse();for(const entry of[...scaling,{system:this.item.system}])if(objectHasKey(entry.system,property))return entry.system[property]})();typeof value<"u"?this.item.update({[`${overlay.base}.${property}`]:value}):ui.notifications.warn(`PF2e System | Failed to initialize property ${property} for overlay`)}}),$html.find("[data-action=overlay-remove-property]").on("click",event=>{event.preventDefault();const overlayData=this.getOverlayFromEvent(event),property=$(event.target).closest("[data-action=overlay-remove-property]").attr("data-property");if(overlayData&&property){const updates={[`${overlayData.base}.-=${property}`]:null};property==="damage"&&(updates[`${overlayData.base}.-=heightening`]=null),this.item.update(updates)}}),$html.find("[data-action=change-level]").on("change",event=>{const overlay=this.getOverlayFromEvent(event);if(!overlay)return;const currentLevel=overlay.level,element=event.target,newLevel=Number(element.value),existingData=this.item.getHeightenLayers().find(layer=>layer.level===currentLevel);this.item.update({[`${overlay.collectionPath}.-=${currentLevel}`]:null,[`${overlay.collectionPath}.${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))}getOverlayFromEvent(event){const overlayEl=htmlClosest(event.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,collectionPath,base,dataPath:base,system}}};_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{level,system}=layer,collectionPath="system.heightening.levels",base=`${collectionPath}.${layer.level}`,missing=[];for(const[key,label]of Object.entries(spellOverridable))key in layer.system||missing.push({key,label});const heightenLevels=this.getAvailableHeightenLevels();return heightenLevels.push(level),heightenLevels.sort((a,b)=>a-b),{id:null,level,collectionPath,base,dataPath:base,type:"heighten",system,missing,heightenLevels}})},"#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(); diff --git a/Data/systems/pf2e/styles/pf2e.css b/Data/systems/pf2e/styles/pf2e.css index 7a2b0efb..3faaf156 100644 --- a/Data/systems/pf2e/styles/pf2e.css +++ b/Data/systems/pf2e/styles/pf2e.css @@ -542,6 +542,7 @@ --font-size-21: 1.3125rem; --font-size-22: 1.375rem; --font-size-26: 1.625rem; + --font-size-27: 1.6875rem; --font-size-30: 1.875rem; --font-size-34: 2.125rem; --font-size-36: 2.25rem; @@ -1367,7 +1368,7 @@ button:active { } /** * DEFAULT STYLE OF THE SIDETIP PLUGIN - * + * * All styles are "namespaced" with .tooltipster-sidetip to prevent * conflicts between plugins. */ @@ -1663,6 +1664,9 @@ a.foundry-href { a.content-link { line-height: 1.6em; } +a.content-link:has(i.fa-sparkles) { + font-style: italic; +} #tooltip a.content-link { color: var(--color-text-dark-primary); } @@ -2102,6 +2106,24 @@ a[href]:hover { font-size: 2em; line-height: 1.2; } +#tooltip.pf2e { + 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); + background: rgba(0, 0, 0, 0.9); + font-size: var(--font-size-14); + padding: 0.25rem 0; + text-align: left; +} +#tooltip.pf2e h1, +#tooltip.pf2e h2, +#tooltip.pf2e h3 { + font-size: var(--font-size-12); + font-weight: 500; + text-align: left; +} /* ----------------------------------------- */ /* Upstream Overrides */ /* ----------------------------------------- */ @@ -3818,31 +3840,33 @@ section.compendium-sidebar ol.directory-list ol.document-matches li.match .detai border-left-color: rgba(255, 255, 255, 0.5); } .attribute-builder .window-content .row-heading { + align-items: center; display: grid; - grid-template-columns: 42px 1fr auto; grid-template-areas: "img description remaining"; - align-items: center; + grid-template-columns: 42px 1fr auto; } .attribute-builder .window-content .row-heading h3 { - grid-column: 1/4; align-self: start; font-size: var(--font-size-24); + grid-column: 1/4; } .attribute-builder .window-content .row-heading .hint-container { grid-column: 1/4; } .attribute-builder .window-content .row-heading img { - grid-area: img; border: 0; + grid-area: img; + height: 2rem; + width: 2rem; } .attribute-builder .window-content .row-heading div.label { - grid-area: description; display: flex; flex-direction: column; + grid-area: description; + margin-right: 10px; overflow: hidden; - white-space: nowrap; text-overflow: ellipsis; - margin-right: 10px; + white-space: nowrap; } .attribute-builder .window-content .row-heading div.remaining { grid-area: remaining; @@ -3891,9 +3915,9 @@ section.compendium-sidebar ol.directory-list ol.document-matches li.match .detai width: 6em; } .attribute-builder .window-content .row-column button > i.key-attribute { + bottom: 3px; font-size: smaller; left: 2px; - margin-top: 1px; position: absolute; } .attribute-builder .window-content .row-column button.boost, .attribute-builder .window-content .row-column button.apex { @@ -4035,7 +4059,9 @@ section.compendium-sidebar ol.directory-list ol.document-matches li.match .detai text-transform: uppercase; } .attribute-builder .window-content div[data-tooltip-content].description, -.attribute-builder .window-content div[data-tooltip-content] .description { +.attribute-builder .window-content div[data-tooltip-content] .description, +.attribute-builder .window-content div[data-tooltip].description, +.attribute-builder .window-content div[data-tooltip] .description { text-decoration: underline dotted; text-underline-offset: 2px; } @@ -4706,7 +4732,7 @@ body > .choices__list--dropdown { position: relative; font-size: var(--font-size-16); height: 24px; - width: 24px; + min-width: 24px; } .actor.sheet .item-image.framed { background-color: var(--tertiary); @@ -5162,7 +5188,7 @@ body > .choices__list--dropdown { align-items: center; column-gap: 0.5rem; display: grid; - grid: "icon name tracking controls" 1fr "icon buttons tracking controls" auto "summary summary summary summary" auto/min-content auto 20% 10%; + grid: "icon name tracking controls" 1fr "icon buttons tracking controls" auto "summary summary summary summary" auto/min-content 1fr 20% 10%; } .actor.sheet.character .attack-popout ol.actions-list li.action > .icon { grid-area: icon; @@ -8650,7 +8676,7 @@ body > .choices__list--dropdown { align-items: center; column-gap: 0.5rem; display: grid; - grid: "icon name tracking controls" 1fr "icon buttons tracking controls" auto "summary summary summary summary" auto/min-content auto 20% 10%; + grid: "icon name tracking controls" 1fr "icon buttons tracking controls" auto "summary summary summary summary" auto/min-content 1fr 20% 10%; } .actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.action > .icon { grid-area: icon; @@ -9169,7 +9195,6 @@ body > .choices__list--dropdown { align-items: baseline; display: block; flex: 0; - padding-right: 16px; } .spellcasting-entry.preparation .sheet-header h1 { display: flex; @@ -9181,16 +9206,25 @@ body > .choices__list--dropdown { justify-content: space-between; } .spellcasting-entry.preparation .sheet-header p.hint { - margin: auto auto 1em; + margin: auto auto 0.5em; } .spellcasting-entry.preparation .sheet-header .item-controls { flex: 0; white-space: nowrap; } +.spellcasting-entry.preparation .sheet-header .search { + margin-bottom: 0.5em; +} .spellcasting-entry.preparation .sheet-content { overflow: hidden scroll; padding-bottom: 1em; - padding-right: 8px; + padding-right: 6px; +} +.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); @@ -11002,11 +11036,6 @@ body > .choices__list--dropdown { flex-direction: row; justify-content: space-between; } -.actor.npc.sheet form .npc-sheet-header .paizo-style { - margin-top: 2px; - padding-left: 0; - padding-right: 0; -} .actor.npc.sheet form hr { margin: 10px 6px 10px 0; } @@ -11233,49 +11262,11 @@ body > .choices__list--dropdown { .actor.npc.sheet form .sheet-body .inventory.active { display: flex; } -.actor.npc.sheet form .sheet-body .inventory .expandable { - display: none; -} -.actor.npc.sheet form .sheet-body .inventory .section-container.inventory-toggles { - padding: 4px 6px 6px 6px; -} .actor.npc.sheet form .sheet-body .inventory .inventory-section { - --border-color: var(--secondary); - flex: 1 0 auto; - padding: 0px; - margin: 0px; max-height: calc(100% - 1rem); } -.actor.npc.sheet form .sheet-body .inventory .inventory-section .coinage { - margin-bottom: 8px; -} -.actor.npc.sheet form .sheet-body .inventory .inventory-section .inventory-list > :first-child { - border-radius: 3px 3px 0px 0px; -} -.actor.npc.sheet form .sheet-body .inventory .inventory-section .inventory-list .inventory-header { - align-items: center; +.actor.npc.sheet form .sheet-body .inventory .inventory-section .inventory-header { background-color: var(--primary-background); - color: var(--color-text-light-0); - display: flex; - flex-flow: row nowrap; - max-height: fit-content; -} -.actor.npc.sheet form .sheet-body .inventory .inventory-section .inventory-list .inventory-header h4 { - margin: 0; -} -.actor.npc.sheet form .sheet-body .inventory .inventory-section .inventory-list .inventory-header div { - border: none; -} -.actor.npc.sheet form .sheet-body .inventory .inventory-section .inventory-list .item .item-image { - border: 2px solid #7a7971; - border-radius: 3px; - margin: 2px 4px 2px 6px; -} -.actor.npc.sheet form .sheet-body .inventory .inventory-section .inventory-list .item .controls .item-toggle-equip { - color: rgba(0, 0, 0, 0.4); -} -.actor.npc.sheet form .sheet-body .inventory .inventory-section .inventory-list .item .controls .item-toggle-equip.active { - color: rgba(0, 0, 0, 0.75); } .actor.npc.sheet form .sheet-body .entries-list { list-style: none; @@ -11927,9 +11918,7 @@ body > .choices__list--dropdown { flex: auto 0 0; padding: 4px; height: auto; - font-family: var(--sans-serif); font-weight: 500; - text-transform: uppercase; } .actor.npc.sheet form select option { color: var(--text-light); @@ -12072,7 +12061,7 @@ body > .choices__list--dropdown { flex-direction: row; height: 100%; } -.sheet.actor.loot section.sidebar { +.sheet.actor.loot form section.sidebar { display: flex; flex-direction: column; width: 200px; @@ -12080,62 +12069,67 @@ body > .choices__list--dropdown { border-right: 1px solid var(--color-text-light-7); box-shadow: 0 0 8px rgba(0, 0, 0, 0.2); } -.sheet.actor.loot section.sidebar > * { +.sheet.actor.loot form section.sidebar > * { flex: 0; } -.sheet.actor.loot section.sidebar .image-container { +.sheet.actor.loot form section.sidebar .image-container { display: flex; } -.sheet.actor.loot section.sidebar .image-container > img.actor-image { +.sheet.actor.loot form section.sidebar .image-container > img.actor-image { flex: none; border: none; border-bottom: 1px solid var(--color-text-light-7); } -.sheet.actor.loot section.sidebar .image-container [data-action=show-image] { +.sheet.actor.loot form section.sidebar .image-container [data-action=show-image] { bottom: 3px; right: 2px; } -.sheet.actor.loot section.sidebar .gm-settings { +.sheet.actor.loot form section.sidebar .gm-settings { border-bottom: 1px solid var(--color-text-light-7); display: flex; flex-direction: column; padding: 0.25rem; } -.sheet.actor.loot section.sidebar .gm-settings .loot-distribution { - box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.3), inset 0 0 0 2px rgba(255, 255, 255, 0.2); +.sheet.actor.loot form section.sidebar .gm-settings .loot-distribution { + display: flex; + flex-direction: column; + gap: 2px; +} +.sheet.actor.loot form section.sidebar .gm-settings .loot-distribution button { background-color: var(--tertiary); } -.sheet.actor.loot section.sidebar .gm-settings label { - display: flex; - align-items: center; - font-weight: bold; +.sheet.actor.loot form section.sidebar .gm-settings .loot-distribution button:not(:hover) { + box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.3), inset 0 0 0 2px rgba(255, 255, 255, 0.2); } -.sheet.actor.loot section.sidebar .sidebar-meta { +.sheet.actor.loot form section.sidebar .gm-settings label { + font-weight: 500; +} +.sheet.actor.loot form section.sidebar .sidebar-meta { border-top: 1px solid var(--color-text-light-7); } -.sheet.actor.loot section.sidebar .hidden-when-empty, -.sheet.actor.loot section.sidebar .bulk { +.sheet.actor.loot form section.sidebar .hidden-when-empty, +.sheet.actor.loot form section.sidebar .bulk { align-self: end; } -.sheet.actor.loot section.sidebar .bulk { +.sheet.actor.loot form section.sidebar .bulk { line-height: 1.5em; margin-right: 8px; } -.sheet.actor.loot section.sidebar > .editor, -.sheet.actor.loot section.sidebar .description { +.sheet.actor.loot form section.sidebar > .editor, +.sheet.actor.loot form section.sidebar .description { flex-basis: auto; min-height: 40px; flex: 1; } -.sheet.actor.loot section.sidebar > .editor > .tox-tinymce .tox-edit-area { +.sheet.actor.loot form section.sidebar > .editor > .tox-tinymce .tox-edit-area { min-height: 120px; } -.sheet.actor.loot section.sidebar .description, -.sheet.actor.loot section.sidebar .editor-content { +.sheet.actor.loot form section.sidebar .description, +.sheet.actor.loot form section.sidebar .editor-content { padding: 0.25rem; overflow: hidden scroll; } -.sheet.actor.loot .sheet-header { +.sheet.actor.loot form .sheet-header { display: flex; flex-direction: row; align-items: center; @@ -12144,72 +12138,72 @@ body > .choices__list--dropdown { border-bottom: 1px solid var(--color-text-light-7); box-shadow: 0 0 8px rgba(0, 0, 0, 0.2); } -.sheet.actor.loot .sheet-header h1 { +.sheet.actor.loot form .sheet-header h1 { margin: 0; border: none; flex: 1; padding-left: 0.5rem; } -.sheet.actor.loot .sheet-header h1 > input { +.sheet.actor.loot form .sheet-header h1 > input { height: 40px; width: 100%; margin: 2px; border: none; } -.sheet.actor.loot .sheet-header h1, -.sheet.actor.loot .sheet-header input { +.sheet.actor.loot form .sheet-header h1, +.sheet.actor.loot form .sheet-header input { font-family: var(--serif-condensed); font-size: var(--font-size-36); font-weight: 700; } -.sheet.actor.loot .sheet-header .sheet-type i { +.sheet.actor.loot form .sheet-header .sheet-type i { padding: 0 0.25rem 0 0.5rem; font-size: var(--font-size-16); } -.sheet.actor.loot .sheet-header .tags { +.sheet.actor.loot form .sheet-header .tags { align-items: center; display: flex; flex: 0 0 auto; margin-left: auto; margin-right: 0.5em; } -.sheet.actor.loot .sheet-header .tags .tag { +.sheet.actor.loot form .sheet-header .tags .tag { color: var(--text-light); font-size: var(--font-size-16); height: unset; padding: 0.1em 0.4em; } -.sheet.actor.loot .sheet-header .tags .tag option { +.sheet.actor.loot form .sheet-header .tags .tag option { background-color: #5e0000; color: inherit; font-size: inherit; } -.sheet.actor.loot .sheet-header .currency { +.sheet.actor.loot form .sheet-header .currency { margin-bottom: 8px; } -.sheet.actor.loot .sheet-body { +.sheet.actor.loot form .sheet-body { padding: 0.5rem; } -.sheet.actor.loot section.content { +.sheet.actor.loot form section.content { display: flex; flex-direction: column; flex: 1; height: 100%; } -.sheet.actor.loot section.content .inventory { +.sheet.actor.loot form section.content .inventory { overflow: hidden; } -.sheet.actor.loot section.content .inventory .inventory-list { +.sheet.actor.loot form section.content .inventory .inventory-list { --border-color: var(--secondary-background); margin-bottom: 2px; } -.sheet.actor.loot section.content .inventory .inventory-list .item-controls { +.sheet.actor.loot form section.content .inventory .inventory-list .item-controls { flex: 0 0 4rem; } -.sheet.actor.loot section.content .inventory .inventory-list .item-controls a.item-toggle-equip { +.sheet.actor.loot form section.content .inventory .inventory-list .item-controls a.item-toggle-equip { display: none; } -.sheet.actor.loot section.content .inventory .inventory-header { +.sheet.actor.loot form section.content .inventory .inventory-header { background: var(--primary-background); color: var(--text-light); } @@ -15286,27 +15280,29 @@ body > .choices__list--dropdown { } #compendium-browser > section.window-content > .content-box .spell-browser dd, #license-viewer > section.window-content > .content-box .spell-browser dd { - text-transform: capitalize; display: inline-block; + text-transform: capitalize; } #compendium-browser > section.window-content > .content-box .spell-browser dd select, #license-viewer > section.window-content > .content-box .spell-browser dd select { - width: 6em; margin-left: 0.5em; + width: 6em; } #compendium-browser > section.window-content > .content-box .spell-browser ul.result-list, #license-viewer > section.window-content > .content-box .spell-browser ul.result-list { - width: 100%; - float: right; - display: block; - margin: 0; + display: flex; + flex-direction: column; height: 100%; + margin: 0; + padding: 0; + width: 100%; overflow: visible scroll; } #compendium-browser > section.window-content > .content-box .spell-browser ul.result-list > li, #license-viewer > section.window-content > .content-box .spell-browser ul.result-list > li { - line-height: var(--font-size-32); - margin: 2px 0; + align-items: center; + gap: 0.25rem; + padding: 0.125rem 0.25rem; } #compendium-browser > section.window-content > .content-box .spell-browser ul.result-list > li:nth-child(odd), #license-viewer > section.window-content > .content-box .spell-browser ul.result-list > li:nth-child(odd) { @@ -15314,47 +15310,35 @@ body > .choices__list--dropdown { } #compendium-browser > section.window-content > .content-box .spell-browser ul.result-list > li > *, #license-viewer > section.window-content > .content-box .spell-browser ul.result-list > li > * { - align-self: center; + align-items: center; + display: flex; + height: 2rem; + justify-content: center; } #compendium-browser > section.window-content > .content-box .spell-browser ul.result-list > li > .image, #license-viewer > section.window-content > .content-box .spell-browser ul.result-list > li > .image { - height: 32px; - max-width: 32px; + max-width: 2rem; } #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 { - line-height: 1em; - padding-left: 5px; -} -#compendium-browser > section.window-content > .content-box .spell-browser ul.result-list > li > .tags, -#license-viewer > section.window-content > .content-box .spell-browser ul.result-list > li > .tags { - justify-content: center; - margin-left: 0.5em; - max-width: 6em; + justify-content: start; } #compendium-browser > section.window-content > .content-box .spell-browser ul.result-list > li > .level, #license-viewer > section.window-content > .content-box .spell-browser ul.result-list > li > .level { flex-grow: 1; font-weight: 900; - height: 32px; - max-width: 18px; - text-align: center; + max-width: 1.5em; } #compendium-browser > section.window-content > .content-box .spell-browser ul.result-list > li > .price, #license-viewer > section.window-content > .content-box .spell-browser ul.result-list > li > .price { flex: none; - height: 32px; - margin-right: 10px; + justify-content: end; + margin-right: var(--font-size-10); min-width: 5em; - text-align: right; } #compendium-browser > section.window-content > .content-box .spell-browser ul.result-list > li > .end, #license-viewer > section.window-content > .content-box .spell-browser ul.result-list > li > .end { - font-weight: 900; - height: 32px; - margin-right: 3px; - max-width: 100px; - text-align: right; + margin-right: 0.5em; } #compendium-browser > section.window-content > .content-box .spell-browser ul.result-list > li:hover, #license-viewer > section.window-content > .content-box .spell-browser ul.result-list > li:hover { @@ -15551,6 +15535,11 @@ body > .choices__list--dropdown { opacity: 0.6; color: #a00; } +.pf2e.item.sheet.affliction form .affliction-stage .formula-row { + align-items: center; + display: flex; + gap: 4px; +} .pf2e.item.sheet.deity form .tab.details .checkbox-pair { align-items: center; display: flex; @@ -16463,6 +16452,9 @@ body > .choices__list--dropdown { align-items: baseline; gap: 2px; } +.pf2e.item.sheet form i.fa-info-circle { + cursor: help; +} .pf2e.item.sheet form > nav { display: flex; align-items: baseline; @@ -18092,6 +18084,7 @@ body > .choices__list--dropdown { height: 1.05rem; } .tags { + align-items: center; display: flex; flex-wrap: wrap; gap: 2px; @@ -18111,10 +18104,9 @@ body > .choices__list--dropdown { border-radius: 2px; box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.5); color: var(--color-text-trait); - display: flex; + display: inline-flex; font-weight: 500; - height: var(--font-size-18); - padding: 0 0.33em; + padding: 0.3em; } .tags .tag.tag_secondary, .tags .tag option.tag_secondary { @@ -18139,24 +18131,47 @@ body > .choices__list--dropdown { box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.3); color: var(--color-text-dark-secondary); font-family: var(--font-primary); - font-size: var(--font-size-10); - height: unset; + line-height: 1.6em; + padding: 0 0.5em; text-transform: none; } +.tags .tag.rarity.common, .tags .tag.rarity[value=common], +.tags .tag.rarity > option[value=common], +.tags .tag option.rarity.common, +.tags .tag option.rarity[value=common], +.tags .tag option.rarity > option[value=common] { + background-color: var(--color-rarity-common); +} +.tags .tag.rarity.uncommon, .tags .tag.rarity[value=uncommon], +.tags .tag.rarity > option[value=uncommon], +.tags .tag option.rarity.uncommon, +.tags .tag option.rarity[value=uncommon], +.tags .tag option.rarity > option[value=uncommon] { + background-color: var(--color-rarity-uncommon); +} +.tags .tag.rarity.rare, .tags .tag.rarity[value=rare], +.tags .tag.rarity > option[value=rare], +.tags .tag option.rarity.rare, +.tags .tag option.rarity[value=rare], +.tags .tag option.rarity > option[value=rare] { + background-color: var(--color-rarity-rare); +} +.tags .tag.rarity.unique, .tags .tag.rarity[value=unique], +.tags .tag.rarity > option[value=unique], +.tags .tag option.rarity.unique, +.tags .tag option.rarity[value=unique], +.tags .tag option.rarity > option[value=unique] { + background-color: var(--color-rarity-unique); +} .tags .tag.mystified, .tags .tag option.mystified { opacity: 0.7; } -li.chat-message .tags .tag_transparent { - line-height: 1.25em; - padding: 0.1em 0.25em; -} .tags.paizo-style { - align-items: center; border: none; border-radius: 3px; - padding: 0.05em; gap: 0; + padding: 0.5em 0.05em; } .tags.paizo-style tag, .tags.paizo-style .tag, @@ -18180,7 +18195,6 @@ li.chat-message .tags .tag_transparent { .tags.paizo-style tag, .tags.paizo-style select.tag { border-width: 2px 3px 2px 2px; - height: var(--font-size-22); } .tags.paizo-style tag:first-child, .tags.paizo-style select.tag:first-child { @@ -18195,7 +18209,6 @@ li.chat-message .tags .tag_transparent { } .tags.paizo-style .tag { border-width: 1px 2px 1px 1px; - height: var(--font-size-19); } .tags.paizo-style .tag:first-child { border-left-width: 3px; @@ -18203,22 +18216,6 @@ li.chat-message .tags .tag_transparent { .tags.paizo-style .tag:last-child { border-right-width: 3px; } -.tags.paizo-style .tag.rarity.common, .tags.paizo-style .tag.rarity[value=common], -.tags.paizo-style .tag.rarity > option[value=common] { - background-color: var(--color-rarity-common); -} -.tags.paizo-style .tag.rarity.uncommon, .tags.paizo-style .tag.rarity[value=uncommon], -.tags.paizo-style .tag.rarity > option[value=uncommon] { - background-color: var(--color-rarity-uncommon); -} -.tags.paizo-style .tag.rarity.rare, .tags.paizo-style .tag.rarity[value=rare], -.tags.paizo-style .tag.rarity > option[value=rare] { - background-color: var(--color-rarity-rare); -} -.tags.paizo-style .tag.rarity.unique, .tags.paizo-style .tag.rarity[value=unique], -.tags.paizo-style .tag.rarity > option[value=unique] { - background-color: var(--color-rarity-unique); -} .tags.paizo-style .tag.alignment { background-color: var(--color-bg-alignment); } @@ -18226,18 +18223,12 @@ li.chat-message .tags .tag_transparent { background-color: var(--color-bg-size); } .tags.paizo-style tag > div { - padding: 0 0.09rem 0 0.25rem; -} -.tags.paizo-style tag > div, -.tags.paizo-style .tag, -.tags.paizo-style select { border-radius: 0; display: flex; font: 500 var(--font-size-10) var(--sans-serif); + padding: 0 0.09rem 0 0.25rem; } -.tags.paizo-style tag > div .tagify__tag-text, -.tags.paizo-style .tag .tagify__tag-text, -.tags.paizo-style select .tagify__tag-text { +.tags.paizo-style tag > div .tagify__tag-text { text-transform: uppercase; } .tags.paizo-style hr.vr { @@ -18253,8 +18244,12 @@ li.chat-message .tags .tag_transparent { .tags.paizo-style[disabled] > .tagify__input { display: none; } +.chat-message .tags { + line-height: normal; +} tags.tags.paizo-style { background-color: rgba(0, 0, 0, 0.075); + padding: 0; --tag-bg: var(--color-bg-trait); --tag-hover: var(--color-bg-trait); --tag-remove-btn-color: var(--color-text-trait); @@ -18284,6 +18279,9 @@ tags.tags.paizo-style .conjunction-not .tagify__tag-text { text-decoration: line-through; text-decoration-color: var(--color-text-trait); } +tags.tags.paizo-style tag { + height: var(--font-size-27); +} tags.tags.paizo-style tag[readonly=true] { padding-right: 2px; } diff --git a/Data/systems/pf2e/system.json b/Data/systems/pf2e/system.json index 8adc7555..7814a72b 100644 --- a/Data/systems/pf2e/system.json +++ b/Data/systems/pf2e/system.json @@ -3,7 +3,7 @@ "title": "Pathfinder 2nd Edition", "description": "A community contributed game system for Pathfinder Second Edition", "license": "./LICENSE", - "version": "5.7.2", + "version": "5.7.3", "compatibility": { "minimum": "11.308", "verified": "11.313", @@ -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/latest/download/pf2e.zip" + "download": "https://github.com/foundryvtt/pf2e/releases/download/5.7.3/pf2e.zip" } diff --git a/Data/systems/pf2e/templates/actors/character/attribute-builder.hbs b/Data/systems/pf2e/templates/actors/character/attribute-builder.hbs index 6ef2cb61..eb26e9b7 100644 --- a/Data/systems/pf2e/templates/actors/character/attribute-builder.hbs +++ b/Data/systems/pf2e/templates/actors/character/attribute-builder.hbs @@ -1,4 +1,4 @@ - +
@@ -18,7 +18,7 @@ {{#if ancestryBoosts}}
{{#if ancestryBoosts.remaining}}
{{ancestryBoosts.remaining}}
{{/if}} - + {{ancestry.name}}
{{localize "TYPES.Item.ancestry"}}
{{ancestry.name}}
@@ -42,13 +42,13 @@

{{localize "PF2E.Actor.Character.AttributeBuilder.Boosts"}}

    {{#each ancestryBoosts.labels as |boost|}} -
  • {{boost}}
  • +
  • {{boost}}
  • {{/each}}

{{localize "PF2E.Actor.Character.AttributeBuilder.Flaws"}}

    {{#each ancestryBoosts.flawLabels as |flaw|}} -
  • {{flaw}}
  • +
  • {{flaw}}
  • {{/each}}
@@ -60,10 +60,10 @@
{{#if voluntaryFlaws.remaining}}
{{voluntaryFlaws.remaining}}
{{/if}}
-
+
{{localize "PF2E.Actor.Character.AttributeBuilder.VoluntaryFlaw.Title"}}
-
{{> attributeRow buttons=voluntaryFlaws.buttons}} {{/if}} - -
{{localize "PF2E.Actor.Character.AttributeBuilder.VoluntaryFlaw.Description"}}
-
{{localize "PF2E.Actor.Character.AttributeBuilder.VoluntaryFlaw.LegacyDescription"}}

@@ -83,7 +80,7 @@ {{#if backgroundBoosts}}
{{#if backgroundBoosts.remaining}}
{{backgroundBoosts.remaining}}
{{/if}} - + {{background.name}}
{{localize "PF2E.Background"}}
{{background.name}}
@@ -122,7 +119,7 @@
{{#if class}}
- + {{class.name}}
{{localize "PF2E.Class"}}
{{class.name}}
@@ -273,7 +270,7 @@ type="button" data-attribute="{{attribute}}" data-action="{{type}}" - class="tooltip boost-button {{type}} {{number}}{{#if button.selected}} selected{{#if button.partial}} partial{{/if}}{{/if}}{{#if button.locked}} locked{{/if}}" + class="boost-button {{type}} {{number}}{{#if button.selected}} selected{{#if button.partial}} partial{{/if}}{{/if}}{{#if button.locked}} locked{{/if}}" {{disabled (and button.disabled (not button.selected))}} > {{#if button.locked}}{{/if}} diff --git a/Data/systems/pf2e/templates/actors/character/partials/strike.hbs b/Data/systems/pf2e/templates/actors/character/partials/strike.hbs index 408f88c3..0b486e2b 100644 --- a/Data/systems/pf2e/templates/actors/character/partials/strike.hbs +++ b/Data/systems/pf2e/templates/actors/character/partials/strike.hbs @@ -9,7 +9,14 @@

{{action.label}} - {{#if action.item.isTemporary}}{{/if}} + {{#if action.item.isTemporary}} + + {{/if}}

{{/unless}} diff --git a/Data/systems/pf2e/templates/actors/loot/sheet.hbs b/Data/systems/pf2e/templates/actors/loot/sheet.hbs index 86d623dc..76c86ec5 100644 --- a/Data/systems/pf2e/templates/actors/loot/sheet.hbs +++ b/Data/systems/pf2e/templates/actors/loot/sheet.hbs @@ -14,7 +14,12 @@ {{/if}}
{{#if user.isGM}} - : {{localize "PF2E.loot.LootDescription"}}

{{localize "PF2E.loot.MerchantLabel"}}: {{localize "PF2E.loot.MerchantDescription"}}

">
+
{{localize "PF2E.loot.MerchantLabel"}}: {{localize "PF2E.loot.MerchantDescription"}}
" + data-tooltip-class="pf2e" + data-tooltip-direction="LEFT" + >
- -
+
+
+ + +
+
+ + +
+
{{/if}} {{#if owner}} diff --git a/Data/systems/pf2e/templates/actors/partials/item-summary.hbs b/Data/systems/pf2e/templates/actors/partials/item-summary.hbs index 1a2549e7..f979694e 100644 --- a/Data/systems/pf2e/templates/actors/partials/item-summary.hbs +++ b/Data/systems/pf2e/templates/actors/partials/item-summary.hbs @@ -1,8 +1,8 @@ {{#if identified}} {{#if item.system.traits}} -
+
{{#if rarityLabel}} - {{localize rarityLabel}} + {{localize rarityLabel}} {{/if}} {{#each chatData.traits as |trait|}} {{localize trait.label}} diff --git a/Data/systems/pf2e/templates/actors/spellcasting-prep-sheet.hbs b/Data/systems/pf2e/templates/actors/spellcasting-prep-sheet.hbs index 8ccf12f0..4c05ffc5 100644 --- a/Data/systems/pf2e/templates/actors/spellcasting-prep-sheet.hbs +++ b/Data/systems/pf2e/templates/actors/spellcasting-prep-sheet.hbs @@ -1,4 +1,4 @@ - +

{{entry.name}} @@ -16,19 +16,31 @@ {{/if}}

+

+
    {{#unless entry.spellPrepList}} {{#if @root.options.editable}}
  1. {{localize "PF2E.SpellSlotEmpty"}}

    - - {{localize "PF2E.AddSpellTitle"}} - - - {{localize "PF2E.OpenSpellBrowserTitle"}} - + {{localize "PF2E.AddSpellTitle"}} + {{localize "PF2E.OpenSpellBrowserTitle"}}
  2. {{/if}} {{/unless}} @@ -49,10 +61,22 @@
    {{localize "PF2E.SpellComponentsLabel"}}
    {{#if @root.options.editable}}
    - - + +
    {{/if}} @@ -61,7 +85,7 @@
  3. - {{spell.name}} + {{spell.name}}

    {{spell.name}}{{{actionGlyph spell.system.time.value}}}

    @@ -87,17 +111,17 @@
    {{/if}} {{/unless}} {{#if @root.editable}}
    - - + +
    {{/if}}
  4. diff --git a/Data/systems/pf2e/templates/chat/action-card.hbs b/Data/systems/pf2e/templates/chat/action-card.hbs index 53a6e1d1..94524772 100644 --- a/Data/systems/pf2e/templates/chat/action-card.hbs +++ b/Data/systems/pf2e/templates/chat/action-card.hbs @@ -1,13 +1,13 @@
    - + {{item.name}}

    {{item.name}}

    -
    - {{#each data.traits}} +
    + {{#each data.traits as |trait|}} {{#unless trait.mystified}} - {{localize this.label}} + {{localize trait.label}} {{/unless}} {{/each}}
    diff --git a/Data/systems/pf2e/templates/chat/action/flavor.hbs b/Data/systems/pf2e/templates/chat/action/flavor.hbs index 997f2f29..bc2fbc4e 100644 --- a/Data/systems/pf2e/templates/chat/action/flavor.hbs +++ b/Data/systems/pf2e/templates/chat/action/flavor.hbs @@ -1,8 +1,8 @@ {{> systems/pf2e/templates/chat/action/header.hbs glyph=action.glyph subtitle=action.subtitle title=action.title}} {{#if traits}} -
    +
    {{#each traits as |trait|}} - {{localize trait.label}} + {{localize trait.label}} {{/each}}
    {{/if}} diff --git a/Data/systems/pf2e/templates/chat/action/self-effect.hbs b/Data/systems/pf2e/templates/chat/action/self-effect.hbs index af415cd5..50fa376d 100644 --- a/Data/systems/pf2e/templates/chat/action/self-effect.hbs +++ b/Data/systems/pf2e/templates/chat/action/self-effect.hbs @@ -1,7 +1,7 @@ {{#if description.full~}}
    {{{description.full}}}
    {{~else if description.preview~}} -
    + diff --git a/Data/systems/pf2e/templates/chat/affliction-card.hbs b/Data/systems/pf2e/templates/chat/affliction-card.hbs index 52b41fc3..932bf516 100644 --- a/Data/systems/pf2e/templates/chat/affliction-card.hbs +++ b/Data/systems/pf2e/templates/chat/affliction-card.hbs @@ -1,6 +1,6 @@
    - + {{item.name}}

    {{item.name}}

    @@ -9,7 +9,7 @@
    {{#if actor}}
    - +
    {{/if}}
    diff --git a/Data/systems/pf2e/templates/chat/armor-card.hbs b/Data/systems/pf2e/templates/chat/armor-card.hbs index e62aa6a2..a12a1632 100644 --- a/Data/systems/pf2e/templates/chat/armor-card.hbs +++ b/Data/systems/pf2e/templates/chat/armor-card.hbs @@ -1,15 +1,19 @@
    - + {{item.name}}

    {{item.name}}

    -
    - {{#if item.isIdentified}} - {{localize data.rarity.label}} +
    + {{#if (and item.isIdentified (ne item.rarity "common"))}} + {{localize data.rarity.label}} {{/if}} {{#each data.traits as |trait|}} {{#unless trait.mystified}} - {{localize trait.label}} + {{localize trait.label}} {{/unless}} {{/each}} {{#each data.properties as |property|}} diff --git a/Data/systems/pf2e/templates/chat/backpack-card.hbs b/Data/systems/pf2e/templates/chat/backpack-card.hbs index 6c37fdde..075977c8 100644 --- a/Data/systems/pf2e/templates/chat/backpack-card.hbs +++ b/Data/systems/pf2e/templates/chat/backpack-card.hbs @@ -1,15 +1,19 @@
    - + {{item.name}}

    {{item.name}}

    -
    - {{#if item.isIdentified}} - {{localize data.rarity.label}} +
    + {{#if (and item.isIdentified (ne item.rarity "common"))}} + {{localize data.rarity.label}} {{/if}} {{#each data.traits as |trait|}} {{#unless trait.mystified}} - {{localize trait.label}} + {{localize trait.label}} {{/unless}} {{/each}} {{#each data.properties as |property|}} diff --git a/Data/systems/pf2e/templates/chat/campaign-feature-card.hbs b/Data/systems/pf2e/templates/chat/campaign-feature-card.hbs index d526d878..3923464a 100644 --- a/Data/systems/pf2e/templates/chat/campaign-feature-card.hbs +++ b/Data/systems/pf2e/templates/chat/campaign-feature-card.hbs @@ -1,15 +1,15 @@
    - + {{item.name}}

    {{item.name}}

    -
    + +
    {{#each data.traits}} - {{#unless trait.mystified}} - {{localize this.label}} - {{/unless}} + {{localize this.label}} {{/each}}
    +
    {{{item.description}}}
    diff --git a/Data/systems/pf2e/templates/chat/check/target-dc-result.hbs b/Data/systems/pf2e/templates/chat/check/target-dc-result.hbs index b89e5528..197302a7 100644 --- a/Data/systems/pf2e/templates/chat/check/target-dc-result.hbs +++ b/Data/systems/pf2e/templates/chat/check/target-dc-result.hbs @@ -1,4 +1,4 @@ -
    +
    {{{dc.markup}}}
    -
    {{{result.markup}}}
    +
    {{{result.markup}}}
    diff --git a/Data/systems/pf2e/templates/chat/condition-card.hbs b/Data/systems/pf2e/templates/chat/condition-card.hbs index 2f5e1826..459eb7ee 100644 --- a/Data/systems/pf2e/templates/chat/condition-card.hbs +++ b/Data/systems/pf2e/templates/chat/condition-card.hbs @@ -1,6 +1,6 @@
    - + {{item.name}}

    {{item.name}}

    diff --git a/Data/systems/pf2e/templates/chat/consumable-card.hbs b/Data/systems/pf2e/templates/chat/consumable-card.hbs index 2de1fb4c..47e73f8c 100644 --- a/Data/systems/pf2e/templates/chat/consumable-card.hbs +++ b/Data/systems/pf2e/templates/chat/consumable-card.hbs @@ -1,16 +1,20 @@
    - + {{item.name}}

    {{item.name}}

    -
    - {{#if item.isIdentified}} - {{localize data.rarity.label}} +
    + {{#if (and item.isIdentified (ne item.rarity "common"))}} + {{localize data.rarity.label}} {{/if}} {{#each data.traits as |trait|}} {{#unless trait.mystified}} - {{localize trait.label}} + {{localize trait.label}} {{/unless}} {{/each}} {{#each data.properties as |property|}} diff --git a/Data/systems/pf2e/templates/chat/damage/damage-card-details.hbs b/Data/systems/pf2e/templates/chat/damage/damage-card-details.hbs index 29e1854e..365bd81c 100644 --- a/Data/systems/pf2e/templates/chat/damage/damage-card-details.hbs +++ b/Data/systems/pf2e/templates/chat/damage/damage-card-details.hbs @@ -1,7 +1,7 @@
    {{#each damageTypes as |data type|}}
    -

    {{localize data.label}}

    +

    {{localize data.label}}

    {{#each data.categories as |category|}}
    diff --git a/Data/systems/pf2e/templates/chat/effect-card.hbs b/Data/systems/pf2e/templates/chat/effect-card.hbs index 2f5e1826..459eb7ee 100644 --- a/Data/systems/pf2e/templates/chat/effect-card.hbs +++ b/Data/systems/pf2e/templates/chat/effect-card.hbs @@ -1,6 +1,6 @@
    - + {{item.name}}

    {{item.name}}

    diff --git a/Data/systems/pf2e/templates/chat/equipment-card.hbs b/Data/systems/pf2e/templates/chat/equipment-card.hbs index 33fbfc97..075977c8 100644 --- a/Data/systems/pf2e/templates/chat/equipment-card.hbs +++ b/Data/systems/pf2e/templates/chat/equipment-card.hbs @@ -1,15 +1,19 @@
    - + {{item.name}}

    {{item.name}}

    -
    - {{#if item.isIdentified}} - {{localize data.rarity.label}} +
    + {{#if (and item.isIdentified (ne item.rarity "common"))}} + {{localize data.rarity.label}} {{/if}} {{#each data.traits as |trait|}} {{#unless trait.mystified}} - {{localize trait.label}} + {{localize trait.label}} {{/unless}} {{/each}} {{#each data.properties as |property|}} diff --git a/Data/systems/pf2e/templates/chat/feat-card.hbs b/Data/systems/pf2e/templates/chat/feat-card.hbs index 49690bb3..f9bb92a7 100644 --- a/Data/systems/pf2e/templates/chat/feat-card.hbs +++ b/Data/systems/pf2e/templates/chat/feat-card.hbs @@ -1,16 +1,22 @@
    - + {{item.name}}

    {{item.name}} {{{actionGlyph item.system.actions.value}}}

    -
    - {{#each data.traits}} - {{#unless trait.mystified}} - {{localize this.label}} - {{/unless}} + +
    + {{#unless (eq data.rarity.name "common")}} + {{localize data.rarity.label}} + {{/unless}} + {{#each data.traits as |trait|}} + {{localize trait.label}} {{/each}}
    diff --git a/Data/systems/pf2e/templates/chat/melee-card.hbs b/Data/systems/pf2e/templates/chat/melee-card.hbs index 2cd96ff6..faf3975b 100644 --- a/Data/systems/pf2e/templates/chat/melee-card.hbs +++ b/Data/systems/pf2e/templates/chat/melee-card.hbs @@ -1,6 +1,6 @@
    - + {{item.name}}

    {{item.name}}

    diff --git a/Data/systems/pf2e/templates/chat/spell-card.hbs b/Data/systems/pf2e/templates/chat/spell-card.hbs index 082a0e99..88844f30 100644 --- a/Data/systems/pf2e/templates/chat/spell-card.hbs +++ b/Data/systems/pf2e/templates/chat/spell-card.hbs @@ -7,20 +7,20 @@ {{#if tokenId}}data-token-id="{{tokenId}}"{{/if}} >
    - + {{item.name}}

    {{item.name}}

    {{data.rankLabel}}

    -
    +
    {{~#if data.actionTraits}} - {{#each data.actionTraits}} - {{localize this.label}} + {{#each data.actionTraits as |trait|}} + {{localize trait.label}} {{/each}}
    {{~/if}} - {{#each data.spellTraits}} - {{localize this.label}} + {{#each data.spellTraits as |trait|}} + {{localize trait.label}} {{/each}}
    diff --git a/Data/systems/pf2e/templates/chat/strike-card.hbs b/Data/systems/pf2e/templates/chat/strike-card.hbs index dcf2a619..3b703bb2 100644 --- a/Data/systems/pf2e/templates/chat/strike-card.hbs +++ b/Data/systems/pf2e/templates/chat/strike-card.hbs @@ -1,6 +1,6 @@
    - + {{strike.label}}

    {{localize "PF2E.WeaponStrikeLabel"}}: {{strike.label}}

    diff --git a/Data/systems/pf2e/templates/chat/treasure-card.hbs b/Data/systems/pf2e/templates/chat/treasure-card.hbs index db007eeb..a539a91e 100644 --- a/Data/systems/pf2e/templates/chat/treasure-card.hbs +++ b/Data/systems/pf2e/templates/chat/treasure-card.hbs @@ -1,6 +1,6 @@
    - +

    {{item.name}}

    diff --git a/Data/systems/pf2e/templates/chat/weapon-card.hbs b/Data/systems/pf2e/templates/chat/weapon-card.hbs index ad1c21fb..c8717bdf 100644 --- a/Data/systems/pf2e/templates/chat/weapon-card.hbs +++ b/Data/systems/pf2e/templates/chat/weapon-card.hbs @@ -1,16 +1,20 @@
    - + {{item.name}}

    {{item.name}}

    -
    - {{#if item.isIdentified}} - {{localize data.rarity.label}} +
    + {{#if (and item.isIdentified (ne item.rarity "common"))}} + {{localize data.rarity.label}} {{/if}} {{#each data.traits as |trait|}} {{#unless trait.mystified}} - {{localize trait.label}} + {{localize trait.label}} {{/unless}} {{/each}} {{#each data.properties as |property|}} diff --git a/Data/systems/pf2e/templates/compendium-browser/compendium-browser.hbs b/Data/systems/pf2e/templates/compendium-browser/compendium-browser.hbs index 3dc50931..74def35f 100644 --- a/Data/systems/pf2e/templates/compendium-browser/compendium-browser.hbs +++ b/Data/systems/pf2e/templates/compendium-browser/compendium-browser.hbs @@ -1,4 +1,4 @@ -
    +
    -
    +
    {{> "systems/pf2e/templates/compendium-browser/settings/pack-settings.hbs"}}
    diff --git a/Data/systems/pf2e/templates/items/affliction-details.hbs b/Data/systems/pf2e/templates/items/affliction-details.hbs index 1d7d7fbe..f5f53d47 100644 --- a/Data/systems/pf2e/templates/items/affliction-details.hbs +++ b/Data/systems/pf2e/templates/items/affliction-details.hbs @@ -19,7 +19,7 @@

    {{localize "PF2E.Item.Affliction.Stage" stage=stage.stage}}

    - +
    @@ -27,13 +27,13 @@

    {{localize "PF2E.FormulaPlaceholder"}}
    - +

    {{#each stage.damage as |damage id|}}
    -
    +
    - +
    @@ -62,7 +62,7 @@

    {{localize "PF2E.ConditionsLabel"}}
    - +

    @@ -81,9 +81,9 @@ {{#if @root.options.editable}}
    - + - +
    {{/if}}
    @@ -100,7 +100,7 @@ {{effect.name}} - {{#if @root.options.editable}}{{/if}} + {{#if @root.options.editable}}{{/if}} {{/each}} @@ -108,12 +108,12 @@
    -

    {{localize "PF2E.Time.Duration"}}

    + {{> systems/pf2e/templates/items/partials/duration.hbs base=(concat "system.stages." stageId ".duration") duration=stage.duration units=../durationUnits}}
{{/each}} diff --git a/Data/systems/pf2e/templates/items/affliction-sidebar.hbs b/Data/systems/pf2e/templates/items/affliction-sidebar.hbs index ee29d8f6..5f865fe1 100644 --- a/Data/systems/pf2e/templates/items/affliction-sidebar.hbs +++ b/Data/systems/pf2e/templates/items/affliction-sidebar.hbs @@ -30,9 +30,16 @@
-
- -
+
diff --git a/Data/systems/pf2e/templates/items/ancestry-details.hbs b/Data/systems/pf2e/templates/items/ancestry-details.hbs index 915a4550..78b30f70 100644 --- a/Data/systems/pf2e/templates/items/ancestry-details.hbs +++ b/Data/systems/pf2e/templates/items/ancestry-details.hbs @@ -73,10 +73,10 @@ {{~#each items as |item i|}}
  • - {{item.name}}{{#unless item.pack}}{{/unless}} + {{item.name}}{{#unless item.pack}}{{/unless}} - + {{#if item.items~}} {{#> abcItems item}}{{@partial-block}}items.{{i}}.{{/abcItems}} {{~/if}} diff --git a/Data/systems/pf2e/templates/items/armor-details.hbs b/Data/systems/pf2e/templates/items/armor-details.hbs index 4bcba7d1..a5e9453e 100644 --- a/Data/systems/pf2e/templates/items/armor-details.hbs +++ b/Data/systems/pf2e/templates/items/armor-details.hbs @@ -135,7 +135,7 @@
    @@ -242,7 +242,7 @@
  • @@ -37,7 +37,7 @@
    - + {{/each}} diff --git a/Data/systems/pf2e/templates/items/rules-panel.hbs b/Data/systems/pf2e/templates/items/rules-panel.hbs index 58c21d39..38b9d50f 100644 --- a/Data/systems/pf2e/templates/items/rules-panel.hbs +++ b/Data/systems/pf2e/templates/items/rules-panel.hbs @@ -12,7 +12,7 @@
    @@ -23,7 +23,7 @@
    @@ -34,11 +34,11 @@
    - +
    @@ -55,7 +55,7 @@ {{/each}} {{/select}} - {{localize "PF2E.Item.Rules.New"}} + {{localize "PF2E.Item.Rules.New"}}
    {{/if}} diff --git a/Data/systems/pf2e/templates/items/rules/aura.hbs b/Data/systems/pf2e/templates/items/rules/aura.hbs index 09d5d3c2..29e7e25d 100644 --- a/Data/systems/pf2e/templates/items/rules/aura.hbs +++ b/Data/systems/pf2e/templates/items/rules/aura.hbs @@ -21,7 +21,7 @@
    {{{form.resolvableValue "level"}}} @@ -35,13 +35,13 @@
    - +
    @@ -66,7 +66,13 @@
    - +
    @@ -207,7 +213,7 @@
    {{rangePicker name=(concat "system.rules." index ".appearance.texture.playbackRate") value=object.appearance.texture.playbackRate placeholder="1" min="0" max="4" step="0.05"}}
    @@ -235,7 +241,7 @@
    diff --git a/Data/systems/pf2e/templates/items/sheet.hbs b/Data/systems/pf2e/templates/items/sheet.hbs index 0e0e6cc1..71213910 100644 --- a/Data/systems/pf2e/templates/items/sheet.hbs +++ b/Data/systems/pf2e/templates/items/sheet.hbs @@ -1,5 +1,4 @@ -
    {{!-- Source image in case of change during data preparation --}} @@ -23,7 +22,7 @@ {{#if itemType}} - {{#if adjustedLevelHint}}{{/if}} + {{#if adjustedLevelHint}}{{/if}} {{itemType}} {{#if hasSidebar}} - -
    +
    {{> (lookup . "detailsTemplate")}}
    @@ -120,7 +119,7 @@ {{#if (not isVariant)}} -
    +
    {{!-- Use ~ so that text areas don't add further indentation --}} {{~> systems/pf2e/templates/items/rules-panel.hbs item=item}}
    diff --git a/Data/systems/pf2e/templates/items/spell-overlay.hbs b/Data/systems/pf2e/templates/items/spell-overlay.hbs index 2bc46c5c..2c82792c 100644 --- a/Data/systems/pf2e/templates/items/spell-overlay.hbs +++ b/Data/systems/pf2e/templates/items/spell-overlay.hbs @@ -11,7 +11,7 @@ {{/select}}
    - +
    @@ -21,7 +21,7 @@
    - +
    @@ -30,7 +30,7 @@
    {{#each missing}} {{/each}} @@ -39,7 +39,7 @@ {{#if system.time}}
    @@ -51,7 +51,7 @@ {{#if system.components}}
    @@ -78,7 +78,7 @@ {{#if system.target}}
    @@ -90,7 +90,7 @@ {{#if system.area}}
    @@ -117,7 +117,7 @@ {{#if system.range}}
    @@ -129,10 +129,10 @@ {{#if system.damage}}

    - + {{localize "PF2E.FormulaPlaceholder"}}
    - +

    @@ -166,8 +166,8 @@ data-title="PF2E.DamageCategoriesLabel" data-config-types="damageCategories" data-property="{{../dataPath}}.damage.value.{{id}}.type.categories" - > - + > +
    {{#if damage.type.categories}} diff --git a/Data/systems/pf2e/templates/items/weapon-details.hbs b/Data/systems/pf2e/templates/items/weapon-details.hbs index 8839327b..a46cdece 100644 --- a/Data/systems/pf2e/templates/items/weapon-details.hbs +++ b/Data/systems/pf2e/templates/items/weapon-details.hbs @@ -35,7 +35,7 @@
    @@ -145,13 +145,13 @@
    {{localize "PF2E.DamageLabel"}} - +
    @@ -231,7 +231,7 @@
    {{localize "PF2E.WeaponCustomDamageLabel"}} - +
    @@ -333,7 +333,7 @@

      {{localize "PF2E.Item.Weapon.MeleeUsage.Label"}} - +

      @@ -383,9 +383,9 @@
        @@ -398,7 +398,7 @@
        diff --git a/Data/systems/pf2e/templates/items/weapon-sidebar.hbs b/Data/systems/pf2e/templates/items/weapon-sidebar.hbs index c7b002b7..618a73d2 100644 --- a/Data/systems/pf2e/templates/items/weapon-sidebar.hbs +++ b/Data/systems/pf2e/templates/items/weapon-sidebar.hbs @@ -50,7 +50,7 @@
        __defProp(target, * @author RubaXa * @author owenm * @license MIT - */function ownKeys(object,enumerableOnly){var keys2=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})),keys2.push.apply(keys2,symbols)}return keys2}__name(ownKeys,"ownKeys"),__name2(ownKeys,"ownKeys");function _objectSpread2(target){for(var i=1;i=0)&&(target[key]=source[key]);return target}__name(_objectWithoutPropertiesLoose,"_objectWithoutPropertiesLoose"),__name2(_objectWithoutPropertiesLoose,"_objectWithoutPropertiesLoose");function _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded),key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}__name(_objectWithoutProperties,"_objectWithoutProperties"),__name2(_objectWithoutProperties,"_objectWithoutProperties");var version="1.15.0";function userAgent(pattern){if(typeof window<"u"&&window.navigator)return!!navigator.userAgent.match(pattern)}__name(userAgent,"userAgent"),__name2(userAgent,"userAgent");var IE11OrLess=userAgent(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),Edge=userAgent(/Edge/i),FireFox=userAgent(/firefox/i),Safari=userAgent(/safari/i)&&!userAgent(/chrome/i)&&!userAgent(/android/i),IOS=userAgent(/iP(ad|od|hone)/i),ChromeForAndroid=userAgent(/chrome/i)&&userAgent(/android/i),captureMode={capture:!1,passive:!1};function on(el,event,fn){el.addEventListener(event,fn,!IE11OrLess&&captureMode)}__name(on,"on"),__name2(on,"on");function off(el,event,fn){el.removeEventListener(event,fn,!IE11OrLess&&captureMode)}__name(off,"off"),__name2(off,"off");function matches(el,selector){if(selector){if(selector[0]===">"&&(selector=selector.substring(1)),el)try{if(el.matches)return el.matches(selector);if(el.msMatchesSelector)return el.msMatchesSelector(selector);if(el.webkitMatchesSelector)return el.webkitMatchesSelector(selector)}catch{return!1}return!1}}__name(matches,"matches"),__name2(matches,"matches");function getParentOrHost(el){return el.host&&el!==document&&el.host.nodeType?el.host:el.parentNode}__name(getParentOrHost,"getParentOrHost"),__name2(getParentOrHost,"getParentOrHost");function closest$1(el,selector,ctx,includeCTX){if(el){ctx=ctx||document;do{if(selector!=null&&(selector[0]===">"?el.parentNode===ctx&&matches(el,selector):matches(el,selector))||includeCTX&&el===ctx)return el;if(el===ctx)break}while(el=getParentOrHost(el))}return null}__name(closest$1,"closest$1"),__name2(closest$1,"closest$1");var R_SPACE=/\s+/g;function toggleClass(el,name2,state){if(el&&name2)if(el.classList)el.classList[state?"add":"remove"](name2);else{var className=(" "+el.className+" ").replace(R_SPACE," ").replace(" "+name2+" "," ");el.className=(className+(state?" "+name2:"")).replace(R_SPACE," ")}}__name(toggleClass,"toggleClass"),__name2(toggleClass,"toggleClass");function css(el,prop,val){var style=el&&el.style;if(style){if(val===void 0)return document.defaultView&&document.defaultView.getComputedStyle?val=document.defaultView.getComputedStyle(el,""):el.currentStyle&&(val=el.currentStyle),prop===void 0?val:val[prop];!(prop in style)&&prop.indexOf("webkit")===-1&&(prop="-webkit-"+prop),style[prop]=val+(typeof val=="string"?"":"px")}}__name(css,"css"),__name2(css,"css");function matrix(el,selfOnly){var appliedTransforms="";if(typeof el=="string")appliedTransforms=el;else do{var transform=css(el,"transform");transform&&transform!=="none"&&(appliedTransforms=transform+" "+appliedTransforms)}while(!selfOnly&&(el=el.parentNode));var matrixFn=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return matrixFn&&new matrixFn(appliedTransforms)}__name(matrix,"matrix"),__name2(matrix,"matrix");function find$1(ctx,tagName,iterator){if(ctx){var list=ctx.getElementsByTagName(tagName),i=0,n2=list.length;if(iterator)for(;i=parentSideVal:visible=elSideVal<=parentSideVal,!visible)return parent;if(parent===getWindowScrollingElement())break;parent=getParentAutoScrollElement(parent,!1)}return!1}__name(isScrolledPast,"isScrolledPast"),__name2(isScrolledPast,"isScrolledPast");function getChild(el,childNum,options,includeDragEl){for(var currentChild=0,i=0,children=el.children;i2&&arguments[2]!==void 0?arguments[2]:{},originalEvent=_ref.evt,data=_objectWithoutProperties(_ref,_excluded);PluginManager.pluginEvent.bind(Sortable)(eventName,sortable,_objectSpread2({dragEl,parentEl,ghostEl,rootEl,nextEl,lastDownEl,cloneEl,cloneHidden,dragStarted:moved,putSortable,activeSortable:Sortable.active,originalEvent,oldIndex,oldDraggableIndex,newIndex,newDraggableIndex,hideGhostForTarget:_hideGhostForTarget,unhideGhostForTarget:_unhideGhostForTarget,cloneNowHidden:__name2(__name(function(){cloneHidden=!0},"cloneNowHidden"),"cloneNowHidden"),cloneNowShown:__name2(__name(function(){cloneHidden=!1},"cloneNowShown"),"cloneNowShown"),dispatchSortableEvent:__name2(__name(function(name2){_dispatchEvent({sortable,name:name2,originalEvent})},"dispatchSortableEvent"),"dispatchSortableEvent")},data))},"pluginEvent3"),"pluginEvent");function _dispatchEvent(info){dispatchEvent$1(_objectSpread2({putSortable,cloneEl,targetEl:dragEl,rootEl,oldIndex,oldDraggableIndex,newIndex,newDraggableIndex},info))}__name(_dispatchEvent,"_dispatchEvent"),__name2(_dispatchEvent,"_dispatchEvent");var dragEl,parentEl,ghostEl,rootEl,nextEl,lastDownEl,cloneEl,cloneHidden,oldIndex,newIndex,oldDraggableIndex,newDraggableIndex,activeGroup,putSortable,awaitingDragStarted=!1,ignoreNextClick=!1,sortables=[],tapEvt,touchEvt,lastDx,lastDy,tapDistanceLeft,tapDistanceTop,moved,lastTarget,lastDirection,pastFirstInvertThresh=!1,isCircumstantialInvert=!1,targetMoveDistance,ghostRelativeParent,ghostRelativeParentInitialScroll=[],_silent=!1,savedInputChecked=[],documentExists=typeof document<"u",PositionGhostAbsolutely=IOS,CSSFloatProperty=Edge||IE11OrLess?"cssFloat":"float",supportDraggable=documentExists&&!ChromeForAndroid&&!IOS&&"draggable"in document.createElement("div"),supportCssPointerEvents=function(){if(documentExists){if(IE11OrLess)return!1;var el=document.createElement("x");return el.style.cssText="pointer-events:auto",el.style.pointerEvents==="auto"}}(),_detectDirection=__name2(__name(function(el,options){var elCSS=css(el),elWidth=parseInt(elCSS.width)-parseInt(elCSS.paddingLeft)-parseInt(elCSS.paddingRight)-parseInt(elCSS.borderLeftWidth)-parseInt(elCSS.borderRightWidth),child1=getChild(el,0,options),child2=getChild(el,1,options),firstChildCSS=child1&&css(child1),secondChildCSS=child2&&css(child2),firstChildWidth=firstChildCSS&&parseInt(firstChildCSS.marginLeft)+parseInt(firstChildCSS.marginRight)+getRect(child1).width,secondChildWidth=secondChildCSS&&parseInt(secondChildCSS.marginLeft)+parseInt(secondChildCSS.marginRight)+getRect(child2).width;if(elCSS.display==="flex")return elCSS.flexDirection==="column"||elCSS.flexDirection==="column-reverse"?"vertical":"horizontal";if(elCSS.display==="grid")return elCSS.gridTemplateColumns.split(" ").length<=1?"vertical":"horizontal";if(child1&&firstChildCSS.float&&firstChildCSS.float!=="none"){var touchingSideChild2=firstChildCSS.float==="left"?"left":"right";return child2&&(secondChildCSS.clear==="both"||secondChildCSS.clear===touchingSideChild2)?"vertical":"horizontal"}return child1&&(firstChildCSS.display==="block"||firstChildCSS.display==="flex"||firstChildCSS.display==="table"||firstChildCSS.display==="grid"||firstChildWidth>=elWidth&&elCSS[CSSFloatProperty]==="none"||child2&&elCSS[CSSFloatProperty]==="none"&&firstChildWidth+secondChildWidth>elWidth)?"vertical":"horizontal"},"_detectDirection2"),"_detectDirection"),_dragElInRowColumn=__name2(__name(function(dragRect,targetRect,vertical){var dragElS1Opp=vertical?dragRect.left:dragRect.top,dragElS2Opp=vertical?dragRect.right:dragRect.bottom,dragElOppLength=vertical?dragRect.width:dragRect.height,targetS1Opp=vertical?targetRect.left:targetRect.top,targetS2Opp=vertical?targetRect.right:targetRect.bottom,targetOppLength=vertical?targetRect.width:targetRect.height;return dragElS1Opp===targetS1Opp||dragElS2Opp===targetS2Opp||dragElS1Opp+dragElOppLength/2===targetS1Opp+targetOppLength/2},"_dragElInRowColumn2"),"_dragElInRowColumn"),_detectNearestEmptySortable=__name2(__name(function(x,y){var ret;return sortables.some(function(sortable){var threshold=sortable[expando].options.emptyInsertThreshold;if(!(!threshold||lastChild(sortable))){var rect=getRect(sortable),insideHorizontally=x>=rect.left-threshold&&x<=rect.right+threshold,insideVertically=y>=rect.top-threshold&&y<=rect.bottom+threshold;if(insideHorizontally&&insideVertically)return ret=sortable}}),ret},"_detectNearestEmptySortable2"),"_detectNearestEmptySortable"),_prepareGroup=__name2(__name(function(options){function toFn(value,pull){return function(to,from,dragEl2,evt){var sameGroup=to.options.group.name&&from.options.group.name&&to.options.group.name===from.options.group.name;if(value==null&&(pull||sameGroup))return!0;if(value==null||value===!1)return!1;if(pull&&value==="clone")return value;if(typeof value=="function")return toFn(value(to,from,dragEl2,evt),pull)(to,from,dragEl2,evt);var otherGroup=(pull?to:from).options.group.name;return value===!0||typeof value=="string"&&value===otherGroup||value.join&&value.indexOf(otherGroup)>-1}}__name(toFn,"toFn"),__name2(toFn,"toFn");var group={},originalGroup=options.group;(!originalGroup||_typeof(originalGroup)!="object")&&(originalGroup={name:originalGroup}),group.name=originalGroup.name,group.checkPull=toFn(originalGroup.pull,!0),group.checkPut=toFn(originalGroup.put),group.revertClone=originalGroup.revertClone,options.group=group},"_prepareGroup2"),"_prepareGroup"),_hideGhostForTarget=__name2(__name(function(){!supportCssPointerEvents&&ghostEl&&css(ghostEl,"display","none")},"_hideGhostForTarget2"),"_hideGhostForTarget"),_unhideGhostForTarget=__name2(__name(function(){!supportCssPointerEvents&&ghostEl&&css(ghostEl,"display","")},"_unhideGhostForTarget2"),"_unhideGhostForTarget");documentExists&&!ChromeForAndroid&&document.addEventListener("click",function(evt){if(ignoreNextClick)return evt.preventDefault(),evt.stopPropagation&&evt.stopPropagation(),evt.stopImmediatePropagation&&evt.stopImmediatePropagation(),ignoreNextClick=!1,!1},!0);var nearestEmptyInsertDetectEvent=__name2(__name(function(evt){if(dragEl){evt=evt.touches?evt.touches[0]:evt;var nearest=_detectNearestEmptySortable(evt.clientX,evt.clientY);if(nearest){var event={};for(var i in evt)evt.hasOwnProperty(i)&&(event[i]=evt[i]);event.target=event.rootEl=nearest,event.preventDefault=void 0,event.stopPropagation=void 0,nearest[expando]._onDragOver(event)}}},"nearestEmptyInsertDetectEvent2"),"nearestEmptyInsertDetectEvent"),_checkOutsideTargetEl=__name2(__name(function(evt){dragEl&&dragEl.parentNode[expando]._isOutsideThisEl(evt.target)},"_checkOutsideTargetEl2"),"_checkOutsideTargetEl");function Sortable(el,options){if(!(el&&el.nodeType&&el.nodeType===1))throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(el));this.el=el,this.options=options=_extends({},options),el[expando]=this;var defaults2={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(el.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:__name2(__name(function(){return _detectDirection(el,this.options)},"direction"),"direction"),ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:__name2(__name(function(dataTransfer,dragEl2){dataTransfer.setData("Text",dragEl2.textContent)},"setData"),"setData"),dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:Sortable.supportPointer!==!1&&"PointerEvent"in window&&!Safari,emptyInsertThreshold:5};PluginManager.initializePlugins(this,el,defaults2);for(var name2 in defaults2)!(name2 in options)&&(options[name2]=defaults2[name2]);_prepareGroup(options);for(var fn in this)fn.charAt(0)==="_"&&typeof this[fn]=="function"&&(this[fn]=this[fn].bind(this));this.nativeDraggable=options.forceFallback?!1:supportDraggable,this.nativeDraggable&&(this.options.touchStartThreshold=1),options.supportPointer?on(el,"pointerdown",this._onTapStart):(on(el,"mousedown",this._onTapStart),on(el,"touchstart",this._onTapStart)),this.nativeDraggable&&(on(el,"dragover",this),on(el,"dragenter",this)),sortables.push(this.el),options.store&&options.store.get&&this.sort(options.store.get(this)||[]),_extends(this,AnimationStateManager())}__name(Sortable,"Sortable"),__name2(Sortable,"Sortable"),Sortable.prototype={constructor:Sortable,_isOutsideThisEl:__name2(__name(function(target){!this.el.contains(target)&&target!==this.el&&(lastTarget=null)},"_isOutsideThisEl"),"_isOutsideThisEl"),_getDirection:__name2(__name(function(evt,target){return typeof this.options.direction=="function"?this.options.direction.call(this,evt,target,dragEl):this.options.direction},"_getDirection"),"_getDirection"),_onTapStart:__name2(__name(function(evt){if(evt.cancelable){var _this=this,el=this.el,options=this.options,preventOnFilter=options.preventOnFilter,type=evt.type,touch=evt.touches&&evt.touches[0]||evt.pointerType&&evt.pointerType==="touch"&&evt,target=(touch||evt).target,originalTarget=evt.target.shadowRoot&&(evt.path&&evt.path[0]||evt.composedPath&&evt.composedPath()[0])||target,filter2=options.filter;if(_saveInputCheckedState(el),!dragEl&&!(/mousedown|pointerdown/.test(type)&&evt.button!==0||options.disabled)&&!originalTarget.isContentEditable&&!(!this.nativeDraggable&&Safari&&target&&target.tagName.toUpperCase()==="SELECT")&&(target=closest$1(target,options.draggable,el,!1),!(target&&target.animated)&&lastDownEl!==target)){if(oldIndex=index(target),oldDraggableIndex=index(target,options.draggable),typeof filter2=="function"){if(filter2.call(this,evt,target,this)){_dispatchEvent({sortable:_this,rootEl:originalTarget,name:"filter",targetEl:target,toEl:el,fromEl:el}),pluginEvent2("filter",_this,{evt}),preventOnFilter&&evt.cancelable&&evt.preventDefault();return}}else if(filter2&&(filter2=filter2.split(",").some(function(criteria){if(criteria=closest$1(originalTarget,criteria.trim(),el,!1),criteria)return _dispatchEvent({sortable:_this,rootEl:criteria,name:"filter",targetEl:target,fromEl:el,toEl:el}),pluginEvent2("filter",_this,{evt}),!0}),filter2)){preventOnFilter&&evt.cancelable&&evt.preventDefault();return}options.handle&&!closest$1(originalTarget,options.handle,el,!1)||this._prepareDragStart(evt,touch,target)}}},"_onTapStart"),"_onTapStart"),_prepareDragStart:__name2(__name(function(evt,touch,target){var _this=this,el=_this.el,options=_this.options,ownerDocument=el.ownerDocument,dragStartFn;if(target&&!dragEl&&target.parentNode===el){var dragRect=getRect(target);if(rootEl=el,dragEl=target,parentEl=dragEl.parentNode,nextEl=dragEl.nextSibling,lastDownEl=target,activeGroup=options.group,Sortable.dragged=dragEl,tapEvt={target:dragEl,clientX:(touch||evt).clientX,clientY:(touch||evt).clientY},tapDistanceLeft=tapEvt.clientX-dragRect.left,tapDistanceTop=tapEvt.clientY-dragRect.top,this._lastX=(touch||evt).clientX,this._lastY=(touch||evt).clientY,dragEl.style["will-change"]="all",dragStartFn=__name2(__name(function(){if(pluginEvent2("delayEnded",_this,{evt}),Sortable.eventCanceled){_this._onDrop();return}_this._disableDelayedDragEvents(),!FireFox&&_this.nativeDraggable&&(dragEl.draggable=!0),_this._triggerDragStart(evt,touch),_dispatchEvent({sortable:_this,name:"choose",originalEvent:evt}),toggleClass(dragEl,options.chosenClass,!0)},"dragStartFn2"),"dragStartFn"),options.ignore.split(",").forEach(function(criteria){find$1(dragEl,criteria.trim(),_disableDraggable)}),on(ownerDocument,"dragover",nearestEmptyInsertDetectEvent),on(ownerDocument,"mousemove",nearestEmptyInsertDetectEvent),on(ownerDocument,"touchmove",nearestEmptyInsertDetectEvent),on(ownerDocument,"mouseup",_this._onDrop),on(ownerDocument,"touchend",_this._onDrop),on(ownerDocument,"touchcancel",_this._onDrop),FireFox&&this.nativeDraggable&&(this.options.touchStartThreshold=4,dragEl.draggable=!0),pluginEvent2("delayStart",this,{evt}),options.delay&&(!options.delayOnTouchOnly||touch)&&(!this.nativeDraggable||!(Edge||IE11OrLess))){if(Sortable.eventCanceled){this._onDrop();return}on(ownerDocument,"mouseup",_this._disableDelayedDrag),on(ownerDocument,"touchend",_this._disableDelayedDrag),on(ownerDocument,"touchcancel",_this._disableDelayedDrag),on(ownerDocument,"mousemove",_this._delayedDragTouchMoveHandler),on(ownerDocument,"touchmove",_this._delayedDragTouchMoveHandler),options.supportPointer&&on(ownerDocument,"pointermove",_this._delayedDragTouchMoveHandler),_this._dragStartTimer=setTimeout(dragStartFn,options.delay)}else dragStartFn()}},"_prepareDragStart"),"_prepareDragStart"),_delayedDragTouchMoveHandler:__name2(__name(function(e){var touch=e.touches?e.touches[0]:e;Math.max(Math.abs(touch.clientX-this._lastX),Math.abs(touch.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},"_delayedDragTouchMoveHandler"),"_delayedDragTouchMoveHandler"),_disableDelayedDrag:__name2(__name(function(){dragEl&&_disableDraggable(dragEl),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},"_disableDelayedDrag"),"_disableDelayedDrag"),_disableDelayedDragEvents:__name2(__name(function(){var ownerDocument=this.el.ownerDocument;off(ownerDocument,"mouseup",this._disableDelayedDrag),off(ownerDocument,"touchend",this._disableDelayedDrag),off(ownerDocument,"touchcancel",this._disableDelayedDrag),off(ownerDocument,"mousemove",this._delayedDragTouchMoveHandler),off(ownerDocument,"touchmove",this._delayedDragTouchMoveHandler),off(ownerDocument,"pointermove",this._delayedDragTouchMoveHandler)},"_disableDelayedDragEvents"),"_disableDelayedDragEvents"),_triggerDragStart:__name2(__name(function(evt,touch){touch=touch||evt.pointerType=="touch"&&evt,!this.nativeDraggable||touch?this.options.supportPointer?on(document,"pointermove",this._onTouchMove):touch?on(document,"touchmove",this._onTouchMove):on(document,"mousemove",this._onTouchMove):(on(dragEl,"dragend",this),on(rootEl,"dragstart",this._onDragStart));try{document.selection?_nextTick(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},"_triggerDragStart"),"_triggerDragStart"),_dragStarted:__name2(__name(function(fallback,evt){if(awaitingDragStarted=!1,rootEl&&dragEl){pluginEvent2("dragStarted",this,{evt}),this.nativeDraggable&&on(document,"dragover",_checkOutsideTargetEl);var options=this.options;!fallback&&toggleClass(dragEl,options.dragClass,!1),toggleClass(dragEl,options.ghostClass,!0),Sortable.active=this,fallback&&this._appendGhost(),_dispatchEvent({sortable:this,name:"start",originalEvent:evt})}else this._nulling()},"_dragStarted"),"_dragStarted"),_emulateDragOver:__name2(__name(function(){if(touchEvt){this._lastX=touchEvt.clientX,this._lastY=touchEvt.clientY,_hideGhostForTarget();for(var target=document.elementFromPoint(touchEvt.clientX,touchEvt.clientY),parent=target;target&&target.shadowRoot&&(target=target.shadowRoot.elementFromPoint(touchEvt.clientX,touchEvt.clientY),target!==parent);)parent=target;if(dragEl.parentNode[expando]._isOutsideThisEl(target),parent)do{if(parent[expando]){var inserted=void 0;if(inserted=parent[expando]._onDragOver({clientX:touchEvt.clientX,clientY:touchEvt.clientY,target,rootEl:parent}),inserted&&!this.options.dragoverBubble)break}target=parent}while(parent=parent.parentNode);_unhideGhostForTarget()}},"_emulateDragOver"),"_emulateDragOver"),_onTouchMove:__name2(__name(function(evt){if(tapEvt){var options=this.options,fallbackTolerance=options.fallbackTolerance,fallbackOffset=options.fallbackOffset,touch=evt.touches?evt.touches[0]:evt,ghostMatrix=ghostEl&&matrix(ghostEl,!0),scaleX=ghostEl&&ghostMatrix&&ghostMatrix.a,scaleY=ghostEl&&ghostMatrix&&ghostMatrix.d,relativeScrollOffset=PositionGhostAbsolutely&&ghostRelativeParent&&getRelativeScrollOffset(ghostRelativeParent),dx=(touch.clientX-tapEvt.clientX+fallbackOffset.x)/(scaleX||1)+(relativeScrollOffset?relativeScrollOffset[0]-ghostRelativeParentInitialScroll[0]:0)/(scaleX||1),dy=(touch.clientY-tapEvt.clientY+fallbackOffset.y)/(scaleY||1)+(relativeScrollOffset?relativeScrollOffset[1]-ghostRelativeParentInitialScroll[1]:0)/(scaleY||1);if(!Sortable.active&&!awaitingDragStarted){if(fallbackTolerance&&Math.max(Math.abs(touch.clientX-this._lastX),Math.abs(touch.clientY-this._lastY))=0&&(_dispatchEvent({rootEl:parentEl,name:"add",toEl:parentEl,fromEl:rootEl,originalEvent:evt}),_dispatchEvent({sortable:this,name:"remove",toEl:parentEl,originalEvent:evt}),_dispatchEvent({rootEl:parentEl,name:"sort",toEl:parentEl,fromEl:rootEl,originalEvent:evt}),_dispatchEvent({sortable:this,name:"sort",toEl:parentEl,originalEvent:evt})),putSortable&&putSortable.save()):newIndex!==oldIndex&&newIndex>=0&&(_dispatchEvent({sortable:this,name:"update",toEl:parentEl,originalEvent:evt}),_dispatchEvent({sortable:this,name:"sort",toEl:parentEl,originalEvent:evt})),Sortable.active&&((newIndex==null||newIndex===-1)&&(newIndex=oldIndex,newDraggableIndex=oldDraggableIndex),_dispatchEvent({sortable:this,name:"end",toEl:parentEl,originalEvent:evt}),this.save()))),this._nulling()},"_onDrop"),"_onDrop"),_nulling:__name2(__name(function(){pluginEvent2("nulling",this),rootEl=dragEl=parentEl=ghostEl=nextEl=cloneEl=lastDownEl=cloneHidden=tapEvt=touchEvt=moved=newIndex=newDraggableIndex=oldIndex=oldDraggableIndex=lastTarget=lastDirection=putSortable=activeGroup=Sortable.dragged=Sortable.ghost=Sortable.clone=Sortable.active=null,savedInputChecked.forEach(function(el){el.checked=!0}),savedInputChecked.length=lastDx=lastDy=0},"_nulling"),"_nulling"),handleEvent:__name2(__name(function(evt){switch(evt.type){case"drop":case"dragend":this._onDrop(evt);break;case"dragenter":case"dragover":dragEl&&(this._onDragOver(evt),_globalDragOver(evt));break;case"selectstart":evt.preventDefault();break}},"handleEvent"),"handleEvent"),toArray:__name2(__name(function(){for(var order=[],el,children=this.el.children,i=0,n2=children.length,options=this.options;irect.right+spacer||evt.clientX<=rect.right&&evt.clientY>rect.bottom&&evt.clientX>=rect.left:evt.clientX>rect.right&&evt.clientY>rect.top||evt.clientX<=rect.right&&evt.clientY>rect.bottom+spacer}__name(_ghostIsLast,"_ghostIsLast"),__name2(_ghostIsLast,"_ghostIsLast");function _getSwapDirection(evt,target,targetRect,vertical,swapThreshold,invertedSwapThreshold,invertSwap,isLastTarget){var mouseOnAxis=vertical?evt.clientY:evt.clientX,targetLength=vertical?targetRect.height:targetRect.width,targetS1=vertical?targetRect.top:targetRect.left,targetS2=vertical?targetRect.bottom:targetRect.right,invert=!1;if(!invertSwap){if(isLastTarget&&targetMoveDistancetargetS1+targetLength*invertedSwapThreshold/2:mouseOnAxistargetS2-targetMoveDistance)return-lastDirection}else if(mouseOnAxis>targetS1+targetLength*(1-swapThreshold)/2&&mouseOnAxistargetS2-targetLength*invertedSwapThreshold/2)?mouseOnAxis>targetS1+targetLength/2?1:-1:0}__name(_getSwapDirection,"_getSwapDirection"),__name2(_getSwapDirection,"_getSwapDirection");function _getInsertDirection(target){return index(dragEl)=0?over:1e3+over,(asUTC-asTS)/(60*1e3)}equals(otherZone){return otherZone.type==="iana"&&otherZone.name===this.name}get isValid(){return this.valid}};__name2(_IANAZone,"IANAZone");let IANAZone=_IANAZone,intlLFCache={};function getCachedLF(locString,opts={}){const key=JSON.stringify([locString,opts]);let dtf=intlLFCache[key];return dtf||(dtf=new Intl.ListFormat(locString,opts),intlLFCache[key]=dtf),dtf}__name(getCachedLF,"getCachedLF"),__name2(getCachedLF,"getCachedLF");let intlDTCache={};function getCachedDTF(locString,opts={}){const key=JSON.stringify([locString,opts]);let dtf=intlDTCache[key];return dtf||(dtf=new Intl.DateTimeFormat(locString,opts),intlDTCache[key]=dtf),dtf}__name(getCachedDTF,"getCachedDTF"),__name2(getCachedDTF,"getCachedDTF");let intlNumCache={};function getCachedINF(locString,opts={}){const key=JSON.stringify([locString,opts]);let inf=intlNumCache[key];return inf||(inf=new Intl.NumberFormat(locString,opts),intlNumCache[key]=inf),inf}__name(getCachedINF,"getCachedINF"),__name2(getCachedINF,"getCachedINF");let intlRelCache={};function getCachedRTF(locString,opts={}){const{base:base2,...cacheKeyOpts}=opts,key=JSON.stringify([locString,cacheKeyOpts]);let inf=intlRelCache[key];return inf||(inf=new Intl.RelativeTimeFormat(locString,opts),intlRelCache[key]=inf),inf}__name(getCachedRTF,"getCachedRTF"),__name2(getCachedRTF,"getCachedRTF");let sysLocaleCache=null;function systemLocale(){return sysLocaleCache||(sysLocaleCache=new Intl.DateTimeFormat().resolvedOptions().locale,sysLocaleCache)}__name(systemLocale,"systemLocale"),__name2(systemLocale,"systemLocale");function parseLocaleString(localeStr){const xIndex=localeStr.indexOf("-x-");xIndex!==-1&&(localeStr=localeStr.substring(0,xIndex));const uIndex=localeStr.indexOf("-u-");if(uIndex===-1)return[localeStr];{let options,selectedStr;try{options=getCachedDTF(localeStr).resolvedOptions(),selectedStr=localeStr}catch{const smaller=localeStr.substring(0,uIndex);options=getCachedDTF(smaller).resolvedOptions(),selectedStr=smaller}const{numberingSystem,calendar}=options;return[selectedStr,numberingSystem,calendar]}}__name(parseLocaleString,"parseLocaleString"),__name2(parseLocaleString,"parseLocaleString");function intlConfigString(localeStr,numberingSystem,outputCalendar){return(outputCalendar||numberingSystem)&&(localeStr.includes("-u-")||(localeStr+="-u"),outputCalendar&&(localeStr+=`-ca-${outputCalendar}`),numberingSystem&&(localeStr+=`-nu-${numberingSystem}`)),localeStr}__name(intlConfigString,"intlConfigString"),__name2(intlConfigString,"intlConfigString");function mapMonths(f){const ms=[];for(let i=1;i<=12;i++){const dt=DateTime.utc(2009,i,1);ms.push(f(dt))}return ms}__name(mapMonths,"mapMonths"),__name2(mapMonths,"mapMonths");function mapWeekdays(f){const ms=[];for(let i=1;i<=7;i++){const dt=DateTime.utc(2016,11,13+i);ms.push(f(dt))}return ms}__name(mapWeekdays,"mapWeekdays"),__name2(mapWeekdays,"mapWeekdays");function listStuff(loc,length,englishFn,intlFn){const mode=loc.listingMode();return mode==="error"?null:mode==="en"?englishFn(length):intlFn(length)}__name(listStuff,"listStuff"),__name2(listStuff,"listStuff");function supportsFastNumbers(loc){return loc.numberingSystem&&loc.numberingSystem!=="latn"?!1:loc.numberingSystem==="latn"||!loc.locale||loc.locale.startsWith("en")||new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem==="latn"}__name(supportsFastNumbers,"supportsFastNumbers"),__name2(supportsFastNumbers,"supportsFastNumbers");const _PolyNumberFormatter=class{static{__name(this,"_PolyNumberFormatter")}constructor(intl,forceSimple,opts){this.padTo=opts.padTo||0,this.floor=opts.floor||!1;const{padTo,floor,...otherOpts}=opts;if(!forceSimple||Object.keys(otherOpts).length>0){const intlOpts={useGrouping:!1,...opts};opts.padTo>0&&(intlOpts.minimumIntegerDigits=opts.padTo),this.inf=getCachedINF(intl,intlOpts)}}format(i){if(this.inf){const fixed=this.floor?Math.floor(i):i;return this.inf.format(fixed)}else{const fixed=this.floor?Math.floor(i):roundTo(i,3);return padStart(fixed,this.padTo)}}};__name2(_PolyNumberFormatter,"PolyNumberFormatter");let PolyNumberFormatter=_PolyNumberFormatter;const _PolyDateFormatter=class{static{__name(this,"_PolyDateFormatter")}constructor(dt,intl,opts){this.opts=opts,this.originalZone=void 0;let z;if(this.opts.timeZone)this.dt=dt;else if(dt.zone.type==="fixed"){const gmtOffset=-1*(dt.offset/60),offsetZ=gmtOffset>=0?`Etc/GMT+${gmtOffset}`:`Etc/GMT${gmtOffset}`;dt.offset!==0&&IANAZone.create(offsetZ).valid?(z=offsetZ,this.dt=dt):(z="UTC",this.dt=dt.offset===0?dt:dt.setZone("UTC").plus({minutes:dt.offset}),this.originalZone=dt.zone)}else dt.zone.type==="system"?this.dt=dt:dt.zone.type==="iana"?(this.dt=dt,z=dt.zone.name):(z="UTC",this.dt=dt.setZone("UTC").plus({minutes:dt.offset}),this.originalZone=dt.zone);const intlOpts={...this.opts};intlOpts.timeZone=intlOpts.timeZone||z,this.dtf=getCachedDTF(intl,intlOpts)}format(){return this.originalZone?this.formatToParts().map(({value})=>value).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const parts=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?parts.map(part=>{if(part.type==="timeZoneName"){const offsetName=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...part,value:offsetName}}else return part}):parts}resolvedOptions(){return this.dtf.resolvedOptions()}};__name2(_PolyDateFormatter,"PolyDateFormatter");let PolyDateFormatter=_PolyDateFormatter;const _PolyRelFormatter=class{static{__name(this,"_PolyRelFormatter")}constructor(intl,isEnglish,opts){this.opts={style:"long",...opts},!isEnglish&&hasRelative()&&(this.rtf=getCachedRTF(intl,opts))}format(count,unit){return this.rtf?this.rtf.format(count,unit):formatRelativeTime(unit,count,this.opts.numeric,this.opts.style!=="long")}formatToParts(count,unit){return this.rtf?this.rtf.formatToParts(count,unit):[]}};__name2(_PolyRelFormatter,"PolyRelFormatter");let PolyRelFormatter=_PolyRelFormatter;const _Locale=class _Locale2{static{__name(this,"_Locale")}static fromOpts(opts){return _Locale2.create(opts.locale,opts.numberingSystem,opts.outputCalendar,opts.defaultToEN)}static create(locale,numberingSystem,outputCalendar,defaultToEN=!1){const specifiedLocale=locale||Settings.defaultLocale,localeR=specifiedLocale||(defaultToEN?"en-US":systemLocale()),numberingSystemR=numberingSystem||Settings.defaultNumberingSystem,outputCalendarR=outputCalendar||Settings.defaultOutputCalendar;return new _Locale2(localeR,numberingSystemR,outputCalendarR,specifiedLocale)}static resetCache(){sysLocaleCache=null,intlDTCache={},intlNumCache={},intlRelCache={}}static fromObject({locale,numberingSystem,outputCalendar}={}){return _Locale2.create(locale,numberingSystem,outputCalendar)}constructor(locale,numbering,outputCalendar,specifiedLocale){const[parsedLocale,parsedNumberingSystem,parsedOutputCalendar]=parseLocaleString(locale);this.locale=parsedLocale,this.numberingSystem=numbering||parsedNumberingSystem||null,this.outputCalendar=outputCalendar||parsedOutputCalendar||null,this.intl=intlConfigString(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=specifiedLocale,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=supportsFastNumbers(this)),this.fastNumbersCached}listingMode(){const isActuallyEn=this.isEnglish(),hasNoWeirdness=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return isActuallyEn&&hasNoWeirdness?"en":"intl"}clone(alts){return!alts||Object.getOwnPropertyNames(alts).length===0?this:_Locale2.create(alts.locale||this.specifiedLocale,alts.numberingSystem||this.numberingSystem,alts.outputCalendar||this.outputCalendar,alts.defaultToEN||!1)}redefaultToEN(alts={}){return this.clone({...alts,defaultToEN:!0})}redefaultToSystem(alts={}){return this.clone({...alts,defaultToEN:!1})}months(length,format=!1){return listStuff(this,length,months,()=>{const intl=format?{month:length,day:"numeric"}:{month:length},formatStr=format?"format":"standalone";return this.monthsCache[formatStr][length]||(this.monthsCache[formatStr][length]=mapMonths(dt=>this.extract(dt,intl,"month"))),this.monthsCache[formatStr][length]})}weekdays(length,format=!1){return listStuff(this,length,weekdays,()=>{const intl=format?{weekday:length,year:"numeric",month:"long",day:"numeric"}:{weekday:length},formatStr=format?"format":"standalone";return this.weekdaysCache[formatStr][length]||(this.weekdaysCache[formatStr][length]=mapWeekdays(dt=>this.extract(dt,intl,"weekday"))),this.weekdaysCache[formatStr][length]})}meridiems(){return listStuff(this,void 0,()=>meridiems,()=>{if(!this.meridiemCache){const intl={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[DateTime.utc(2016,11,13,9),DateTime.utc(2016,11,13,19)].map(dt=>this.extract(dt,intl,"dayperiod"))}return this.meridiemCache})}eras(length){return listStuff(this,length,eras,()=>{const intl={era:length};return this.eraCache[length]||(this.eraCache[length]=[DateTime.utc(-40,1,1),DateTime.utc(2017,1,1)].map(dt=>this.extract(dt,intl,"era"))),this.eraCache[length]})}extract(dt,intlOpts,field){const df=this.dtFormatter(dt,intlOpts),results=df.formatToParts(),matching=results.find(m=>m.type.toLowerCase()===field);return matching?matching.value:null}numberFormatter(opts={}){return new PolyNumberFormatter(this.intl,opts.forceSimple||this.fastNumbers,opts)}dtFormatter(dt,intlOpts={}){return new PolyDateFormatter(dt,this.intl,intlOpts)}relFormatter(opts={}){return new PolyRelFormatter(this.intl,this.isEnglish(),opts)}listFormatter(opts={}){return getCachedLF(this.intl,opts)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}equals(other){return this.locale===other.locale&&this.numberingSystem===other.numberingSystem&&this.outputCalendar===other.outputCalendar}};__name2(_Locale,"Locale");let Locale=_Locale,singleton=null;const _FixedOffsetZone=class _FixedOffsetZone2 extends Zone{static{__name(this,"_FixedOffsetZone")}static get utcInstance(){return singleton===null&&(singleton=new _FixedOffsetZone2(0)),singleton}static instance(offset2){return offset2===0?_FixedOffsetZone2.utcInstance:new _FixedOffsetZone2(offset2)}static parseSpecifier(s2){if(s2){const r=s2.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new _FixedOffsetZone2(signedOffset(r[1],r[2]))}return null}constructor(offset2){super(),this.fixed=offset2}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${formatOffset(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${formatOffset(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(ts,format){return formatOffset(this.fixed,format)}get isUniversal(){return!0}offset(){return this.fixed}equals(otherZone){return otherZone.type==="fixed"&&otherZone.fixed===this.fixed}get isValid(){return!0}};__name2(_FixedOffsetZone,"FixedOffsetZone");let FixedOffsetZone=_FixedOffsetZone;const _InvalidZone=class extends Zone{static{__name(this,"_InvalidZone")}constructor(zoneName){super(),this.zoneName=zoneName}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};__name2(_InvalidZone,"InvalidZone");let InvalidZone=_InvalidZone;function normalizeZone(input,defaultZone2){if(isUndefined(input)||input===null)return defaultZone2;if(input instanceof Zone)return input;if(isString(input)){const lowered=input.toLowerCase();return lowered==="default"?defaultZone2:lowered==="local"||lowered==="system"?SystemZone.instance:lowered==="utc"||lowered==="gmt"?FixedOffsetZone.utcInstance:FixedOffsetZone.parseSpecifier(lowered)||IANAZone.create(input)}else return isNumber(input)?FixedOffsetZone.instance(input):typeof input=="object"&&"offset"in input&&typeof input.offset=="function"?input:new InvalidZone(input)}__name(normalizeZone,"normalizeZone"),__name2(normalizeZone,"normalizeZone");let now=__name2(()=>Date.now(),"now"),defaultZone="system",defaultLocale=null,defaultNumberingSystem=null,defaultOutputCalendar=null,twoDigitCutoffYear=60,throwOnInvalid;const _Settings=class{static{__name(this,"_Settings")}static get now(){return now}static set now(n2){now=n2}static set defaultZone(zone){defaultZone=zone}static get defaultZone(){return normalizeZone(defaultZone,SystemZone.instance)}static get defaultLocale(){return defaultLocale}static set defaultLocale(locale){defaultLocale=locale}static get defaultNumberingSystem(){return defaultNumberingSystem}static set defaultNumberingSystem(numberingSystem){defaultNumberingSystem=numberingSystem}static get defaultOutputCalendar(){return defaultOutputCalendar}static set defaultOutputCalendar(outputCalendar){defaultOutputCalendar=outputCalendar}static get twoDigitCutoffYear(){return twoDigitCutoffYear}static set twoDigitCutoffYear(cutoffYear){twoDigitCutoffYear=cutoffYear%100}static get throwOnInvalid(){return throwOnInvalid}static set throwOnInvalid(t2){throwOnInvalid=t2}static resetCaches(){Locale.resetCache(),IANAZone.resetCache()}};__name2(_Settings,"Settings");let Settings=_Settings;function isUndefined(o){return typeof o>"u"}__name(isUndefined,"isUndefined"),__name2(isUndefined,"isUndefined");function isNumber(o){return typeof o=="number"}__name(isNumber,"isNumber"),__name2(isNumber,"isNumber");function isInteger(o){return typeof o=="number"&&o%1===0}__name(isInteger,"isInteger"),__name2(isInteger,"isInteger");function isString(o){return typeof o=="string"}__name(isString,"isString"),__name2(isString,"isString");function isDate(o){return Object.prototype.toString.call(o)==="[object Date]"}__name(isDate,"isDate"),__name2(isDate,"isDate");function hasRelative(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}__name(hasRelative,"hasRelative"),__name2(hasRelative,"hasRelative");function maybeArray(thing){return Array.isArray(thing)?thing:[thing]}__name(maybeArray,"maybeArray"),__name2(maybeArray,"maybeArray");function bestBy(arr,by,compare2){if(arr.length!==0)return arr.reduce((best,next)=>{const pair2=[by(next),next];return best&&compare2(best[0],pair2[0])===best[0]?best:pair2},null)[1]}__name(bestBy,"bestBy"),__name2(bestBy,"bestBy");function pick(obj,keys2){return keys2.reduce((a,k)=>(a[k]=obj[k],a),{})}__name(pick,"pick"),__name2(pick,"pick");function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}__name(hasOwnProperty,"hasOwnProperty"),__name2(hasOwnProperty,"hasOwnProperty");function integerBetween(thing,bottom,top2){return isInteger(thing)&&thing>=bottom&&thing<=top2}__name(integerBetween,"integerBetween"),__name2(integerBetween,"integerBetween");function floorMod(x,n2){return x-n2*Math.floor(x/n2)}__name(floorMod,"floorMod"),__name2(floorMod,"floorMod");function padStart(input,n2=2){const isNeg=input<0;let padded;return isNeg?padded="-"+(""+-input).padStart(n2,"0"):padded=(""+input).padStart(n2,"0"),padded}__name(padStart,"padStart"),__name2(padStart,"padStart");function parseInteger(string2){if(!(isUndefined(string2)||string2===null||string2===""))return parseInt(string2,10)}__name(parseInteger,"parseInteger"),__name2(parseInteger,"parseInteger");function parseFloating(string2){if(!(isUndefined(string2)||string2===null||string2===""))return parseFloat(string2)}__name(parseFloating,"parseFloating"),__name2(parseFloating,"parseFloating");function parseMillis(fraction){if(!(isUndefined(fraction)||fraction===null||fraction==="")){const f=parseFloat("0."+fraction)*1e3;return Math.floor(f)}}__name(parseMillis,"parseMillis"),__name2(parseMillis,"parseMillis");function roundTo(number2,digits,towardZero=!1){const factor=10**digits;return(towardZero?Math.trunc:Math.round)(number2*factor)/factor}__name(roundTo,"roundTo"),__name2(roundTo,"roundTo");function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}__name(isLeapYear,"isLeapYear"),__name2(isLeapYear,"isLeapYear");function daysInYear(year){return isLeapYear(year)?366:365}__name(daysInYear,"daysInYear"),__name2(daysInYear,"daysInYear");function daysInMonth(year,month){const modMonth=floorMod(month-1,12)+1,modYear=year+(month-modMonth)/12;return modMonth===2?isLeapYear(modYear)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][modMonth-1]}__name(daysInMonth,"daysInMonth"),__name2(daysInMonth,"daysInMonth");function objToLocalTS(obj){let d=Date.UTC(obj.year,obj.month-1,obj.day,obj.hour,obj.minute,obj.second,obj.millisecond);return obj.year<100&&obj.year>=0&&(d=new Date(d),d.setUTCFullYear(obj.year,obj.month-1,obj.day)),+d}__name(objToLocalTS,"objToLocalTS"),__name2(objToLocalTS,"objToLocalTS");function weeksInWeekYear(weekYear){const p1=(weekYear+Math.floor(weekYear/4)-Math.floor(weekYear/100)+Math.floor(weekYear/400))%7,last2=weekYear-1,p2=(last2+Math.floor(last2/4)-Math.floor(last2/100)+Math.floor(last2/400))%7;return p1===4||p2===3?53:52}__name(weeksInWeekYear,"weeksInWeekYear"),__name2(weeksInWeekYear,"weeksInWeekYear");function untruncateYear(year){return year>99?year:year>Settings.twoDigitCutoffYear?1900+year:2e3+year}__name(untruncateYear,"untruncateYear"),__name2(untruncateYear,"untruncateYear");function parseZoneInfo(ts,offsetFormat,locale,timeZone=null){const date=new Date(ts),intlOpts={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};timeZone&&(intlOpts.timeZone=timeZone);const modified={timeZoneName:offsetFormat,...intlOpts},parsed=new Intl.DateTimeFormat(locale,modified).formatToParts(date).find(m=>m.type.toLowerCase()==="timezonename");return parsed?parsed.value:null}__name(parseZoneInfo,"parseZoneInfo"),__name2(parseZoneInfo,"parseZoneInfo");function signedOffset(offHourStr,offMinuteStr){let offHour=parseInt(offHourStr,10);Number.isNaN(offHour)&&(offHour=0);const offMin=parseInt(offMinuteStr,10)||0,offMinSigned=offHour<0||Object.is(offHour,-0)?-offMin:offMin;return offHour*60+offMinSigned}__name(signedOffset,"signedOffset"),__name2(signedOffset,"signedOffset");function asNumber(value){const numericValue=Number(value);if(typeof value=="boolean"||value===""||Number.isNaN(numericValue))throw new InvalidArgumentError(`Invalid unit value ${value}`);return numericValue}__name(asNumber,"asNumber"),__name2(asNumber,"asNumber");function normalizeObject(obj,normalizer){const normalized={};for(const u in obj)if(hasOwnProperty(obj,u)){const v=obj[u];if(v==null)continue;normalized[normalizer(u)]=asNumber(v)}return normalized}__name(normalizeObject,"normalizeObject"),__name2(normalizeObject,"normalizeObject");function formatOffset(offset2,format){const hours=Math.trunc(Math.abs(offset2/60)),minutes=Math.trunc(Math.abs(offset2%60)),sign=offset2>=0?"+":"-";switch(format){case"short":return`${sign}${padStart(hours,2)}:${padStart(minutes,2)}`;case"narrow":return`${sign}${hours}${minutes>0?`:${minutes}`:""}`;case"techie":return`${sign}${padStart(hours,2)}${padStart(minutes,2)}`;default:throw new RangeError(`Value format ${format} is out of range for property format`)}}__name(formatOffset,"formatOffset"),__name2(formatOffset,"formatOffset");function timeObject(obj){return pick(obj,["hour","minute","second","millisecond"])}__name(timeObject,"timeObject"),__name2(timeObject,"timeObject");const monthsLong=["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],monthsNarrow=["J","F","M","A","M","J","J","A","S","O","N","D"];function months(length){switch(length){case"narrow":return[...monthsNarrow];case"short":return[...monthsShort];case"long":return[...monthsLong];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}__name(months,"months"),__name2(months,"months");const weekdaysLong=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],weekdaysShort=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],weekdaysNarrow=["M","T","W","T","F","S","S"];function weekdays(length){switch(length){case"narrow":return[...weekdaysNarrow];case"short":return[...weekdaysShort];case"long":return[...weekdaysLong];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}__name(weekdays,"weekdays"),__name2(weekdays,"weekdays");const meridiems=["AM","PM"],erasLong=["Before Christ","Anno Domini"],erasShort=["BC","AD"],erasNarrow=["B","A"];function eras(length){switch(length){case"narrow":return[...erasNarrow];case"short":return[...erasShort];case"long":return[...erasLong];default:return null}}__name(eras,"eras"),__name2(eras,"eras");function meridiemForDateTime(dt){return meridiems[dt.hour<12?0:1]}__name(meridiemForDateTime,"meridiemForDateTime"),__name2(meridiemForDateTime,"meridiemForDateTime");function weekdayForDateTime(dt,length){return weekdays(length)[dt.weekday-1]}__name(weekdayForDateTime,"weekdayForDateTime"),__name2(weekdayForDateTime,"weekdayForDateTime");function monthForDateTime(dt,length){return months(length)[dt.month-1]}__name(monthForDateTime,"monthForDateTime"),__name2(monthForDateTime,"monthForDateTime");function eraForDateTime(dt,length){return eras(length)[dt.year<0?0:1]}__name(eraForDateTime,"eraForDateTime"),__name2(eraForDateTime,"eraForDateTime");function formatRelativeTime(unit,count,numeric="always",narrow=!1){const units={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},lastable=["hours","minutes","seconds"].indexOf(unit)===-1;if(numeric==="auto"&&lastable){const isDay=unit==="days";switch(count){case 1:return isDay?"tomorrow":`next ${units[unit][0]}`;case-1:return isDay?"yesterday":`last ${units[unit][0]}`;case 0:return isDay?"today":`this ${units[unit][0]}`}}const isInPast=Object.is(count,-0)||count<0,fmtValue=Math.abs(count),singular=fmtValue===1,lilUnits=units[unit],fmtUnit=narrow?singular?lilUnits[1]:lilUnits[2]||lilUnits[1]:singular?units[unit][0]:unit;return isInPast?`${fmtValue} ${fmtUnit} ago`:`in ${fmtValue} ${fmtUnit}`}__name(formatRelativeTime,"formatRelativeTime"),__name2(formatRelativeTime,"formatRelativeTime");function stringifyTokens(splits,tokenToString){let s2="";for(const token of splits)token.literal?s2+=token.val:s2+=tokenToString(token.val);return s2}__name(stringifyTokens,"stringifyTokens"),__name2(stringifyTokens,"stringifyTokens");const macroTokenToFormatOpts={D:DATE_SHORT,DD:DATE_MED,DDD:DATE_FULL,DDDD:DATE_HUGE,t:TIME_SIMPLE,tt:TIME_WITH_SECONDS,ttt:TIME_WITH_SHORT_OFFSET,tttt:TIME_WITH_LONG_OFFSET,T:TIME_24_SIMPLE,TT:TIME_24_WITH_SECONDS,TTT:TIME_24_WITH_SHORT_OFFSET,TTTT:TIME_24_WITH_LONG_OFFSET,f:DATETIME_SHORT,ff:DATETIME_MED,fff:DATETIME_FULL,ffff:DATETIME_HUGE,F:DATETIME_SHORT_WITH_SECONDS,FF:DATETIME_MED_WITH_SECONDS,FFF:DATETIME_FULL_WITH_SECONDS,FFFF:DATETIME_HUGE_WITH_SECONDS},_Formatter=class _Formatter2{static{__name(this,"_Formatter")}static create(locale,opts={}){return new _Formatter2(locale,opts)}static parseFormat(fmt){let current=null,currentFull="",bracketed=!1;const splits=[];for(let i=0;i0&&splits.push({literal:bracketed||/^\s+$/.test(currentFull),val:currentFull}),current=null,currentFull="",bracketed=!bracketed):bracketed||c===current?currentFull+=c:(currentFull.length>0&&splits.push({literal:/^\s+$/.test(currentFull),val:currentFull}),currentFull=c,current=c)}return currentFull.length>0&&splits.push({literal:bracketed||/^\s+$/.test(currentFull),val:currentFull}),splits}static macroTokenToFormatOpts(token){return macroTokenToFormatOpts[token]}constructor(locale,formatOpts){this.opts=formatOpts,this.loc=locale,this.systemLoc=null}formatWithSystemDefault(dt,opts){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(dt,{...this.opts,...opts}).format()}dtFormatter(dt,opts={}){return this.loc.dtFormatter(dt,{...this.opts,...opts})}formatDateTime(dt,opts){return this.dtFormatter(dt,opts).format()}formatDateTimeParts(dt,opts){return this.dtFormatter(dt,opts).formatToParts()}formatInterval(interval,opts){return this.dtFormatter(interval.start,opts).dtf.formatRange(interval.start.toJSDate(),interval.end.toJSDate())}resolvedOptions(dt,opts){return this.dtFormatter(dt,opts).resolvedOptions()}num(n2,p=0){if(this.opts.forceSimple)return padStart(n2,p);const opts={...this.opts};return p>0&&(opts.padTo=p),this.loc.numberFormatter(opts).format(n2)}formatDateTimeFromString(dt,fmt){const knownEnglish=this.loc.listingMode()==="en",useDateTimeFormatter=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",string2=__name2((opts,extract)=>this.loc.extract(dt,opts,extract),"string"),formatOffset2=__name2(opts=>dt.isOffsetFixed&&dt.offset===0&&opts.allowZ?"Z":dt.isValid?dt.zone.formatOffset(dt.ts,opts.format):"","formatOffset"),meridiem=__name2(()=>knownEnglish?meridiemForDateTime(dt):string2({hour:"numeric",hourCycle:"h12"},"dayperiod"),"meridiem"),month=__name2((length,standalone)=>knownEnglish?monthForDateTime(dt,length):string2(standalone?{month:length}:{month:length,day:"numeric"},"month"),"month"),weekday=__name2((length,standalone)=>knownEnglish?weekdayForDateTime(dt,length):string2(standalone?{weekday:length}:{weekday:length,month:"long",day:"numeric"},"weekday"),"weekday"),maybeMacro=__name2(token=>{const formatOpts=_Formatter2.macroTokenToFormatOpts(token);return formatOpts?this.formatWithSystemDefault(dt,formatOpts):token},"maybeMacro"),era=__name2(length=>knownEnglish?eraForDateTime(dt,length):string2({era:length},"era"),"era"),tokenToString=__name2(token=>{switch(token){case"S":return this.num(dt.millisecond);case"u":case"SSS":return this.num(dt.millisecond,3);case"s":return this.num(dt.second);case"ss":return this.num(dt.second,2);case"uu":return this.num(Math.floor(dt.millisecond/10),2);case"uuu":return this.num(Math.floor(dt.millisecond/100));case"m":return this.num(dt.minute);case"mm":return this.num(dt.minute,2);case"h":return this.num(dt.hour%12===0?12:dt.hour%12);case"hh":return this.num(dt.hour%12===0?12:dt.hour%12,2);case"H":return this.num(dt.hour);case"HH":return this.num(dt.hour,2);case"Z":return formatOffset2({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return formatOffset2({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return formatOffset2({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return dt.zone.offsetName(dt.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return dt.zone.offsetName(dt.ts,{format:"long",locale:this.loc.locale});case"z":return dt.zoneName;case"a":return meridiem();case"d":return useDateTimeFormatter?string2({day:"numeric"},"day"):this.num(dt.day);case"dd":return useDateTimeFormatter?string2({day:"2-digit"},"day"):this.num(dt.day,2);case"c":return this.num(dt.weekday);case"ccc":return weekday("short",!0);case"cccc":return weekday("long",!0);case"ccccc":return weekday("narrow",!0);case"E":return this.num(dt.weekday);case"EEE":return weekday("short",!1);case"EEEE":return weekday("long",!1);case"EEEEE":return weekday("narrow",!1);case"L":return useDateTimeFormatter?string2({month:"numeric",day:"numeric"},"month"):this.num(dt.month);case"LL":return useDateTimeFormatter?string2({month:"2-digit",day:"numeric"},"month"):this.num(dt.month,2);case"LLL":return month("short",!0);case"LLLL":return month("long",!0);case"LLLLL":return month("narrow",!0);case"M":return useDateTimeFormatter?string2({month:"numeric"},"month"):this.num(dt.month);case"MM":return useDateTimeFormatter?string2({month:"2-digit"},"month"):this.num(dt.month,2);case"MMM":return month("short",!1);case"MMMM":return month("long",!1);case"MMMMM":return month("narrow",!1);case"y":return useDateTimeFormatter?string2({year:"numeric"},"year"):this.num(dt.year);case"yy":return useDateTimeFormatter?string2({year:"2-digit"},"year"):this.num(dt.year.toString().slice(-2),2);case"yyyy":return useDateTimeFormatter?string2({year:"numeric"},"year"):this.num(dt.year,4);case"yyyyyy":return useDateTimeFormatter?string2({year:"numeric"},"year"):this.num(dt.year,6);case"G":return era("short");case"GG":return era("long");case"GGGGG":return era("narrow");case"kk":return this.num(dt.weekYear.toString().slice(-2),2);case"kkkk":return this.num(dt.weekYear,4);case"W":return this.num(dt.weekNumber);case"WW":return this.num(dt.weekNumber,2);case"o":return this.num(dt.ordinal);case"ooo":return this.num(dt.ordinal,3);case"q":return this.num(dt.quarter);case"qq":return this.num(dt.quarter,2);case"X":return this.num(Math.floor(dt.ts/1e3));case"x":return this.num(dt.ts);default:return maybeMacro(token)}},"tokenToString");return stringifyTokens(_Formatter2.parseFormat(fmt),tokenToString)}formatDurationFromString(dur,fmt){const tokenToField=__name2(token=>{switch(token[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},"tokenToField"),tokenToString=__name2(lildur=>token=>{const mapped=tokenToField(token);return mapped?this.num(lildur.get(mapped),token.length):token},"tokenToString"),tokens=_Formatter2.parseFormat(fmt),realTokens=tokens.reduce((found,{literal:literal2,val})=>literal2?found:found.concat(val),[]),collapsed=dur.shiftTo(...realTokens.map(tokenToField).filter(t2=>t2));return stringifyTokens(tokens,tokenToString(collapsed))}};__name2(_Formatter,"Formatter");let Formatter=_Formatter;const _Invalid=class{static{__name(this,"_Invalid")}constructor(reason,explanation){this.reason=reason,this.explanation=explanation}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};__name2(_Invalid,"Invalid");let Invalid=_Invalid;const ianaRegex=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function combineRegexes(...regexes){const full=regexes.reduce((f,r)=>f+r.source,"");return RegExp(`^${full}$`)}__name(combineRegexes,"combineRegexes"),__name2(combineRegexes,"combineRegexes");function combineExtractors(...extractors){return m=>extractors.reduce(([mergedVals,mergedZone,cursor],ex)=>{const[val,zone,next]=ex(m,cursor);return[{...mergedVals,...val},zone||mergedZone,next]},[{},null,1]).slice(0,2)}__name(combineExtractors,"combineExtractors"),__name2(combineExtractors,"combineExtractors");function parse(s2,...patterns){if(s2==null)return[null,null];for(const[regex,extractor]of patterns){const m=regex.exec(s2);if(m)return extractor(m)}return[null,null]}__name(parse,"parse"),__name2(parse,"parse");function simpleParse(...keys2){return(match2,cursor)=>{const ret={};let i;for(i=0;inum!==void 0&&(force||num&&hasNegativePrefix)?-num:num,"maybeNegate");return[{years:maybeNegate(parseFloating(yearStr)),months:maybeNegate(parseFloating(monthStr)),weeks:maybeNegate(parseFloating(weekStr)),days:maybeNegate(parseFloating(dayStr)),hours:maybeNegate(parseFloating(hourStr)),minutes:maybeNegate(parseFloating(minuteStr)),seconds:maybeNegate(parseFloating(secondStr),secondStr==="-0"),milliseconds:maybeNegate(parseMillis(millisecondsStr),negativeSeconds)}]}__name(extractISODuration,"extractISODuration"),__name2(extractISODuration,"extractISODuration");const obsOffsets={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr){const result={year:yearStr.length===2?untruncateYear(parseInteger(yearStr)):parseInteger(yearStr),month:monthsShort.indexOf(monthStr)+1,day:parseInteger(dayStr),hour:parseInteger(hourStr),minute:parseInteger(minuteStr)};return secondStr&&(result.second=parseInteger(secondStr)),weekdayStr&&(result.weekday=weekdayStr.length>3?weekdaysLong.indexOf(weekdayStr)+1:weekdaysShort.indexOf(weekdayStr)+1),result}__name(fromStrings,"fromStrings"),__name2(fromStrings,"fromStrings");const rfc2822=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function extractRFC2822(match2){const[,weekdayStr,dayStr,monthStr,yearStr,hourStr,minuteStr,secondStr,obsOffset,milOffset,offHourStr,offMinuteStr]=match2,result=fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr);let offset2;return obsOffset?offset2=obsOffsets[obsOffset]:milOffset?offset2=0:offset2=signedOffset(offHourStr,offMinuteStr),[result,new FixedOffsetZone(offset2)]}__name(extractRFC2822,"extractRFC2822"),__name2(extractRFC2822,"extractRFC2822");function preprocessRFC2822(s2){return s2.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}__name(preprocessRFC2822,"preprocessRFC2822"),__name2(preprocessRFC2822,"preprocessRFC2822");const rfc1123=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,rfc850=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,ascii=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function extractRFC1123Or850(match2){const[,weekdayStr,dayStr,monthStr,yearStr,hourStr,minuteStr,secondStr]=match2;return[fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr),FixedOffsetZone.utcInstance]}__name(extractRFC1123Or850,"extractRFC1123Or850"),__name2(extractRFC1123Or850,"extractRFC1123Or850");function extractASCII(match2){const[,weekdayStr,monthStr,dayStr,hourStr,minuteStr,secondStr,yearStr]=match2;return[fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr),FixedOffsetZone.utcInstance]}__name(extractASCII,"extractASCII"),__name2(extractASCII,"extractASCII");const isoYmdWithTimeExtensionRegex=combineRegexes(isoYmdRegex,isoTimeExtensionRegex),isoWeekWithTimeExtensionRegex=combineRegexes(isoWeekRegex,isoTimeExtensionRegex),isoOrdinalWithTimeExtensionRegex=combineRegexes(isoOrdinalRegex,isoTimeExtensionRegex),isoTimeCombinedRegex=combineRegexes(isoTimeRegex),extractISOYmdTimeAndOffset=combineExtractors(extractISOYmd,extractISOTime,extractISOOffset,extractIANAZone),extractISOWeekTimeAndOffset=combineExtractors(extractISOWeekData,extractISOTime,extractISOOffset,extractIANAZone),extractISOOrdinalDateAndTime=combineExtractors(extractISOOrdinalData,extractISOTime,extractISOOffset,extractIANAZone),extractISOTimeAndOffset=combineExtractors(extractISOTime,extractISOOffset,extractIANAZone);function parseISODate(s2){return parse(s2,[isoYmdWithTimeExtensionRegex,extractISOYmdTimeAndOffset],[isoWeekWithTimeExtensionRegex,extractISOWeekTimeAndOffset],[isoOrdinalWithTimeExtensionRegex,extractISOOrdinalDateAndTime],[isoTimeCombinedRegex,extractISOTimeAndOffset])}__name(parseISODate,"parseISODate"),__name2(parseISODate,"parseISODate");function parseRFC2822Date(s2){return parse(preprocessRFC2822(s2),[rfc2822,extractRFC2822])}__name(parseRFC2822Date,"parseRFC2822Date"),__name2(parseRFC2822Date,"parseRFC2822Date");function parseHTTPDate(s2){return parse(s2,[rfc1123,extractRFC1123Or850],[rfc850,extractRFC1123Or850],[ascii,extractASCII])}__name(parseHTTPDate,"parseHTTPDate"),__name2(parseHTTPDate,"parseHTTPDate");function parseISODuration(s2){return parse(s2,[isoDuration,extractISODuration])}__name(parseISODuration,"parseISODuration"),__name2(parseISODuration,"parseISODuration");const extractISOTimeOnly=combineExtractors(extractISOTime);function parseISOTimeOnly(s2){return parse(s2,[isoTimeOnly,extractISOTimeOnly])}__name(parseISOTimeOnly,"parseISOTimeOnly"),__name2(parseISOTimeOnly,"parseISOTimeOnly");const sqlYmdWithTimeExtensionRegex=combineRegexes(sqlYmdRegex,sqlTimeExtensionRegex),sqlTimeCombinedRegex=combineRegexes(sqlTimeRegex),extractISOTimeOffsetAndIANAZone=combineExtractors(extractISOTime,extractISOOffset,extractIANAZone);function parseSQL(s2){return parse(s2,[sqlYmdWithTimeExtensionRegex,extractISOYmdTimeAndOffset],[sqlTimeCombinedRegex,extractISOTimeOffsetAndIANAZone])}__name(parseSQL,"parseSQL"),__name2(parseSQL,"parseSQL");const INVALID$2="Invalid Duration",lowOrderMatrix={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},casualMatrix={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...lowOrderMatrix},daysInYearAccurate=146097/400,daysInMonthAccurate=146097/4800,accurateMatrix={years:{quarters:4,months:12,weeks:daysInYearAccurate/7,days:daysInYearAccurate,hours:daysInYearAccurate*24,minutes:daysInYearAccurate*24*60,seconds:daysInYearAccurate*24*60*60,milliseconds:daysInYearAccurate*24*60*60*1e3},quarters:{months:3,weeks:daysInYearAccurate/28,days:daysInYearAccurate/4,hours:daysInYearAccurate*24/4,minutes:daysInYearAccurate*24*60/4,seconds:daysInYearAccurate*24*60*60/4,milliseconds:daysInYearAccurate*24*60*60*1e3/4},months:{weeks:daysInMonthAccurate/7,days:daysInMonthAccurate,hours:daysInMonthAccurate*24,minutes:daysInMonthAccurate*24*60,seconds:daysInMonthAccurate*24*60*60,milliseconds:daysInMonthAccurate*24*60*60*1e3},...lowOrderMatrix},orderedUnits$1=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],reverseUnits=orderedUnits$1.slice(0).reverse();function clone$1(dur,alts,clear=!1){const conf={values:clear?alts.values:{...dur.values,...alts.values||{}},loc:dur.loc.clone(alts.loc),conversionAccuracy:alts.conversionAccuracy||dur.conversionAccuracy,matrix:alts.matrix||dur.matrix};return new Duration(conf)}__name(clone$1,"clone$1"),__name2(clone$1,"clone$1");function durationToMillis(matrix2,vals){let sum=vals.milliseconds??0;for(const unit of reverseUnits.slice(1))vals[unit]&&(sum+=vals[unit]*matrix2[unit].milliseconds);return sum}__name(durationToMillis,"durationToMillis"),__name2(durationToMillis,"durationToMillis");function normalizeValues(matrix2,vals){const factor=durationToMillis(matrix2,vals)<0?-1:1;orderedUnits$1.reduceRight((previous,current)=>{if(isUndefined(vals[current]))return previous;if(previous){const previousVal=vals[previous]*factor,conv=matrix2[current][previous],rollUp=Math.floor(previousVal/conv);vals[current]+=rollUp*factor,vals[previous]-=rollUp*conv*factor}return current},null),orderedUnits$1.reduce((previous,current)=>{if(isUndefined(vals[current]))return previous;if(previous){const fraction=vals[previous]%1;vals[previous]-=fraction,vals[current]+=fraction*matrix2[previous][current]}return current},null)}__name(normalizeValues,"normalizeValues"),__name2(normalizeValues,"normalizeValues");function removeZeroes(vals){const newVals={};for(const[key,value]of Object.entries(vals))value!==0&&(newVals[key]=value);return newVals}__name(removeZeroes,"removeZeroes"),__name2(removeZeroes,"removeZeroes");const _Duration=class _Duration2{static{__name(this,"_Duration")}constructor(config2){const accurate=config2.conversionAccuracy==="longterm"||!1;let matrix2=accurate?accurateMatrix:casualMatrix;config2.matrix&&(matrix2=config2.matrix),this.values=config2.values,this.loc=config2.loc||Locale.create(),this.conversionAccuracy=accurate?"longterm":"casual",this.invalid=config2.invalid||null,this.matrix=matrix2,this.isLuxonDuration=!0}static fromMillis(count,opts){return _Duration2.fromObject({milliseconds:count},opts)}static fromObject(obj,opts={}){if(obj==null||typeof obj!="object")throw new InvalidArgumentError(`Duration.fromObject: argument expected to be an object, got ${obj===null?"null":typeof obj}`);return new _Duration2({values:normalizeObject(obj,_Duration2.normalizeUnit),loc:Locale.fromObject(opts),conversionAccuracy:opts.conversionAccuracy,matrix:opts.matrix})}static fromDurationLike(durationLike){if(isNumber(durationLike))return _Duration2.fromMillis(durationLike);if(_Duration2.isDuration(durationLike))return durationLike;if(typeof durationLike=="object")return _Duration2.fromObject(durationLike);throw new InvalidArgumentError(`Unknown duration argument ${durationLike} of type ${typeof durationLike}`)}static fromISO(text,opts){const[parsed]=parseISODuration(text);return parsed?_Duration2.fromObject(parsed,opts):_Duration2.invalid("unparsable",`the input "${text}" can't be parsed as ISO 8601`)}static fromISOTime(text,opts){const[parsed]=parseISOTimeOnly(text);return parsed?_Duration2.fromObject(parsed,opts):_Duration2.invalid("unparsable",`the input "${text}" can't be parsed as ISO 8601`)}static invalid(reason,explanation=null){if(!reason)throw new InvalidArgumentError("need to specify a reason the Duration is invalid");const invalid=reason instanceof Invalid?reason:new Invalid(reason,explanation);if(Settings.throwOnInvalid)throw new InvalidDurationError(invalid);return new _Duration2({invalid})}static normalizeUnit(unit){const normalized={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[unit&&unit.toLowerCase()];if(!normalized)throw new InvalidUnitError(unit);return normalized}static isDuration(o){return o&&o.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(fmt,opts={}){const fmtOpts={...opts,floor:opts.round!==!1&&opts.floor!==!1};return this.isValid?Formatter.create(this.loc,fmtOpts).formatDurationFromString(this,fmt):INVALID$2}toHuman(opts={}){if(!this.isValid)return INVALID$2;const l2=orderedUnits$1.map(unit=>{const val=this.values[unit];return isUndefined(val)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...opts,unit:unit.slice(0,-1)}).format(val)}).filter(n2=>n2);return this.loc.listFormatter({type:"conjunction",style:opts.listStyle||"narrow",...opts}).format(l2)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let s2="P";return this.years!==0&&(s2+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(s2+=this.months+this.quarters*3+"M"),this.weeks!==0&&(s2+=this.weeks+"W"),this.days!==0&&(s2+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(s2+="T"),this.hours!==0&&(s2+=this.hours+"H"),this.minutes!==0&&(s2+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(s2+=roundTo(this.seconds+this.milliseconds/1e3,3)+"S"),s2==="P"&&(s2+="T0S"),s2}toISOTime(opts={}){if(!this.isValid)return null;const millis=this.toMillis();return millis<0||millis>=864e5?null:(opts={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...opts,includeOffset:!1},DateTime.fromMillis(millis,{zone:"UTC"}).toISOTime(opts))}toJSON(){return this.toISO()}toString(){return this.toISO()}toMillis(){return this.isValid?durationToMillis(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(duration){if(!this.isValid)return this;const dur=_Duration2.fromDurationLike(duration),result={};for(const k of orderedUnits$1)(hasOwnProperty(dur.values,k)||hasOwnProperty(this.values,k))&&(result[k]=dur.get(k)+this.get(k));return clone$1(this,{values:result},!0)}minus(duration){if(!this.isValid)return this;const dur=_Duration2.fromDurationLike(duration);return this.plus(dur.negate())}mapUnits(fn){if(!this.isValid)return this;const result={};for(const k of Object.keys(this.values))result[k]=asNumber(fn(this.values[k],k));return clone$1(this,{values:result},!0)}get(unit){return this[_Duration2.normalizeUnit(unit)]}set(values){if(!this.isValid)return this;const mixed={...this.values,...normalizeObject(values,_Duration2.normalizeUnit)};return clone$1(this,{values:mixed})}reconfigure({locale,numberingSystem,conversionAccuracy,matrix:matrix2}={}){const opts={loc:this.loc.clone({locale,numberingSystem}),matrix:matrix2,conversionAccuracy};return clone$1(this,opts)}as(unit){return this.isValid?this.shiftTo(unit).get(unit):NaN}normalize(){if(!this.isValid)return this;const vals=this.toObject();return normalizeValues(this.matrix,vals),clone$1(this,{values:vals},!0)}rescale(){if(!this.isValid)return this;const vals=removeZeroes(this.normalize().shiftToAll().toObject());return clone$1(this,{values:vals},!0)}shiftTo(...units){if(!this.isValid)return this;if(units.length===0)return this;units=units.map(u=>_Duration2.normalizeUnit(u));const built={},accumulated={},vals=this.toObject();let lastUnit;for(const k of orderedUnits$1)if(units.indexOf(k)>=0){lastUnit=k;let own=0;for(const ak in accumulated)own+=this.matrix[ak][k]*accumulated[ak],accumulated[ak]=0;isNumber(vals[k])&&(own+=vals[k]);const i=Math.trunc(own);built[k]=i,accumulated[k]=(own*1e3-i*1e3)/1e3}else isNumber(vals[k])&&(accumulated[k]=vals[k]);for(const key in accumulated)accumulated[key]!==0&&(built[lastUnit]+=key===lastUnit?accumulated[key]:accumulated[key]/this.matrix[lastUnit][key]);return normalizeValues(this.matrix,built),clone$1(this,{values:built},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const negated={};for(const k of Object.keys(this.values))negated[k]=this.values[k]===0?0:-this.values[k];return clone$1(this,{values:negated},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(other){if(!this.isValid||!other.isValid||!this.loc.equals(other.loc))return!1;function eq(v1,v2){return v1===void 0||v1===0?v2===void 0||v2===0:v1===v2}__name(eq,"eq"),__name2(eq,"eq");for(const u of orderedUnits$1)if(!eq(this.values[u],other.values[u]))return!1;return!0}};__name2(_Duration,"Duration");let Duration=_Duration;const INVALID$1="Invalid Interval";function validateStartEnd(start,end){return!start||!start.isValid?Interval.invalid("missing or invalid start"):!end||!end.isValid?Interval.invalid("missing or invalid end"):enddateTime:!1}isBefore(dateTime){return this.isValid?this.e<=dateTime:!1}contains(dateTime){return this.isValid?this.s<=dateTime&&this.e>dateTime:!1}set({start,end}={}){return this.isValid?_Interval2.fromDateTimes(start||this.s,end||this.e):this}splitAt(...dateTimes){if(!this.isValid)return[];const sorted=dateTimes.map(friendlyDateTime).filter(d=>this.contains(d)).sort(),results=[];let{s:s2}=this,i=0;for(;s2+this.e?this.e:added;results.push(_Interval2.fromDateTimes(s2,next)),s2=next,i+=1}return results}splitBy(duration){const dur=Duration.fromDurationLike(duration);if(!this.isValid||!dur.isValid||dur.as("milliseconds")===0)return[];let{s:s2}=this,idx=1,next;const results=[];for(;s2x*idx));next=+added>+this.e?this.e:added,results.push(_Interval2.fromDateTimes(s2,next)),s2=next,idx+=1}return results}divideEqually(numberOfParts){return this.isValid?this.splitBy(this.length()/numberOfParts).slice(0,numberOfParts):[]}overlaps(other){return this.e>other.s&&this.s=other.e:!1}equals(other){return!this.isValid||!other.isValid?!1:this.s.equals(other.s)&&this.e.equals(other.e)}intersection(other){if(!this.isValid)return this;const s2=this.s>other.s?this.s:other.s,e=this.e=e?null:_Interval2.fromDateTimes(s2,e)}union(other){if(!this.isValid)return this;const s2=this.sother.e?this.e:other.e;return _Interval2.fromDateTimes(s2,e)}static merge(intervals){const[found,final]=intervals.sort((a,b)=>a.s-b.s).reduce(([sofar,current],item)=>current?current.overlaps(item)||current.abutsStart(item)?[sofar,current.union(item)]:[sofar.concat([current]),item]:[sofar,item],[[],null]);return final&&found.push(final),found}static xor(intervals){let start=null,currentCount=0;const results=[],ends=intervals.map(i=>[{time:i.s,type:"s"},{time:i.e,type:"e"}]),flattened2=Array.prototype.concat(...ends),arr=flattened2.sort((a,b)=>a.time-b.time);for(const i of arr)currentCount+=i.type==="s"?1:-1,currentCount===1?start=i.time:(start&&+start!=+i.time&&results.push(_Interval2.fromDateTimes(start,i.time)),start=null);return _Interval2.merge(results)}difference(...intervals){return _Interval2.xor([this].concat(intervals)).map(i=>this.intersection(i)).filter(i=>i&&!i.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:INVALID$1}toLocaleString(formatOpts=DATE_SHORT,opts={}){return this.isValid?Formatter.create(this.s.loc.clone(opts),formatOpts).formatInterval(this):INVALID$1}toISO(opts){return this.isValid?`${this.s.toISO(opts)}/${this.e.toISO(opts)}`:INVALID$1}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:INVALID$1}toISOTime(opts){return this.isValid?`${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`:INVALID$1}toFormat(dateFormat,{separator=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`:INVALID$1}toDuration(unit,opts){return this.isValid?this.e.diff(this.s,unit,opts):Duration.invalid(this.invalidReason)}mapEndpoints(mapFn){return _Interval2.fromDateTimes(mapFn(this.s),mapFn(this.e))}};__name2(_Interval,"Interval");let Interval=_Interval;const _Info=class{static{__name(this,"_Info")}static hasDST(zone=Settings.defaultZone){const proto=DateTime.now().setZone(zone).set({month:12});return!zone.isUniversal&&proto.offset!==proto.set({month:6}).offset}static isValidIANAZone(zone){return IANAZone.isValidZone(zone)}static normalizeZone(input){return normalizeZone(input,Settings.defaultZone)}static months(length="long",{locale=null,numberingSystem=null,locObj=null,outputCalendar="gregory"}={}){return(locObj||Locale.create(locale,numberingSystem,outputCalendar)).months(length)}static monthsFormat(length="long",{locale=null,numberingSystem=null,locObj=null,outputCalendar="gregory"}={}){return(locObj||Locale.create(locale,numberingSystem,outputCalendar)).months(length,!0)}static weekdays(length="long",{locale=null,numberingSystem=null,locObj=null}={}){return(locObj||Locale.create(locale,numberingSystem,null)).weekdays(length)}static weekdaysFormat(length="long",{locale=null,numberingSystem=null,locObj=null}={}){return(locObj||Locale.create(locale,numberingSystem,null)).weekdays(length,!0)}static meridiems({locale=null}={}){return Locale.create(locale).meridiems()}static eras(length="short",{locale=null}={}){return Locale.create(locale,null,"gregory").eras(length)}static features(){return{relative:hasRelative()}}};__name2(_Info,"Info");let Info=_Info;function dayDiff(earlier,later){const utcDayStart=__name2(dt=>dt.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),"utcDayStart"),ms=utcDayStart(later)-utcDayStart(earlier);return Math.floor(Duration.fromMillis(ms).as("days"))}__name(dayDiff,"dayDiff"),__name2(dayDiff,"dayDiff");function highOrderDiffs(cursor,later,units){const differs=[["years",(a,b)=>b.year-a.year],["quarters",(a,b)=>b.quarter-a.quarter+(b.year-a.year)*4],["months",(a,b)=>b.month-a.month+(b.year-a.year)*12],["weeks",(a,b)=>{const days=dayDiff(a,b);return(days-days%7)/7}],["days",dayDiff]],results={},earlier=cursor;let lowestOrder,highWater;for(const[unit,differ]of differs)units.indexOf(unit)>=0&&(lowestOrder=unit,results[unit]=differ(cursor,later),highWater=earlier.plus(results),highWater>later?(results[unit]--,cursor=earlier.plus(results),cursor>later&&(highWater=cursor,results[unit]--,cursor=earlier.plus(results))):cursor=highWater);return[cursor,results,highWater,lowestOrder]}__name(highOrderDiffs,"highOrderDiffs"),__name2(highOrderDiffs,"highOrderDiffs");function diff(earlier,later,units,opts){let[cursor,results,highWater,lowestOrder]=highOrderDiffs(earlier,later,units);const remainingMillis=later-cursor,lowerOrderUnits=units.filter(u=>["hours","minutes","seconds","milliseconds"].indexOf(u)>=0);lowerOrderUnits.length===0&&(highWater0?Duration.fromMillis(remainingMillis,opts).shiftTo(...lowerOrderUnits).plus(duration):duration}__name(diff,"diff"),__name2(diff,"diff");const numberingSystems={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},numberingSystemsUTF16={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},hanidecChars=numberingSystems.hanidec.replace(/[\[|\]]/g,"").split("");function parseDigits(str){let value=parseInt(str,10);if(isNaN(value)){value="";for(let i=0;i=min&&code<=max&&(value+=code-min)}}return parseInt(value,10)}else return value}__name(parseDigits,"parseDigits"),__name2(parseDigits,"parseDigits");function digitRegex({numberingSystem},append=""){return new RegExp(`${numberingSystems[numberingSystem||"latn"]}${append}`)}__name(digitRegex,"digitRegex"),__name2(digitRegex,"digitRegex");const MISSING_FTP="missing Intl.DateTimeFormat.formatToParts support";function intUnit(regex,post=i=>i){return{regex,deser:([s2])=>post(parseDigits(s2))}}__name(intUnit,"intUnit"),__name2(intUnit,"intUnit");const NBSP=String.fromCharCode(160),spaceOrNBSP=`[ ${NBSP}]`,spaceOrNBSPRegExp=new RegExp(spaceOrNBSP,"g");function fixListRegex(s2){return s2.replace(/\./g,"\\.?").replace(spaceOrNBSPRegExp,spaceOrNBSP)}__name(fixListRegex,"fixListRegex"),__name2(fixListRegex,"fixListRegex");function stripInsensitivities(s2){return s2.replace(/\./g,"").replace(spaceOrNBSPRegExp," ").toLowerCase()}__name(stripInsensitivities,"stripInsensitivities"),__name2(stripInsensitivities,"stripInsensitivities");function oneOf(strings,startIndex){return strings===null?null:{regex:RegExp(strings.map(fixListRegex).join("|")),deser:([s2])=>strings.findIndex(i=>stripInsensitivities(s2)===stripInsensitivities(i))+startIndex}}__name(oneOf,"oneOf"),__name2(oneOf,"oneOf");function offset$1(regex,groups){return{regex,deser:([,h,m])=>signedOffset(h,m),groups}}__name(offset$1,"offset$1"),__name2(offset$1,"offset$1");function simple(regex){return{regex,deser:([s2])=>s2}}__name(simple,"simple"),__name2(simple,"simple");function escapeToken(value){return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}__name(escapeToken,"escapeToken"),__name2(escapeToken,"escapeToken");function unitForToken(token,loc){const one=digitRegex(loc),two=digitRegex(loc,"{2}"),three=digitRegex(loc,"{3}"),four=digitRegex(loc,"{4}"),six=digitRegex(loc,"{6}"),oneOrTwo=digitRegex(loc,"{1,2}"),oneToThree=digitRegex(loc,"{1,3}"),oneToSix=digitRegex(loc,"{1,6}"),oneToNine=digitRegex(loc,"{1,9}"),twoToFour=digitRegex(loc,"{2,4}"),fourToSix=digitRegex(loc,"{4,6}"),literal2=__name2(t2=>({regex:RegExp(escapeToken(t2.val)),deser:([s2])=>s2,literal:!0}),"literal"),unit=__name2(t2=>{if(token.literal)return literal2(t2);switch(t2.val){case"G":return oneOf(loc.eras("short"),0);case"GG":return oneOf(loc.eras("long"),0);case"y":return intUnit(oneToSix);case"yy":return intUnit(twoToFour,untruncateYear);case"yyyy":return intUnit(four);case"yyyyy":return intUnit(fourToSix);case"yyyyyy":return intUnit(six);case"M":return intUnit(oneOrTwo);case"MM":return intUnit(two);case"MMM":return oneOf(loc.months("short",!0),1);case"MMMM":return oneOf(loc.months("long",!0),1);case"L":return intUnit(oneOrTwo);case"LL":return intUnit(two);case"LLL":return oneOf(loc.months("short",!1),1);case"LLLL":return oneOf(loc.months("long",!1),1);case"d":return intUnit(oneOrTwo);case"dd":return intUnit(two);case"o":return intUnit(oneToThree);case"ooo":return intUnit(three);case"HH":return intUnit(two);case"H":return intUnit(oneOrTwo);case"hh":return intUnit(two);case"h":return intUnit(oneOrTwo);case"mm":return intUnit(two);case"m":return intUnit(oneOrTwo);case"q":return intUnit(oneOrTwo);case"qq":return intUnit(two);case"s":return intUnit(oneOrTwo);case"ss":return intUnit(two);case"S":return intUnit(oneToThree);case"SSS":return intUnit(three);case"u":return simple(oneToNine);case"uu":return simple(oneOrTwo);case"uuu":return intUnit(one);case"a":return oneOf(loc.meridiems(),0);case"kkkk":return intUnit(four);case"kk":return intUnit(twoToFour,untruncateYear);case"W":return intUnit(oneOrTwo);case"WW":return intUnit(two);case"E":case"c":return intUnit(one);case"EEE":return oneOf(loc.weekdays("short",!1),1);case"EEEE":return oneOf(loc.weekdays("long",!1),1);case"ccc":return oneOf(loc.weekdays("short",!0),1);case"cccc":return oneOf(loc.weekdays("long",!0),1);case"Z":case"ZZ":return offset$1(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`),2);case"ZZZ":return offset$1(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`),2);case"z":return simple(/[a-z_+-/]{1,256}?/i);case" ":return simple(/[^\S\n\r]/);default:return literal2(t2)}},"unitate")(token)||{invalidReason:MISSING_FTP};return unit.token=token,unit}__name(unitForToken,"unitForToken"),__name2(unitForToken,"unitForToken");const partTypeStyleToTokenVal={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function tokenForPart(part,formatOpts,resolvedOpts){const{type,value}=part;if(type==="literal"){const isSpace=/^\s+$/.test(value);return{literal:!isSpace,val:isSpace?" ":value}}const style=formatOpts[type];let actualType=type;type==="hour"&&(formatOpts.hour12!=null?actualType=formatOpts.hour12?"hour12":"hour24":formatOpts.hourCycle!=null?formatOpts.hourCycle==="h11"||formatOpts.hourCycle==="h12"?actualType="hour12":actualType="hour24":actualType=resolvedOpts.hour12?"hour12":"hour24");let val=partTypeStyleToTokenVal[actualType];if(typeof val=="object"&&(val=val[style]),val)return{literal:!1,val}}__name(tokenForPart,"tokenForPart"),__name2(tokenForPart,"tokenForPart");function buildRegex(units){return[`^${units.map(u=>u.regex).reduce((f,r)=>`${f}(${r.source})`,"")}$`,units]}__name(buildRegex,"buildRegex"),__name2(buildRegex,"buildRegex");function match(input,regex,handlers2){const matches2=input.match(regex);if(matches2){const all={};let matchIndex=1;for(const i in handlers2)if(hasOwnProperty(handlers2,i)){const h=handlers2[i],groups=h.groups?h.groups+1:1;!h.literal&&h.token&&(all[h.token.val[0]]=h.deser(matches2.slice(matchIndex,matchIndex+groups))),matchIndex+=groups}return[matches2,all]}else return[matches2,{}]}__name(match,"match"),__name2(match,"match");function dateTimeFromMatches(matches2){const toField=__name2(token=>{switch(token){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},"toField");let zone=null,specificOffset;return isUndefined(matches2.z)||(zone=IANAZone.create(matches2.z)),isUndefined(matches2.Z)||(zone||(zone=new FixedOffsetZone(matches2.Z)),specificOffset=matches2.Z),isUndefined(matches2.q)||(matches2.M=(matches2.q-1)*3+1),isUndefined(matches2.h)||(matches2.h<12&&matches2.a===1?matches2.h+=12:matches2.h===12&&matches2.a===0&&(matches2.h=0)),matches2.G===0&&matches2.y&&(matches2.y=-matches2.y),isUndefined(matches2.u)||(matches2.S=parseMillis(matches2.u)),[Object.keys(matches2).reduce((r,k)=>{const f=toField(k);return f&&(r[f]=matches2[k]),r},{}),zone,specificOffset]}__name(dateTimeFromMatches,"dateTimeFromMatches"),__name2(dateTimeFromMatches,"dateTimeFromMatches");let dummyDateTimeCache=null;function getDummyDateTime(){return dummyDateTimeCache||(dummyDateTimeCache=DateTime.fromMillis(1555555555555)),dummyDateTimeCache}__name(getDummyDateTime,"getDummyDateTime"),__name2(getDummyDateTime,"getDummyDateTime");function maybeExpandMacroToken(token,locale){if(token.literal)return token;const formatOpts=Formatter.macroTokenToFormatOpts(token.val),tokens=formatOptsToTokens(formatOpts,locale);return tokens==null||tokens.includes(void 0)?token:tokens}__name(maybeExpandMacroToken,"maybeExpandMacroToken"),__name2(maybeExpandMacroToken,"maybeExpandMacroToken");function expandMacroTokens(tokens,locale){return Array.prototype.concat(...tokens.map(t2=>maybeExpandMacroToken(t2,locale)))}__name(expandMacroTokens,"expandMacroTokens"),__name2(expandMacroTokens,"expandMacroTokens");function explainFromTokens(locale,input,format){const tokens=expandMacroTokens(Formatter.parseFormat(format),locale),units=tokens.map(t2=>unitForToken(t2,locale)),disqualifyingUnit=units.find(t2=>t2.invalidReason);if(disqualifyingUnit)return{input,tokens,invalidReason:disqualifyingUnit.invalidReason};{const[regexString,handlers2]=buildRegex(units),regex=RegExp(regexString,"i"),[rawMatches,matches2]=match(input,regex,handlers2),[result,zone,specificOffset]=matches2?dateTimeFromMatches(matches2):[null,null,void 0];if(hasOwnProperty(matches2,"a")&&hasOwnProperty(matches2,"H"))throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format");return{input,tokens,regex,rawMatches,matches:matches2,result,zone,specificOffset}}}__name(explainFromTokens,"explainFromTokens"),__name2(explainFromTokens,"explainFromTokens");function parseFromTokens(locale,input,format){const{result,zone,specificOffset,invalidReason}=explainFromTokens(locale,input,format);return[result,zone,specificOffset,invalidReason]}__name(parseFromTokens,"parseFromTokens"),__name2(parseFromTokens,"parseFromTokens");function formatOptsToTokens(formatOpts,locale){if(!formatOpts)return null;const df=Formatter.create(locale,formatOpts).dtFormatter(getDummyDateTime()),parts=df.formatToParts(),resolvedOpts=df.resolvedOptions();return parts.map(p=>tokenForPart(p,formatOpts,resolvedOpts))}__name(formatOptsToTokens,"formatOptsToTokens"),__name2(formatOptsToTokens,"formatOptsToTokens");const nonLeapLadder=[0,31,59,90,120,151,181,212,243,273,304,334],leapLadder=[0,31,60,91,121,152,182,213,244,274,305,335];function unitOutOfRange(unit,value){return new Invalid("unit out of range",`you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`)}__name(unitOutOfRange,"unitOutOfRange"),__name2(unitOutOfRange,"unitOutOfRange");function dayOfWeek(year,month,day){const d=new Date(Date.UTC(year,month-1,day));year<100&&year>=0&&d.setUTCFullYear(d.getUTCFullYear()-1900);const js=d.getUTCDay();return js===0?7:js}__name(dayOfWeek,"dayOfWeek"),__name2(dayOfWeek,"dayOfWeek");function computeOrdinal(year,month,day){return day+(isLeapYear(year)?leapLadder:nonLeapLadder)[month-1]}__name(computeOrdinal,"computeOrdinal"),__name2(computeOrdinal,"computeOrdinal");function uncomputeOrdinal(year,ordinal){const table=isLeapYear(year)?leapLadder:nonLeapLadder,month0=table.findIndex(i=>iweeksInWeekYear(year)?(weekYear=year+1,weekNumber=1):weekYear=year,{weekYear,weekNumber,weekday,...timeObject(gregObj)}}__name(gregorianToWeek,"gregorianToWeek"),__name2(gregorianToWeek,"gregorianToWeek");function weekToGregorian(weekData){const{weekYear,weekNumber,weekday}=weekData,weekdayOfJan4=dayOfWeek(weekYear,1,4),yearInDays=daysInYear(weekYear);let ordinal=weekNumber*7+weekday-weekdayOfJan4-3,year;ordinal<1?(year=weekYear-1,ordinal+=daysInYear(year)):ordinal>yearInDays?(year=weekYear+1,ordinal-=daysInYear(weekYear)):year=weekYear;const{month,day}=uncomputeOrdinal(year,ordinal);return{year,month,day,...timeObject(weekData)}}__name(weekToGregorian,"weekToGregorian"),__name2(weekToGregorian,"weekToGregorian");function gregorianToOrdinal(gregData){const{year,month,day}=gregData,ordinal=computeOrdinal(year,month,day);return{year,ordinal,...timeObject(gregData)}}__name(gregorianToOrdinal,"gregorianToOrdinal"),__name2(gregorianToOrdinal,"gregorianToOrdinal");function ordinalToGregorian(ordinalData){const{year,ordinal}=ordinalData,{month,day}=uncomputeOrdinal(year,ordinal);return{year,month,day,...timeObject(ordinalData)}}__name(ordinalToGregorian,"ordinalToGregorian"),__name2(ordinalToGregorian,"ordinalToGregorian");function hasInvalidWeekData(obj){const validYear=isInteger(obj.weekYear),validWeek=integerBetween(obj.weekNumber,1,weeksInWeekYear(obj.weekYear)),validWeekday=integerBetween(obj.weekday,1,7);return validYear?validWeek?validWeekday?!1:unitOutOfRange("weekday",obj.weekday):unitOutOfRange("week",obj.week):unitOutOfRange("weekYear",obj.weekYear)}__name(hasInvalidWeekData,"hasInvalidWeekData"),__name2(hasInvalidWeekData,"hasInvalidWeekData");function hasInvalidOrdinalData(obj){const validYear=isInteger(obj.year),validOrdinal=integerBetween(obj.ordinal,1,daysInYear(obj.year));return validYear?validOrdinal?!1:unitOutOfRange("ordinal",obj.ordinal):unitOutOfRange("year",obj.year)}__name(hasInvalidOrdinalData,"hasInvalidOrdinalData"),__name2(hasInvalidOrdinalData,"hasInvalidOrdinalData");function hasInvalidGregorianData(obj){const validYear=isInteger(obj.year),validMonth=integerBetween(obj.month,1,12),validDay=integerBetween(obj.day,1,daysInMonth(obj.year,obj.month));return validYear?validMonth?validDay?!1:unitOutOfRange("day",obj.day):unitOutOfRange("month",obj.month):unitOutOfRange("year",obj.year)}__name(hasInvalidGregorianData,"hasInvalidGregorianData"),__name2(hasInvalidGregorianData,"hasInvalidGregorianData");function hasInvalidTimeData(obj){const{hour,minute,second,millisecond}=obj,validHour=integerBetween(hour,0,23)||hour===24&&minute===0&&second===0&&millisecond===0,validMinute=integerBetween(minute,0,59),validSecond=integerBetween(second,0,59),validMillisecond=integerBetween(millisecond,0,999);return validHour?validMinute?validSecond?validMillisecond?!1:unitOutOfRange("millisecond",millisecond):unitOutOfRange("second",second):unitOutOfRange("minute",minute):unitOutOfRange("hour",hour)}__name(hasInvalidTimeData,"hasInvalidTimeData"),__name2(hasInvalidTimeData,"hasInvalidTimeData");const INVALID="Invalid DateTime",MAX_DATE=864e13;function unsupportedZone(zone){return new Invalid("unsupported zone",`the zone "${zone.name}" is not supported`)}__name(unsupportedZone,"unsupportedZone"),__name2(unsupportedZone,"unsupportedZone");function possiblyCachedWeekData(dt){return dt.weekData===null&&(dt.weekData=gregorianToWeek(dt.c)),dt.weekData}__name(possiblyCachedWeekData,"possiblyCachedWeekData"),__name2(possiblyCachedWeekData,"possiblyCachedWeekData");function clone(inst,alts){const current={ts:inst.ts,zone:inst.zone,c:inst.c,o:inst.o,loc:inst.loc,invalid:inst.invalid};return new DateTime({...current,...alts,old:current})}__name(clone,"clone"),__name2(clone,"clone");function fixOffset(localTS,o,tz){let utcGuess=localTS-o*60*1e3;const o2=tz.offset(utcGuess);if(o===o2)return[utcGuess,o];utcGuess-=(o2-o)*60*1e3;const o3=tz.offset(utcGuess);return o2===o3?[utcGuess,o2]:[localTS-Math.min(o2,o3)*60*1e3,Math.max(o2,o3)]}__name(fixOffset,"fixOffset"),__name2(fixOffset,"fixOffset");function tsToObj(ts,offset2){ts+=offset2*60*1e3;const d=new Date(ts);return{year:d.getUTCFullYear(),month:d.getUTCMonth()+1,day:d.getUTCDate(),hour:d.getUTCHours(),minute:d.getUTCMinutes(),second:d.getUTCSeconds(),millisecond:d.getUTCMilliseconds()}}__name(tsToObj,"tsToObj"),__name2(tsToObj,"tsToObj");function objToTS(obj,offset2,zone){return fixOffset(objToLocalTS(obj),offset2,zone)}__name(objToTS,"objToTS"),__name2(objToTS,"objToTS");function adjustTime(inst,dur){const oPre=inst.o,year=inst.c.year+Math.trunc(dur.years),month=inst.c.month+Math.trunc(dur.months)+Math.trunc(dur.quarters)*3,c={...inst.c,year,month,day:Math.min(inst.c.day,daysInMonth(year,month))+Math.trunc(dur.days)+Math.trunc(dur.weeks)*7},millisToAdd=Duration.fromObject({years:dur.years-Math.trunc(dur.years),quarters:dur.quarters-Math.trunc(dur.quarters),months:dur.months-Math.trunc(dur.months),weeks:dur.weeks-Math.trunc(dur.weeks),days:dur.days-Math.trunc(dur.days),hours:dur.hours,minutes:dur.minutes,seconds:dur.seconds,milliseconds:dur.milliseconds}).as("milliseconds"),localTS=objToLocalTS(c);let[ts,o]=fixOffset(localTS,oPre,inst.zone);return millisToAdd!==0&&(ts+=millisToAdd,o=inst.zone.offset(ts)),{ts,o}}__name(adjustTime,"adjustTime"),__name2(adjustTime,"adjustTime");function parseDataToDateTime(parsed,parsedZone,opts,format,text,specificOffset){const{setZone,zone}=opts;if(parsed&&Object.keys(parsed).length!==0||parsedZone){const interpretationZone=parsedZone||zone,inst=DateTime.fromObject(parsed,{...opts,zone:interpretationZone,specificOffset});return setZone?inst:inst.setZone(zone)}else return DateTime.invalid(new Invalid("unparsable",`the input "${text}" can't be parsed as ${format}`))}__name(parseDataToDateTime,"parseDataToDateTime"),__name2(parseDataToDateTime,"parseDataToDateTime");function toTechFormat(dt,format,allowZ=!0){return dt.isValid?Formatter.create(Locale.create("en-US"),{allowZ,forceSimple:!0}).formatDateTimeFromString(dt,format):null}__name(toTechFormat,"toTechFormat"),__name2(toTechFormat,"toTechFormat");function toISODate(o,extended){const longFormat=o.c.year>9999||o.c.year<0;let c="";return longFormat&&o.c.year>=0&&(c+="+"),c+=padStart(o.c.year,longFormat?6:4),extended?(c+="-",c+=padStart(o.c.month),c+="-",c+=padStart(o.c.day)):(c+=padStart(o.c.month),c+=padStart(o.c.day)),c}__name(toISODate,"toISODate"),__name2(toISODate,"toISODate");function toISOTime(o,extended,suppressSeconds,suppressMilliseconds,includeOffset,extendedZone){let c=padStart(o.c.hour);return extended?(c+=":",c+=padStart(o.c.minute),(o.c.millisecond!==0||o.c.second!==0||!suppressSeconds)&&(c+=":")):c+=padStart(o.c.minute),(o.c.millisecond!==0||o.c.second!==0||!suppressSeconds)&&(c+=padStart(o.c.second),(o.c.millisecond!==0||!suppressMilliseconds)&&(c+=".",c+=padStart(o.c.millisecond,3))),includeOffset&&(o.isOffsetFixed&&o.offset===0&&!extendedZone?c+="Z":o.o<0?(c+="-",c+=padStart(Math.trunc(-o.o/60)),c+=":",c+=padStart(Math.trunc(-o.o%60))):(c+="+",c+=padStart(Math.trunc(o.o/60)),c+=":",c+=padStart(Math.trunc(o.o%60)))),extendedZone&&(c+="["+o.zone.ianaName+"]"),c}__name(toISOTime,"toISOTime"),__name2(toISOTime,"toISOTime");const defaultUnitValues={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},defaultWeekUnitValues={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},defaultOrdinalUnitValues={ordinal:1,hour:0,minute:0,second:0,millisecond:0},orderedUnits=["year","month","day","hour","minute","second","millisecond"],orderedWeekUnits=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],orderedOrdinalUnits=["year","ordinal","hour","minute","second","millisecond"];function normalizeUnit(unit){const normalized={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[unit.toLowerCase()];if(!normalized)throw new InvalidUnitError(unit);return normalized}__name(normalizeUnit,"normalizeUnit"),__name2(normalizeUnit,"normalizeUnit");function quickDT(obj,opts){const zone=normalizeZone(opts.zone,Settings.defaultZone),loc=Locale.fromObject(opts),tsNow=Settings.now();let ts,o;if(isUndefined(obj.year))ts=tsNow;else{for(const u of orderedUnits)isUndefined(obj[u])&&(obj[u]=defaultUnitValues[u]);const invalid=hasInvalidGregorianData(obj)||hasInvalidTimeData(obj);if(invalid)return DateTime.invalid(invalid);const offsetProvis=zone.offset(tsNow);[ts,o]=objToTS(obj,offsetProvis,zone)}return new DateTime({ts,zone,loc,o})}__name(quickDT,"quickDT"),__name2(quickDT,"quickDT");function diffRelative(start,end,opts){const round=isUndefined(opts.round)?!0:opts.round,format=__name2((c,unit)=>(c=roundTo(c,round||opts.calendary?0:2,!0),end.loc.clone(opts).relFormatter(opts).format(c,unit)),"format"),differ=__name2(unit=>opts.calendary?end.hasSame(start,unit)?0:end.startOf(unit).diff(start.startOf(unit),unit).get(unit):end.diff(start,unit).get(unit),"differ");if(opts.unit)return format(differ(opts.unit),opts.unit);for(const unit of opts.units){const count=differ(unit);if(Math.abs(count)>=1)return format(count,unit)}return format(start>end?-0:0,opts.units[opts.units.length-1])}__name(diffRelative,"diffRelative"),__name2(diffRelative,"diffRelative");function lastOpts(argList){let opts={},args;return argList.length>0&&typeof argList[argList.length-1]=="object"?(opts=argList[argList.length-1],args=Array.from(argList).slice(0,argList.length-1)):args=Array.from(argList),[opts,args]}__name(lastOpts,"lastOpts"),__name2(lastOpts,"lastOpts");const _DateTime=class _DateTime2{static{__name(this,"_DateTime")}constructor(config2){const zone=config2.zone||Settings.defaultZone;let invalid=config2.invalid||(Number.isNaN(config2.ts)?new Invalid("invalid input"):null)||(zone.isValid?null:unsupportedZone(zone));this.ts=isUndefined(config2.ts)?Settings.now():config2.ts;let c=null,o=null;if(!invalid)if(config2.old&&config2.old.ts===this.ts&&config2.old.zone.equals(zone))[c,o]=[config2.old.c,config2.old.o];else{const ot=zone.offset(this.ts);c=tsToObj(this.ts,ot),invalid=Number.isNaN(c.year)?new Invalid("invalid input"):null,c=invalid?null:c,o=invalid?null:ot}this._zone=zone,this.loc=config2.loc||Locale.create(),this.invalid=invalid,this.weekData=null,this.c=c,this.o=o,this.isLuxonDateTime=!0}static now(){return new _DateTime2({})}static local(){const[opts,args]=lastOpts(arguments),[year,month,day,hour,minute,second,millisecond]=args;return quickDT({year,month,day,hour,minute,second,millisecond},opts)}static utc(){const[opts,args]=lastOpts(arguments),[year,month,day,hour,minute,second,millisecond]=args;return opts.zone=FixedOffsetZone.utcInstance,quickDT({year,month,day,hour,minute,second,millisecond},opts)}static fromJSDate(date,options={}){const ts=isDate(date)?date.valueOf():NaN;if(Number.isNaN(ts))return _DateTime2.invalid("invalid input");const zoneToUse=normalizeZone(options.zone,Settings.defaultZone);return zoneToUse.isValid?new _DateTime2({ts,zone:zoneToUse,loc:Locale.fromObject(options)}):_DateTime2.invalid(unsupportedZone(zoneToUse))}static fromMillis(milliseconds,options={}){if(isNumber(milliseconds))return milliseconds<-MAX_DATE||milliseconds>MAX_DATE?_DateTime2.invalid("Timestamp out of range"):new _DateTime2({ts:milliseconds,zone:normalizeZone(options.zone,Settings.defaultZone),loc:Locale.fromObject(options)});throw new InvalidArgumentError(`fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`)}static fromSeconds(seconds,options={}){if(isNumber(seconds))return new _DateTime2({ts:seconds*1e3,zone:normalizeZone(options.zone,Settings.defaultZone),loc:Locale.fromObject(options)});throw new InvalidArgumentError("fromSeconds requires a numerical input")}static fromObject(obj,opts={}){obj=obj||{};const zoneToUse=normalizeZone(opts.zone,Settings.defaultZone);if(!zoneToUse.isValid)return _DateTime2.invalid(unsupportedZone(zoneToUse));const tsNow=Settings.now(),offsetProvis=isUndefined(opts.specificOffset)?zoneToUse.offset(tsNow):opts.specificOffset,normalized=normalizeObject(obj,normalizeUnit),containsOrdinal=!isUndefined(normalized.ordinal),containsGregorYear=!isUndefined(normalized.year),containsGregorMD=!isUndefined(normalized.month)||!isUndefined(normalized.day),containsGregor=containsGregorYear||containsGregorMD,definiteWeekDef=normalized.weekYear||normalized.weekNumber,loc=Locale.fromObject(opts);if((containsGregor||containsOrdinal)&&definiteWeekDef)throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(containsGregorMD&&containsOrdinal)throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");const useWeekData=definiteWeekDef||normalized.weekday&&!containsGregor;let units,defaultValues,objNow=tsToObj(tsNow,offsetProvis);useWeekData?(units=orderedWeekUnits,defaultValues=defaultWeekUnitValues,objNow=gregorianToWeek(objNow)):containsOrdinal?(units=orderedOrdinalUnits,defaultValues=defaultOrdinalUnitValues,objNow=gregorianToOrdinal(objNow)):(units=orderedUnits,defaultValues=defaultUnitValues);let foundFirst=!1;for(const u of units){const v=normalized[u];isUndefined(v)?foundFirst?normalized[u]=defaultValues[u]:normalized[u]=objNow[u]:foundFirst=!0}const higherOrderInvalid=useWeekData?hasInvalidWeekData(normalized):containsOrdinal?hasInvalidOrdinalData(normalized):hasInvalidGregorianData(normalized),invalid=higherOrderInvalid||hasInvalidTimeData(normalized);if(invalid)return _DateTime2.invalid(invalid);const gregorian=useWeekData?weekToGregorian(normalized):containsOrdinal?ordinalToGregorian(normalized):normalized,[tsFinal,offsetFinal]=objToTS(gregorian,offsetProvis,zoneToUse),inst=new _DateTime2({ts:tsFinal,zone:zoneToUse,o:offsetFinal,loc});return normalized.weekday&&containsGregor&&obj.weekday!==inst.weekday?_DateTime2.invalid("mismatched weekday",`you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`):inst}static fromISO(text,opts={}){const[vals,parsedZone]=parseISODate(text);return parseDataToDateTime(vals,parsedZone,opts,"ISO 8601",text)}static fromRFC2822(text,opts={}){const[vals,parsedZone]=parseRFC2822Date(text);return parseDataToDateTime(vals,parsedZone,opts,"RFC 2822",text)}static fromHTTP(text,opts={}){const[vals,parsedZone]=parseHTTPDate(text);return parseDataToDateTime(vals,parsedZone,opts,"HTTP",opts)}static fromFormat(text,fmt,opts={}){if(isUndefined(text)||isUndefined(fmt))throw new InvalidArgumentError("fromFormat requires an input string and a format");const{locale=null,numberingSystem=null}=opts,localeToUse=Locale.fromOpts({locale,numberingSystem,defaultToEN:!0}),[vals,parsedZone,specificOffset,invalid]=parseFromTokens(localeToUse,text,fmt);return invalid?_DateTime2.invalid(invalid):parseDataToDateTime(vals,parsedZone,opts,`format ${fmt}`,text,specificOffset)}static fromString(text,fmt,opts={}){return _DateTime2.fromFormat(text,fmt,opts)}static fromSQL(text,opts={}){const[vals,parsedZone]=parseSQL(text);return parseDataToDateTime(vals,parsedZone,opts,"SQL",text)}static invalid(reason,explanation=null){if(!reason)throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");const invalid=reason instanceof Invalid?reason:new Invalid(reason,explanation);if(Settings.throwOnInvalid)throw new InvalidDateTimeError(invalid);return new _DateTime2({invalid})}static isDateTime(o){return o&&o.isLuxonDateTime||!1}static parseFormatForOpts(formatOpts,localeOpts={}){const tokenList=formatOptsToTokens(formatOpts,Locale.fromObject(localeOpts));return tokenList?tokenList.map(t2=>t2?t2.val:null).join(""):null}static expandFormat(fmt,localeOpts={}){return expandMacroTokens(Formatter.parseFormat(fmt),Locale.fromObject(localeOpts)).map(t2=>t2.val).join("")}get(unit){return this[unit]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?possiblyCachedWeekData(this).weekYear:NaN}get weekNumber(){return this.isValid?possiblyCachedWeekData(this).weekNumber:NaN}get weekday(){return this.isValid?possiblyCachedWeekData(this).weekday:NaN}get ordinal(){return this.isValid?gregorianToOrdinal(this.c).ordinal:NaN}get monthShort(){return this.isValid?Info.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Info.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Info.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Info.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const dayMs=864e5,minuteMs=6e4,localTS=objToLocalTS(this.c),oEarlier=this.zone.offset(localTS-dayMs),oLater=this.zone.offset(localTS+dayMs),o1=this.zone.offset(localTS-oEarlier*minuteMs),o2=this.zone.offset(localTS-oLater*minuteMs);if(o1===o2)return[this];const ts1=localTS-o1*minuteMs,ts2=localTS-o2*minuteMs,c1=tsToObj(ts1,o1),c2=tsToObj(ts2,o2);return c1.hour===c2.hour&&c1.minute===c2.minute&&c1.second===c2.second&&c1.millisecond===c2.millisecond?[clone(this,{ts:ts1}),clone(this,{ts:ts2})]:[this]}get isInLeapYear(){return isLeapYear(this.year)}get daysInMonth(){return daysInMonth(this.year,this.month)}get daysInYear(){return this.isValid?daysInYear(this.year):NaN}get weeksInWeekYear(){return this.isValid?weeksInWeekYear(this.weekYear):NaN}resolvedLocaleOptions(opts={}){const{locale,numberingSystem,calendar}=Formatter.create(this.loc.clone(opts),opts).resolvedOptions(this);return{locale,numberingSystem,outputCalendar:calendar}}toUTC(offset2=0,opts={}){return this.setZone(FixedOffsetZone.instance(offset2),opts)}toLocal(){return this.setZone(Settings.defaultZone)}setZone(zone,{keepLocalTime=!1,keepCalendarTime=!1}={}){if(zone=normalizeZone(zone,Settings.defaultZone),zone.equals(this.zone))return this;if(zone.isValid){let newTS=this.ts;if(keepLocalTime||keepCalendarTime){const offsetGuess=zone.offset(this.ts),asObj=this.toObject();[newTS]=objToTS(asObj,offsetGuess,zone)}return clone(this,{ts:newTS,zone})}else return _DateTime2.invalid(unsupportedZone(zone))}reconfigure({locale,numberingSystem,outputCalendar}={}){const loc=this.loc.clone({locale,numberingSystem,outputCalendar});return clone(this,{loc})}setLocale(locale){return this.reconfigure({locale})}set(values){if(!this.isValid)return this;const normalized=normalizeObject(values,normalizeUnit),settingWeekStuff=!isUndefined(normalized.weekYear)||!isUndefined(normalized.weekNumber)||!isUndefined(normalized.weekday),containsOrdinal=!isUndefined(normalized.ordinal),containsGregorYear=!isUndefined(normalized.year),containsGregorMD=!isUndefined(normalized.month)||!isUndefined(normalized.day),containsGregor=containsGregorYear||containsGregorMD,definiteWeekDef=normalized.weekYear||normalized.weekNumber;if((containsGregor||containsOrdinal)&&definiteWeekDef)throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(containsGregorMD&&containsOrdinal)throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");let mixed;settingWeekStuff?mixed=weekToGregorian({...gregorianToWeek(this.c),...normalized}):isUndefined(normalized.ordinal)?(mixed={...this.toObject(),...normalized},isUndefined(normalized.day)&&(mixed.day=Math.min(daysInMonth(mixed.year,mixed.month),mixed.day))):mixed=ordinalToGregorian({...gregorianToOrdinal(this.c),...normalized});const[ts,o]=objToTS(mixed,this.o,this.zone);return clone(this,{ts,o})}plus(duration){if(!this.isValid)return this;const dur=Duration.fromDurationLike(duration);return clone(this,adjustTime(this,dur))}minus(duration){if(!this.isValid)return this;const dur=Duration.fromDurationLike(duration).negate();return clone(this,adjustTime(this,dur))}startOf(unit){if(!this.isValid)return this;const o={},normalizedUnit=Duration.normalizeUnit(unit);switch(normalizedUnit){case"years":o.month=1;case"quarters":case"months":o.day=1;case"weeks":case"days":o.hour=0;case"hours":o.minute=0;case"minutes":o.second=0;case"seconds":o.millisecond=0;break}if(normalizedUnit==="weeks"&&(o.weekday=1),normalizedUnit==="quarters"){const q=Math.ceil(this.month/3);o.month=(q-1)*3+1}return this.set(o)}endOf(unit){return this.isValid?this.plus({[unit]:1}).startOf(unit).minus(1):this}toFormat(fmt,opts={}){return this.isValid?Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this,fmt):INVALID}toLocaleString(formatOpts=DATE_SHORT,opts={}){return this.isValid?Formatter.create(this.loc.clone(opts),formatOpts).formatDateTime(this):INVALID}toLocaleParts(opts={}){return this.isValid?Formatter.create(this.loc.clone(opts),opts).formatDateTimeParts(this):[]}toISO({format="extended",suppressSeconds=!1,suppressMilliseconds=!1,includeOffset=!0,extendedZone=!1}={}){if(!this.isValid)return null;const ext=format==="extended";let c=toISODate(this,ext);return c+="T",c+=toISOTime(this,ext,suppressSeconds,suppressMilliseconds,includeOffset,extendedZone),c}toISODate({format="extended"}={}){return this.isValid?toISODate(this,format==="extended"):null}toISOWeekDate(){return toTechFormat(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds=!1,suppressSeconds=!1,includeOffset=!0,includePrefix=!1,extendedZone=!1,format="extended"}={}){return this.isValid?(includePrefix?"T":"")+toISOTime(this,format==="extended",suppressSeconds,suppressMilliseconds,includeOffset,extendedZone):null}toRFC2822(){return toTechFormat(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return toTechFormat(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?toISODate(this,!0):null}toSQLTime({includeOffset=!0,includeZone=!1,includeOffsetSpace=!0}={}){let fmt="HH:mm:ss.SSS";return(includeZone||includeOffset)&&(includeOffsetSpace&&(fmt+=" "),includeZone?fmt+="z":includeOffset&&(fmt+="ZZ")),toTechFormat(this,fmt,!0)}toSQL(opts={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(opts)}`:null}toString(){return this.isValid?this.toISO():INVALID}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(opts={}){if(!this.isValid)return{};const base2={...this.c};return opts.includeConfig&&(base2.outputCalendar=this.outputCalendar,base2.numberingSystem=this.loc.numberingSystem,base2.locale=this.loc.locale),base2}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(otherDateTime,unit="milliseconds",opts={}){if(!this.isValid||!otherDateTime.isValid)return Duration.invalid("created by diffing an invalid DateTime");const durOpts={locale:this.locale,numberingSystem:this.numberingSystem,...opts},units=maybeArray(unit).map(Duration.normalizeUnit),otherIsLater=otherDateTime.valueOf()>this.valueOf(),earlier=otherIsLater?this:otherDateTime,later=otherIsLater?otherDateTime:this,diffed=diff(earlier,later,units,durOpts);return otherIsLater?diffed.negate():diffed}diffNow(unit="milliseconds",opts={}){return this.diff(_DateTime2.now(),unit,opts)}until(otherDateTime){return this.isValid?Interval.fromDateTimes(this,otherDateTime):this}hasSame(otherDateTime,unit){if(!this.isValid)return!1;const inputMs=otherDateTime.valueOf(),adjustedToZone=this.setZone(otherDateTime.zone,{keepLocalTime:!0});return adjustedToZone.startOf(unit)<=inputMs&&inputMs<=adjustedToZone.endOf(unit)}equals(other){return this.isValid&&other.isValid&&this.valueOf()===other.valueOf()&&this.zone.equals(other.zone)&&this.loc.equals(other.loc)}toRelative(options={}){if(!this.isValid)return null;const base2=options.base||_DateTime2.fromObject({},{zone:this.zone}),padding=options.padding?thisi.valueOf(),Math.min)}static max(...dateTimes){if(!dateTimes.every(_DateTime2.isDateTime))throw new InvalidArgumentError("max requires all arguments be DateTimes");return bestBy(dateTimes,i=>i.valueOf(),Math.max)}static fromFormatExplain(text,fmt,options={}){const{locale=null,numberingSystem=null}=options,localeToUse=Locale.fromOpts({locale,numberingSystem,defaultToEN:!0});return explainFromTokens(localeToUse,text,fmt)}static fromStringExplain(text,fmt,options={}){return _DateTime2.fromFormatExplain(text,fmt,options)}static get DATE_SHORT(){return DATE_SHORT}static get DATE_MED(){return DATE_MED}static get DATE_MED_WITH_WEEKDAY(){return DATE_MED_WITH_WEEKDAY}static get DATE_FULL(){return DATE_FULL}static get DATE_HUGE(){return DATE_HUGE}static get TIME_SIMPLE(){return TIME_SIMPLE}static get TIME_WITH_SECONDS(){return TIME_WITH_SECONDS}static get TIME_WITH_SHORT_OFFSET(){return TIME_WITH_SHORT_OFFSET}static get TIME_WITH_LONG_OFFSET(){return TIME_WITH_LONG_OFFSET}static get TIME_24_SIMPLE(){return TIME_24_SIMPLE}static get TIME_24_WITH_SECONDS(){return TIME_24_WITH_SECONDS}static get TIME_24_WITH_SHORT_OFFSET(){return TIME_24_WITH_SHORT_OFFSET}static get TIME_24_WITH_LONG_OFFSET(){return TIME_24_WITH_LONG_OFFSET}static get DATETIME_SHORT(){return DATETIME_SHORT}static get DATETIME_SHORT_WITH_SECONDS(){return DATETIME_SHORT_WITH_SECONDS}static get DATETIME_MED(){return DATETIME_MED}static get DATETIME_MED_WITH_SECONDS(){return DATETIME_MED_WITH_SECONDS}static get DATETIME_MED_WITH_WEEKDAY(){return DATETIME_MED_WITH_WEEKDAY}static get DATETIME_FULL(){return DATETIME_FULL}static get DATETIME_FULL_WITH_SECONDS(){return DATETIME_FULL_WITH_SECONDS}static get DATETIME_HUGE(){return DATETIME_HUGE}static get DATETIME_HUGE_WITH_SECONDS(){return DATETIME_HUGE_WITH_SECONDS}};__name2(_DateTime,"DateTime");let DateTime=_DateTime;function friendlyDateTime(dateTimeish){if(DateTime.isDateTime(dateTimeish))return dateTimeish;if(dateTimeish&&dateTimeish.valueOf&&isNumber(dateTimeish.valueOf()))return DateTime.fromJSDate(dateTimeish);if(dateTimeish&&typeof dateTimeish=="object")return DateTime.fromObject(dateTimeish);throw new InvalidArgumentError(`Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`)}__name(friendlyDateTime,"friendlyDateTime"),__name2(friendlyDateTime,"friendlyDateTime");const _Text=class _Text2{static{__name(this,"_Text")}lineAt(pos){if(pos<0||pos>this.length)throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);return this.lineInner(pos,!1,1,0)}line(n2){if(n2<1||n2>this.lines)throw new RangeError(`Invalid line number ${n2} in ${this.lines}-line document`);return this.lineInner(n2,!0,1,0)}replace(from,to,text){let parts=[];return this.decompose(0,from,parts,2),text.length&&text.decompose(0,text.length,parts,3),this.decompose(to,this.length,parts,1),TextNode.from(parts,this.length-(to-from)+text.length)}append(other){return this.replace(this.length,this.length,other)}slice(from,to=this.length){let parts=[];return this.decompose(from,to,parts,0),TextNode.from(parts,to-from)}eq(other){if(other==this)return!0;if(other.length!=this.length||other.lines!=this.lines)return!1;let start=this.scanIdentical(other,1),end=this.length-this.scanIdentical(other,-1),a=new RawTextCursor(this),b=new RawTextCursor(other);for(let skip=start,pos=start;;){if(a.next(skip),b.next(skip),skip=0,a.lineBreak!=b.lineBreak||a.done!=b.done||a.value!=b.value)return!1;if(pos+=a.value.length,a.done||pos>=end)return!0}}iter(dir=1){return new RawTextCursor(this,dir)}iterRange(from,to=this.length){return new PartialTextCursor(this,from,to)}iterLines(from,to){let inner;if(from==null)inner=this.iter();else{to==null&&(to=this.lines+1);let start=this.line(from).from;inner=this.iterRange(start,Math.max(start,to==this.lines+1?this.length:to<=1?0:this.line(to-1).to))}return new LineCursor(inner)}toString(){return this.sliceString(0)}toJSON(){let lines=[];return this.flatten(lines),lines}constructor(){}static of(text){if(text.length==0)throw new RangeError("A document must have at least one line");return text.length==1&&!text[0]?_Text2.empty:text.length<=32?new TextLeaf(text):TextNode.from(TextLeaf.split(text,[]))}};__name2(_Text,"Text");let Text=_Text;const _TextLeaf=class _TextLeaf2 extends Text{static{__name(this,"_TextLeaf")}constructor(text,length=textLength(text)){super(),this.text=text,this.length=length}get lines(){return this.text.length}get children(){return null}lineInner(target,isLine,line,offset2){for(let i=0;;i++){let string2=this.text[i],end=offset2+string2.length;if((isLine?line:end)>=target)return new Line(offset2,end,line,string2);offset2=end+1,line++}}decompose(from,to,target,open){let text=from<=0&&to>=this.length?this:new _TextLeaf2(sliceText(this.text,from,to),Math.min(to,this.length)-Math.max(0,from));if(open&1){let prev=target.pop(),joined=appendText(text.text,prev.text.slice(),0,text.length);if(joined.length<=32)target.push(new _TextLeaf2(joined,prev.length+text.length));else{let mid=joined.length>>1;target.push(new _TextLeaf2(joined.slice(0,mid)),new _TextLeaf2(joined.slice(mid)))}}else target.push(text)}replace(from,to,text){if(!(text instanceof _TextLeaf2))return super.replace(from,to,text);let lines=appendText(this.text,appendText(text.text,sliceText(this.text,0,from)),to),newLen=this.length+text.length-(to-from);return lines.length<=32?new _TextLeaf2(lines,newLen):TextNode.from(_TextLeaf2.split(lines,[]),newLen)}sliceString(from,to=this.length,lineSep=` + */function ownKeys(object,enumerableOnly){var keys2=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})),keys2.push.apply(keys2,symbols)}return keys2}__name(ownKeys,"ownKeys"),__name2(ownKeys,"ownKeys");function _objectSpread2(target){for(var i=1;i=0)&&(target[key]=source[key]);return target}__name(_objectWithoutPropertiesLoose,"_objectWithoutPropertiesLoose"),__name2(_objectWithoutPropertiesLoose,"_objectWithoutPropertiesLoose");function _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded),key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}__name(_objectWithoutProperties,"_objectWithoutProperties"),__name2(_objectWithoutProperties,"_objectWithoutProperties");var version="1.15.0";function userAgent(pattern){if(typeof window<"u"&&window.navigator)return!!navigator.userAgent.match(pattern)}__name(userAgent,"userAgent"),__name2(userAgent,"userAgent");var IE11OrLess=userAgent(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),Edge=userAgent(/Edge/i),FireFox=userAgent(/firefox/i),Safari=userAgent(/safari/i)&&!userAgent(/chrome/i)&&!userAgent(/android/i),IOS=userAgent(/iP(ad|od|hone)/i),ChromeForAndroid=userAgent(/chrome/i)&&userAgent(/android/i),captureMode={capture:!1,passive:!1};function on(el,event,fn){el.addEventListener(event,fn,!IE11OrLess&&captureMode)}__name(on,"on"),__name2(on,"on");function off(el,event,fn){el.removeEventListener(event,fn,!IE11OrLess&&captureMode)}__name(off,"off"),__name2(off,"off");function matches(el,selector){if(selector){if(selector[0]===">"&&(selector=selector.substring(1)),el)try{if(el.matches)return el.matches(selector);if(el.msMatchesSelector)return el.msMatchesSelector(selector);if(el.webkitMatchesSelector)return el.webkitMatchesSelector(selector)}catch{return!1}return!1}}__name(matches,"matches"),__name2(matches,"matches");function getParentOrHost(el){return el.host&&el!==document&&el.host.nodeType?el.host:el.parentNode}__name(getParentOrHost,"getParentOrHost"),__name2(getParentOrHost,"getParentOrHost");function closest$1(el,selector,ctx,includeCTX){if(el){ctx=ctx||document;do{if(selector!=null&&(selector[0]===">"?el.parentNode===ctx&&matches(el,selector):matches(el,selector))||includeCTX&&el===ctx)return el;if(el===ctx)break}while(el=getParentOrHost(el))}return null}__name(closest$1,"closest$1"),__name2(closest$1,"closest$1");var R_SPACE=/\s+/g;function toggleClass(el,name2,state){if(el&&name2)if(el.classList)el.classList[state?"add":"remove"](name2);else{var className=(" "+el.className+" ").replace(R_SPACE," ").replace(" "+name2+" "," ");el.className=(className+(state?" "+name2:"")).replace(R_SPACE," ")}}__name(toggleClass,"toggleClass"),__name2(toggleClass,"toggleClass");function css(el,prop,val){var style=el&&el.style;if(style){if(val===void 0)return document.defaultView&&document.defaultView.getComputedStyle?val=document.defaultView.getComputedStyle(el,""):el.currentStyle&&(val=el.currentStyle),prop===void 0?val:val[prop];!(prop in style)&&prop.indexOf("webkit")===-1&&(prop="-webkit-"+prop),style[prop]=val+(typeof val=="string"?"":"px")}}__name(css,"css"),__name2(css,"css");function matrix(el,selfOnly){var appliedTransforms="";if(typeof el=="string")appliedTransforms=el;else do{var transform=css(el,"transform");transform&&transform!=="none"&&(appliedTransforms=transform+" "+appliedTransforms)}while(!selfOnly&&(el=el.parentNode));var matrixFn=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return matrixFn&&new matrixFn(appliedTransforms)}__name(matrix,"matrix"),__name2(matrix,"matrix");function find$1(ctx,tagName,iterator){if(ctx){var list=ctx.getElementsByTagName(tagName),i=0,n2=list.length;if(iterator)for(;i=parentSideVal:visible=elSideVal<=parentSideVal,!visible)return parent;if(parent===getWindowScrollingElement())break;parent=getParentAutoScrollElement(parent,!1)}return!1}__name(isScrolledPast,"isScrolledPast"),__name2(isScrolledPast,"isScrolledPast");function getChild(el,childNum,options,includeDragEl){for(var currentChild=0,i=0,children=el.children;i2&&arguments[2]!==void 0?arguments[2]:{},originalEvent=_ref.evt,data=_objectWithoutProperties(_ref,_excluded);PluginManager.pluginEvent.bind(Sortable)(eventName,sortable,_objectSpread2({dragEl,parentEl,ghostEl,rootEl,nextEl,lastDownEl,cloneEl,cloneHidden,dragStarted:moved,putSortable,activeSortable:Sortable.active,originalEvent,oldIndex,oldDraggableIndex,newIndex,newDraggableIndex,hideGhostForTarget:_hideGhostForTarget,unhideGhostForTarget:_unhideGhostForTarget,cloneNowHidden:__name2(__name(function(){cloneHidden=!0},"cloneNowHidden"),"cloneNowHidden"),cloneNowShown:__name2(__name(function(){cloneHidden=!1},"cloneNowShown"),"cloneNowShown"),dispatchSortableEvent:__name2(__name(function(name2){_dispatchEvent({sortable,name:name2,originalEvent})},"dispatchSortableEvent"),"dispatchSortableEvent")},data))},"pluginEvent3"),"pluginEvent");function _dispatchEvent(info){dispatchEvent$1(_objectSpread2({putSortable,cloneEl,targetEl:dragEl,rootEl,oldIndex,oldDraggableIndex,newIndex,newDraggableIndex},info))}__name(_dispatchEvent,"_dispatchEvent"),__name2(_dispatchEvent,"_dispatchEvent");var dragEl,parentEl,ghostEl,rootEl,nextEl,lastDownEl,cloneEl,cloneHidden,oldIndex,newIndex,oldDraggableIndex,newDraggableIndex,activeGroup,putSortable,awaitingDragStarted=!1,ignoreNextClick=!1,sortables=[],tapEvt,touchEvt,lastDx,lastDy,tapDistanceLeft,tapDistanceTop,moved,lastTarget,lastDirection,pastFirstInvertThresh=!1,isCircumstantialInvert=!1,targetMoveDistance,ghostRelativeParent,ghostRelativeParentInitialScroll=[],_silent=!1,savedInputChecked=[],documentExists=typeof document<"u",PositionGhostAbsolutely=IOS,CSSFloatProperty=Edge||IE11OrLess?"cssFloat":"float",supportDraggable=documentExists&&!ChromeForAndroid&&!IOS&&"draggable"in document.createElement("div"),supportCssPointerEvents=function(){if(documentExists){if(IE11OrLess)return!1;var el=document.createElement("x");return el.style.cssText="pointer-events:auto",el.style.pointerEvents==="auto"}}(),_detectDirection=__name2(__name(function(el,options){var elCSS=css(el),elWidth=parseInt(elCSS.width)-parseInt(elCSS.paddingLeft)-parseInt(elCSS.paddingRight)-parseInt(elCSS.borderLeftWidth)-parseInt(elCSS.borderRightWidth),child1=getChild(el,0,options),child2=getChild(el,1,options),firstChildCSS=child1&&css(child1),secondChildCSS=child2&&css(child2),firstChildWidth=firstChildCSS&&parseInt(firstChildCSS.marginLeft)+parseInt(firstChildCSS.marginRight)+getRect(child1).width,secondChildWidth=secondChildCSS&&parseInt(secondChildCSS.marginLeft)+parseInt(secondChildCSS.marginRight)+getRect(child2).width;if(elCSS.display==="flex")return elCSS.flexDirection==="column"||elCSS.flexDirection==="column-reverse"?"vertical":"horizontal";if(elCSS.display==="grid")return elCSS.gridTemplateColumns.split(" ").length<=1?"vertical":"horizontal";if(child1&&firstChildCSS.float&&firstChildCSS.float!=="none"){var touchingSideChild2=firstChildCSS.float==="left"?"left":"right";return child2&&(secondChildCSS.clear==="both"||secondChildCSS.clear===touchingSideChild2)?"vertical":"horizontal"}return child1&&(firstChildCSS.display==="block"||firstChildCSS.display==="flex"||firstChildCSS.display==="table"||firstChildCSS.display==="grid"||firstChildWidth>=elWidth&&elCSS[CSSFloatProperty]==="none"||child2&&elCSS[CSSFloatProperty]==="none"&&firstChildWidth+secondChildWidth>elWidth)?"vertical":"horizontal"},"_detectDirection2"),"_detectDirection"),_dragElInRowColumn=__name2(__name(function(dragRect,targetRect,vertical){var dragElS1Opp=vertical?dragRect.left:dragRect.top,dragElS2Opp=vertical?dragRect.right:dragRect.bottom,dragElOppLength=vertical?dragRect.width:dragRect.height,targetS1Opp=vertical?targetRect.left:targetRect.top,targetS2Opp=vertical?targetRect.right:targetRect.bottom,targetOppLength=vertical?targetRect.width:targetRect.height;return dragElS1Opp===targetS1Opp||dragElS2Opp===targetS2Opp||dragElS1Opp+dragElOppLength/2===targetS1Opp+targetOppLength/2},"_dragElInRowColumn2"),"_dragElInRowColumn"),_detectNearestEmptySortable=__name2(__name(function(x,y){var ret;return sortables.some(function(sortable){var threshold=sortable[expando].options.emptyInsertThreshold;if(!(!threshold||lastChild(sortable))){var rect=getRect(sortable),insideHorizontally=x>=rect.left-threshold&&x<=rect.right+threshold,insideVertically=y>=rect.top-threshold&&y<=rect.bottom+threshold;if(insideHorizontally&&insideVertically)return ret=sortable}}),ret},"_detectNearestEmptySortable2"),"_detectNearestEmptySortable"),_prepareGroup=__name2(__name(function(options){function toFn(value,pull){return function(to,from,dragEl2,evt){var sameGroup=to.options.group.name&&from.options.group.name&&to.options.group.name===from.options.group.name;if(value==null&&(pull||sameGroup))return!0;if(value==null||value===!1)return!1;if(pull&&value==="clone")return value;if(typeof value=="function")return toFn(value(to,from,dragEl2,evt),pull)(to,from,dragEl2,evt);var otherGroup=(pull?to:from).options.group.name;return value===!0||typeof value=="string"&&value===otherGroup||value.join&&value.indexOf(otherGroup)>-1}}__name(toFn,"toFn"),__name2(toFn,"toFn");var group={},originalGroup=options.group;(!originalGroup||_typeof(originalGroup)!="object")&&(originalGroup={name:originalGroup}),group.name=originalGroup.name,group.checkPull=toFn(originalGroup.pull,!0),group.checkPut=toFn(originalGroup.put),group.revertClone=originalGroup.revertClone,options.group=group},"_prepareGroup2"),"_prepareGroup"),_hideGhostForTarget=__name2(__name(function(){!supportCssPointerEvents&&ghostEl&&css(ghostEl,"display","none")},"_hideGhostForTarget2"),"_hideGhostForTarget"),_unhideGhostForTarget=__name2(__name(function(){!supportCssPointerEvents&&ghostEl&&css(ghostEl,"display","")},"_unhideGhostForTarget2"),"_unhideGhostForTarget");documentExists&&!ChromeForAndroid&&document.addEventListener("click",function(evt){if(ignoreNextClick)return evt.preventDefault(),evt.stopPropagation&&evt.stopPropagation(),evt.stopImmediatePropagation&&evt.stopImmediatePropagation(),ignoreNextClick=!1,!1},!0);var nearestEmptyInsertDetectEvent=__name2(__name(function(evt){if(dragEl){evt=evt.touches?evt.touches[0]:evt;var nearest=_detectNearestEmptySortable(evt.clientX,evt.clientY);if(nearest){var event={};for(var i in evt)evt.hasOwnProperty(i)&&(event[i]=evt[i]);event.target=event.rootEl=nearest,event.preventDefault=void 0,event.stopPropagation=void 0,nearest[expando]._onDragOver(event)}}},"nearestEmptyInsertDetectEvent2"),"nearestEmptyInsertDetectEvent"),_checkOutsideTargetEl=__name2(__name(function(evt){dragEl&&dragEl.parentNode[expando]._isOutsideThisEl(evt.target)},"_checkOutsideTargetEl2"),"_checkOutsideTargetEl");function Sortable(el,options){if(!(el&&el.nodeType&&el.nodeType===1))throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(el));this.el=el,this.options=options=_extends({},options),el[expando]=this;var defaults2={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(el.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:__name2(__name(function(){return _detectDirection(el,this.options)},"direction"),"direction"),ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:__name2(__name(function(dataTransfer,dragEl2){dataTransfer.setData("Text",dragEl2.textContent)},"setData"),"setData"),dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:Sortable.supportPointer!==!1&&"PointerEvent"in window&&!Safari,emptyInsertThreshold:5};PluginManager.initializePlugins(this,el,defaults2);for(var name2 in defaults2)!(name2 in options)&&(options[name2]=defaults2[name2]);_prepareGroup(options);for(var fn in this)fn.charAt(0)==="_"&&typeof this[fn]=="function"&&(this[fn]=this[fn].bind(this));this.nativeDraggable=options.forceFallback?!1:supportDraggable,this.nativeDraggable&&(this.options.touchStartThreshold=1),options.supportPointer?on(el,"pointerdown",this._onTapStart):(on(el,"mousedown",this._onTapStart),on(el,"touchstart",this._onTapStart)),this.nativeDraggable&&(on(el,"dragover",this),on(el,"dragenter",this)),sortables.push(this.el),options.store&&options.store.get&&this.sort(options.store.get(this)||[]),_extends(this,AnimationStateManager())}__name(Sortable,"Sortable"),__name2(Sortable,"Sortable"),Sortable.prototype={constructor:Sortable,_isOutsideThisEl:__name2(__name(function(target){!this.el.contains(target)&&target!==this.el&&(lastTarget=null)},"_isOutsideThisEl"),"_isOutsideThisEl"),_getDirection:__name2(__name(function(evt,target){return typeof this.options.direction=="function"?this.options.direction.call(this,evt,target,dragEl):this.options.direction},"_getDirection"),"_getDirection"),_onTapStart:__name2(__name(function(evt){if(evt.cancelable){var _this=this,el=this.el,options=this.options,preventOnFilter=options.preventOnFilter,type=evt.type,touch=evt.touches&&evt.touches[0]||evt.pointerType&&evt.pointerType==="touch"&&evt,target=(touch||evt).target,originalTarget=evt.target.shadowRoot&&(evt.path&&evt.path[0]||evt.composedPath&&evt.composedPath()[0])||target,filter2=options.filter;if(_saveInputCheckedState(el),!dragEl&&!(/mousedown|pointerdown/.test(type)&&evt.button!==0||options.disabled)&&!originalTarget.isContentEditable&&!(!this.nativeDraggable&&Safari&&target&&target.tagName.toUpperCase()==="SELECT")&&(target=closest$1(target,options.draggable,el,!1),!(target&&target.animated)&&lastDownEl!==target)){if(oldIndex=index(target),oldDraggableIndex=index(target,options.draggable),typeof filter2=="function"){if(filter2.call(this,evt,target,this)){_dispatchEvent({sortable:_this,rootEl:originalTarget,name:"filter",targetEl:target,toEl:el,fromEl:el}),pluginEvent2("filter",_this,{evt}),preventOnFilter&&evt.cancelable&&evt.preventDefault();return}}else if(filter2&&(filter2=filter2.split(",").some(function(criteria){if(criteria=closest$1(originalTarget,criteria.trim(),el,!1),criteria)return _dispatchEvent({sortable:_this,rootEl:criteria,name:"filter",targetEl:target,fromEl:el,toEl:el}),pluginEvent2("filter",_this,{evt}),!0}),filter2)){preventOnFilter&&evt.cancelable&&evt.preventDefault();return}options.handle&&!closest$1(originalTarget,options.handle,el,!1)||this._prepareDragStart(evt,touch,target)}}},"_onTapStart"),"_onTapStart"),_prepareDragStart:__name2(__name(function(evt,touch,target){var _this=this,el=_this.el,options=_this.options,ownerDocument=el.ownerDocument,dragStartFn;if(target&&!dragEl&&target.parentNode===el){var dragRect=getRect(target);if(rootEl=el,dragEl=target,parentEl=dragEl.parentNode,nextEl=dragEl.nextSibling,lastDownEl=target,activeGroup=options.group,Sortable.dragged=dragEl,tapEvt={target:dragEl,clientX:(touch||evt).clientX,clientY:(touch||evt).clientY},tapDistanceLeft=tapEvt.clientX-dragRect.left,tapDistanceTop=tapEvt.clientY-dragRect.top,this._lastX=(touch||evt).clientX,this._lastY=(touch||evt).clientY,dragEl.style["will-change"]="all",dragStartFn=__name2(__name(function(){if(pluginEvent2("delayEnded",_this,{evt}),Sortable.eventCanceled){_this._onDrop();return}_this._disableDelayedDragEvents(),!FireFox&&_this.nativeDraggable&&(dragEl.draggable=!0),_this._triggerDragStart(evt,touch),_dispatchEvent({sortable:_this,name:"choose",originalEvent:evt}),toggleClass(dragEl,options.chosenClass,!0)},"dragStartFn2"),"dragStartFn"),options.ignore.split(",").forEach(function(criteria){find$1(dragEl,criteria.trim(),_disableDraggable)}),on(ownerDocument,"dragover",nearestEmptyInsertDetectEvent),on(ownerDocument,"mousemove",nearestEmptyInsertDetectEvent),on(ownerDocument,"touchmove",nearestEmptyInsertDetectEvent),on(ownerDocument,"mouseup",_this._onDrop),on(ownerDocument,"touchend",_this._onDrop),on(ownerDocument,"touchcancel",_this._onDrop),FireFox&&this.nativeDraggable&&(this.options.touchStartThreshold=4,dragEl.draggable=!0),pluginEvent2("delayStart",this,{evt}),options.delay&&(!options.delayOnTouchOnly||touch)&&(!this.nativeDraggable||!(Edge||IE11OrLess))){if(Sortable.eventCanceled){this._onDrop();return}on(ownerDocument,"mouseup",_this._disableDelayedDrag),on(ownerDocument,"touchend",_this._disableDelayedDrag),on(ownerDocument,"touchcancel",_this._disableDelayedDrag),on(ownerDocument,"mousemove",_this._delayedDragTouchMoveHandler),on(ownerDocument,"touchmove",_this._delayedDragTouchMoveHandler),options.supportPointer&&on(ownerDocument,"pointermove",_this._delayedDragTouchMoveHandler),_this._dragStartTimer=setTimeout(dragStartFn,options.delay)}else dragStartFn()}},"_prepareDragStart"),"_prepareDragStart"),_delayedDragTouchMoveHandler:__name2(__name(function(e){var touch=e.touches?e.touches[0]:e;Math.max(Math.abs(touch.clientX-this._lastX),Math.abs(touch.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},"_delayedDragTouchMoveHandler"),"_delayedDragTouchMoveHandler"),_disableDelayedDrag:__name2(__name(function(){dragEl&&_disableDraggable(dragEl),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},"_disableDelayedDrag"),"_disableDelayedDrag"),_disableDelayedDragEvents:__name2(__name(function(){var ownerDocument=this.el.ownerDocument;off(ownerDocument,"mouseup",this._disableDelayedDrag),off(ownerDocument,"touchend",this._disableDelayedDrag),off(ownerDocument,"touchcancel",this._disableDelayedDrag),off(ownerDocument,"mousemove",this._delayedDragTouchMoveHandler),off(ownerDocument,"touchmove",this._delayedDragTouchMoveHandler),off(ownerDocument,"pointermove",this._delayedDragTouchMoveHandler)},"_disableDelayedDragEvents"),"_disableDelayedDragEvents"),_triggerDragStart:__name2(__name(function(evt,touch){touch=touch||evt.pointerType=="touch"&&evt,!this.nativeDraggable||touch?this.options.supportPointer?on(document,"pointermove",this._onTouchMove):touch?on(document,"touchmove",this._onTouchMove):on(document,"mousemove",this._onTouchMove):(on(dragEl,"dragend",this),on(rootEl,"dragstart",this._onDragStart));try{document.selection?_nextTick(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},"_triggerDragStart"),"_triggerDragStart"),_dragStarted:__name2(__name(function(fallback,evt){if(awaitingDragStarted=!1,rootEl&&dragEl){pluginEvent2("dragStarted",this,{evt}),this.nativeDraggable&&on(document,"dragover",_checkOutsideTargetEl);var options=this.options;!fallback&&toggleClass(dragEl,options.dragClass,!1),toggleClass(dragEl,options.ghostClass,!0),Sortable.active=this,fallback&&this._appendGhost(),_dispatchEvent({sortable:this,name:"start",originalEvent:evt})}else this._nulling()},"_dragStarted"),"_dragStarted"),_emulateDragOver:__name2(__name(function(){if(touchEvt){this._lastX=touchEvt.clientX,this._lastY=touchEvt.clientY,_hideGhostForTarget();for(var target=document.elementFromPoint(touchEvt.clientX,touchEvt.clientY),parent=target;target&&target.shadowRoot&&(target=target.shadowRoot.elementFromPoint(touchEvt.clientX,touchEvt.clientY),target!==parent);)parent=target;if(dragEl.parentNode[expando]._isOutsideThisEl(target),parent)do{if(parent[expando]){var inserted=void 0;if(inserted=parent[expando]._onDragOver({clientX:touchEvt.clientX,clientY:touchEvt.clientY,target,rootEl:parent}),inserted&&!this.options.dragoverBubble)break}target=parent}while(parent=parent.parentNode);_unhideGhostForTarget()}},"_emulateDragOver"),"_emulateDragOver"),_onTouchMove:__name2(__name(function(evt){if(tapEvt){var options=this.options,fallbackTolerance=options.fallbackTolerance,fallbackOffset=options.fallbackOffset,touch=evt.touches?evt.touches[0]:evt,ghostMatrix=ghostEl&&matrix(ghostEl,!0),scaleX=ghostEl&&ghostMatrix&&ghostMatrix.a,scaleY=ghostEl&&ghostMatrix&&ghostMatrix.d,relativeScrollOffset=PositionGhostAbsolutely&&ghostRelativeParent&&getRelativeScrollOffset(ghostRelativeParent),dx=(touch.clientX-tapEvt.clientX+fallbackOffset.x)/(scaleX||1)+(relativeScrollOffset?relativeScrollOffset[0]-ghostRelativeParentInitialScroll[0]:0)/(scaleX||1),dy=(touch.clientY-tapEvt.clientY+fallbackOffset.y)/(scaleY||1)+(relativeScrollOffset?relativeScrollOffset[1]-ghostRelativeParentInitialScroll[1]:0)/(scaleY||1);if(!Sortable.active&&!awaitingDragStarted){if(fallbackTolerance&&Math.max(Math.abs(touch.clientX-this._lastX),Math.abs(touch.clientY-this._lastY))=0&&(_dispatchEvent({rootEl:parentEl,name:"add",toEl:parentEl,fromEl:rootEl,originalEvent:evt}),_dispatchEvent({sortable:this,name:"remove",toEl:parentEl,originalEvent:evt}),_dispatchEvent({rootEl:parentEl,name:"sort",toEl:parentEl,fromEl:rootEl,originalEvent:evt}),_dispatchEvent({sortable:this,name:"sort",toEl:parentEl,originalEvent:evt})),putSortable&&putSortable.save()):newIndex!==oldIndex&&newIndex>=0&&(_dispatchEvent({sortable:this,name:"update",toEl:parentEl,originalEvent:evt}),_dispatchEvent({sortable:this,name:"sort",toEl:parentEl,originalEvent:evt})),Sortable.active&&((newIndex==null||newIndex===-1)&&(newIndex=oldIndex,newDraggableIndex=oldDraggableIndex),_dispatchEvent({sortable:this,name:"end",toEl:parentEl,originalEvent:evt}),this.save()))),this._nulling()},"_onDrop"),"_onDrop"),_nulling:__name2(__name(function(){pluginEvent2("nulling",this),rootEl=dragEl=parentEl=ghostEl=nextEl=cloneEl=lastDownEl=cloneHidden=tapEvt=touchEvt=moved=newIndex=newDraggableIndex=oldIndex=oldDraggableIndex=lastTarget=lastDirection=putSortable=activeGroup=Sortable.dragged=Sortable.ghost=Sortable.clone=Sortable.active=null,savedInputChecked.forEach(function(el){el.checked=!0}),savedInputChecked.length=lastDx=lastDy=0},"_nulling"),"_nulling"),handleEvent:__name2(__name(function(evt){switch(evt.type){case"drop":case"dragend":this._onDrop(evt);break;case"dragenter":case"dragover":dragEl&&(this._onDragOver(evt),_globalDragOver(evt));break;case"selectstart":evt.preventDefault();break}},"handleEvent"),"handleEvent"),toArray:__name2(__name(function(){for(var order=[],el,children=this.el.children,i=0,n2=children.length,options=this.options;irect.right+spacer||evt.clientX<=rect.right&&evt.clientY>rect.bottom&&evt.clientX>=rect.left:evt.clientX>rect.right&&evt.clientY>rect.top||evt.clientX<=rect.right&&evt.clientY>rect.bottom+spacer}__name(_ghostIsLast,"_ghostIsLast"),__name2(_ghostIsLast,"_ghostIsLast");function _getSwapDirection(evt,target,targetRect,vertical,swapThreshold,invertedSwapThreshold,invertSwap,isLastTarget){var mouseOnAxis=vertical?evt.clientY:evt.clientX,targetLength=vertical?targetRect.height:targetRect.width,targetS1=vertical?targetRect.top:targetRect.left,targetS2=vertical?targetRect.bottom:targetRect.right,invert=!1;if(!invertSwap){if(isLastTarget&&targetMoveDistancetargetS1+targetLength*invertedSwapThreshold/2:mouseOnAxistargetS2-targetMoveDistance)return-lastDirection}else if(mouseOnAxis>targetS1+targetLength*(1-swapThreshold)/2&&mouseOnAxistargetS2-targetLength*invertedSwapThreshold/2)?mouseOnAxis>targetS1+targetLength/2?1:-1:0}__name(_getSwapDirection,"_getSwapDirection"),__name2(_getSwapDirection,"_getSwapDirection");function _getInsertDirection(target){return index(dragEl)0&&t2[t2.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t2||op[1]>t2[0]&&op[1]=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}};throw new TypeError(s2?"Object is not iterable.":"Symbol.iterator is not defined.")}__name(__values,"__values"),__name2(__values,"__values");function __read(o,n2){var m=typeof Symbol=="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{for(;(n2===void 0||n2-- >0)&&!(r=i.next()).done;)ar.push(r.value)}catch(error){e={error}}finally{try{r&&!r.done&&(m=i.return)&&m.call(i)}finally{if(e)throw e.error}}return ar}__name(__read,"__read"),__name2(__read,"__read");var ENTRIES="ENTRIES",KEYS="KEYS",VALUES="VALUES",LEAF="",TreeIterator=function(){function TreeIterator2(set,type){var node=set._tree,keys2=Array.from(node.keys());this.set=set,this._type=type,this._path=keys2.length>0?[{node,keys:keys2}]:[]}return __name(TreeIterator2,"TreeIterator2"),__name2(TreeIterator2,"TreeIterator"),TreeIterator2.prototype.next=function(){var value=this.dive();return this.backtrack(),value},TreeIterator2.prototype.dive=function(){if(this._path.length===0)return{done:!0,value:void 0};var _a3=last$1(this._path),node=_a3.node,keys2=_a3.keys;if(last$1(keys2)===LEAF)return{done:!1,value:this.result()};var child=node.get(last$1(keys2));return this._path.push({node:child,keys:Array.from(child.keys())}),this.dive()},TreeIterator2.prototype.backtrack=function(){if(this._path.length!==0){var keys2=last$1(this._path).keys;keys2.pop(),!(keys2.length>0)&&(this._path.pop(),this.backtrack())}},TreeIterator2.prototype.key=function(){return this.set._prefix+this._path.map(function(_a3){var keys2=_a3.keys;return last$1(keys2)}).filter(function(key){return key!==LEAF}).join("")},TreeIterator2.prototype.value=function(){return last$1(this._path).node.get(LEAF)},TreeIterator2.prototype.result=function(){switch(this._type){case VALUES:return this.value();case KEYS:return this.key();default:return[this.key(),this.value()]}},TreeIterator2.prototype[Symbol.iterator]=function(){return this},TreeIterator2}(),last$1=__name2(function(array){return array[array.length-1]},"last$1"),fuzzySearch=__name2(function(node,query,maxDistance){var results=new Map;if(query===void 0)return results;for(var n2=query.length+1,m=n2+maxDistance,matrix2=new Uint8Array(m*n2).fill(maxDistance+1),j=0;jmaxDistance)continue key}recurse(node.get(key),query,maxDistance,results,matrix2,i,n2,prefix+key)}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_1)throw e_1.error}}},"recurse"),SearchableMap=function(){function SearchableMap2(tree,prefix){tree===void 0&&(tree=new Map),prefix===void 0&&(prefix=""),this._size=void 0,this._tree=tree,this._prefix=prefix}return __name(SearchableMap2,"SearchableMap2"),__name2(SearchableMap2,"SearchableMap"),SearchableMap2.prototype.atPrefix=function(prefix){var e_1,_a3;if(!prefix.startsWith(this._prefix))throw new Error("Mismatched prefix");var _b2=__read(trackDown(this._tree,prefix.slice(this._prefix.length)),2),node=_b2[0],path=_b2[1];if(node===void 0){var _c2=__read(last(path),2),parentNode=_c2[0],key=_c2[1];try{for(var _d=__values(parentNode.keys()),_e=_d.next();!_e.done;_e=_d.next()){var k=_e.value;if(k!==LEAF&&k.startsWith(key)){var node_1=new Map;return node_1.set(k.slice(key.length),parentNode.get(k)),new SearchableMap2(node_1,prefix)}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_e&&!_e.done&&(_a3=_d.return)&&_a3.call(_d)}finally{if(e_1)throw e_1.error}}}return new SearchableMap2(node,prefix)},SearchableMap2.prototype.clear=function(){this._size=void 0,this._tree.clear()},SearchableMap2.prototype.delete=function(key){return this._size=void 0,remove$1(this._tree,key)},SearchableMap2.prototype.entries=function(){return new TreeIterator(this,ENTRIES)},SearchableMap2.prototype.forEach=function(fn){var e_2,_a3;try{for(var _b2=__values(this),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var _d=__read(_c2.value,2),key=_d[0],value=_d[1];fn(key,value,this)}}catch(e_2_1){e_2={error:e_2_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_2)throw e_2.error}}},SearchableMap2.prototype.fuzzyGet=function(key,maxEditDistance){return fuzzySearch(this._tree,key,maxEditDistance)},SearchableMap2.prototype.get=function(key){var node=lookup(this._tree,key);return node!==void 0?node.get(LEAF):void 0},SearchableMap2.prototype.has=function(key){var node=lookup(this._tree,key);return node!==void 0&&node.has(LEAF)},SearchableMap2.prototype.keys=function(){return new TreeIterator(this,KEYS)},SearchableMap2.prototype.set=function(key,value){if(typeof key!="string")throw new Error("key must be a string");this._size=void 0;var node=createPath(this._tree,key);return node.set(LEAF,value),this},Object.defineProperty(SearchableMap2.prototype,"size",{get:function(){if(this._size)return this._size;this._size=0;for(var iter=this.entries();!iter.next().done;)this._size+=1;return this._size},enumerable:!1,configurable:!0}),SearchableMap2.prototype.update=function(key,fn){if(typeof key!="string")throw new Error("key must be a string");this._size=void 0;var node=createPath(this._tree,key);return node.set(LEAF,fn(node.get(LEAF))),this},SearchableMap2.prototype.fetch=function(key,initial){if(typeof key!="string")throw new Error("key must be a string");this._size=void 0;var node=createPath(this._tree,key),value=node.get(LEAF);return value===void 0&&node.set(LEAF,value=initial()),value},SearchableMap2.prototype.values=function(){return new TreeIterator(this,VALUES)},SearchableMap2.prototype[Symbol.iterator]=function(){return this.entries()},SearchableMap2.from=function(entries){var e_3,_a3,tree=new SearchableMap2;try{for(var entries_1=__values(entries),entries_1_1=entries_1.next();!entries_1_1.done;entries_1_1=entries_1.next()){var _b2=__read(entries_1_1.value,2),key=_b2[0],value=_b2[1];tree.set(key,value)}}catch(e_3_1){e_3={error:e_3_1}}finally{try{entries_1_1&&!entries_1_1.done&&(_a3=entries_1.return)&&_a3.call(entries_1)}finally{if(e_3)throw e_3.error}}return tree},SearchableMap2.fromObject=function(object){return SearchableMap2.from(Object.entries(object))},SearchableMap2}(),trackDown=__name2(function(tree,key,path){var e_4,_a3;if(path===void 0&&(path=[]),key.length===0||tree==null)return[tree,path];try{for(var _b2=__values(tree.keys()),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var k=_c2.value;if(k!==LEAF&&key.startsWith(k))return path.push([tree,k]),trackDown(tree.get(k),key.slice(k.length),path)}}catch(e_4_1){e_4={error:e_4_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_4)throw e_4.error}}return path.push([tree,key]),trackDown(void 0,"",path)},"trackDown"),lookup=__name2(function(tree,key){var e_5,_a3;if(key.length===0||tree==null)return tree;try{for(var _b2=__values(tree.keys()),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var k=_c2.value;if(k!==LEAF&&key.startsWith(k))return lookup(tree.get(k),key.slice(k.length))}}catch(e_5_1){e_5={error:e_5_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_5)throw e_5.error}}},"lookup"),createPath=__name2(function(node,key){var e_6,_a3,keyLength=key.length;outer:for(var pos=0;node&&pos0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new SearchableMap,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}},MiniSearch2.prototype.discard=function(id){var _this=this,shortId=this._idToShortId.get(id);if(shortId==null)throw new Error("MiniSearch: cannot discard document with ID ".concat(id,": it is not in the index"));this._idToShortId.delete(id),this._documentIds.delete(shortId),this._storedFields.delete(shortId),(this._fieldLength.get(shortId)||[]).forEach(function(fieldLength,fieldId){_this.removeFieldLength(shortId,fieldId,_this._documentCount,fieldLength)}),this._fieldLength.delete(shortId),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()},MiniSearch2.prototype.maybeAutoVacuum=function(){if(this._options.autoVacuum!==!1){var _a3=this._options.autoVacuum,minDirtFactor=_a3.minDirtFactor,minDirtCount=_a3.minDirtCount,batchSize=_a3.batchSize,batchWait=_a3.batchWait;this.conditionalVacuum({batchSize,batchWait},{minDirtCount,minDirtFactor})}},MiniSearch2.prototype.discardAll=function(ids){var e_9,_a3,autoVacuum=this._options.autoVacuum;try{this._options.autoVacuum=!1;try{for(var ids_1=__values(ids),ids_1_1=ids_1.next();!ids_1_1.done;ids_1_1=ids_1.next()){var id=ids_1_1.value;this.discard(id)}}catch(e_9_1){e_9={error:e_9_1}}finally{try{ids_1_1&&!ids_1_1.done&&(_a3=ids_1.return)&&_a3.call(ids_1)}finally{if(e_9)throw e_9.error}}}finally{this._options.autoVacuum=autoVacuum}this.maybeAutoVacuum()},MiniSearch2.prototype.replace=function(updatedDocument){var _a3=this._options,idField=_a3.idField,extractField=_a3.extractField,id=extractField(updatedDocument,idField);this.discard(id),this.add(updatedDocument)},MiniSearch2.prototype.vacuum=function(options){return options===void 0&&(options={}),this.conditionalVacuum(options)},MiniSearch2.prototype.conditionalVacuum=function(options,conditions){var _this=this;return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&conditions,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(function(){var conditions2=_this._enqueuedVacuumConditions;return _this._enqueuedVacuumConditions=defaultVacuumConditions,_this.performVacuuming(options,conditions2)}),this._enqueuedVacuum)):this.vacuumConditionsMet(conditions)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(options),this._currentVacuum)},MiniSearch2.prototype.performVacuuming=function(options,conditions){return __awaiter(this,void 0,void 0,function(){var initialDirtCount,batchSize,batchWait_1,i,_a3,_b2,_c2,term,fieldsData,fieldsData_1,fieldsData_1_1,_d,fieldId,fieldIndex,fieldIndex_1,fieldIndex_1_1,_e,shortId,e_10_1,e_10,_f,e_11,_g,e_12,_h;return __generator(this,function(_j){switch(_j.label){case 0:if(initialDirtCount=this._dirtCount,!this.vacuumConditionsMet(conditions))return[3,10];batchSize=options.batchSize||defaultVacuumOptions.batchSize,batchWait_1=options.batchWait||defaultVacuumOptions.batchWait,i=1,_j.label=1;case 1:_j.trys.push([1,7,8,9]),_a3=__values(this._index),_b2=_a3.next(),_j.label=2;case 2:if(_b2.done)return[3,6];_c2=__read(_b2.value,2),term=_c2[0],fieldsData=_c2[1];try{for(fieldsData_1=(e_11=void 0,__values(fieldsData)),fieldsData_1_1=fieldsData_1.next();!fieldsData_1_1.done;fieldsData_1_1=fieldsData_1.next()){_d=__read(fieldsData_1_1.value,2),fieldId=_d[0],fieldIndex=_d[1];try{for(fieldIndex_1=(e_12=void 0,__values(fieldIndex)),fieldIndex_1_1=fieldIndex_1.next();!fieldIndex_1_1.done;fieldIndex_1_1=fieldIndex_1.next())_e=__read(fieldIndex_1_1.value,1),shortId=_e[0],!this._documentIds.has(shortId)&&(fieldIndex.size<=1?fieldsData.delete(fieldId):fieldIndex.delete(shortId))}catch(e_12_1){e_12={error:e_12_1}}finally{try{fieldIndex_1_1&&!fieldIndex_1_1.done&&(_h=fieldIndex_1.return)&&_h.call(fieldIndex_1)}finally{if(e_12)throw e_12.error}}}}catch(e_11_1){e_11={error:e_11_1}}finally{try{fieldsData_1_1&&!fieldsData_1_1.done&&(_g=fieldsData_1.return)&&_g.call(fieldsData_1)}finally{if(e_11)throw e_11.error}}return this._index.get(term).size===0&&this._index.delete(term),i%batchSize!==0?[3,4]:[4,new Promise(function(resolve){return setTimeout(resolve,batchWait_1)})];case 3:_j.sent(),_j.label=4;case 4:i+=1,_j.label=5;case 5:return _b2=_a3.next(),[3,2];case 6:return[3,9];case 7:return e_10_1=_j.sent(),e_10={error:e_10_1},[3,9];case 8:try{_b2&&!_b2.done&&(_f=_a3.return)&&_f.call(_a3)}finally{if(e_10)throw e_10.error}return[7];case 9:this._dirtCount-=initialDirtCount,_j.label=10;case 10:return[4,null];case 11:return _j.sent(),this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null,[2]}})})},MiniSearch2.prototype.vacuumConditionsMet=function(conditions){if(conditions==null)return!0;var minDirtCount=conditions.minDirtCount,minDirtFactor=conditions.minDirtFactor;return minDirtCount=minDirtCount||defaultAutoVacuumOptions.minDirtCount,minDirtFactor=minDirtFactor||defaultAutoVacuumOptions.minDirtFactor,this.dirtCount>=minDirtCount&&this.dirtFactor>=minDirtFactor},Object.defineProperty(MiniSearch2.prototype,"isVacuuming",{get:function(){return this._currentVacuum!=null},enumerable:!1,configurable:!0}),Object.defineProperty(MiniSearch2.prototype,"dirtCount",{get:function(){return this._dirtCount},enumerable:!1,configurable:!0}),Object.defineProperty(MiniSearch2.prototype,"dirtFactor",{get:function(){return this._dirtCount/(1+this._documentCount+this._dirtCount)},enumerable:!1,configurable:!0}),MiniSearch2.prototype.has=function(id){return this._idToShortId.has(id)},MiniSearch2.prototype.getStoredFields=function(id){var shortId=this._idToShortId.get(id);if(shortId!=null)return this._storedFields.get(shortId)},MiniSearch2.prototype.search=function(query,searchOptions){var e_13,_a3;searchOptions===void 0&&(searchOptions={});var combinedResults=this.executeQuery(query,searchOptions),results=[];try{for(var combinedResults_1=__values(combinedResults),combinedResults_1_1=combinedResults_1.next();!combinedResults_1_1.done;combinedResults_1_1=combinedResults_1.next()){var _b2=__read(combinedResults_1_1.value,2),docId=_b2[0],_c2=_b2[1],score2=_c2.score,terms=_c2.terms,match2=_c2.match,quality=terms.length,result={id:this._documentIds.get(docId),score:score2*quality,terms:Object.keys(match2),match:match2};Object.assign(result,this._storedFields.get(docId)),(searchOptions.filter==null||searchOptions.filter(result))&&results.push(result)}}catch(e_13_1){e_13={error:e_13_1}}finally{try{combinedResults_1_1&&!combinedResults_1_1.done&&(_a3=combinedResults_1.return)&&_a3.call(combinedResults_1)}finally{if(e_13)throw e_13.error}}return results.sort(byScore),results},MiniSearch2.prototype.autoSuggest=function(queryString,options){var e_14,_a3,e_15,_b2;options===void 0&&(options={}),options=__assign(__assign({},this._options.autoSuggestOptions),options);var suggestions=new Map;try{for(var _c2=__values(this.search(queryString,options)),_d=_c2.next();!_d.done;_d=_c2.next()){var _e=_d.value,score2=_e.score,terms=_e.terms,phrase2=terms.join(" "),suggestion=suggestions.get(phrase2);suggestion!=null?(suggestion.score+=score2,suggestion.count+=1):suggestions.set(phrase2,{score:score2,terms,count:1})}}catch(e_14_1){e_14={error:e_14_1}}finally{try{_d&&!_d.done&&(_a3=_c2.return)&&_a3.call(_c2)}finally{if(e_14)throw e_14.error}}var results=[];try{for(var suggestions_1=__values(suggestions),suggestions_1_1=suggestions_1.next();!suggestions_1_1.done;suggestions_1_1=suggestions_1.next()){var _f=__read(suggestions_1_1.value,2),suggestion=_f[0],_g=_f[1],score2=_g.score,terms=_g.terms,count=_g.count;results.push({suggestion,terms,score:score2/count})}}catch(e_15_1){e_15={error:e_15_1}}finally{try{suggestions_1_1&&!suggestions_1_1.done&&(_b2=suggestions_1.return)&&_b2.call(suggestions_1)}finally{if(e_15)throw e_15.error}}return results.sort(byScore),results},Object.defineProperty(MiniSearch2.prototype,"documentCount",{get:function(){return this._documentCount},enumerable:!1,configurable:!0}),Object.defineProperty(MiniSearch2.prototype,"termCount",{get:function(){return this._index.size},enumerable:!1,configurable:!0}),MiniSearch2.loadJSON=function(json2,options){if(options==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(json2),options)},MiniSearch2.getDefault=function(optionName){if(defaultOptions.hasOwnProperty(optionName))return getOwnProperty(defaultOptions,optionName);throw new Error('MiniSearch: unknown option "'.concat(optionName,'"'))},MiniSearch2.loadJS=function(js,options){var e_16,_a3,e_17,_b2,e_18,_c2,index2=js.index,documentCount=js.documentCount,nextId=js.nextId,documentIds=js.documentIds,fieldIds=js.fieldIds,fieldLength=js.fieldLength,averageFieldLength=js.averageFieldLength,storedFields=js.storedFields,dirtCount=js.dirtCount,serializationVersion=js.serializationVersion;if(serializationVersion!==1&&serializationVersion!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");var miniSearch=new MiniSearch2(options);miniSearch._documentCount=documentCount,miniSearch._nextId=nextId,miniSearch._documentIds=objectToNumericMap(documentIds),miniSearch._idToShortId=new Map,miniSearch._fieldIds=fieldIds,miniSearch._fieldLength=objectToNumericMap(fieldLength),miniSearch._avgFieldLength=averageFieldLength,miniSearch._storedFields=objectToNumericMap(storedFields),miniSearch._dirtCount=dirtCount||0,miniSearch._index=new SearchableMap;try{for(var _d=__values(miniSearch._documentIds),_e=_d.next();!_e.done;_e=_d.next()){var _f=__read(_e.value,2),shortId=_f[0],id=_f[1];miniSearch._idToShortId.set(id,shortId)}}catch(e_16_1){e_16={error:e_16_1}}finally{try{_e&&!_e.done&&(_a3=_d.return)&&_a3.call(_d)}finally{if(e_16)throw e_16.error}}try{for(var index_1=__values(index2),index_1_1=index_1.next();!index_1_1.done;index_1_1=index_1.next()){var _g=__read(index_1_1.value,2),term=_g[0],data=_g[1],dataMap=new Map;try{for(var _h=(e_18=void 0,__values(Object.keys(data))),_j=_h.next();!_j.done;_j=_h.next()){var fieldId=_j.value,indexEntry=data[fieldId];serializationVersion===1&&(indexEntry=indexEntry.ds),dataMap.set(parseInt(fieldId,10),objectToNumericMap(indexEntry))}}catch(e_18_1){e_18={error:e_18_1}}finally{try{_j&&!_j.done&&(_c2=_h.return)&&_c2.call(_h)}finally{if(e_18)throw e_18.error}}miniSearch._index.set(term,dataMap)}}catch(e_17_1){e_17={error:e_17_1}}finally{try{index_1_1&&!index_1_1.done&&(_b2=index_1.return)&&_b2.call(index_1)}finally{if(e_17)throw e_17.error}}return miniSearch},MiniSearch2.prototype.executeQuery=function(query,searchOptions){var _this=this;if(searchOptions===void 0&&(searchOptions={}),typeof query!="string"){var options_1=__assign(__assign(__assign({},searchOptions),query),{queries:void 0}),results_1=query.queries.map(function(subquery){return _this.executeQuery(subquery,options_1)});return this.combineResults(results_1,options_1.combineWith)}var _a3=this._options,tokenize=_a3.tokenize,processTerm=_a3.processTerm,globalSearchOptions=_a3.searchOptions,options=__assign(__assign({tokenize,processTerm},globalSearchOptions),searchOptions),searchTokenize=options.tokenize,searchProcessTerm=options.processTerm,terms=searchTokenize(query).flatMap(function(term){return searchProcessTerm(term)}).filter(function(term){return!!term}),queries=terms.map(termToQuerySpec(options)),results=queries.map(function(query2){return _this.executeQuerySpec(query2,options)});return this.combineResults(results,options.combineWith)},MiniSearch2.prototype.executeQuerySpec=function(query,searchOptions){var e_19,_a3,e_20,_b2,options=__assign(__assign({},this._options.searchOptions),searchOptions),boosts=(options.fields||this._options.fields).reduce(function(boosts2,field){var _a4;return __assign(__assign({},boosts2),(_a4={},_a4[field]=getOwnProperty(options.boost,field)||1,_a4))},{}),boostDocument=options.boostDocument,weights=options.weights,maxFuzzy=options.maxFuzzy,bm25params=options.bm25,_c2=__assign(__assign({},defaultSearchOptions.weights),weights),fuzzyWeight=_c2.fuzzy,prefixWeight=_c2.prefix,data=this._index.get(query.term),results=this.termResults(query.term,query.term,1,data,boosts,boostDocument,bm25params),prefixMatches,fuzzyMatches;if(query.prefix&&(prefixMatches=this._index.atPrefix(query.term)),query.fuzzy){var fuzzy=query.fuzzy===!0?.2:query.fuzzy,maxDistance=fuzzy<1?Math.min(maxFuzzy,Math.round(query.term.length*fuzzy)):fuzzy;maxDistance&&(fuzzyMatches=this._index.fuzzyGet(query.term,maxDistance))}if(prefixMatches)try{for(var prefixMatches_1=__values(prefixMatches),prefixMatches_1_1=prefixMatches_1.next();!prefixMatches_1_1.done;prefixMatches_1_1=prefixMatches_1.next()){var _d=__read(prefixMatches_1_1.value,2),term=_d[0],data_1=_d[1],distance=term.length-query.term.length;if(distance){fuzzyMatches?.delete(term);var weight=prefixWeight*term.length/(term.length+.3*distance);this.termResults(query.term,term,weight,data_1,boosts,boostDocument,bm25params,results)}}}catch(e_19_1){e_19={error:e_19_1}}finally{try{prefixMatches_1_1&&!prefixMatches_1_1.done&&(_a3=prefixMatches_1.return)&&_a3.call(prefixMatches_1)}finally{if(e_19)throw e_19.error}}if(fuzzyMatches)try{for(var _e=__values(fuzzyMatches.keys()),_f=_e.next();!_f.done;_f=_e.next()){var term=_f.value,_g=__read(fuzzyMatches.get(term),2),data_2=_g[0],distance=_g[1];if(distance){var weight=fuzzyWeight*term.length/(term.length+distance);this.termResults(query.term,term,weight,data_2,boosts,boostDocument,bm25params,results)}}}catch(e_20_1){e_20={error:e_20_1}}finally{try{_f&&!_f.done&&(_b2=_e.return)&&_b2.call(_e)}finally{if(e_20)throw e_20.error}}return results},MiniSearch2.prototype.combineResults=function(results,combineWith){if(combineWith===void 0&&(combineWith=OR),results.length===0)return new Map;var operator2=combineWith.toLowerCase();return results.reduce(combinators[operator2])||new Map},MiniSearch2.prototype.toJSON=function(){var e_21,_a3,e_22,_b2,index2=[];try{for(var _c2=__values(this._index),_d=_c2.next();!_d.done;_d=_c2.next()){var _e=__read(_d.value,2),term=_e[0],fieldIndex=_e[1],data={};try{for(var fieldIndex_2=(e_22=void 0,__values(fieldIndex)),fieldIndex_2_1=fieldIndex_2.next();!fieldIndex_2_1.done;fieldIndex_2_1=fieldIndex_2.next()){var _f=__read(fieldIndex_2_1.value,2),fieldId=_f[0],freqs=_f[1];data[fieldId]=Object.fromEntries(freqs)}}catch(e_22_1){e_22={error:e_22_1}}finally{try{fieldIndex_2_1&&!fieldIndex_2_1.done&&(_b2=fieldIndex_2.return)&&_b2.call(fieldIndex_2)}finally{if(e_22)throw e_22.error}}index2.push([term,data])}}catch(e_21_1){e_21={error:e_21_1}}finally{try{_d&&!_d.done&&(_a3=_c2.return)&&_a3.call(_c2)}finally{if(e_21)throw e_21.error}}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:index2,serializationVersion:2}},MiniSearch2.prototype.termResults=function(sourceTerm,derivedTerm,termWeight,fieldTermData,fieldBoosts,boostDocumentFn,bm25params,results){var e_23,_a3,e_24,_b2,_c2;if(results===void 0&&(results=new Map),fieldTermData==null)return results;try{for(var _d=__values(Object.keys(fieldBoosts)),_e=_d.next();!_e.done;_e=_d.next()){var field=_e.value,fieldBoost=fieldBoosts[field],fieldId=this._fieldIds[field],fieldTermFreqs=fieldTermData.get(fieldId);if(fieldTermFreqs!=null){var matchingFields=fieldTermFreqs.size,avgFieldLength=this._avgFieldLength[fieldId];try{for(var _f=(e_24=void 0,__values(fieldTermFreqs.keys())),_g=_f.next();!_g.done;_g=_f.next()){var docId=_g.value;if(!this._documentIds.has(docId)){this.removeTerm(fieldId,docId,derivedTerm),matchingFields-=1;continue}var docBoost=boostDocumentFn?boostDocumentFn(this._documentIds.get(docId),derivedTerm,this._storedFields.get(docId)):1;if(docBoost){var termFreq=fieldTermFreqs.get(docId),fieldLength=this._fieldLength.get(docId)[fieldId],rawScore=calcBM25Score(termFreq,matchingFields,this._documentCount,fieldLength,avgFieldLength,bm25params),weightedScore=termWeight*fieldBoost*docBoost*rawScore,result=results.get(docId);if(result){result.score+=weightedScore,assignUniqueTerm(result.terms,sourceTerm);var match2=getOwnProperty(result.match,derivedTerm);match2?match2.push(field):result.match[derivedTerm]=[field]}else results.set(docId,{score:weightedScore,terms:[sourceTerm],match:(_c2={},_c2[derivedTerm]=[field],_c2)})}}}catch(e_24_1){e_24={error:e_24_1}}finally{try{_g&&!_g.done&&(_b2=_f.return)&&_b2.call(_f)}finally{if(e_24)throw e_24.error}}}}}catch(e_23_1){e_23={error:e_23_1}}finally{try{_e&&!_e.done&&(_a3=_d.return)&&_a3.call(_d)}finally{if(e_23)throw e_23.error}}return results},MiniSearch2.prototype.addTerm=function(fieldId,documentId,term){var indexData=this._index.fetch(term,createMap),fieldIndex=indexData.get(fieldId);if(fieldIndex==null)fieldIndex=new Map,fieldIndex.set(documentId,1),indexData.set(fieldId,fieldIndex);else{var docs=fieldIndex.get(documentId);fieldIndex.set(documentId,(docs||0)+1)}},MiniSearch2.prototype.removeTerm=function(fieldId,documentId,term){if(!this._index.has(term)){this.warnDocumentChanged(documentId,fieldId,term);return}var indexData=this._index.fetch(term,createMap),fieldIndex=indexData.get(fieldId);fieldIndex==null||fieldIndex.get(documentId)==null?this.warnDocumentChanged(documentId,fieldId,term):fieldIndex.get(documentId)<=1?fieldIndex.size<=1?indexData.delete(fieldId):fieldIndex.delete(documentId):fieldIndex.set(documentId,fieldIndex.get(documentId)-1),this._index.get(term).size===0&&this._index.delete(term)},MiniSearch2.prototype.warnDocumentChanged=function(shortDocumentId,fieldId,term){var e_25,_a3;try{for(var _b2=__values(Object.keys(this._fieldIds)),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var fieldName=_c2.value;if(this._fieldIds[fieldName]===fieldId){this._options.logger("warn","MiniSearch: document with ID ".concat(this._documentIds.get(shortDocumentId),' has changed before removal: term "').concat(term,'" was not present in field "').concat(fieldName,'". Removing a document after it has changed can corrupt the index!'),"version_conflict");return}}}catch(e_25_1){e_25={error:e_25_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_25)throw e_25.error}}},MiniSearch2.prototype.addDocumentId=function(documentId){var shortDocumentId=this._nextId;return this._idToShortId.set(documentId,shortDocumentId),this._documentIds.set(shortDocumentId,documentId),this._documentCount+=1,this._nextId+=1,shortDocumentId},MiniSearch2.prototype.addFields=function(fields){for(var i=0;i=0?over:1e3+over,(asUTC-asTS)/(60*1e3)}equals(otherZone){return otherZone.type==="iana"&&otherZone.name===this.name}get isValid(){return this.valid}};__name2(_IANAZone,"IANAZone");let IANAZone=_IANAZone,intlLFCache={};function getCachedLF(locString,opts={}){const key=JSON.stringify([locString,opts]);let dtf=intlLFCache[key];return dtf||(dtf=new Intl.ListFormat(locString,opts),intlLFCache[key]=dtf),dtf}__name(getCachedLF,"getCachedLF"),__name2(getCachedLF,"getCachedLF");let intlDTCache={};function getCachedDTF(locString,opts={}){const key=JSON.stringify([locString,opts]);let dtf=intlDTCache[key];return dtf||(dtf=new Intl.DateTimeFormat(locString,opts),intlDTCache[key]=dtf),dtf}__name(getCachedDTF,"getCachedDTF"),__name2(getCachedDTF,"getCachedDTF");let intlNumCache={};function getCachedINF(locString,opts={}){const key=JSON.stringify([locString,opts]);let inf=intlNumCache[key];return inf||(inf=new Intl.NumberFormat(locString,opts),intlNumCache[key]=inf),inf}__name(getCachedINF,"getCachedINF"),__name2(getCachedINF,"getCachedINF");let intlRelCache={};function getCachedRTF(locString,opts={}){const{base:base2,...cacheKeyOpts}=opts,key=JSON.stringify([locString,cacheKeyOpts]);let inf=intlRelCache[key];return inf||(inf=new Intl.RelativeTimeFormat(locString,opts),intlRelCache[key]=inf),inf}__name(getCachedRTF,"getCachedRTF"),__name2(getCachedRTF,"getCachedRTF");let sysLocaleCache=null;function systemLocale(){return sysLocaleCache||(sysLocaleCache=new Intl.DateTimeFormat().resolvedOptions().locale,sysLocaleCache)}__name(systemLocale,"systemLocale"),__name2(systemLocale,"systemLocale");function parseLocaleString(localeStr){const xIndex=localeStr.indexOf("-x-");xIndex!==-1&&(localeStr=localeStr.substring(0,xIndex));const uIndex=localeStr.indexOf("-u-");if(uIndex===-1)return[localeStr];{let options,selectedStr;try{options=getCachedDTF(localeStr).resolvedOptions(),selectedStr=localeStr}catch{const smaller=localeStr.substring(0,uIndex);options=getCachedDTF(smaller).resolvedOptions(),selectedStr=smaller}const{numberingSystem,calendar}=options;return[selectedStr,numberingSystem,calendar]}}__name(parseLocaleString,"parseLocaleString"),__name2(parseLocaleString,"parseLocaleString");function intlConfigString(localeStr,numberingSystem,outputCalendar){return(outputCalendar||numberingSystem)&&(localeStr.includes("-u-")||(localeStr+="-u"),outputCalendar&&(localeStr+=`-ca-${outputCalendar}`),numberingSystem&&(localeStr+=`-nu-${numberingSystem}`)),localeStr}__name(intlConfigString,"intlConfigString"),__name2(intlConfigString,"intlConfigString");function mapMonths(f){const ms=[];for(let i=1;i<=12;i++){const dt=DateTime.utc(2009,i,1);ms.push(f(dt))}return ms}__name(mapMonths,"mapMonths"),__name2(mapMonths,"mapMonths");function mapWeekdays(f){const ms=[];for(let i=1;i<=7;i++){const dt=DateTime.utc(2016,11,13+i);ms.push(f(dt))}return ms}__name(mapWeekdays,"mapWeekdays"),__name2(mapWeekdays,"mapWeekdays");function listStuff(loc,length,englishFn,intlFn){const mode=loc.listingMode();return mode==="error"?null:mode==="en"?englishFn(length):intlFn(length)}__name(listStuff,"listStuff"),__name2(listStuff,"listStuff");function supportsFastNumbers(loc){return loc.numberingSystem&&loc.numberingSystem!=="latn"?!1:loc.numberingSystem==="latn"||!loc.locale||loc.locale.startsWith("en")||new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem==="latn"}__name(supportsFastNumbers,"supportsFastNumbers"),__name2(supportsFastNumbers,"supportsFastNumbers");const _PolyNumberFormatter=class{static{__name(this,"_PolyNumberFormatter")}constructor(intl,forceSimple,opts){this.padTo=opts.padTo||0,this.floor=opts.floor||!1;const{padTo,floor,...otherOpts}=opts;if(!forceSimple||Object.keys(otherOpts).length>0){const intlOpts={useGrouping:!1,...opts};opts.padTo>0&&(intlOpts.minimumIntegerDigits=opts.padTo),this.inf=getCachedINF(intl,intlOpts)}}format(i){if(this.inf){const fixed=this.floor?Math.floor(i):i;return this.inf.format(fixed)}else{const fixed=this.floor?Math.floor(i):roundTo(i,3);return padStart(fixed,this.padTo)}}};__name2(_PolyNumberFormatter,"PolyNumberFormatter");let PolyNumberFormatter=_PolyNumberFormatter;const _PolyDateFormatter=class{static{__name(this,"_PolyDateFormatter")}constructor(dt,intl,opts){this.opts=opts,this.originalZone=void 0;let z;if(this.opts.timeZone)this.dt=dt;else if(dt.zone.type==="fixed"){const gmtOffset=-1*(dt.offset/60),offsetZ=gmtOffset>=0?`Etc/GMT+${gmtOffset}`:`Etc/GMT${gmtOffset}`;dt.offset!==0&&IANAZone.create(offsetZ).valid?(z=offsetZ,this.dt=dt):(z="UTC",this.dt=dt.offset===0?dt:dt.setZone("UTC").plus({minutes:dt.offset}),this.originalZone=dt.zone)}else dt.zone.type==="system"?this.dt=dt:dt.zone.type==="iana"?(this.dt=dt,z=dt.zone.name):(z="UTC",this.dt=dt.setZone("UTC").plus({minutes:dt.offset}),this.originalZone=dt.zone);const intlOpts={...this.opts};intlOpts.timeZone=intlOpts.timeZone||z,this.dtf=getCachedDTF(intl,intlOpts)}format(){return this.originalZone?this.formatToParts().map(({value})=>value).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const parts=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?parts.map(part=>{if(part.type==="timeZoneName"){const offsetName=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...part,value:offsetName}}else return part}):parts}resolvedOptions(){return this.dtf.resolvedOptions()}};__name2(_PolyDateFormatter,"PolyDateFormatter");let PolyDateFormatter=_PolyDateFormatter;const _PolyRelFormatter=class{static{__name(this,"_PolyRelFormatter")}constructor(intl,isEnglish,opts){this.opts={style:"long",...opts},!isEnglish&&hasRelative()&&(this.rtf=getCachedRTF(intl,opts))}format(count,unit){return this.rtf?this.rtf.format(count,unit):formatRelativeTime(unit,count,this.opts.numeric,this.opts.style!=="long")}formatToParts(count,unit){return this.rtf?this.rtf.formatToParts(count,unit):[]}};__name2(_PolyRelFormatter,"PolyRelFormatter");let PolyRelFormatter=_PolyRelFormatter;const _Locale=class _Locale2{static{__name(this,"_Locale")}static fromOpts(opts){return _Locale2.create(opts.locale,opts.numberingSystem,opts.outputCalendar,opts.defaultToEN)}static create(locale,numberingSystem,outputCalendar,defaultToEN=!1){const specifiedLocale=locale||Settings.defaultLocale,localeR=specifiedLocale||(defaultToEN?"en-US":systemLocale()),numberingSystemR=numberingSystem||Settings.defaultNumberingSystem,outputCalendarR=outputCalendar||Settings.defaultOutputCalendar;return new _Locale2(localeR,numberingSystemR,outputCalendarR,specifiedLocale)}static resetCache(){sysLocaleCache=null,intlDTCache={},intlNumCache={},intlRelCache={}}static fromObject({locale,numberingSystem,outputCalendar}={}){return _Locale2.create(locale,numberingSystem,outputCalendar)}constructor(locale,numbering,outputCalendar,specifiedLocale){const[parsedLocale,parsedNumberingSystem,parsedOutputCalendar]=parseLocaleString(locale);this.locale=parsedLocale,this.numberingSystem=numbering||parsedNumberingSystem||null,this.outputCalendar=outputCalendar||parsedOutputCalendar||null,this.intl=intlConfigString(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=specifiedLocale,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=supportsFastNumbers(this)),this.fastNumbersCached}listingMode(){const isActuallyEn=this.isEnglish(),hasNoWeirdness=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return isActuallyEn&&hasNoWeirdness?"en":"intl"}clone(alts){return!alts||Object.getOwnPropertyNames(alts).length===0?this:_Locale2.create(alts.locale||this.specifiedLocale,alts.numberingSystem||this.numberingSystem,alts.outputCalendar||this.outputCalendar,alts.defaultToEN||!1)}redefaultToEN(alts={}){return this.clone({...alts,defaultToEN:!0})}redefaultToSystem(alts={}){return this.clone({...alts,defaultToEN:!1})}months(length,format=!1){return listStuff(this,length,months,()=>{const intl=format?{month:length,day:"numeric"}:{month:length},formatStr=format?"format":"standalone";return this.monthsCache[formatStr][length]||(this.monthsCache[formatStr][length]=mapMonths(dt=>this.extract(dt,intl,"month"))),this.monthsCache[formatStr][length]})}weekdays(length,format=!1){return listStuff(this,length,weekdays,()=>{const intl=format?{weekday:length,year:"numeric",month:"long",day:"numeric"}:{weekday:length},formatStr=format?"format":"standalone";return this.weekdaysCache[formatStr][length]||(this.weekdaysCache[formatStr][length]=mapWeekdays(dt=>this.extract(dt,intl,"weekday"))),this.weekdaysCache[formatStr][length]})}meridiems(){return listStuff(this,void 0,()=>meridiems,()=>{if(!this.meridiemCache){const intl={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[DateTime.utc(2016,11,13,9),DateTime.utc(2016,11,13,19)].map(dt=>this.extract(dt,intl,"dayperiod"))}return this.meridiemCache})}eras(length){return listStuff(this,length,eras,()=>{const intl={era:length};return this.eraCache[length]||(this.eraCache[length]=[DateTime.utc(-40,1,1),DateTime.utc(2017,1,1)].map(dt=>this.extract(dt,intl,"era"))),this.eraCache[length]})}extract(dt,intlOpts,field){const df=this.dtFormatter(dt,intlOpts),results=df.formatToParts(),matching=results.find(m=>m.type.toLowerCase()===field);return matching?matching.value:null}numberFormatter(opts={}){return new PolyNumberFormatter(this.intl,opts.forceSimple||this.fastNumbers,opts)}dtFormatter(dt,intlOpts={}){return new PolyDateFormatter(dt,this.intl,intlOpts)}relFormatter(opts={}){return new PolyRelFormatter(this.intl,this.isEnglish(),opts)}listFormatter(opts={}){return getCachedLF(this.intl,opts)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}equals(other){return this.locale===other.locale&&this.numberingSystem===other.numberingSystem&&this.outputCalendar===other.outputCalendar}};__name2(_Locale,"Locale");let Locale=_Locale,singleton=null;const _FixedOffsetZone=class _FixedOffsetZone2 extends Zone{static{__name(this,"_FixedOffsetZone")}static get utcInstance(){return singleton===null&&(singleton=new _FixedOffsetZone2(0)),singleton}static instance(offset2){return offset2===0?_FixedOffsetZone2.utcInstance:new _FixedOffsetZone2(offset2)}static parseSpecifier(s2){if(s2){const r=s2.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new _FixedOffsetZone2(signedOffset(r[1],r[2]))}return null}constructor(offset2){super(),this.fixed=offset2}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${formatOffset(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${formatOffset(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(ts,format){return formatOffset(this.fixed,format)}get isUniversal(){return!0}offset(){return this.fixed}equals(otherZone){return otherZone.type==="fixed"&&otherZone.fixed===this.fixed}get isValid(){return!0}};__name2(_FixedOffsetZone,"FixedOffsetZone");let FixedOffsetZone=_FixedOffsetZone;const _InvalidZone=class extends Zone{static{__name(this,"_InvalidZone")}constructor(zoneName){super(),this.zoneName=zoneName}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};__name2(_InvalidZone,"InvalidZone");let InvalidZone=_InvalidZone;function normalizeZone(input,defaultZone2){if(isUndefined(input)||input===null)return defaultZone2;if(input instanceof Zone)return input;if(isString(input)){const lowered=input.toLowerCase();return lowered==="default"?defaultZone2:lowered==="local"||lowered==="system"?SystemZone.instance:lowered==="utc"||lowered==="gmt"?FixedOffsetZone.utcInstance:FixedOffsetZone.parseSpecifier(lowered)||IANAZone.create(input)}else return isNumber(input)?FixedOffsetZone.instance(input):typeof input=="object"&&"offset"in input&&typeof input.offset=="function"?input:new InvalidZone(input)}__name(normalizeZone,"normalizeZone"),__name2(normalizeZone,"normalizeZone");let now=__name2(()=>Date.now(),"now"),defaultZone="system",defaultLocale=null,defaultNumberingSystem=null,defaultOutputCalendar=null,twoDigitCutoffYear=60,throwOnInvalid;const _Settings=class{static{__name(this,"_Settings")}static get now(){return now}static set now(n2){now=n2}static set defaultZone(zone){defaultZone=zone}static get defaultZone(){return normalizeZone(defaultZone,SystemZone.instance)}static get defaultLocale(){return defaultLocale}static set defaultLocale(locale){defaultLocale=locale}static get defaultNumberingSystem(){return defaultNumberingSystem}static set defaultNumberingSystem(numberingSystem){defaultNumberingSystem=numberingSystem}static get defaultOutputCalendar(){return defaultOutputCalendar}static set defaultOutputCalendar(outputCalendar){defaultOutputCalendar=outputCalendar}static get twoDigitCutoffYear(){return twoDigitCutoffYear}static set twoDigitCutoffYear(cutoffYear){twoDigitCutoffYear=cutoffYear%100}static get throwOnInvalid(){return throwOnInvalid}static set throwOnInvalid(t2){throwOnInvalid=t2}static resetCaches(){Locale.resetCache(),IANAZone.resetCache()}};__name2(_Settings,"Settings");let Settings=_Settings;function isUndefined(o){return typeof o>"u"}__name(isUndefined,"isUndefined"),__name2(isUndefined,"isUndefined");function isNumber(o){return typeof o=="number"}__name(isNumber,"isNumber"),__name2(isNumber,"isNumber");function isInteger(o){return typeof o=="number"&&o%1===0}__name(isInteger,"isInteger"),__name2(isInteger,"isInteger");function isString(o){return typeof o=="string"}__name(isString,"isString"),__name2(isString,"isString");function isDate(o){return Object.prototype.toString.call(o)==="[object Date]"}__name(isDate,"isDate"),__name2(isDate,"isDate");function hasRelative(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}__name(hasRelative,"hasRelative"),__name2(hasRelative,"hasRelative");function maybeArray(thing){return Array.isArray(thing)?thing:[thing]}__name(maybeArray,"maybeArray"),__name2(maybeArray,"maybeArray");function bestBy(arr,by,compare2){if(arr.length!==0)return arr.reduce((best,next)=>{const pair2=[by(next),next];return best&&compare2(best[0],pair2[0])===best[0]?best:pair2},null)[1]}__name(bestBy,"bestBy"),__name2(bestBy,"bestBy");function pick(obj,keys2){return keys2.reduce((a,k)=>(a[k]=obj[k],a),{})}__name(pick,"pick"),__name2(pick,"pick");function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}__name(hasOwnProperty,"hasOwnProperty"),__name2(hasOwnProperty,"hasOwnProperty");function integerBetween(thing,bottom,top2){return isInteger(thing)&&thing>=bottom&&thing<=top2}__name(integerBetween,"integerBetween"),__name2(integerBetween,"integerBetween");function floorMod(x,n2){return x-n2*Math.floor(x/n2)}__name(floorMod,"floorMod"),__name2(floorMod,"floorMod");function padStart(input,n2=2){const isNeg=input<0;let padded;return isNeg?padded="-"+(""+-input).padStart(n2,"0"):padded=(""+input).padStart(n2,"0"),padded}__name(padStart,"padStart"),__name2(padStart,"padStart");function parseInteger(string2){if(!(isUndefined(string2)||string2===null||string2===""))return parseInt(string2,10)}__name(parseInteger,"parseInteger"),__name2(parseInteger,"parseInteger");function parseFloating(string2){if(!(isUndefined(string2)||string2===null||string2===""))return parseFloat(string2)}__name(parseFloating,"parseFloating"),__name2(parseFloating,"parseFloating");function parseMillis(fraction){if(!(isUndefined(fraction)||fraction===null||fraction==="")){const f=parseFloat("0."+fraction)*1e3;return Math.floor(f)}}__name(parseMillis,"parseMillis"),__name2(parseMillis,"parseMillis");function roundTo(number2,digits,towardZero=!1){const factor=10**digits;return(towardZero?Math.trunc:Math.round)(number2*factor)/factor}__name(roundTo,"roundTo"),__name2(roundTo,"roundTo");function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}__name(isLeapYear,"isLeapYear"),__name2(isLeapYear,"isLeapYear");function daysInYear(year){return isLeapYear(year)?366:365}__name(daysInYear,"daysInYear"),__name2(daysInYear,"daysInYear");function daysInMonth(year,month){const modMonth=floorMod(month-1,12)+1,modYear=year+(month-modMonth)/12;return modMonth===2?isLeapYear(modYear)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][modMonth-1]}__name(daysInMonth,"daysInMonth"),__name2(daysInMonth,"daysInMonth");function objToLocalTS(obj){let d=Date.UTC(obj.year,obj.month-1,obj.day,obj.hour,obj.minute,obj.second,obj.millisecond);return obj.year<100&&obj.year>=0&&(d=new Date(d),d.setUTCFullYear(obj.year,obj.month-1,obj.day)),+d}__name(objToLocalTS,"objToLocalTS"),__name2(objToLocalTS,"objToLocalTS");function weeksInWeekYear(weekYear){const p1=(weekYear+Math.floor(weekYear/4)-Math.floor(weekYear/100)+Math.floor(weekYear/400))%7,last2=weekYear-1,p2=(last2+Math.floor(last2/4)-Math.floor(last2/100)+Math.floor(last2/400))%7;return p1===4||p2===3?53:52}__name(weeksInWeekYear,"weeksInWeekYear"),__name2(weeksInWeekYear,"weeksInWeekYear");function untruncateYear(year){return year>99?year:year>Settings.twoDigitCutoffYear?1900+year:2e3+year}__name(untruncateYear,"untruncateYear"),__name2(untruncateYear,"untruncateYear");function parseZoneInfo(ts,offsetFormat,locale,timeZone=null){const date=new Date(ts),intlOpts={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};timeZone&&(intlOpts.timeZone=timeZone);const modified={timeZoneName:offsetFormat,...intlOpts},parsed=new Intl.DateTimeFormat(locale,modified).formatToParts(date).find(m=>m.type.toLowerCase()==="timezonename");return parsed?parsed.value:null}__name(parseZoneInfo,"parseZoneInfo"),__name2(parseZoneInfo,"parseZoneInfo");function signedOffset(offHourStr,offMinuteStr){let offHour=parseInt(offHourStr,10);Number.isNaN(offHour)&&(offHour=0);const offMin=parseInt(offMinuteStr,10)||0,offMinSigned=offHour<0||Object.is(offHour,-0)?-offMin:offMin;return offHour*60+offMinSigned}__name(signedOffset,"signedOffset"),__name2(signedOffset,"signedOffset");function asNumber(value){const numericValue=Number(value);if(typeof value=="boolean"||value===""||Number.isNaN(numericValue))throw new InvalidArgumentError(`Invalid unit value ${value}`);return numericValue}__name(asNumber,"asNumber"),__name2(asNumber,"asNumber");function normalizeObject(obj,normalizer){const normalized={};for(const u in obj)if(hasOwnProperty(obj,u)){const v=obj[u];if(v==null)continue;normalized[normalizer(u)]=asNumber(v)}return normalized}__name(normalizeObject,"normalizeObject"),__name2(normalizeObject,"normalizeObject");function formatOffset(offset2,format){const hours=Math.trunc(Math.abs(offset2/60)),minutes=Math.trunc(Math.abs(offset2%60)),sign=offset2>=0?"+":"-";switch(format){case"short":return`${sign}${padStart(hours,2)}:${padStart(minutes,2)}`;case"narrow":return`${sign}${hours}${minutes>0?`:${minutes}`:""}`;case"techie":return`${sign}${padStart(hours,2)}${padStart(minutes,2)}`;default:throw new RangeError(`Value format ${format} is out of range for property format`)}}__name(formatOffset,"formatOffset"),__name2(formatOffset,"formatOffset");function timeObject(obj){return pick(obj,["hour","minute","second","millisecond"])}__name(timeObject,"timeObject"),__name2(timeObject,"timeObject");const monthsLong=["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],monthsNarrow=["J","F","M","A","M","J","J","A","S","O","N","D"];function months(length){switch(length){case"narrow":return[...monthsNarrow];case"short":return[...monthsShort];case"long":return[...monthsLong];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}__name(months,"months"),__name2(months,"months");const weekdaysLong=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],weekdaysShort=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],weekdaysNarrow=["M","T","W","T","F","S","S"];function weekdays(length){switch(length){case"narrow":return[...weekdaysNarrow];case"short":return[...weekdaysShort];case"long":return[...weekdaysLong];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}__name(weekdays,"weekdays"),__name2(weekdays,"weekdays");const meridiems=["AM","PM"],erasLong=["Before Christ","Anno Domini"],erasShort=["BC","AD"],erasNarrow=["B","A"];function eras(length){switch(length){case"narrow":return[...erasNarrow];case"short":return[...erasShort];case"long":return[...erasLong];default:return null}}__name(eras,"eras"),__name2(eras,"eras");function meridiemForDateTime(dt){return meridiems[dt.hour<12?0:1]}__name(meridiemForDateTime,"meridiemForDateTime"),__name2(meridiemForDateTime,"meridiemForDateTime");function weekdayForDateTime(dt,length){return weekdays(length)[dt.weekday-1]}__name(weekdayForDateTime,"weekdayForDateTime"),__name2(weekdayForDateTime,"weekdayForDateTime");function monthForDateTime(dt,length){return months(length)[dt.month-1]}__name(monthForDateTime,"monthForDateTime"),__name2(monthForDateTime,"monthForDateTime");function eraForDateTime(dt,length){return eras(length)[dt.year<0?0:1]}__name(eraForDateTime,"eraForDateTime"),__name2(eraForDateTime,"eraForDateTime");function formatRelativeTime(unit,count,numeric="always",narrow=!1){const units={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},lastable=["hours","minutes","seconds"].indexOf(unit)===-1;if(numeric==="auto"&&lastable){const isDay=unit==="days";switch(count){case 1:return isDay?"tomorrow":`next ${units[unit][0]}`;case-1:return isDay?"yesterday":`last ${units[unit][0]}`;case 0:return isDay?"today":`this ${units[unit][0]}`}}const isInPast=Object.is(count,-0)||count<0,fmtValue=Math.abs(count),singular=fmtValue===1,lilUnits=units[unit],fmtUnit=narrow?singular?lilUnits[1]:lilUnits[2]||lilUnits[1]:singular?units[unit][0]:unit;return isInPast?`${fmtValue} ${fmtUnit} ago`:`in ${fmtValue} ${fmtUnit}`}__name(formatRelativeTime,"formatRelativeTime"),__name2(formatRelativeTime,"formatRelativeTime");function stringifyTokens(splits,tokenToString){let s2="";for(const token of splits)token.literal?s2+=token.val:s2+=tokenToString(token.val);return s2}__name(stringifyTokens,"stringifyTokens"),__name2(stringifyTokens,"stringifyTokens");const macroTokenToFormatOpts={D:DATE_SHORT,DD:DATE_MED,DDD:DATE_FULL,DDDD:DATE_HUGE,t:TIME_SIMPLE,tt:TIME_WITH_SECONDS,ttt:TIME_WITH_SHORT_OFFSET,tttt:TIME_WITH_LONG_OFFSET,T:TIME_24_SIMPLE,TT:TIME_24_WITH_SECONDS,TTT:TIME_24_WITH_SHORT_OFFSET,TTTT:TIME_24_WITH_LONG_OFFSET,f:DATETIME_SHORT,ff:DATETIME_MED,fff:DATETIME_FULL,ffff:DATETIME_HUGE,F:DATETIME_SHORT_WITH_SECONDS,FF:DATETIME_MED_WITH_SECONDS,FFF:DATETIME_FULL_WITH_SECONDS,FFFF:DATETIME_HUGE_WITH_SECONDS},_Formatter=class _Formatter2{static{__name(this,"_Formatter")}static create(locale,opts={}){return new _Formatter2(locale,opts)}static parseFormat(fmt){let current=null,currentFull="",bracketed=!1;const splits=[];for(let i=0;i0&&splits.push({literal:bracketed||/^\s+$/.test(currentFull),val:currentFull}),current=null,currentFull="",bracketed=!bracketed):bracketed||c===current?currentFull+=c:(currentFull.length>0&&splits.push({literal:/^\s+$/.test(currentFull),val:currentFull}),currentFull=c,current=c)}return currentFull.length>0&&splits.push({literal:bracketed||/^\s+$/.test(currentFull),val:currentFull}),splits}static macroTokenToFormatOpts(token){return macroTokenToFormatOpts[token]}constructor(locale,formatOpts){this.opts=formatOpts,this.loc=locale,this.systemLoc=null}formatWithSystemDefault(dt,opts){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(dt,{...this.opts,...opts}).format()}dtFormatter(dt,opts={}){return this.loc.dtFormatter(dt,{...this.opts,...opts})}formatDateTime(dt,opts){return this.dtFormatter(dt,opts).format()}formatDateTimeParts(dt,opts){return this.dtFormatter(dt,opts).formatToParts()}formatInterval(interval,opts){return this.dtFormatter(interval.start,opts).dtf.formatRange(interval.start.toJSDate(),interval.end.toJSDate())}resolvedOptions(dt,opts){return this.dtFormatter(dt,opts).resolvedOptions()}num(n2,p=0){if(this.opts.forceSimple)return padStart(n2,p);const opts={...this.opts};return p>0&&(opts.padTo=p),this.loc.numberFormatter(opts).format(n2)}formatDateTimeFromString(dt,fmt){const knownEnglish=this.loc.listingMode()==="en",useDateTimeFormatter=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",string2=__name2((opts,extract)=>this.loc.extract(dt,opts,extract),"string"),formatOffset2=__name2(opts=>dt.isOffsetFixed&&dt.offset===0&&opts.allowZ?"Z":dt.isValid?dt.zone.formatOffset(dt.ts,opts.format):"","formatOffset"),meridiem=__name2(()=>knownEnglish?meridiemForDateTime(dt):string2({hour:"numeric",hourCycle:"h12"},"dayperiod"),"meridiem"),month=__name2((length,standalone)=>knownEnglish?monthForDateTime(dt,length):string2(standalone?{month:length}:{month:length,day:"numeric"},"month"),"month"),weekday=__name2((length,standalone)=>knownEnglish?weekdayForDateTime(dt,length):string2(standalone?{weekday:length}:{weekday:length,month:"long",day:"numeric"},"weekday"),"weekday"),maybeMacro=__name2(token=>{const formatOpts=_Formatter2.macroTokenToFormatOpts(token);return formatOpts?this.formatWithSystemDefault(dt,formatOpts):token},"maybeMacro"),era=__name2(length=>knownEnglish?eraForDateTime(dt,length):string2({era:length},"era"),"era"),tokenToString=__name2(token=>{switch(token){case"S":return this.num(dt.millisecond);case"u":case"SSS":return this.num(dt.millisecond,3);case"s":return this.num(dt.second);case"ss":return this.num(dt.second,2);case"uu":return this.num(Math.floor(dt.millisecond/10),2);case"uuu":return this.num(Math.floor(dt.millisecond/100));case"m":return this.num(dt.minute);case"mm":return this.num(dt.minute,2);case"h":return this.num(dt.hour%12===0?12:dt.hour%12);case"hh":return this.num(dt.hour%12===0?12:dt.hour%12,2);case"H":return this.num(dt.hour);case"HH":return this.num(dt.hour,2);case"Z":return formatOffset2({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return formatOffset2({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return formatOffset2({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return dt.zone.offsetName(dt.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return dt.zone.offsetName(dt.ts,{format:"long",locale:this.loc.locale});case"z":return dt.zoneName;case"a":return meridiem();case"d":return useDateTimeFormatter?string2({day:"numeric"},"day"):this.num(dt.day);case"dd":return useDateTimeFormatter?string2({day:"2-digit"},"day"):this.num(dt.day,2);case"c":return this.num(dt.weekday);case"ccc":return weekday("short",!0);case"cccc":return weekday("long",!0);case"ccccc":return weekday("narrow",!0);case"E":return this.num(dt.weekday);case"EEE":return weekday("short",!1);case"EEEE":return weekday("long",!1);case"EEEEE":return weekday("narrow",!1);case"L":return useDateTimeFormatter?string2({month:"numeric",day:"numeric"},"month"):this.num(dt.month);case"LL":return useDateTimeFormatter?string2({month:"2-digit",day:"numeric"},"month"):this.num(dt.month,2);case"LLL":return month("short",!0);case"LLLL":return month("long",!0);case"LLLLL":return month("narrow",!0);case"M":return useDateTimeFormatter?string2({month:"numeric"},"month"):this.num(dt.month);case"MM":return useDateTimeFormatter?string2({month:"2-digit"},"month"):this.num(dt.month,2);case"MMM":return month("short",!1);case"MMMM":return month("long",!1);case"MMMMM":return month("narrow",!1);case"y":return useDateTimeFormatter?string2({year:"numeric"},"year"):this.num(dt.year);case"yy":return useDateTimeFormatter?string2({year:"2-digit"},"year"):this.num(dt.year.toString().slice(-2),2);case"yyyy":return useDateTimeFormatter?string2({year:"numeric"},"year"):this.num(dt.year,4);case"yyyyyy":return useDateTimeFormatter?string2({year:"numeric"},"year"):this.num(dt.year,6);case"G":return era("short");case"GG":return era("long");case"GGGGG":return era("narrow");case"kk":return this.num(dt.weekYear.toString().slice(-2),2);case"kkkk":return this.num(dt.weekYear,4);case"W":return this.num(dt.weekNumber);case"WW":return this.num(dt.weekNumber,2);case"o":return this.num(dt.ordinal);case"ooo":return this.num(dt.ordinal,3);case"q":return this.num(dt.quarter);case"qq":return this.num(dt.quarter,2);case"X":return this.num(Math.floor(dt.ts/1e3));case"x":return this.num(dt.ts);default:return maybeMacro(token)}},"tokenToString");return stringifyTokens(_Formatter2.parseFormat(fmt),tokenToString)}formatDurationFromString(dur,fmt){const tokenToField=__name2(token=>{switch(token[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},"tokenToField"),tokenToString=__name2(lildur=>token=>{const mapped=tokenToField(token);return mapped?this.num(lildur.get(mapped),token.length):token},"tokenToString"),tokens=_Formatter2.parseFormat(fmt),realTokens=tokens.reduce((found,{literal:literal2,val})=>literal2?found:found.concat(val),[]),collapsed=dur.shiftTo(...realTokens.map(tokenToField).filter(t2=>t2));return stringifyTokens(tokens,tokenToString(collapsed))}};__name2(_Formatter,"Formatter");let Formatter=_Formatter;const _Invalid=class{static{__name(this,"_Invalid")}constructor(reason,explanation){this.reason=reason,this.explanation=explanation}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};__name2(_Invalid,"Invalid");let Invalid=_Invalid;const ianaRegex=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function combineRegexes(...regexes){const full=regexes.reduce((f,r)=>f+r.source,"");return RegExp(`^${full}$`)}__name(combineRegexes,"combineRegexes"),__name2(combineRegexes,"combineRegexes");function combineExtractors(...extractors){return m=>extractors.reduce(([mergedVals,mergedZone,cursor],ex)=>{const[val,zone,next]=ex(m,cursor);return[{...mergedVals,...val},zone||mergedZone,next]},[{},null,1]).slice(0,2)}__name(combineExtractors,"combineExtractors"),__name2(combineExtractors,"combineExtractors");function parse(s2,...patterns){if(s2==null)return[null,null];for(const[regex,extractor]of patterns){const m=regex.exec(s2);if(m)return extractor(m)}return[null,null]}__name(parse,"parse"),__name2(parse,"parse");function simpleParse(...keys2){return(match2,cursor)=>{const ret={};let i;for(i=0;inum!==void 0&&(force||num&&hasNegativePrefix)?-num:num,"maybeNegate");return[{years:maybeNegate(parseFloating(yearStr)),months:maybeNegate(parseFloating(monthStr)),weeks:maybeNegate(parseFloating(weekStr)),days:maybeNegate(parseFloating(dayStr)),hours:maybeNegate(parseFloating(hourStr)),minutes:maybeNegate(parseFloating(minuteStr)),seconds:maybeNegate(parseFloating(secondStr),secondStr==="-0"),milliseconds:maybeNegate(parseMillis(millisecondsStr),negativeSeconds)}]}__name(extractISODuration,"extractISODuration"),__name2(extractISODuration,"extractISODuration");const obsOffsets={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr){const result={year:yearStr.length===2?untruncateYear(parseInteger(yearStr)):parseInteger(yearStr),month:monthsShort.indexOf(monthStr)+1,day:parseInteger(dayStr),hour:parseInteger(hourStr),minute:parseInteger(minuteStr)};return secondStr&&(result.second=parseInteger(secondStr)),weekdayStr&&(result.weekday=weekdayStr.length>3?weekdaysLong.indexOf(weekdayStr)+1:weekdaysShort.indexOf(weekdayStr)+1),result}__name(fromStrings,"fromStrings"),__name2(fromStrings,"fromStrings");const rfc2822=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function extractRFC2822(match2){const[,weekdayStr,dayStr,monthStr,yearStr,hourStr,minuteStr,secondStr,obsOffset,milOffset,offHourStr,offMinuteStr]=match2,result=fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr);let offset2;return obsOffset?offset2=obsOffsets[obsOffset]:milOffset?offset2=0:offset2=signedOffset(offHourStr,offMinuteStr),[result,new FixedOffsetZone(offset2)]}__name(extractRFC2822,"extractRFC2822"),__name2(extractRFC2822,"extractRFC2822");function preprocessRFC2822(s2){return s2.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}__name(preprocessRFC2822,"preprocessRFC2822"),__name2(preprocessRFC2822,"preprocessRFC2822");const rfc1123=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,rfc850=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,ascii=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function extractRFC1123Or850(match2){const[,weekdayStr,dayStr,monthStr,yearStr,hourStr,minuteStr,secondStr]=match2;return[fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr),FixedOffsetZone.utcInstance]}__name(extractRFC1123Or850,"extractRFC1123Or850"),__name2(extractRFC1123Or850,"extractRFC1123Or850");function extractASCII(match2){const[,weekdayStr,monthStr,dayStr,hourStr,minuteStr,secondStr,yearStr]=match2;return[fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr),FixedOffsetZone.utcInstance]}__name(extractASCII,"extractASCII"),__name2(extractASCII,"extractASCII");const isoYmdWithTimeExtensionRegex=combineRegexes(isoYmdRegex,isoTimeExtensionRegex),isoWeekWithTimeExtensionRegex=combineRegexes(isoWeekRegex,isoTimeExtensionRegex),isoOrdinalWithTimeExtensionRegex=combineRegexes(isoOrdinalRegex,isoTimeExtensionRegex),isoTimeCombinedRegex=combineRegexes(isoTimeRegex),extractISOYmdTimeAndOffset=combineExtractors(extractISOYmd,extractISOTime,extractISOOffset,extractIANAZone),extractISOWeekTimeAndOffset=combineExtractors(extractISOWeekData,extractISOTime,extractISOOffset,extractIANAZone),extractISOOrdinalDateAndTime=combineExtractors(extractISOOrdinalData,extractISOTime,extractISOOffset,extractIANAZone),extractISOTimeAndOffset=combineExtractors(extractISOTime,extractISOOffset,extractIANAZone);function parseISODate(s2){return parse(s2,[isoYmdWithTimeExtensionRegex,extractISOYmdTimeAndOffset],[isoWeekWithTimeExtensionRegex,extractISOWeekTimeAndOffset],[isoOrdinalWithTimeExtensionRegex,extractISOOrdinalDateAndTime],[isoTimeCombinedRegex,extractISOTimeAndOffset])}__name(parseISODate,"parseISODate"),__name2(parseISODate,"parseISODate");function parseRFC2822Date(s2){return parse(preprocessRFC2822(s2),[rfc2822,extractRFC2822])}__name(parseRFC2822Date,"parseRFC2822Date"),__name2(parseRFC2822Date,"parseRFC2822Date");function parseHTTPDate(s2){return parse(s2,[rfc1123,extractRFC1123Or850],[rfc850,extractRFC1123Or850],[ascii,extractASCII])}__name(parseHTTPDate,"parseHTTPDate"),__name2(parseHTTPDate,"parseHTTPDate");function parseISODuration(s2){return parse(s2,[isoDuration,extractISODuration])}__name(parseISODuration,"parseISODuration"),__name2(parseISODuration,"parseISODuration");const extractISOTimeOnly=combineExtractors(extractISOTime);function parseISOTimeOnly(s2){return parse(s2,[isoTimeOnly,extractISOTimeOnly])}__name(parseISOTimeOnly,"parseISOTimeOnly"),__name2(parseISOTimeOnly,"parseISOTimeOnly");const sqlYmdWithTimeExtensionRegex=combineRegexes(sqlYmdRegex,sqlTimeExtensionRegex),sqlTimeCombinedRegex=combineRegexes(sqlTimeRegex),extractISOTimeOffsetAndIANAZone=combineExtractors(extractISOTime,extractISOOffset,extractIANAZone);function parseSQL(s2){return parse(s2,[sqlYmdWithTimeExtensionRegex,extractISOYmdTimeAndOffset],[sqlTimeCombinedRegex,extractISOTimeOffsetAndIANAZone])}__name(parseSQL,"parseSQL"),__name2(parseSQL,"parseSQL");const INVALID$2="Invalid Duration",lowOrderMatrix={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},casualMatrix={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...lowOrderMatrix},daysInYearAccurate=146097/400,daysInMonthAccurate=146097/4800,accurateMatrix={years:{quarters:4,months:12,weeks:daysInYearAccurate/7,days:daysInYearAccurate,hours:daysInYearAccurate*24,minutes:daysInYearAccurate*24*60,seconds:daysInYearAccurate*24*60*60,milliseconds:daysInYearAccurate*24*60*60*1e3},quarters:{months:3,weeks:daysInYearAccurate/28,days:daysInYearAccurate/4,hours:daysInYearAccurate*24/4,minutes:daysInYearAccurate*24*60/4,seconds:daysInYearAccurate*24*60*60/4,milliseconds:daysInYearAccurate*24*60*60*1e3/4},months:{weeks:daysInMonthAccurate/7,days:daysInMonthAccurate,hours:daysInMonthAccurate*24,minutes:daysInMonthAccurate*24*60,seconds:daysInMonthAccurate*24*60*60,milliseconds:daysInMonthAccurate*24*60*60*1e3},...lowOrderMatrix},orderedUnits$1=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],reverseUnits=orderedUnits$1.slice(0).reverse();function clone$1(dur,alts,clear=!1){const conf={values:clear?alts.values:{...dur.values,...alts.values||{}},loc:dur.loc.clone(alts.loc),conversionAccuracy:alts.conversionAccuracy||dur.conversionAccuracy,matrix:alts.matrix||dur.matrix};return new Duration(conf)}__name(clone$1,"clone$1"),__name2(clone$1,"clone$1");function durationToMillis(matrix2,vals){let sum=vals.milliseconds??0;for(const unit of reverseUnits.slice(1))vals[unit]&&(sum+=vals[unit]*matrix2[unit].milliseconds);return sum}__name(durationToMillis,"durationToMillis"),__name2(durationToMillis,"durationToMillis");function normalizeValues(matrix2,vals){const factor=durationToMillis(matrix2,vals)<0?-1:1;orderedUnits$1.reduceRight((previous,current)=>{if(isUndefined(vals[current]))return previous;if(previous){const previousVal=vals[previous]*factor,conv=matrix2[current][previous],rollUp=Math.floor(previousVal/conv);vals[current]+=rollUp*factor,vals[previous]-=rollUp*conv*factor}return current},null),orderedUnits$1.reduce((previous,current)=>{if(isUndefined(vals[current]))return previous;if(previous){const fraction=vals[previous]%1;vals[previous]-=fraction,vals[current]+=fraction*matrix2[previous][current]}return current},null)}__name(normalizeValues,"normalizeValues"),__name2(normalizeValues,"normalizeValues");function removeZeroes(vals){const newVals={};for(const[key,value]of Object.entries(vals))value!==0&&(newVals[key]=value);return newVals}__name(removeZeroes,"removeZeroes"),__name2(removeZeroes,"removeZeroes");const _Duration=class _Duration2{static{__name(this,"_Duration")}constructor(config2){const accurate=config2.conversionAccuracy==="longterm"||!1;let matrix2=accurate?accurateMatrix:casualMatrix;config2.matrix&&(matrix2=config2.matrix),this.values=config2.values,this.loc=config2.loc||Locale.create(),this.conversionAccuracy=accurate?"longterm":"casual",this.invalid=config2.invalid||null,this.matrix=matrix2,this.isLuxonDuration=!0}static fromMillis(count,opts){return _Duration2.fromObject({milliseconds:count},opts)}static fromObject(obj,opts={}){if(obj==null||typeof obj!="object")throw new InvalidArgumentError(`Duration.fromObject: argument expected to be an object, got ${obj===null?"null":typeof obj}`);return new _Duration2({values:normalizeObject(obj,_Duration2.normalizeUnit),loc:Locale.fromObject(opts),conversionAccuracy:opts.conversionAccuracy,matrix:opts.matrix})}static fromDurationLike(durationLike){if(isNumber(durationLike))return _Duration2.fromMillis(durationLike);if(_Duration2.isDuration(durationLike))return durationLike;if(typeof durationLike=="object")return _Duration2.fromObject(durationLike);throw new InvalidArgumentError(`Unknown duration argument ${durationLike} of type ${typeof durationLike}`)}static fromISO(text,opts){const[parsed]=parseISODuration(text);return parsed?_Duration2.fromObject(parsed,opts):_Duration2.invalid("unparsable",`the input "${text}" can't be parsed as ISO 8601`)}static fromISOTime(text,opts){const[parsed]=parseISOTimeOnly(text);return parsed?_Duration2.fromObject(parsed,opts):_Duration2.invalid("unparsable",`the input "${text}" can't be parsed as ISO 8601`)}static invalid(reason,explanation=null){if(!reason)throw new InvalidArgumentError("need to specify a reason the Duration is invalid");const invalid=reason instanceof Invalid?reason:new Invalid(reason,explanation);if(Settings.throwOnInvalid)throw new InvalidDurationError(invalid);return new _Duration2({invalid})}static normalizeUnit(unit){const normalized={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[unit&&unit.toLowerCase()];if(!normalized)throw new InvalidUnitError(unit);return normalized}static isDuration(o){return o&&o.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(fmt,opts={}){const fmtOpts={...opts,floor:opts.round!==!1&&opts.floor!==!1};return this.isValid?Formatter.create(this.loc,fmtOpts).formatDurationFromString(this,fmt):INVALID$2}toHuman(opts={}){if(!this.isValid)return INVALID$2;const l2=orderedUnits$1.map(unit=>{const val=this.values[unit];return isUndefined(val)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...opts,unit:unit.slice(0,-1)}).format(val)}).filter(n2=>n2);return this.loc.listFormatter({type:"conjunction",style:opts.listStyle||"narrow",...opts}).format(l2)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let s2="P";return this.years!==0&&(s2+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(s2+=this.months+this.quarters*3+"M"),this.weeks!==0&&(s2+=this.weeks+"W"),this.days!==0&&(s2+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(s2+="T"),this.hours!==0&&(s2+=this.hours+"H"),this.minutes!==0&&(s2+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(s2+=roundTo(this.seconds+this.milliseconds/1e3,3)+"S"),s2==="P"&&(s2+="T0S"),s2}toISOTime(opts={}){if(!this.isValid)return null;const millis=this.toMillis();return millis<0||millis>=864e5?null:(opts={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...opts,includeOffset:!1},DateTime.fromMillis(millis,{zone:"UTC"}).toISOTime(opts))}toJSON(){return this.toISO()}toString(){return this.toISO()}toMillis(){return this.isValid?durationToMillis(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(duration){if(!this.isValid)return this;const dur=_Duration2.fromDurationLike(duration),result={};for(const k of orderedUnits$1)(hasOwnProperty(dur.values,k)||hasOwnProperty(this.values,k))&&(result[k]=dur.get(k)+this.get(k));return clone$1(this,{values:result},!0)}minus(duration){if(!this.isValid)return this;const dur=_Duration2.fromDurationLike(duration);return this.plus(dur.negate())}mapUnits(fn){if(!this.isValid)return this;const result={};for(const k of Object.keys(this.values))result[k]=asNumber(fn(this.values[k],k));return clone$1(this,{values:result},!0)}get(unit){return this[_Duration2.normalizeUnit(unit)]}set(values){if(!this.isValid)return this;const mixed={...this.values,...normalizeObject(values,_Duration2.normalizeUnit)};return clone$1(this,{values:mixed})}reconfigure({locale,numberingSystem,conversionAccuracy,matrix:matrix2}={}){const opts={loc:this.loc.clone({locale,numberingSystem}),matrix:matrix2,conversionAccuracy};return clone$1(this,opts)}as(unit){return this.isValid?this.shiftTo(unit).get(unit):NaN}normalize(){if(!this.isValid)return this;const vals=this.toObject();return normalizeValues(this.matrix,vals),clone$1(this,{values:vals},!0)}rescale(){if(!this.isValid)return this;const vals=removeZeroes(this.normalize().shiftToAll().toObject());return clone$1(this,{values:vals},!0)}shiftTo(...units){if(!this.isValid)return this;if(units.length===0)return this;units=units.map(u=>_Duration2.normalizeUnit(u));const built={},accumulated={},vals=this.toObject();let lastUnit;for(const k of orderedUnits$1)if(units.indexOf(k)>=0){lastUnit=k;let own=0;for(const ak in accumulated)own+=this.matrix[ak][k]*accumulated[ak],accumulated[ak]=0;isNumber(vals[k])&&(own+=vals[k]);const i=Math.trunc(own);built[k]=i,accumulated[k]=(own*1e3-i*1e3)/1e3}else isNumber(vals[k])&&(accumulated[k]=vals[k]);for(const key in accumulated)accumulated[key]!==0&&(built[lastUnit]+=key===lastUnit?accumulated[key]:accumulated[key]/this.matrix[lastUnit][key]);return normalizeValues(this.matrix,built),clone$1(this,{values:built},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const negated={};for(const k of Object.keys(this.values))negated[k]=this.values[k]===0?0:-this.values[k];return clone$1(this,{values:negated},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(other){if(!this.isValid||!other.isValid||!this.loc.equals(other.loc))return!1;function eq(v1,v2){return v1===void 0||v1===0?v2===void 0||v2===0:v1===v2}__name(eq,"eq"),__name2(eq,"eq");for(const u of orderedUnits$1)if(!eq(this.values[u],other.values[u]))return!1;return!0}};__name2(_Duration,"Duration");let Duration=_Duration;const INVALID$1="Invalid Interval";function validateStartEnd(start,end){return!start||!start.isValid?Interval.invalid("missing or invalid start"):!end||!end.isValid?Interval.invalid("missing or invalid end"):enddateTime:!1}isBefore(dateTime){return this.isValid?this.e<=dateTime:!1}contains(dateTime){return this.isValid?this.s<=dateTime&&this.e>dateTime:!1}set({start,end}={}){return this.isValid?_Interval2.fromDateTimes(start||this.s,end||this.e):this}splitAt(...dateTimes){if(!this.isValid)return[];const sorted=dateTimes.map(friendlyDateTime).filter(d=>this.contains(d)).sort(),results=[];let{s:s2}=this,i=0;for(;s2+this.e?this.e:added;results.push(_Interval2.fromDateTimes(s2,next)),s2=next,i+=1}return results}splitBy(duration){const dur=Duration.fromDurationLike(duration);if(!this.isValid||!dur.isValid||dur.as("milliseconds")===0)return[];let{s:s2}=this,idx=1,next;const results=[];for(;s2x*idx));next=+added>+this.e?this.e:added,results.push(_Interval2.fromDateTimes(s2,next)),s2=next,idx+=1}return results}divideEqually(numberOfParts){return this.isValid?this.splitBy(this.length()/numberOfParts).slice(0,numberOfParts):[]}overlaps(other){return this.e>other.s&&this.s=other.e:!1}equals(other){return!this.isValid||!other.isValid?!1:this.s.equals(other.s)&&this.e.equals(other.e)}intersection(other){if(!this.isValid)return this;const s2=this.s>other.s?this.s:other.s,e=this.e=e?null:_Interval2.fromDateTimes(s2,e)}union(other){if(!this.isValid)return this;const s2=this.sother.e?this.e:other.e;return _Interval2.fromDateTimes(s2,e)}static merge(intervals){const[found,final]=intervals.sort((a,b)=>a.s-b.s).reduce(([sofar,current],item)=>current?current.overlaps(item)||current.abutsStart(item)?[sofar,current.union(item)]:[sofar.concat([current]),item]:[sofar,item],[[],null]);return final&&found.push(final),found}static xor(intervals){let start=null,currentCount=0;const results=[],ends=intervals.map(i=>[{time:i.s,type:"s"},{time:i.e,type:"e"}]),flattened2=Array.prototype.concat(...ends),arr=flattened2.sort((a,b)=>a.time-b.time);for(const i of arr)currentCount+=i.type==="s"?1:-1,currentCount===1?start=i.time:(start&&+start!=+i.time&&results.push(_Interval2.fromDateTimes(start,i.time)),start=null);return _Interval2.merge(results)}difference(...intervals){return _Interval2.xor([this].concat(intervals)).map(i=>this.intersection(i)).filter(i=>i&&!i.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:INVALID$1}toLocaleString(formatOpts=DATE_SHORT,opts={}){return this.isValid?Formatter.create(this.s.loc.clone(opts),formatOpts).formatInterval(this):INVALID$1}toISO(opts){return this.isValid?`${this.s.toISO(opts)}/${this.e.toISO(opts)}`:INVALID$1}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:INVALID$1}toISOTime(opts){return this.isValid?`${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`:INVALID$1}toFormat(dateFormat,{separator=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`:INVALID$1}toDuration(unit,opts){return this.isValid?this.e.diff(this.s,unit,opts):Duration.invalid(this.invalidReason)}mapEndpoints(mapFn){return _Interval2.fromDateTimes(mapFn(this.s),mapFn(this.e))}};__name2(_Interval,"Interval");let Interval=_Interval;const _Info=class{static{__name(this,"_Info")}static hasDST(zone=Settings.defaultZone){const proto=DateTime.now().setZone(zone).set({month:12});return!zone.isUniversal&&proto.offset!==proto.set({month:6}).offset}static isValidIANAZone(zone){return IANAZone.isValidZone(zone)}static normalizeZone(input){return normalizeZone(input,Settings.defaultZone)}static months(length="long",{locale=null,numberingSystem=null,locObj=null,outputCalendar="gregory"}={}){return(locObj||Locale.create(locale,numberingSystem,outputCalendar)).months(length)}static monthsFormat(length="long",{locale=null,numberingSystem=null,locObj=null,outputCalendar="gregory"}={}){return(locObj||Locale.create(locale,numberingSystem,outputCalendar)).months(length,!0)}static weekdays(length="long",{locale=null,numberingSystem=null,locObj=null}={}){return(locObj||Locale.create(locale,numberingSystem,null)).weekdays(length)}static weekdaysFormat(length="long",{locale=null,numberingSystem=null,locObj=null}={}){return(locObj||Locale.create(locale,numberingSystem,null)).weekdays(length,!0)}static meridiems({locale=null}={}){return Locale.create(locale).meridiems()}static eras(length="short",{locale=null}={}){return Locale.create(locale,null,"gregory").eras(length)}static features(){return{relative:hasRelative()}}};__name2(_Info,"Info");let Info=_Info;function dayDiff(earlier,later){const utcDayStart=__name2(dt=>dt.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),"utcDayStart"),ms=utcDayStart(later)-utcDayStart(earlier);return Math.floor(Duration.fromMillis(ms).as("days"))}__name(dayDiff,"dayDiff"),__name2(dayDiff,"dayDiff");function highOrderDiffs(cursor,later,units){const differs=[["years",(a,b)=>b.year-a.year],["quarters",(a,b)=>b.quarter-a.quarter+(b.year-a.year)*4],["months",(a,b)=>b.month-a.month+(b.year-a.year)*12],["weeks",(a,b)=>{const days=dayDiff(a,b);return(days-days%7)/7}],["days",dayDiff]],results={},earlier=cursor;let lowestOrder,highWater;for(const[unit,differ]of differs)units.indexOf(unit)>=0&&(lowestOrder=unit,results[unit]=differ(cursor,later),highWater=earlier.plus(results),highWater>later?(results[unit]--,cursor=earlier.plus(results),cursor>later&&(highWater=cursor,results[unit]--,cursor=earlier.plus(results))):cursor=highWater);return[cursor,results,highWater,lowestOrder]}__name(highOrderDiffs,"highOrderDiffs"),__name2(highOrderDiffs,"highOrderDiffs");function diff(earlier,later,units,opts){let[cursor,results,highWater,lowestOrder]=highOrderDiffs(earlier,later,units);const remainingMillis=later-cursor,lowerOrderUnits=units.filter(u=>["hours","minutes","seconds","milliseconds"].indexOf(u)>=0);lowerOrderUnits.length===0&&(highWater0?Duration.fromMillis(remainingMillis,opts).shiftTo(...lowerOrderUnits).plus(duration):duration}__name(diff,"diff"),__name2(diff,"diff");const numberingSystems={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},numberingSystemsUTF16={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},hanidecChars=numberingSystems.hanidec.replace(/[\[|\]]/g,"").split("");function parseDigits(str){let value=parseInt(str,10);if(isNaN(value)){value="";for(let i=0;i=min&&code<=max&&(value+=code-min)}}return parseInt(value,10)}else return value}__name(parseDigits,"parseDigits"),__name2(parseDigits,"parseDigits");function digitRegex({numberingSystem},append=""){return new RegExp(`${numberingSystems[numberingSystem||"latn"]}${append}`)}__name(digitRegex,"digitRegex"),__name2(digitRegex,"digitRegex");const MISSING_FTP="missing Intl.DateTimeFormat.formatToParts support";function intUnit(regex,post=i=>i){return{regex,deser:([s2])=>post(parseDigits(s2))}}__name(intUnit,"intUnit"),__name2(intUnit,"intUnit");const NBSP=String.fromCharCode(160),spaceOrNBSP=`[ ${NBSP}]`,spaceOrNBSPRegExp=new RegExp(spaceOrNBSP,"g");function fixListRegex(s2){return s2.replace(/\./g,"\\.?").replace(spaceOrNBSPRegExp,spaceOrNBSP)}__name(fixListRegex,"fixListRegex"),__name2(fixListRegex,"fixListRegex");function stripInsensitivities(s2){return s2.replace(/\./g,"").replace(spaceOrNBSPRegExp," ").toLowerCase()}__name(stripInsensitivities,"stripInsensitivities"),__name2(stripInsensitivities,"stripInsensitivities");function oneOf(strings,startIndex){return strings===null?null:{regex:RegExp(strings.map(fixListRegex).join("|")),deser:([s2])=>strings.findIndex(i=>stripInsensitivities(s2)===stripInsensitivities(i))+startIndex}}__name(oneOf,"oneOf"),__name2(oneOf,"oneOf");function offset$1(regex,groups){return{regex,deser:([,h,m])=>signedOffset(h,m),groups}}__name(offset$1,"offset$1"),__name2(offset$1,"offset$1");function simple(regex){return{regex,deser:([s2])=>s2}}__name(simple,"simple"),__name2(simple,"simple");function escapeToken(value){return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}__name(escapeToken,"escapeToken"),__name2(escapeToken,"escapeToken");function unitForToken(token,loc){const one=digitRegex(loc),two=digitRegex(loc,"{2}"),three=digitRegex(loc,"{3}"),four=digitRegex(loc,"{4}"),six=digitRegex(loc,"{6}"),oneOrTwo=digitRegex(loc,"{1,2}"),oneToThree=digitRegex(loc,"{1,3}"),oneToSix=digitRegex(loc,"{1,6}"),oneToNine=digitRegex(loc,"{1,9}"),twoToFour=digitRegex(loc,"{2,4}"),fourToSix=digitRegex(loc,"{4,6}"),literal2=__name2(t2=>({regex:RegExp(escapeToken(t2.val)),deser:([s2])=>s2,literal:!0}),"literal"),unit=__name2(t2=>{if(token.literal)return literal2(t2);switch(t2.val){case"G":return oneOf(loc.eras("short"),0);case"GG":return oneOf(loc.eras("long"),0);case"y":return intUnit(oneToSix);case"yy":return intUnit(twoToFour,untruncateYear);case"yyyy":return intUnit(four);case"yyyyy":return intUnit(fourToSix);case"yyyyyy":return intUnit(six);case"M":return intUnit(oneOrTwo);case"MM":return intUnit(two);case"MMM":return oneOf(loc.months("short",!0),1);case"MMMM":return oneOf(loc.months("long",!0),1);case"L":return intUnit(oneOrTwo);case"LL":return intUnit(two);case"LLL":return oneOf(loc.months("short",!1),1);case"LLLL":return oneOf(loc.months("long",!1),1);case"d":return intUnit(oneOrTwo);case"dd":return intUnit(two);case"o":return intUnit(oneToThree);case"ooo":return intUnit(three);case"HH":return intUnit(two);case"H":return intUnit(oneOrTwo);case"hh":return intUnit(two);case"h":return intUnit(oneOrTwo);case"mm":return intUnit(two);case"m":return intUnit(oneOrTwo);case"q":return intUnit(oneOrTwo);case"qq":return intUnit(two);case"s":return intUnit(oneOrTwo);case"ss":return intUnit(two);case"S":return intUnit(oneToThree);case"SSS":return intUnit(three);case"u":return simple(oneToNine);case"uu":return simple(oneOrTwo);case"uuu":return intUnit(one);case"a":return oneOf(loc.meridiems(),0);case"kkkk":return intUnit(four);case"kk":return intUnit(twoToFour,untruncateYear);case"W":return intUnit(oneOrTwo);case"WW":return intUnit(two);case"E":case"c":return intUnit(one);case"EEE":return oneOf(loc.weekdays("short",!1),1);case"EEEE":return oneOf(loc.weekdays("long",!1),1);case"ccc":return oneOf(loc.weekdays("short",!0),1);case"cccc":return oneOf(loc.weekdays("long",!0),1);case"Z":case"ZZ":return offset$1(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`),2);case"ZZZ":return offset$1(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`),2);case"z":return simple(/[a-z_+-/]{1,256}?/i);case" ":return simple(/[^\S\n\r]/);default:return literal2(t2)}},"unitate")(token)||{invalidReason:MISSING_FTP};return unit.token=token,unit}__name(unitForToken,"unitForToken"),__name2(unitForToken,"unitForToken");const partTypeStyleToTokenVal={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function tokenForPart(part,formatOpts,resolvedOpts){const{type,value}=part;if(type==="literal"){const isSpace=/^\s+$/.test(value);return{literal:!isSpace,val:isSpace?" ":value}}const style=formatOpts[type];let actualType=type;type==="hour"&&(formatOpts.hour12!=null?actualType=formatOpts.hour12?"hour12":"hour24":formatOpts.hourCycle!=null?formatOpts.hourCycle==="h11"||formatOpts.hourCycle==="h12"?actualType="hour12":actualType="hour24":actualType=resolvedOpts.hour12?"hour12":"hour24");let val=partTypeStyleToTokenVal[actualType];if(typeof val=="object"&&(val=val[style]),val)return{literal:!1,val}}__name(tokenForPart,"tokenForPart"),__name2(tokenForPart,"tokenForPart");function buildRegex(units){return[`^${units.map(u=>u.regex).reduce((f,r)=>`${f}(${r.source})`,"")}$`,units]}__name(buildRegex,"buildRegex"),__name2(buildRegex,"buildRegex");function match(input,regex,handlers2){const matches2=input.match(regex);if(matches2){const all={};let matchIndex=1;for(const i in handlers2)if(hasOwnProperty(handlers2,i)){const h=handlers2[i],groups=h.groups?h.groups+1:1;!h.literal&&h.token&&(all[h.token.val[0]]=h.deser(matches2.slice(matchIndex,matchIndex+groups))),matchIndex+=groups}return[matches2,all]}else return[matches2,{}]}__name(match,"match"),__name2(match,"match");function dateTimeFromMatches(matches2){const toField=__name2(token=>{switch(token){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},"toField");let zone=null,specificOffset;return isUndefined(matches2.z)||(zone=IANAZone.create(matches2.z)),isUndefined(matches2.Z)||(zone||(zone=new FixedOffsetZone(matches2.Z)),specificOffset=matches2.Z),isUndefined(matches2.q)||(matches2.M=(matches2.q-1)*3+1),isUndefined(matches2.h)||(matches2.h<12&&matches2.a===1?matches2.h+=12:matches2.h===12&&matches2.a===0&&(matches2.h=0)),matches2.G===0&&matches2.y&&(matches2.y=-matches2.y),isUndefined(matches2.u)||(matches2.S=parseMillis(matches2.u)),[Object.keys(matches2).reduce((r,k)=>{const f=toField(k);return f&&(r[f]=matches2[k]),r},{}),zone,specificOffset]}__name(dateTimeFromMatches,"dateTimeFromMatches"),__name2(dateTimeFromMatches,"dateTimeFromMatches");let dummyDateTimeCache=null;function getDummyDateTime(){return dummyDateTimeCache||(dummyDateTimeCache=DateTime.fromMillis(1555555555555)),dummyDateTimeCache}__name(getDummyDateTime,"getDummyDateTime"),__name2(getDummyDateTime,"getDummyDateTime");function maybeExpandMacroToken(token,locale){if(token.literal)return token;const formatOpts=Formatter.macroTokenToFormatOpts(token.val),tokens=formatOptsToTokens(formatOpts,locale);return tokens==null||tokens.includes(void 0)?token:tokens}__name(maybeExpandMacroToken,"maybeExpandMacroToken"),__name2(maybeExpandMacroToken,"maybeExpandMacroToken");function expandMacroTokens(tokens,locale){return Array.prototype.concat(...tokens.map(t2=>maybeExpandMacroToken(t2,locale)))}__name(expandMacroTokens,"expandMacroTokens"),__name2(expandMacroTokens,"expandMacroTokens");function explainFromTokens(locale,input,format){const tokens=expandMacroTokens(Formatter.parseFormat(format),locale),units=tokens.map(t2=>unitForToken(t2,locale)),disqualifyingUnit=units.find(t2=>t2.invalidReason);if(disqualifyingUnit)return{input,tokens,invalidReason:disqualifyingUnit.invalidReason};{const[regexString,handlers2]=buildRegex(units),regex=RegExp(regexString,"i"),[rawMatches,matches2]=match(input,regex,handlers2),[result,zone,specificOffset]=matches2?dateTimeFromMatches(matches2):[null,null,void 0];if(hasOwnProperty(matches2,"a")&&hasOwnProperty(matches2,"H"))throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format");return{input,tokens,regex,rawMatches,matches:matches2,result,zone,specificOffset}}}__name(explainFromTokens,"explainFromTokens"),__name2(explainFromTokens,"explainFromTokens");function parseFromTokens(locale,input,format){const{result,zone,specificOffset,invalidReason}=explainFromTokens(locale,input,format);return[result,zone,specificOffset,invalidReason]}__name(parseFromTokens,"parseFromTokens"),__name2(parseFromTokens,"parseFromTokens");function formatOptsToTokens(formatOpts,locale){if(!formatOpts)return null;const df=Formatter.create(locale,formatOpts).dtFormatter(getDummyDateTime()),parts=df.formatToParts(),resolvedOpts=df.resolvedOptions();return parts.map(p=>tokenForPart(p,formatOpts,resolvedOpts))}__name(formatOptsToTokens,"formatOptsToTokens"),__name2(formatOptsToTokens,"formatOptsToTokens");const nonLeapLadder=[0,31,59,90,120,151,181,212,243,273,304,334],leapLadder=[0,31,60,91,121,152,182,213,244,274,305,335];function unitOutOfRange(unit,value){return new Invalid("unit out of range",`you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`)}__name(unitOutOfRange,"unitOutOfRange"),__name2(unitOutOfRange,"unitOutOfRange");function dayOfWeek(year,month,day){const d=new Date(Date.UTC(year,month-1,day));year<100&&year>=0&&d.setUTCFullYear(d.getUTCFullYear()-1900);const js=d.getUTCDay();return js===0?7:js}__name(dayOfWeek,"dayOfWeek"),__name2(dayOfWeek,"dayOfWeek");function computeOrdinal(year,month,day){return day+(isLeapYear(year)?leapLadder:nonLeapLadder)[month-1]}__name(computeOrdinal,"computeOrdinal"),__name2(computeOrdinal,"computeOrdinal");function uncomputeOrdinal(year,ordinal){const table=isLeapYear(year)?leapLadder:nonLeapLadder,month0=table.findIndex(i=>iweeksInWeekYear(year)?(weekYear=year+1,weekNumber=1):weekYear=year,{weekYear,weekNumber,weekday,...timeObject(gregObj)}}__name(gregorianToWeek,"gregorianToWeek"),__name2(gregorianToWeek,"gregorianToWeek");function weekToGregorian(weekData){const{weekYear,weekNumber,weekday}=weekData,weekdayOfJan4=dayOfWeek(weekYear,1,4),yearInDays=daysInYear(weekYear);let ordinal=weekNumber*7+weekday-weekdayOfJan4-3,year;ordinal<1?(year=weekYear-1,ordinal+=daysInYear(year)):ordinal>yearInDays?(year=weekYear+1,ordinal-=daysInYear(weekYear)):year=weekYear;const{month,day}=uncomputeOrdinal(year,ordinal);return{year,month,day,...timeObject(weekData)}}__name(weekToGregorian,"weekToGregorian"),__name2(weekToGregorian,"weekToGregorian");function gregorianToOrdinal(gregData){const{year,month,day}=gregData,ordinal=computeOrdinal(year,month,day);return{year,ordinal,...timeObject(gregData)}}__name(gregorianToOrdinal,"gregorianToOrdinal"),__name2(gregorianToOrdinal,"gregorianToOrdinal");function ordinalToGregorian(ordinalData){const{year,ordinal}=ordinalData,{month,day}=uncomputeOrdinal(year,ordinal);return{year,month,day,...timeObject(ordinalData)}}__name(ordinalToGregorian,"ordinalToGregorian"),__name2(ordinalToGregorian,"ordinalToGregorian");function hasInvalidWeekData(obj){const validYear=isInteger(obj.weekYear),validWeek=integerBetween(obj.weekNumber,1,weeksInWeekYear(obj.weekYear)),validWeekday=integerBetween(obj.weekday,1,7);return validYear?validWeek?validWeekday?!1:unitOutOfRange("weekday",obj.weekday):unitOutOfRange("week",obj.week):unitOutOfRange("weekYear",obj.weekYear)}__name(hasInvalidWeekData,"hasInvalidWeekData"),__name2(hasInvalidWeekData,"hasInvalidWeekData");function hasInvalidOrdinalData(obj){const validYear=isInteger(obj.year),validOrdinal=integerBetween(obj.ordinal,1,daysInYear(obj.year));return validYear?validOrdinal?!1:unitOutOfRange("ordinal",obj.ordinal):unitOutOfRange("year",obj.year)}__name(hasInvalidOrdinalData,"hasInvalidOrdinalData"),__name2(hasInvalidOrdinalData,"hasInvalidOrdinalData");function hasInvalidGregorianData(obj){const validYear=isInteger(obj.year),validMonth=integerBetween(obj.month,1,12),validDay=integerBetween(obj.day,1,daysInMonth(obj.year,obj.month));return validYear?validMonth?validDay?!1:unitOutOfRange("day",obj.day):unitOutOfRange("month",obj.month):unitOutOfRange("year",obj.year)}__name(hasInvalidGregorianData,"hasInvalidGregorianData"),__name2(hasInvalidGregorianData,"hasInvalidGregorianData");function hasInvalidTimeData(obj){const{hour,minute,second,millisecond}=obj,validHour=integerBetween(hour,0,23)||hour===24&&minute===0&&second===0&&millisecond===0,validMinute=integerBetween(minute,0,59),validSecond=integerBetween(second,0,59),validMillisecond=integerBetween(millisecond,0,999);return validHour?validMinute?validSecond?validMillisecond?!1:unitOutOfRange("millisecond",millisecond):unitOutOfRange("second",second):unitOutOfRange("minute",minute):unitOutOfRange("hour",hour)}__name(hasInvalidTimeData,"hasInvalidTimeData"),__name2(hasInvalidTimeData,"hasInvalidTimeData");const INVALID="Invalid DateTime",MAX_DATE=864e13;function unsupportedZone(zone){return new Invalid("unsupported zone",`the zone "${zone.name}" is not supported`)}__name(unsupportedZone,"unsupportedZone"),__name2(unsupportedZone,"unsupportedZone");function possiblyCachedWeekData(dt){return dt.weekData===null&&(dt.weekData=gregorianToWeek(dt.c)),dt.weekData}__name(possiblyCachedWeekData,"possiblyCachedWeekData"),__name2(possiblyCachedWeekData,"possiblyCachedWeekData");function clone(inst,alts){const current={ts:inst.ts,zone:inst.zone,c:inst.c,o:inst.o,loc:inst.loc,invalid:inst.invalid};return new DateTime({...current,...alts,old:current})}__name(clone,"clone"),__name2(clone,"clone");function fixOffset(localTS,o,tz){let utcGuess=localTS-o*60*1e3;const o2=tz.offset(utcGuess);if(o===o2)return[utcGuess,o];utcGuess-=(o2-o)*60*1e3;const o3=tz.offset(utcGuess);return o2===o3?[utcGuess,o2]:[localTS-Math.min(o2,o3)*60*1e3,Math.max(o2,o3)]}__name(fixOffset,"fixOffset"),__name2(fixOffset,"fixOffset");function tsToObj(ts,offset2){ts+=offset2*60*1e3;const d=new Date(ts);return{year:d.getUTCFullYear(),month:d.getUTCMonth()+1,day:d.getUTCDate(),hour:d.getUTCHours(),minute:d.getUTCMinutes(),second:d.getUTCSeconds(),millisecond:d.getUTCMilliseconds()}}__name(tsToObj,"tsToObj"),__name2(tsToObj,"tsToObj");function objToTS(obj,offset2,zone){return fixOffset(objToLocalTS(obj),offset2,zone)}__name(objToTS,"objToTS"),__name2(objToTS,"objToTS");function adjustTime(inst,dur){const oPre=inst.o,year=inst.c.year+Math.trunc(dur.years),month=inst.c.month+Math.trunc(dur.months)+Math.trunc(dur.quarters)*3,c={...inst.c,year,month,day:Math.min(inst.c.day,daysInMonth(year,month))+Math.trunc(dur.days)+Math.trunc(dur.weeks)*7},millisToAdd=Duration.fromObject({years:dur.years-Math.trunc(dur.years),quarters:dur.quarters-Math.trunc(dur.quarters),months:dur.months-Math.trunc(dur.months),weeks:dur.weeks-Math.trunc(dur.weeks),days:dur.days-Math.trunc(dur.days),hours:dur.hours,minutes:dur.minutes,seconds:dur.seconds,milliseconds:dur.milliseconds}).as("milliseconds"),localTS=objToLocalTS(c);let[ts,o]=fixOffset(localTS,oPre,inst.zone);return millisToAdd!==0&&(ts+=millisToAdd,o=inst.zone.offset(ts)),{ts,o}}__name(adjustTime,"adjustTime"),__name2(adjustTime,"adjustTime");function parseDataToDateTime(parsed,parsedZone,opts,format,text,specificOffset){const{setZone,zone}=opts;if(parsed&&Object.keys(parsed).length!==0||parsedZone){const interpretationZone=parsedZone||zone,inst=DateTime.fromObject(parsed,{...opts,zone:interpretationZone,specificOffset});return setZone?inst:inst.setZone(zone)}else return DateTime.invalid(new Invalid("unparsable",`the input "${text}" can't be parsed as ${format}`))}__name(parseDataToDateTime,"parseDataToDateTime"),__name2(parseDataToDateTime,"parseDataToDateTime");function toTechFormat(dt,format,allowZ=!0){return dt.isValid?Formatter.create(Locale.create("en-US"),{allowZ,forceSimple:!0}).formatDateTimeFromString(dt,format):null}__name(toTechFormat,"toTechFormat"),__name2(toTechFormat,"toTechFormat");function toISODate(o,extended){const longFormat=o.c.year>9999||o.c.year<0;let c="";return longFormat&&o.c.year>=0&&(c+="+"),c+=padStart(o.c.year,longFormat?6:4),extended?(c+="-",c+=padStart(o.c.month),c+="-",c+=padStart(o.c.day)):(c+=padStart(o.c.month),c+=padStart(o.c.day)),c}__name(toISODate,"toISODate"),__name2(toISODate,"toISODate");function toISOTime(o,extended,suppressSeconds,suppressMilliseconds,includeOffset,extendedZone){let c=padStart(o.c.hour);return extended?(c+=":",c+=padStart(o.c.minute),(o.c.millisecond!==0||o.c.second!==0||!suppressSeconds)&&(c+=":")):c+=padStart(o.c.minute),(o.c.millisecond!==0||o.c.second!==0||!suppressSeconds)&&(c+=padStart(o.c.second),(o.c.millisecond!==0||!suppressMilliseconds)&&(c+=".",c+=padStart(o.c.millisecond,3))),includeOffset&&(o.isOffsetFixed&&o.offset===0&&!extendedZone?c+="Z":o.o<0?(c+="-",c+=padStart(Math.trunc(-o.o/60)),c+=":",c+=padStart(Math.trunc(-o.o%60))):(c+="+",c+=padStart(Math.trunc(o.o/60)),c+=":",c+=padStart(Math.trunc(o.o%60)))),extendedZone&&(c+="["+o.zone.ianaName+"]"),c}__name(toISOTime,"toISOTime"),__name2(toISOTime,"toISOTime");const defaultUnitValues={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},defaultWeekUnitValues={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},defaultOrdinalUnitValues={ordinal:1,hour:0,minute:0,second:0,millisecond:0},orderedUnits=["year","month","day","hour","minute","second","millisecond"],orderedWeekUnits=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],orderedOrdinalUnits=["year","ordinal","hour","minute","second","millisecond"];function normalizeUnit(unit){const normalized={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[unit.toLowerCase()];if(!normalized)throw new InvalidUnitError(unit);return normalized}__name(normalizeUnit,"normalizeUnit"),__name2(normalizeUnit,"normalizeUnit");function quickDT(obj,opts){const zone=normalizeZone(opts.zone,Settings.defaultZone),loc=Locale.fromObject(opts),tsNow=Settings.now();let ts,o;if(isUndefined(obj.year))ts=tsNow;else{for(const u of orderedUnits)isUndefined(obj[u])&&(obj[u]=defaultUnitValues[u]);const invalid=hasInvalidGregorianData(obj)||hasInvalidTimeData(obj);if(invalid)return DateTime.invalid(invalid);const offsetProvis=zone.offset(tsNow);[ts,o]=objToTS(obj,offsetProvis,zone)}return new DateTime({ts,zone,loc,o})}__name(quickDT,"quickDT"),__name2(quickDT,"quickDT");function diffRelative(start,end,opts){const round=isUndefined(opts.round)?!0:opts.round,format=__name2((c,unit)=>(c=roundTo(c,round||opts.calendary?0:2,!0),end.loc.clone(opts).relFormatter(opts).format(c,unit)),"format"),differ=__name2(unit=>opts.calendary?end.hasSame(start,unit)?0:end.startOf(unit).diff(start.startOf(unit),unit).get(unit):end.diff(start,unit).get(unit),"differ");if(opts.unit)return format(differ(opts.unit),opts.unit);for(const unit of opts.units){const count=differ(unit);if(Math.abs(count)>=1)return format(count,unit)}return format(start>end?-0:0,opts.units[opts.units.length-1])}__name(diffRelative,"diffRelative"),__name2(diffRelative,"diffRelative");function lastOpts(argList){let opts={},args;return argList.length>0&&typeof argList[argList.length-1]=="object"?(opts=argList[argList.length-1],args=Array.from(argList).slice(0,argList.length-1)):args=Array.from(argList),[opts,args]}__name(lastOpts,"lastOpts"),__name2(lastOpts,"lastOpts");const _DateTime=class _DateTime2{static{__name(this,"_DateTime")}constructor(config2){const zone=config2.zone||Settings.defaultZone;let invalid=config2.invalid||(Number.isNaN(config2.ts)?new Invalid("invalid input"):null)||(zone.isValid?null:unsupportedZone(zone));this.ts=isUndefined(config2.ts)?Settings.now():config2.ts;let c=null,o=null;if(!invalid)if(config2.old&&config2.old.ts===this.ts&&config2.old.zone.equals(zone))[c,o]=[config2.old.c,config2.old.o];else{const ot=zone.offset(this.ts);c=tsToObj(this.ts,ot),invalid=Number.isNaN(c.year)?new Invalid("invalid input"):null,c=invalid?null:c,o=invalid?null:ot}this._zone=zone,this.loc=config2.loc||Locale.create(),this.invalid=invalid,this.weekData=null,this.c=c,this.o=o,this.isLuxonDateTime=!0}static now(){return new _DateTime2({})}static local(){const[opts,args]=lastOpts(arguments),[year,month,day,hour,minute,second,millisecond]=args;return quickDT({year,month,day,hour,minute,second,millisecond},opts)}static utc(){const[opts,args]=lastOpts(arguments),[year,month,day,hour,minute,second,millisecond]=args;return opts.zone=FixedOffsetZone.utcInstance,quickDT({year,month,day,hour,minute,second,millisecond},opts)}static fromJSDate(date,options={}){const ts=isDate(date)?date.valueOf():NaN;if(Number.isNaN(ts))return _DateTime2.invalid("invalid input");const zoneToUse=normalizeZone(options.zone,Settings.defaultZone);return zoneToUse.isValid?new _DateTime2({ts,zone:zoneToUse,loc:Locale.fromObject(options)}):_DateTime2.invalid(unsupportedZone(zoneToUse))}static fromMillis(milliseconds,options={}){if(isNumber(milliseconds))return milliseconds<-MAX_DATE||milliseconds>MAX_DATE?_DateTime2.invalid("Timestamp out of range"):new _DateTime2({ts:milliseconds,zone:normalizeZone(options.zone,Settings.defaultZone),loc:Locale.fromObject(options)});throw new InvalidArgumentError(`fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`)}static fromSeconds(seconds,options={}){if(isNumber(seconds))return new _DateTime2({ts:seconds*1e3,zone:normalizeZone(options.zone,Settings.defaultZone),loc:Locale.fromObject(options)});throw new InvalidArgumentError("fromSeconds requires a numerical input")}static fromObject(obj,opts={}){obj=obj||{};const zoneToUse=normalizeZone(opts.zone,Settings.defaultZone);if(!zoneToUse.isValid)return _DateTime2.invalid(unsupportedZone(zoneToUse));const tsNow=Settings.now(),offsetProvis=isUndefined(opts.specificOffset)?zoneToUse.offset(tsNow):opts.specificOffset,normalized=normalizeObject(obj,normalizeUnit),containsOrdinal=!isUndefined(normalized.ordinal),containsGregorYear=!isUndefined(normalized.year),containsGregorMD=!isUndefined(normalized.month)||!isUndefined(normalized.day),containsGregor=containsGregorYear||containsGregorMD,definiteWeekDef=normalized.weekYear||normalized.weekNumber,loc=Locale.fromObject(opts);if((containsGregor||containsOrdinal)&&definiteWeekDef)throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(containsGregorMD&&containsOrdinal)throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");const useWeekData=definiteWeekDef||normalized.weekday&&!containsGregor;let units,defaultValues,objNow=tsToObj(tsNow,offsetProvis);useWeekData?(units=orderedWeekUnits,defaultValues=defaultWeekUnitValues,objNow=gregorianToWeek(objNow)):containsOrdinal?(units=orderedOrdinalUnits,defaultValues=defaultOrdinalUnitValues,objNow=gregorianToOrdinal(objNow)):(units=orderedUnits,defaultValues=defaultUnitValues);let foundFirst=!1;for(const u of units){const v=normalized[u];isUndefined(v)?foundFirst?normalized[u]=defaultValues[u]:normalized[u]=objNow[u]:foundFirst=!0}const higherOrderInvalid=useWeekData?hasInvalidWeekData(normalized):containsOrdinal?hasInvalidOrdinalData(normalized):hasInvalidGregorianData(normalized),invalid=higherOrderInvalid||hasInvalidTimeData(normalized);if(invalid)return _DateTime2.invalid(invalid);const gregorian=useWeekData?weekToGregorian(normalized):containsOrdinal?ordinalToGregorian(normalized):normalized,[tsFinal,offsetFinal]=objToTS(gregorian,offsetProvis,zoneToUse),inst=new _DateTime2({ts:tsFinal,zone:zoneToUse,o:offsetFinal,loc});return normalized.weekday&&containsGregor&&obj.weekday!==inst.weekday?_DateTime2.invalid("mismatched weekday",`you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`):inst}static fromISO(text,opts={}){const[vals,parsedZone]=parseISODate(text);return parseDataToDateTime(vals,parsedZone,opts,"ISO 8601",text)}static fromRFC2822(text,opts={}){const[vals,parsedZone]=parseRFC2822Date(text);return parseDataToDateTime(vals,parsedZone,opts,"RFC 2822",text)}static fromHTTP(text,opts={}){const[vals,parsedZone]=parseHTTPDate(text);return parseDataToDateTime(vals,parsedZone,opts,"HTTP",opts)}static fromFormat(text,fmt,opts={}){if(isUndefined(text)||isUndefined(fmt))throw new InvalidArgumentError("fromFormat requires an input string and a format");const{locale=null,numberingSystem=null}=opts,localeToUse=Locale.fromOpts({locale,numberingSystem,defaultToEN:!0}),[vals,parsedZone,specificOffset,invalid]=parseFromTokens(localeToUse,text,fmt);return invalid?_DateTime2.invalid(invalid):parseDataToDateTime(vals,parsedZone,opts,`format ${fmt}`,text,specificOffset)}static fromString(text,fmt,opts={}){return _DateTime2.fromFormat(text,fmt,opts)}static fromSQL(text,opts={}){const[vals,parsedZone]=parseSQL(text);return parseDataToDateTime(vals,parsedZone,opts,"SQL",text)}static invalid(reason,explanation=null){if(!reason)throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");const invalid=reason instanceof Invalid?reason:new Invalid(reason,explanation);if(Settings.throwOnInvalid)throw new InvalidDateTimeError(invalid);return new _DateTime2({invalid})}static isDateTime(o){return o&&o.isLuxonDateTime||!1}static parseFormatForOpts(formatOpts,localeOpts={}){const tokenList=formatOptsToTokens(formatOpts,Locale.fromObject(localeOpts));return tokenList?tokenList.map(t2=>t2?t2.val:null).join(""):null}static expandFormat(fmt,localeOpts={}){return expandMacroTokens(Formatter.parseFormat(fmt),Locale.fromObject(localeOpts)).map(t2=>t2.val).join("")}get(unit){return this[unit]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?possiblyCachedWeekData(this).weekYear:NaN}get weekNumber(){return this.isValid?possiblyCachedWeekData(this).weekNumber:NaN}get weekday(){return this.isValid?possiblyCachedWeekData(this).weekday:NaN}get ordinal(){return this.isValid?gregorianToOrdinal(this.c).ordinal:NaN}get monthShort(){return this.isValid?Info.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Info.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Info.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Info.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const dayMs=864e5,minuteMs=6e4,localTS=objToLocalTS(this.c),oEarlier=this.zone.offset(localTS-dayMs),oLater=this.zone.offset(localTS+dayMs),o1=this.zone.offset(localTS-oEarlier*minuteMs),o2=this.zone.offset(localTS-oLater*minuteMs);if(o1===o2)return[this];const ts1=localTS-o1*minuteMs,ts2=localTS-o2*minuteMs,c1=tsToObj(ts1,o1),c2=tsToObj(ts2,o2);return c1.hour===c2.hour&&c1.minute===c2.minute&&c1.second===c2.second&&c1.millisecond===c2.millisecond?[clone(this,{ts:ts1}),clone(this,{ts:ts2})]:[this]}get isInLeapYear(){return isLeapYear(this.year)}get daysInMonth(){return daysInMonth(this.year,this.month)}get daysInYear(){return this.isValid?daysInYear(this.year):NaN}get weeksInWeekYear(){return this.isValid?weeksInWeekYear(this.weekYear):NaN}resolvedLocaleOptions(opts={}){const{locale,numberingSystem,calendar}=Formatter.create(this.loc.clone(opts),opts).resolvedOptions(this);return{locale,numberingSystem,outputCalendar:calendar}}toUTC(offset2=0,opts={}){return this.setZone(FixedOffsetZone.instance(offset2),opts)}toLocal(){return this.setZone(Settings.defaultZone)}setZone(zone,{keepLocalTime=!1,keepCalendarTime=!1}={}){if(zone=normalizeZone(zone,Settings.defaultZone),zone.equals(this.zone))return this;if(zone.isValid){let newTS=this.ts;if(keepLocalTime||keepCalendarTime){const offsetGuess=zone.offset(this.ts),asObj=this.toObject();[newTS]=objToTS(asObj,offsetGuess,zone)}return clone(this,{ts:newTS,zone})}else return _DateTime2.invalid(unsupportedZone(zone))}reconfigure({locale,numberingSystem,outputCalendar}={}){const loc=this.loc.clone({locale,numberingSystem,outputCalendar});return clone(this,{loc})}setLocale(locale){return this.reconfigure({locale})}set(values){if(!this.isValid)return this;const normalized=normalizeObject(values,normalizeUnit),settingWeekStuff=!isUndefined(normalized.weekYear)||!isUndefined(normalized.weekNumber)||!isUndefined(normalized.weekday),containsOrdinal=!isUndefined(normalized.ordinal),containsGregorYear=!isUndefined(normalized.year),containsGregorMD=!isUndefined(normalized.month)||!isUndefined(normalized.day),containsGregor=containsGregorYear||containsGregorMD,definiteWeekDef=normalized.weekYear||normalized.weekNumber;if((containsGregor||containsOrdinal)&&definiteWeekDef)throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(containsGregorMD&&containsOrdinal)throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");let mixed;settingWeekStuff?mixed=weekToGregorian({...gregorianToWeek(this.c),...normalized}):isUndefined(normalized.ordinal)?(mixed={...this.toObject(),...normalized},isUndefined(normalized.day)&&(mixed.day=Math.min(daysInMonth(mixed.year,mixed.month),mixed.day))):mixed=ordinalToGregorian({...gregorianToOrdinal(this.c),...normalized});const[ts,o]=objToTS(mixed,this.o,this.zone);return clone(this,{ts,o})}plus(duration){if(!this.isValid)return this;const dur=Duration.fromDurationLike(duration);return clone(this,adjustTime(this,dur))}minus(duration){if(!this.isValid)return this;const dur=Duration.fromDurationLike(duration).negate();return clone(this,adjustTime(this,dur))}startOf(unit){if(!this.isValid)return this;const o={},normalizedUnit=Duration.normalizeUnit(unit);switch(normalizedUnit){case"years":o.month=1;case"quarters":case"months":o.day=1;case"weeks":case"days":o.hour=0;case"hours":o.minute=0;case"minutes":o.second=0;case"seconds":o.millisecond=0;break}if(normalizedUnit==="weeks"&&(o.weekday=1),normalizedUnit==="quarters"){const q=Math.ceil(this.month/3);o.month=(q-1)*3+1}return this.set(o)}endOf(unit){return this.isValid?this.plus({[unit]:1}).startOf(unit).minus(1):this}toFormat(fmt,opts={}){return this.isValid?Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this,fmt):INVALID}toLocaleString(formatOpts=DATE_SHORT,opts={}){return this.isValid?Formatter.create(this.loc.clone(opts),formatOpts).formatDateTime(this):INVALID}toLocaleParts(opts={}){return this.isValid?Formatter.create(this.loc.clone(opts),opts).formatDateTimeParts(this):[]}toISO({format="extended",suppressSeconds=!1,suppressMilliseconds=!1,includeOffset=!0,extendedZone=!1}={}){if(!this.isValid)return null;const ext=format==="extended";let c=toISODate(this,ext);return c+="T",c+=toISOTime(this,ext,suppressSeconds,suppressMilliseconds,includeOffset,extendedZone),c}toISODate({format="extended"}={}){return this.isValid?toISODate(this,format==="extended"):null}toISOWeekDate(){return toTechFormat(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds=!1,suppressSeconds=!1,includeOffset=!0,includePrefix=!1,extendedZone=!1,format="extended"}={}){return this.isValid?(includePrefix?"T":"")+toISOTime(this,format==="extended",suppressSeconds,suppressMilliseconds,includeOffset,extendedZone):null}toRFC2822(){return toTechFormat(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return toTechFormat(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?toISODate(this,!0):null}toSQLTime({includeOffset=!0,includeZone=!1,includeOffsetSpace=!0}={}){let fmt="HH:mm:ss.SSS";return(includeZone||includeOffset)&&(includeOffsetSpace&&(fmt+=" "),includeZone?fmt+="z":includeOffset&&(fmt+="ZZ")),toTechFormat(this,fmt,!0)}toSQL(opts={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(opts)}`:null}toString(){return this.isValid?this.toISO():INVALID}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(opts={}){if(!this.isValid)return{};const base2={...this.c};return opts.includeConfig&&(base2.outputCalendar=this.outputCalendar,base2.numberingSystem=this.loc.numberingSystem,base2.locale=this.loc.locale),base2}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(otherDateTime,unit="milliseconds",opts={}){if(!this.isValid||!otherDateTime.isValid)return Duration.invalid("created by diffing an invalid DateTime");const durOpts={locale:this.locale,numberingSystem:this.numberingSystem,...opts},units=maybeArray(unit).map(Duration.normalizeUnit),otherIsLater=otherDateTime.valueOf()>this.valueOf(),earlier=otherIsLater?this:otherDateTime,later=otherIsLater?otherDateTime:this,diffed=diff(earlier,later,units,durOpts);return otherIsLater?diffed.negate():diffed}diffNow(unit="milliseconds",opts={}){return this.diff(_DateTime2.now(),unit,opts)}until(otherDateTime){return this.isValid?Interval.fromDateTimes(this,otherDateTime):this}hasSame(otherDateTime,unit){if(!this.isValid)return!1;const inputMs=otherDateTime.valueOf(),adjustedToZone=this.setZone(otherDateTime.zone,{keepLocalTime:!0});return adjustedToZone.startOf(unit)<=inputMs&&inputMs<=adjustedToZone.endOf(unit)}equals(other){return this.isValid&&other.isValid&&this.valueOf()===other.valueOf()&&this.zone.equals(other.zone)&&this.loc.equals(other.loc)}toRelative(options={}){if(!this.isValid)return null;const base2=options.base||_DateTime2.fromObject({},{zone:this.zone}),padding=options.padding?thisi.valueOf(),Math.min)}static max(...dateTimes){if(!dateTimes.every(_DateTime2.isDateTime))throw new InvalidArgumentError("max requires all arguments be DateTimes");return bestBy(dateTimes,i=>i.valueOf(),Math.max)}static fromFormatExplain(text,fmt,options={}){const{locale=null,numberingSystem=null}=options,localeToUse=Locale.fromOpts({locale,numberingSystem,defaultToEN:!0});return explainFromTokens(localeToUse,text,fmt)}static fromStringExplain(text,fmt,options={}){return _DateTime2.fromFormatExplain(text,fmt,options)}static get DATE_SHORT(){return DATE_SHORT}static get DATE_MED(){return DATE_MED}static get DATE_MED_WITH_WEEKDAY(){return DATE_MED_WITH_WEEKDAY}static get DATE_FULL(){return DATE_FULL}static get DATE_HUGE(){return DATE_HUGE}static get TIME_SIMPLE(){return TIME_SIMPLE}static get TIME_WITH_SECONDS(){return TIME_WITH_SECONDS}static get TIME_WITH_SHORT_OFFSET(){return TIME_WITH_SHORT_OFFSET}static get TIME_WITH_LONG_OFFSET(){return TIME_WITH_LONG_OFFSET}static get TIME_24_SIMPLE(){return TIME_24_SIMPLE}static get TIME_24_WITH_SECONDS(){return TIME_24_WITH_SECONDS}static get TIME_24_WITH_SHORT_OFFSET(){return TIME_24_WITH_SHORT_OFFSET}static get TIME_24_WITH_LONG_OFFSET(){return TIME_24_WITH_LONG_OFFSET}static get DATETIME_SHORT(){return DATETIME_SHORT}static get DATETIME_SHORT_WITH_SECONDS(){return DATETIME_SHORT_WITH_SECONDS}static get DATETIME_MED(){return DATETIME_MED}static get DATETIME_MED_WITH_SECONDS(){return DATETIME_MED_WITH_SECONDS}static get DATETIME_MED_WITH_WEEKDAY(){return DATETIME_MED_WITH_WEEKDAY}static get DATETIME_FULL(){return DATETIME_FULL}static get DATETIME_FULL_WITH_SECONDS(){return DATETIME_FULL_WITH_SECONDS}static get DATETIME_HUGE(){return DATETIME_HUGE}static get DATETIME_HUGE_WITH_SECONDS(){return DATETIME_HUGE_WITH_SECONDS}};__name2(_DateTime,"DateTime");let DateTime=_DateTime;function friendlyDateTime(dateTimeish){if(DateTime.isDateTime(dateTimeish))return dateTimeish;if(dateTimeish&&dateTimeish.valueOf&&isNumber(dateTimeish.valueOf()))return DateTime.fromJSDate(dateTimeish);if(dateTimeish&&typeof dateTimeish=="object")return DateTime.fromObject(dateTimeish);throw new InvalidArgumentError(`Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`)}__name(friendlyDateTime,"friendlyDateTime"),__name2(friendlyDateTime,"friendlyDateTime");const _Text=class _Text2{static{__name(this,"_Text")}lineAt(pos){if(pos<0||pos>this.length)throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);return this.lineInner(pos,!1,1,0)}line(n2){if(n2<1||n2>this.lines)throw new RangeError(`Invalid line number ${n2} in ${this.lines}-line document`);return this.lineInner(n2,!0,1,0)}replace(from,to,text){let parts=[];return this.decompose(0,from,parts,2),text.length&&text.decompose(0,text.length,parts,3),this.decompose(to,this.length,parts,1),TextNode.from(parts,this.length-(to-from)+text.length)}append(other){return this.replace(this.length,this.length,other)}slice(from,to=this.length){let parts=[];return this.decompose(from,to,parts,0),TextNode.from(parts,to-from)}eq(other){if(other==this)return!0;if(other.length!=this.length||other.lines!=this.lines)return!1;let start=this.scanIdentical(other,1),end=this.length-this.scanIdentical(other,-1),a=new RawTextCursor(this),b=new RawTextCursor(other);for(let skip=start,pos=start;;){if(a.next(skip),b.next(skip),skip=0,a.lineBreak!=b.lineBreak||a.done!=b.done||a.value!=b.value)return!1;if(pos+=a.value.length,a.done||pos>=end)return!0}}iter(dir=1){return new RawTextCursor(this,dir)}iterRange(from,to=this.length){return new PartialTextCursor(this,from,to)}iterLines(from,to){let inner;if(from==null)inner=this.iter();else{to==null&&(to=this.lines+1);let start=this.line(from).from;inner=this.iterRange(start,Math.max(start,to==this.lines+1?this.length:to<=1?0:this.line(to-1).to))}return new LineCursor(inner)}toString(){return this.sliceString(0)}toJSON(){let lines=[];return this.flatten(lines),lines}constructor(){}static of(text){if(text.length==0)throw new RangeError("A document must have at least one line");return text.length==1&&!text[0]?_Text2.empty:text.length<=32?new TextLeaf(text):TextNode.from(TextLeaf.split(text,[]))}};__name2(_Text,"Text");let Text=_Text;const _TextLeaf=class _TextLeaf2 extends Text{static{__name(this,"_TextLeaf")}constructor(text,length=textLength(text)){super(),this.text=text,this.length=length}get lines(){return this.text.length}get children(){return null}lineInner(target,isLine,line,offset2){for(let i=0;;i++){let string2=this.text[i],end=offset2+string2.length;if((isLine?line:end)>=target)return new Line(offset2,end,line,string2);offset2=end+1,line++}}decompose(from,to,target,open){let text=from<=0&&to>=this.length?this:new _TextLeaf2(sliceText(this.text,from,to),Math.min(to,this.length)-Math.max(0,from));if(open&1){let prev=target.pop(),joined=appendText(text.text,prev.text.slice(),0,text.length);if(joined.length<=32)target.push(new _TextLeaf2(joined,prev.length+text.length));else{let mid=joined.length>>1;target.push(new _TextLeaf2(joined.slice(0,mid)),new _TextLeaf2(joined.slice(mid)))}}else target.push(text)}replace(from,to,text){if(!(text instanceof _TextLeaf2))return super.replace(from,to,text);let lines=appendText(this.text,appendText(text.text,sliceText(this.text,0,from)),to),newLen=this.length+text.length-(to-from);return lines.length<=32?new _TextLeaf2(lines,newLen):TextNode.from(_TextLeaf2.split(lines,[]),newLen)}sliceString(from,to=this.length,lineSep=` `){let result="";for(let pos=0,i=0;pos<=to&&ifrom&&i&&(result+=lineSep),frompos&&(result+=line.slice(Math.max(0,from-pos),to-pos)),pos=end+1}return result}flatten(target){for(let line of this.text)target.push(line)}scanIdentical(){return 0}static split(text,target){let part=[],len=-1;for(let line of text)part.push(line),len+=line.length+1,part.length==32&&(target.push(new _TextLeaf2(part,len)),part=[],len=-1);return len>-1&&target.push(new _TextLeaf2(part,len)),target}};__name2(_TextLeaf,"TextLeaf");let TextLeaf=_TextLeaf;const _TextNode=class _TextNode2 extends Text{static{__name(this,"_TextNode")}constructor(children,length){super(),this.children=children,this.length=length,this.lines=0;for(let child of children)this.lines+=child.lines}lineInner(target,isLine,line,offset2){for(let i=0;;i++){let child=this.children[i],end=offset2+child.length,endLine=line+child.lines-1;if((isLine?endLine:end)>=target)return child.lineInner(target,isLine,line,offset2);offset2=end+1,line=endLine+1}}decompose(from,to,target,open){for(let i=0,pos=0;pos<=to&&i=pos){let childOpen=open&((pos<=from?1:0)|(end>=to?2:0));pos>=from&&end<=to&&!childOpen?target.push(child):child.decompose(from-pos,to-pos,target,childOpen)}pos=end+1}}replace(from,to,text){if(text.lines=pos&&to<=end){let updated=child.replace(from-pos,to-pos,text),totalLines=this.lines-child.lines+updated.lines;if(updated.lines>5-1&&updated.lines>totalLines>>5+1){let copy=this.children.slice();return copy[i]=updated,new _TextNode2(copy,this.length-(to-from)+text.length)}return super.replace(pos,end,updated)}pos=end+1}return super.replace(from,to,text)}sliceString(from,to=this.length,lineSep=` `){let result="";for(let i=0,pos=0;ifrom&&i&&(result+=lineSep),frompos&&(result+=child.sliceString(from-pos,to-pos,lineSep)),pos=end+1}return result}flatten(target){for(let child of this.children)child.flatten(target)}scanIdentical(other,dir){if(!(other instanceof _TextNode2))return 0;let length=0,[iA,iB,eA,eB]=dir>0?[0,0,this.children.length,other.children.length]:[this.children.length-1,other.children.length-1,-1,-1];for(;;iA+=dir,iB+=dir){if(iA==eA||iB==eB)return length;let chA=this.children[iA],chB=other.children[iB];if(chA!=chB)return length+chA.scanIdentical(chB,dir);length+=chA.length+1}}static from(children,length=children.reduce((l2,ch)=>l2+ch.length+1,-1)){let lines=0;for(let ch of children)lines+=ch.lines;if(lines<32){let flat=[];for(let ch of children)ch.flatten(flat);return new TextLeaf(flat,length)}let chunk=Math.max(32,lines>>5),maxChunk=chunk<<1,minChunk=chunk>>1,chunked=[],currentLines=0,currentLen=-1,currentChunk=[];function add2(child){let last2;if(child.lines>maxChunk&&child instanceof _TextNode2)for(let node of child.children)add2(node);else child.lines>minChunk&&(currentLines>minChunk||!currentLines)?(flush(),chunked.push(child)):child instanceof TextLeaf&¤tLines&&(last2=currentChunk[currentChunk.length-1])instanceof TextLeaf&&child.lines+last2.lines<=32?(currentLines+=child.lines,currentLen+=child.length+1,currentChunk[currentChunk.length-1]=new TextLeaf(last2.text.concat(child.text),last2.length+1+child.length)):(currentLines+child.lines>chunk&&flush(),currentLines+=child.lines,currentLen+=child.length+1,currentChunk.push(child))}__name(add2,"add2"),__name2(add2,"add");function flush(){currentLines!=0&&(chunked.push(currentChunk.length==1?currentChunk[0]:_TextNode2.from(currentChunk,currentLen)),currentLen=-1,currentLines=currentChunk.length=0)}__name(flush,"flush"),__name2(flush,"flush");for(let child of children)add2(child);return flush(),chunked.length==1?chunked[0]:new _TextNode2(chunked,length)}};__name2(_TextNode,"TextNode");let TextNode=_TextNode;Text.empty=new TextLeaf([""],0);function textLength(text){let length=-1;for(let line of text)length+=line.length+1;return length}__name(textLength,"textLength"),__name2(textLength,"textLength");function appendText(text,target,from=0,to=1e9){for(let pos=0,i=0,first=!0;i=from&&(end>to&&(line=line.slice(0,to-pos)),pos0?1:(text instanceof TextLeaf?text.text.length:text.children.length)<<1]}nextInner(skip,dir){for(this.done=this.lineBreak=!1;;){let last2=this.nodes.length-1,top2=this.nodes[last2],offsetValue=this.offsets[last2],offset2=offsetValue>>1,size=top2 instanceof TextLeaf?top2.text.length:top2.children.length;if(offset2==(dir>0?size:0)){if(last2==0)return this.done=!0,this.value="",this;dir>0&&this.offsets[last2-1]++,this.nodes.pop(),this.offsets.pop()}else if((offsetValue&1)==(dir>0?0:1)){if(this.offsets[last2]+=dir,skip==0)return this.lineBreak=!0,this.value=` `,this;skip--}else if(top2 instanceof TextLeaf){let next=top2.text[offset2+(dir<0?-1:0)];if(this.offsets[last2]+=dir,next.length>Math.max(0,skip))return this.value=skip==0?next:dir>0?next.slice(skip):next.slice(0,next.length-skip),this;skip-=next.length}else{let next=top2.children[offset2+(dir<0?-1:0)];skip>next.length?(skip-=next.length,this.offsets[last2]+=dir):(dir<0&&this.offsets[last2]--,this.nodes.push(next),this.offsets.push(dir>0?1:(next instanceof TextLeaf?next.text.length:next.children.length)<<1))}}}next(skip=0){return skip<0&&(this.nextInner(-skip,-this.dir),skip=this.value.length),this.nextInner(skip,this.dir)}};__name2(_RawTextCursor,"RawTextCursor");let RawTextCursor=_RawTextCursor;const _PartialTextCursor=class{static{__name(this,"_PartialTextCursor")}constructor(text,start,end){this.value="",this.done=!1,this.cursor=new RawTextCursor(text,start>end?-1:1),this.pos=start>end?text.length:0,this.from=Math.min(start,end),this.to=Math.max(start,end)}nextInner(skip,dir){if(dir<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;skip+=Math.max(0,dir<0?this.pos-this.to:this.from-this.pos);let limit2=dir<0?this.pos-this.from:this.to-this.pos;skip>limit2&&(skip=limit2),limit2-=skip;let{value}=this.cursor.next(skip);return this.pos+=(value.length+skip)*dir,this.value=value.length<=limit2?value:dir<0?value.slice(value.length-limit2):value.slice(0,limit2),this.done=!this.value,this}next(skip=0){return skip<0?skip=Math.max(skip,this.from-this.pos):skip>0&&(skip=Math.min(skip,this.to-this.pos)),this.nextInner(skip,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}};__name2(_PartialTextCursor,"PartialTextCursor");let PartialTextCursor=_PartialTextCursor;const _LineCursor=class{static{__name(this,"_LineCursor")}constructor(inner){this.inner=inner,this.afterBreak=!0,this.value="",this.done=!1}next(skip=0){let{done,lineBreak,value}=this.inner.next(skip);return done?(this.done=!0,this.value=""):lineBreak?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=value,this.afterBreak=!1),this}get lineBreak(){return!1}};__name2(_LineCursor,"LineCursor");let LineCursor=_LineCursor;typeof Symbol<"u"&&(Text.prototype[Symbol.iterator]=function(){return this.iter()},RawTextCursor.prototype[Symbol.iterator]=PartialTextCursor.prototype[Symbol.iterator]=LineCursor.prototype[Symbol.iterator]=function(){return this});const _Line=class{static{__name(this,"_Line")}constructor(from,to,number2,text){this.from=from,this.to=to,this.number=number2,this.text=text}get length(){return this.to-this.from}};__name2(_Line,"Line");let Line=_Line,extend="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(s2=>s2?parseInt(s2,36):1);for(let i=1;icode)return extend[i-1]<=code;return!1}__name(isExtendingChar,"isExtendingChar"),__name2(isExtendingChar,"isExtendingChar");function isRegionalIndicator(code){return code>=127462&&code<=127487}__name(isRegionalIndicator,"isRegionalIndicator"),__name2(isRegionalIndicator,"isRegionalIndicator");const ZWJ=8205;function findClusterBreak(str,pos,forward=!0,includeExtending=!0){return(forward?nextClusterBreak:prevClusterBreak)(str,pos,includeExtending)}__name(findClusterBreak,"findClusterBreak"),__name2(findClusterBreak,"findClusterBreak");function nextClusterBreak(str,pos,includeExtending){if(pos==str.length)return pos;pos&&surrogateLow(str.charCodeAt(pos))&&surrogateHigh(str.charCodeAt(pos-1))&&pos--;let prev=codePointAt(str,pos);for(pos+=codePointSize(prev);pos=0&&isRegionalIndicator(codePointAt(str,i));)countBefore++,i-=2;if(countBefore%2==0)break;pos+=2}else break}return pos}__name(nextClusterBreak,"nextClusterBreak"),__name2(nextClusterBreak,"nextClusterBreak");function prevClusterBreak(str,pos,includeExtending){for(;pos>0;){let found=nextClusterBreak(str,pos-2,includeExtending);if(found=56320&&ch<57344}__name(surrogateLow,"surrogateLow"),__name2(surrogateLow,"surrogateLow");function surrogateHigh(ch){return ch>=55296&&ch<56320}__name(surrogateHigh,"surrogateHigh"),__name2(surrogateHigh,"surrogateHigh");function codePointAt(str,pos){let code0=str.charCodeAt(pos);if(!surrogateHigh(code0)||pos+1==str.length)return code0;let code1=str.charCodeAt(pos+1);return surrogateLow(code1)?(code0-55296<<10)+(code1-56320)+65536:code0}__name(codePointAt,"codePointAt"),__name2(codePointAt,"codePointAt");function fromCodePoint(code){return code<=65535?String.fromCharCode(code):(code-=65536,String.fromCharCode((code>>10)+55296,(code&1023)+56320))}__name(fromCodePoint,"fromCodePoint"),__name2(fromCodePoint,"fromCodePoint");function codePointSize(code){return code<65536?1:2}__name(codePointSize,"codePointSize"),__name2(codePointSize,"codePointSize");const DefaultSplit=/\r\n?|\n/;var MapMode=function(MapMode2){return MapMode2[MapMode2.Simple=0]="Simple",MapMode2[MapMode2.TrackDel=1]="TrackDel",MapMode2[MapMode2.TrackBefore=2]="TrackBefore",MapMode2[MapMode2.TrackAfter=3]="TrackAfter",MapMode2}(MapMode||(MapMode={}));const _ChangeDesc=class _ChangeDesc2{static{__name(this,"_ChangeDesc")}constructor(sections){this.sections=sections}get length(){let result=0;for(let i=0;ipos)return posB+(pos-posA);posB+=len}else{if(mode!=MapMode.Simple&&endA>=pos&&(mode==MapMode.TrackDel&&posApos||mode==MapMode.TrackBefore&&posApos))return null;if(endA>pos||endA==pos&&assoc<0&&!len)return pos==posA||assoc<0?posB:posB+ins;posB+=ins}posA=endA}if(pos>posA)throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);return posB}touchesRange(from,to=from){for(let i=0,pos=0;i=0&&pos<=to&&end>=from)return posto?"cover":!0;pos=end}return!1}toString(){let result="";for(let i=0;i=0?":"+ins:"")}return result}toJSON(){return this.sections}static fromJSON(json2){if(!Array.isArray(json2)||json2.length%2||json2.some(a=>typeof a!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new _ChangeDesc2(json2)}static create(sections){return new _ChangeDesc2(sections)}};__name2(_ChangeDesc,"ChangeDesc");let ChangeDesc=_ChangeDesc;const _ChangeSet=class _ChangeSet2 extends ChangeDesc{static{__name(this,"_ChangeSet")}constructor(sections,inserted){super(sections),this.inserted=inserted}apply(doc2){if(this.length!=doc2.length)throw new RangeError("Applying change set to a document with the wrong length");return iterChanges(this,(fromA,toA,fromB,_toB,text)=>doc2=doc2.replace(fromB,fromB+(toA-fromA),text),!1),doc2}mapDesc(other,before=!1){return mapSet(this,other,before,!0)}invert(doc2){let sections=this.sections.slice(),inserted=[];for(let i=0,pos=0;i=0){sections[i]=ins,sections[i+1]=len;let index2=i>>1;for(;inserted.length0&&addInsert(resultInserted,resultSections,iter.text),iter.forward(len),pos+=len}let end=ranges[i++];for(;pos>1].toJSON()))}return parts}static of(changes,length,lineSep){let sections=[],inserted=[],pos=0,total=null;function flush(force=!1){if(!force&&!sections.length)return;posto||from<0||to>length)throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);let insText=insert2?typeof insert2=="string"?Text.of(insert2.split(lineSep||DefaultSplit)):insert2:Text.empty,insLen=insText.length;if(from==to&&insLen==0)return;frompos&&addSection(sections,from-pos,-1),addSection(sections,to-from,insLen),addInsert(inserted,sections,insText),pos=to}}return __name(process2,"process2"),__name2(process2,"process"),process2(changes),flush(!total),total}static empty(length){return new _ChangeSet2(length?[length,-1]:[],[])}static fromJSON(json2){if(!Array.isArray(json2))throw new RangeError("Invalid JSON representation of ChangeSet");let sections=[],inserted=[];for(let i=0;ii2&&typeof e!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(part.length==1)sections.push(part[0],0);else{for(;inserted.length=0&&ins<=0&&ins==sections[last2+1]?sections[last2]+=len:len==0&§ions[last2]==0?sections[last2+1]+=ins:forceJoin?(sections[last2]+=len,sections[last2+1]+=ins):sections.push(len,ins)}__name(addSection,"addSection"),__name2(addSection,"addSection");function addInsert(values,sections,value){if(value.length==0)return;let index2=sections.length-2>>1;if(index2>1])),!(individual||i==desc.sections.length||desc.sections[i+1]<0);)len=desc.sections[i++],ins=desc.sections[i++];f(posA,endA,posB,endB,text),posA=endA,posB=endB}}}__name(iterChanges,"iterChanges"),__name2(iterChanges,"iterChanges");function mapSet(setA,setB,before,mkSet=!1){let sections=[],insert2=mkSet?[]:null,a=new SectionIter(setA),b=new SectionIter(setB);for(let inserted=-1;;)if(a.ins==-1&&b.ins==-1){let len=Math.min(a.len,b.len);addSection(sections,len,-1),a.forward(len),b.forward(len)}else if(b.ins>=0&&(a.ins<0||inserted==a.i||a.off==0&&(b.len=0&&inserted=0){let len=0,left=a.len;for(;left;)if(b.ins==-1){let piece=Math.min(left,b.len);len+=piece,left-=piece,b.forward(piece)}else if(b.ins==0&&b.lenlen||b.ins>=0&&b.len>len)&&(open||sections.length>sectionLen),a.forward2(len),b.forward(len)}}}}__name(composeSets,"composeSets"),__name2(composeSets,"composeSets");const _SectionIter=class{static{__name(this,"_SectionIter")}constructor(set){this.set=set,this.i=0,this.next()}next(){let{sections}=this.set;this.i>1;return index2>=inserted.length?Text.empty:inserted[index2]}textBit(len){let{inserted}=this.set,index2=this.i-2>>1;return index2>=inserted.length&&!len?Text.empty:inserted[index2].slice(this.off,len==null?void 0:this.off+len)}forward(len){len==this.len?this.next():(this.len-=len,this.off+=len)}forward2(len){this.ins==-1?this.forward(len):len==this.ins?this.next():(this.ins-=len,this.off+=len)}};__name2(_SectionIter,"SectionIter");let SectionIter=_SectionIter;const _SelectionRange=class _SelectionRange2{static{__name(this,"_SelectionRange")}constructor(from,to,flags){this.from=from,this.to=to,this.flags=flags}get anchor(){return this.flags&16?this.to:this.from}get head(){return this.flags&16?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&4?-1:this.flags&8?1:0}get bidiLevel(){let level=this.flags&3;return level==3?null:level}get goalColumn(){let value=this.flags>>5;return value==33554431?void 0:value}map(change,assoc=-1){let from,to;return this.empty?from=to=change.mapPos(this.from,assoc):(from=change.mapPos(this.from,1),to=change.mapPos(this.to,-1)),from==this.from&&to==this.to?this:new _SelectionRange2(from,to,this.flags)}extend(from,to=from){if(from<=this.anchor&&to>=this.anchor)return EditorSelection.range(from,to);let head=Math.abs(from-this.anchor)>Math.abs(to-this.anchor)?from:to;return EditorSelection.range(this.anchor,head)}eq(other){return this.anchor==other.anchor&&this.head==other.head}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(json2){if(!json2||typeof json2.anchor!="number"||typeof json2.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return EditorSelection.range(json2.anchor,json2.head)}static create(from,to,flags){return new _SelectionRange2(from,to,flags)}};__name2(_SelectionRange,"SelectionRange");let SelectionRange=_SelectionRange;const _EditorSelection=class _EditorSelection2{static{__name(this,"_EditorSelection")}constructor(ranges,mainIndex){this.ranges=ranges,this.mainIndex=mainIndex}map(change,assoc=-1){return change.empty?this:_EditorSelection2.create(this.ranges.map(r=>r.map(change,assoc)),this.mainIndex)}eq(other){if(this.ranges.length!=other.ranges.length||this.mainIndex!=other.mainIndex)return!1;for(let i=0;ir.toJSON()),main:this.mainIndex}}static fromJSON(json2){if(!json2||!Array.isArray(json2.ranges)||typeof json2.main!="number"||json2.main>=json2.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new _EditorSelection2(json2.ranges.map(r=>SelectionRange.fromJSON(r)),json2.main)}static single(anchor,head=anchor){return new _EditorSelection2([_EditorSelection2.range(anchor,head)],0)}static create(ranges,mainIndex=0){if(ranges.length==0)throw new RangeError("A selection needs at least one range");for(let pos=0,i=0;ianchor?4:0)|flags)}static normalized(ranges,mainIndex=0){let main=ranges[mainIndex];ranges.sort((a,b)=>a.from-b.from),mainIndex=ranges.indexOf(main);for(let i=1;irange.head?_EditorSelection2.range(to,from):_EditorSelection2.range(from,to))}}return new _EditorSelection2(ranges,mainIndex)}};__name2(_EditorSelection,"EditorSelection");let EditorSelection=_EditorSelection;function checkSelection(selection,docLength){for(let range of selection.ranges)if(range.to>docLength)throw new RangeError("Selection points outside of document")}__name(checkSelection,"checkSelection"),__name2(checkSelection,"checkSelection");let nextID=0;const _Facet=class _Facet2{static{__name(this,"_Facet")}constructor(combine,compareInput,compare2,isStatic,enables){this.combine=combine,this.compareInput=compareInput,this.compare=compare2,this.isStatic=isStatic,this.id=nextID++,this.default=combine([]),this.extensions=typeof enables=="function"?enables(this):enables}static define(config2={}){return new _Facet2(config2.combine||(a=>a),config2.compareInput||((a,b)=>a===b),config2.compare||(config2.combine?(a,b)=>a===b:sameArray$1),!!config2.static,config2.enables)}of(value){return new FacetProvider([],this,0,value)}compute(deps,get){if(this.isStatic)throw new Error("Can't compute a static facet");return new FacetProvider(deps,this,1,get)}computeN(deps,get){if(this.isStatic)throw new Error("Can't compute a static facet");return new FacetProvider(deps,this,2,get)}from(field,get){return get||(get=__name2(x=>x,"get")),this.compute([field],state=>get(state.field(field)))}};__name2(_Facet,"Facet");let Facet=_Facet;function sameArray$1(a,b){return a==b||a.length==b.length&&a.every((e,i)=>e===b[i])}__name(sameArray$1,"sameArray$1"),__name2(sameArray$1,"sameArray$1");const _FacetProvider=class{static{__name(this,"_FacetProvider")}constructor(dependencies,facet,type,value){this.dependencies=dependencies,this.facet=facet,this.type=type,this.value=value,this.id=nextID++}dynamicSlot(addresses){var _a3;let getter=this.value,compare2=this.facet.compareInput,id=this.id,idx=addresses[id]>>1,multi=this.type==2,depDoc=!1,depSel=!1,depAddrs=[];for(let dep of this.dependencies)dep=="doc"?depDoc=!0:dep=="selection"?depSel=!0:((_a3=addresses[dep.id])!==null&&_a3!==void 0?_a3:1)&1||depAddrs.push(addresses[dep.id]);return{create(state){return state.values[idx]=getter(state),1},update(state,tr){if(depDoc&&tr.docChanged||depSel&&(tr.docChanged||tr.selection)||ensureAll(state,depAddrs)){let newVal=getter(state);if(multi?!compareArray(newVal,state.values[idx],compare2):!compare2(newVal,state.values[idx]))return state.values[idx]=newVal,1}return 0},reconfigure:(state,oldState)=>{let newVal,oldAddr=oldState.config.address[id];if(oldAddr!=null){let oldVal=getAddr(oldState,oldAddr);if(this.dependencies.every(dep=>dep instanceof Facet?oldState.facet(dep)===state.facet(dep):dep instanceof StateField?oldState.field(dep,!1)==state.field(dep,!1):!0)||(multi?compareArray(newVal=getter(state),oldVal,compare2):compare2(newVal=getter(state),oldVal)))return state.values[idx]=oldVal,0}else newVal=getter(state);return state.values[idx]=newVal,1}}}};__name2(_FacetProvider,"FacetProvider");let FacetProvider=_FacetProvider;function compareArray(a,b,compare2){if(a.length!=b.length)return!1;for(let i=0;iaddresses[p.id]),providerTypes=providers.map(p=>p.type),dynamic=providerAddrs.filter(p=>!(p&1)),idx=addresses[facet.id]>>1;function get(state){let values=[];for(let i=0;ia===b),config2);return config2.provide&&(field.provides=config2.provide(field)),field}create(state){let init=state.facet(initField).find(i=>i.field==this);return(init?.create||this.createF)(state)}slot(addresses){let idx=addresses[this.id]>>1;return{create:state=>(state.values[idx]=this.create(state),1),update:(state,tr)=>{let oldVal=state.values[idx],value=this.updateF(oldVal,tr);return this.compareF(oldVal,value)?0:(state.values[idx]=value,1)},reconfigure:(state,oldState)=>oldState.config.address[this.id]!=null?(state.values[idx]=oldState.field(this),0):(state.values[idx]=this.create(state),1)}}init(create){return[this,initField.of({field:this,create})]}get extension(){return this}};__name2(_StateField,"StateField");let StateField=_StateField;const Prec_={lowest:4,low:3,default:2,high:1,highest:0};function prec(value){return ext=>new PrecExtension(ext,value)}__name(prec,"prec"),__name2(prec,"prec");const Prec={highest:prec(Prec_.highest),high:prec(Prec_.high),default:prec(Prec_.default),low:prec(Prec_.low),lowest:prec(Prec_.lowest)},_PrecExtension=class{static{__name(this,"_PrecExtension")}constructor(inner,prec2){this.inner=inner,this.prec=prec2}};__name2(_PrecExtension,"PrecExtension");let PrecExtension=_PrecExtension;const _Compartment=class _Compartment2{static{__name(this,"_Compartment")}of(ext){return new CompartmentInstance(this,ext)}reconfigure(content2){return _Compartment2.reconfigure.of({compartment:this,extension:content2})}get(state){return state.config.compartments.get(this)}};__name2(_Compartment,"Compartment");let Compartment=_Compartment;const _CompartmentInstance=class{static{__name(this,"_CompartmentInstance")}constructor(compartment,inner){this.compartment=compartment,this.inner=inner}};__name2(_CompartmentInstance,"CompartmentInstance");let CompartmentInstance=_CompartmentInstance;const _Configuration=class _Configuration2{static{__name(this,"_Configuration")}constructor(base2,compartments,dynamicSlots,address,staticValues,facets){for(this.base=base2,this.compartments=compartments,this.dynamicSlots=dynamicSlots,this.address=address,this.staticValues=staticValues,this.facets=facets,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(base2,compartments,oldState){let fields=[],facets=Object.create(null),newCompartments=new Map;for(let ext of flatten(base2,compartments,newCompartments))ext instanceof StateField?fields.push(ext):(facets[ext.facet.id]||(facets[ext.facet.id]=[])).push(ext);let address=Object.create(null),staticValues=[],dynamicSlots=[];for(let field of fields)address[field.id]=dynamicSlots.length<<1,dynamicSlots.push(a=>field.slot(a));let oldFacets=oldState?.config.facets;for(let id in facets){let providers=facets[id],facet=providers[0].facet,oldProviders=oldFacets&&oldFacets[id]||[];if(providers.every(p=>p.type==0))if(address[facet.id]=staticValues.length<<1|1,sameArray$1(oldProviders,providers))staticValues.push(oldState.facet(facet));else{let value=facet.combine(providers.map(p=>p.value));staticValues.push(oldState&&facet.compare(value,oldState.facet(facet))?oldState.facet(facet):value)}else{for(let p of providers)p.type==0?(address[p.id]=staticValues.length<<1|1,staticValues.push(p.value)):(address[p.id]=dynamicSlots.length<<1,dynamicSlots.push(a=>p.dynamicSlot(a)));address[facet.id]=dynamicSlots.length<<1,dynamicSlots.push(a=>dynamicFacetSlot(a,facet,providers))}}let dynamic=dynamicSlots.map(f=>f(address));return new _Configuration2(base2,newCompartments,dynamic,address,staticValues,facets)}};__name2(_Configuration,"Configuration");let Configuration=_Configuration;function flatten(extension,compartments,newCompartments){let result=[[],[],[],[],[]],seen=new Map;function inner(ext,prec2){let known=seen.get(ext);if(known!=null){if(known<=prec2)return;let found=result[known].indexOf(ext);found>-1&&result[known].splice(found,1),ext instanceof CompartmentInstance&&newCompartments.delete(ext.compartment)}if(seen.set(ext,prec2),Array.isArray(ext))for(let e of ext)inner(e,prec2);else if(ext instanceof CompartmentInstance){if(newCompartments.has(ext.compartment))throw new RangeError("Duplicate use of compartment in extensions");let content2=compartments.get(ext.compartment)||ext.inner;newCompartments.set(ext.compartment,content2),inner(content2,prec2)}else if(ext instanceof PrecExtension)inner(ext.inner,ext.prec);else if(ext instanceof StateField)result[prec2].push(ext),ext.provides&&inner(ext.provides,prec2);else if(ext instanceof FacetProvider)result[prec2].push(ext),ext.facet.extensions&&inner(ext.facet.extensions,Prec_.default);else{let content2=ext.extension;if(!content2)throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);inner(content2,prec2)}}return __name(inner,"inner"),__name2(inner,"inner"),inner(extension,Prec_.default),result.reduce((a,b)=>a.concat(b))}__name(flatten,"flatten"),__name2(flatten,"flatten");function ensureAddr(state,addr){if(addr&1)return 2;let idx=addr>>1,status=state.status[idx];if(status==4)throw new Error("Cyclic dependency between fields and/or facets");if(status&2)return status;state.status[idx]=4;let changed=state.computeSlot(state,state.config.dynamicSlots[idx]);return state.status[idx]=2|changed}__name(ensureAddr,"ensureAddr"),__name2(ensureAddr,"ensureAddr");function getAddr(state,addr){return addr&1?state.config.staticValues[addr>>1]:state.values[addr>>1]}__name(getAddr,"getAddr"),__name2(getAddr,"getAddr");const languageData=Facet.define(),allowMultipleSelections=Facet.define({combine:values=>values.some(v=>v),static:!0}),lineSeparator=Facet.define({combine:values=>values.length?values[0]:void 0,static:!0}),changeFilter=Facet.define(),transactionFilter=Facet.define(),transactionExtender=Facet.define(),readOnly=Facet.define({combine:values=>values.length?values[0]:!1}),_Annotation=class{static{__name(this,"_Annotation")}constructor(type,value){this.type=type,this.value=value}static define(){return new AnnotationType}};__name2(_Annotation,"Annotation");let Annotation=_Annotation;const _AnnotationType=class{static{__name(this,"_AnnotationType")}of(value){return new Annotation(this,value)}};__name2(_AnnotationType,"AnnotationType");let AnnotationType=_AnnotationType;const _StateEffectType=class{static{__name(this,"_StateEffectType")}constructor(map2){this.map=map2}of(value){return new StateEffect(this,value)}};__name2(_StateEffectType,"StateEffectType");let StateEffectType=_StateEffectType;const _StateEffect=class _StateEffect2{static{__name(this,"_StateEffect")}constructor(type,value){this.type=type,this.value=value}map(mapping){let mapped=this.type.map(this.value,mapping);return mapped===void 0?void 0:mapped==this.value?this:new _StateEffect2(this.type,mapped)}is(type){return this.type==type}static define(spec={}){return new StateEffectType(spec.map||(v=>v))}static mapEffects(effects,mapping){if(!effects.length)return effects;let result=[];for(let effect of effects){let mapped=effect.map(mapping);mapped&&result.push(mapped)}return result}};__name2(_StateEffect,"StateEffect");let StateEffect=_StateEffect;StateEffect.reconfigure=StateEffect.define(),StateEffect.appendConfig=StateEffect.define();const _Transaction=class _Transaction2{static{__name(this,"_Transaction")}constructor(startState,changes,selection,effects,annotations,scrollIntoView2){this.startState=startState,this.changes=changes,this.selection=selection,this.effects=effects,this.annotations=annotations,this.scrollIntoView=scrollIntoView2,this._doc=null,this._state=null,selection&&checkSelection(selection,changes.newLength),annotations.some(a=>a.type==_Transaction2.time)||(this.annotations=annotations.concat(_Transaction2.time.of(Date.now())))}static create(startState,changes,selection,effects,annotations,scrollIntoView2){return new _Transaction2(startState,changes,selection,effects,annotations,scrollIntoView2)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(type){for(let ann of this.annotations)if(ann.type==type)return ann.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(event){let e=this.annotation(_Transaction2.userEvent);return!!(e&&(e==event||e.length>event.length&&e.slice(0,event.length)==event&&e[event.length]=="."))}};__name2(_Transaction,"Transaction");let Transaction=_Transaction;Transaction.time=Annotation.define(),Transaction.userEvent=Annotation.define(),Transaction.addToHistory=Annotation.define(),Transaction.remote=Annotation.define();function joinRanges(a,b){let result=[];for(let iA=0,iB=0;;){let from,to;if(iA=a[iA]))from=a[iA++],to=a[iA++];else if(iB=0;i--){let filtered=filters[i](tr);filtered instanceof Transaction?tr=filtered:Array.isArray(filtered)&&filtered.length==1&&filtered[0]instanceof Transaction?tr=filtered[0]:tr=resolveTransaction(state,asArray$2(filtered),!1)}return tr}__name(filterTransaction,"filterTransaction"),__name2(filterTransaction,"filterTransaction");function extendTransaction(tr){let state=tr.startState,extenders=state.facet(transactionExtender),spec=tr;for(let i=extenders.length-1;i>=0;i--){let extension=extenders[i](tr);extension&&Object.keys(extension).length&&(spec=mergeTransaction(spec,resolveTransactionInner(state,extension,tr.changes.newLength),!0))}return spec==tr?tr:Transaction.create(state,tr.changes,tr.selection,spec.effects,spec.annotations,spec.scrollIntoView)}__name(extendTransaction,"extendTransaction"),__name2(extendTransaction,"extendTransaction");const none$2=[];function asArray$2(value){return value==null?none$2:Array.isArray(value)?value:[value]}__name(asArray$2,"asArray$2"),__name2(asArray$2,"asArray$2");var CharCategory=function(CharCategory2){return CharCategory2[CharCategory2.Word=0]="Word",CharCategory2[CharCategory2.Space=1]="Space",CharCategory2[CharCategory2.Other=2]="Other",CharCategory2}(CharCategory||(CharCategory={}));const nonASCIISingleCaseWordChar=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let wordChar;try{wordChar=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function hasWordChar(str){if(wordChar)return wordChar.test(str);for(let i=0;i"\x80"&&(ch.toUpperCase()!=ch.toLowerCase()||nonASCIISingleCaseWordChar.test(ch)))return!0}return!1}__name(hasWordChar,"hasWordChar"),__name2(hasWordChar,"hasWordChar");function makeCategorizer(wordChars){return char=>{if(!/\S/.test(char))return CharCategory.Space;if(hasWordChar(char))return CharCategory.Word;for(let i=0;i-1)return CharCategory.Word;return CharCategory.Other}}__name(makeCategorizer,"makeCategorizer"),__name2(makeCategorizer,"makeCategorizer");const _EditorState=class _EditorState2{static{__name(this,"_EditorState")}constructor(config2,doc2,selection,values,computeSlot,tr){this.config=config2,this.doc=doc2,this.selection=selection,this.values=values,this.status=config2.statusTemplate.slice(),this.computeSlot=computeSlot,tr&&(tr._state=this);for(let i=0;icompartments.set(key,val)),conf=null),compartments.set(effect.value.compartment,effect.value.extension)):effect.is(StateEffect.reconfigure)?(conf=null,base2=effect.value):effect.is(StateEffect.appendConfig)&&(conf=null,base2=asArray$2(base2).concat(effect.value));let startValues;conf?startValues=tr.startState.values.slice():(conf=Configuration.resolve(base2,compartments,this),startValues=new _EditorState2(conf,this.doc,this.selection,conf.dynamicSlots.map(()=>null),(state,slot)=>slot.reconfigure(state,this),null).values),new _EditorState2(conf,tr.newDoc,tr.newSelection,startValues,(state,slot)=>slot.update(state,tr),tr)}replaceSelection(text){return typeof text=="string"&&(text=this.toText(text)),this.changeByRange(range=>({changes:{from:range.from,to:range.to,insert:text},range:EditorSelection.cursor(range.from+text.length)}))}changeByRange(f){let sel=this.selection,result1=f(sel.ranges[0]),changes=this.changes(result1.changes),ranges=[result1.range],effects=asArray$2(result1.effects);for(let i=1;ifield.spec.fromJSON(value,state)))}}return _EditorState2.create({doc:json2.doc,selection:EditorSelection.fromJSON(json2.selection),extensions:config2.extensions?fieldInit.concat([config2.extensions]):fieldInit})}static create(config2={}){let configuration=Configuration.resolve(config2.extensions||[],new Map),doc2=config2.doc instanceof Text?config2.doc:Text.of((config2.doc||"").split(configuration.staticFacet(_EditorState2.lineSeparator)||DefaultSplit)),selection=config2.selection?config2.selection instanceof EditorSelection?config2.selection:EditorSelection.single(config2.selection.anchor,config2.selection.head):EditorSelection.single(0);return checkSelection(selection,doc2.length),configuration.staticFacet(allowMultipleSelections)||(selection=selection.asSingle()),new _EditorState2(configuration,doc2,selection,configuration.dynamicSlots.map(()=>null),(state,slot)=>slot.create(state),null)}get tabSize(){return this.facet(_EditorState2.tabSize)}get lineBreak(){return this.facet(_EditorState2.lineSeparator)||` -`}get readOnly(){return this.facet(readOnly)}phrase(phrase2,...insert2){for(let map2 of this.facet(_EditorState2.phrases))if(Object.prototype.hasOwnProperty.call(map2,phrase2)){phrase2=map2[phrase2];break}return insert2.length&&(phrase2=phrase2.replace(/\$(\$|\d*)/g,(m,i)=>{if(i=="$")return"$";let n2=+(i||1);return!n2||n2>insert2.length?m:insert2[n2-1]})),phrase2}languageDataAt(name2,pos,side=-1){let values=[];for(let provider of this.facet(languageData))for(let result of provider(this,pos,side))Object.prototype.hasOwnProperty.call(result,name2)&&values.push(result[name2]);return values}charCategorizer(at){return makeCategorizer(this.languageDataAt("wordChars",at).join(""))}wordAt(pos){let{text,from,length}=this.doc.lineAt(pos),cat=this.charCategorizer(pos),start=pos-from,end=pos-from;for(;start>0;){let prev=findClusterBreak(text,start,!1);if(cat(text.slice(prev,start))!=CharCategory.Word)break;start=prev}for(;endvalues.length?values[0]:4}),EditorState.lineSeparator=lineSeparator,EditorState.readOnly=readOnly,EditorState.phrases=Facet.define({compare(a,b){let kA=Object.keys(a),kB=Object.keys(b);return kA.length==kB.length&&kA.every(k=>a[k]==b[k])}}),EditorState.languageData=languageData,EditorState.changeFilter=changeFilter,EditorState.transactionFilter=transactionFilter,EditorState.transactionExtender=transactionExtender,Compartment.reconfigure=StateEffect.define();function combineConfig(configs,defaults2,combine={}){let result={};for(let config2 of configs)for(let key of Object.keys(config2)){let value=config2[key],current=result[key];if(current===void 0)result[key]=value;else if(!(current===value||value===void 0))if(Object.hasOwnProperty.call(combine,key))result[key]=combine[key](current,value);else throw new Error("Config merge conflict for field "+key)}for(let key in defaults2)result[key]===void 0&&(result[key]=defaults2[key]);return result}__name(combineConfig,"combineConfig"),__name2(combineConfig,"combineConfig");const _RangeValue=class{static{__name(this,"_RangeValue")}eq(other){return this==other}range(from,to=from){return Range$1.create(from,to,this)}};__name2(_RangeValue,"RangeValue");let RangeValue=_RangeValue;RangeValue.prototype.startSide=RangeValue.prototype.endSide=0,RangeValue.prototype.point=!1,RangeValue.prototype.mapMode=MapMode.TrackDel;let Range$1=(_a=class{static{__name(this,"_a")}constructor(from,to,value){this.from=from,this.to=to,this.value=value}static create(from,to,value){return new _a(from,to,value)}},__name2(_a,"Range"),_a);function cmpRange(a,b){return a.from-b.from||a.value.startSide-b.value.startSide}__name(cmpRange,"cmpRange"),__name2(cmpRange,"cmpRange");const _Chunk=class _Chunk2{static{__name(this,"_Chunk")}constructor(from,to,value,maxPoint){this.from=from,this.to=to,this.value=value,this.maxPoint=maxPoint}get length(){return this.to[this.to.length-1]}findIndex(pos,side,end,startAt=0){let arr=end?this.to:this.from;for(let lo=startAt,hi=arr.length;;){if(lo==hi)return lo;let mid=lo+hi>>1,diff2=arr[mid]-pos||(end?this.value[mid].endSide:this.value[mid].startSide)-side;if(mid==lo)return diff2>=0?lo:hi;diff2>=0?hi=mid:lo=mid+1}}between(offset2,from,to,f){for(let i=this.findIndex(from,-1e9,!0),e=this.findIndex(to,1e9,!1,i);inewTo||newFrom==newTo&&val.startSide>0&&val.endSide<=0)continue;(newTo-newFrom||val.endSide-val.startSide)<0||(newPos<0&&(newPos=newFrom),val.point&&(maxPoint=Math.max(maxPoint,newTo-newFrom)),value.push(val),from.push(newFrom-newPos),to.push(newTo-newPos))}return{mapped:value.length?new _Chunk2(from,to,value,maxPoint):null,pos:newPos}}};__name2(_Chunk,"Chunk");let Chunk=_Chunk;const _RangeSet=class _RangeSet2{static{__name(this,"_RangeSet")}constructor(chunkPos,chunk,nextLayer,maxPoint){this.chunkPos=chunkPos,this.chunk=chunk,this.nextLayer=nextLayer,this.maxPoint=maxPoint}static create(chunkPos,chunk,nextLayer,maxPoint){return new _RangeSet2(chunkPos,chunk,nextLayer,maxPoint)}get length(){let last2=this.chunk.length-1;return last2<0?0:Math.max(this.chunkEnd(last2),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let size=this.nextLayer.size;for(let chunk of this.chunk)size+=chunk.value.length;return size}chunkEnd(index2){return this.chunkPos[index2]+this.chunk[index2].length}update(updateSpec){let{add:add2=[],sort:sort2=!1,filterFrom=0,filterTo=this.length}=updateSpec,filter2=updateSpec.filter;if(add2.length==0&&!filter2)return this;if(sort2&&(add2=add2.slice().sort(cmpRange)),this.isEmpty)return add2.length?_RangeSet2.of(add2):this;let cur2=new LayerCursor(this,null,-1).goto(0),i=0,spill=[],builder=new RangeSetBuilder;for(;cur2.value||i=0){let range=add2[i++];builder.addInner(range.from,range.to,range.value)||spill.push(range)}else cur2.rangeIndex==1&&cur2.chunkIndexthis.chunkEnd(cur2.chunkIndex)||filterTocur2.to||filterTo=start&&from<=start+chunk.length&&chunk.between(start,from-start,to-start,f)===!1)return}this.nextLayer.between(from,to,f)}}iter(from=0){return HeapCursor.from([this]).goto(from)}get isEmpty(){return this.nextLayer==this}static iter(sets,from=0){return HeapCursor.from(sets).goto(from)}static compare(oldSets,newSets,textDiff,comparator,minPointSize=-1){let a=oldSets.filter(set=>set.maxPoint>0||!set.isEmpty&&set.maxPoint>=minPointSize),b=newSets.filter(set=>set.maxPoint>0||!set.isEmpty&&set.maxPoint>=minPointSize),sharedChunks=findSharedChunks(a,b,textDiff),sideA=new SpanCursor(a,sharedChunks,minPointSize),sideB=new SpanCursor(b,sharedChunks,minPointSize);textDiff.iterGaps((fromA,fromB,length)=>compare(sideA,fromA,sideB,fromB,length,comparator)),textDiff.empty&&textDiff.length==0&&compare(sideA,0,sideB,0,0,comparator)}static eq(oldSets,newSets,from=0,to){to==null&&(to=1e9-1);let a=oldSets.filter(set=>!set.isEmpty&&newSets.indexOf(set)<0),b=newSets.filter(set=>!set.isEmpty&&oldSets.indexOf(set)<0);if(a.length!=b.length)return!1;if(!a.length)return!0;let sharedChunks=findSharedChunks(a,b),sideA=new SpanCursor(a,sharedChunks,0).goto(from),sideB=new SpanCursor(b,sharedChunks,0).goto(from);for(;;){if(sideA.to!=sideB.to||!sameValues(sideA.active,sideB.active)||sideA.point&&(!sideB.point||!sideA.point.eq(sideB.point)))return!1;if(sideA.to>to)return!0;sideA.next(),sideB.next()}}static spans(sets,from,to,iterator,minPointSize=-1){let cursor=new SpanCursor(sets,null,minPointSize).goto(from),pos=from,openRanges=cursor.openStart;for(;;){let curTo=Math.min(cursor.to,to);if(cursor.point){let active=cursor.activeForPoint(cursor.to),openCount=cursor.pointFrompos&&(iterator.span(pos,curTo,cursor.active,openRanges),openRanges=cursor.openEnd(curTo));if(cursor.to>to)return openRanges+(cursor.point&&cursor.to>to?1:0);pos=cursor.to,cursor.next()}}static of(ranges,sort2=!1){let build=new RangeSetBuilder;for(let range of ranges instanceof Range$1?[ranges]:sort2?lazySort(ranges):ranges)build.add(range.from,range.to,range.value);return build.finish()}};__name2(_RangeSet,"RangeSet");let RangeSet=_RangeSet;RangeSet.empty=new RangeSet([],[],null,-1);function lazySort(ranges){if(ranges.length>1)for(let prev=ranges[0],i=1;i0)return ranges.slice().sort(cmpRange);prev=cur2}return ranges}__name(lazySort,"lazySort"),__name2(lazySort,"lazySort"),RangeSet.empty.nextLayer=RangeSet.empty;const _RangeSetBuilder=class _RangeSetBuilder2{static{__name(this,"_RangeSetBuilder")}finishChunk(newArrays){this.chunks.push(new Chunk(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,newArrays&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(from,to,value){this.addInner(from,to,value)||(this.nextLayer||(this.nextLayer=new _RangeSetBuilder2)).add(from,to,value)}addInner(from,to,value){let diff2=from-this.lastTo||value.startSide-this.last.endSide;if(diff2<=0&&(from-this.lastFrom||value.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return diff2<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=from),this.from.push(from-this.chunkStart),this.to.push(to-this.chunkStart),this.last=value,this.lastFrom=from,this.lastTo=to,this.value.push(value),value.point&&(this.maxPoint=Math.max(this.maxPoint,to-from)),!0)}addChunk(from,chunk){if((from-this.lastTo||chunk.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,chunk.maxPoint),this.chunks.push(chunk),this.chunkPos.push(from);let last2=chunk.value.length-1;return this.last=chunk.value[last2],this.lastFrom=chunk.from[last2]+from,this.lastTo=chunk.to[last2]+from,!0}finish(){return this.finishInner(RangeSet.empty)}finishInner(next){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return next;let result=RangeSet.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(next):next,this.setMaxPoint);return this.from=null,result}};__name2(_RangeSetBuilder,"RangeSetBuilder");let RangeSetBuilder=_RangeSetBuilder;function findSharedChunks(a,b,textDiff){let inA=new Map;for(let set of a)for(let i=0;i=this.minPoint)break}}setRangeIndex(index2){if(index2==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=minPoint&&heap.push(new LayerCursor(cur2,skip,minPoint,i));return heap.length==1?heap[0]:new _HeapCursor2(heap)}get startSide(){return this.value?this.value.startSide:0}goto(pos,side=-1e9){for(let cur2 of this.heap)cur2.goto(pos,side);for(let i=this.heap.length>>1;i>=0;i--)heapBubble(this.heap,i);return this.next(),this}forward(pos,side){for(let cur2 of this.heap)cur2.forward(pos,side);for(let i=this.heap.length>>1;i>=0;i--)heapBubble(this.heap,i);(this.to-pos||this.value.endSide-side)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let top2=this.heap[0];this.from=top2.from,this.to=top2.to,this.value=top2.value,this.rank=top2.rank,top2.value&&top2.next(),heapBubble(this.heap,0)}}};__name2(_HeapCursor,"HeapCursor");let HeapCursor=_HeapCursor;function heapBubble(heap,index2){for(let cur2=heap[index2];;){let childIndex=(index2<<1)+1;if(childIndex>=heap.length)break;let child=heap[childIndex];if(childIndex+1=0&&(child=heap[childIndex+1],childIndex++),cur2.compare(child)<0)break;heap[childIndex]=cur2,heap[index2]=child,index2=childIndex}}__name(heapBubble,"heapBubble"),__name2(heapBubble,"heapBubble");const _SpanCursor=class{static{__name(this,"_SpanCursor")}constructor(sets,skip,minPoint){this.minPoint=minPoint,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=HeapCursor.from(sets,skip,minPoint)}goto(pos,side=-1e9){return this.cursor.goto(pos,side),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=pos,this.endSide=side,this.openStart=-1,this.next(),this}forward(pos,side){for(;this.minActive>-1&&(this.activeTo[this.minActive]-pos||this.active[this.minActive].endSide-side)<0;)this.removeActive(this.minActive);this.cursor.forward(pos,side)}removeActive(index2){remove$1(this.active,index2),remove$1(this.activeTo,index2),remove$1(this.activeRank,index2),this.minActive=findMinIndex(this.active,this.activeTo)}addActive(trackOpen){let i=0,{value,to,rank}=this.cursor;for(;i-1&&(this.activeTo[a]-this.cursor.from||this.active[a].endSide-this.cursor.startSide)<0){if(this.activeTo[a]>from){this.to=this.activeTo[a],this.endSide=this.active[a].endSide;break}this.removeActive(a),trackOpen&&remove$1(trackOpen,a)}else if(this.cursor.value)if(this.cursor.from>from){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let nextVal=this.cursor.value;if(!nextVal.point)this.addActive(trackOpen),this.cursor.next();else if(wasPoint&&this.cursor.to==this.to&&this.cursor.from=0&&trackOpen[i]=0&&!(this.activeRank[i]to||this.activeTo[i]==to&&this.active[i].endSide>=this.point.endSide)&&active.push(this.active[i]);return active.reverse()}openEnd(to){let open=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>to;i--)open++;return open}};__name2(_SpanCursor,"SpanCursor");let SpanCursor=_SpanCursor;function compare(a,startA,b,startB,length,comparator){a.goto(startA),b.goto(startB);let endB=startB+length,pos=startB,dPos=startB-startA;for(;;){let diff2=a.to+dPos-b.to||a.endSide-b.endSide,end=diff2<0?a.to+dPos:b.to,clipEnd=Math.min(end,endB);if(a.point||b.point?a.point&&b.point&&(a.point==b.point||a.point.eq(b.point))&&sameValues(a.activeForPoint(a.to),b.activeForPoint(b.to))||comparator.comparePoint(pos,clipEnd,a.point,b.point):clipEnd>pos&&!sameValues(a.active,b.active)&&comparator.compareRange(pos,clipEnd,a.active,b.active),end>endB)break;pos=end,diff2<=0&&a.next(),diff2>=0&&b.next()}}__name(compare,"compare"),__name2(compare,"compare");function sameValues(a,b){if(a.length!=b.length)return!1;for(let i=0;i=index2;i--)array[i+1]=array[i];array[index2]=value}__name(insert,"insert"),__name2(insert,"insert");function findMinIndex(value,array){let found=-1,foundPos=1e9;for(let i=0;i=col)return i;if(i==string2.length)break;n2+=string2.charCodeAt(i)==9?tabSize-n2%tabSize:1,i=findClusterBreak(string2,i)}return strict===!0?-1:string2.length}__name(findColumn,"findColumn"),__name2(findColumn,"findColumn");const C="\u037C",COUNT=typeof Symbol>"u"?"__"+C:Symbol.for(C),SET=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),top=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},_StyleModule=class{static{__name(this,"_StyleModule")}constructor(spec,options){this.rules=[];let{finish}=options||{};function splitSelector(selector){return/^@/.test(selector)?[selector]:selector.split(/,\s*/)}__name(splitSelector,"splitSelector"),__name2(splitSelector,"splitSelector");function render(selectors,spec2,target,isKeyframes){let local=[],isAt=/^@(\w+)\b/.exec(selectors[0]),keyframes=isAt&&isAt[1]=="keyframes";if(isAt&&spec2==null)return target.push(selectors[0]+";");for(let prop in spec2){let value=spec2[prop];if(/&/.test(prop))render(prop.split(/,\s*/).map(part=>selectors.map(sel=>part.replace(/&/,sel))).reduce((a,b)=>a.concat(b)),value,target);else if(value&&typeof value=="object"){if(!isAt)throw new RangeError("The value of a property ("+prop+") should be a primitive value.");render(splitSelector(prop),value,local,keyframes)}else value!=null&&local.push(prop.replace(/_.*/,"").replace(/[A-Z]/g,l2=>"-"+l2.toLowerCase())+": "+value+";")}(local.length||keyframes)&&target.push((finish&&!isAt&&!isKeyframes?selectors.map(finish):selectors).join(", ")+" {"+local.join(" ")+"}")}__name(render,"render"),__name2(render,"render");for(let prop in spec)render(splitSelector(prop),spec[prop],this.rules)}getRules(){return this.rules.join(` +`}get readOnly(){return this.facet(readOnly)}phrase(phrase2,...insert2){for(let map2 of this.facet(_EditorState2.phrases))if(Object.prototype.hasOwnProperty.call(map2,phrase2)){phrase2=map2[phrase2];break}return insert2.length&&(phrase2=phrase2.replace(/\$(\$|\d*)/g,(m,i)=>{if(i=="$")return"$";let n2=+(i||1);return!n2||n2>insert2.length?m:insert2[n2-1]})),phrase2}languageDataAt(name2,pos,side=-1){let values=[];for(let provider of this.facet(languageData))for(let result of provider(this,pos,side))Object.prototype.hasOwnProperty.call(result,name2)&&values.push(result[name2]);return values}charCategorizer(at){return makeCategorizer(this.languageDataAt("wordChars",at).join(""))}wordAt(pos){let{text,from,length}=this.doc.lineAt(pos),cat=this.charCategorizer(pos),start=pos-from,end=pos-from;for(;start>0;){let prev=findClusterBreak(text,start,!1);if(cat(text.slice(prev,start))!=CharCategory.Word)break;start=prev}for(;endvalues.length?values[0]:4}),EditorState.lineSeparator=lineSeparator,EditorState.readOnly=readOnly,EditorState.phrases=Facet.define({compare(a,b){let kA=Object.keys(a),kB=Object.keys(b);return kA.length==kB.length&&kA.every(k=>a[k]==b[k])}}),EditorState.languageData=languageData,EditorState.changeFilter=changeFilter,EditorState.transactionFilter=transactionFilter,EditorState.transactionExtender=transactionExtender,Compartment.reconfigure=StateEffect.define();function combineConfig(configs,defaults2,combine={}){let result={};for(let config2 of configs)for(let key of Object.keys(config2)){let value=config2[key],current=result[key];if(current===void 0)result[key]=value;else if(!(current===value||value===void 0))if(Object.hasOwnProperty.call(combine,key))result[key]=combine[key](current,value);else throw new Error("Config merge conflict for field "+key)}for(let key in defaults2)result[key]===void 0&&(result[key]=defaults2[key]);return result}__name(combineConfig,"combineConfig"),__name2(combineConfig,"combineConfig");const _RangeValue=class{static{__name(this,"_RangeValue")}eq(other){return this==other}range(from,to=from){return Range$1.create(from,to,this)}};__name2(_RangeValue,"RangeValue");let RangeValue=_RangeValue;RangeValue.prototype.startSide=RangeValue.prototype.endSide=0,RangeValue.prototype.point=!1,RangeValue.prototype.mapMode=MapMode.TrackDel;let Range$1=(_a=class{static{__name(this,"_a")}constructor(from,to,value){this.from=from,this.to=to,this.value=value}static create(from,to,value){return new _a(from,to,value)}},__name2(_a,"Range"),_a);function cmpRange(a,b){return a.from-b.from||a.value.startSide-b.value.startSide}__name(cmpRange,"cmpRange"),__name2(cmpRange,"cmpRange");const _Chunk=class _Chunk2{static{__name(this,"_Chunk")}constructor(from,to,value,maxPoint){this.from=from,this.to=to,this.value=value,this.maxPoint=maxPoint}get length(){return this.to[this.to.length-1]}findIndex(pos,side,end,startAt=0){let arr=end?this.to:this.from;for(let lo=startAt,hi=arr.length;;){if(lo==hi)return lo;let mid=lo+hi>>1,diff2=arr[mid]-pos||(end?this.value[mid].endSide:this.value[mid].startSide)-side;if(mid==lo)return diff2>=0?lo:hi;diff2>=0?hi=mid:lo=mid+1}}between(offset2,from,to,f){for(let i=this.findIndex(from,-1e9,!0),e=this.findIndex(to,1e9,!1,i);inewTo||newFrom==newTo&&val.startSide>0&&val.endSide<=0)continue;(newTo-newFrom||val.endSide-val.startSide)<0||(newPos<0&&(newPos=newFrom),val.point&&(maxPoint=Math.max(maxPoint,newTo-newFrom)),value.push(val),from.push(newFrom-newPos),to.push(newTo-newPos))}return{mapped:value.length?new _Chunk2(from,to,value,maxPoint):null,pos:newPos}}};__name2(_Chunk,"Chunk");let Chunk=_Chunk;const _RangeSet=class _RangeSet2{static{__name(this,"_RangeSet")}constructor(chunkPos,chunk,nextLayer,maxPoint){this.chunkPos=chunkPos,this.chunk=chunk,this.nextLayer=nextLayer,this.maxPoint=maxPoint}static create(chunkPos,chunk,nextLayer,maxPoint){return new _RangeSet2(chunkPos,chunk,nextLayer,maxPoint)}get length(){let last2=this.chunk.length-1;return last2<0?0:Math.max(this.chunkEnd(last2),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let size=this.nextLayer.size;for(let chunk of this.chunk)size+=chunk.value.length;return size}chunkEnd(index2){return this.chunkPos[index2]+this.chunk[index2].length}update(updateSpec){let{add:add2=[],sort:sort2=!1,filterFrom=0,filterTo=this.length}=updateSpec,filter2=updateSpec.filter;if(add2.length==0&&!filter2)return this;if(sort2&&(add2=add2.slice().sort(cmpRange)),this.isEmpty)return add2.length?_RangeSet2.of(add2):this;let cur2=new LayerCursor(this,null,-1).goto(0),i=0,spill=[],builder=new RangeSetBuilder;for(;cur2.value||i=0){let range=add2[i++];builder.addInner(range.from,range.to,range.value)||spill.push(range)}else cur2.rangeIndex==1&&cur2.chunkIndexthis.chunkEnd(cur2.chunkIndex)||filterTocur2.to||filterTo=start&&from<=start+chunk.length&&chunk.between(start,from-start,to-start,f)===!1)return}this.nextLayer.between(from,to,f)}}iter(from=0){return HeapCursor.from([this]).goto(from)}get isEmpty(){return this.nextLayer==this}static iter(sets,from=0){return HeapCursor.from(sets).goto(from)}static compare(oldSets,newSets,textDiff,comparator,minPointSize=-1){let a=oldSets.filter(set=>set.maxPoint>0||!set.isEmpty&&set.maxPoint>=minPointSize),b=newSets.filter(set=>set.maxPoint>0||!set.isEmpty&&set.maxPoint>=minPointSize),sharedChunks=findSharedChunks(a,b,textDiff),sideA=new SpanCursor(a,sharedChunks,minPointSize),sideB=new SpanCursor(b,sharedChunks,minPointSize);textDiff.iterGaps((fromA,fromB,length)=>compare(sideA,fromA,sideB,fromB,length,comparator)),textDiff.empty&&textDiff.length==0&&compare(sideA,0,sideB,0,0,comparator)}static eq(oldSets,newSets,from=0,to){to==null&&(to=1e9-1);let a=oldSets.filter(set=>!set.isEmpty&&newSets.indexOf(set)<0),b=newSets.filter(set=>!set.isEmpty&&oldSets.indexOf(set)<0);if(a.length!=b.length)return!1;if(!a.length)return!0;let sharedChunks=findSharedChunks(a,b),sideA=new SpanCursor(a,sharedChunks,0).goto(from),sideB=new SpanCursor(b,sharedChunks,0).goto(from);for(;;){if(sideA.to!=sideB.to||!sameValues(sideA.active,sideB.active)||sideA.point&&(!sideB.point||!sideA.point.eq(sideB.point)))return!1;if(sideA.to>to)return!0;sideA.next(),sideB.next()}}static spans(sets,from,to,iterator,minPointSize=-1){let cursor=new SpanCursor(sets,null,minPointSize).goto(from),pos=from,openRanges=cursor.openStart;for(;;){let curTo=Math.min(cursor.to,to);if(cursor.point){let active=cursor.activeForPoint(cursor.to),openCount=cursor.pointFrompos&&(iterator.span(pos,curTo,cursor.active,openRanges),openRanges=cursor.openEnd(curTo));if(cursor.to>to)return openRanges+(cursor.point&&cursor.to>to?1:0);pos=cursor.to,cursor.next()}}static of(ranges,sort2=!1){let build=new RangeSetBuilder;for(let range of ranges instanceof Range$1?[ranges]:sort2?lazySort(ranges):ranges)build.add(range.from,range.to,range.value);return build.finish()}};__name2(_RangeSet,"RangeSet");let RangeSet=_RangeSet;RangeSet.empty=new RangeSet([],[],null,-1);function lazySort(ranges){if(ranges.length>1)for(let prev=ranges[0],i=1;i0)return ranges.slice().sort(cmpRange);prev=cur2}return ranges}__name(lazySort,"lazySort"),__name2(lazySort,"lazySort"),RangeSet.empty.nextLayer=RangeSet.empty;const _RangeSetBuilder=class _RangeSetBuilder2{static{__name(this,"_RangeSetBuilder")}finishChunk(newArrays){this.chunks.push(new Chunk(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,newArrays&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(from,to,value){this.addInner(from,to,value)||(this.nextLayer||(this.nextLayer=new _RangeSetBuilder2)).add(from,to,value)}addInner(from,to,value){let diff2=from-this.lastTo||value.startSide-this.last.endSide;if(diff2<=0&&(from-this.lastFrom||value.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return diff2<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=from),this.from.push(from-this.chunkStart),this.to.push(to-this.chunkStart),this.last=value,this.lastFrom=from,this.lastTo=to,this.value.push(value),value.point&&(this.maxPoint=Math.max(this.maxPoint,to-from)),!0)}addChunk(from,chunk){if((from-this.lastTo||chunk.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,chunk.maxPoint),this.chunks.push(chunk),this.chunkPos.push(from);let last2=chunk.value.length-1;return this.last=chunk.value[last2],this.lastFrom=chunk.from[last2]+from,this.lastTo=chunk.to[last2]+from,!0}finish(){return this.finishInner(RangeSet.empty)}finishInner(next){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return next;let result=RangeSet.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(next):next,this.setMaxPoint);return this.from=null,result}};__name2(_RangeSetBuilder,"RangeSetBuilder");let RangeSetBuilder=_RangeSetBuilder;function findSharedChunks(a,b,textDiff){let inA=new Map;for(let set of a)for(let i=0;i=this.minPoint)break}}setRangeIndex(index2){if(index2==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=minPoint&&heap.push(new LayerCursor(cur2,skip,minPoint,i));return heap.length==1?heap[0]:new _HeapCursor2(heap)}get startSide(){return this.value?this.value.startSide:0}goto(pos,side=-1e9){for(let cur2 of this.heap)cur2.goto(pos,side);for(let i=this.heap.length>>1;i>=0;i--)heapBubble(this.heap,i);return this.next(),this}forward(pos,side){for(let cur2 of this.heap)cur2.forward(pos,side);for(let i=this.heap.length>>1;i>=0;i--)heapBubble(this.heap,i);(this.to-pos||this.value.endSide-side)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let top2=this.heap[0];this.from=top2.from,this.to=top2.to,this.value=top2.value,this.rank=top2.rank,top2.value&&top2.next(),heapBubble(this.heap,0)}}};__name2(_HeapCursor,"HeapCursor");let HeapCursor=_HeapCursor;function heapBubble(heap,index2){for(let cur2=heap[index2];;){let childIndex=(index2<<1)+1;if(childIndex>=heap.length)break;let child=heap[childIndex];if(childIndex+1=0&&(child=heap[childIndex+1],childIndex++),cur2.compare(child)<0)break;heap[childIndex]=cur2,heap[index2]=child,index2=childIndex}}__name(heapBubble,"heapBubble"),__name2(heapBubble,"heapBubble");const _SpanCursor=class{static{__name(this,"_SpanCursor")}constructor(sets,skip,minPoint){this.minPoint=minPoint,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=HeapCursor.from(sets,skip,minPoint)}goto(pos,side=-1e9){return this.cursor.goto(pos,side),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=pos,this.endSide=side,this.openStart=-1,this.next(),this}forward(pos,side){for(;this.minActive>-1&&(this.activeTo[this.minActive]-pos||this.active[this.minActive].endSide-side)<0;)this.removeActive(this.minActive);this.cursor.forward(pos,side)}removeActive(index2){remove(this.active,index2),remove(this.activeTo,index2),remove(this.activeRank,index2),this.minActive=findMinIndex(this.active,this.activeTo)}addActive(trackOpen){let i=0,{value,to,rank}=this.cursor;for(;i-1&&(this.activeTo[a]-this.cursor.from||this.active[a].endSide-this.cursor.startSide)<0){if(this.activeTo[a]>from){this.to=this.activeTo[a],this.endSide=this.active[a].endSide;break}this.removeActive(a),trackOpen&&remove(trackOpen,a)}else if(this.cursor.value)if(this.cursor.from>from){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let nextVal=this.cursor.value;if(!nextVal.point)this.addActive(trackOpen),this.cursor.next();else if(wasPoint&&this.cursor.to==this.to&&this.cursor.from=0&&trackOpen[i]=0&&!(this.activeRank[i]to||this.activeTo[i]==to&&this.active[i].endSide>=this.point.endSide)&&active.push(this.active[i]);return active.reverse()}openEnd(to){let open=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>to;i--)open++;return open}};__name2(_SpanCursor,"SpanCursor");let SpanCursor=_SpanCursor;function compare(a,startA,b,startB,length,comparator){a.goto(startA),b.goto(startB);let endB=startB+length,pos=startB,dPos=startB-startA;for(;;){let diff2=a.to+dPos-b.to||a.endSide-b.endSide,end=diff2<0?a.to+dPos:b.to,clipEnd=Math.min(end,endB);if(a.point||b.point?a.point&&b.point&&(a.point==b.point||a.point.eq(b.point))&&sameValues(a.activeForPoint(a.to),b.activeForPoint(b.to))||comparator.comparePoint(pos,clipEnd,a.point,b.point):clipEnd>pos&&!sameValues(a.active,b.active)&&comparator.compareRange(pos,clipEnd,a.active,b.active),end>endB)break;pos=end,diff2<=0&&a.next(),diff2>=0&&b.next()}}__name(compare,"compare"),__name2(compare,"compare");function sameValues(a,b){if(a.length!=b.length)return!1;for(let i=0;i=index2;i--)array[i+1]=array[i];array[index2]=value}__name(insert,"insert"),__name2(insert,"insert");function findMinIndex(value,array){let found=-1,foundPos=1e9;for(let i=0;i=col)return i;if(i==string2.length)break;n2+=string2.charCodeAt(i)==9?tabSize-n2%tabSize:1,i=findClusterBreak(string2,i)}return strict===!0?-1:string2.length}__name(findColumn,"findColumn"),__name2(findColumn,"findColumn");const C="\u037C",COUNT=typeof Symbol>"u"?"__"+C:Symbol.for(C),SET=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),top=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},_StyleModule=class{static{__name(this,"_StyleModule")}constructor(spec,options){this.rules=[];let{finish}=options||{};function splitSelector(selector){return/^@/.test(selector)?[selector]:selector.split(/,\s*/)}__name(splitSelector,"splitSelector"),__name2(splitSelector,"splitSelector");function render(selectors,spec2,target,isKeyframes){let local=[],isAt=/^@(\w+)\b/.exec(selectors[0]),keyframes=isAt&&isAt[1]=="keyframes";if(isAt&&spec2==null)return target.push(selectors[0]+";");for(let prop in spec2){let value=spec2[prop];if(/&/.test(prop))render(prop.split(/,\s*/).map(part=>selectors.map(sel=>part.replace(/&/,sel))).reduce((a,b)=>a.concat(b)),value,target);else if(value&&typeof value=="object"){if(!isAt)throw new RangeError("The value of a property ("+prop+") should be a primitive value.");render(splitSelector(prop),value,local,keyframes)}else value!=null&&local.push(prop.replace(/_.*/,"").replace(/[A-Z]/g,l2=>"-"+l2.toLowerCase())+": "+value+";")}(local.length||keyframes)&&target.push((finish&&!isAt&&!isKeyframes?selectors.map(finish):selectors).join(", ")+" {"+local.join(" ")+"}")}__name(render,"render"),__name2(render,"render");for(let prop in spec)render(splitSelector(prop),spec[prop],this.rules)}getRules(){return this.rules.join(` `)}static newName(){let id=top[COUNT]||1;return top[COUNT]=id+1,C+id.toString(36)}static mount(root,modules,options){let set=root[SET],nonce=options&&options.nonce;set?nonce&&set.setNonce(nonce):set=new StyleSet(root,nonce),set.mount(Array.isArray(modules)?modules:[modules])}};__name2(_StyleModule,"StyleModule");let StyleModule=_StyleModule,adoptedSet=new Map;const _StyleSet=class{static{__name(this,"_StyleSet")}constructor(root,nonce){let doc2=root.ownerDocument||root,win=doc2.defaultView;if(!root.head&&root.adoptedStyleSheets&&win.CSSStyleSheet){let adopted=adoptedSet.get(doc2);if(adopted)return root.adoptedStyleSheets=[adopted.sheet,...root.adoptedStyleSheets],root[SET]=adopted;this.sheet=new win.CSSStyleSheet,root.adoptedStyleSheets=[this.sheet,...root.adoptedStyleSheets],adoptedSet.set(doc2,this)}else{this.styleTag=doc2.createElement("style"),nonce&&this.styleTag.setAttribute("nonce",nonce);let target=root.head||root;target.insertBefore(this.styleTag,target.firstChild)}this.modules=[],root[SET]=this}mount(modules){let sheet=this.sheet,pos=0,j=0;for(let i=0;i-1&&(this.modules.splice(index2,1),j--,index2=-1),index2==-1){if(this.modules.splice(j++,0,mod),sheet)for(let k=0;k",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},mac=typeof navigator<"u"&&/Mac/.test(navigator.platform),ie$1=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),i=0;i<10;i++)base[48+i]=base[96+i]=String(i);for(var i=1;i<=24;i++)base[i+111]="F"+i;for(var i=65;i<=90;i++)base[i]=String.fromCharCode(i+32),shift[i]=String.fromCharCode(i);for(var code in base)shift.hasOwnProperty(code)||(shift[code]=base[code]);function keyName(event){var ignoreKey=mac&&event.metaKey&&event.shiftKey&&!event.ctrlKey&&!event.altKey||ie$1&&event.shiftKey&&event.key&&event.key.length==1||event.key=="Unidentified",name2=!ignoreKey&&event.key||(event.shiftKey?shift:base)[event.keyCode]||event.key||"Unidentified";return name2=="Esc"&&(name2="Escape"),name2=="Del"&&(name2="Delete"),name2=="Left"&&(name2="ArrowLeft"),name2=="Up"&&(name2="ArrowUp"),name2=="Right"&&(name2="ArrowRight"),name2=="Down"&&(name2="ArrowDown"),name2}__name(keyName,"keyName"),__name2(keyName,"keyName");function getSelection(root){let target;return root.nodeType==11?target=root.getSelection?root:root.ownerDocument:target=root,target.getSelection()}__name(getSelection,"getSelection"),__name2(getSelection,"getSelection");function contains(dom,node){return node?dom==node||dom.contains(node.nodeType!=1?node.parentNode:node):!1}__name(contains,"contains"),__name2(contains,"contains");function deepActiveElement(doc2){let elt=doc2.activeElement;for(;elt&&elt.shadowRoot;)elt=elt.shadowRoot.activeElement;return elt}__name(deepActiveElement,"deepActiveElement"),__name2(deepActiveElement,"deepActiveElement");function hasSelection(dom,selection){if(!selection.anchorNode)return!1;try{return contains(dom,selection.anchorNode)}catch{return!1}}__name(hasSelection,"hasSelection"),__name2(hasSelection,"hasSelection");function clientRectsFor(dom){return dom.nodeType==3?textRange(dom,0,dom.nodeValue.length).getClientRects():dom.nodeType==1?dom.getClientRects():[]}__name(clientRectsFor,"clientRectsFor"),__name2(clientRectsFor,"clientRectsFor");function isEquivalentPosition(node,off2,targetNode,targetOff){return targetNode?scanFor(node,off2,targetNode,targetOff,-1)||scanFor(node,off2,targetNode,targetOff,1):!1}__name(isEquivalentPosition,"isEquivalentPosition"),__name2(isEquivalentPosition,"isEquivalentPosition");function domIndex(node){for(var index2=0;;index2++)if(node=node.previousSibling,!node)return index2}__name(domIndex,"domIndex"),__name2(domIndex,"domIndex");function scanFor(node,off2,targetNode,targetOff,dir){for(;;){if(node==targetNode&&off2==targetOff)return!0;if(off2==(dir<0?0:maxOffset(node))){if(node.nodeName=="DIV")return!1;let parent=node.parentNode;if(!parent||parent.nodeType!=1)return!1;off2=domIndex(node)+(dir<0?0:1),node=parent}else if(node.nodeType==1){if(node=node.childNodes[off2+(dir<0?-1:0)],node.nodeType==1&&node.contentEditable=="false")return!1;off2=dir<0?maxOffset(node):0}else return!1}}__name(scanFor,"scanFor"),__name2(scanFor,"scanFor");function maxOffset(node){return node.nodeType==3?node.nodeValue.length:node.childNodes.length}__name(maxOffset,"maxOffset"),__name2(maxOffset,"maxOffset");function flattenRect(rect,left){let x=left?rect.left:rect.right;return{left:x,right:x,top:rect.top,bottom:rect.bottom}}__name(flattenRect,"flattenRect"),__name2(flattenRect,"flattenRect");function windowRect(win){return{left:0,right:win.innerWidth,top:0,bottom:win.innerHeight}}__name(windowRect,"windowRect"),__name2(windowRect,"windowRect");function scrollRectIntoView(dom,rect,side,x,y,xMargin,yMargin,ltr){let doc2=dom.ownerDocument,win=doc2.defaultView||window;for(let cur2=dom,stop=!1;cur2&&!stop;)if(cur2.nodeType==1){let bounding,top2=cur2==doc2.body,scaleX=1,scaleY=1;if(top2)bounding=windowRect(win);else{if(/^(fixed|sticky)$/.test(getComputedStyle(cur2).position)&&(stop=!0),cur2.scrollHeight<=cur2.clientHeight&&cur2.scrollWidth<=cur2.clientWidth){cur2=cur2.assignedSlot||cur2.parentNode;continue}let rect2=cur2.getBoundingClientRect();scaleX=rect2.width/cur2.offsetWidth,scaleY=rect2.height/cur2.offsetHeight,bounding={left:rect2.left,right:rect2.left+cur2.clientWidth*scaleX,top:rect2.top,bottom:rect2.top+cur2.clientHeight*scaleY}}let moveX=0,moveY=0;if(y=="nearest")rect.top0&&rect.bottom>bounding.bottom+moveY&&(moveY=rect.bottom-bounding.bottom+moveY+yMargin)):rect.bottom>bounding.bottom&&(moveY=rect.bottom-bounding.bottom+yMargin,side<0&&rect.top-moveY0&&rect.right>bounding.right+moveX&&(moveX=rect.right-bounding.right+moveX+xMargin)):rect.right>bounding.right&&(moveX=rect.right-bounding.right+xMargin,side<0&&rect.leftcur2.clientHeight||cur2.scrollWidth>cur2.clientWidth)return cur2;cur2=cur2.assignedSlot||cur2.parentNode}else if(cur2.nodeType==11)cur2=cur2.host;else break;return null}__name(scrollableParent,"scrollableParent"),__name2(scrollableParent,"scrollableParent");const _DOMSelectionState=class{static{__name(this,"_DOMSelectionState")}constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(domSel){return this.anchorNode==domSel.anchorNode&&this.anchorOffset==domSel.anchorOffset&&this.focusNode==domSel.focusNode&&this.focusOffset==domSel.focusOffset}setRange(range){let{anchorNode,focusNode}=range;this.set(anchorNode,Math.min(range.anchorOffset,anchorNode?maxOffset(anchorNode):0),focusNode,Math.min(range.focusOffset,focusNode?maxOffset(focusNode):0))}set(anchorNode,anchorOffset,focusNode,focusOffset){this.anchorNode=anchorNode,this.anchorOffset=anchorOffset,this.focusNode=focusNode,this.focusOffset=focusOffset}};__name2(_DOMSelectionState,"DOMSelectionState");let DOMSelectionState=_DOMSelectionState,preventScrollSupported=null;function focusPreventScroll(dom){if(dom.setActive)return dom.setActive();if(preventScrollSupported)return dom.focus(preventScrollSupported);let stack=[];for(let cur2=dom;cur2&&(stack.push(cur2,cur2.scrollTop,cur2.scrollLeft),cur2!=cur2.ownerDocument);cur2=cur2.parentNode);if(dom.focus(preventScrollSupported==null?{get preventScroll(){return preventScrollSupported={preventScroll:!0},!0}}:void 0),!preventScrollSupported){preventScrollSupported=!1;for(let i=0;iMath.max(1,elt.scrollHeight-elt.clientHeight-4)}__name(isScrolledToBottom,"isScrolledToBottom"),__name2(isScrolledToBottom,"isScrolledToBottom");const _DOMPos=class _DOMPos2{static{__name(this,"_DOMPos")}constructor(node,offset2,precise=!0){this.node=node,this.offset=offset2,this.precise=precise}static before(dom,precise){return new _DOMPos2(dom.parentNode,domIndex(dom),precise)}static after(dom,precise){return new _DOMPos2(dom.parentNode,domIndex(dom)+1,precise)}};__name2(_DOMPos,"DOMPos");let DOMPos=_DOMPos;const noChildren=[],_ContentView=class _ContentView2{static{__name(this,"_ContentView")}constructor(){this.parent=null,this.dom=null,this.flags=2}get overrideDOMText(){return null}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(view){let pos=this.posAtStart;for(let child of this.children){if(child==view)return pos;pos+=child.length+child.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(view){return this.posBefore(view)+view.length}sync(view,track){if(this.flags&2){let parent=this.dom,prev=null,next;for(let child of this.children){if(child.flags&7){if(!child.dom&&(next=prev?prev.nextSibling:parent.firstChild)){let contentView=_ContentView2.get(next);(!contentView||!contentView.parent&&contentView.canReuseDOM(child))&&child.reuseDOM(next)}child.sync(view,track),child.flags&=-8}if(next=prev?prev.nextSibling:parent.firstChild,track&&!track.written&&track.node==parent&&next!=child.dom&&(track.written=!0),child.dom.parentNode==parent)for(;next&&next!=child.dom;)next=rm$1(next);else parent.insertBefore(child.dom,next);prev=child.dom}for(next=prev?prev.nextSibling:parent.firstChild,next&&track&&track.node==parent&&(track.written=!0);next;)next=rm$1(next)}else if(this.flags&1)for(let child of this.children)child.flags&7&&(child.sync(view,track),child.flags&=-8)}reuseDOM(_dom){}localPosFromDOM(node,offset2){let after;if(node==this.dom)after=this.dom.childNodes[offset2];else{let bias=maxOffset(node)==0?0:offset2==0?-1:1;for(;;){let parent=node.parentNode;if(parent==this.dom)break;bias==0&&parent.firstChild!=parent.lastChild&&(node==parent.firstChild?bias=-1:bias=1),node=parent}bias<0?after=node:after=node.nextSibling}if(after==this.dom.firstChild)return 0;for(;after&&!_ContentView2.get(after);)after=after.nextSibling;if(!after)return this.length;for(let i=0,pos=0;;i++){let child=this.children[i];if(child.dom==after)return pos;pos+=child.length+child.breakAfter}}domBoundsAround(from,to,offset2=0){let fromI=-1,fromStart=-1,toI=-1,toEnd=-1;for(let i=0,pos=offset2,prevEnd=offset2;ito)return child.domBoundsAround(from,to,pos);if(end>=from&&fromI==-1&&(fromI=i,fromStart=pos),pos>to&&child.dom.parentNode==this.dom){toI=i,toEnd=prevEnd;break}prevEnd=end,pos=end+child.breakAfter}return{from:fromStart,to:toEnd<0?offset2+this.length:toEnd,startDOM:(fromI?this.children[fromI-1].dom.nextSibling:null)||this.dom.firstChild,endDOM:toI=0?this.children[toI].dom:null}}markDirty(andParent=!1){this.flags|=2,this.markParentsDirty(andParent)}markParentsDirty(childList){for(let parent=this.parent;parent;parent=parent.parent){if(childList&&(parent.flags|=2),parent.flags&1)return;parent.flags|=1,childList=!1}}setParent(parent){this.parent!=parent&&(this.parent=parent,this.flags&7&&this.markParentsDirty(!0))}setDOM(dom){this.dom!=dom&&(this.dom&&(this.dom.cmView=null),this.dom=dom,dom.cmView=this)}get rootView(){for(let v=this;;){let parent=v.parent;if(!parent)return v;v=parent}}replaceChildren(from,to,children=noChildren){this.markDirty();for(let i=from;ithis.pos||pos==this.pos&&(bias>0||this.i==0||this.children[this.i-1].breakAfter))return this.off=pos-this.pos,this;let next=this.children[--this.i];this.pos-=next.length+next.breakAfter}}};__name2(_ChildCursor,"ChildCursor");let ChildCursor=_ChildCursor;function replaceRange(parent,fromI,fromOff,toI,toOff,insert2,breakAtStart,openStart,openEnd){let{children}=parent,before=children.length?children[fromI]:null,last2=insert2.length?insert2[insert2.length-1]:null,breakAtEnd=last2?last2.breakAfter:breakAtStart;if(!(fromI==toI&&before&&!breakAtStart&&!breakAtEnd&&insert2.length<2&&before.merge(fromOff,toOff,insert2.length?last2:null,fromOff==0,openStart,openEnd))){if(toI0&&(!breakAtStart&&insert2.length&&before.merge(fromOff,before.length,insert2[0],!1,openStart,0)?before.breakAfter=insert2.shift().breakAfter:(fromOff2);var browser={mac:ios||/Mac/.test(nav.platform),windows:/Win/.test(nav.platform),linux:/Linux|X11/.test(nav.platform),ie,ie_version:ie_upto10?doc.documentMode||6:ie_11up?+ie_11up[1]:ie_edge?+ie_edge[1]:0,gecko,gecko_version:gecko?+(/Firefox\/(\d+)/.exec(nav.userAgent)||[0,0])[1]:0,chrome:!!chrome,chrome_version:chrome?+chrome[1]:0,ios,android:/Android\b/.test(nav.userAgent),webkit,safari,webkit_version:webkit?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0,tabSize:doc.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};const MaxJoinLen=256,_TextView=class _TextView2 extends ContentView{static{__name(this,"_TextView")}constructor(text){super(),this.text=text}get length(){return this.text.length}createDOM(textDOM){this.setDOM(textDOM||document.createTextNode(this.text))}sync(view,track){this.dom||this.createDOM(),this.dom.nodeValue!=this.text&&(track&&track.node==this.dom&&(track.written=!0),this.dom.nodeValue=this.text)}reuseDOM(dom){dom.nodeType==3&&this.createDOM(dom)}merge(from,to,source){return this.flags&8||source&&(!(source instanceof _TextView2)||this.length-(to-from)+source.length>MaxJoinLen||source.flags&8)?!1:(this.text=this.text.slice(0,from)+(source?source.text:"")+this.text.slice(to),this.markDirty(),!0)}split(from){let result=new _TextView2(this.text.slice(from));return this.text=this.text.slice(0,from),this.markDirty(),result.flags|=this.flags&8,result}localPosFromDOM(node,offset2){return node==this.dom?offset2:offset2?this.text.length:0}domAtPos(pos){return new DOMPos(this.dom,pos)}domBoundsAround(_from,_to,offset2){return{from:offset2,to:offset2+this.length,startDOM:this.dom,endDOM:this.dom.nextSibling}}coordsAt(pos,side){return textCoords(this.dom,pos,side)}};__name2(_TextView,"TextView");let TextView=_TextView;const _MarkView=class _MarkView2 extends ContentView{static{__name(this,"_MarkView")}constructor(mark,children=[],length=0){super(),this.mark=mark,this.children=children,this.length=length;for(let ch of children)ch.setParent(this)}setAttrs(dom){if(clearAttributes(dom),this.mark.class&&(dom.className=this.mark.class),this.mark.attrs)for(let name2 in this.mark.attrs)dom.setAttribute(name2,this.mark.attrs[name2]);return dom}canReuseDOM(other){return super.canReuseDOM(other)&&!((this.flags|other.flags)&8)}reuseDOM(node){node.nodeName==this.mark.tagName.toUpperCase()&&(this.setDOM(node),this.flags|=6)}sync(view,track){this.dom?this.flags&4&&this.setAttrs(this.dom):this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))),super.sync(view,track)}merge(from,to,source,_hasStart,openStart,openEnd){return source&&(!(source instanceof _MarkView2&&source.mark.eq(this.mark))||from&&openStart<=0||tofrom&&result.push(off2=from&&(detachFrom=i),off2=end,i++}let length=this.length-from;return this.length=from,detachFrom>-1&&(this.children.length=detachFrom,this.markDirty()),new _MarkView2(this.mark,result,length)}domAtPos(pos){return inlineDOMAtPos(this,pos)}coordsAt(pos,side){return coordsInChildren(this,pos,side)}};__name2(_MarkView,"MarkView");let MarkView=_MarkView;function textCoords(text,pos,side){let length=text.nodeValue.length;pos>length&&(pos=length);let from=pos,to=pos,flatten2=0;pos==0&&side<0||pos==length&&side>=0?browser.chrome||browser.gecko||(pos?(from--,flatten2=1):to=0)?0:rects.length-1];return browser.safari&&!flatten2&&rect.width==0&&(rect=Array.prototype.find.call(rects,r=>r.width)||rect),flatten2?flattenRect(rect,flatten2<0):rect||null}__name(textCoords,"textCoords"),__name2(textCoords,"textCoords");const _WidgetView=class _WidgetView2 extends ContentView{static{__name(this,"_WidgetView")}static create(widget,length,side){return new _WidgetView2(widget,length,side)}constructor(widget,length,side){super(),this.widget=widget,this.length=length,this.side=side,this.prevWidget=null}split(from){let result=_WidgetView2.create(this.widget,this.length-from,this.side);return this.length-=from,result}sync(view){(!this.dom||!this.widget.updateDOM(this.dom,view))&&(this.dom&&this.prevWidget&&this.prevWidget.destroy(this.dom),this.prevWidget=null,this.setDOM(this.widget.toDOM(view)),this.dom.contentEditable="false")}getSide(){return this.side}merge(from,to,source,hasStart,openStart,openEnd){return source&&(!(source instanceof _WidgetView2)||!this.widget.compare(source.widget)||from>0&&openStart<=0||to0)?DOMPos.before(this.dom):DOMPos.after(this.dom,pos==this.length)}domBoundsAround(){return null}coordsAt(pos,side){let custom=this.widget.coordsAt(this.dom,pos,side);if(custom)return custom;let rects=this.dom.getClientRects(),rect=null;if(!rects.length)return null;let fromBack=this.side?this.side<0:pos>0;for(let i=fromBack?rects.length-1:0;rect=rects[i],!(pos>0?i==0:i==rects.length-1||rect.top0?DOMPos.before(this.dom):DOMPos.after(this.dom)}localPosFromDOM(){return 0}domBoundsAround(){return null}coordsAt(pos){return this.dom.getBoundingClientRect()}get overrideDOMText(){return Text.empty}get isHidden(){return!0}};__name2(_WidgetBufferView,"WidgetBufferView");let WidgetBufferView=_WidgetBufferView;TextView.prototype.children=WidgetView.prototype.children=WidgetBufferView.prototype.children=noChildren;function inlineDOMAtPos(parent,pos){let dom=parent.dom,{children}=parent,i=0;for(let off2=0;ioff2&&pos0;j--){let prev=children[j-1];if(prev.dom.parentNode==dom)return prev.domAtPos(prev.length)}for(let j=i;j0&&view instanceof MarkView&&children.length&&(last2=children[children.length-1])instanceof MarkView&&last2.mark.eq(view.mark)?joinInlineInto(last2,view.children[0],open-1):(children.push(view),view.setParent(parent)),parent.length+=view.length}__name(joinInlineInto,"joinInlineInto"),__name2(joinInlineInto,"joinInlineInto");function coordsInChildren(view,pos,side){let before=null,beforePos=-1,after=null,afterPos=-1;function scan(view2,pos2){for(let i=0,off2=0;i=pos2&&(child.children.length?scan(child,pos2-off2):(!after||after.isHidden&&side>0)&&(end>pos2||off2==end&&child.getSide()>0)?(after=child,afterPos=pos2-off2):(off2-1?1:0)!=keysB.length-(ignore&&keysB.indexOf(ignore)>-1?1:0))return!1;for(let key of keysA)if(key!=ignore&&(keysB.indexOf(key)==-1||a[key]!==b[key]))return!1;return!0}__name(attrsEq,"attrsEq"),__name2(attrsEq,"attrsEq");function updateAttrs(dom,prev,attrs){let changed=!1;if(prev)for(let name2 in prev)attrs&&name2 in attrs||(changed=!0,name2=="style"?dom.style.cssText="":dom.removeAttribute(name2));if(attrs)for(let name2 in attrs)prev&&prev[name2]==attrs[name2]||(changed=!0,name2=="style"?dom.style.cssText=attrs[name2]:dom.setAttribute(name2,attrs[name2]));return changed}__name(updateAttrs,"updateAttrs"),__name2(updateAttrs,"updateAttrs");function getAttrs(dom){let attrs=Object.create(null);for(let i=0;i0&&this.children[i-1].length==0;)this.children[--i].destroy();return this.children.length=i,this.markDirty(),this.length=at,end}transferDOM(other){this.dom&&(this.markDirty(),other.setDOM(this.dom),other.prevAttrs=this.prevAttrs===void 0?this.attrs:this.prevAttrs,this.prevAttrs=void 0,this.dom=null)}setDeco(attrs){attrsEq(this.attrs,attrs)||(this.dom&&(this.prevAttrs=this.attrs,this.markDirty()),this.attrs=attrs)}append(child,openStart){joinInlineInto(this,child,openStart)}addLineDeco(deco){let attrs=deco.spec.attributes,cls=deco.spec.class;attrs&&(this.attrs=combineAttrs(attrs,this.attrs||{})),cls&&(this.attrs=combineAttrs({class:cls},this.attrs||{}))}domAtPos(pos){return inlineDOMAtPos(this,pos)}reuseDOM(node){node.nodeName=="DIV"&&(this.setDOM(node),this.flags|=6)}sync(view,track){var _a3;this.dom?this.flags&4&&(clearAttributes(this.dom),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0):(this.setDOM(document.createElement("div")),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0),this.prevAttrs!==void 0&&(updateAttrs(this.dom,this.prevAttrs,this.attrs),this.dom.classList.add("cm-line"),this.prevAttrs=void 0),super.sync(view,track);let last2=this.dom.lastChild;for(;last2&&ContentView.get(last2)instanceof MarkView;)last2=last2.lastChild;if(!last2||!this.length||last2.nodeName!="BR"&&((_a3=ContentView.get(last2))===null||_a3===void 0?void 0:_a3.isEditable)==!1&&(!browser.ios||!this.children.some(ch=>ch instanceof TextView))){let hack=document.createElement("BR");hack.cmIgnore=!0,this.dom.appendChild(hack)}}measureTextSize(){if(this.children.length==0||this.length>20)return null;let totalWidth=0,textHeight;for(let child of this.children){if(!(child instanceof TextView)||/[^ -~]/.test(child.text))return null;let rects=clientRectsFor(child.dom);if(rects.length!=1)return null;totalWidth+=rects[0].width,textHeight=rects[0].height}return totalWidth?{lineHeight:this.dom.getBoundingClientRect().height,charWidth:totalWidth/this.length,textHeight}:null}coordsAt(pos,side){let rect=coordsInChildren(this,pos,side);if(!this.children.length&&rect&&this.parent){let{heightOracle}=this.parent.view.viewState,height=rect.bottom-rect.top;if(Math.abs(height-heightOracle.lineHeight)<2&&heightOracle.textHeight=pos){if(block instanceof _LineView2)return block;if(end>pos)break}off2=end+block.breakAfter}return null}};__name2(_LineView,"LineView");let LineView=_LineView;const _BlockWidgetView=class _BlockWidgetView2 extends ContentView{static{__name(this,"_BlockWidgetView")}constructor(widget,length,deco){super(),this.widget=widget,this.length=length,this.deco=deco,this.breakAfter=0,this.prevWidget=null}merge(from,to,source,_takeDeco,openStart,openEnd){return source&&(!(source instanceof _BlockWidgetView2)||!this.widget.compare(source.widget)||from>0&&openStart<=0||to0}};__name2(_BlockWidgetView,"BlockWidgetView");let BlockWidgetView=_BlockWidgetView;const _WidgetType=class{static{__name(this,"_WidgetType")}eq(widget){return!1}updateDOM(dom,view){return!1}compare(other){return this==other||this.constructor==other.constructor&&this.eq(other)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(event){return!0}coordsAt(dom,pos,side){return null}get isHidden(){return!1}destroy(dom){}};__name2(_WidgetType,"WidgetType");let WidgetType=_WidgetType;var BlockType=function(BlockType2){return BlockType2[BlockType2.Text=0]="Text",BlockType2[BlockType2.WidgetBefore=1]="WidgetBefore",BlockType2[BlockType2.WidgetAfter=2]="WidgetAfter",BlockType2[BlockType2.WidgetRange=3]="WidgetRange",BlockType2}(BlockType||(BlockType={}));const _Decoration=class extends RangeValue{static{__name(this,"_Decoration")}constructor(startSide,endSide,widget,spec){super(),this.startSide=startSide,this.endSide=endSide,this.widget=widget,this.spec=spec}get heightRelevant(){return!1}static mark(spec){return new MarkDecoration(spec)}static widget(spec){let side=Math.max(-1e4,Math.min(1e4,spec.side||0)),block=!!spec.block;return side+=block&&!spec.inlineOrder?side>0?3e8:-4e8:side>0?1e8:-1e8,new PointDecoration(spec,side,side,block,spec.widget||null,!1)}static replace(spec){let block=!!spec.block,startSide,endSide;if(spec.isBlockGap)startSide=-5e8,endSide=4e8;else{let{start,end}=getInclusive(spec,block);startSide=(start?block?-3e8:-1:5e8)-1,endSide=(end?block?2e8:1:-6e8)+1}return new PointDecoration(spec,startSide,endSide,block,spec.widget||null,!0)}static line(spec){return new LineDecoration(spec)}static set(of,sort2=!1){return RangeSet.of(of,sort2)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}};__name2(_Decoration,"Decoration");let Decoration=_Decoration;Decoration.none=RangeSet.empty;const _MarkDecoration=class _MarkDecoration2 extends Decoration{static{__name(this,"_MarkDecoration")}constructor(spec){let{start,end}=getInclusive(spec);super(start?-1:5e8,end?1:-6e8,null,spec),this.tagName=spec.tagName||"span",this.class=spec.class||"",this.attrs=spec.attributes||null}eq(other){var _a3,_b2;return this==other||other instanceof _MarkDecoration2&&this.tagName==other.tagName&&(this.class||((_a3=this.attrs)===null||_a3===void 0?void 0:_a3.class))==(other.class||((_b2=other.attrs)===null||_b2===void 0?void 0:_b2.class))&&attrsEq(this.attrs,other.attrs,"class")}range(from,to=from){if(from>=to)throw new RangeError("Mark decorations may not be empty");return super.range(from,to)}};__name2(_MarkDecoration,"MarkDecoration");let MarkDecoration=_MarkDecoration;MarkDecoration.prototype.point=!1;const _LineDecoration=class _LineDecoration2 extends Decoration{static{__name(this,"_LineDecoration")}constructor(spec){super(-2e8,-2e8,null,spec)}eq(other){return other instanceof _LineDecoration2&&this.spec.class==other.spec.class&&attrsEq(this.spec.attributes,other.spec.attributes)}range(from,to=from){if(to!=from)throw new RangeError("Line decoration ranges must be zero-length");return super.range(from,to)}};__name2(_LineDecoration,"LineDecoration");let LineDecoration=_LineDecoration;LineDecoration.prototype.mapMode=MapMode.TrackBefore,LineDecoration.prototype.point=!0;const _PointDecoration=class _PointDecoration2 extends Decoration{static{__name(this,"_PointDecoration")}constructor(spec,startSide,endSide,block,widget,isReplace){super(startSide,endSide,widget,spec),this.block=block,this.isReplace=isReplace,this.mapMode=block?startSide<=0?MapMode.TrackBefore:MapMode.TrackAfter:MapMode.TrackDel}get type(){return this.startSide!=this.endSide?BlockType.WidgetRange:this.startSide<=0?BlockType.WidgetBefore:BlockType.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(other){return other instanceof _PointDecoration2&&widgetsEq(this.widget,other.widget)&&this.block==other.block&&this.startSide==other.startSide&&this.endSide==other.endSide}range(from,to=from){if(this.isReplace&&(from>to||from==to&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&to!=from)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(from,to)}};__name2(_PointDecoration,"PointDecoration");let PointDecoration=_PointDecoration;PointDecoration.prototype.point=!0;function getInclusive(spec,block=!1){let{inclusiveStart:start,inclusiveEnd:end}=spec;return start==null&&(start=spec.inclusive),end==null&&(end=spec.inclusive),{start:start??block,end:end??block}}__name(getInclusive,"getInclusive"),__name2(getInclusive,"getInclusive");function widgetsEq(a,b){return a==b||!!(a&&b&&a.compare(b))}__name(widgetsEq,"widgetsEq"),__name2(widgetsEq,"widgetsEq");function addRange(from,to,ranges,margin=0){let last2=ranges.length-1;last2>=0&&ranges[last2]+margin>=from?ranges[last2]=Math.max(ranges[last2],to):ranges.push(from,to)}__name(addRange,"addRange"),__name2(addRange,"addRange");const _ContentBuilder=class _ContentBuilder2{static{__name(this,"_ContentBuilder")}constructor(doc2,pos,end,disallowBlockEffectsFor){this.doc=doc2,this.pos=pos,this.end=end,this.disallowBlockEffectsFor=disallowBlockEffectsFor,this.content=[],this.curLine=null,this.breakAtStart=0,this.pendingBuffer=0,this.bufferMarks=[],this.atCursorPos=!0,this.openStart=-1,this.openEnd=-1,this.text="",this.textOff=0,this.cursor=doc2.iter(),this.skip=pos}posCovered(){if(this.content.length==0)return!this.breakAtStart&&this.doc.lineAt(this.pos).from!=this.pos;let last2=this.content[this.content.length-1];return!(last2.breakAfter||last2 instanceof BlockWidgetView&&last2.deco.endSide<0)}getLine(){return this.curLine||(this.content.push(this.curLine=new LineView),this.atCursorPos=!0),this.curLine}flushBuffer(active=this.bufferMarks){this.pendingBuffer&&(this.curLine.append(wrapMarks(new WidgetBufferView(-1),active),active.length),this.pendingBuffer=0)}addBlockWidget(view){this.flushBuffer(),this.curLine=null,this.content.push(view)}finish(openEnd){this.pendingBuffer&&openEnd<=this.bufferMarks.length?this.flushBuffer():this.pendingBuffer=0,!this.posCovered()&&!(openEnd&&this.content.length&&this.content[this.content.length-1]instanceof BlockWidgetView)&&this.getLine()}buildText(length,active,openStart){for(;length>0;){if(this.textOff==this.text.length){let{value,lineBreak,done}=this.cursor.next(this.skip);if(this.skip=0,done)throw new Error("Ran out of text content when drawing inline views");if(lineBreak){this.posCovered()||this.getLine(),this.content.length?this.content[this.content.length-1].breakAfter=1:this.breakAtStart=1,this.flushBuffer(),this.curLine=null,this.atCursorPos=!0,length--;continue}else this.text=value,this.textOff=0}let take=Math.min(this.text.length-this.textOff,length,512);this.flushBuffer(active.slice(active.length-openStart)),this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff,this.textOff+take)),active),openStart),this.atCursorPos=!0,this.textOff+=take,length-=take,openStart=0}}span(from,to,active,openStart){this.buildText(to-from,active,openStart),this.pos=to,this.openStart<0&&(this.openStart=openStart)}point(from,to,deco,active,openStart,index2){if(this.disallowBlockEffectsFor[index2]&&deco instanceof PointDecoration){if(deco.block)throw new RangeError("Block decorations may not be specified via plugins");if(to>this.doc.lineAt(this.pos).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}let len=to-from;if(deco instanceof PointDecoration)if(deco.block)deco.startSide>0&&!this.posCovered()&&this.getLine(),this.addBlockWidget(new BlockWidgetView(deco.widget||new NullWidget("div"),len,deco));else{let view=WidgetView.create(deco.widget||new NullWidget("span"),len,len?0:deco.startSide),cursorBefore=this.atCursorPos&&!view.isEditable&&openStart<=active.length&&(from0),cursorAfter=!view.isEditable&&(fromactive.length||deco.startSide<=0),line=this.getLine();this.pendingBuffer==2&&!cursorBefore&&!view.isEditable&&(this.pendingBuffer=0),this.flushBuffer(active),cursorBefore&&(line.append(wrapMarks(new WidgetBufferView(1),active),openStart),openStart=active.length+Math.max(0,openStart-active.length)),line.append(wrapMarks(view,active),openStart),this.atCursorPos=cursorAfter,this.pendingBuffer=cursorAfter?fromactive.length?1:2:0,this.pendingBuffer&&(this.bufferMarks=active.slice())}else this.doc.lineAt(this.pos).from==this.pos&&this.getLine().addLineDeco(deco);len&&(this.textOff+len<=this.text.length?this.textOff+=len:(this.skip+=len-(this.text.length-this.textOff),this.text="",this.textOff=0),this.pos=to),this.openStart<0&&(this.openStart=openStart)}static build(text,from,to,decorations2,dynamicDecorationMap){let builder=new _ContentBuilder2(text,from,to,dynamicDecorationMap);return builder.openEnd=RangeSet.spans(decorations2,from,to,builder),builder.openStart<0&&(builder.openStart=builder.openEnd),builder.finish(builder.openEnd),builder}};__name2(_ContentBuilder,"ContentBuilder");let ContentBuilder=_ContentBuilder;function wrapMarks(view,active){for(let mark of active)view=new MarkView(mark,[view],view.length);return view}__name(wrapMarks,"wrapMarks"),__name2(wrapMarks,"wrapMarks");const _NullWidget=class extends WidgetType{static{__name(this,"_NullWidget")}constructor(tag){super(),this.tag=tag}eq(other){return other.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(elt){return elt.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}};__name2(_NullWidget,"NullWidget");let NullWidget=_NullWidget;const clickAddsSelectionRange=Facet.define(),dragMovesSelection$1=Facet.define(),mouseSelectionStyle=Facet.define(),exceptionSink=Facet.define(),updateListener=Facet.define(),inputHandler$1=Facet.define(),focusChangeEffect=Facet.define(),perLineTextDirection=Facet.define({combine:values=>values.some(x=>x)}),nativeSelectionHidden=Facet.define({combine:values=>values.some(x=>x)}),_ScrollTarget=class _ScrollTarget2{static{__name(this,"_ScrollTarget")}constructor(range,y="nearest",x="nearest",yMargin=5,xMargin=5){this.range=range,this.y=y,this.x=x,this.yMargin=yMargin,this.xMargin=xMargin}map(changes){return changes.empty?this:new _ScrollTarget2(this.range.map(changes),this.y,this.x,this.yMargin,this.xMargin)}};__name2(_ScrollTarget,"ScrollTarget");let ScrollTarget=_ScrollTarget;const scrollIntoView$1=StateEffect.define({map:(t2,ch)=>t2.map(ch)});function logException(state,exception,context){let handler=state.facet(exceptionSink);handler.length?handler[0](exception):window.onerror?window.onerror(String(exception),context,void 0,void 0,exception):context?console.error(context+":",exception):console.error(exception)}__name(logException,"logException"),__name2(logException,"logException");const editable=Facet.define({combine:values=>values.length?values[0]:!0});let nextPluginID=0;const viewPlugin=Facet.define(),_ViewPlugin=class _ViewPlugin2{static{__name(this,"_ViewPlugin")}constructor(id,create,domEventHandlers,domEventObservers,buildExtensions){this.id=id,this.create=create,this.domEventHandlers=domEventHandlers,this.domEventObservers=domEventObservers,this.extension=buildExtensions(this)}static define(create,spec){const{eventHandlers,eventObservers,provide,decorations:deco}=spec||{};return new _ViewPlugin2(nextPluginID++,create,eventHandlers,eventObservers,plugin=>{let ext=[viewPlugin.of(plugin)];return deco&&ext.push(decorations.of(view=>{let pluginInst=view.plugin(plugin);return pluginInst?deco(pluginInst):Decoration.none})),provide&&ext.push(provide(plugin)),ext})}static fromClass(cls,spec){return _ViewPlugin2.define(view=>new cls(view),spec)}};__name2(_ViewPlugin,"ViewPlugin");let ViewPlugin=_ViewPlugin;const _PluginInstance=class{static{__name(this,"_PluginInstance")}constructor(spec){this.spec=spec,this.mustUpdate=null,this.value=null}update(view){if(this.value){if(this.mustUpdate){let update=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(update)}catch(e){if(logException(update.state,e,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.create(view)}catch(e){logException(view.state,e,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(view){var _a3;if(!((_a3=this.value)===null||_a3===void 0)&&_a3.destroy)try{this.value.destroy()}catch(e){logException(view.state,e,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}};__name2(_PluginInstance,"PluginInstance");let PluginInstance=_PluginInstance;const editorAttributes=Facet.define(),contentAttributes=Facet.define(),decorations=Facet.define(),atomicRanges=Facet.define(),bidiIsolatedRanges=Facet.define();function getIsolatedRanges(view,from,to){let isolates=view.state.facet(bidiIsolatedRanges);if(!isolates.length)return isolates;let sets=isolates.map(i=>i instanceof Function?i(view):i),result=[];return RangeSet.spans(sets,from,to,{point(){},span(from2,to2,active,open){let level=result;for(let i=active.length-1;i>=0;i--,open--){let iso=active[i].spec.bidiIsolate,update;if(iso!=null)if(open>0&&level.length&&(update=level[level.length-1]).to==from2&&update.direction==iso)update.to=to2,level=update.inner;else{let add2={from:from2,to:to2,direction:iso,inner:[]};level.push(add2),level=add2.inner}}}}),result}__name(getIsolatedRanges,"getIsolatedRanges"),__name2(getIsolatedRanges,"getIsolatedRanges");const scrollMargins=Facet.define();function getScrollMargins(view){let left=0,right=0,top2=0,bottom=0;for(let source of view.state.facet(scrollMargins)){let m=source(view);m&&(m.left!=null&&(left=Math.max(left,m.left)),m.right!=null&&(right=Math.max(right,m.right)),m.top!=null&&(top2=Math.max(top2,m.top)),m.bottom!=null&&(bottom=Math.max(bottom,m.bottom)))}return{left,right,top:top2,bottom}}__name(getScrollMargins,"getScrollMargins"),__name2(getScrollMargins,"getScrollMargins");const styleModule=Facet.define(),_ChangedRange=class _ChangedRange2{static{__name(this,"_ChangedRange")}constructor(fromA,toA,fromB,toB){this.fromA=fromA,this.toA=toA,this.fromB=fromB,this.toB=toB}join(other){return new _ChangedRange2(Math.min(this.fromA,other.fromA),Math.max(this.toA,other.toA),Math.min(this.fromB,other.fromB),Math.max(this.toB,other.toB))}addToSet(set){let i=set.length,me=this;for(;i>0;i--){let range=set[i-1];if(!(range.fromA>me.toA)){if(range.toAend)break;rI+=2}if(!next)return result;new _ChangedRange2(next.fromA,next.toA,next.fromB,next.toB).addToSet(result),posA=next.toA,posB=next.toB}}};__name2(_ChangedRange,"ChangedRange");let ChangedRange=_ChangedRange;const _ViewUpdate=class _ViewUpdate2{static{__name(this,"_ViewUpdate")}constructor(view,state,transactions){this.view=view,this.state=state,this.transactions=transactions,this.flags=0,this.startState=view.state,this.changes=ChangeSet.empty(this.startState.doc.length);for(let tr of transactions)this.changes=this.changes.compose(tr.changes);let changedRanges=[];this.changes.iterChangedRanges((fromA,toA,fromB,toB)=>changedRanges.push(new ChangedRange(fromA,toA,fromB,toB))),this.changedRanges=changedRanges}static create(view,state,transactions){return new _ViewUpdate2(view,state,transactions)}get viewportChanged(){return(this.flags&4)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&10)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(tr=>tr.selection)}get empty(){return this.flags==0&&this.transactions.length==0}};__name2(_ViewUpdate,"ViewUpdate");let ViewUpdate=_ViewUpdate;var Direction=function(Direction2){return Direction2[Direction2.LTR=0]="LTR",Direction2[Direction2.RTL=1]="RTL",Direction2}(Direction||(Direction={}));const LTR=Direction.LTR,RTL=Direction.RTL;function dec(str){let result=[];for(let i=0;i=index2){if(span.level==level)return i;(maybe<0||(assoc!=0?assoc<0?span.fromindex2:order[maybe].level>span.level))&&(maybe=i)}}if(maybe<0)throw new RangeError("Index out of range");return maybe}};__name2(_BidiSpan,"BidiSpan");let BidiSpan=_BidiSpan;function isolatesEq(a,b){if(a.length!=b.length)return!1;for(let i=0;i=0;sJ-=3)if(BracketStack[sJ+1]==-br){let flags=BracketStack[sJ+2],type2=flags&2?outerType:flags&4?flags&1?oppositeType:outerType:0;type2&&(types[i]=types[BracketStack[sJ]]=type2),sI=sJ;break}}else{if(BracketStack.length==189)break;BracketStack[sI++]=i,BracketStack[sI++]=ch,BracketStack[sI++]=context}else if((type=types[i])==2||type==1){let embed=type==outerType;context=embed?0:1;for(let sJ=sI-3;sJ>=0;sJ-=3){let cur2=BracketStack[sJ+2];if(cur2&2)break;if(embed)BracketStack[sJ+2]|=2;else{if(cur2&4)break;BracketStack[sJ+2]|=4}}}}}__name(processBracketPairs,"processBracketPairs"),__name2(processBracketPairs,"processBracketPairs");function processNeutrals(rFrom,rTo,isolates,outerType){for(let iI=0,prev=outerType;iI<=isolates.length;iI++){let from=iI?isolates[iI-1].to:rFrom,to=iIi;)j==fromJ&&(j=isolates[--jI].from,fromJ=jI?isolates[jI-1].to:rFrom),types[--j]=replace;i=end}else prev=type,i++}}}__name(processNeutrals,"processNeutrals"),__name2(processNeutrals,"processNeutrals");function emitSpans(line,from,to,level,baseLevel,isolates,order){let ourType=level%2?2:1;if(level%2==baseLevel%2)for(let iCh=from,iI=0;iChiCh&&order.push(new BidiSpan(iCh,iso.from,localLevel));let dirSwap=iso.direction==LTR!=!(localLevel%2);computeSectionOrder(line,dirSwap?level+1:level,baseLevel,iso.inner,iso.from,iso.to,order),iCh=iso.to}iScan=iso.to}else{if(iScan==to||(sameDir?types[iScan]!=ourType:types[iScan]==ourType))break;iScan++}recurse2?emitSpans(line,iCh,iScan,level+1,baseLevel,recurse2,order):iChfrom;){let sameDir=!0,isNum=!1;if(!iI||iCh>isolates[iI-1].to){let next=types[iCh-1];next!=ourType&&(sameDir=!1,isNum=next==16)}let recurse2=!sameDir&&ourType==1?[]:null,localLevel=sameDir?level:level+1,iScan=iCh;run:for(;;)if(iI&&iScan==isolates[iI-1].to){if(isNum)break run;let iso=isolates[--iI];if(!sameDir)for(let upto=iso.from,jI=iI;;){if(upto==from)break run;if(jI&&isolates[jI-1].to==upto)upto=isolates[--jI].from;else{if(types[upto-1]==ourType)break run;break}}if(recurse2)recurse2.push(iso);else{iso.totypes.length;)types[types.length]=256;let order=[],level=direction==LTR?0:1;return computeSectionOrder(line,level,level,isolates,0,line.length,order),order}__name(computeOrder,"computeOrder"),__name2(computeOrder,"computeOrder");function trivialOrder(length){return[new BidiSpan(0,length,0)]}__name(trivialOrder,"trivialOrder"),__name2(trivialOrder,"trivialOrder");let movedOver="";function moveVisually(line,order,dir,start,forward){var _a3;let startIndex=start.head-line.from,spanI=-1;if(startIndex==0){if(!forward||!line.length)return null;order[0].level!=dir&&(startIndex=order[0].side(!1,dir),spanI=0)}else if(startIndex==line.length){if(forward)return null;let last2=order[order.length-1];last2.level!=dir&&(startIndex=last2.side(!0,dir),spanI=order.length-1)}spanI<0&&(spanI=BidiSpan.find(order,startIndex,(_a3=start.bidiLevel)!==null&&_a3!==void 0?_a3:-1,start.assoc));let span=order[spanI];startIndex==span.side(forward,dir)&&(span=order[spanI+=forward?1:-1],startIndex=span.side(!forward,dir));let indexForward=forward==(span.dir==dir),nextIndex=findClusterBreak(line.text,startIndex,indexForward);if(movedOver=line.text.slice(Math.min(startIndex,nextIndex),Math.max(startIndex,nextIndex)),nextIndex!=span.side(forward,dir))return EditorSelection.cursor(nextIndex+line.from,indexForward?-1:1,span.level);let nextSpan=spanI==(forward?order.length-1:0)?null:order[spanI+(forward?1:-1)];return!nextSpan&&span.level!=dir?EditorSelection.cursor(forward?line.to:line.from,forward?-1:1,dir):nextSpan&&nextSpan.level0&&changedRanges.length&&(changedRanges.every(({fromA,toA})=>toAthis.minWidthTo)?(this.minWidthFrom=update.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=update.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0);let readCompositionAt=-1;this.view.inputState.composing>=0&&(!((_a3=this.domChanged)===null||_a3===void 0)&&_a3.newSel?readCompositionAt=this.domChanged.newSel.head:!touchesComposition(update.changes,this.hasComposition)&&!update.selectionSet&&(readCompositionAt=update.state.selection.main.head));let composition=readCompositionAt>-1?findCompositionRange(this.view,update.changes,readCompositionAt):null;if(this.domChanged=null,this.hasComposition){this.markedForComposition.clear();let{from,to}=this.hasComposition;changedRanges=new ChangedRange(from,to,update.changes.mapPos(from,-1),update.changes.mapPos(to,1)).addToSet(changedRanges.slice())}this.hasComposition=composition?{from:composition.range.fromB,to:composition.range.toB}:null,(browser.ie||browser.chrome)&&!composition&&update&&update.state.doc.lines!=update.startState.doc.lines&&(this.forceSelection=!0);let prevDeco=this.decorations,deco=this.updateDeco(),decoDiff=findChangedDeco(prevDeco,deco,update.changes);return changedRanges=ChangedRange.extendWithRanges(changedRanges,decoDiff),!(this.flags&7)&&changedRanges.length==0?!1:(this.updateInner(changedRanges,update.startState.doc.length,composition),update.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(changes,oldLength,composition){this.view.viewState.mustMeasureContent=!0,this.updateChildren(changes,oldLength,composition);let{observer}=this.view;observer.ignore(()=>{this.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let track=browser.chrome||browser.ios?{node:observer.selectionRange.focusNode,written:!1}:void 0;this.sync(this.view,track),this.flags&=-8,track&&(track.written||observer.selectionRange.focusNode!=track.node)&&(this.forceSelection=!0),this.dom.style.height=""}),this.markedForComposition.forEach(cView=>cView.flags&=-9);let gaps=[];if(this.view.viewport.from||this.view.viewport.to=0?ranges[i]:null;if(!next)break;let{fromA,toA,fromB,toB}=next,content2,breakAtStart,openStart,openEnd;if(composition&&composition.range.fromBfromB){let before=ContentBuilder.build(this.view.state.doc,fromB,composition.range.fromB,this.decorations,this.dynamicDecorationMap),after=ContentBuilder.build(this.view.state.doc,composition.range.toB,toB,this.decorations,this.dynamicDecorationMap);breakAtStart=before.breakAtStart,openStart=before.openStart,openEnd=after.openEnd;let compLine=this.compositionView(composition);after.breakAtStart?compLine.breakAfter=1:after.content.length&&compLine.merge(compLine.length,compLine.length,after.content[0],!1,after.openStart,0)&&(compLine.breakAfter=after.content[0].breakAfter,after.content.shift()),before.content.length&&compLine.merge(0,0,before.content[before.content.length-1],!0,0,before.openEnd)&&before.content.pop(),content2=before.content.concat(compLine).concat(after.content)}else({content:content2,breakAtStart,openStart,openEnd}=ContentBuilder.build(this.view.state.doc,fromB,toB,this.decorations,this.dynamicDecorationMap));let{i:toI,off:toOff}=cursor.findPos(toA,1),{i:fromI,off:fromOff}=cursor.findPos(fromA,-1);replaceRange(this,fromI,fromOff,toI,toOff,content2,breakAtStart,openStart,openEnd)}composition&&this.fixCompositionDOM(composition)}compositionView(composition){let cur2=new TextView(composition.text.nodeValue);cur2.flags|=8;for(let{deco}of composition.marks)cur2=new MarkView(deco,[cur2],cur2.length);let line=new LineView;return line.append(cur2,0),line}fixCompositionDOM(composition){let fix=__name2((dom,cView2)=>{cView2.flags|=8|(cView2.children.some(c=>c.flags&7)?1:0),this.markedForComposition.add(cView2);let prev=ContentView.get(dom);prev&&prev!=cView2&&(prev.dom=null),cView2.setDOM(dom)},"fix"),pos=this.childPos(composition.range.fromB,1),cView=this.children[pos.i];fix(composition.line,cView);for(let i=composition.marks.length-1;i>=-1;i--)pos=cView.childPos(pos.off,1),cView=cView.children[pos.i],fix(i>=0?composition.marks[i].node:composition.text,cView)}updateSelection(mustRead=!1,fromPointer=!1){(mustRead||!this.view.observer.selectionRange.focusNode)&&this.view.observer.readSelectionRange();let activeElt=this.view.root.activeElement,focused=activeElt==this.dom,selectionNotFocus=!focused&&hasSelection(this.dom,this.view.observer.selectionRange)&&!(activeElt&&this.dom.contains(activeElt));if(!(focused||fromPointer||selectionNotFocus))return;let force=this.forceSelection;this.forceSelection=!1;let main=this.view.state.selection.main,anchor=this.moveToLine(this.domAtPos(main.anchor)),head=main.empty?anchor:this.moveToLine(this.domAtPos(main.head));if(browser.gecko&&main.empty&&!this.hasComposition&&betweenUneditable(anchor)){let dummy=document.createTextNode("");this.view.observer.ignore(()=>anchor.node.insertBefore(dummy,anchor.node.childNodes[anchor.offset]||null)),anchor=head=new DOMPos(dummy,0),force=!0}let domSel=this.view.observer.selectionRange;(force||!domSel.focusNode||!isEquivalentPosition(anchor.node,anchor.offset,domSel.anchorNode,domSel.anchorOffset)||!isEquivalentPosition(head.node,head.offset,domSel.focusNode,domSel.focusOffset))&&(this.view.observer.ignore(()=>{browser.android&&browser.chrome&&this.dom.contains(domSel.focusNode)&&inUneditable(domSel.focusNode,this.dom)&&(this.dom.blur(),this.dom.focus({preventScroll:!0}));let rawSel=getSelection(this.view.root);if(rawSel)if(main.empty){if(browser.gecko){let nextTo=nextToUneditable(anchor.node,anchor.offset);if(nextTo&&nextTo!=3){let text=nearbyTextNode(anchor.node,anchor.offset,nextTo==1?1:-1);text&&(anchor=new DOMPos(text.node,text.offset))}}rawSel.collapse(anchor.node,anchor.offset),main.bidiLevel!=null&&rawSel.caretBidiLevel!==void 0&&(rawSel.caretBidiLevel=main.bidiLevel)}else if(rawSel.extend){rawSel.collapse(anchor.node,anchor.offset);try{rawSel.extend(head.node,head.offset)}catch{}}else{let range=document.createRange();main.anchor>main.head&&([anchor,head]=[head,anchor]),range.setEnd(head.node,head.offset),range.setStart(anchor.node,anchor.offset),rawSel.removeAllRanges(),rawSel.addRange(range)}selectionNotFocus&&this.view.root.activeElement==this.dom&&(this.dom.blur(),activeElt&&activeElt.focus())}),this.view.observer.setSelectionRange(anchor,head)),this.impreciseAnchor=anchor.precise?null:new DOMPos(domSel.anchorNode,domSel.anchorOffset),this.impreciseHead=head.precise?null:new DOMPos(domSel.focusNode,domSel.focusOffset)}enforceCursorAssoc(){if(this.hasComposition)return;let{view}=this,cursor=view.state.selection.main,sel=getSelection(view.root),{anchorNode,anchorOffset}=view.observer.selectionRange;if(!sel||!cursor.empty||!cursor.assoc||!sel.modify)return;let line=LineView.find(this,cursor.head);if(!line)return;let lineStart=line.posAtStart;if(cursor.head==lineStart||cursor.head==lineStart+line.length)return;let before=this.coordsAt(cursor.head,-1),after=this.coordsAt(cursor.head,1);if(!before||!after||before.bottom>after.top)return;let dom=this.domAtPos(cursor.head+cursor.assoc);sel.collapse(dom.node,dom.offset),sel.modify("move",cursor.assoc<0?"forward":"backward","lineboundary"),view.observer.readSelectionRange();let newRange=view.observer.selectionRange;view.docView.posFromDOM(newRange.anchorNode,newRange.anchorOffset)!=cursor.from&&sel.collapse(anchorNode,anchorOffset)}moveToLine(pos){let dom=this.dom,newPos;if(pos.node!=dom)return pos;for(let i=pos.offset;!newPos&&i=0;i--){let view=ContentView.get(dom.childNodes[i]);view instanceof LineView&&(newPos=view.domAtPos(view.length))}return newPos?new DOMPos(newPos.node,newPos.offset,!0):pos}nearest(dom){for(let cur2=dom;cur2;){let domView=ContentView.get(cur2);if(domView&&domView.rootView==this)return domView;cur2=cur2.parentNode}return null}posFromDOM(node,offset2){let view=this.nearest(node);if(!view)throw new RangeError("Trying to find position for a DOM position outside of the document");return view.localPosFromDOM(node,offset2)+view.posAtStart}domAtPos(pos){let{i,off:off2}=this.childCursor().findPos(pos,-1);for(;i=0;i--){let child=this.children[i],end=off2-child.breakAfter,start=end-child.length;if(endpos||child.covers(1))&&(!best||child instanceof LineView&&!(best instanceof LineView&&side>=0))&&(best=child,bestPos=start),off2=start}return best?best.coordsAt(pos-bestPos,side):null}coordsForChar(pos){let{i,off:off2}=this.childPos(pos,1),child=this.children[i];if(!(child instanceof LineView))return null;for(;child.children.length;){let{i:i2,off:childOff}=child.childPos(off2,1);for(;;i2++){if(i2==child.children.length)return null;if((child=child.children[i2]).length)break}off2=childOff}if(!(child instanceof TextView))return null;let end=findClusterBreak(child.text,off2);if(end==off2)return null;let rects=textRange(child.dom,off2,end).getClientRects();return!rects.length||rects[0].top>=rects[0].bottom?null:rects[0]}measureVisibleLineHeights(viewport){let result=[],{from,to}=viewport,contentWidth=this.view.contentDOM.clientWidth,isWider=contentWidth>Math.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,widest=-1,ltr=this.view.textDirection==Direction.LTR;for(let pos=0,i=0;ito)break;if(pos>=from){let childRect=child.dom.getBoundingClientRect();if(result.push(childRect.height),isWider){let last2=child.dom.lastChild,rects=last2?clientRectsFor(last2):[];if(rects.length){let rect=rects[rects.length-1],width=ltr?rect.right-childRect.left:childRect.right-rect.left;width>widest&&(widest=width,this.minWidth=contentWidth,this.minWidthFrom=pos,this.minWidthTo=end)}}}pos=end+child.breakAfter}return result}textDirectionAt(pos){let{i}=this.childPos(pos,1);return getComputedStyle(this.children[i].dom).direction=="rtl"?Direction.RTL:Direction.LTR}measureTextSize(){for(let child of this.children)if(child instanceof LineView){let measure=child.measureTextSize();if(measure)return measure}let dummy=document.createElement("div"),lineHeight,charWidth,textHeight;return dummy.className="cm-line",dummy.style.width="99999px",dummy.style.position="absolute",dummy.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.dom.appendChild(dummy);let rect=clientRectsFor(dummy.firstChild)[0];lineHeight=dummy.getBoundingClientRect().height,charWidth=rect?rect.width/27:7,textHeight=rect?rect.height:lineHeight,dummy.remove()}),{lineHeight,charWidth,textHeight}}childCursor(pos=this.length){let i=this.children.length;return i&&(pos-=this.children[--i].length),new ChildCursor(this.children,pos,i)}computeBlockGapDeco(){let deco=[],vs=this.view.viewState;for(let pos=0,i=0;;i++){let next=i==vs.viewports.length?null:vs.viewports[i],end=next?next.from-1:this.length;if(end>pos){let height=(vs.lineBlockAt(end).bottom-vs.lineBlockAt(pos).top)/this.view.scaleY;deco.push(Decoration.replace({widget:new BlockGapWidget(height),block:!0,inclusive:!0,isBlockGap:!0}).range(pos,end))}if(!next)break;pos=next.to+1}return Decoration.set(deco)}updateDeco(){let allDeco=this.view.state.facet(decorations).map((d,i)=>(this.dynamicDecorationMap[i]=typeof d=="function")?d(this.view):d);for(let i=allDeco.length;irange.anchor?-1:1),other;if(!rect)return;!range.empty&&(other=this.coordsAt(range.anchor,range.anchor>range.head?-1:1))&&(rect={left:Math.min(rect.left,other.left),top:Math.min(rect.top,other.top),right:Math.max(rect.right,other.right),bottom:Math.max(rect.bottom,other.bottom)});let margins=getScrollMargins(this.view),targetRect={left:rect.left-margins.left,top:rect.top-margins.top,right:rect.right+margins.right,bottom:rect.bottom+margins.bottom};scrollRectIntoView(this.view.scrollDOM,targetRect,range.head0)node=node.childNodes[offset2-1],offset2=maxOffset(node);else break}if(side>=0)for(let node=startNode,offset2=startOffset;;){if(node.nodeType==3)return{node,offset:offset2};if(node.nodeType==1&&offset2=0)node=node.childNodes[offset2],offset2=0;else break}return null}__name(nearbyTextNode,"nearbyTextNode"),__name2(nearbyTextNode,"nearbyTextNode");function nextToUneditable(node,offset2){return node.nodeType!=1?0:(offset2&&node.childNodes[offset2-1].contentEditable=="false"?1:0)|(offset2{fromcomposition.from&&(touched=!0)}),touched}__name(touchesComposition,"touchesComposition"),__name2(touchesComposition,"touchesComposition");function groupAt(state,pos,bias=1){let categorize=state.charCategorizer(pos),line=state.doc.lineAt(pos),linePos=pos-line.from;if(line.length==0)return EditorSelection.cursor(pos);linePos==0?bias=1:linePos==line.length&&(bias=-1);let from=linePos,to=linePos;bias<0?from=findClusterBreak(line.text,linePos,!1):to=findClusterBreak(line.text,linePos);let cat=categorize(line.text.slice(from,to));for(;from>0;){let prev=findClusterBreak(line.text,from,!1);if(categorize(line.text.slice(prev,from))!=cat)break;from=prev}for(;tox?rect.left-x:Math.max(0,x-rect.right)}__name(getdx,"getdx"),__name2(getdx,"getdx");function getdy(y,rect){return rect.top>y?rect.top-y:Math.max(0,y-rect.bottom)}__name(getdy,"getdy"),__name2(getdy,"getdy");function yOverlap(a,b){return a.topb.top+1}__name(yOverlap,"yOverlap"),__name2(yOverlap,"yOverlap");function upTop(rect,top2){return top2rect.bottom?{top:rect.top,left:rect.left,right:rect.right,bottom}:rect}__name(upBot,"upBot"),__name2(upBot,"upBot");function domPosAtCoords(parent,x,y){let closest2,closestRect,closestX,closestY,closestOverlap=!1,above,below,aboveRect,belowRect;for(let child=parent.firstChild;child;child=child.nextSibling){let rects=clientRectsFor(child);for(let i=0;idy||closestY==dy&&closestX>dx){closest2=child,closestRect=rect,closestX=dx,closestY=dy;let side=dy?y0?i0)}dx==0?y>rect.bottom&&(!aboveRect||aboveRect.bottomrect.top)&&(below=child,belowRect=rect):aboveRect&&yOverlap(aboveRect,rect)?aboveRect=upBot(aboveRect,rect.bottom):belowRect&&yOverlap(belowRect,rect)&&(belowRect=upTop(belowRect,rect.top))}}if(aboveRect&&aboveRect.bottom>=y?(closest2=above,closestRect=aboveRect):belowRect&&belowRect.top<=y&&(closest2=below,closestRect=belowRect),!closest2)return{node:parent,offset:0};let clipX=Math.max(closestRect.left,Math.min(closestRect.right,x));if(closest2.nodeType==3)return domPosInText(closest2,clipX,y);if(closestOverlap&&closest2.contentEditable!="false")return domPosAtCoords(closest2,clipX,y);let offset2=Array.prototype.indexOf.call(parent.childNodes,closest2)+(x>=(closestRect.left+closestRect.right)/2?1:0);return{node:parent,offset:offset2}}__name(domPosAtCoords,"domPosAtCoords"),__name2(domPosAtCoords,"domPosAtCoords");function domPosInText(node,x,y){let len=node.nodeValue.length,closestOffset=-1,closestDY=1e9,generalSide=0;for(let i=0;iy?rect.top-y:y-rect.bottom)-1;if(rect.left-1<=x&&rect.right+1>=x&&dy=(rect.left+rect.right)/2,after=right;if((browser.chrome||browser.gecko)&&textRange(node,i).getBoundingClientRect().left==rect.right&&(after=!right),dy<=0)return{node,offset:i+(after?1:0)};closestOffset=i+(after?1:0),closestDY=dy}}}return{node,offset:closestOffset>-1?closestOffset:generalSide>0?node.nodeValue.length:0}}__name(domPosInText,"domPosInText"),__name2(domPosInText,"domPosInText");function posAtCoords(view,coords,precise,bias=-1){var _a3,_b2;let content2=view.contentDOM.getBoundingClientRect(),docTop=content2.top+view.viewState.paddingTop,block,{docHeight}=view.viewState,{x,y}=coords,yOffset=y-docTop;if(yOffset<0)return 0;if(yOffset>docHeight)return view.state.doc.length;for(let halfLine=view.viewState.heightOracle.textHeight/2,bounced=!1;block=view.elementAtHeight(yOffset),block.type!=BlockType.Text;)for(;yOffset=bias>0?block.bottom+halfLine:block.top-halfLine,!(yOffset>=0&&yOffset<=docHeight);){if(bounced)return precise?null:0;bounced=!0,bias=-bias}y=docTop+yOffset;let lineStart=block.from;if(lineStartview.viewport.to)return view.viewport.to==view.state.doc.length?view.state.doc.length:precise?null:posAtCoordsImprecise(view,content2,block,x,y);let doc2=view.dom.ownerDocument,root=view.root.elementFromPoint?view.root:doc2,element=root.elementFromPoint(x,y);element&&!view.contentDOM.contains(element)&&(element=null),element||(x=Math.max(content2.left+1,Math.min(content2.right-1,x)),element=root.elementFromPoint(x,y),element&&!view.contentDOM.contains(element)&&(element=null));let node,offset2=-1;if(element&&((_a3=view.docView.nearest(element))===null||_a3===void 0?void 0:_a3.isEditable)!=!1){if(doc2.caretPositionFromPoint){let pos=doc2.caretPositionFromPoint(x,y);pos&&({offsetNode:node,offset:offset2}=pos)}else if(doc2.caretRangeFromPoint){let range=doc2.caretRangeFromPoint(x,y);range&&({startContainer:node,startOffset:offset2}=range,(!view.contentDOM.contains(node)||browser.safari&&isSuspiciousSafariCaretResult(node,offset2,x)||browser.chrome&&isSuspiciousChromeCaretResult(node,offset2,x))&&(node=void 0))}}if(!node||!view.docView.dom.contains(node)){let line=LineView.find(view.docView,lineStart);if(!line)return yOffset>block.top+block.height/2?block.to:block.from;({node,offset:offset2}=domPosAtCoords(line.dom,x,y))}let nearest=view.docView.nearest(node);if(!nearest)return null;if(nearest.isWidget&&((_b2=nearest.dom)===null||_b2===void 0?void 0:_b2.nodeType)==1){let rect=nearest.dom.getBoundingClientRect();return coords.yview.defaultLineHeight*1.5){let textHeight=view.viewState.heightOracle.textHeight,line=Math.floor((y-block.top-(view.defaultLineHeight-textHeight)*.5)/textHeight);into+=line*view.viewState.heightOracle.lineLength}let content2=view.state.sliceDoc(block.from,block.to);return block.from+findColumn(content2,into,view.state.tabSize)}__name(posAtCoordsImprecise,"posAtCoordsImprecise"),__name2(posAtCoordsImprecise,"posAtCoordsImprecise");function isSuspiciousSafariCaretResult(node,offset2,x){let len;if(node.nodeType!=3||offset2!=(len=node.nodeValue.length))return!1;for(let next=node.nextSibling;next;next=next.nextSibling)if(next.nodeType!=1||next.nodeName!="BR")return!1;return textRange(node,len-1,len).getBoundingClientRect().left>x}__name(isSuspiciousSafariCaretResult,"isSuspiciousSafariCaretResult"),__name2(isSuspiciousSafariCaretResult,"isSuspiciousSafariCaretResult");function isSuspiciousChromeCaretResult(node,offset2,x){if(offset2!=0)return!1;for(let cur2=node;;){let parent=cur2.parentNode;if(!parent||parent.nodeType!=1||parent.firstChild!=cur2)return!1;if(parent.classList.contains("cm-line"))break;cur2=parent}let rect=node.nodeType==1?node.getBoundingClientRect():textRange(node,0,Math.max(node.nodeValue.length,1)).getBoundingClientRect();return x-rect.left>5}__name(isSuspiciousChromeCaretResult,"isSuspiciousChromeCaretResult"),__name2(isSuspiciousChromeCaretResult,"isSuspiciousChromeCaretResult");function blockAt(view,pos){let line=view.lineBlockAt(pos);if(Array.isArray(line.type)){for(let l2 of line.type)if(l2.to>pos||l2.to==pos&&(l2.to==line.to||l2.type==BlockType.Text))return l2}return line}__name(blockAt,"blockAt"),__name2(blockAt,"blockAt");function moveToLineBoundary(view,start,forward,includeWrap){let line=blockAt(view,start.head),coords=!includeWrap||line.type!=BlockType.Text||!(view.lineWrapping||line.widgetLineBreaks)?null:view.coordsAtPos(start.assoc<0&&start.head>line.from?start.head-1:start.head);if(coords){let editorRect=view.dom.getBoundingClientRect(),direction=view.textDirectionAt(line.from),pos=view.posAtCoords({x:forward==(direction==Direction.LTR)?editorRect.right-1:editorRect.left+1,y:(coords.top+coords.bottom)/2});if(pos!=null)return EditorSelection.cursor(pos,forward?-1:1)}return EditorSelection.cursor(forward?line.to:line.from,forward?-1:1)}__name(moveToLineBoundary,"moveToLineBoundary"),__name2(moveToLineBoundary,"moveToLineBoundary");function moveByChar(view,start,forward,by){let line=view.state.doc.lineAt(start.head),spans=view.bidiSpans(line),direction=view.textDirectionAt(line.from);for(let cur2=start,check=null;;){let next=moveVisually(line,spans,direction,cur2,forward),char=movedOver;if(!next){if(line.number==(forward?view.state.doc.lines:1))return cur2;char=` `,line=view.state.doc.line(line.number+(forward?1:-1)),spans=view.bidiSpans(line),next=EditorSelection.cursor(forward?line.from:line.to)}if(check){if(!check(char))return cur2}else{if(!by)return next;check=by(char)}cur2=next}}__name(moveByChar,"moveByChar"),__name2(moveByChar,"moveByChar");function byGroup(view,pos,start){let categorize=view.state.charCategorizer(pos),cat=categorize(start);return next=>{let nextCat=categorize(next);return cat==CharCategory.Space&&(cat=nextCat),cat==nextCat}}__name(byGroup,"byGroup"),__name2(byGroup,"byGroup");function moveVertically(view,start,forward,distance){let startPos=start.head,dir=forward?1:-1;if(startPos==(forward?view.state.doc.length:0))return EditorSelection.cursor(startPos,start.assoc);let goal=start.goalColumn,startY,rect=view.contentDOM.getBoundingClientRect(),startCoords=view.coordsAtPos(startPos,start.assoc||-1),docTop=view.documentTop;if(startCoords)goal==null&&(goal=startCoords.left-rect.left),startY=dir<0?startCoords.top:startCoords.bottom;else{let line=view.viewState.lineBlockAt(startPos);goal==null&&(goal=Math.min(rect.right-rect.left,view.defaultCharacterWidth*(startPos-line.from))),startY=(dir<0?line.top:line.bottom)+docTop}let resolvedGoal=rect.left+goal,dist2=distance??view.viewState.heightOracle.textHeight>>1;for(let extra=0;;extra+=10){let curY=startY+(dist2+extra)*dir,pos=posAtCoords(view,{x:resolvedGoal,y:curY},!1,dir);if(curYrect.bottom||(dir<0?posstartPos)){let charRect=view.docView.coordsForChar(pos),assoc=!charRect||curY{if(pos>from&&posf(view)),pos.from,oldPos.head>pos.from?-1:1);return newPos==pos.from?pos:EditorSelection.cursor(newPos,newPos{if(event.target==view.scrollDOM&&event.clientY>view.contentDOM.getBoundingClientRect().bottom&&(this.runHandlers("mousedown",event),!event.defaultPrevented&&event.button==2)){let start=view.contentDOM.style.minHeight;view.contentDOM.style.minHeight="100%",setTimeout(()=>view.contentDOM.style.minHeight=start,200)}}),view.scrollDOM.addEventListener("drop",event=>{event.target==view.scrollDOM&&event.clientY>view.contentDOM.getBoundingClientRect().bottom&&this.runHandlers("drop",event)}),this.notifiedFocused=view.hasFocus,browser.safari&&view.contentDOM.addEventListener("input",()=>null),browser.gecko&&firefoxCopyCutHack(view.contentDOM.ownerDocument)}handleEvent(event){!eventBelongsToEditor(this.view,event)||this.ignoreDuringComposition(event)||event.type=="keydown"&&this.keydown(event)||this.runHandlers(event.type,event)}runHandlers(type,event){let handlers2=this.handlers[type];if(handlers2){for(let observer of handlers2.observers)observer(this.view,event);for(let handler of handlers2.handlers){if(event.defaultPrevented)break;if(handler(this.view,event)){event.preventDefault();break}}}}ensureHandlers(plugins2){let handlers2=computeHandlers(plugins2),prev=this.handlers,dom=this.view.contentDOM;for(let type in handlers2)if(type!="scroll"){let passive=!handlers2[type].handlers.length,exists=prev[type];exists&&passive!=!exists.handlers.length&&(dom.removeEventListener(type,this.handleEvent),exists=null),exists||dom.addEventListener(type,this.handleEvent,{passive})}for(let type in prev)type!="scroll"&&!handlers2[type]&&dom.removeEventListener(type,this.handleEvent);this.handlers=handlers2}keydown(event){if(this.lastKeyCode=event.keyCode,this.lastKeyTime=Date.now(),event.keyCode==9&&Date.now()key.keyCode==event.keyCode))&&!event.ctrlKey||EmacsyPendingKeys.indexOf(event.key)>-1&&event.ctrlKey&&!event.shiftKey)?(this.pendingIOSKey=pending||event,setTimeout(()=>this.flushIOSKey(),250),!0):(event.keyCode!=229&&this.view.observer.forceFlush(),!1)}flushIOSKey(){let key=this.pendingIOSKey;return key?(this.pendingIOSKey=void 0,dispatchKey(this.view.contentDOM,key.key,key.keyCode)):!1}ignoreDuringComposition(event){return/^key/.test(event.type)?this.composing>0?!0:browser.safari&&!browser.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1:!1}startMouseSelection(mouseSelection){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=mouseSelection}update(update){this.mouseSelection&&this.mouseSelection.update(update),update.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}};__name2(_InputState,"InputState");let InputState=_InputState;function bindHandler(plugin,handler){return(view,event)=>{try{return handler.call(plugin,event,view)}catch(e){logException(view.state,e)}}}__name(bindHandler,"bindHandler"),__name2(bindHandler,"bindHandler");function computeHandlers(plugins2){let result=Object.create(null);function record(type){return result[type]||(result[type]={observers:[],handlers:[]})}__name(record,"record"),__name2(record,"record");for(let plugin of plugins2){let spec=plugin.spec;if(spec&&spec.domEventHandlers)for(let type in spec.domEventHandlers){let f=spec.domEventHandlers[type];f&&record(type).handlers.push(bindHandler(plugin.value,f))}if(spec&&spec.domEventObservers)for(let type in spec.domEventObservers){let f=spec.domEventObservers[type];f&&record(type).observers.push(bindHandler(plugin.value,f))}}for(let type in handlers)record(type).handlers.push(handlers[type]);for(let type in observers)record(type).observers.push(observers[type]);return result}__name(computeHandlers,"computeHandlers"),__name2(computeHandlers,"computeHandlers");const PendingKeys=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],EmacsyPendingKeys="dthko",modifierCodes=[16,17,18,20,91,92,224,225],dragScrollMargin=6;function dragScrollSpeed(dist2){return Math.max(0,dist2)*.7+8}__name(dragScrollSpeed,"dragScrollSpeed"),__name2(dragScrollSpeed,"dragScrollSpeed");function dist(a,b){return Math.max(Math.abs(a.clientX-b.clientX),Math.abs(a.clientY-b.clientY))}__name(dist,"dist"),__name2(dist,"dist");const _MouseSelection=class{static{__name(this,"_MouseSelection")}constructor(view,startEvent,style,mustSelect){this.view=view,this.startEvent=startEvent,this.style=style,this.mustSelect=mustSelect,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=startEvent,this.scrollParent=scrollableParent(view.contentDOM),this.atoms=view.state.facet(atomicRanges).map(f=>f(view));let doc2=view.contentDOM.ownerDocument;doc2.addEventListener("mousemove",this.move=this.move.bind(this)),doc2.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=startEvent.shiftKey,this.multiple=view.state.facet(EditorState.allowMultipleSelections)&&addsSelectionRange(view,startEvent),this.dragging=isInPrimarySelection(view,startEvent)&&getClickType(startEvent)==1?null:!1}start(event){this.dragging===!1&&this.select(event)}move(event){var _a3;if(event.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&dist(this.startEvent,event)<10)return;this.select(this.lastEvent=event);let sx=0,sy=0,rect=((_a3=this.scrollParent)===null||_a3===void 0?void 0:_a3.getBoundingClientRect())||{left:0,top:0,right:this.view.win.innerWidth,bottom:this.view.win.innerHeight},margins=getScrollMargins(this.view);event.clientX-margins.left<=rect.left+dragScrollMargin?sx=-dragScrollSpeed(rect.left-event.clientX):event.clientX+margins.right>=rect.right-dragScrollMargin&&(sx=dragScrollSpeed(event.clientX-rect.right)),event.clientY-margins.top<=rect.top+dragScrollMargin?sy=-dragScrollSpeed(rect.top-event.clientY):event.clientY+margins.bottom>=rect.bottom-dragScrollMargin&&(sy=dragScrollSpeed(event.clientY-rect.bottom)),this.setScrollSpeed(sx,sy)}up(event){this.dragging==null&&this.select(this.lastEvent),this.dragging||event.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let doc2=this.view.contentDOM.ownerDocument;doc2.removeEventListener("mousemove",this.move),doc2.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=null}setScrollSpeed(sx,sy){this.scrollSpeed={x:sx,y:sy},sx||sy?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){this.scrollParent?(this.scrollParent.scrollLeft+=this.scrollSpeed.x,this.scrollParent.scrollTop+=this.scrollSpeed.y):this.view.win.scrollBy(this.scrollSpeed.x,this.scrollSpeed.y),this.dragging===!1&&this.select(this.lastEvent)}skipAtoms(sel){let ranges=null;for(let i=0;ithis.select(this.lastEvent),20)}};__name2(_MouseSelection,"MouseSelection");let MouseSelection=_MouseSelection;function addsSelectionRange(view,event){let facet=view.state.facet(clickAddsSelectionRange);return facet.length?facet[0](event):browser.mac?event.metaKey:event.ctrlKey}__name(addsSelectionRange,"addsSelectionRange"),__name2(addsSelectionRange,"addsSelectionRange");function dragMovesSelection(view,event){let facet=view.state.facet(dragMovesSelection$1);return facet.length?facet[0](event):browser.mac?!event.altKey:!event.ctrlKey}__name(dragMovesSelection,"dragMovesSelection"),__name2(dragMovesSelection,"dragMovesSelection");function isInPrimarySelection(view,event){let{main}=view.state.selection;if(main.empty)return!1;let sel=getSelection(view.root);if(!sel||sel.rangeCount==0)return!0;let rects=sel.getRangeAt(0).getClientRects();for(let i=0;i=event.clientX&&rect.top<=event.clientY&&rect.bottom>=event.clientY)return!0}return!1}__name(isInPrimarySelection,"isInPrimarySelection"),__name2(isInPrimarySelection,"isInPrimarySelection");function eventBelongsToEditor(view,event){if(!event.bubbles)return!0;if(event.defaultPrevented)return!1;for(let node=event.target,cView;node!=view.contentDOM;node=node.parentNode)if(!node||node.nodeType==11||(cView=ContentView.get(node))&&cView.ignoreEvent(event))return!1;return!0}__name(eventBelongsToEditor,"eventBelongsToEditor"),__name2(eventBelongsToEditor,"eventBelongsToEditor");const handlers=Object.create(null),observers=Object.create(null),brokenClipboardAPI=browser.ie&&browser.ie_version<15||browser.ios&&browser.webkit_version<604;function capturePaste(view){let parent=view.dom.parentNode;if(!parent)return;let target=parent.appendChild(document.createElement("textarea"));target.style.cssText="position: fixed; left: -10000px; top: 10px",target.focus(),setTimeout(()=>{view.focus(),target.remove(),doPaste(view,target.value)},50)}__name(capturePaste,"capturePaste"),__name2(capturePaste,"capturePaste");function doPaste(view,input){let{state}=view,changes,i=1,text=state.toText(input),byLine=text.lines==state.selection.ranges.length;if(lastLinewiseCopy!=null&&state.selection.ranges.every(r=>r.empty)&&lastLinewiseCopy==text.toString()){let lastLine=-1;changes=state.changeByRange(range=>{let line=state.doc.lineAt(range.from);if(line.from==lastLine)return{range};lastLine=line.from;let insert2=state.toText((byLine?text.line(i++).text:input)+state.lineBreak);return{changes:{from:line.from,insert:insert2},range:EditorSelection.cursor(range.from+insert2.length)}})}else byLine?changes=state.changeByRange(range=>{let line=text.line(i++);return{changes:{from:range.from,to:range.to,insert:line.text},range:EditorSelection.cursor(range.from+line.length)}}):changes=state.replaceSelection(text);view.dispatch(changes,{userEvent:"input.paste",scrollIntoView:!0})}__name(doPaste,"doPaste"),__name2(doPaste,"doPaste"),observers.scroll=view=>{view.inputState.lastScrollTop=view.scrollDOM.scrollTop,view.inputState.lastScrollLeft=view.scrollDOM.scrollLeft},handlers.keydown=(view,event)=>(view.inputState.setSelectionOrigin("select"),event.keyCode==27&&(view.inputState.lastEscPress=Date.now()),!1),observers.touchstart=(view,e)=>{view.inputState.lastTouchTime=Date.now(),view.inputState.setSelectionOrigin("select.pointer")},observers.touchmove=view=>{view.inputState.setSelectionOrigin("select.pointer")},handlers.mousedown=(view,event)=>{if(view.observer.flush(),view.inputState.lastTouchTime>Date.now()-2e3)return!1;let style=null;for(let makeStyle of view.state.facet(mouseSelectionStyle))if(style=makeStyle(view,event),style)break;if(!style&&event.button==0&&(style=basicMouseSelection(view,event)),style){let mustFocus=!view.hasFocus;view.inputState.startMouseSelection(new MouseSelection(view,event,style,mustFocus)),mustFocus&&view.observer.ignore(()=>focusPreventScroll(view.contentDOM));let mouseSel=view.inputState.mouseSelection;if(mouseSel)return mouseSel.start(event),!mouseSel.dragging}return!1};function rangeForClick(view,pos,bias,type){if(type==1)return EditorSelection.cursor(pos,bias);if(type==2)return groupAt(view.state,pos,bias);{let visual=LineView.find(view.docView,pos),line=view.state.doc.lineAt(visual?visual.posAtEnd:pos),from=visual?visual.posAtStart:line.from,to=visual?visual.posAtEnd:line.to;return toy>=rect.top&&y<=rect.bottom,"insideY"),inside=__name2((x,y,rect)=>insideY(y,rect)&&x>=rect.left&&x<=rect.right,"inside");function findPositionSide(view,pos,x,y){let line=LineView.find(view.docView,pos);if(!line)return 1;let off2=pos-line.posAtStart;if(off2==0)return 1;if(off2==line.length)return-1;let before=line.coordsAt(off2,-1);if(before&&inside(x,y,before))return-1;let after=line.coordsAt(off2,1);return after&&inside(x,y,after)?1:before&&insideY(y,before)?-1:1}__name(findPositionSide,"findPositionSide"),__name2(findPositionSide,"findPositionSide");function queryPos(view,event){let pos=view.posAtCoords({x:event.clientX,y:event.clientY},!1);return{pos,bias:findPositionSide(view,pos,event.clientX,event.clientY)}}__name(queryPos,"queryPos"),__name2(queryPos,"queryPos");const BadMouseDetail=browser.ie&&browser.ie_version<=11;let lastMouseDown=null,lastMouseDownCount=0,lastMouseDownTime=0;function getClickType(event){if(!BadMouseDetail)return event.detail;let last2=lastMouseDown,lastTime=lastMouseDownTime;return lastMouseDown=event,lastMouseDownTime=Date.now(),lastMouseDownCount=!last2||lastTime>Date.now()-400&&Math.abs(last2.clientX-event.clientX)<2&&Math.abs(last2.clientY-event.clientY)<2?(lastMouseDownCount+1)%3:1}__name(getClickType,"getClickType"),__name2(getClickType,"getClickType");function basicMouseSelection(view,event){let start=queryPos(view,event),type=getClickType(event),startSel=view.state.selection;return{update(update){update.docChanged&&(start.pos=update.changes.mapPos(start.pos),startSel=startSel.map(update.changes))},get(event2,extend2,multiple){let cur2=queryPos(view,event2),removed,range=rangeForClick(view,cur2.pos,cur2.bias,type);if(start.pos!=cur2.pos&&!extend2){let startRange=rangeForClick(view,start.pos,start.bias,type),from=Math.min(startRange.from,range.from),to=Math.max(startRange.to,range.to);range=from1&&(removed=removeRangeAround(startSel,cur2.pos))?removed:multiple?startSel.addRange(range):EditorSelection.create([range])}}}__name(basicMouseSelection,"basicMouseSelection"),__name2(basicMouseSelection,"basicMouseSelection");function removeRangeAround(sel,pos){for(let i=0;i=pos)return EditorSelection.create(sel.ranges.slice(0,i).concat(sel.ranges.slice(i+1)),sel.mainIndex==i?0:sel.mainIndex-(sel.mainIndex>i?1:0))}return null}__name(removeRangeAround,"removeRangeAround"),__name2(removeRangeAround,"removeRangeAround"),handlers.dragstart=(view,event)=>{let{selection:{main}}=view.state,{mouseSelection}=view.inputState;return mouseSelection&&(mouseSelection.dragging=main),event.dataTransfer&&(event.dataTransfer.setData("Text",view.state.sliceDoc(main.from,main.to)),event.dataTransfer.effectAllowed="copyMove"),!1};function dropText(view,event,text,direct){if(!text)return;let dropPos=view.posAtCoords({x:event.clientX,y:event.clientY},!1),{mouseSelection}=view.inputState,del=direct&&mouseSelection&&mouseSelection.dragging&&dragMovesSelection(view,event)?{from:mouseSelection.dragging.from,to:mouseSelection.dragging.to}:null,ins={from:dropPos,insert:text},changes=view.state.changes(del?[del,ins]:ins);view.focus(),view.dispatch({changes,selection:{anchor:changes.mapPos(dropPos,-1),head:changes.mapPos(dropPos,1)},userEvent:del?"move.drop":"input.drop"})}__name(dropText,"dropText"),__name2(dropText,"dropText"),handlers.drop=(view,event)=>{if(!event.dataTransfer)return!1;if(view.state.readOnly)return!0;let files=event.dataTransfer.files;if(files&&files.length){let text=Array(files.length),read=0,finishFile=__name2(()=>{++read==files.length&&dropText(view,event,text.filter(s2=>s2!=null).join(view.state.lineBreak),!1)},"finishFile");for(let i=0;i{/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result)||(text[i]=reader.result),finishFile()},reader.readAsText(files[i])}return!0}else{let text=event.dataTransfer.getData("Text");if(text)return dropText(view,event,text,!0),!0}return!1},handlers.paste=(view,event)=>{if(view.state.readOnly)return!0;view.observer.flush();let data=brokenClipboardAPI?null:event.clipboardData;return data?(doPaste(view,data.getData("text/plain")||data.getData("text/uri-text")),!0):(capturePaste(view),!1)};function captureCopy(view,text){let parent=view.dom.parentNode;if(!parent)return;let target=parent.appendChild(document.createElement("textarea"));target.style.cssText="position: fixed; left: -10000px; top: 10px",target.value=text,target.focus(),target.selectionEnd=text.length,target.selectionStart=0,setTimeout(()=>{target.remove(),view.focus()},50)}__name(captureCopy,"captureCopy"),__name2(captureCopy,"captureCopy");function copiedRange(state){let content2=[],ranges=[],linewise=!1;for(let range of state.selection.ranges)range.empty||(content2.push(state.sliceDoc(range.from,range.to)),ranges.push(range));if(!content2.length){let upto=-1;for(let{from}of state.selection.ranges){let line=state.doc.lineAt(from);line.number>upto&&(content2.push(line.text),ranges.push({from:line.from,to:Math.min(state.doc.length,line.to+1)})),upto=line.number}linewise=!0}return{text:content2.join(state.lineBreak),ranges,linewise}}__name(copiedRange,"copiedRange"),__name2(copiedRange,"copiedRange");let lastLinewiseCopy=null;handlers.copy=handlers.cut=(view,event)=>{let{text,ranges,linewise}=copiedRange(view.state);if(!text&&!linewise)return!1;lastLinewiseCopy=linewise?text:null,event.type=="cut"&&!view.state.readOnly&&view.dispatch({changes:ranges,scrollIntoView:!0,userEvent:"delete.cut"});let data=brokenClipboardAPI?null:event.clipboardData;return data?(data.clearData(),data.setData("text/plain",text),!0):(captureCopy(view,text),!1)};const isFocusChange=Annotation.define();function focusChangeTransaction(state,focus){let effects=[];for(let getEffect of state.facet(focusChangeEffect)){let effect=getEffect(state,focus);effect&&effects.push(effect)}return effects?state.update({effects,annotations:isFocusChange.of(!0)}):null}__name(focusChangeTransaction,"focusChangeTransaction"),__name2(focusChangeTransaction,"focusChangeTransaction");function updateForFocusChange(view){setTimeout(()=>{let focus=view.hasFocus;if(focus!=view.inputState.notifiedFocused){let tr=focusChangeTransaction(view.state,focus);tr?view.dispatch(tr):view.update([])}},10)}__name(updateForFocusChange,"updateForFocusChange"),__name2(updateForFocusChange,"updateForFocusChange"),observers.focus=view=>{view.inputState.lastFocusTime=Date.now(),!view.scrollDOM.scrollTop&&(view.inputState.lastScrollTop||view.inputState.lastScrollLeft)&&(view.scrollDOM.scrollTop=view.inputState.lastScrollTop,view.scrollDOM.scrollLeft=view.inputState.lastScrollLeft),updateForFocusChange(view)},observers.blur=view=>{view.observer.clearSelectionRange(),updateForFocusChange(view)},observers.compositionstart=observers.compositionupdate=view=>{view.inputState.compositionFirstChange==null&&(view.inputState.compositionFirstChange=!0),view.inputState.composing<0&&(view.inputState.composing=0)},observers.compositionend=view=>{view.inputState.composing=-1,view.inputState.compositionEndedAt=Date.now(),view.inputState.compositionPendingKey=!0,view.inputState.compositionPendingChange=view.observer.pendingRecords().length>0,view.inputState.compositionFirstChange=null,browser.chrome&&browser.android?view.observer.flushSoon():view.inputState.compositionPendingChange?Promise.resolve().then(()=>view.observer.flush()):setTimeout(()=>{view.inputState.composing<0&&view.docView.hasComposition&&view.update([])},50)},observers.contextmenu=view=>{view.inputState.lastContextMenu=Date.now()},handlers.beforeinput=(view,event)=>{var _a3;let pending;if(browser.chrome&&browser.android&&(pending=PendingKeys.find(key=>key.inputType==event.inputType))&&(view.observer.delayAndroidKey(pending.key,pending.keyCode),pending.key=="Backspace"||pending.key=="Delete")){let startViewHeight=((_a3=window.visualViewport)===null||_a3===void 0?void 0:_a3.height)||0;setTimeout(()=>{var _a4;(((_a4=window.visualViewport)===null||_a4===void 0?void 0:_a4.height)||0)>startViewHeight+10&&view.hasFocus&&(view.contentDOM.blur(),view.focus())},100)}return!1};const appliedFirefoxHack=new Set;function firefoxCopyCutHack(doc2){appliedFirefoxHack.has(doc2)||(appliedFirefoxHack.add(doc2),doc2.addEventListener("copy",()=>{}),doc2.addEventListener("cut",()=>{}))}__name(firefoxCopyCutHack,"firefoxCopyCutHack"),__name2(firefoxCopyCutHack,"firefoxCopyCutHack");const wrappingWhiteSpace=["pre-wrap","normal","pre-line","break-spaces"],_HeightOracle=class{static{__name(this,"_HeightOracle")}constructor(lineWrapping){this.lineWrapping=lineWrapping,this.doc=Text.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30,this.heightChanged=!1}heightForGap(from,to){let lines=this.doc.lineAt(to).number-this.doc.lineAt(from).number+1;return this.lineWrapping&&(lines+=Math.max(0,Math.ceil((to-from-lines*this.lineLength*.5)/this.lineLength))),this.lineHeight*lines}heightForLine(length){return this.lineWrapping?(1+Math.max(0,Math.ceil((length-this.lineLength)/(this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(doc2){return this.doc=doc2,this}mustRefreshForWrapping(whiteSpace){return wrappingWhiteSpace.indexOf(whiteSpace)>-1!=this.lineWrapping}mustRefreshForHeights(lineHeights){let newHeight=!1;for(let i=0;i-1,changed=Math.round(lineHeight)!=Math.round(this.lineHeight)||this.lineWrapping!=lineWrapping;if(this.lineWrapping=lineWrapping,this.lineHeight=lineHeight,this.charWidth=charWidth,this.textHeight=textHeight,this.lineLength=lineLength,changed){this.heightSamples={};for(let i=0;i0}set outdated(value){this.flags=(value?2:0)|this.flags&-3}setHeight(oracle,height){this.height!=height&&(Math.abs(this.height-height)>Epsilon&&(oracle.heightChanged=!0),this.height=height)}replace(_from,_to,nodes){return _HeightMap2.of(nodes)}decomposeLeft(_to,result){result.push(this)}decomposeRight(_from,result){result.push(this)}applyChanges(decorations2,oldDoc,oracle,changes){let me=this,doc2=oracle.doc;for(let i=changes.length-1;i>=0;i--){let{fromA,toA,fromB,toB}=changes[i],start=me.lineAt(fromA,QueryType$1.ByPosNoHeight,oracle.setDoc(oldDoc),0,0),end=start.to>=toA?start:me.lineAt(toA,QueryType$1.ByPosNoHeight,oracle,0,0);for(toB+=end.to-toA,toA=end.to;i>0&&start.from<=changes[i-1].toA;)fromA=changes[i-1].fromA,fromB=changes[i-1].fromB,i--,fromAafter*2){let split=nodes[i-1];split.break?nodes.splice(--i,1,split.left,null,split.right):nodes.splice(--i,1,split.left,split.right),j+=1+split.break,before-=split.size}else if(after>before*2){let split=nodes[j];split.break?nodes.splice(j,1,split.left,null,split.right):nodes.splice(j,1,split.left,split.right),j+=2+split.break,after-=split.size}else break;else if(before=offset2&&f(this.blockAt(0,oracle,top2,offset2))}updateHeight(oracle,offset2=0,_force=!1,measured){return measured&&measured.from<=offset2&&measured.more&&this.setHeight(oracle,measured.heights[measured.index++]),this.outdated=!1,this}toString(){return`block(${this.length})`}};__name2(_HeightMapBlock,"HeightMapBlock");let HeightMapBlock=_HeightMapBlock;const _HeightMapText=class _HeightMapText2 extends HeightMapBlock{static{__name(this,"_HeightMapText")}constructor(length,height){super(length,height,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0}blockAt(_height,_oracle,top2,offset2){return new BlockInfo(offset2,this.length,top2,this.height,this.breaks)}replace(_from,_to,nodes){let node=nodes[0];return nodes.length==1&&(node instanceof _HeightMapText2||node instanceof HeightMapGap&&node.flags&4)&&Math.abs(this.length-node.length)<10?(node instanceof HeightMapGap?node=new _HeightMapText2(node.length,this.height):node.height=this.height,this.outdated||(node.outdated=!1),node):HeightMap.of(nodes)}updateHeight(oracle,offset2=0,force=!1,measured){return measured&&measured.from<=offset2&&measured.more?this.setHeight(oracle,measured.heights[measured.index++]):(force||this.outdated)&&this.setHeight(oracle,Math.max(this.widgetHeight,oracle.heightForLine(this.length-this.collapsed))+this.breaks*oracle.lineHeight),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}};__name2(_HeightMapText,"HeightMapText");let HeightMapText=_HeightMapText;const _HeightMapGap=class _HeightMapGap2 extends HeightMap{static{__name(this,"_HeightMapGap")}constructor(length){super(length,0)}heightMetrics(oracle,offset2){let firstLine=oracle.doc.lineAt(offset2).number,lastLine=oracle.doc.lineAt(offset2+this.length).number,lines=lastLine-firstLine+1,perLine,perChar=0;if(oracle.lineWrapping){let totalPerLine=Math.min(this.height,oracle.lineHeight*lines);perLine=totalPerLine/lines,this.length>lines+1&&(perChar=(this.height-totalPerLine)/(this.length-lines-1))}else perLine=this.height/lines;return{firstLine,lastLine,perLine,perChar}}blockAt(height,oracle,top2,offset2){let{firstLine,lastLine,perLine,perChar}=this.heightMetrics(oracle,offset2);if(oracle.lineWrapping){let guess=offset2+Math.round(Math.max(0,Math.min(1,(height-top2)/this.height))*this.length),line=oracle.doc.lineAt(guess),lineHeight=perLine+line.length*perChar,lineTop=Math.max(top2,height-lineHeight/2);return new BlockInfo(line.from,line.length,lineTop,lineHeight,0)}else{let line=Math.max(0,Math.min(lastLine-firstLine,Math.floor((height-top2)/perLine))),{from,length}=oracle.doc.line(firstLine+line);return new BlockInfo(from,length,top2+perLine*line,perLine,0)}}lineAt(value,type,oracle,top2,offset2){if(type==QueryType$1.ByHeight)return this.blockAt(value,oracle,top2,offset2);if(type==QueryType$1.ByPosNoHeight){let{from,to}=oracle.doc.lineAt(value);return new BlockInfo(from,to-from,0,0,0)}let{firstLine,perLine,perChar}=this.heightMetrics(oracle,offset2),line=oracle.doc.lineAt(value),lineHeight=perLine+line.length*perChar,linesAbove=line.number-firstLine,lineTop=top2+perLine*linesAbove+perChar*(line.from-offset2-linesAbove);return new BlockInfo(line.from,line.length,Math.max(top2,Math.min(lineTop,top2+this.height-lineHeight)),lineHeight,0)}forEachLine(from,to,oracle,top2,offset2,f){from=Math.max(from,offset2),to=Math.min(to,offset2+this.length);let{firstLine,perLine,perChar}=this.heightMetrics(oracle,offset2);for(let pos=from,lineTop=top2;pos<=to;){let line=oracle.doc.lineAt(pos);if(pos==from){let linesAbove=line.number-firstLine;lineTop+=perLine*linesAbove+perChar*(from-offset2-linesAbove)}let lineHeight=perLine+perChar*line.length;f(new BlockInfo(line.from,line.length,lineTop,lineHeight,0)),lineTop+=lineHeight,pos=line.to+1}}replace(from,to,nodes){let after=this.length-to;if(after>0){let last2=nodes[nodes.length-1];last2 instanceof _HeightMapGap2?nodes[nodes.length-1]=new _HeightMapGap2(last2.length+after):nodes.push(null,new _HeightMapGap2(after-1))}if(from>0){let first=nodes[0];first instanceof _HeightMapGap2?nodes[0]=new _HeightMapGap2(from+first.length):nodes.unshift(new _HeightMapGap2(from-1),null)}return HeightMap.of(nodes)}decomposeLeft(to,result){result.push(new _HeightMapGap2(to-1),null)}decomposeRight(from,result){result.push(null,new _HeightMapGap2(this.length-from-1))}updateHeight(oracle,offset2=0,force=!1,measured){let end=offset2+this.length;if(measured&&measured.from<=offset2+this.length&&measured.more){let nodes=[],pos=Math.max(offset2,measured.from),singleHeight=-1;for(measured.from>offset2&&nodes.push(new _HeightMapGap2(measured.from-offset2-1).updateHeight(oracle,offset2));pos<=end&&measured.more;){let len=oracle.doc.lineAt(pos).length;nodes.length&&nodes.push(null);let height=measured.heights[measured.index++];singleHeight==-1?singleHeight=height:Math.abs(height-singleHeight)>=Epsilon&&(singleHeight=-2);let line=new HeightMapText(len,height);line.outdated=!1,nodes.push(line),pos+=len+1}pos<=end&&nodes.push(null,new _HeightMapGap2(end-pos).updateHeight(oracle,pos));let result=HeightMap.of(nodes);return(singleHeight<0||Math.abs(result.height-this.height)>=Epsilon||Math.abs(singleHeight-this.heightMetrics(oracle,offset2).perLine)>=Epsilon)&&(oracle.heightChanged=!0),result}else(force||this.outdated)&&(this.setHeight(oracle,oracle.heightForGap(offset2,offset2+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}};__name2(_HeightMapGap,"HeightMapGap");let HeightMapGap=_HeightMapGap;const _HeightMapBranch=class extends HeightMap{static{__name(this,"_HeightMapBranch")}constructor(left,brk,right){super(left.length+brk+right.length,left.height+right.height,brk|(left.outdated||right.outdated?2:0)),this.left=left,this.right=right,this.size=left.size+right.size}get break(){return this.flags&1}blockAt(height,oracle,top2,offset2){let mid=top2+this.left.height;return heightrightOffset))return base2;let subQuery=type==QueryType$1.ByPosNoHeight?QueryType$1.ByPosNoHeight:QueryType$1.ByPos;return left?base2.join(this.right.lineAt(rightOffset,subQuery,oracle,rightTop,rightOffset)):this.left.lineAt(rightOffset,subQuery,oracle,top2,offset2).join(base2)}forEachLine(from,to,oracle,top2,offset2,f){let rightTop=top2+this.left.height,rightOffset=offset2+this.left.length+this.break;if(this.break)from=rightOffset&&this.right.forEachLine(from,to,oracle,rightTop,rightOffset,f);else{let mid=this.lineAt(rightOffset,QueryType$1.ByPos,oracle,top2,offset2);from=from&&mid.from<=to&&f(mid),to>mid.to&&this.right.forEachLine(mid.to+1,to,oracle,rightTop,rightOffset,f)}}replace(from,to,nodes){let rightStart=this.left.length+this.break;if(tothis.left.length)return this.balanced(this.left,this.right.replace(from-rightStart,to-rightStart,nodes));let result=[];from>0&&this.decomposeLeft(from,result);let left=result.length;for(let node of nodes)result.push(node);if(from>0&&mergeGaps(result,left-1),to=left&&result.push(null)),to>left&&this.right.decomposeLeft(to-left,result)}decomposeRight(from,result){let left=this.left.length,right=left+this.break;if(from>=right)return this.right.decomposeRight(from-right,result);from2*right.size||right.size>2*left.size?HeightMap.of(this.break?[left,null,right]:[left,right]):(this.left=left,this.right=right,this.height=left.height+right.height,this.outdated=left.outdated||right.outdated,this.size=left.size+right.size,this.length=left.length+this.break+right.length,this)}updateHeight(oracle,offset2=0,force=!1,measured){let{left,right}=this,rightStart=offset2+left.length+this.break,rebalance=null;return measured&&measured.from<=offset2+left.length&&measured.more?rebalance=left=left.updateHeight(oracle,offset2,force,measured):left.updateHeight(oracle,offset2,force),measured&&measured.from<=rightStart+right.length&&measured.more?rebalance=right=right.updateHeight(oracle,rightStart,force,measured):right.updateHeight(oracle,rightStart,force),rebalance?this.balanced(left,right):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}};__name2(_HeightMapBranch,"HeightMapBranch");let HeightMapBranch=_HeightMapBranch;function mergeGaps(nodes,around){let before,after;nodes[around]==null&&(before=nodes[around-1])instanceof HeightMapGap&&(after=nodes[around+1])instanceof HeightMapGap&&nodes.splice(around-1,3,new HeightMapGap(before.length+1+after.length))}__name(mergeGaps,"mergeGaps"),__name2(mergeGaps,"mergeGaps");const relevantWidgetHeight=5,_NodeBuilder=class _NodeBuilder2{static{__name(this,"_NodeBuilder")}constructor(pos,oracle){this.pos=pos,this.oracle=oracle,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=pos}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(_from,to){if(this.lineStart>-1){let end=Math.min(to,this.lineEnd),last2=this.nodes[this.nodes.length-1];last2 instanceof HeightMapText?last2.length+=end-this.pos:(end>this.pos||!this.isCovered)&&this.nodes.push(new HeightMapText(end-this.pos,-1)),this.writtenTo=end,to>end&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=to}point(from,to,deco){if(from=relevantWidgetHeight)&&this.addLineDeco(height,breaks,len)}else to>from&&this.span(from,to);this.lineEnd>-1&&this.lineEnd-1)return;let{from,to}=this.oracle.doc.lineAt(this.pos);this.lineStart=from,this.lineEnd=to,this.writtenTofrom&&this.nodes.push(new HeightMapText(this.pos-from,-1)),this.writtenTo=this.pos}blankContent(from,to){let gap=new HeightMapGap(to-from);return this.oracle.doc.lineAt(from).to==to&&(gap.flags|=4),gap}ensureLine(){this.enterLine();let last2=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(last2 instanceof HeightMapText)return last2;let line=new HeightMapText(0,-1);return this.nodes.push(line),line}addBlock(block){this.enterLine();let deco=block.deco;deco&&deco.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(block),this.writtenTo=this.pos=this.pos+block.length,deco&&deco.endSide>0&&(this.covering=block)}addLineDeco(height,breaks,length){let line=this.ensureLine();line.length+=length,line.collapsed+=length,line.widgetHeight=Math.max(line.widgetHeight,height),line.breaks+=breaks,this.writtenTo=this.pos=this.pos+length}finish(from){let last2=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(last2 instanceof HeightMapText)&&!this.isCovered?this.nodes.push(new HeightMapText(0,-1)):(this.writtenToelt.clientHeight||elt.scrollWidth>elt.clientWidth)&&style.overflow!="visible"){let parentRect=elt.getBoundingClientRect();left=Math.max(left,parentRect.left),right=Math.min(right,parentRect.right),top2=Math.max(top2,parentRect.top),bottom=parent==dom.parentNode?parentRect.bottom:Math.min(bottom,parentRect.bottom)}parent=style.position=="absolute"||style.position=="fixed"?elt.offsetParent:elt.parentNode}else if(parent.nodeType==11)parent=parent.host;else break;return{left:left-rect.left,right:Math.max(left,right)-rect.left,top:top2-(rect.top+paddingTop),bottom:Math.max(top2,bottom)-(rect.top+paddingTop)}}__name(visiblePixelRange,"visiblePixelRange"),__name2(visiblePixelRange,"visiblePixelRange");function fullPixelRange(dom,paddingTop){let rect=dom.getBoundingClientRect();return{left:0,right:rect.right-rect.left,top:paddingTop,bottom:rect.bottom-(rect.top+paddingTop)}}__name(fullPixelRange,"fullPixelRange"),__name2(fullPixelRange,"fullPixelRange");const _LineGap=class{static{__name(this,"_LineGap")}constructor(from,to,size){this.from=from,this.to=to,this.size=size}static same(a,b){if(a.length!=b.length)return!1;for(let i=0;itypeof v!="function"&&v.class=="cm-lineWrapping");this.heightOracle=new HeightOracle(guessWrapping),this.stateDeco=state.facet(decorations).filter(d=>typeof d!="function"),this.heightMap=HeightMap.empty().applyChanges(this.stateDeco,Text.empty,this.heightOracle.setDoc(state.doc),[new ChangedRange(0,0,0,state.doc.length)]),this.viewport=this.getViewport(0,null),this.updateViewportLines(),this.updateForViewport(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=Decoration.set(this.lineGaps.map(gap=>gap.draw(this,!1))),this.computeVisibleRanges()}updateForViewport(){let viewports=[this.viewport],{main}=this.state.selection;for(let i=0;i<=1;i++){let pos=i?main.head:main.anchor;if(!viewports.some(({from,to})=>pos>=from&&pos<=to)){let{from,to}=this.lineBlockAt(pos);viewports.push(new Viewport(from,to))}}this.viewports=viewports.sort((a,b)=>a.from-b.from),this.scaler=this.heightMap.height<=7e6?IdScaler:new BigScaler(this.heightOracle,this.heightMap,this.viewports)}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,block=>{this.viewportLines.push(this.scaler.scale==1?block:scaleBlock(block,this.scaler))})}update(update,scrollTarget=null){this.state=update.state;let prevDeco=this.stateDeco;this.stateDeco=this.state.facet(decorations).filter(d=>typeof d!="function");let contentChanges=update.changedRanges,heightChanges=ChangedRange.extendWithRanges(contentChanges,heightRelevantDecoChanges(prevDeco,this.stateDeco,update?update.changes:ChangeSet.empty(this.state.doc.length))),prevHeight=this.heightMap.height,scrollAnchor=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollTop);this.heightMap=this.heightMap.applyChanges(this.stateDeco,update.startState.doc,this.heightOracle.setDoc(this.state.doc),heightChanges),this.heightMap.height!=prevHeight&&(update.flags|=2),scrollAnchor?(this.scrollAnchorPos=update.changes.mapPos(scrollAnchor.from,-1),this.scrollAnchorHeight=scrollAnchor.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=this.heightMap.height);let viewport=heightChanges.length?this.mapViewport(this.viewport,update.changes):this.viewport;(scrollTarget&&(scrollTarget.range.headviewport.to)||!this.viewportIsAppropriate(viewport))&&(viewport=this.getViewport(0,scrollTarget));let updateLines=!update.changes.empty||update.flags&2||viewport.from!=this.viewport.from||viewport.to!=this.viewport.to;this.viewport=viewport,this.updateForViewport(),updateLines&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,update.changes))),update.flags|=this.computeVisibleRanges(),scrollTarget&&(this.scrollTarget=scrollTarget),!this.mustEnforceCursorAssoc&&update.selectionSet&&update.view.lineWrapping&&update.state.selection.main.empty&&update.state.selection.main.assoc&&!update.state.facet(nativeSelectionHidden)&&(this.mustEnforceCursorAssoc=!0)}measure(view){let dom=view.contentDOM,style=window.getComputedStyle(dom),oracle=this.heightOracle,whiteSpace=style.whiteSpace;this.defaultTextDirection=style.direction=="rtl"?Direction.RTL:Direction.LTR;let refresh=this.heightOracle.mustRefreshForWrapping(whiteSpace),domRect=dom.getBoundingClientRect(),measureContent=refresh||this.mustMeasureContent||this.contentDOMHeight!=domRect.height;this.contentDOMHeight=domRect.height,this.mustMeasureContent=!1;let result=0,bias=0;if(domRect.width&&domRect.height){let scaleX=domRect.width/dom.offsetWidth,scaleY=domRect.height/dom.offsetHeight;(scaleX>.995&&scaleX<1.005||!isFinite(scaleX)||Math.abs(domRect.width-dom.offsetWidth)<1)&&(scaleX=1),(scaleY>.995&&scaleY<1.005||!isFinite(scaleY)||Math.abs(domRect.height-dom.offsetHeight)<1)&&(scaleY=1),(this.scaleX!=scaleX||this.scaleY!=scaleY)&&(this.scaleX=scaleX,this.scaleY=scaleY,result|=8,refresh=measureContent=!0)}let paddingTop=(parseInt(style.paddingTop)||0)*this.scaleY,paddingBottom=(parseInt(style.paddingBottom)||0)*this.scaleY;(this.paddingTop!=paddingTop||this.paddingBottom!=paddingBottom)&&(this.paddingTop=paddingTop,this.paddingBottom=paddingBottom,result|=10),this.editorWidth!=view.scrollDOM.clientWidth&&(oracle.lineWrapping&&(measureContent=!0),this.editorWidth=view.scrollDOM.clientWidth,result|=8);let scrollTop=view.scrollDOM.scrollTop*this.scaleY;this.scrollTop!=scrollTop&&(this.scrollAnchorHeight=-1,this.scrollTop=scrollTop),this.scrolledToBottom=isScrolledToBottom(view.scrollDOM);let pixelViewport=(this.printing?fullPixelRange:visiblePixelRange)(dom,this.paddingTop),dTop=pixelViewport.top-this.pixelViewport.top,dBottom=pixelViewport.bottom-this.pixelViewport.bottom;this.pixelViewport=pixelViewport;let inView=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(inView!=this.inView&&(this.inView=inView,inView&&(measureContent=!0)),!this.inView&&!this.scrollTarget)return 0;let contentWidth=domRect.width;if((this.contentDOMWidth!=contentWidth||this.editorHeight!=view.scrollDOM.clientHeight)&&(this.contentDOMWidth=domRect.width,this.editorHeight=view.scrollDOM.clientHeight,result|=8),measureContent){let lineHeights=view.docView.measureVisibleLineHeights(this.viewport);if(oracle.mustRefreshForHeights(lineHeights)&&(refresh=!0),refresh||oracle.lineWrapping&&Math.abs(contentWidth-this.contentDOMWidth)>oracle.charWidth){let{lineHeight,charWidth,textHeight}=view.docView.measureTextSize();refresh=lineHeight>0&&oracle.refresh(whiteSpace,lineHeight,charWidth,textHeight,contentWidth/charWidth,lineHeights),refresh&&(view.docView.minWidth=0,result|=8)}dTop>0&&dBottom>0?bias=Math.max(dTop,dBottom):dTop<0&&dBottom<0&&(bias=Math.min(dTop,dBottom)),oracle.heightChanged=!1;for(let vp of this.viewports){let heights=vp.from==this.viewport.from?lineHeights:view.docView.measureVisibleLineHeights(vp);this.heightMap=(refresh?HeightMap.empty().applyChanges(this.stateDeco,Text.empty,this.heightOracle,[new ChangedRange(0,0,0,view.state.doc.length)]):this.heightMap).updateHeight(oracle,0,refresh,new MeasuredHeights(vp.from,heights))}oracle.heightChanged&&(result|=2)}let viewportChange=!this.viewportIsAppropriate(this.viewport,bias)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return viewportChange&&(this.viewport=this.getViewport(bias,this.scrollTarget)),this.updateForViewport(),(result&2||viewportChange)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(refresh?[]:this.lineGaps,view)),result|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,view.docView.enforceCursorAssoc()),result}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(bias,scrollTarget){let marginTop=.5-Math.max(-.5,Math.min(.5,bias/1e3/2)),map2=this.heightMap,oracle=this.heightOracle,{visibleTop,visibleBottom}=this,viewport=new Viewport(map2.lineAt(visibleTop-marginTop*1e3,QueryType$1.ByHeight,oracle,0,0).from,map2.lineAt(visibleBottom+(1-marginTop)*1e3,QueryType$1.ByHeight,oracle,0,0).to);if(scrollTarget){let{head}=scrollTarget.range;if(headviewport.to){let viewHeight=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),block=map2.lineAt(head,QueryType$1.ByPos,oracle,0,0),topPos;scrollTarget.y=="center"?topPos=(block.top+block.bottom)/2-viewHeight/2:scrollTarget.y=="start"||scrollTarget.y=="nearest"&&head=visibleBottom+Math.max(10,Math.min(bias,250)))&&top2>visibleTop-2*1e3&&bottom>1,doubleMargin=margin<<1;if(this.defaultTextDirection!=Direction.LTR&&!wrapping)return[];let gaps=[],addGap=__name2((from,to,line,structure)=>{if(to-fromfrom&&posgap2.from>=line.from&&gap2.to<=line.to&&Math.abs(gap2.from-from)gap2.frompos));if(!gap){if(tor.from<=to&&r.to>=to)){let lineStart=mayMeasure.moveToLineBoundary(EditorSelection.cursor(to),!1,!0).head;lineStart>from&&(to=lineStart)}gap=new LineGap(from,to,this.gapSize(line,from,to,structure))}gaps.push(gap)},"addGap");for(let line of this.viewportLines){if(line.lengthline.from&&addGap(line.from,viewFrom,line,structure),viewTogap.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(){let deco=this.stateDeco;this.lineGaps.length&&(deco=deco.concat(this.lineGapDeco));let ranges=[];RangeSet.spans(deco,this.viewport.from,this.viewport.to,{span(from,to){ranges.push({from,to})},point(){}},20);let changed=ranges.length!=this.visibleRanges.length||this.visibleRanges.some((r,i)=>r.from!=ranges[i].from||r.to!=ranges[i].to);return this.visibleRanges=ranges,changed?4:0}lineBlockAt(pos){return pos>=this.viewport.from&&pos<=this.viewport.to&&this.viewportLines.find(b=>b.from<=pos&&b.to>=pos)||scaleBlock(this.heightMap.lineAt(pos,QueryType$1.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(height){return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height),QueryType$1.ByHeight,this.heightOracle,0,0),this.scaler)}scrollAnchorAt(scrollTop){let block=this.lineBlockAtHeight(scrollTop+8);return block.from>=this.viewport.from||this.viewportLines[0].top-scrollTop>200?block:this.viewportLines[0]}elementAtHeight(height){return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}};__name2(_ViewState,"ViewState");let ViewState=_ViewState;const _Viewport=class{static{__name(this,"_Viewport")}constructor(from,to){this.from=from,this.to=to}};__name2(_Viewport,"Viewport");let Viewport=_Viewport;function lineStructure(from,to,stateDeco){let ranges=[],pos=from,total=0;return RangeSet.spans(stateDeco,from,to,{span(){},point(from2,to2){from2>pos&&(ranges.push({from:pos,to:from2}),total+=from2-pos),pos=to2}},20),pos=1)return ranges[ranges.length-1].to;let dist2=Math.floor(total*ratio);for(let i=0;;i++){let{from,to}=ranges[i],size=to-from;if(dist2<=size)return from+dist2;dist2-=size}}__name(findPosition,"findPosition"),__name2(findPosition,"findPosition");function findFraction(structure,pos){let counted=0;for(let{from,to}of structure.ranges){if(pos<=to){counted+=pos-from;break}counted+=to-from}return counted/structure.total}__name(findFraction,"findFraction"),__name2(findFraction,"findFraction");function find(array,f){for(let val of array)if(f(val))return val}__name(find,"find"),__name2(find,"find");const IdScaler={toDOM(n2){return n2},fromDOM(n2){return n2},scale:1},_BigScaler=class{static{__name(this,"_BigScaler")}constructor(oracle,heightMap,viewports){let vpHeight=0,base2=0,domBase=0;this.viewports=viewports.map(({from,to})=>{let top2=heightMap.lineAt(from,QueryType$1.ByPos,oracle,0,0).top,bottom=heightMap.lineAt(to,QueryType$1.ByPos,oracle,0,0).bottom;return vpHeight+=bottom-top2,{from,to,top:top2,bottom,domTop:0,domBottom:0}}),this.scale=(7e6-vpHeight)/(heightMap.height-vpHeight);for(let obj of this.viewports)obj.domTop=domBase+(obj.top-base2)*this.scale,domBase=obj.domBottom=obj.domTop+(obj.bottom-obj.top),base2=obj.bottom}toDOM(n2){for(let i=0,base2=0,domBase=0;;i++){let vp=iscaleBlock(b,scaler)):block._content)}__name(scaleBlock,"scaleBlock"),__name2(scaleBlock,"scaleBlock");const theme=Facet.define({combine:strs=>strs.join(" ")}),darkTheme=Facet.define({combine:values=>values.indexOf(!0)>-1}),baseThemeID=StyleModule.newName(),baseLightID=StyleModule.newName(),baseDarkID=StyleModule.newName(),lightDarkIDs={"&light":"."+baseLightID,"&dark":"."+baseDarkID};function buildTheme(main,spec,scopes){return new StyleModule(spec,{finish(sel){return/&/.test(sel)?sel.replace(/&\w*/,m=>{if(m=="&")return main;if(!scopes||!scopes[m])throw new RangeError(`Unsupported selector: ${m}`);return scopes[m]}):main+" "+sel}})}__name(buildTheme,"buildTheme"),__name2(buildTheme,"buildTheme");const baseTheme$1$2=buildTheme("."+baseThemeID,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#444"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",insetInlineStart:0,zIndex:200},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",borderRight:"1px solid #ddd"},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top"},".cm-highlightSpace:before":{content:"attr(data-display)",position:"absolute",pointerEvents:"none",color:"#888"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},lightDarkIDs),LineBreakPlaceholder="\uFFFF",_DOMReader=class{static{__name(this,"_DOMReader")}constructor(points,state){this.points=points,this.text="",this.lineSeparator=state.facet(EditorState.lineSeparator)}append(text){this.text+=text}lineBreak(){this.text+=LineBreakPlaceholder}readRange(start,end){if(!start)return this;let parent=start.parentNode;for(let cur2=start;;){this.findPointBefore(parent,cur2);let oldLen=this.text.length;this.readNode(cur2);let next=cur2.nextSibling;if(next==end)break;let view=ContentView.get(cur2),nextView=ContentView.get(next);(view&&nextView?view.breakAfter:(view?view.breakAfter:isBlockElement(cur2))||isBlockElement(next)&&(cur2.nodeName!="BR"||cur2.cmIgnore)&&this.text.length>oldLen)&&this.lineBreak(),cur2=next}return this.findPointBefore(parent,end),this}readTextNode(node){let text=node.nodeValue;for(let point of this.points)point.node==node&&(point.pos=this.text.length+Math.min(point.offset,text.length));for(let off2=0,re=this.lineSeparator?null:/\r\n?|\n/g;;){let nextBreak=-1,breakSize=1,m;if(this.lineSeparator?(nextBreak=text.indexOf(this.lineSeparator,off2),breakSize=this.lineSeparator.length):(m=re.exec(text))&&(nextBreak=m.index,breakSize=m[0].length),this.append(text.slice(off2,nextBreak<0?text.length:nextBreak)),nextBreak<0)break;if(this.lineBreak(),breakSize>1)for(let point of this.points)point.node==node&&point.pos>this.text.length&&(point.pos-=breakSize-1);off2=nextBreak+breakSize}}readNode(node){if(node.cmIgnore)return;let view=ContentView.get(node),fromView=view&&view.overrideDOMText;if(fromView!=null){this.findPointInside(node,fromView.length);for(let i=fromView.iter();!i.next().done;)i.lineBreak?this.lineBreak():this.append(i.value)}else node.nodeType==3?this.readTextNode(node):node.nodeName=="BR"?node.nextSibling&&this.lineBreak():node.nodeType==1&&this.readRange(node.firstChild,null)}findPointBefore(node,next){for(let point of this.points)point.node==node&&node.childNodes[point.offset]==next&&(point.pos=this.text.length)}findPointInside(node,length){for(let point of this.points)(node.nodeType==3?point.node==node:node.contains(point.node))&&(point.pos=this.text.length+(isAtEnd(node,point.node,point.offset)?length:0))}};__name2(_DOMReader,"DOMReader");let DOMReader=_DOMReader;function isAtEnd(parent,node,offset2){for(;;){if(!node||offset2-1)this.newSel=null;else if(start>-1&&(this.bounds=view.docView.domBoundsAround(start,end,0))){let selPoints=iHead||iAnchor?[]:selectionPoints(view),reader=new DOMReader(selPoints,view.state);reader.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=reader.text,this.newSel=selectionFromPoints(selPoints,this.bounds.from)}else{let domSel=view.observer.selectionRange,head=iHead&&iHead.node==domSel.focusNode&&iHead.offset==domSel.focusOffset||!contains(view.contentDOM,domSel.focusNode)?view.state.selection.main.head:view.docView.posFromDOM(domSel.focusNode,domSel.focusOffset),anchor=iAnchor&&iAnchor.node==domSel.anchorNode&&iAnchor.offset==domSel.anchorOffset||!contains(view.contentDOM,domSel.anchorNode)?view.state.selection.main.anchor:view.docView.posFromDOM(domSel.anchorNode,domSel.anchorOffset);this.newSel=EditorSelection.single(anchor,head)}}};__name2(_DOMChange,"DOMChange");let DOMChange=_DOMChange;function applyDOMChange(view,domChange){let change,{newSel}=domChange,sel=view.state.selection.main,lastKey=view.inputState.lastKeyTime>Date.now()-100?view.inputState.lastKeyCode:-1;if(domChange.bounds){let{from,to}=domChange.bounds,preferredPos=sel.from,preferredSide=null;(lastKey===8||browser.android&&domChange.text.length=sel.from&&change.to<=sel.to&&(change.from!=sel.from||change.to!=sel.to)&&sel.to-sel.from-(change.to-change.from)<=4?change={from:sel.from,to:sel.to,insert:view.state.doc.slice(sel.from,change.from).append(change.insert).append(view.state.doc.slice(change.to,sel.to))}:(browser.mac||browser.android)&&change&&change.from==change.to&&change.from==sel.head-1&&/^\. ?$/.test(change.insert.toString())&&view.contentDOM.getAttribute("autocorrect")=="off"?(newSel&&change.insert.length==2&&(newSel=EditorSelection.single(newSel.main.anchor-1,newSel.main.head-1)),change={from:sel.from,to:sel.to,insert:Text.of([" "])}):browser.chrome&&change&&change.from==change.to&&change.from==sel.head&&change.insert.toString()==` `&&view.lineWrapping&&(newSel&&(newSel=EditorSelection.single(newSel.main.anchor-1,newSel.main.head-1)),change={from:sel.from,to:sel.to,insert:Text.of([" "])}),change){if(browser.ios&&view.inputState.flushIOSKey()||browser.android&&(change.from==sel.from&&change.to==sel.to&&change.insert.length==1&&change.insert.lines==2&&dispatchKey(view.contentDOM,"Enter",13)||(change.from==sel.from-1&&change.to==sel.to&&change.insert.length==0||lastKey==8&&change.insert.lengthsel.head)&&dispatchKey(view.contentDOM,"Backspace",8)||change.from==sel.from&&change.to==sel.to+1&&change.insert.length==0&&dispatchKey(view.contentDOM,"Delete",46)))return!0;let text=change.insert.toString();view.inputState.composing>=0&&view.inputState.composing++;let defaultTr,defaultInsert=__name2(()=>defaultTr||(defaultTr=applyDefaultInsert(view,change,newSel)),"defaultInsert");return view.state.facet(inputHandler$1).some(h=>h(view,change.from,change.to,text,defaultInsert))||view.dispatch(defaultInsert()),!0}else if(newSel&&!newSel.main.eq(sel)){let scrollIntoView2=!1,userEvent="select";return view.inputState.lastSelectionTime>Date.now()-50&&(view.inputState.lastSelectionOrigin=="select"&&(scrollIntoView2=!0),userEvent=view.inputState.lastSelectionOrigin),view.dispatch({selection:newSel,scrollIntoView:scrollIntoView2,userEvent}),!0}else return!1}__name(applyDOMChange,"applyDOMChange"),__name2(applyDOMChange,"applyDOMChange");function applyDefaultInsert(view,change,newSel){let tr,startState=view.state,sel=startState.selection.main;if(change.from>=sel.from&&change.to<=sel.to&&change.to-change.from>=(sel.to-sel.from)/3&&(!newSel||newSel.main.empty&&newSel.main.from==change.from+change.insert.length)&&view.inputState.composing<0){let before=sel.fromchange.to?startState.sliceDoc(change.to,sel.to):"";tr=startState.replaceSelection(view.state.toText(before+change.insert.sliceString(0,void 0,view.state.lineBreak)+after))}else{let changes=startState.changes(change),mainSel=newSel&&newSel.main.to<=changes.newLength?newSel.main:void 0;if(startState.selection.ranges.length>1&&view.inputState.composing>=0&&change.to<=sel.to&&change.to>=sel.to-10){let replaced=view.state.sliceDoc(change.from,change.to),compositionRange,composition=newSel&&findCompositionNode(view,newSel.main.head);if(composition){let dLen=change.insert.length-(change.to-change.from);compositionRange={from:composition.from,to:composition.to-dLen}}else compositionRange=view.state.doc.lineAt(sel.head);let offset2=sel.to-change.to,size=sel.to-sel.from;tr=startState.changeByRange(range=>{if(range.from==sel.from&&range.to==sel.to)return{changes,range:mainSel||range.map(changes)};let to=range.to-offset2,from=to-replaced.length;if(range.to-range.from!=size||view.state.sliceDoc(from,to)!=replaced||range.to>=compositionRange.from&&range.from<=compositionRange.to)return{range};let rangeChanges=startState.changes({from,to,insert:change.insert}),selOff=range.to-sel.to;return{changes:rangeChanges,range:mainSel?EditorSelection.range(Math.max(0,mainSel.anchor+selOff),Math.max(0,mainSel.head+selOff)):range.map(rangeChanges)}})}else tr={changes,selection:mainSel&&startState.selection.replaceRange(mainSel)}}let userEvent="input.type";return(view.composing||view.inputState.compositionPendingChange&&view.inputState.compositionEndedAt>Date.now()-50)&&(view.inputState.compositionPendingChange=!1,userEvent+=".compose",view.inputState.compositionFirstChange&&(userEvent+=".start",view.inputState.compositionFirstChange=!1)),startState.update(tr,{userEvent,scrollIntoView:!0})}__name(applyDefaultInsert,"applyDefaultInsert"),__name2(applyDefaultInsert,"applyDefaultInsert");function findDiff(a,b,preferredPos,preferredSide){let minLen=Math.min(a.length,b.length),from=0;for(;from0&&toB>0&&a.charCodeAt(toA-1)==b.charCodeAt(toB-1);)toA--,toB--;if(preferredSide=="end"){let adjust=Math.max(0,from-Math.min(toA,toB));preferredPos-=toA+adjust-from}if(toA=toA?from-preferredPos:0;from-=move,toB=from+(toB-toA),toA=from}else if(toB=toB?from-preferredPos:0;from-=move,toA=from+(toA-toB),toB=from}return{from,toA,toB}}__name(findDiff,"findDiff"),__name2(findDiff,"findDiff");function selectionPoints(view){let result=[];if(view.root.activeElement!=view.contentDOM)return result;let{anchorNode,anchorOffset,focusNode,focusOffset}=view.observer.selectionRange;return anchorNode&&(result.push(new DOMPoint(anchorNode,anchorOffset)),(focusNode!=anchorNode||focusOffset!=anchorOffset)&&result.push(new DOMPoint(focusNode,focusOffset))),result}__name(selectionPoints,"selectionPoints"),__name2(selectionPoints,"selectionPoints");function selectionFromPoints(points,base2){if(points.length==0)return null;let anchor=points[0].pos,head=points.length==2?points[1].pos:anchor;return anchor>-1&&head>-1?EditorSelection.single(anchor+base2,head+base2):null}__name(selectionFromPoints,"selectionFromPoints"),__name2(selectionFromPoints,"selectionFromPoints");const observeOptions={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},useCharData=browser.ie&&browser.ie_version<=11,_DOMObserver=class{static{__name(this,"_DOMObserver")}constructor(view){this.view=view,this.active=!1,this.selectionRange=new DOMSelectionState,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.resizeContent=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.parentCheck=-1,this.dom=view.contentDOM,this.observer=new MutationObserver(mutations=>{for(let mut of mutations)this.queue.push(mut);(browser.ie&&browser.ie_version<=11||browser.ios&&view.composing)&&mutations.some(m=>m.type=="childList"&&m.removedNodes.length||m.type=="characterData"&&m.oldValue.length>m.target.nodeValue.length)?this.flushSoon():this.flush()}),useCharData&&(this.onCharData=event=>{this.queue.push({target:event.target,type:"characterData",oldValue:event.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var _a3;((_a3=this.view.docView)===null||_a3===void 0?void 0:_a3.lastUpdate)this.view.requestMeasure()),this.resizeContent.observe(view.contentDOM)),this.addWindowListeners(this.win=view.win),this.start(),typeof IntersectionObserver=="function"&&(this.intersection=new IntersectionObserver(entries=>{this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),entries.length>0&&entries[entries.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(entries=>{entries.length>0&&entries[entries.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(){this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500)}updateGaps(gaps){if(this.gapIntersection&&(gaps.length!=this.gaps.length||this.gaps.some((g,i)=>g!=gaps[i]))){this.gapIntersection.disconnect();for(let gap of gaps)this.gapIntersection.observe(gap);this.gaps=gaps}}onSelectionChange(event){let wasChanged=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view}=this,sel=this.selectionRange;if(view.state.facet(editable)?view.root.activeElement!=this.dom:!hasSelection(view.dom,sel))return;let context=sel.anchorNode&&view.docView.nearest(sel.anchorNode);if(context&&context.ignoreEvent(event)){wasChanged||(this.selectionChanged=!1);return}(browser.ie&&browser.ie_version<=11||browser.android&&browser.chrome)&&!view.state.selection.main.empty&&sel.focusNode&&isEquivalentPosition(sel.focusNode,sel.focusOffset,sel.anchorNode,sel.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view}=this,range=browser.safari&&view.root.nodeType==11&&deepActiveElement(this.dom.ownerDocument)==this.dom&&safariSelectionRangeHack(this.view)||getSelection(view.root);if(!range||this.selectionRange.eq(range))return!1;let local=hasSelection(this.dom,range);return local&&!this.selectionChanged&&view.inputState.lastFocusTime>Date.now()-200&&view.inputState.lastTouchTime{let key2=this.delayedAndroidKey;key2&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=key2.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&key2.force&&dispatchKey(this.dom,key2.key,key2.keyCode))},"flush");this.flushingAndroidKey=this.view.win.requestAnimationFrame(flush)}(!this.delayedAndroidKey||key=="Enter")&&(this.delayedAndroidKey={key,keyCode,force:this.lastChange{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let mut of this.observer.takeRecords())this.queue.push(mut);return this.queue}processRecords(){let records=this.pendingRecords();records.length&&(this.queue=[]);let from=-1,to=-1,typeOver=!1;for(let record of records){let range=this.readMutation(record);range&&(range.typeOver&&(typeOver=!0),from==-1?{from,to}=range:(from=Math.min(range.from,from),to=Math.max(range.to,to)))}return{from,to,typeOver}}readChange(){let{from,to,typeOver}=this.processRecords(),newSel=this.selectionChanged&&hasSelection(this.dom,this.selectionRange);if(from<0&&!newSel)return null;from>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let change=new DOMChange(this.view,from,to,typeOver);return this.view.docView.domChanged={newSel:change.newSel?change.newSel.main:null},change}flush(readSelection=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;readSelection&&this.readSelectionRange();let domChange=this.readChange();if(!domChange)return!1;let startState=this.view.state,handled=applyDOMChange(this.view,domChange);return this.view.state==startState&&this.view.update([]),handled}readMutation(rec){let cView=this.view.docView.nearest(rec.target);if(!cView||cView.ignoreMutation(rec))return null;if(cView.markDirty(rec.type=="attributes"),rec.type=="attributes"&&(cView.flags|=4),rec.type=="childList"){let childBefore=findChild(cView,rec.previousSibling||rec.target.previousSibling,-1),childAfter=findChild(cView,rec.nextSibling||rec.target.nextSibling,1);return{from:childBefore?cView.posAfter(childBefore):cView.posAtStart,to:childAfter?cView.posBefore(childAfter):cView.posAtEnd,typeOver:!1}}else return rec.type=="characterData"?{from:cView.posAtStart,to:cView.posAtEnd,typeOver:rec.target.nodeValue==rec.oldValue}:null}setWindow(win){win!=this.win&&(this.removeWindowListeners(this.win),this.win=win,this.addWindowListeners(this.win))}addWindowListeners(win){win.addEventListener("resize",this.onResize),win.addEventListener("beforeprint",this.onPrint),win.addEventListener("scroll",this.onScroll),win.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(win){win.removeEventListener("scroll",this.onScroll),win.removeEventListener("resize",this.onResize),win.removeEventListener("beforeprint",this.onPrint),win.document.removeEventListener("selectionchange",this.onSelectionChange)}destroy(){var _a3,_b2,_c2,_d;this.stop(),(_a3=this.intersection)===null||_a3===void 0||_a3.disconnect(),(_b2=this.gapIntersection)===null||_b2===void 0||_b2.disconnect(),(_c2=this.resizeScroll)===null||_c2===void 0||_c2.disconnect(),(_d=this.resizeContent)===null||_d===void 0||_d.disconnect();for(let dom of this.scrollTargets)dom.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey)}};__name2(_DOMObserver,"DOMObserver");let DOMObserver=_DOMObserver;function findChild(cView,dom,dir){for(;dom;){let curView=ContentView.get(dom);if(curView&&curView.parent==cView)return curView;let parent=dom.parentNode;dom=parent!=cView.dom?parent:dir>0?dom.nextSibling:dom.previousSibling}return null}__name(findChild,"findChild"),__name2(findChild,"findChild");function safariSelectionRangeHack(view){let found=null;function read(event){event.preventDefault(),event.stopImmediatePropagation(),found=event.getTargetRanges()[0]}if(__name(read,"read"),__name2(read,"read"),view.contentDOM.addEventListener("beforeinput",read,!0),view.dom.ownerDocument.execCommand("indent"),view.contentDOM.removeEventListener("beforeinput",read,!0),!found)return null;let anchorNode=found.startContainer,anchorOffset=found.startOffset,focusNode=found.endContainer,focusOffset=found.endOffset,curAnchor=view.docView.domAtPos(view.state.selection.main.anchor);return isEquivalentPosition(curAnchor.node,curAnchor.offset,focusNode,focusOffset)&&([anchorNode,anchorOffset,focusNode,focusOffset]=[focusNode,focusOffset,anchorNode,anchorOffset]),{anchorNode,anchorOffset,focusNode,focusOffset}}__name(safariSelectionRangeHack,"safariSelectionRangeHack"),__name2(safariSelectionRangeHack,"safariSelectionRangeHack");const _EditorView=class _EditorView2{static{__name(this,"_EditorView")}get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return this.inputState.composing>0}get compositionStarted(){return this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(config2={}){this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.style.cssText="position: fixed; top: -10000px",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM);let{dispatch}=config2;this.dispatchTransactions=config2.dispatchTransactions||dispatch&&(trs=>trs.forEach(tr=>dispatch(tr,this)))||(trs=>this.update(trs)),this.dispatch=this.dispatch.bind(this),this._root=config2.root||getRoot(config2.parent)||document,this.viewState=new ViewState(config2.state||EditorState.create(config2)),this.plugins=this.state.facet(viewPlugin).map(spec=>new PluginInstance(spec));for(let plugin of this.plugins)plugin.update(this);this.observer=new DOMObserver(this),this.inputState=new InputState(this),this.inputState.ensureHandlers(this.plugins),this.docView=new DocView(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),config2.parent&&config2.parent.appendChild(this.dom)}dispatch(...input){let trs=input.length==1&&input[0]instanceof Transaction?input:input.length==1&&Array.isArray(input[0])?input[0]:[this.state.update(...input)];this.dispatchTransactions(trs,this)}update(transactions){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let redrawn=!1,attrsChanged=!1,update,state=this.state;for(let tr of transactions){if(tr.startState!=state)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");state=tr.state}if(this.destroyed){this.viewState.state=state;return}let focus=this.hasFocus,focusFlag=0,dispatchFocus=null;transactions.some(tr=>tr.annotation(isFocusChange))?(this.inputState.notifiedFocused=focus,focusFlag=1):focus!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=focus,dispatchFocus=focusChangeTransaction(state,focus),dispatchFocus||(focusFlag=1));let pendingKey=this.observer.delayedAndroidKey,domChange=null;if(pendingKey?(this.observer.clearDelayedAndroidKey(),domChange=this.observer.readChange(),(domChange&&!this.state.doc.eq(state.doc)||!this.state.selection.eq(state.selection))&&(domChange=null)):this.observer.clear(),state.facet(EditorState.phrases)!=this.state.facet(EditorState.phrases))return this.setState(state);update=ViewUpdate.create(this,state,transactions),update.flags|=focusFlag;let scrollTarget=this.viewState.scrollTarget;try{this.updateState=2;for(let tr of transactions){if(scrollTarget&&(scrollTarget=scrollTarget.map(tr.changes)),tr.scrollIntoView){let{main}=tr.state.selection;scrollTarget=new ScrollTarget(main.empty?main:EditorSelection.cursor(main.head,main.head>main.anchor?-1:1))}for(let e of tr.effects)e.is(scrollIntoView$1)&&(scrollTarget=e.value)}this.viewState.update(update,scrollTarget),this.bidiCache=CachedOrder.update(this.bidiCache,update.changes),update.empty||(this.updatePlugins(update),this.inputState.update(update)),redrawn=this.docView.update(update),this.state.facet(styleModule)!=this.styleModules&&this.mountStyles(),attrsChanged=this.updateAttrs(),this.showAnnouncements(transactions),this.docView.updateSelection(redrawn,transactions.some(tr=>tr.isUserEvent("select.pointer")))}finally{this.updateState=0}if(update.startState.facet(theme)!=update.state.facet(theme)&&(this.viewState.mustMeasureContent=!0),(redrawn||attrsChanged||scrollTarget||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),!update.empty)for(let listener of this.state.facet(updateListener))listener(update);(dispatchFocus||domChange)&&Promise.resolve().then(()=>{dispatchFocus&&this.state==dispatchFocus.startState&&this.dispatch(dispatchFocus),domChange&&!applyDOMChange(this,domChange)&&pendingKey.force&&dispatchKey(this.contentDOM,pendingKey.key,pendingKey.keyCode)})}setState(newState){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=newState;return}this.updateState=2;let hadFocus=this.hasFocus;try{for(let plugin of this.plugins)plugin.destroy(this);this.viewState=new ViewState(newState),this.plugins=newState.facet(viewPlugin).map(spec=>new PluginInstance(spec)),this.pluginMap.clear();for(let plugin of this.plugins)plugin.update(this);this.docView=new DocView(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}hadFocus&&this.focus(),this.requestMeasure()}updatePlugins(update){let prevSpecs=update.startState.facet(viewPlugin),specs=update.state.facet(viewPlugin);if(prevSpecs!=specs){let newPlugins=[];for(let spec of specs){let found=prevSpecs.indexOf(spec);if(found<0)newPlugins.push(new PluginInstance(spec));else{let plugin=this.plugins[found];plugin.mustUpdate=update,newPlugins.push(plugin)}}for(let plugin of this.plugins)plugin.mustUpdate!=update&&plugin.destroy(this);this.plugins=newPlugins,this.pluginMap.clear()}else for(let p of this.plugins)p.mustUpdate=update;for(let i=0;i-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,flush&&this.observer.forceFlush();let updated=null,sDOM=this.scrollDOM,scrollTop=sDOM.scrollTop*this.scaleY,{scrollAnchorPos,scrollAnchorHeight}=this.viewState;Math.abs(scrollTop-this.viewState.scrollTop)>1&&(scrollAnchorHeight=-1),this.viewState.scrollAnchorHeight=-1;try{for(let i=0;;i++){if(scrollAnchorHeight<0)if(isScrolledToBottom(sDOM))scrollAnchorPos=-1,scrollAnchorHeight=this.viewState.heightMap.height;else{let block=this.viewState.scrollAnchorAt(scrollTop);scrollAnchorPos=block.from,scrollAnchorHeight=block.top}this.updateState=1;let changed=this.viewState.measure(this);if(!changed&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(i>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let measuring=[];changed&4||([this.measureRequests,measuring]=[measuring,this.measureRequests]);let measured=measuring.map(m=>{try{return m.read(this)}catch(e){return logException(this.state,e),BadMeasure}}),update=ViewUpdate.create(this,this.state,[]),redrawn=!1;update.flags|=changed,updated?updated.flags|=changed:updated=update,this.updateState=2,update.empty||(this.updatePlugins(update),this.inputState.update(update),this.updateAttrs(),redrawn=this.docView.update(update));for(let i2=0;i21||diff2<-1){scrollTop=scrollTop+diff2,sDOM.scrollTop=scrollTop/this.scaleY,scrollAnchorHeight=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(updated&&!updated.empty)for(let listener of this.state.facet(updateListener))listener(updated)}get themeClasses(){return baseThemeID+" "+(this.state.facet(darkTheme)?baseDarkID:baseLightID)+" "+this.state.facet(theme)}updateAttrs(){let editorAttrs=attrsFromFacet(this,editorAttributes,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),contentAttrs={spellcheck:"false",autocorrect:"off",autocapitalize:"off",translate:"no",contenteditable:this.state.facet(editable)?"true":"false",class:"cm-content",style:`${browser.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(contentAttrs["aria-readonly"]="true"),attrsFromFacet(this,contentAttributes,contentAttrs);let changed=this.observer.ignore(()=>{let changedContent=updateAttrs(this.contentDOM,this.contentAttrs,contentAttrs),changedEditor=updateAttrs(this.dom,this.editorAttrs,editorAttrs);return changedContent||changedEditor});return this.editorAttrs=editorAttrs,this.contentAttrs=contentAttrs,changed}showAnnouncements(trs){let first=!0;for(let tr of trs)for(let effect of tr.effects)if(effect.is(_EditorView2.announce)){first&&(this.announceDOM.textContent=""),first=!1;let div=this.announceDOM.appendChild(document.createElement("div"));div.textContent=effect.value}}mountStyles(){this.styleModules=this.state.facet(styleModule);let nonce=this.state.facet(_EditorView2.cspNonce);StyleModule.mount(this.root,this.styleModules.concat(baseTheme$1$2).reverse(),nonce?{nonce}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(request){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),request){if(this.measureRequests.indexOf(request)>-1)return;if(request.key!=null){for(let i=0;ip.spec==plugin)||null),known&&known.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(height){return this.readMeasured(),this.viewState.elementAtHeight(height)}lineBlockAtHeight(height){return this.readMeasured(),this.viewState.lineBlockAtHeight(height)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(pos){return this.viewState.lineBlockAt(pos)}get contentHeight(){return this.viewState.contentHeight}moveByChar(start,forward,by){return skipAtoms(this,start,moveByChar(this,start,forward,by))}moveByGroup(start,forward){return skipAtoms(this,start,moveByChar(this,start,forward,initial=>byGroup(this,start.head,initial)))}moveToLineBoundary(start,forward,includeWrap=!0){return moveToLineBoundary(this,start,forward,includeWrap)}moveVertically(start,forward,distance){return skipAtoms(this,start,moveVertically(this,start,forward,distance))}domAtPos(pos){return this.docView.domAtPos(pos)}posAtDOM(node,offset2=0){return this.docView.posFromDOM(node,offset2)}posAtCoords(coords,precise=!0){return this.readMeasured(),posAtCoords(this,coords,precise)}coordsAtPos(pos,side=1){this.readMeasured();let rect=this.docView.coordsAt(pos,side);if(!rect||rect.left==rect.right)return rect;let line=this.state.doc.lineAt(pos),order=this.bidiSpans(line),span=order[BidiSpan.find(order,pos-line.from,-1,side)];return flattenRect(rect,span.dir==Direction.LTR==side>0)}coordsForChar(pos){return this.readMeasured(),this.docView.coordsForChar(pos)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(pos){return!this.state.facet(perLineTextDirection)||posthis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(pos))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(line){if(line.length>MaxBidiLine)return trivialOrder(line.length);let dir=this.textDirectionAt(line.from),isolates;for(let entry of this.bidiCache)if(entry.from==line.from&&entry.dir==dir&&(entry.fresh||isolatesEq(entry.isolates,isolates=getIsolatedRanges(this,line.from,line.to))))return entry.order;isolates||(isolates=getIsolatedRanges(this,line.from,line.to));let order=computeOrder(line.text,dir,isolates);return this.bidiCache.push(new CachedOrder(line.from,line.to,dir,isolates,!0,order)),order}get hasFocus(){var _a3;return(this.dom.ownerDocument.hasFocus()||browser.safari&&((_a3=this.inputState)===null||_a3===void 0?void 0:_a3.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{focusPreventScroll(this.contentDOM),this.docView.updateSelection()})}setRoot(root){this._root!=root&&(this._root=root,this.observer.setWindow((root.nodeType==9?root:root.ownerDocument).defaultView||window),this.mountStyles())}destroy(){for(let plugin of this.plugins)plugin.destroy(this);this.plugins=[],this.inputState.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(pos,options={}){return scrollIntoView$1.of(new ScrollTarget(typeof pos=="number"?EditorSelection.cursor(pos):pos,options.y,options.x,options.yMargin,options.xMargin))}static domEventHandlers(handlers2){return ViewPlugin.define(()=>({}),{eventHandlers:handlers2})}static domEventObservers(observers2){return ViewPlugin.define(()=>({}),{eventObservers:observers2})}static theme(spec,options){let prefix=StyleModule.newName(),result=[theme.of(prefix),styleModule.of(buildTheme(`.${prefix}`,spec))];return options&&options.dark&&result.push(darkTheme.of(!0)),result}static baseTheme(spec){return Prec.lowest(styleModule.of(buildTheme("."+baseThemeID,spec,lightDarkIDs)))}static findFromDOM(dom){var _a3;let content2=dom.querySelector(".cm-content"),cView=content2&&ContentView.get(content2)||ContentView.get(dom);return((_a3=cView?.rootView)===null||_a3===void 0?void 0:_a3.view)||null}};__name2(_EditorView,"EditorView");let EditorView=_EditorView;EditorView.styleModule=styleModule,EditorView.inputHandler=inputHandler$1,EditorView.focusChangeEffect=focusChangeEffect,EditorView.perLineTextDirection=perLineTextDirection,EditorView.exceptionSink=exceptionSink,EditorView.updateListener=updateListener,EditorView.editable=editable,EditorView.mouseSelectionStyle=mouseSelectionStyle,EditorView.dragMovesSelection=dragMovesSelection$1,EditorView.clickAddsSelectionRange=clickAddsSelectionRange,EditorView.decorations=decorations,EditorView.atomicRanges=atomicRanges,EditorView.bidiIsolatedRanges=bidiIsolatedRanges,EditorView.scrollMargins=scrollMargins,EditorView.darkTheme=darkTheme,EditorView.cspNonce=Facet.define({combine:values=>values.length?values[0]:""}),EditorView.contentAttributes=contentAttributes,EditorView.editorAttributes=editorAttributes,EditorView.lineWrapping=EditorView.contentAttributes.of({class:"cm-lineWrapping"}),EditorView.announce=StateEffect.define();const MaxBidiLine=4096,BadMeasure={},_CachedOrder=class _CachedOrder2{static{__name(this,"_CachedOrder")}constructor(from,to,dir,isolates,fresh,order){this.from=from,this.to=to,this.dir=dir,this.isolates=isolates,this.fresh=fresh,this.order=order}static update(cache,changes){if(changes.empty&&!cache.some(c=>c.fresh))return cache;let result=[],lastDir=cache.length?cache[cache.length-1].dir:Direction.LTR;for(let i=Math.max(0,cache.length-10);i=0;i--){let source=sources[i],value=typeof source=="function"?source(view):source;value&&combineAttrs(value,base2)}return base2}__name(attrsFromFacet,"attrsFromFacet"),__name2(attrsFromFacet,"attrsFromFacet");const currentPlatform=browser.mac?"mac":browser.windows?"win":browser.linux?"linux":"key";function normalizeKeyName(name2,platform){const parts=name2.split(/-(?!$)/);let result=parts[parts.length-1];result=="Space"&&(result=" ");let alt,ctrl,shift2,meta2;for(let i=0;ia.concat(b),[]))),map2}__name(getKeymap,"getKeymap"),__name2(getKeymap,"getKeymap");function runScopeHandlers(view,event,scope2){return runHandlers(getKeymap(view.state),event,view,scope2)}__name(runScopeHandlers,"runScopeHandlers"),__name2(runScopeHandlers,"runScopeHandlers");let storedPrefix=null;const PrefixTimeout=4e3;function buildKeymap(bindings,platform=currentPlatform){let bound=Object.create(null),isPrefix=Object.create(null),checkPrefix=__name2((name2,is2)=>{let current=isPrefix[name2];if(current==null)isPrefix[name2]=is2;else if(current!=is2)throw new Error("Key binding "+name2+" is used both as a regular binding and as a multi-stroke prefix")},"checkPrefix"),add2=__name2((scope2,key,command2,preventDefault2,stopPropagation)=>{var _a3,_b2;let scopeObj=bound[scope2]||(bound[scope2]=Object.create(null)),parts=key.split(/ (?!$)/).map(k=>normalizeKeyName(k,platform));for(let i=1;i{let ourObj=storedPrefix={view,prefix,scope:scope2};return setTimeout(()=>{storedPrefix==ourObj&&(storedPrefix=null)},PrefixTimeout),!0}]})}let full=parts.join(" ");checkPrefix(full,!1);let binding=scopeObj[full]||(scopeObj[full]={preventDefault:!1,stopPropagation:!1,run:((_b2=(_a3=scopeObj._any)===null||_a3===void 0?void 0:_a3.run)===null||_b2===void 0?void 0:_b2.slice())||[]});command2&&binding.run.push(command2),preventDefault2&&(binding.preventDefault=!0),stopPropagation&&(binding.stopPropagation=!0)},"add");for(let b of bindings){let scopes=b.scope?b.scope.split(" "):["editor"];if(b.any)for(let scope2 of scopes){let scopeObj=bound[scope2]||(bound[scope2]=Object.create(null));scopeObj._any||(scopeObj._any={preventDefault:!1,stopPropagation:!1,run:[]});for(let key in scopeObj)scopeObj[key].run.push(b.any)}let name2=b[platform]||b.key;if(name2)for(let scope2 of scopes)add2(scope2,name2,b.run,b.preventDefault,b.stopPropagation),b.shift&&add2(scope2,"Shift-"+name2,b.shift,b.preventDefault,b.stopPropagation)}return bound}__name(buildKeymap,"buildKeymap"),__name2(buildKeymap,"buildKeymap");function runHandlers(map2,event,view,scope2){let name2=keyName(event),charCode=codePointAt(name2,0),isChar=codePointSize(charCode)==name2.length&&name2!=" ",prefix="",handled=!1,prevented=!1,stopPropagation=!1;storedPrefix&&storedPrefix.view==view&&storedPrefix.scope==scope2&&(prefix=storedPrefix.prefix+" ",modifierCodes.indexOf(event.keyCode)<0&&(prevented=!0,storedPrefix=null));let ran=new Set,runFor=__name2(binding=>{if(binding){for(let cmd2 of binding.run)if(!ran.has(cmd2)&&(ran.add(cmd2),cmd2(view,event)))return binding.stopPropagation&&(stopPropagation=!0),!0;binding.preventDefault&&(binding.stopPropagation&&(stopPropagation=!0),prevented=!0)}return!1},"runFor"),scopeObj=map2[scope2],baseName,shiftName;return scopeObj&&(runFor(scopeObj[prefix+modifiers(name2,event,!isChar)])?handled=!0:isChar&&(event.altKey||event.metaKey||event.ctrlKey)&&!(browser.windows&&event.ctrlKey&&event.altKey)&&(baseName=base[event.keyCode])&&baseName!=name2?(runFor(scopeObj[prefix+modifiers(baseName,event,!0)])||event.shiftKey&&(shiftName=shift[event.keyCode])!=name2&&shiftName!=baseName&&runFor(scopeObj[prefix+modifiers(shiftName,event,!1)]))&&(handled=!0):isChar&&event.shiftKey&&runFor(scopeObj[prefix+modifiers(name2,event,!0)])&&(handled=!0),!handled&&runFor(scopeObj._any)&&(handled=!0)),prevented&&(handled=!0),handled&&stopPropagation&&event.stopPropagation(),handled}__name(runHandlers,"runHandlers"),__name2(runHandlers,"runHandlers");const _RectangleMarker=class _RectangleMarker2{static{__name(this,"_RectangleMarker")}constructor(className,left,top2,width,height){this.className=className,this.left=left,this.top=top2,this.width=width,this.height=height}draw(){let elt=document.createElement("div");return elt.className=this.className,this.adjust(elt),elt}update(elt,prev){return prev.className!=this.className?!1:(this.adjust(elt),!0)}adjust(elt){elt.style.left=this.left+"px",elt.style.top=this.top+"px",this.width!=null&&(elt.style.width=this.width+"px"),elt.style.height=this.height+"px"}eq(p){return this.left==p.left&&this.top==p.top&&this.width==p.width&&this.height==p.height&&this.className==p.className}static forRange(view,className,range){if(range.empty){let pos=view.coordsAtPos(range.head,range.assoc||1);if(!pos)return[];let base2=getBase(view);return[new _RectangleMarker2(className,pos.left-base2.left,pos.top-base2.top,null,pos.bottom-pos.top)]}else return rectanglesForRange(view,className,range)}};__name2(_RectangleMarker,"RectangleMarker");let RectangleMarker=_RectangleMarker;function getBase(view){let rect=view.scrollDOM.getBoundingClientRect();return{left:(view.textDirection==Direction.LTR?rect.left:rect.right-view.scrollDOM.clientWidth*view.scaleX)-view.scrollDOM.scrollLeft*view.scaleX,top:rect.top-view.scrollDOM.scrollTop*view.scaleY}}__name(getBase,"getBase"),__name2(getBase,"getBase");function wrappedLine(view,pos,inside2){let range=EditorSelection.cursor(pos);return{from:Math.max(inside2.from,view.moveToLineBoundary(range,!1,!0).from),to:Math.min(inside2.to,view.moveToLineBoundary(range,!0,!0).from),type:BlockType.Text}}__name(wrappedLine,"wrappedLine"),__name2(wrappedLine,"wrappedLine");function rectanglesForRange(view,className,range){if(range.to<=view.viewport.from||range.from>=view.viewport.to)return[];let from=Math.max(range.from,view.viewport.from),to=Math.min(range.to,view.viewport.to),ltr=view.textDirection==Direction.LTR,content2=view.contentDOM,contentRect=content2.getBoundingClientRect(),base2=getBase(view),lineElt=content2.querySelector(".cm-line"),lineStyle=lineElt&&window.getComputedStyle(lineElt),leftSide=contentRect.left+(lineStyle?parseInt(lineStyle.paddingLeft)+Math.min(0,parseInt(lineStyle.textIndent)):0),rightSide=contentRect.right-(lineStyle?parseInt(lineStyle.paddingRight):0),startBlock=blockAt(view,from),endBlock=blockAt(view,to),visualStart=startBlock.type==BlockType.Text?startBlock:null,visualEnd=endBlock.type==BlockType.Text?endBlock:null;if(visualStart&&(view.lineWrapping||startBlock.widgetLineBreaks)&&(visualStart=wrappedLine(view,from,visualStart)),visualEnd&&(view.lineWrapping||endBlock.widgetLineBreaks)&&(visualEnd=wrappedLine(view,to,visualEnd)),visualStart&&visualEnd&&visualStart.from==visualEnd.from)return pieces(drawForLine(range.from,range.to,visualStart));{let top2=visualStart?drawForLine(range.from,null,visualStart):drawForWidget(startBlock,!1),bottom=visualEnd?drawForLine(null,range.to,visualEnd):drawForWidget(endBlock,!0),between=[];return(visualStart||startBlock).to<(visualEnd||endBlock).from-(visualStart&&visualEnd?1:0)||startBlock.widgetLineBreaks>1&&top2.bottom+view.defaultLineHeight/2start&&r.from=endPos)break;spanTo>pos&&addSpan(Math.max(spanFrom,pos),from2==null&&spanFrom<=start,Math.min(spanTo,endPos),to2==null&&spanTo>=end,span.dir)}if(pos=docLine.to+1,pos>=endPos)break}return horizontal.length==0&&addSpan(start,from2==null,end,to2==null,view.textDirection),{top:top2,bottom,horizontal}}__name(drawForLine,"drawForLine"),__name2(drawForLine,"drawForLine");function drawForWidget(block,top2){let y=contentRect.top+(top2?block.top:block.bottom);return{top:y,bottom:y,horizontal:[]}}__name(drawForWidget,"drawForWidget"),__name2(drawForWidget,"drawForWidget")}__name(rectanglesForRange,"rectanglesForRange"),__name2(rectanglesForRange,"rectanglesForRange");function sameMarker(a,b){return a.constructor==b.constructor&&a.eq(b)}__name(sameMarker,"sameMarker"),__name2(sameMarker,"sameMarker");const _LayerView=class{static{__name(this,"_LayerView")}constructor(view,layer2){this.view=view,this.layer=layer2,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=view.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),layer2.above&&this.dom.classList.add("cm-layer-above"),layer2.class&&this.dom.classList.add(layer2.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(view.state),view.requestMeasure(this.measureReq),layer2.mount&&layer2.mount(this.dom,view)}update(update){update.startState.facet(layerOrder)!=update.state.facet(layerOrder)&&this.setOrder(update.state),(this.layer.update(update,this.dom)||update.geometryChanged)&&(this.scale(),update.view.requestMeasure(this.measureReq))}setOrder(state){let pos=0,order=state.facet(layerOrder);for(;pos!sameMarker(p,this.drawn[i]))){let old=this.dom.firstChild,oldI=0;for(let marker of markers)marker.update&&old&&marker.constructor&&this.drawn[oldI].constructor&&marker.update(old,this.drawn[oldI])?(old=old.nextSibling,oldI++):this.dom.insertBefore(marker.draw(),old);for(;old;){let next=old.nextSibling;old.remove(),old=next}this.drawn=markers}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}};__name2(_LayerView,"LayerView");let LayerView=_LayerView;const layerOrder=Facet.define();function layer(config2){return[ViewPlugin.define(v=>new LayerView(v,config2)),layerOrder.of(config2)]}__name(layer,"layer"),__name2(layer,"layer");const CanHidePrimary=!browser.ios,selectionConfig=Facet.define({combine(configs){return combineConfig(configs,{cursorBlinkRate:1200,drawRangeCursor:!0},{cursorBlinkRate:(a,b)=>Math.min(a,b),drawRangeCursor:(a,b)=>a||b})}});function drawSelection(config2={}){return[selectionConfig.of(config2),cursorLayer,selectionLayer,hideNativeSelection,nativeSelectionHidden.of(!0)]}__name(drawSelection,"drawSelection"),__name2(drawSelection,"drawSelection");function configChanged(update){return update.startState.facet(selectionConfig)!=update.state.facet(selectionConfig)}__name(configChanged,"configChanged"),__name2(configChanged,"configChanged");const cursorLayer=layer({above:!0,markers(view){let{state}=view,conf=state.facet(selectionConfig),cursors=[];for(let r of state.selection.ranges){let prim=r==state.selection.main;if(r.empty?!prim||CanHidePrimary:conf.drawRangeCursor){let className=prim?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",cursor=r.empty?r:EditorSelection.cursor(r.head,r.head>r.anchor?-1:1);for(let piece of RectangleMarker.forRange(view,className,cursor))cursors.push(piece)}}return cursors},update(update,dom){update.transactions.some(tr=>tr.selection)&&(dom.style.animationName=dom.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let confChange=configChanged(update);return confChange&&setBlinkRate(update.state,dom),update.docChanged||update.selectionSet||confChange},mount(dom,view){setBlinkRate(view.state,dom)},class:"cm-cursorLayer"});function setBlinkRate(state,dom){dom.style.animationDuration=state.facet(selectionConfig).cursorBlinkRate+"ms"}__name(setBlinkRate,"setBlinkRate"),__name2(setBlinkRate,"setBlinkRate");const selectionLayer=layer({above:!1,markers(view){return view.state.selection.ranges.map(r=>r.empty?[]:RectangleMarker.forRange(view,"cm-selectionBackground",r)).reduce((a,b)=>a.concat(b))},update(update,dom){return update.docChanged||update.selectionSet||update.viewportChanged||configChanged(update)},class:"cm-selectionLayer"}),themeSpec={".cm-line":{"& ::selection":{backgroundColor:"transparent !important"},"&::selection":{backgroundColor:"transparent !important"}}};CanHidePrimary&&(themeSpec[".cm-line"].caretColor="transparent !important");const hideNativeSelection=Prec.highest(EditorView.theme(themeSpec)),setDropCursorPos=StateEffect.define({map(pos,mapping){return pos==null?null:mapping.mapPos(pos)}}),dropCursorPos=StateField.define({create(){return null},update(pos,tr){return pos!=null&&(pos=tr.changes.mapPos(pos)),tr.effects.reduce((pos2,e)=>e.is(setDropCursorPos)?e.value:pos2,pos)}}),drawDropCursor=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(update){var _a3;let cursorPos=update.state.field(dropCursorPos);cursorPos==null?this.cursor!=null&&((_a3=this.cursor)===null||_a3===void 0||_a3.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(update.startState.field(dropCursorPos)!=cursorPos||update.docChanged||update.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view}=this,pos=view.state.field(dropCursorPos),rect=pos!=null&&view.coordsAtPos(pos);if(!rect)return null;let outer=view.scrollDOM.getBoundingClientRect();return{left:rect.left-outer.left+view.scrollDOM.scrollLeft*view.scaleX,top:rect.top-outer.top+view.scrollDOM.scrollTop*view.scaleY,height:rect.bottom-rect.top}}drawCursor(pos){if(this.cursor){let{scaleX,scaleY}=this.view;pos?(this.cursor.style.left=pos.left/scaleX+"px",this.cursor.style.top=pos.top/scaleY+"px",this.cursor.style.height=pos.height/scaleY+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(pos){this.view.state.field(dropCursorPos)!=pos&&this.view.dispatch({effects:setDropCursorPos.of(pos)})}},{eventObservers:{dragover(event){this.setDropPos(this.view.posAtCoords({x:event.clientX,y:event.clientY}))},dragleave(event){(event.target==this.view.contentDOM||!this.view.contentDOM.contains(event.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function dropCursor(){return[dropCursorPos,drawDropCursor]}__name(dropCursor,"dropCursor"),__name2(dropCursor,"dropCursor");function iterMatches(doc2,re,from,to,f){re.lastIndex=0;for(let cursor=doc2.iterRange(from,to),pos=from,m;!cursor.next().done;pos+=cursor.value.length)if(!cursor.lineBreak)for(;m=re.exec(cursor.value);)f(pos+m.index,m)}__name(iterMatches,"iterMatches"),__name2(iterMatches,"iterMatches");function matchRanges(view,maxLength){let visible=view.visibleRanges;if(visible.length==1&&visible[0].from==view.viewport.from&&visible[0].to==view.viewport.to)return visible;let result=[];for(let{from,to}of visible)from=Math.max(view.state.doc.lineAt(from).from,from-maxLength),to=Math.min(view.state.doc.lineAt(to).to,to+maxLength),result.length&&result[result.length-1].to>=from?result[result.length-1].to=to:result.push({from,to});return result}__name(matchRanges,"matchRanges"),__name2(matchRanges,"matchRanges");const _MatchDecorator=class{static{__name(this,"_MatchDecorator")}constructor(config2){const{regexp,decoration,decorate,boundary,maxLength=1e3}=config2;if(!regexp.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=regexp,decorate)this.addMatch=(match2,view,from,add2)=>decorate(add2,from,from+match2[0].length,match2,view);else if(typeof decoration=="function")this.addMatch=(match2,view,from,add2)=>{let deco=decoration(match2,view,from);deco&&add2(from,from+match2[0].length,deco)};else if(decoration)this.addMatch=(match2,_view,from,add2)=>add2(from,from+match2[0].length,decoration);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=boundary,this.maxLength=maxLength}createDeco(view){let build=new RangeSetBuilder,add2=build.add.bind(build);for(let{from,to}of matchRanges(view,this.maxLength))iterMatches(view.state.doc,this.regexp,from,to,(from2,m)=>this.addMatch(m,view,from2,add2));return build.finish()}updateDeco(update,deco){let changeFrom=1e9,changeTo=-1;return update.docChanged&&update.changes.iterChanges((_f,_t,from,to)=>{to>update.view.viewport.from&&from1e3?this.createDeco(update.view):changeTo>-1?this.updateRange(update.view,deco.map(update.changes),changeFrom,changeTo):deco}updateRange(view,deco,updateFrom,updateTo){for(let r of view.visibleRanges){let from=Math.max(r.from,updateFrom),to=Math.min(r.to,updateTo);if(to>from){let fromLine=view.state.doc.lineAt(from),toLine=fromLine.tofromLine.from;from--)if(this.boundary.test(fromLine.text[from-1-fromLine.from])){start=from;break}for(;toranges.push(deco2.range(from2,to2)),"add");if(fromLine==toLine)for(this.regexp.lastIndex=start-fromLine.from;(m=this.regexp.exec(fromLine.text))&&m.indexthis.addMatch(m2,view,from2,add2));deco=deco.update({filterFrom:start,filterTo:end,filter:(from2,to2)=>from2end,add:ranges})}}return deco}};__name2(_MatchDecorator,"MatchDecorator");let MatchDecorator=_MatchDecorator;const UnicodeRegexpSupport=/x/.unicode!=null?"gu":"g",Specials=new RegExp(`[\0-\b --\x7F-\x9F\xAD\u061C\u200B\u200E\u200F\u2028\u2029\u202D\u202E\u2066\u2067\u2069\uFEFF\uFFF9-\uFFFC]`,UnicodeRegexpSupport),Names={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"};let _supportsTabSize=null;function supportsTabSize(){var _a3;if(_supportsTabSize==null&&typeof document<"u"&&document.body){let styles=document.body.style;_supportsTabSize=((_a3=styles.tabSize)!==null&&_a3!==void 0?_a3:styles.MozTabSize)!=null}return _supportsTabSize||!1}__name(supportsTabSize,"supportsTabSize"),__name2(supportsTabSize,"supportsTabSize");const specialCharConfig=Facet.define({combine(configs){let config2=combineConfig(configs,{render:null,specialChars:Specials,addSpecialChars:null});return(config2.replaceTabs=!supportsTabSize())&&(config2.specialChars=new RegExp(" |"+config2.specialChars.source,UnicodeRegexpSupport)),config2.addSpecialChars&&(config2.specialChars=new RegExp(config2.specialChars.source+"|"+config2.addSpecialChars.source,UnicodeRegexpSupport)),config2}});function highlightSpecialChars(config2={}){return[specialCharConfig.of(config2),specialCharPlugin()]}__name(highlightSpecialChars,"highlightSpecialChars"),__name2(highlightSpecialChars,"highlightSpecialChars");let _plugin=null;function specialCharPlugin(){return _plugin||(_plugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.decorations=Decoration.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(view.state.facet(specialCharConfig)),this.decorations=this.decorator.createDeco(view)}makeDecorator(conf){return new MatchDecorator({regexp:conf.specialChars,decoration:(m,view,pos)=>{let{doc:doc2}=view.state,code=codePointAt(m[0],0);if(code==9){let line=doc2.lineAt(pos),size=view.state.tabSize,col=countColumn(line.text,size,pos-line.from);return Decoration.replace({widget:new TabWidget((size-col%size)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[code]||(this.decorationCache[code]=Decoration.replace({widget:new SpecialCharWidget(conf,code)}))},boundary:conf.replaceTabs?void 0:/[^]/})}update(update){let conf=update.state.facet(specialCharConfig);update.startState.facet(specialCharConfig)!=conf?(this.decorator=this.makeDecorator(conf),this.decorations=this.decorator.createDeco(update.view)):this.decorations=this.decorator.updateDeco(update,this.decorations)}},{decorations:v=>v.decorations}))}__name(specialCharPlugin,"specialCharPlugin"),__name2(specialCharPlugin,"specialCharPlugin");const DefaultPlaceholder="\u2022";function placeholder$1(code){return code>=32?DefaultPlaceholder:code==10?"\u2424":String.fromCharCode(9216+code)}__name(placeholder$1,"placeholder$1"),__name2(placeholder$1,"placeholder$1");const _SpecialCharWidget=class extends WidgetType{static{__name(this,"_SpecialCharWidget")}constructor(options,code){super(),this.options=options,this.code=code}eq(other){return other.code==this.code}toDOM(view){let ph=placeholder$1(this.code),desc=view.state.phrase("Control character")+" "+(Names[this.code]||"0x"+this.code.toString(16)),custom=this.options.render&&this.options.render(this.code,desc,ph);if(custom)return custom;let span=document.createElement("span");return span.textContent=ph,span.title=desc,span.setAttribute("aria-label",desc),span.className="cm-specialChar",span}ignoreEvent(){return!1}};__name2(_SpecialCharWidget,"SpecialCharWidget");let SpecialCharWidget=_SpecialCharWidget;const _TabWidget=class extends WidgetType{static{__name(this,"_TabWidget")}constructor(width){super(),this.width=width}eq(other){return other.width==this.width}toDOM(){let span=document.createElement("span");return span.textContent=" ",span.className="cm-tab",span.style.width=this.width+"px",span}ignoreEvent(){return!1}};__name2(_TabWidget,"TabWidget");let TabWidget=_TabWidget;function highlightActiveLine(){return activeLineHighlighter}__name(highlightActiveLine,"highlightActiveLine"),__name2(highlightActiveLine,"highlightActiveLine");const lineDeco=Decoration.line({class:"cm-activeLine"}),activeLineHighlighter=ViewPlugin.fromClass(class{constructor(view){this.decorations=this.getDeco(view)}update(update){(update.docChanged||update.selectionSet)&&(this.decorations=this.getDeco(update.view))}getDeco(view){let lastLineStart=-1,deco=[];for(let r of view.state.selection.ranges){let line=view.lineBlockAt(r.head);line.from>lastLineStart&&(deco.push(lineDeco.range(line.from)),lastLineStart=line.from)}return Decoration.set(deco)}},{decorations:v=>v.decorations}),MaxOff=2e3;function rectangleFor(state,a,b){let startLine=Math.min(a.line,b.line),endLine=Math.max(a.line,b.line),ranges=[];if(a.off>MaxOff||b.off>MaxOff||a.col<0||b.col<0){let startOff=Math.min(a.off,b.off),endOff=Math.max(a.off,b.off);for(let i=startLine;i<=endLine;i++){let line=state.doc.line(i);line.length<=endOff&&ranges.push(EditorSelection.range(line.from+startOff,line.to+endOff))}}else{let startCol=Math.min(a.col,b.col),endCol=Math.max(a.col,b.col);for(let i=startLine;i<=endLine;i++){let line=state.doc.line(i),start=findColumn(line.text,startCol,state.tabSize,!0);if(start<0)ranges.push(EditorSelection.cursor(line.to));else{let end=findColumn(line.text,endCol,state.tabSize);ranges.push(EditorSelection.range(line.from+start,line.from+end))}}}return ranges}__name(rectangleFor,"rectangleFor"),__name2(rectangleFor,"rectangleFor");function absoluteColumn(view,x){let ref=view.coordsAtPos(view.viewport.from);return ref?Math.round(Math.abs((ref.left-x)/view.defaultCharacterWidth)):-1}__name(absoluteColumn,"absoluteColumn"),__name2(absoluteColumn,"absoluteColumn");function getPos(view,event){let offset2=view.posAtCoords({x:event.clientX,y:event.clientY},!1),line=view.state.doc.lineAt(offset2),off2=offset2-line.from,col=off2>MaxOff?-1:off2==line.length?absoluteColumn(view,event.clientX):countColumn(line.text,view.state.tabSize,offset2-line.from);return{line:line.number,col,off:off2}}__name(getPos,"getPos"),__name2(getPos,"getPos");function rectangleSelectionStyle(view,event){let start=getPos(view,event),startSel=view.state.selection;return start?{update(update){if(update.docChanged){let newStart=update.changes.mapPos(update.startState.doc.line(start.line).from),newLine=update.state.doc.lineAt(newStart);start={line:newLine.number,col:start.col,off:Math.min(start.off,newLine.length)},startSel=startSel.map(update.changes)}},get(event2,_extend,multiple){let cur2=getPos(view,event2);if(!cur2)return startSel;let ranges=rectangleFor(view.state,start,cur2);return ranges.length?multiple?EditorSelection.create(ranges.concat(startSel.ranges)):EditorSelection.create(ranges):startSel}}:null}__name(rectangleSelectionStyle,"rectangleSelectionStyle"),__name2(rectangleSelectionStyle,"rectangleSelectionStyle");function rectangularSelection(options){let filter2=options?.eventFilter||(e=>e.altKey&&e.button==0);return EditorView.mouseSelectionStyle.of((view,event)=>filter2(event)?rectangleSelectionStyle(view,event):null)}__name(rectangularSelection,"rectangularSelection"),__name2(rectangularSelection,"rectangularSelection");const keys={Alt:[18,e=>!!e.altKey],Control:[17,e=>!!e.ctrlKey],Shift:[16,e=>!!e.shiftKey],Meta:[91,e=>!!e.metaKey]},showCrosshair={style:"cursor: crosshair"};function crosshairCursor(options={}){let[code,getter]=keys[options.key||"Alt"],plugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.isDown=!1}set(isDown){this.isDown!=isDown&&(this.isDown=isDown,this.view.update([]))}},{eventObservers:{keydown(e){this.set(e.keyCode==code||getter(e))},keyup(e){(e.keyCode==code||!getter(e))&&this.set(!1)},mousemove(e){this.set(getter(e))}}});return[plugin,EditorView.contentAttributes.of(view=>{var _a3;return!((_a3=view.plugin(plugin))===null||_a3===void 0)&&_a3.isDown?showCrosshair:null})]}__name(crosshairCursor,"crosshairCursor"),__name2(crosshairCursor,"crosshairCursor");const Outside="-10000px",_TooltipViewManager=class{static{__name(this,"_TooltipViewManager")}constructor(view,facet,createTooltipView){this.facet=facet,this.createTooltipView=createTooltipView,this.input=view.state.facet(facet),this.tooltips=this.input.filter(t2=>t2),this.tooltipViews=this.tooltips.map(createTooltipView)}update(update){var _a3;let input=update.state.facet(this.facet),tooltips=input.filter(x=>x);if(input===this.input){for(let t2 of this.tooltipViews)t2.update&&t2.update(update);return!1}let tooltipViews=[];for(let i=0;i{var _a3,_b2,_c2;return{position:browser.ios?"absolute":((_a3=values.find(conf=>conf.position))===null||_a3===void 0?void 0:_a3.position)||"fixed",parent:((_b2=values.find(conf=>conf.parent))===null||_b2===void 0?void 0:_b2.parent)||null,tooltipSpace:((_c2=values.find(conf=>conf.tooltipSpace))===null||_c2===void 0?void 0:_c2.tooltipSpace)||windowSpace}}}),knownHeight=new WeakMap,tooltipPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let config2=view.state.facet(tooltipConfig);this.position=config2.position,this.parent=config2.parent,this.classes=view.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.manager=new TooltipViewManager(view,showTooltip,t2=>this.createTooltip(t2)),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(entries=>{Date.now()>this.lastTransaction-50&&entries.length>0&&entries[entries.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),view.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let tooltip of this.manager.tooltipViews)this.intersectionObserver.observe(tooltip.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(update){update.transactions.length&&(this.lastTransaction=Date.now());let updated=this.manager.update(update);updated&&this.observeIntersection();let shouldMeasure=updated||update.geometryChanged,newConfig=update.state.facet(tooltipConfig);if(newConfig.position!=this.position&&!this.madeAbsolute){this.position=newConfig.position;for(let t2 of this.manager.tooltipViews)t2.dom.style.position=this.position;shouldMeasure=!0}if(newConfig.parent!=this.parent){this.parent&&this.container.remove(),this.parent=newConfig.parent,this.createContainer();for(let t2 of this.manager.tooltipViews)this.container.appendChild(t2.dom);shouldMeasure=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);shouldMeasure&&this.maybeMeasure()}createTooltip(tooltip){let tooltipView=tooltip.create(this.view);if(tooltipView.dom.classList.add("cm-tooltip"),tooltip.arrow&&!tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let arrow=document.createElement("div");arrow.className="cm-tooltip-arrow",tooltipView.dom.appendChild(arrow)}return tooltipView.dom.style.position=this.position,tooltipView.dom.style.top=Outside,this.container.appendChild(tooltipView.dom),tooltipView.mount&&tooltipView.mount(this.view),tooltipView}destroy(){var _a3,_b2;this.view.win.removeEventListener("resize",this.measureSoon);for(let tooltipView of this.manager.tooltipViews)tooltipView.dom.remove(),(_a3=tooltipView.destroy)===null||_a3===void 0||_a3.call(tooltipView);this.parent&&this.container.remove(),(_b2=this.intersectionObserver)===null||_b2===void 0||_b2.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let editor=this.view.dom.getBoundingClientRect(),scaleX=1,scaleY=1,makeAbsolute=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{offsetParent}=this.manager.tooltipViews[0].dom;makeAbsolute=!!(offsetParent&&offsetParent!=this.container.ownerDocument.body)}if(makeAbsolute||this.position=="absolute")if(this.parent){let rect=this.parent.getBoundingClientRect();rect.width&&rect.height&&(scaleX=rect.width/this.parent.offsetWidth,scaleY=rect.height/this.parent.offsetHeight)}else({scaleX,scaleY}=this.view.viewState);return{editor,parent:this.parent?this.container.getBoundingClientRect():editor,pos:this.manager.tooltips.map((t2,i)=>{let tv=this.manager.tooltipViews[i];return tv.getCoords?tv.getCoords(t2.pos):this.view.coordsAtPos(t2.pos)}),size:this.manager.tooltipViews.map(({dom})=>dom.getBoundingClientRect()),space:this.view.state.facet(tooltipConfig).tooltipSpace(this.view),scaleX,scaleY,makeAbsolute}}writeMeasure(measured){var _a3;if(measured.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let t2 of this.manager.tooltipViews)t2.dom.style.position="absolute"}let{editor,space,scaleX,scaleY}=measured,others=[];for(let i=0;i=Math.min(editor.bottom,space.bottom)||pos.rightMath.min(editor.right,space.right)+.1){dom.style.top=Outside;continue}let arrow=tooltip.arrow?tView.dom.querySelector(".cm-tooltip-arrow"):null,arrowHeight=arrow?7:0,width=size.right-size.left,height=(_a3=knownHeight.get(tView))!==null&&_a3!==void 0?_a3:size.bottom-size.top,offset2=tView.offset||noOffset,ltr=this.view.textDirection==Direction.LTR,left=size.width>space.right-space.left?ltr?space.left:space.right-size.width:ltr?Math.min(pos.left-(arrow?14:0)+offset2.x,space.right-width):Math.max(space.left,pos.left-width+(arrow?14:0)-offset2.x),above=!!tooltip.above;!tooltip.strictSide&&(above?pos.top-(size.bottom-size.top)-offset2.yspace.bottom)&&above==space.bottom-pos.bottom>pos.top-space.top&&(above=!above);let spaceVert=(above?pos.top-space.top:space.bottom-pos.bottom)-arrowHeight;if(spaceVertleft&&r.toptop2&&(top2=above?r.top-height-2-arrowHeight:r.bottom+arrowHeight+2);if(this.position=="absolute"?(dom.style.top=(top2-measured.parent.top)/scaleY+"px",dom.style.left=(left-measured.parent.left)/scaleX+"px"):(dom.style.top=top2/scaleY+"px",dom.style.left=left/scaleX+"px"),arrow){let arrowLeft=pos.left+(ltr?offset2.x:-offset2.x)-(left+14-7);arrow.style.left=arrowLeft/scaleX+"px"}tView.overlap!==!0&&others.push({left,top:top2,right,bottom:top2+height}),dom.classList.toggle("cm-tooltip-above",above),dom.classList.toggle("cm-tooltip-below",!above),tView.positioned&&tView.positioned(measured.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let tv of this.manager.tooltipViews)tv.dom.style.top=Outside}},{eventObservers:{scroll(){this.maybeMeasure()}}}),baseTheme$5=EditorView.baseTheme({".cm-tooltip":{zIndex:100,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:`${7*2}px`,position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),noOffset={x:0,y:0},showTooltip=Facet.define({enables:[tooltipPlugin,baseTheme$5]}),showHoverTooltip=Facet.define(),_HoverTooltipHost=class _HoverTooltipHost2{static{__name(this,"_HoverTooltipHost")}static create(view){return new _HoverTooltipHost2(view)}constructor(view){this.view=view,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new TooltipViewManager(view,showHoverTooltip,t2=>this.createHostedView(t2))}createHostedView(tooltip){let hostedView=tooltip.create(this.view);return hostedView.dom.classList.add("cm-tooltip-section"),this.dom.appendChild(hostedView.dom),this.mounted&&hostedView.mount&&hostedView.mount(this.view),hostedView}mount(view){for(let hostedView of this.manager.tooltipViews)hostedView.mount&&hostedView.mount(view);this.mounted=!0}positioned(space){for(let hostedView of this.manager.tooltipViews)hostedView.positioned&&hostedView.positioned(space)}update(update){this.manager.update(update)}destroy(){var _a3;for(let t2 of this.manager.tooltipViews)(_a3=t2.destroy)===null||_a3===void 0||_a3.call(t2)}};__name2(_HoverTooltipHost,"HoverTooltipHost");let HoverTooltipHost=_HoverTooltipHost;const showHoverTooltipHost=showTooltip.compute([showHoverTooltip],state=>{let tooltips=state.facet(showHoverTooltip).filter(t2=>t2);return tooltips.length===0?null:{pos:Math.min(...tooltips.map(t2=>t2.pos)),end:Math.max(...tooltips.filter(t2=>t2.end!=null).map(t2=>t2.end)),create:HoverTooltipHost.create,above:tooltips[0].above,arrow:tooltips.some(t2=>t2.arrow)}}),_HoverPlugin=class{static{__name(this,"_HoverPlugin")}constructor(view,source,field,setHover,hoverTime){this.view=view,this.source=source,this.field=field,this.setHover=setHover,this.hoverTime=hoverTime,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:view.dom,time:0},this.checkHover=this.checkHover.bind(this),view.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),view.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active)return;let hovered=Date.now()-this.lastMove.time;hoveredposCoords.bottom||lastMove.xposCoords.right+view.defaultCharacterWidth)return;let bidi=view.bidiSpans(view.state.doc.lineAt(pos)).find(s2=>s2.from<=pos&&s2.to>=pos),rtl=bidi&&bidi.dir==Direction.RTL?-1:1;side=lastMove.x{this.pending==pending&&(this.pending=null,result&&view.dispatch({effects:this.setHover.of(result)}))},e=>logException(view.state,e,"hover tooltip"))}else open&&view.dispatch({effects:this.setHover.of(open)})}mousemove(event){var _a3;this.lastMove={x:event.clientX,y:event.clientY,target:event.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let tooltip=this.active;if(tooltip&&!isInTooltip(this.lastMove.target)||this.pending){let{pos}=tooltip||this.pending,end=(_a3=tooltip?.end)!==null&&_a3!==void 0?_a3:pos;(pos==end?this.view.posAtCoords(this.lastMove)!=pos:!isOverRange(this.view,pos,end,event.clientX,event.clientY))&&(this.view.dispatch({effects:this.setHover.of(null)}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1,this.active&&!isInTooltip(e.relatedTarget)&&this.view.dispatch({effects:this.setHover.of(null)})}destroy(){clearTimeout(this.hoverTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}};__name2(_HoverPlugin,"HoverPlugin");let HoverPlugin=_HoverPlugin;function isInTooltip(elt){for(let cur2=elt;cur2;cur2=cur2.parentNode)if(cur2.nodeType==1&&cur2.classList.contains("cm-tooltip"))return!0;return!1}__name(isInTooltip,"isInTooltip"),__name2(isInTooltip,"isInTooltip");function isOverRange(view,from,to,x,y,margin){let rect=view.scrollDOM.getBoundingClientRect(),docBottom=view.documentTop+view.documentPadding.top+view.contentHeight;if(rect.left>x||rect.righty||Math.min(rect.bottom,docBottom)=from&&pos<=to}__name(isOverRange,"isOverRange"),__name2(isOverRange,"isOverRange");function hoverTooltip(source,options={}){let setHover=StateEffect.define(),hoverState=StateField.define({create(){return null},update(value,tr){if(value&&(options.hideOnChange&&(tr.docChanged||tr.selection)||options.hideOn&&options.hideOn(tr,value)))return null;if(value&&tr.docChanged){let newPos=tr.changes.mapPos(value.pos,-1,MapMode.TrackDel);if(newPos==null)return null;let copy=Object.assign(Object.create(null),value);copy.pos=newPos,value.end!=null&&(copy.end=tr.changes.mapPos(value.end)),value=copy}for(let effect of tr.effects)effect.is(setHover)&&(value=effect.value),effect.is(closeHoverTooltipEffect)&&(value=null);return value},provide:f=>showHoverTooltip.from(f)});return[hoverState,ViewPlugin.define(view=>new HoverPlugin(view,source,hoverState,setHover,options.hoverTime||300)),showHoverTooltipHost]}__name(hoverTooltip,"hoverTooltip"),__name2(hoverTooltip,"hoverTooltip");function getTooltip(view,tooltip){let plugin=view.plugin(tooltipPlugin);if(!plugin)return null;let found=plugin.manager.tooltips.indexOf(tooltip);return found<0?null:plugin.manager.tooltipViews[found]}__name(getTooltip,"getTooltip"),__name2(getTooltip,"getTooltip");const closeHoverTooltipEffect=StateEffect.define(),panelConfig=Facet.define({combine(configs){let topContainer,bottomContainer;for(let c of configs)topContainer=topContainer||c.topContainer,bottomContainer=bottomContainer||c.bottomContainer;return{topContainer,bottomContainer}}});function getPanel(view,panel){let plugin=view.plugin(panelPlugin),index2=plugin?plugin.specs.indexOf(panel):-1;return index2>-1?plugin.panels[index2]:null}__name(getPanel,"getPanel"),__name2(getPanel,"getPanel");const panelPlugin=ViewPlugin.fromClass(class{constructor(view){this.input=view.state.facet(showPanel),this.specs=this.input.filter(s2=>s2),this.panels=this.specs.map(spec=>spec(view));let conf=view.state.facet(panelConfig);this.top=new PanelGroup(view,!0,conf.topContainer),this.bottom=new PanelGroup(view,!1,conf.bottomContainer),this.top.sync(this.panels.filter(p=>p.top)),this.bottom.sync(this.panels.filter(p=>!p.top));for(let p of this.panels)p.dom.classList.add("cm-panel"),p.mount&&p.mount()}update(update){let conf=update.state.facet(panelConfig);this.top.container!=conf.topContainer&&(this.top.sync([]),this.top=new PanelGroup(update.view,!0,conf.topContainer)),this.bottom.container!=conf.bottomContainer&&(this.bottom.sync([]),this.bottom=new PanelGroup(update.view,!1,conf.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let input=update.state.facet(showPanel);if(input!=this.input){let specs=input.filter(x=>x),panels=[],top2=[],bottom=[],mount2=[];for(let spec of specs){let known=this.specs.indexOf(spec),panel;known<0?(panel=spec(update.view),mount2.push(panel)):(panel=this.panels[known],panel.update&&panel.update(update)),panels.push(panel),(panel.top?top2:bottom).push(panel)}this.specs=specs,this.panels=panels,this.top.sync(top2),this.bottom.sync(bottom);for(let p of mount2)p.dom.classList.add("cm-panel"),p.mount&&p.mount()}else for(let p of this.panels)p.update&&p.update(update)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:plugin=>EditorView.scrollMargins.of(view=>{let value=view.plugin(plugin);return value&&{top:value.top.scrollMargin(),bottom:value.bottom.scrollMargin()}})}),_PanelGroup=class{static{__name(this,"_PanelGroup")}constructor(view,top2,container){this.view=view,this.top=top2,this.container=container,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(panels){for(let p of this.panels)p.destroy&&panels.indexOf(p)<0&&p.destroy();this.panels=panels,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom",this.dom.style[this.top?"top":"bottom"]="0";let parent=this.container||this.view.dom;parent.insertBefore(this.dom,this.top?parent.firstChild:null)}let curDOM=this.dom.firstChild;for(let panel of this.panels)if(panel.dom.parentNode==this.dom){for(;curDOM!=panel.dom;)curDOM=rm(curDOM);curDOM=curDOM.nextSibling}else this.dom.insertBefore(panel.dom,curDOM);for(;curDOM;)curDOM=rm(curDOM)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let cls of this.classes.split(" "))cls&&this.container.classList.remove(cls);for(let cls of(this.classes=this.view.themeClasses).split(" "))cls&&this.container.classList.add(cls)}}};__name2(_PanelGroup,"PanelGroup");let PanelGroup=_PanelGroup;function rm(node){let next=node.nextSibling;return node.remove(),next}__name(rm,"rm"),__name2(rm,"rm");const showPanel=Facet.define({enables:panelPlugin}),_GutterMarker=class extends RangeValue{static{__name(this,"_GutterMarker")}compare(other){return this==other||this.constructor==other.constructor&&this.eq(other)}eq(other){return!1}destroy(dom){}};__name2(_GutterMarker,"GutterMarker");let GutterMarker=_GutterMarker;GutterMarker.prototype.elementClass="",GutterMarker.prototype.toDOM=void 0,GutterMarker.prototype.mapMode=MapMode.TrackBefore,GutterMarker.prototype.startSide=GutterMarker.prototype.endSide=-1,GutterMarker.prototype.point=!0;const gutterLineClass=Facet.define(),defaults$1={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>RangeSet.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{}},activeGutters=Facet.define();function gutter(config2){return[gutters(),activeGutters.of(Object.assign(Object.assign({},defaults$1),config2))]}__name(gutter,"gutter"),__name2(gutter,"gutter");const unfixGutters=Facet.define({combine:values=>values.some(x=>x)});function gutters(config2){let result=[gutterView];return config2&&config2.fixed===!1&&result.push(unfixGutters.of(!0)),result}__name(gutters,"gutters"),__name2(gutters,"gutters");const gutterView=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.prevViewport=view.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=view.state.facet(activeGutters).map(conf=>new SingleGutterView(view,conf));for(let gutter2 of this.gutters)this.dom.appendChild(gutter2.dom);this.fixed=!view.state.facet(unfixGutters),this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),view.scrollDOM.insertBefore(this.dom,view.contentDOM)}update(update){if(this.updateGutters(update)){let vpA=this.prevViewport,vpB=update.view.viewport,vpOverlap=Math.min(vpA.to,vpB.to)-Math.max(vpA.from,vpB.from);this.syncGutters(vpOverlap<(vpB.to-vpB.from)*.8)}update.geometryChanged&&(this.dom.style.minHeight=this.view.contentHeight+"px"),this.view.state.facet(unfixGutters)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":""),this.prevViewport=update.view.viewport}syncGutters(detach){let after=this.dom.nextSibling;detach&&this.dom.remove();let lineClasses=RangeSet.iter(this.view.state.facet(gutterLineClass),this.view.viewport.from),classSet=[],contexts=this.gutters.map(gutter2=>new UpdateContext(gutter2,this.view.viewport,-this.view.documentPadding.top));for(let line of this.view.viewportLineBlocks)if(classSet.length&&(classSet=[]),Array.isArray(line.type)){let first=!0;for(let b of line.type)if(b.type==BlockType.Text&&first){advanceCursor(lineClasses,classSet,b.from);for(let cx of contexts)cx.line(this.view,b,classSet);first=!1}else if(b.widget)for(let cx of contexts)cx.widget(this.view,b)}else if(line.type==BlockType.Text){advanceCursor(lineClasses,classSet,line.from);for(let cx of contexts)cx.line(this.view,line,classSet)}else if(line.widget)for(let cx of contexts)cx.widget(this.view,line);for(let cx of contexts)cx.finish();detach&&this.view.scrollDOM.insertBefore(this.dom,after)}updateGutters(update){let prev=update.startState.facet(activeGutters),cur2=update.state.facet(activeGutters),change=update.docChanged||update.heightChanged||update.viewportChanged||!RangeSet.eq(update.startState.facet(gutterLineClass),update.state.facet(gutterLineClass),update.view.viewport.from,update.view.viewport.to);if(prev==cur2)for(let gutter2 of this.gutters)gutter2.update(update)&&(change=!0);else{change=!0;let gutters2=[];for(let conf of cur2){let known=prev.indexOf(conf);known<0?gutters2.push(new SingleGutterView(this.view,conf)):(this.gutters[known].update(update),gutters2.push(this.gutters[known]))}for(let g of this.gutters)g.dom.remove(),gutters2.indexOf(g)<0&&g.destroy();for(let g of gutters2)this.dom.appendChild(g.dom);this.gutters=gutters2}return change}destroy(){for(let view of this.gutters)view.destroy();this.dom.remove()}},{provide:plugin=>EditorView.scrollMargins.of(view=>{let value=view.plugin(plugin);return!value||value.gutters.length==0||!value.fixed?null:view.textDirection==Direction.LTR?{left:value.dom.offsetWidth*view.scaleX}:{right:value.dom.offsetWidth*view.scaleX}})});function asArray$1(val){return Array.isArray(val)?val:[val]}__name(asArray$1,"asArray$1"),__name2(asArray$1,"asArray$1");function advanceCursor(cursor,collect,pos){for(;cursor.value&&cursor.from<=pos;)cursor.from==pos&&collect.push(cursor.value),cursor.next()}__name(advanceCursor,"advanceCursor"),__name2(advanceCursor,"advanceCursor");const _UpdateContext=class{static{__name(this,"_UpdateContext")}constructor(gutter2,viewport,height){this.gutter=gutter2,this.height=height,this.i=0,this.cursor=RangeSet.iter(gutter2.markers,viewport.from)}addElement(view,block,markers){let{gutter:gutter2}=this,above=(block.top-this.height)/view.scaleY,height=block.height/view.scaleY;if(this.i==gutter2.elements.length){let newElt=new GutterElement(view,height,above,markers);gutter2.elements.push(newElt),gutter2.dom.appendChild(newElt.dom)}else gutter2.elements[this.i].update(view,height,above,markers);this.height=block.bottom,this.i++}line(view,line,extraMarkers){let localMarkers=[];advanceCursor(this.cursor,localMarkers,line.from),extraMarkers.length&&(localMarkers=localMarkers.concat(extraMarkers));let forLine=this.gutter.config.lineMarker(view,line,localMarkers);forLine&&localMarkers.unshift(forLine);let gutter2=this.gutter;localMarkers.length==0&&!gutter2.config.renderEmptyElements||this.addElement(view,line,localMarkers)}widget(view,block){let marker=this.gutter.config.widgetMarker(view,block.widget,block);marker&&this.addElement(view,block,[marker])}finish(){let gutter2=this.gutter;for(;gutter2.elements.length>this.i;){let last2=gutter2.elements.pop();gutter2.dom.removeChild(last2.dom),last2.destroy()}}};__name2(_UpdateContext,"UpdateContext");let UpdateContext=_UpdateContext;const _SingleGutterView=class{static{__name(this,"_SingleGutterView")}constructor(view,config2){this.view=view,this.config=config2,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let prop in config2.domEventHandlers)this.dom.addEventListener(prop,event=>{let target=event.target,y;if(target!=this.dom&&this.dom.contains(target)){for(;target.parentNode!=this.dom;)target=target.parentNode;let rect=target.getBoundingClientRect();y=(rect.top+rect.bottom)/2}else y=event.clientY;let line=view.lineBlockAtHeight(y-view.documentTop);config2.domEventHandlers[prop](view,line,event)&&event.preventDefault()});this.markers=asArray$1(config2.markers(view)),config2.initialSpacer&&(this.spacer=new GutterElement(view,0,0,[config2.initialSpacer(view)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(update){let prevMarkers=this.markers;if(this.markers=asArray$1(this.config.markers(update.view)),this.spacer&&this.config.updateSpacer){let updated=this.config.updateSpacer(this.spacer.markers[0],update);updated!=this.spacer.markers[0]&&this.spacer.update(update.view,0,0,[updated])}let vp=update.view.viewport;return!RangeSet.eq(this.markers,prevMarkers,vp.from,vp.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(update):!1)}destroy(){for(let elt of this.elements)elt.destroy()}};__name2(_SingleGutterView,"SingleGutterView");let SingleGutterView=_SingleGutterView;const _GutterElement=class{static{__name(this,"_GutterElement")}constructor(view,height,above,markers){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(view,height,above,markers)}update(view,height,above,markers){this.height!=height&&(this.height=height,this.dom.style.height=height+"px"),this.above!=above&&(this.dom.style.marginTop=(this.above=above)?above+"px":""),sameMarkers(this.markers,markers)||this.setMarkers(view,markers)}setMarkers(view,markers){let cls="cm-gutterElement",domPos=this.dom.firstChild;for(let iNew=0,iOld=0;;){let skipTo=iOld,marker=iNewexists(view,line,event2)||add2(view,line,event2):add2}return result}})}}),_NumberMarker=class extends GutterMarker{static{__name(this,"_NumberMarker")}constructor(number2){super(),this.number=number2}eq(other){return this.number==other.number}toDOM(){return document.createTextNode(this.number)}};__name2(_NumberMarker,"NumberMarker");let NumberMarker=_NumberMarker;function formatNumber(view,number2){return view.state.facet(lineNumberConfig).formatNumber(number2,view.state)}__name(formatNumber,"formatNumber"),__name2(formatNumber,"formatNumber");const lineNumberGutter=activeGutters.compute([lineNumberConfig],state=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(view){return view.state.facet(lineNumberMarkers)},lineMarker(view,line,others){return others.some(m=>m.toDOM)?null:new NumberMarker(formatNumber(view,view.state.doc.lineAt(line.from).number))},widgetMarker:()=>null,lineMarkerChange:update=>update.startState.facet(lineNumberConfig)!=update.state.facet(lineNumberConfig),initialSpacer(view){return new NumberMarker(formatNumber(view,maxLineNumber(view.state.doc.lines)))},updateSpacer(spacer,update){let max=formatNumber(update.view,maxLineNumber(update.view.state.doc.lines));return max==spacer.number?spacer:new NumberMarker(max)},domEventHandlers:state.facet(lineNumberConfig).domEventHandlers}));function lineNumbers(config2={}){return[lineNumberConfig.of(config2),gutters(),lineNumberGutter]}__name(lineNumbers,"lineNumbers"),__name2(lineNumbers,"lineNumbers");function maxLineNumber(lines){let last2=9;for(;last2{let marks=[],last2=-1;for(let range of state.selection.ranges){let linePos=state.doc.lineAt(range.head).from;linePos>last2&&(last2=linePos,marks.push(activeLineGutterMarker.range(linePos)))}return RangeSet.of(marks)});function highlightActiveLineGutter(){return activeLineGutterHighlighter}__name(highlightActiveLineGutter,"highlightActiveLineGutter"),__name2(highlightActiveLineGutter,"highlightActiveLineGutter");const DefaultBufferLength=1024;let nextPropID=0;const _Range=class{static{__name(this,"_Range")}constructor(from,to){this.from=from,this.to=to}};__name2(_Range,"Range");let Range=_Range;const _NodeProp=class{static{__name(this,"_NodeProp")}constructor(config2={}){this.id=nextPropID++,this.perNode=!!config2.perNode,this.deserialize=config2.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(match2){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof match2!="function"&&(match2=NodeType.match(match2)),type=>{let result=match2(type);return result===void 0?null:[this,result]}}};__name2(_NodeProp,"NodeProp");let NodeProp=_NodeProp;NodeProp.closedBy=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.openedBy=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.group=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.contextHash=new NodeProp({perNode:!0}),NodeProp.lookAhead=new NodeProp({perNode:!0}),NodeProp.mounted=new NodeProp({perNode:!0});const noProps=Object.create(null),_NodeType=class _NodeType2{static{__name(this,"_NodeType")}constructor(name2,props,id,flags=0){this.name=name2,this.props=props,this.id=id,this.flags=flags}static define(spec){let props=spec.props&&spec.props.length?Object.create(null):noProps,flags=(spec.top?1:0)|(spec.skipped?2:0)|(spec.error?4:0)|(spec.name==null?8:0),type=new _NodeType2(spec.name||"",props,spec.id,flags);if(spec.props){for(let src of spec.props)if(Array.isArray(src)||(src=src(type)),src){if(src[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");props[src[0].id]=src[1]}}return type}prop(prop){return this.props[prop.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(name2){if(typeof name2=="string"){if(this.name==name2)return!0;let group=this.prop(NodeProp.group);return group?group.indexOf(name2)>-1:!1}return this.id==name2}static match(map2){let direct=Object.create(null);for(let prop in map2)for(let name2 of prop.split(" "))direct[name2]=map2[prop];return node=>{for(let groups=node.prop(NodeProp.group),i=-1;i<(groups?groups.length:0);i++){let found=direct[i<0?node.name:groups[i]];if(found)return found}}}};__name2(_NodeType,"NodeType");let NodeType=_NodeType;NodeType.none=new NodeType("",Object.create(null),0,8);const _NodeSet=class _NodeSet2{static{__name(this,"_NodeSet")}constructor(types2){this.types=types2;for(let i=0;i0;for(let c=this.cursor(mode|IterMode.IncludeAnonymous);;){let entered=!1;if(c.from<=to&&c.to>=from&&(!anon&&c.type.isAnonymous||enter(c)!==!1)){if(c.firstChild())continue;entered=!0}for(;entered&&leave&&(anon||!c.type.isAnonymous)&&leave(c),!c.nextSibling();){if(!c.parent())return;entered=!0}}}prop(prop){return prop.perNode?this.props?this.props[prop.id]:void 0:this.type.prop(prop)}get propValues(){let result=[];if(this.props)for(let id in this.props)result.push([+id,this.props[id]]);return result}balance(config2={}){return this.children.length<=8?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,(children,positions,length)=>new _Tree2(this.type,children,positions,length,this.propValues),config2.makeTree||((children,positions,length)=>new _Tree2(NodeType.none,children,positions,length)))}static build(data){return buildTree(data)}};__name2(_Tree,"Tree");let Tree=_Tree;Tree.empty=new Tree(NodeType.none,[],[],0);const _FlatBufferCursor=class _FlatBufferCursor2{static{__name(this,"_FlatBufferCursor")}constructor(buffer,index2){this.buffer=buffer,this.index=index2}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new _FlatBufferCursor2(this.buffer,this.index)}};__name2(_FlatBufferCursor,"FlatBufferCursor");let FlatBufferCursor=_FlatBufferCursor;const _TreeBuffer=class _TreeBuffer2{static{__name(this,"_TreeBuffer")}constructor(buffer,length,set){this.buffer=buffer,this.length=length,this.set=set}get type(){return NodeType.none}toString(){let result=[];for(let index2=0;index20));i=buffer[i+3]);return pick2}slice(startI,endI,from){let b=this.buffer,copy=new Uint16Array(endI-startI),len=0;for(let i=startI,j=0;i=pos&&frompos;case 1:return from<=pos&&to>pos;case 2:return to>pos;case 4:return!0}}__name(checkSide,"checkSide"),__name2(checkSide,"checkSide");function enterUnfinishedNodesBefore(node,pos){let scan=node.childBefore(pos);for(;scan;){let last2=scan.lastChild;if(!last2||last2.to!=scan.to)break;last2.type.isError&&last2.from==last2.to?(node=scan,scan=last2.prevSibling):scan=last2}return node}__name(enterUnfinishedNodesBefore,"enterUnfinishedNodesBefore"),__name2(enterUnfinishedNodesBefore,"enterUnfinishedNodesBefore");function resolveNode(node,pos,side,overlays){for(var _a3;node.from==node.to||(side<1?node.from>=pos:node.from>pos)||(side>-1?node.to<=pos:node.to0?children.length:-1;i!=e;i+=dir){let next=children[i],start=positions[i]+parent.from;if(checkSide(side,pos,start,start+next.length)){if(next instanceof TreeBuffer){if(mode&IterMode.ExcludeBuffers)continue;let index2=next.findChild(0,next.buffer.length,dir,pos-start,side);if(index2>-1)return new BufferNode(new BufferContext(parent,next,i,start),null,index2)}else if(mode&IterMode.IncludeAnonymous||!next.type.isAnonymous||hasChild(next)){let mounted;if(!(mode&IterMode.IgnoreMounts)&&next.props&&(mounted=next.prop(NodeProp.mounted))&&!mounted.overlay)return new _TreeNode2(mounted.tree,start,i,parent);let inner=new _TreeNode2(next,start,i,parent);return mode&IterMode.IncludeAnonymous||!inner.type.isAnonymous?inner:inner.nextChild(dir<0?next.children.length-1:0,dir,pos,side)}}}if(mode&IterMode.IncludeAnonymous||!parent.type.isAnonymous||(parent.index>=0?i=parent.index+dir:i=dir<0?-1:parent._parent._tree.children.length,parent=parent._parent,!parent))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(pos){return this.nextChild(0,1,pos,2)}childBefore(pos){return this.nextChild(this._tree.children.length-1,-1,pos,-2)}enter(pos,side,mode=0){let mounted;if(!(mode&IterMode.IgnoreOverlays)&&(mounted=this._tree.prop(NodeProp.mounted))&&mounted.overlay){let rPos=pos-this.from;for(let{from,to}of mounted.overlay)if((side>0?from<=rPos:from=rPos:to>rPos))return new _TreeNode2(mounted.tree,mounted.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,pos,side,mode)}nextSignificantParent(){let val=this;for(;val.type.isAnonymous&&val._parent;)val=val._parent;return val}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}cursor(mode=0){return new TreeCursor(this,mode)}get tree(){return this._tree}toTree(){return this._tree}resolve(pos,side=0){return resolveNode(this,pos,side,!1)}resolveInner(pos,side=0){return resolveNode(this,pos,side,!0)}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos)}getChild(type,before=null,after=null){let r=getChildren(this,type,before,after);return r.length?r[0]:null}getChildren(type,before=null,after=null){return getChildren(this,type,before,after)}toString(){return this._tree.toString()}get node(){return this}matchContext(context){return matchNodeContext(this,context)}};__name2(_TreeNode,"TreeNode");let TreeNode=_TreeNode;function getChildren(node,type,before,after){let cur2=node.cursor(),result=[];if(!cur2.firstChild())return result;if(before!=null){for(;!cur2.type.is(before);)if(!cur2.nextSibling())return result}for(;;){if(after!=null&&cur2.type.is(after))return result;if(cur2.type.is(type)&&result.push(cur2.node),!cur2.nextSibling())return after==null?result:[]}}__name(getChildren,"getChildren"),__name2(getChildren,"getChildren");function matchNodeContext(node,context,i=context.length-1){for(let p=node.parent;i>=0;p=p.parent){if(!p)return!1;if(!p.type.isAnonymous){if(context[i]&&context[i]!=p.name)return!1;i--}}return!0}__name(matchNodeContext,"matchNodeContext"),__name2(matchNodeContext,"matchNodeContext");const _BufferContext=class{static{__name(this,"_BufferContext")}constructor(parent,buffer,index2,start){this.parent=parent,this.buffer=buffer,this.index=index2,this.start=start}};__name2(_BufferContext,"BufferContext");let BufferContext=_BufferContext;const _BufferNode=class _BufferNode2{static{__name(this,"_BufferNode")}get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(context,_parent,index2){this.context=context,this._parent=_parent,this.index=index2,this.type=context.buffer.set.types[context.buffer.buffer[index2]]}child(dir,pos,side){let{buffer}=this.context,index2=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.context.start,side);return index2<0?null:new _BufferNode2(this.context,this,index2)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(pos){return this.child(1,pos,2)}childBefore(pos){return this.child(-1,pos,-2)}enter(pos,side,mode=0){if(mode&IterMode.ExcludeBuffers)return null;let{buffer}=this.context,index2=buffer.findChild(this.index+4,buffer.buffer[this.index+3],side>0?1:-1,pos-this.context.start,side);return index2<0?null:new _BufferNode2(this.context,this,index2)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(dir){return this._parent?null:this.context.parent.nextChild(this.context.index+dir,dir,0,4)}get nextSibling(){let{buffer}=this.context,after=buffer.buffer[this.index+3];return after<(this._parent?buffer.buffer[this._parent.index+3]:buffer.buffer.length)?new _BufferNode2(this.context,this._parent,after):this.externalSibling(1)}get prevSibling(){let{buffer}=this.context,parentStart=this._parent?this._parent.index+4:0;return this.index==parentStart?this.externalSibling(-1):new _BufferNode2(this.context,this._parent,buffer.findChild(parentStart,this.index,-1,0,4))}cursor(mode=0){return new TreeCursor(this,mode)}get tree(){return null}toTree(){let children=[],positions=[],{buffer}=this.context,startI=this.index+4,endI=buffer.buffer[this.index+3];if(endI>startI){let from=buffer.buffer[this.index+1];children.push(buffer.slice(startI,endI,from)),positions.push(0)}return new Tree(this.type,children,positions,this.to-this.from)}resolve(pos,side=0){return resolveNode(this,pos,side,!1)}resolveInner(pos,side=0){return resolveNode(this,pos,side,!0)}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos)}toString(){return this.context.buffer.childString(this.index)}getChild(type,before=null,after=null){let r=getChildren(this,type,before,after);return r.length?r[0]:null}getChildren(type,before=null,after=null){return getChildren(this,type,before,after)}get node(){return this}matchContext(context){return matchNodeContext(this,context)}};__name2(_BufferNode,"BufferNode");let BufferNode=_BufferNode;const _TreeCursor=class{static{__name(this,"_TreeCursor")}get name(){return this.type.name}constructor(node,mode=0){if(this.mode=mode,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,node instanceof TreeNode)this.yieldNode(node);else{this._tree=node.context.parent,this.buffer=node.context;for(let n2=node._parent;n2;n2=n2._parent)this.stack.unshift(n2.index);this.bufferNode=node,this.yieldBuf(node.index)}}yieldNode(node){return node?(this._tree=node,this.type=node.type,this.from=node.from,this.to=node.to,!0):!1}yieldBuf(index2,type){this.index=index2;let{start,buffer}=this.buffer;return this.type=type||buffer.set.types[buffer.buffer[index2]],this.from=start+buffer.buffer[index2+1],this.to=start+buffer.buffer[index2+2],!0}yield(node){return node?node instanceof TreeNode?(this.buffer=null,this.yieldNode(node)):(this.buffer=node.context,this.yieldBuf(node.index,node.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(dir,pos,side){if(!this.buffer)return this.yield(this._tree.nextChild(dir<0?this._tree._tree.children.length-1:0,dir,pos,side,this.mode));let{buffer}=this.buffer,index2=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.buffer.start,side);return index2<0?!1:(this.stack.push(this.index),this.yieldBuf(index2))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(pos){return this.enterChild(1,pos,2)}childBefore(pos){return this.enterChild(-1,pos,-2)}enter(pos,side,mode=this.mode){return this.buffer?mode&IterMode.ExcludeBuffers?!1:this.enterChild(1,pos,side):this.yield(this._tree.enter(pos,side,mode))}parent(){if(!this.buffer)return this.yieldNode(this.mode&IterMode.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let parent=this.mode&IterMode.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(parent)}sibling(dir){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+dir,dir,0,4,this.mode)):!1;let{buffer}=this.buffer,d=this.stack.length-1;if(dir<0){let parentStart=d<0?0:this.stack[d]+4;if(this.index!=parentStart)return this.yieldBuf(buffer.findChild(parentStart,this.index,-1,0,4))}else{let after=buffer.buffer[this.index+3];if(after<(d<0?buffer.buffer.length:buffer.buffer[this.stack[d]+3]))return this.yieldBuf(after)}return d<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+dir,dir,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(dir){let index2,parent,{buffer}=this;if(buffer){if(dir>0){if(this.index-1)for(let i=index2+dir,e=dir<0?-1:parent._tree.children.length;i!=e;i+=dir){let child=parent._tree.children[i];if(this.mode&IterMode.IncludeAnonymous||child instanceof TreeBuffer||!child.type.isAnonymous||hasChild(child))return!1}return!0}move(dir,enter){if(enter&&this.enterChild(dir,0,4))return!0;for(;;){if(this.sibling(dir))return!0;if(this.atLastNode(dir)||!this.parent())return!1}}next(enter=!0){return this.move(1,enter)}prev(enter=!0){return this.move(-1,enter)}moveTo(pos,side=0){for(;(this.from==this.to||(side<1?this.from>=pos:this.from>pos)||(side>-1?this.to<=pos:this.to=0;){for(let c=cache;c;c=c._parent)if(c.index==index2){if(index2==this.index)return c;result=c,depth=d+1;break scan}index2=this.stack[--d]}for(let i=depth;i=0;d--){if(d<0)return matchNodeContext(this.node,context,i);let type=types2[buffer.buffer[this.stack[d]]];if(!type.isAnonymous){if(context[i]&&context[i]!=type.name)return!1;i--}}return!0}};__name2(_TreeCursor,"TreeCursor");let TreeCursor=_TreeCursor;function hasChild(tree){return tree.children.some(ch=>ch instanceof TreeBuffer||!ch.type.isAnonymous||hasChild(ch))}__name(hasChild,"hasChild"),__name2(hasChild,"hasChild");function buildTree(data){var _a3;let{buffer,nodeSet,maxBufferLength=DefaultBufferLength,reused=[],minRepeatType=nodeSet.types.length}=data,cursor=Array.isArray(buffer)?new FlatBufferCursor(buffer,buffer.length):buffer,types2=nodeSet.types,contextHash=0,lookAhead=0;function takeNode(parentStart,minPos,children2,positions2,inRepeat){let{id,start,end,size}=cursor,lookAheadAtStart=lookAhead;for(;size<0;)if(cursor.next(),size==-1){let node2=reused[id];children2.push(node2),positions2.push(start-parentStart);return}else if(size==-3){contextHash=id;return}else if(size==-4){lookAhead=id;return}else throw new RangeError(`Unrecognized record size: ${size}`);let type=types2[id],node,buffer2,startPos=start-parentStart;if(end-start<=maxBufferLength&&(buffer2=findBufferSize(cursor.pos-minPos,inRepeat))){let data2=new Uint16Array(buffer2.size-buffer2.skip),endPos=cursor.pos-buffer2.size,index2=data2.length;for(;cursor.pos>endPos;)index2=copyToBuffer(buffer2.start,data2,index2);node=new TreeBuffer(data2,end-buffer2.start,nodeSet),startPos=buffer2.start-parentStart}else{let endPos=cursor.pos-size;cursor.next();let localChildren=[],localPositions=[],localInRepeat=id>=minRepeatType?id:-1,lastGroup=0,lastEnd=end;for(;cursor.pos>endPos;)localInRepeat>=0&&cursor.id==localInRepeat&&cursor.size>=0?(cursor.end<=lastEnd-maxBufferLength&&(makeRepeatLeaf(localChildren,localPositions,start,lastGroup,cursor.end,lastEnd,localInRepeat,lookAheadAtStart),lastGroup=localChildren.length,lastEnd=cursor.end),cursor.next()):takeNode(start,endPos,localChildren,localPositions,localInRepeat);if(localInRepeat>=0&&lastGroup>0&&lastGroup-1&&lastGroup>0){let make=makeBalanced(type);node=balanceRange(type,localChildren,localPositions,0,localChildren.length,0,end-start,make,make)}else node=makeTree(type,localChildren,localPositions,end-start,lookAheadAtStart-end)}children2.push(node),positions2.push(startPos)}__name(takeNode,"takeNode"),__name2(takeNode,"takeNode");function makeBalanced(type){return(children2,positions2,length2)=>{let lookAhead2=0,lastI=children2.length-1,last2,lookAheadProp;if(lastI>=0&&(last2=children2[lastI])instanceof Tree){if(!lastI&&last2.type==type&&last2.length==length2)return last2;(lookAheadProp=last2.prop(NodeProp.lookAhead))&&(lookAhead2=positions2[lastI]+last2.length+lookAheadProp)}return makeTree(type,children2,positions2,length2,lookAhead2)}}__name(makeBalanced,"makeBalanced"),__name2(makeBalanced,"makeBalanced");function makeRepeatLeaf(children2,positions2,base2,i,from,to,type,lookAhead2){let localChildren=[],localPositions=[];for(;children2.length>i;)localChildren.push(children2.pop()),localPositions.push(positions2.pop()+base2-from);children2.push(makeTree(nodeSet.types[type],localChildren,localPositions,to-from,lookAhead2-to)),positions2.push(from-base2)}__name(makeRepeatLeaf,"makeRepeatLeaf"),__name2(makeRepeatLeaf,"makeRepeatLeaf");function makeTree(type,children2,positions2,length2,lookAhead2=0,props){if(contextHash){let pair2=[NodeProp.contextHash,contextHash];props=props?[pair2].concat(props):[pair2]}if(lookAhead2>25){let pair2=[NodeProp.lookAhead,lookAhead2];props=props?[pair2].concat(props):[pair2]}return new Tree(type,children2,positions2,length2,props)}__name(makeTree,"makeTree"),__name2(makeTree,"makeTree");function findBufferSize(maxSize,inRepeat){let fork=cursor.fork(),size=0,start=0,skip=0,minStart=fork.end-maxBufferLength,result={size:0,start:0,skip:0};scan:for(let minPos=fork.pos-maxSize;fork.pos>minPos;){let nodeSize2=fork.size;if(fork.id==inRepeat&&nodeSize2>=0){result.size=size,result.start=start,result.skip=skip,skip+=4,size+=4,fork.next();continue}let startPos=fork.pos-nodeSize2;if(nodeSize2<0||startPos=minRepeatType?4:0,nodeStart2=fork.start;for(fork.next();fork.pos>startPos;){if(fork.size<0)if(fork.size==-3)localSkipped+=4;else break scan;else fork.id>=minRepeatType&&(localSkipped+=4);fork.next()}start=nodeStart2,size+=nodeSize2,skip+=localSkipped}return(inRepeat<0||size==maxSize)&&(result.size=size,result.start=start,result.skip=skip),result.size>4?result:void 0}__name(findBufferSize,"findBufferSize"),__name2(findBufferSize,"findBufferSize");function copyToBuffer(bufferStart,buffer2,index2){let{id,start,end,size}=cursor;if(cursor.next(),size>=0&&id4){let endPos=cursor.pos-(size-4);for(;cursor.pos>endPos;)index2=copyToBuffer(bufferStart,buffer2,index2)}buffer2[--index2]=startIndex,buffer2[--index2]=end-bufferStart,buffer2[--index2]=start-bufferStart,buffer2[--index2]=id}else size==-3?contextHash=id:size==-4&&(lookAhead=id);return index2}__name(copyToBuffer,"copyToBuffer"),__name2(copyToBuffer,"copyToBuffer");let children=[],positions=[];for(;cursor.pos>0;)takeNode(data.start||0,data.bufferStart||0,children,positions,-1);let length=(_a3=data.length)!==null&&_a3!==void 0?_a3:children.length?positions[0]+children[0].length:0;return new Tree(types2[data.topID],children.reverse(),positions.reverse(),length)}__name(buildTree,"buildTree"),__name2(buildTree,"buildTree");const nodeSizeCache=new WeakMap;function nodeSize(balanceType,node){if(!balanceType.isAnonymous||node instanceof TreeBuffer||node.type!=balanceType)return 1;let size=nodeSizeCache.get(node);if(size==null){size=1;for(let child of node.children){if(child.type!=balanceType||!(child instanceof Tree)){size=1;break}size+=nodeSize(balanceType,child)}nodeSizeCache.set(node,size)}return size}__name(nodeSize,"nodeSize"),__name2(nodeSize,"nodeSize");function balanceRange(balanceType,children,positions,from,to,start,length,mkTop,mkTree){let total=0;for(let i=from;i=maxChild)break;groupSize+=nextSize}if(i==groupFrom+1){if(groupSize>maxChild){let only=children2[groupFrom];divide(only.children,only.positions,0,only.children.length,positions2[groupFrom]+offset2);continue}localChildren.push(children2[groupFrom])}else{let length2=positions2[i-1]+children2[i-1].length-groupStart;localChildren.push(balanceRange(balanceType,children2,positions2,groupFrom,i,groupStart,length2,null,mkTree))}localPositions.push(groupStart+offset2-start)}}return __name(divide,"divide"),__name2(divide,"divide"),divide(children,positions,from,to,0),(mkTop||mkTree)(localChildren,localPositions,length)}__name(balanceRange,"balanceRange"),__name2(balanceRange,"balanceRange");const _TreeFragment=class _TreeFragment2{static{__name(this,"_TreeFragment")}constructor(from,to,tree,offset2,openStart=!1,openEnd=!1){this.from=from,this.to=to,this.tree=tree,this.offset=offset2,this.open=(openStart?1:0)|(openEnd?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(tree,fragments=[],partial=!1){let result=[new _TreeFragment2(0,tree.length,tree,0,!1,partial)];for(let f of fragments)f.to>tree.length&&result.push(f);return result}static applyChanges(fragments,changes,minGap=128){if(!changes.length)return fragments;let result=[],fI=1,nextF=fragments.length?fragments[0]:null;for(let cI=0,pos=0,off2=0;;cI++){let nextC=cI=minGap)for(;nextF&&nextF.from=cut.from||nextPos<=cut.to||off2){let fFrom=Math.max(cut.from,pos)-off2,fTo=Math.min(cut.to,nextPos)-off2;cut=fFrom>=fTo?null:new _TreeFragment2(fFrom,fTo,cut.tree,cut.offset+off2,cI>0,!!nextC)}if(cut&&result.push(cut),nextF.to>nextPos)break;nextF=fInew Range(r.from,r.to)):[new Range(0,0)]:[new Range(0,input.length)],this.createParse(input,fragments||[],ranges)}parse(input,fragments,ranges){let parse2=this.startParse(input,fragments,ranges);for(;;){let done=parse2.advance();if(done)return done}}};__name2(_Parser,"Parser");let Parser=_Parser;const _StringInput=class{static{__name(this,"_StringInput")}constructor(string2){this.string=string2}get length(){return this.string.length}chunk(from){return this.string.slice(from)}get lineChunks(){return!1}read(from,to){return this.string.slice(from,to)}};__name2(_StringInput,"StringInput");let StringInput=_StringInput;new NodeProp({perNode:!0});let nextTagID=0;const _Tag=class _Tag2{static{__name(this,"_Tag")}constructor(set,base2,modified){this.set=set,this.base=base2,this.modified=modified,this.id=nextTagID++}static define(parent){if(parent?.base)throw new Error("Can not derive from a modified tag");let tag=new _Tag2([],null,[]);if(tag.set.push(tag),parent)for(let t2 of parent.set)tag.set.push(t2);return tag}static defineModifier(){let mod=new Modifier;return tag=>tag.modified.indexOf(mod)>-1?tag:Modifier.get(tag.base||tag,tag.modified.concat(mod).sort((a,b)=>a.id-b.id))}};__name2(_Tag,"Tag");let Tag=_Tag,nextModifierID=0;const _Modifier=class _Modifier2{static{__name(this,"_Modifier")}constructor(){this.instances=[],this.id=nextModifierID++}static get(base2,mods){if(!mods.length)return base2;let exists=mods[0].instances.find(t2=>t2.base==base2&&sameArray(mods,t2.modified));if(exists)return exists;let set=[],tag=new Tag(set,base2,mods);for(let m of mods)m.instances.push(tag);let configs=powerSet(mods);for(let parent of base2.set)if(!parent.modified.length)for(let config2 of configs)set.push(_Modifier2.get(parent,config2));return tag}};__name2(_Modifier,"Modifier");let Modifier=_Modifier;function sameArray(a,b){return a.length==b.length&&a.every((x,i)=>x==b[i])}__name(sameArray,"sameArray"),__name2(sameArray,"sameArray");function powerSet(array){let sets=[[]];for(let i=0;ib.length-a.length)}__name(powerSet,"powerSet"),__name2(powerSet,"powerSet");function styleTags(spec){let byName=Object.create(null);for(let prop in spec){let tags2=spec[prop];Array.isArray(tags2)||(tags2=[tags2]);for(let part of prop.split(" "))if(part){let pieces=[],mode=2,rest=part;for(let pos=0;;){if(rest=="..."&&pos>0&&pos+3==part.length){mode=1;break}let m=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);if(!m)throw new RangeError("Invalid path: "+part);if(pieces.push(m[0]=="*"?"":m[0][0]=='"'?JSON.parse(m[0]):m[0]),pos+=m[0].length,pos==part.length)break;let next=part[pos++];if(pos==part.length&&next=="!"){mode=0;break}if(next!="/")throw new RangeError("Invalid path: "+part);rest=part.slice(pos)}let last2=pieces.length-1,inner=pieces[last2];if(!inner)throw new RangeError("Invalid path: "+part);let rule=new Rule(tags2,mode,last2>0?pieces.slice(0,last2):null);byName[inner]=rule.sort(byName[inner])}}return ruleNodeProp.add(byName)}__name(styleTags,"styleTags"),__name2(styleTags,"styleTags");const ruleNodeProp=new NodeProp,_Rule=class{static{__name(this,"_Rule")}constructor(tags2,mode,context,next){this.tags=tags2,this.mode=mode,this.context=context,this.next=next}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(other){return!other||other.depth{let cls=all;for(let tag of tags3)for(let sub of tag.set){let tagClass=map2[sub.id];if(tagClass){cls=cls?cls+" "+tagClass:tagClass;break}}return cls},scope:scope2}}__name(tagHighlighter,"tagHighlighter"),__name2(tagHighlighter,"tagHighlighter");function highlightTags(highlighters,tags2){let result=null;for(let highlighter of highlighters){let value=highlighter.style(tags2);value&&(result=result?result+" "+value:value)}return result}__name(highlightTags,"highlightTags"),__name2(highlightTags,"highlightTags");function highlightTree(tree,highlighter,putStyle,from=0,to=tree.length){let builder=new HighlightBuilder(from,Array.isArray(highlighter)?highlighter:[highlighter],putStyle);builder.highlightRange(tree.cursor(),from,to,"",builder.highlighters),builder.flush(to)}__name(highlightTree,"highlightTree"),__name2(highlightTree,"highlightTree");const _HighlightBuilder=class{static{__name(this,"_HighlightBuilder")}constructor(at,highlighters,span){this.at=at,this.highlighters=highlighters,this.span=span,this.class=""}startSpan(at,cls){cls!=this.class&&(this.flush(at),at>this.at&&(this.at=at),this.class=cls)}flush(to){to>this.at&&this.class&&this.span(this.at,to,this.class)}highlightRange(cursor,from,to,inheritedClass,highlighters){let{type,from:start,to:end}=cursor;if(start>=to||end<=from)return;type.isTop&&(highlighters=this.highlighters.filter(h=>!h.scope||h.scope(type)));let cls=inheritedClass,rule=getStyleTags(cursor)||Rule.empty,tagCls=highlightTags(highlighters,rule.tags);if(tagCls&&(cls&&(cls+=" "),cls+=tagCls,rule.mode==1&&(inheritedClass+=(inheritedClass?" ":"")+tagCls)),this.startSpan(Math.max(from,start),cls),rule.opaque)return;let mounted=cursor.tree&&cursor.tree.prop(NodeProp.mounted);if(mounted&&mounted.overlay){let inner=cursor.node.enter(mounted.overlay[0].from+start,1),innerHighlighters=this.highlighters.filter(h=>!h.scope||h.scope(mounted.tree.type)),hasChild2=cursor.firstChild();for(let i=0,pos=start;;i++){let next=i=nextPos||!cursor.nextSibling())););if(!next||nextPos>to)break;pos=next.to+start,pos>from&&(this.highlightRange(inner.cursor(),Math.max(from,next.from+start),Math.min(to,pos),"",innerHighlighters),this.startSpan(Math.min(to,pos),cls))}hasChild2&&cursor.parent()}else if(cursor.firstChild()){mounted&&(inheritedClass="");do if(!(cursor.to<=from)){if(cursor.from>=to)break;this.highlightRange(cursor,from,to,inheritedClass,highlighters),this.startSpan(Math.min(to,cursor.to),cls)}while(cursor.nextSibling());cursor.parent()}}};__name2(_HighlightBuilder,"HighlightBuilder");let HighlightBuilder=_HighlightBuilder;function getStyleTags(node){let rule=node.type.prop(ruleNodeProp);for(;rule&&rule.context&&!node.matchContext(rule.context);)rule=rule.next;return rule||null}__name(getStyleTags,"getStyleTags"),__name2(getStyleTags,"getStyleTags");const t=Tag.define,comment=t(),name=t(),typeName=t(name),propertyName=t(name),literal=t(),string=t(literal),number=t(literal),content=t(),heading=t(content),keyword=t(),operator=t(),punctuation=t(),bracket=t(punctuation),meta=t(),tags={comment,lineComment:t(comment),blockComment:t(comment),docComment:t(comment),name,variableName:t(name),typeName,tagName:t(typeName),propertyName,attributeName:t(propertyName),className:t(name),labelName:t(name),namespace:t(name),macroName:t(name),literal,string,docString:t(string),character:t(string),attributeValue:t(string),number,integer:t(number),float:t(number),bool:t(literal),regexp:t(literal),escape:t(literal),color:t(literal),url:t(literal),keyword,self:t(keyword),null:t(keyword),atom:t(keyword),unit:t(keyword),modifier:t(keyword),operatorKeyword:t(keyword),controlKeyword:t(keyword),definitionKeyword:t(keyword),moduleKeyword:t(keyword),operator,derefOperator:t(operator),arithmeticOperator:t(operator),logicOperator:t(operator),bitwiseOperator:t(operator),compareOperator:t(operator),updateOperator:t(operator),definitionOperator:t(operator),typeOperator:t(operator),controlOperator:t(operator),punctuation,separator:t(punctuation),bracket,angleBracket:t(bracket),squareBracket:t(bracket),paren:t(bracket),brace:t(bracket),content,heading,heading1:t(heading),heading2:t(heading),heading3:t(heading),heading4:t(heading),heading5:t(heading),heading6:t(heading),contentSeparator:t(content),list:t(content),quote:t(content),emphasis:t(content),strong:t(content),link:t(content),monospace:t(content),strikethrough:t(content),inserted:t(),deleted:t(),changed:t(),invalid:t(),meta,documentMeta:t(meta),annotation:t(meta),processingInstruction:t(meta),definition:Tag.defineModifier(),constant:Tag.defineModifier(),function:Tag.defineModifier(),standard:Tag.defineModifier(),local:Tag.defineModifier(),special:Tag.defineModifier()};tagHighlighter([{tag:tags.link,class:"tok-link"},{tag:tags.heading,class:"tok-heading"},{tag:tags.emphasis,class:"tok-emphasis"},{tag:tags.strong,class:"tok-strong"},{tag:tags.keyword,class:"tok-keyword"},{tag:tags.atom,class:"tok-atom"},{tag:tags.bool,class:"tok-bool"},{tag:tags.url,class:"tok-url"},{tag:tags.labelName,class:"tok-labelName"},{tag:tags.inserted,class:"tok-inserted"},{tag:tags.deleted,class:"tok-deleted"},{tag:tags.literal,class:"tok-literal"},{tag:tags.string,class:"tok-string"},{tag:tags.number,class:"tok-number"},{tag:[tags.regexp,tags.escape,tags.special(tags.string)],class:"tok-string2"},{tag:tags.variableName,class:"tok-variableName"},{tag:tags.local(tags.variableName),class:"tok-variableName tok-local"},{tag:tags.definition(tags.variableName),class:"tok-variableName tok-definition"},{tag:tags.special(tags.variableName),class:"tok-variableName2"},{tag:tags.definition(tags.propertyName),class:"tok-propertyName tok-definition"},{tag:tags.typeName,class:"tok-typeName"},{tag:tags.namespace,class:"tok-namespace"},{tag:tags.className,class:"tok-className"},{tag:tags.macroName,class:"tok-macroName"},{tag:tags.propertyName,class:"tok-propertyName"},{tag:tags.operator,class:"tok-operator"},{tag:tags.comment,class:"tok-comment"},{tag:tags.meta,class:"tok-meta"},{tag:tags.invalid,class:"tok-invalid"},{tag:tags.punctuation,class:"tok-punctuation"}]);var _a$1;const languageDataProp=new NodeProp;function defineLanguageFacet(baseData){return Facet.define({combine:baseData?values=>values.concat(baseData):void 0})}__name(defineLanguageFacet,"defineLanguageFacet"),__name2(defineLanguageFacet,"defineLanguageFacet");const sublanguageProp=new NodeProp,_Language=class{static{__name(this,"_Language")}constructor(data,parser2,extraExtensions=[],name2=""){this.data=data,this.name=name2,EditorState.prototype.hasOwnProperty("tree")||Object.defineProperty(EditorState.prototype,"tree",{get(){return syntaxTree(this)}}),this.parser=parser2,this.extension=[language.of(this),EditorState.languageData.of((state,pos,side)=>{let top2=topNodeAt(state,pos,side),data2=top2.type.prop(languageDataProp);if(!data2)return[];let base2=state.facet(data2),sub=top2.type.prop(sublanguageProp);if(sub){let innerNode=top2.resolve(pos-top2.from,side);for(let sublang of sub)if(sublang.test(innerNode,state)){let data3=state.facet(sublang.facet);return sublang.type=="replace"?data3:data3.concat(base2)}}return base2})].concat(extraExtensions)}isActiveAt(state,pos,side=-1){return topNodeAt(state,pos,side).type.prop(languageDataProp)==this.data}findRegions(state){let lang=state.facet(language);if(lang?.data==this.data)return[{from:0,to:state.doc.length}];if(!lang||!lang.allowsNesting)return[];let result=[],explore=__name2((tree,from)=>{if(tree.prop(languageDataProp)==this.data){result.push({from,to:from+tree.length});return}let mount2=tree.prop(NodeProp.mounted);if(mount2){if(mount2.tree.prop(languageDataProp)==this.data){if(mount2.overlay)for(let r of mount2.overlay)result.push({from:r.from+from,to:r.to+from});else result.push({from,to:from+tree.length});return}else if(mount2.overlay){let size=result.length;if(explore(mount2.tree,mount2.overlay[0].from+from),result.length>size)return}}for(let i=0;itype.isTop?data:void 0)]}),spec.name)}configure(options,name2){return new _LRLanguage2(this.data,this.parser.configure(options),name2||this.name)}get allowsNesting(){return this.parser.hasWrappers()}};__name2(_LRLanguage,"LRLanguage");let LRLanguage=_LRLanguage;function syntaxTree(state){let field=state.field(Language.state,!1);return field?field.tree:Tree.empty}__name(syntaxTree,"syntaxTree"),__name2(syntaxTree,"syntaxTree");const _DocInput=class{static{__name(this,"_DocInput")}constructor(doc2){this.doc=doc2,this.cursorPos=0,this.string="",this.cursor=doc2.iter()}get length(){return this.doc.length}syncTo(pos){return this.string=this.cursor.next(pos-this.cursorPos).value,this.cursorPos=pos+this.string.length,this.cursorPos-this.string.length}chunk(pos){return this.syncTo(pos),this.string}get lineChunks(){return!0}read(from,to){let stringStart=this.cursorPos-this.string.length;return from=this.cursorPos?this.doc.sliceString(from,to):this.string.slice(from-stringStart,to-stringStart)}};__name2(_DocInput,"DocInput");let DocInput=_DocInput,currentContext=null;const _ParseContext=class _ParseContext2{static{__name(this,"_ParseContext")}constructor(parser2,state,fragments=[],tree,treeLen,viewport,skipped,scheduleOn){this.parser=parser2,this.state=state,this.fragments=fragments,this.tree=tree,this.treeLen=treeLen,this.viewport=viewport,this.skipped=skipped,this.scheduleOn=scheduleOn,this.parse=null,this.tempSkipped=[]}static create(parser2,state,viewport){return new _ParseContext2(parser2,state,[],Tree.empty,0,viewport,[],null)}startParse(){return this.parser.startParse(new DocInput(this.state.doc),this.fragments)}work(until,upto){return upto!=null&&upto>=this.state.doc.length&&(upto=void 0),this.tree!=Tree.empty&&this.isDone(upto??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var _a3;if(typeof until=="number"){let endTime=Date.now()+until;until=__name2(()=>Date.now()>endTime,"until")}for(this.parse||(this.parse=this.startParse()),upto!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>upto)&&upto=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>pos)&&this.parse.stopAt(pos),this.withContext(()=>{for(;!(tree=this.parse.advance()););}),this.treeLen=pos,this.tree=tree,this.fragments=this.withoutTempSkipped(TreeFragment.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(f){let prev=currentContext;currentContext=this;try{return f()}finally{currentContext=prev}}withoutTempSkipped(fragments){for(let r;r=this.tempSkipped.pop();)fragments=cutFragments(fragments,r.from,r.to);return fragments}changes(changes,newState){let{fragments,tree,treeLen,viewport,skipped}=this;if(this.takeTree(),!changes.empty){let ranges=[];if(changes.iterChangedRanges((fromA,toA,fromB,toB)=>ranges.push({fromA,toA,fromB,toB})),fragments=TreeFragment.applyChanges(fragments,ranges),tree=Tree.empty,treeLen=0,viewport={from:changes.mapPos(viewport.from,-1),to:changes.mapPos(viewport.to,1)},this.skipped.length){skipped=[];for(let r of this.skipped){let from=changes.mapPos(r.from,1),to=changes.mapPos(r.to,-1);fromviewport.from&&(this.fragments=cutFragments(this.fragments,from,to),this.skipped.splice(i--,1))}return this.skipped.length>=startLen?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(from,to){this.skipped.push({from,to})}static getSkippingParser(until){return new class extends Parser{createParse(input,fragments,ranges){let from=ranges[0].from,to=ranges[ranges.length-1].to;return{parsedPos:from,advance(){let cx=currentContext;if(cx){for(let r of ranges)cx.tempSkipped.push(r);until&&(cx.scheduleOn=cx.scheduleOn?Promise.all([cx.scheduleOn,until]):until)}return this.parsedPos=to,new Tree(NodeType.none,[],[],to-from)},stoppedAt:null,stopAt(){}}}}}isDone(upto){upto=Math.min(upto,this.state.doc.length);let frags=this.fragments;return this.treeLen>=upto&&frags.length&&frags[0].from==0&&frags[0].to>=upto}static get(){return currentContext}};__name2(_ParseContext,"ParseContext");let ParseContext=_ParseContext;function cutFragments(fragments,from,to){return TreeFragment.applyChanges(fragments,[{fromA:from,toA:to,fromB:from,toB:to}])}__name(cutFragments,"cutFragments"),__name2(cutFragments,"cutFragments");const _LanguageState=class _LanguageState2{static{__name(this,"_LanguageState")}constructor(context){this.context=context,this.tree=context.tree}apply(tr){if(!tr.docChanged&&this.tree==this.context.tree)return this;let newCx=this.context.changes(tr.changes,tr.state),upto=this.context.treeLen==tr.startState.doc.length?void 0:Math.max(tr.changes.mapPos(this.context.treeLen),newCx.viewport.to);return newCx.work(20,upto)||newCx.takeTree(),new _LanguageState2(newCx)}static init(state){let vpTo=Math.min(3e3,state.doc.length),parseState=ParseContext.create(state.facet(language).parser,state,{from:0,to:vpTo});return parseState.work(20,vpTo)||parseState.takeTree(),new _LanguageState2(parseState)}};__name2(_LanguageState,"LanguageState");let LanguageState=_LanguageState;Language.state=StateField.define({create:LanguageState.init,update(value,tr){for(let e of tr.effects)if(e.is(Language.setState))return e.value;return tr.startState.facet(language)!=tr.state.facet(language)?LanguageState.init(tr.state):value.apply(tr)}});let requestIdle=__name2(callback=>{let timeout=setTimeout(()=>callback(),500);return()=>clearTimeout(timeout)},"requestIdle");typeof requestIdleCallback<"u"&&(requestIdle=__name2(callback=>{let idle=-1,timeout=setTimeout(()=>{idle=requestIdleCallback(callback,{timeout:500-100})},100);return()=>idle<0?clearTimeout(timeout):cancelIdleCallback(idle)},"requestIdle"));const isInputPending=typeof navigator<"u"&&(!((_a$1=navigator.scheduling)===null||_a$1===void 0)&&_a$1.isInputPending)?()=>navigator.scheduling.isInputPending():null,parseWorker=ViewPlugin.fromClass((_c=class{static{__name(this,"_c")}constructor(view){this.view=view,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(update){let cx=this.view.state.field(Language.state).context;(cx.updateViewport(update.view.viewport)||this.view.viewport.to>cx.treeLen)&&this.scheduleWork(),update.docChanged&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(cx)}scheduleWork(){if(this.working)return;let{state}=this.view,field=state.field(Language.state);(field.tree!=field.context.tree||!field.context.isDone(state.doc.length))&&(this.working=requestIdle(this.work))}work(deadline){this.working=null;let now2=Date.now();if(this.chunkEndvpTo+1e3,done=field.context.work(()=>isInputPending&&isInputPending()||Date.now()>endTime,vpTo+(viewportFirst?0:1e5));this.chunkBudget-=Date.now()-now2,(done||this.chunkBudget<=0)&&(field.context.takeTree(),this.view.dispatch({effects:Language.setState.of(new LanguageState(field.context))})),this.chunkBudget>0&&!(done&&!viewportFirst)&&this.scheduleWork(),this.checkAsyncSchedule(field.context)}checkAsyncSchedule(cx){cx.scheduleOn&&(this.workScheduled++,cx.scheduleOn.then(()=>this.scheduleWork()).catch(err=>logException(this.view.state,err)).then(()=>this.workScheduled--),cx.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},__name2(_c,"ParseWorker"),_c),{eventHandlers:{focus(){this.scheduleWork()}}}),language=Facet.define({combine(languages){return languages.length?languages[0]:null},enables:language2=>[Language.state,parseWorker,EditorView.contentAttributes.compute([language2],state=>{let lang=state.facet(language2);return lang&&lang.name?{"data-language":lang.name}:{}})]}),_LanguageSupport=class{static{__name(this,"_LanguageSupport")}constructor(language2,support=[]){this.language=language2,this.support=support,this.extension=[language2,support]}};__name2(_LanguageSupport,"LanguageSupport");let LanguageSupport=_LanguageSupport;const indentService=Facet.define(),indentUnit=Facet.define({combine:values=>{if(!values.length)return" ";let unit=values[0];if(!unit||/\S/.test(unit)||Array.from(unit).some(e=>e!=unit[0]))throw new Error("Invalid indent unit: "+JSON.stringify(values[0]));return unit}});function getIndentUnit(state){let unit=state.facet(indentUnit);return unit.charCodeAt(0)==9?state.tabSize*unit.length:unit.length}__name(getIndentUnit,"getIndentUnit"),__name2(getIndentUnit,"getIndentUnit");function indentString(state,cols){let result="",ts=state.tabSize,ch=state.facet(indentUnit)[0];if(ch==" "){for(;cols>=ts;)result+=" ",cols-=ts;ch=" "}for(let i=0;i=line.from&&simulateBreak<=line.to?simulateDoubleBreak&&simulateBreak==pos?{text:"",from:pos}:(bias<0?simulateBreak-1&&(result+=override-this.countColumn(text,text.search(/\S|$/))),result}countColumn(line,pos=line.length){return countColumn(line,this.state.tabSize,pos)}lineIndent(pos,bias=1){let{text,from}=this.lineAt(pos,bias),override=this.options.overrideIndentation;if(override){let overriden=override(from);if(overriden>-1)return overriden}return this.countColumn(text,text.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}};__name2(_IndentContext,"IndentContext");let IndentContext=_IndentContext;const indentNodeProp=new NodeProp;function syntaxIndentation(cx,ast,pos){return indentFrom(ast.resolveInner(pos).enterUnfinishedNodesBefore(pos),pos,cx)}__name(syntaxIndentation,"syntaxIndentation"),__name2(syntaxIndentation,"syntaxIndentation");function ignoreClosed(cx){return cx.pos==cx.options.simulateBreak&&cx.options.simulateDoubleBreak}__name(ignoreClosed,"ignoreClosed"),__name2(ignoreClosed,"ignoreClosed");function indentStrategy(tree){let strategy=tree.type.prop(indentNodeProp);if(strategy)return strategy;let first=tree.firstChild,close;if(first&&(close=first.type.prop(NodeProp.closedBy))){let last2=tree.lastChild,closed=last2&&close.indexOf(last2.name)>-1;return cx=>delimitedStrategy(cx,!0,1,void 0,closed&&!ignoreClosed(cx)?last2.from:void 0)}return tree.parent==null?topIndent:null}__name(indentStrategy,"indentStrategy"),__name2(indentStrategy,"indentStrategy");function indentFrom(node,pos,base2){for(;node;node=node.parent){let strategy=indentStrategy(node);if(strategy)return strategy(TreeIndentContext.create(base2,pos,node))}return null}__name(indentFrom,"indentFrom"),__name2(indentFrom,"indentFrom");function topIndent(){return 0}__name(topIndent,"topIndent"),__name2(topIndent,"topIndent");const _TreeIndentContext=class _TreeIndentContext2 extends IndentContext{static{__name(this,"_TreeIndentContext")}constructor(base2,pos,node){super(base2.state,base2.options),this.base=base2,this.pos=pos,this.node=node}static create(base2,pos,node){return new _TreeIndentContext2(base2,pos,node)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(node){let line=this.state.doc.lineAt(node.from);for(;;){let atBreak=node.resolve(line.from);for(;atBreak.parent&&atBreak.parent.from==atBreak.from;)atBreak=atBreak.parent;if(isParent(atBreak,node))break;line=this.state.doc.lineAt(atBreak.from)}return this.lineIndent(line.from)}continue(){let parent=this.node.parent;return parent?indentFrom(parent,this.pos,this.base):0}};__name2(_TreeIndentContext,"TreeIndentContext");let TreeIndentContext=_TreeIndentContext;function isParent(parent,of){for(let cur2=of;cur2;cur2=cur2.parent)if(parent==cur2)return!0;return!1}__name(isParent,"isParent"),__name2(isParent,"isParent");function bracketedAligned(context){let tree=context.node,openToken=tree.childAfter(tree.from),last2=tree.lastChild;if(!openToken)return null;let sim=context.options.simulateBreak,openLine=context.state.doc.lineAt(openToken.from),lineEnd=sim==null||sim<=openLine.from?openLine.to:Math.min(openLine.to,sim);for(let pos=openToken.to;;){let next=tree.childAfter(pos);if(!next||next==last2)return null;if(!next.type.isSkipped)return next.from{let matchExcept=except&&except.test(context.textAfter);return context.baseIndent+(matchExcept?0:units*context.unit)}}__name(continuedIndent,"continuedIndent"),__name2(continuedIndent,"continuedIndent");const DontIndentBeyond=200;function indentOnInput(){return EditorState.transactionFilter.of(tr=>{if(!tr.docChanged||!tr.isUserEvent("input.type")&&!tr.isUserEvent("input.complete"))return tr;let rules=tr.startState.languageDataAt("indentOnInput",tr.startState.selection.main.head);if(!rules.length)return tr;let doc2=tr.newDoc,{head}=tr.newSelection.main,line=doc2.lineAt(head);if(head>line.from+DontIndentBeyond)return tr;let lineStart=doc2.sliceString(line.from,head);if(!rules.some(r=>r.test(lineStart)))return tr;let{state}=tr,last2=-1,changes=[];for(let{head:head2}of state.selection.ranges){let line2=state.doc.lineAt(head2);if(line2.from==last2)continue;last2=line2.from;let indent=getIndentation(state,line2.from);if(indent==null)continue;let cur2=/^\s*/.exec(line2.text)[0],norm=indentString(state,indent);cur2!=norm&&changes.push({from:line2.from,to:line2.from+cur2.length,insert:norm})}return changes.length?[tr,{changes,sequential:!0}]:tr})}__name(indentOnInput,"indentOnInput"),__name2(indentOnInput,"indentOnInput");const foldService=Facet.define(),foldNodeProp=new NodeProp;function foldInside(node){let first=node.firstChild,last2=node.lastChild;return first&&first.toend)continue;if(found&&cur2.from=start&&value.to>end&&(found=value)}}return found}__name(syntaxFolding,"syntaxFolding"),__name2(syntaxFolding,"syntaxFolding");function isUnfinished(node){let ch=node.lastChild;return ch&&ch.to==node.to&&ch.type.isError}__name(isUnfinished,"isUnfinished"),__name2(isUnfinished,"isUnfinished");function foldable(state,lineStart,lineEnd){for(let service of state.facet(foldService)){let result=service(state,lineStart,lineEnd);if(result)return result}return syntaxFolding(state,lineStart,lineEnd)}__name(foldable,"foldable"),__name2(foldable,"foldable");function mapRange(range,mapping){let from=mapping.mapPos(range.from,1),to=mapping.mapPos(range.to,-1);return from>=to?void 0:{from,to}}__name(mapRange,"mapRange"),__name2(mapRange,"mapRange");const foldEffect=StateEffect.define({map:mapRange}),unfoldEffect=StateEffect.define({map:mapRange});function selectedLines(view){let lines=[];for(let{head}of view.state.selection.ranges)lines.some(l2=>l2.from<=head&&l2.to>=head)||lines.push(view.lineBlockAt(head));return lines}__name(selectedLines,"selectedLines"),__name2(selectedLines,"selectedLines");const foldState=StateField.define({create(){return Decoration.none},update(folded,tr){folded=folded.map(tr.changes);for(let e of tr.effects)e.is(foldEffect)&&!foldExists(folded,e.value.from,e.value.to)?folded=folded.update({add:[foldWidget.range(e.value.from,e.value.to)]}):e.is(unfoldEffect)&&(folded=folded.update({filter:(from,to)=>e.value.from!=from||e.value.to!=to,filterFrom:e.value.from,filterTo:e.value.to}));if(tr.selection){let onSelection=!1,{head}=tr.selection.main;folded.between(head,head,(a,b)=>{ahead&&(onSelection=!0)}),onSelection&&(folded=folded.update({filterFrom:head,filterTo:head,filter:(a,b)=>b<=head||a>=head}))}return folded},provide:f=>EditorView.decorations.from(f),toJSON(folded,state){let ranges=[];return folded.between(0,state.doc.length,(from,to)=>{ranges.push(from,to)}),ranges},fromJSON(value){if(!Array.isArray(value)||value.length%2)throw new RangeError("Invalid JSON for fold state");let ranges=[];for(let i=0;i{(!found||found.from>from2)&&(found={from:from2,to:to2})}),found}__name(findFold,"findFold"),__name2(findFold,"findFold");function foldExists(folded,from,to){let found=!1;return folded.between(from,from,(a,b)=>{a==from&&b==to&&(found=!0)}),found}__name(foldExists,"foldExists"),__name2(foldExists,"foldExists");function maybeEnable(state,other){return state.field(foldState,!1)?other:other.concat(StateEffect.appendConfig.of(codeFolding()))}__name(maybeEnable,"maybeEnable"),__name2(maybeEnable,"maybeEnable");const foldCode=__name2(view=>{for(let line of selectedLines(view)){let range=foldable(view.state,line.from,line.to);if(range)return view.dispatch({effects:maybeEnable(view.state,[foldEffect.of(range),announceFold(view,range)])}),!0}return!1},"foldCode"),unfoldCode=__name2(view=>{if(!view.state.field(foldState,!1))return!1;let effects=[];for(let line of selectedLines(view)){let folded=findFold(view.state,line.from,line.to);folded&&effects.push(unfoldEffect.of(folded),announceFold(view,folded,!1))}return effects.length&&view.dispatch({effects}),effects.length>0},"unfoldCode");function announceFold(view,range,fold=!0){let lineFrom=view.state.doc.lineAt(range.from).number,lineTo=view.state.doc.lineAt(range.to).number;return EditorView.announce.of(`${view.state.phrase(fold?"Folded lines":"Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`)}__name(announceFold,"announceFold"),__name2(announceFold,"announceFold");const foldAll=__name2(view=>{let{state}=view,effects=[];for(let pos=0;pos{let field=view.state.field(foldState,!1);if(!field||!field.size)return!1;let effects=[];return field.between(0,view.state.doc.length,(from,to)=>{effects.push(unfoldEffect.of({from,to}))}),view.dispatch({effects}),!0},"unfoldAll"),foldKeymap=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:foldCode},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:unfoldCode},{key:"Ctrl-Alt-[",run:foldAll},{key:"Ctrl-Alt-]",run:unfoldAll}],defaultConfig={placeholderDOM:null,placeholderText:"\u2026"},foldConfig=Facet.define({combine(values){return combineConfig(values,defaultConfig)}});function codeFolding(config2){let result=[foldState,baseTheme$1$1];return config2&&result.push(foldConfig.of(config2)),result}__name(codeFolding,"codeFolding"),__name2(codeFolding,"codeFolding");const foldWidget=Decoration.replace({widget:new class extends WidgetType{toDOM(view){let{state}=view,conf=state.facet(foldConfig),onclick=__name2(event=>{let line=view.lineBlockAt(view.posAtDOM(event.target)),folded=findFold(view.state,line.from,line.to);folded&&view.dispatch({effects:unfoldEffect.of(folded)}),event.preventDefault()},"onclick");if(conf.placeholderDOM)return conf.placeholderDOM(view,onclick);let element=document.createElement("span");return element.textContent=conf.placeholderText,element.setAttribute("aria-label",state.phrase("folded code")),element.title=state.phrase("unfold"),element.className="cm-foldPlaceholder",element.onclick=onclick,element}}}),foldGutterDefaults={openText:"\u2304",closedText:"\u203A",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1},_FoldMarker=class extends GutterMarker{static{__name(this,"_FoldMarker")}constructor(config2,open){super(),this.config=config2,this.open=open}eq(other){return this.config==other.config&&this.open==other.open}toDOM(view){if(this.config.markerDOM)return this.config.markerDOM(this.open);let span=document.createElement("span");return span.textContent=this.open?this.config.openText:this.config.closedText,span.title=view.state.phrase(this.open?"Fold line":"Unfold line"),span}};__name2(_FoldMarker,"FoldMarker");let FoldMarker=_FoldMarker;function foldGutter(config2={}){let fullConfig=Object.assign(Object.assign({},foldGutterDefaults),config2),canFold=new FoldMarker(fullConfig,!0),canUnfold=new FoldMarker(fullConfig,!1),markers=ViewPlugin.fromClass(class{constructor(view){this.from=view.viewport.from,this.markers=this.buildMarkers(view)}update(update){(update.docChanged||update.viewportChanged||update.startState.facet(language)!=update.state.facet(language)||update.startState.field(foldState,!1)!=update.state.field(foldState,!1)||syntaxTree(update.startState)!=syntaxTree(update.state)||fullConfig.foldingChanged(update))&&(this.markers=this.buildMarkers(update.view))}buildMarkers(view){let builder=new RangeSetBuilder;for(let line of view.viewportLineBlocks){let mark=findFold(view.state,line.from,line.to)?canUnfold:foldable(view.state,line.from,line.to)?canFold:null;mark&&builder.add(line.from,line.from,mark)}return builder.finish()}}),{domEventHandlers}=fullConfig;return[markers,gutter({class:"cm-foldGutter",markers(view){var _a3;return((_a3=view.plugin(markers))===null||_a3===void 0?void 0:_a3.markers)||RangeSet.empty},initialSpacer(){return new FoldMarker(fullConfig,!1)},domEventHandlers:Object.assign(Object.assign({},domEventHandlers),{click:(view,line,event)=>{if(domEventHandlers.click&&domEventHandlers.click(view,line,event))return!0;let folded=findFold(view.state,line.from,line.to);if(folded)return view.dispatch({effects:unfoldEffect.of(folded)}),!0;let range=foldable(view.state,line.from,line.to);return range?(view.dispatch({effects:foldEffect.of(range)}),!0):!1}})}),codeFolding()]}__name(foldGutter,"foldGutter"),__name2(foldGutter,"foldGutter");const baseTheme$1$1=EditorView.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}}),_HighlightStyle=class _HighlightStyle2{static{__name(this,"_HighlightStyle")}constructor(specs,options){this.specs=specs;let modSpec;function def(spec){let cls=StyleModule.newName();return(modSpec||(modSpec=Object.create(null)))["."+cls]=spec,cls}__name(def,"def"),__name2(def,"def");const all=typeof options.all=="string"?options.all:options.all?def(options.all):void 0,scopeOpt=options.scope;this.scope=scopeOpt instanceof Language?type=>type.prop(languageDataProp)==scopeOpt.data:scopeOpt?type=>type==scopeOpt:void 0,this.style=tagHighlighter(specs.map(style=>({tag:style.tag,class:style.class||def(Object.assign({},style,{tag:null}))})),{all}).style,this.module=modSpec?new StyleModule(modSpec):null,this.themeType=options.themeType}static define(specs,options){return new _HighlightStyle2(specs,options||{})}};__name2(_HighlightStyle,"HighlightStyle");let HighlightStyle=_HighlightStyle;const highlighterFacet=Facet.define(),fallbackHighlighter=Facet.define({combine(values){return values.length?[values[0]]:null}});function getHighlighters(state){let main=state.facet(highlighterFacet);return main.length?main:state.facet(fallbackHighlighter)}__name(getHighlighters,"getHighlighters"),__name2(getHighlighters,"getHighlighters");function syntaxHighlighting(highlighter,options){let ext=[treeHighlighter],themeType;return highlighter instanceof HighlightStyle&&(highlighter.module&&ext.push(EditorView.styleModule.of(highlighter.module)),themeType=highlighter.themeType),options?.fallback?ext.push(fallbackHighlighter.of(highlighter)):themeType?ext.push(highlighterFacet.computeN([EditorView.darkTheme],state=>state.facet(EditorView.darkTheme)==(themeType=="dark")?[highlighter]:[])):ext.push(highlighterFacet.of(highlighter)),ext}__name(syntaxHighlighting,"syntaxHighlighting"),__name2(syntaxHighlighting,"syntaxHighlighting");const _TreeHighlighter=class{static{__name(this,"_TreeHighlighter")}constructor(view){this.markCache=Object.create(null),this.tree=syntaxTree(view.state),this.decorations=this.buildDeco(view,getHighlighters(view.state))}update(update){let tree=syntaxTree(update.state),highlighters=getHighlighters(update.state),styleChange=highlighters!=getHighlighters(update.startState);tree.length{builder.add(from2,to2,this.markCache[style]||(this.markCache[style]=Decoration.mark({class:style})))},from,to);return builder.finish()}};__name2(_TreeHighlighter,"TreeHighlighter");let TreeHighlighter=_TreeHighlighter;const treeHighlighter=Prec.high(ViewPlugin.fromClass(TreeHighlighter,{decorations:v=>v.decorations})),defaultHighlightStyle=HighlightStyle.define([{tag:tags.meta,color:"#404740"},{tag:tags.link,textDecoration:"underline"},{tag:tags.heading,textDecoration:"underline",fontWeight:"bold"},{tag:tags.emphasis,fontStyle:"italic"},{tag:tags.strong,fontWeight:"bold"},{tag:tags.strikethrough,textDecoration:"line-through"},{tag:tags.keyword,color:"#708"},{tag:[tags.atom,tags.bool,tags.url,tags.contentSeparator,tags.labelName],color:"#219"},{tag:[tags.literal,tags.inserted],color:"#164"},{tag:[tags.string,tags.deleted],color:"#a11"},{tag:[tags.regexp,tags.escape,tags.special(tags.string)],color:"#e40"},{tag:tags.definition(tags.variableName),color:"#00f"},{tag:tags.local(tags.variableName),color:"#30a"},{tag:[tags.typeName,tags.namespace],color:"#085"},{tag:tags.className,color:"#167"},{tag:[tags.special(tags.variableName),tags.macroName],color:"#256"},{tag:tags.definition(tags.propertyName),color:"#00c"},{tag:tags.comment,color:"#940"},{tag:tags.invalid,color:"#f00"}]),baseTheme$4=EditorView.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),DefaultScanDist=1e4,DefaultBrackets="()[]{}",bracketMatchingConfig=Facet.define({combine(configs){return combineConfig(configs,{afterCursor:!0,brackets:DefaultBrackets,maxScanDistance:DefaultScanDist,renderMatch:defaultRenderMatch})}}),matchingMark=Decoration.mark({class:"cm-matchingBracket"}),nonmatchingMark=Decoration.mark({class:"cm-nonmatchingBracket"});function defaultRenderMatch(match2){let decorations2=[],mark=match2.matched?matchingMark:nonmatchingMark;return decorations2.push(mark.range(match2.start.from,match2.start.to)),match2.end&&decorations2.push(mark.range(match2.end.from,match2.end.to)),decorations2}__name(defaultRenderMatch,"defaultRenderMatch"),__name2(defaultRenderMatch,"defaultRenderMatch");const bracketMatchingState=StateField.define({create(){return Decoration.none},update(deco,tr){if(!tr.docChanged&&!tr.selection)return deco;let decorations2=[],config2=tr.state.facet(bracketMatchingConfig);for(let range of tr.state.selection.ranges){if(!range.empty)continue;let match2=matchBrackets(tr.state,range.head,-1,config2)||range.head>0&&matchBrackets(tr.state,range.head-1,1,config2)||config2.afterCursor&&(matchBrackets(tr.state,range.head,1,config2)||range.headEditorView.decorations.from(f)}),bracketMatchingUnique=[bracketMatchingState,baseTheme$4];function bracketMatching(config2={}){return[bracketMatchingConfig.of(config2),bracketMatchingUnique]}__name(bracketMatching,"bracketMatching"),__name2(bracketMatching,"bracketMatching");const bracketMatchingHandle=new NodeProp;function matchingNodes(node,dir,brackets){let byProp=node.prop(dir<0?NodeProp.openedBy:NodeProp.closedBy);if(byProp)return byProp;if(node.name.length==1){let index2=brackets.indexOf(node.name);if(index2>-1&&index2%2==(dir<0?1:0))return[brackets[index2+dir]]}return null}__name(matchingNodes,"matchingNodes"),__name2(matchingNodes,"matchingNodes");function findHandle(node){let hasHandle=node.type.prop(bracketMatchingHandle);return hasHandle?hasHandle(node.node):node}__name(findHandle,"findHandle"),__name2(findHandle,"findHandle");function matchBrackets(state,pos,dir,config2={}){let maxScanDistance=config2.maxScanDistance||DefaultScanDist,brackets=config2.brackets||DefaultBrackets,tree=syntaxTree(state),node=tree.resolveInner(pos,dir);for(let cur2=node;cur2;cur2=cur2.parent){let matches2=matchingNodes(cur2.type,dir,brackets);if(matches2&&cur2.from0?pos>=handle.from&&poshandle.from&&pos<=handle.to))return matchMarkedBrackets(state,pos,dir,cur2,handle,matches2,brackets)}}return matchPlainBrackets(state,pos,dir,tree,node.type,maxScanDistance,brackets)}__name(matchBrackets,"matchBrackets"),__name2(matchBrackets,"matchBrackets");function matchMarkedBrackets(_state,_pos,dir,token,handle,matching,brackets){let parent=token.parent,firstToken={from:handle.from,to:handle.to},depth=0,cursor=parent?.cursor();if(cursor&&(dir<0?cursor.childBefore(token.from):cursor.childAfter(token.to)))do if(dir<0?cursor.to<=token.from:cursor.from>=token.to){if(depth==0&&matching.indexOf(cursor.type.name)>-1&&cursor.from0)return null;let startToken={from:dir<0?pos-1:pos,to:dir>0?pos+1:pos},iter=state.doc.iterRange(pos,dir>0?state.doc.length:0),depth=0;for(let distance=0;!iter.next().done&&distance<=maxScanDistance;){let text=iter.value;dir<0&&(distance+=text.length);let basePos=pos+distance*dir;for(let pos2=dir>0?0:text.length-1,end=dir>0?text.length:-1;pos2!=end;pos2+=dir){let found=brackets.indexOf(text[pos2]);if(!(found<0||tree.resolveInner(basePos+pos2,1).type!=tokenType))if(found%2==0==dir>0)depth++;else{if(depth==1)return{start:startToken,end:{from:basePos+pos2,to:basePos+pos2+1},matched:found>>1==bracket2>>1};depth--}}dir>0&&(distance+=text.length)}return iter.done?{start:startToken,matched:!1}:null}__name(matchPlainBrackets,"matchPlainBrackets"),__name2(matchPlainBrackets,"matchPlainBrackets");const noTokens=Object.create(null),typeArray=[NodeType.none],warned=[],defaultTable=Object.create(null);for(let[legacyName,name2]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])defaultTable[legacyName]=createTokenType(noTokens,name2);function warnForPart(part,msg){warned.indexOf(part)>-1||(warned.push(part),console.warn(msg))}__name(warnForPart,"warnForPart"),__name2(warnForPart,"warnForPart");function createTokenType(extra,tagStr){let tag=null;for(let part of tagStr.split(".")){let value=extra[part]||tags[part];value?typeof value=="function"?tag?tag=value(tag):warnForPart(part,`Modifier ${part} used at start of tag`):tag?warnForPart(part,`Tag ${part} used as modifier`):tag=value:warnForPart(part,`Unknown highlighting tag ${part}`)}if(!tag)return 0;let name2=tagStr.replace(/ /g,"_"),type=NodeType.define({id:typeArray.length,name:name2,props:[styleTags({[name2]:tag})]});return typeArray.push(type),type.id}__name(createTokenType,"createTokenType"),__name2(createTokenType,"createTokenType");const _CompletionContext=class{static{__name(this,"_CompletionContext")}constructor(state,pos,explicit){this.state=state,this.pos=pos,this.explicit=explicit,this.abortListeners=[]}tokenBefore(types2){let token=syntaxTree(this.state).resolveInner(this.pos,-1);for(;token&&types2.indexOf(token.name)<0;)token=token.parent;return token?{from:token.from,to:this.pos,text:this.state.sliceDoc(token.from,this.pos),type:token.type}:null}matchBefore(expr){let line=this.state.doc.lineAt(this.pos),start=Math.max(line.from,this.pos-250),str=line.text.slice(start-line.from,this.pos-line.from),found=str.search(ensureAnchor(expr,!1));return found<0?null:{from:start+found,to:this.pos,text:str.slice(found)}}get aborted(){return this.abortListeners==null}addEventListener(type,listener){type=="abort"&&this.abortListeners&&this.abortListeners.push(listener)}};__name2(_CompletionContext,"CompletionContext");let CompletionContext=_CompletionContext;function toSet(chars){let flat=Object.keys(chars).join(""),words=/\w/.test(flat);return words&&(flat=flat.replace(/\w/g,"")),`[${words?"\\w":""}${flat.replace(/[^\w\s]/g,"\\$&")}]`}__name(toSet,"toSet"),__name2(toSet,"toSet");function prefixMatch(options){let first=Object.create(null),rest=Object.create(null);for(let{label}of options){first[label[0]]=!0;for(let i=1;itypeof o=="string"?{label:o}:o),[validFor,match2]=options.every(o=>/^\w+$/.test(o.label))?[/\w*$/,/\w+$/]:prefixMatch(options);return context=>{let token=context.matchBefore(match2);return token||context.explicit?{from:token?token.from:context.pos,options,validFor}:null}}__name(completeFromList,"completeFromList"),__name2(completeFromList,"completeFromList");const _Option=class{static{__name(this,"_Option")}constructor(completion,source,match2,score2){this.completion=completion,this.source=source,this.match=match2,this.score=score2}};__name2(_Option,"Option");let Option=_Option;function cur(state){return state.selection.main.from}__name(cur,"cur"),__name2(cur,"cur");function ensureAnchor(expr,start){var _a3;let{source}=expr,addStart=start&&source[0]!="^",addEnd=source[source.length-1]!="$";return!addStart&&!addEnd?expr:new RegExp(`${addStart?"^":""}(?:${source})${addEnd?"$":""}`,(_a3=expr.flags)!==null&&_a3!==void 0?_a3:expr.ignoreCase?"i":"")}__name(ensureAnchor,"ensureAnchor"),__name2(ensureAnchor,"ensureAnchor");const pickedCompletion=Annotation.define();function insertCompletionText(state,text,from,to){let{main}=state.selection,fromOff=from-main.from,toOff=to-main.from;return Object.assign(Object.assign({},state.changeByRange(range=>range!=main&&from!=to&&state.sliceDoc(range.from+fromOff,range.from+toOff)!=state.sliceDoc(from,to)?{range}:{changes:{from:range.from+fromOff,to:to==main.from?range.to:range.from+toOff,insert:text},range:EditorSelection.cursor(range.from+fromOff+text.length)})),{scrollIntoView:!0,userEvent:"input.complete"})}__name(insertCompletionText,"insertCompletionText"),__name2(insertCompletionText,"insertCompletionText");const SourceCache=new WeakMap;function asSource(source){if(!Array.isArray(source))return source;let known=SourceCache.get(source);return known||SourceCache.set(source,known=completeFromList(source)),known}__name(asSource,"asSource"),__name2(asSource,"asSource");const startCompletionEffect=StateEffect.define(),closeCompletionEffect=StateEffect.define(),_FuzzyMatcher=class{static{__name(this,"_FuzzyMatcher")}constructor(pattern){this.pattern=pattern,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let p=0;p=48&&next<=57||next>=97&&next<=122?2:next>=65&&next<=90?1:0:(ch=fromCodePoint(next))!=ch.toLowerCase()?1:ch!=ch.toUpperCase()?2:0;(!i||type==1&&hasLower||prevType==0&&type!=0)&&(chars[byWordTo]==next||folded[byWordTo]==next&&(byWordFolded=!0)?byWord[byWordTo++]=i:byWord.length&&(wordAdjacent=!1)),prevType=type,i+=codePointSize(next)}return byWordTo==len&&byWord[0]==0&&wordAdjacent?this.result(-100+(byWordFolded?-200:0),byWord,word):adjacentTo==len&&adjacentStart==0?this.ret(-200-word.length+(adjacentEnd==word.length?0:-100),[0,adjacentEnd]):direct>-1?this.ret(-700-word.length,[direct,direct+this.pattern.length]):adjacentTo==len?this.ret(-200+-700-word.length,[adjacentStart,adjacentEnd]):byWordTo==len?this.result(-100+(byWordFolded?-200:0)+-700+(wordAdjacent?0:-1100),byWord,word):chars.length==2?!1:this.result((any[0]?-700:0)+-200+-1100,any,word)}result(score2,positions,word){let result=[],i=0;for(let pos of positions){let to=pos+(this.astral?codePointSize(codePointAt(word,pos)):1);i&&result[i-1]==pos?result[i-1]=to:(result[i++]=pos,result[i++]=to)}return this.ret(score2-word.length,result)}};__name2(_FuzzyMatcher,"FuzzyMatcher");let FuzzyMatcher=_FuzzyMatcher;const completionConfig=Facet.define({combine(configs){return combineConfig(configs,{activateOnTyping:!0,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:defaultPositionInfo,compareCompletions:(a,b)=>a.label.localeCompare(b.label),interactionDelay:75},{defaultKeymap:(a,b)=>a&&b,closeOnBlur:(a,b)=>a&&b,icons:(a,b)=>a&&b,tooltipClass:(a,b)=>c=>joinClass(a(c),b(c)),optionClass:(a,b)=>c=>joinClass(a(c),b(c)),addToOptions:(a,b)=>a.concat(b)})}});function joinClass(a,b){return a?b?a+" "+b:a:b}__name(joinClass,"joinClass"),__name2(joinClass,"joinClass");function defaultPositionInfo(view,list,option2,info,space,tooltip){let rtl=view.textDirection==Direction.RTL,left=rtl,narrow=!1,side="top",offset2,maxWidth,spaceLeft=list.left-space.left,spaceRight=space.right-list.right,infoWidth=info.right-info.left,infoHeight=info.bottom-info.top;if(left&&spaceLeft=infoHeight||spaceBelow>list.top?offset2=option2.bottom-list.top:(side="bottom",offset2=list.bottom-option2.top)}let scaleY=(list.bottom-list.top)/tooltip.offsetHeight,scaleX=(list.right-list.left)/tooltip.offsetWidth;return{style:`${side}: ${offset2/scaleY}px; max-width: ${maxWidth/scaleX}px`,class:"cm-completionInfo-"+(narrow?rtl?"left-narrow":"right-narrow":left?"left":"right")}}__name(defaultPositionInfo,"defaultPositionInfo"),__name2(defaultPositionInfo,"defaultPositionInfo");function optionContent(config2){let content2=config2.addToOptions.slice();return config2.icons&&content2.push({render(completion){let icon=document.createElement("div");return icon.classList.add("cm-completionIcon"),completion.type&&icon.classList.add(...completion.type.split(/\s+/g).map(cls=>"cm-completionIcon-"+cls)),icon.setAttribute("aria-hidden","true"),icon},position:20}),content2.push({render(completion,_s,match2){let labelElt=document.createElement("span");labelElt.className="cm-completionLabel";let label=completion.displayLabel||completion.label,off2=0;for(let j=0;joff2&&labelElt.appendChild(document.createTextNode(label.slice(off2,from)));let span=labelElt.appendChild(document.createElement("span"));span.appendChild(document.createTextNode(label.slice(from,to))),span.className="cm-completionMatchedText",off2=to}return off2a.position-b.position).map(a=>a.render)}__name(optionContent,"optionContent"),__name2(optionContent,"optionContent");function rangeAroundSelected(total,selected,max){if(total<=max)return{from:0,to:total};if(selected<0&&(selected=0),selected<=total>>1){let off3=Math.floor(selected/max);return{from:off3*max,to:(off3+1)*max}}let off2=Math.floor((total-selected)/max);return{from:total-(off2+1)*max,to:total-off2*max}}__name(rangeAroundSelected,"rangeAroundSelected"),__name2(rangeAroundSelected,"rangeAroundSelected");const _CompletionTooltip=class{static{__name(this,"_CompletionTooltip")}constructor(view,stateField,applyCompletion2){this.view=view,this.stateField=stateField,this.applyCompletion=applyCompletion2,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:pos=>this.placeInfo(pos),key:this},this.space=null,this.currentClass="";let cState=view.state.field(stateField),{options,selected}=cState.open,config2=view.state.facet(completionConfig);this.optionContent=optionContent(config2),this.optionClass=config2.optionClass,this.tooltipClass=config2.tooltipClass,this.range=rangeAroundSelected(options.length,selected,config2.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(view.state),this.dom.addEventListener("mousedown",e=>{for(let dom=e.target,match2;dom&&dom!=this.dom;dom=dom.parentNode)if(dom.nodeName=="LI"&&(match2=/-(\d+)$/.exec(dom.id))&&+match2[1]{let state=view.state.field(this.stateField,!1);state&&state.tooltip&&view.state.facet(completionConfig).closeOnBlur&&e.relatedTarget!=view.contentDOM&&view.dispatch({effects:closeCompletionEffect.of(null)})}),this.list=this.dom.appendChild(this.createListBox(options,cState.id,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}mount(){this.updateSel()}update(update){var _a3,_b2,_c2;let cState=update.state.field(this.stateField),prevState=update.startState.field(this.stateField);this.updateTooltipClass(update.state),cState!=prevState&&(this.updateSel(),((_a3=cState.open)===null||_a3===void 0?void 0:_a3.disabled)!=((_b2=prevState.open)===null||_b2===void 0?void 0:_b2.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!(!((_c2=cState.open)===null||_c2===void 0)&&_c2.disabled)))}updateTooltipClass(state){let cls=this.tooltipClass(state);if(cls!=this.currentClass){for(let c of this.currentClass.split(" "))c&&this.dom.classList.remove(c);for(let c of cls.split(" "))c&&this.dom.classList.add(c);this.currentClass=cls}}positioned(space){this.space=space,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let cState=this.view.state.field(this.stateField),open=cState.open;if((open.selected>-1&&open.selected=this.range.to)&&(this.range=rangeAroundSelected(open.options.length,open.selected,this.view.state.facet(completionConfig).maxRenderedOptions),this.list.remove(),this.list=this.dom.appendChild(this.createListBox(open.options,cState.id,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})),this.updateSelectedOption(open.selected)){this.destroyInfo();let{completion}=open.options[open.selected],{info}=completion;if(!info)return;let infoResult=typeof info=="string"?document.createTextNode(info):info(completion);if(!infoResult)return;"then"in infoResult?infoResult.then(obj=>{obj&&this.view.state.field(this.stateField,!1)==cState&&this.addInfoPane(obj,completion)}).catch(e=>logException(this.view.state,e,"completion info")):this.addInfoPane(infoResult,completion)}}addInfoPane(content2,completion){this.destroyInfo();let wrap=this.info=document.createElement("div");if(wrap.className="cm-tooltip cm-completionInfo",content2.nodeType!=null)wrap.appendChild(content2),this.infoDestroy=null;else{let{dom,destroy:destroy2}=content2;wrap.appendChild(dom),this.infoDestroy=destroy2||null}this.dom.appendChild(wrap),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(selected){let set=null;for(let opt=this.list.firstChild,i=this.range.from;opt;opt=opt.nextSibling,i++)opt.nodeName!="LI"||!opt.id?i--:i==selected?opt.hasAttribute("aria-selected")||(opt.setAttribute("aria-selected","true"),set=opt):opt.hasAttribute("aria-selected")&&opt.removeAttribute("aria-selected");return set&&scrollIntoView(this.list,set),set}measureInfo(){let sel=this.dom.querySelector("[aria-selected]");if(!sel||!this.info)return null;let listRect=this.dom.getBoundingClientRect(),infoRect=this.info.getBoundingClientRect(),selRect=sel.getBoundingClientRect(),space=this.space;if(!space){let win=this.dom.ownerDocument.defaultView||window;space={left:0,top:0,right:win.innerWidth,bottom:win.innerHeight}}return selRect.top>Math.min(space.bottom,listRect.bottom)-10||selRect.bottomrange.from||range.from==0))if(curSection=name2,typeof section!="string"&§ion.header)ul.appendChild(section.header(section));else{let header=ul.appendChild(document.createElement("completion-section"));header.textContent=name2}}const li=ul.appendChild(document.createElement("li"));li.id=id+"-"+i,li.setAttribute("role","option");let cls=this.optionClass(completion);cls&&(li.className=cls);for(let source of this.optionContent){let node=source(completion,this.view.state,match2);node&&li.appendChild(node)}}return range.from&&ul.classList.add("cm-completionListIncompleteTop"),range.tonew CompletionTooltip(view,stateField,applyCompletion2)}__name(completionTooltip,"completionTooltip"),__name2(completionTooltip,"completionTooltip");function scrollIntoView(container,element){let parent=container.getBoundingClientRect(),self2=element.getBoundingClientRect(),scaleY=parent.height/container.offsetHeight;self2.topparent.bottom&&(container.scrollTop+=(self2.bottom-parent.bottom)/scaleY)}__name(scrollIntoView,"scrollIntoView"),__name2(scrollIntoView,"scrollIntoView");function score(option2){return(option2.boost||0)*100+(option2.apply?10:0)+(option2.info?5:0)+(option2.type?1:0)}__name(score,"score"),__name2(score,"score");function sortOptions(active,state){let options=[],sections=null,addOption=__name2(option2=>{options.push(option2);let{section}=option2.completion;if(section){sections||(sections=[]);let name2=typeof section=="string"?section:section.name;sections.some(s2=>s2.name==name2)||sections.push(typeof section=="string"?{name:name2}:section)}},"addOption");for(let a of active)if(a.hasResult()){let getMatch=a.result.getMatch;if(a.result.filter===!1)for(let option2 of a.result.options)addOption(new Option(option2,a.source,getMatch?getMatch(option2):[],1e9-options.length));else{let matcher=new FuzzyMatcher(state.sliceDoc(a.from,a.to));for(let option2 of a.result.options)if(matcher.match(option2.label)){let matched=option2.displayLabel?getMatch?getMatch(option2,matcher.matched):[]:matcher.matched;addOption(new Option(option2,a.source,matched,matcher.score+(option2.boost||0)))}}}if(sections){let sectionOrder=Object.create(null),pos=0,cmp=__name2((a,b)=>{var _a3,_b2;return((_a3=a.rank)!==null&&_a3!==void 0?_a3:1e9)-((_b2=b.rank)!==null&&_b2!==void 0?_b2:1e9)||(a.nameb.score-a.score||compare2(a.completion,b.completion))){let cur2=opt.completion;!prev||prev.label!=cur2.label||prev.detail!=cur2.detail||prev.type!=null&&cur2.type!=null&&prev.type!=cur2.type||prev.apply!=cur2.apply||prev.boost!=cur2.boost?result.push(opt):score(opt.completion)>score(prev)&&(result[result.length-1]=opt),prev=opt.completion}return result}__name(sortOptions,"sortOptions"),__name2(sortOptions,"sortOptions");const _CompletionDialog=class _CompletionDialog2{static{__name(this,"_CompletionDialog")}constructor(options,attrs,tooltip,timestamp,selected,disabled){this.options=options,this.attrs=attrs,this.tooltip=tooltip,this.timestamp=timestamp,this.selected=selected,this.disabled=disabled}setSelected(selected,id){return selected==this.selected||selected>=this.options.length?this:new _CompletionDialog2(this.options,makeAttrs(id,selected),this.tooltip,this.timestamp,selected,this.disabled)}static build(active,state,id,prev,conf){let options=sortOptions(active,state);if(!options.length)return prev&&active.some(a=>a.state==1)?new _CompletionDialog2(prev.options,prev.attrs,prev.tooltip,prev.timestamp,prev.selected,!0):null;let selected=state.facet(completionConfig).selectOnOpen?0:-1;if(prev&&prev.selected!=selected&&prev.selected!=-1){let selectedValue=prev.options[prev.selected].completion;for(let i=0;ib.hasResult()?Math.min(a,b.from):a,1e8),create:completionTooltip(completionState,applyCompletion),above:conf.aboveCursor},prev?prev.timestamp:Date.now(),selected,!1)}map(changes){return new _CompletionDialog2(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:changes.mapPos(this.tooltip.pos)}),this.timestamp,this.selected,this.disabled)}};__name2(_CompletionDialog,"CompletionDialog");let CompletionDialog=_CompletionDialog;const _CompletionState=class _CompletionState2{static{__name(this,"_CompletionState")}constructor(active,id,open){this.active=active,this.id=id,this.open=open}static start(){return new _CompletionState2(none$1,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(tr){let{state}=tr,conf=state.facet(completionConfig),active=(conf.override||state.languageDataAt("autocomplete",cur(state)).map(asSource)).map(source=>(this.active.find(s2=>s2.source==source)||new ActiveSource(source,this.active.some(a=>a.state!=0)?1:0)).update(tr,conf));active.length==this.active.length&&active.every((a,i)=>a==this.active[i])&&(active=this.active);let open=this.open;open&&tr.docChanged&&(open=open.map(tr.changes)),tr.selection||active.some(a=>a.hasResult()&&tr.changes.touchesRange(a.from,a.to))||!sameResults(active,this.active)?open=CompletionDialog.build(active,state,this.id,open,conf):open&&open.disabled&&!active.some(a=>a.state==1)&&(open=null),!open&&active.every(a=>a.state!=1)&&active.some(a=>a.hasResult())&&(active=active.map(a=>a.hasResult()?new ActiveSource(a.source,0):a));for(let effect of tr.effects)effect.is(setSelectedEffect)&&(open=open&&open.setSelected(effect.value,this.id));return active==this.active&&open==this.open?this:new _CompletionState2(active,this.id,open)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:baseAttrs}};__name2(_CompletionState,"CompletionState");let CompletionState=_CompletionState;function sameResults(a,b){if(a==b)return!0;for(let iA=0,iB=0;;){for(;iA-1&&(result["aria-activedescendant"]=id+"-"+selected),result}__name(makeAttrs,"makeAttrs"),__name2(makeAttrs,"makeAttrs");const none$1=[];function getUserEvent(tr){return tr.isUserEvent("input.type")?"input":tr.isUserEvent("delete.backward")?"delete":null}__name(getUserEvent,"getUserEvent"),__name2(getUserEvent,"getUserEvent");const _ActiveSource=class _ActiveSource2{static{__name(this,"_ActiveSource")}constructor(source,state,explicitPos=-1){this.source=source,this.state=state,this.explicitPos=explicitPos}hasResult(){return!1}update(tr,conf){let event=getUserEvent(tr),value=this;event?value=value.handleUserEvent(tr,event,conf):tr.docChanged?value=value.handleChange(tr):tr.selection&&value.state!=0&&(value=new _ActiveSource2(value.source,0));for(let effect of tr.effects)if(effect.is(startCompletionEffect))value=new _ActiveSource2(value.source,1,effect.value?cur(tr.state):-1);else if(effect.is(closeCompletionEffect))value=new _ActiveSource2(value.source,0);else if(effect.is(setActiveEffect))for(let active of effect.value)active.source==value.source&&(value=active);return value}handleUserEvent(tr,type,conf){return type=="delete"||!conf.activateOnTyping?this.map(tr.changes):new _ActiveSource2(this.source,1)}handleChange(tr){return tr.changes.touchesRange(cur(tr.startState))?new _ActiveSource2(this.source,0):this.map(tr.changes)}map(changes){return changes.empty||this.explicitPos<0?this:new _ActiveSource2(this.source,this.state,changes.mapPos(this.explicitPos))}};__name2(_ActiveSource,"ActiveSource");let ActiveSource=_ActiveSource;const _ActiveResult=class _ActiveResult2 extends ActiveSource{static{__name(this,"_ActiveResult")}constructor(source,explicitPos,result,from,to){super(source,2,explicitPos),this.result=result,this.from=from,this.to=to}hasResult(){return!0}handleUserEvent(tr,type,conf){var _a3;let from=tr.changes.mapPos(this.from),to=tr.changes.mapPos(this.to,1),pos=cur(tr.state);if((this.explicitPos<0?pos<=from:posto||type=="delete"&&cur(tr.startState)==this.from)return new ActiveSource(this.source,type=="input"&&conf.activateOnTyping?1:0);let explicitPos=this.explicitPos<0?-1:tr.changes.mapPos(this.explicitPos),updated;return checkValid(this.result.validFor,tr.state,from,to)?new _ActiveResult2(this.source,explicitPos,this.result,from,to):this.result.update&&(updated=this.result.update(this.result,from,to,new CompletionContext(tr.state,pos,explicitPos>=0)))?new _ActiveResult2(this.source,explicitPos,updated,updated.from,(_a3=updated.to)!==null&&_a3!==void 0?_a3:cur(tr.state)):new ActiveSource(this.source,1,explicitPos)}handleChange(tr){return tr.changes.touchesRange(this.from,this.to)?new ActiveSource(this.source,0):this.map(tr.changes)}map(mapping){return mapping.empty?this:new _ActiveResult2(this.source,this.explicitPos<0?-1:mapping.mapPos(this.explicitPos),this.result,mapping.mapPos(this.from),mapping.mapPos(this.to,1))}};__name2(_ActiveResult,"ActiveResult");let ActiveResult=_ActiveResult;function checkValid(validFor,state,from,to){if(!validFor)return!1;let text=state.sliceDoc(from,to);return typeof validFor=="function"?validFor(text,from,to,state):ensureAnchor(validFor,!0).test(text)}__name(checkValid,"checkValid"),__name2(checkValid,"checkValid");const setActiveEffect=StateEffect.define({map(sources,mapping){return sources.map(s2=>s2.map(mapping))}}),setSelectedEffect=StateEffect.define(),completionState=StateField.define({create(){return CompletionState.start()},update(value,tr){return value.update(tr)},provide:f=>[showTooltip.from(f,val=>val.tooltip),EditorView.contentAttributes.from(f,state=>state.attrs)]});function applyCompletion(view,option2){const apply=option2.completion.apply||option2.completion.label;let result=view.state.field(completionState).active.find(a=>a.source==option2.source);return result instanceof ActiveResult?(typeof apply=="string"?view.dispatch(Object.assign(Object.assign({},insertCompletionText(view.state,apply,result.from,result.to)),{annotations:pickedCompletion.of(option2.completion)})):apply(view,option2.completion,result.from,result.to),!0):!1}__name(applyCompletion,"applyCompletion"),__name2(applyCompletion,"applyCompletion");function moveCompletionSelection(forward,by="option"){return view=>{let cState=view.state.field(completionState,!1);if(!cState||!cState.open||cState.open.disabled||Date.now()-cState.open.timestamp-1?cState.open.selected+step*(forward?1:-1):forward?0:length-1;return selected<0?selected=by=="page"?0:length-1:selected>=length&&(selected=by=="page"?length-1:0),view.dispatch({effects:setSelectedEffect.of(selected)}),!0}}__name(moveCompletionSelection,"moveCompletionSelection"),__name2(moveCompletionSelection,"moveCompletionSelection");const acceptCompletion=__name2(view=>{let cState=view.state.field(completionState,!1);return view.state.readOnly||!cState||!cState.open||cState.open.selected<0||cState.open.disabled||Date.now()-cState.open.timestampview.state.field(completionState,!1)?(view.dispatch({effects:startCompletionEffect.of(!0)}),!0):!1,"startCompletion"),closeCompletion=__name2(view=>{let cState=view.state.field(completionState,!1);return!cState||!cState.active.some(a=>a.state!=0)?!1:(view.dispatch({effects:closeCompletionEffect.of(null)}),!0)},"closeCompletion"),_RunningQuery=class{static{__name(this,"_RunningQuery")}constructor(active,context){this.active=active,this.context=context,this.time=Date.now(),this.updates=[],this.done=void 0}};__name2(_RunningQuery,"RunningQuery");let RunningQuery=_RunningQuery;const DebounceTime=50,MaxUpdateCount=50,MinAbortTime=1e3,completionPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.composing=0;for(let active of view.state.field(completionState).active)active.state==1&&this.startQuery(active)}update(update){let cState=update.state.field(completionState);if(!update.selectionSet&&!update.docChanged&&update.startState.field(completionState)==cState)return;let doesReset=update.transactions.some(tr=>(tr.selection||tr.docChanged)&&!getUserEvent(tr));for(let i=0;iMaxUpdateCount&&Date.now()-query.time>MinAbortTime){for(let handler of query.context.abortListeners)try{handler()}catch(e){logException(this.view.state,e)}query.context.abortListeners=null,this.running.splice(i--,1)}else query.updates.push(...update.transactions)}if(this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),this.debounceUpdate=cState.active.some(a=>a.state==1&&!this.running.some(q=>q.active.source==a.source))?setTimeout(()=>this.startUpdate(),DebounceTime):-1,this.composing!=0)for(let tr of update.transactions)getUserEvent(tr)=="input"?this.composing=2:this.composing==2&&tr.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1;let{state}=this.view,cState=state.field(completionState);for(let active of cState.active)active.state==1&&!this.running.some(r=>r.active.source==active.source)&&this.startQuery(active)}startQuery(active){let{state}=this.view,pos=cur(state),context=new CompletionContext(state,pos,active.explicitPos==pos),pending=new RunningQuery(active,context);this.running.push(pending),Promise.resolve(active.source(context)).then(result=>{pending.context.aborted||(pending.done=result||null,this.scheduleAccept())},err=>{this.view.dispatch({effects:closeCompletionEffect.of(null)}),logException(this.view.state,err)})}scheduleAccept(){this.running.every(q=>q.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),DebounceTime))}accept(){var _a3;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let updated=[],conf=this.view.state.facet(completionConfig);for(let i=0;ia.source==query.active.source);if(current&¤t.state==1)if(query.done==null){let active=new ActiveSource(query.active.source,0);for(let tr of query.updates)active=active.update(tr,conf);active.state!=1&&updated.push(active)}else this.startQuery(current)}updated.length&&this.view.dispatch({effects:setActiveEffect.of(updated)})}},{eventHandlers:{blur(event){let state=this.view.state.field(completionState,!1);if(state&&state.tooltip&&this.view.state.facet(completionConfig).closeOnBlur){let dialog=state.open&&getTooltip(this.view,state.open.tooltip);(!dialog||!dialog.dom.contains(event.relatedTarget))&&this.view.dispatch({effects:closeCompletionEffect.of(null)})}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:startCompletionEffect.of(!1)}),20),this.composing=0}}}),baseTheme$3=EditorView.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"\xB7\xB7\xB7"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'\u0192'"}},".cm-completionIcon-class":{"&:after":{content:"'\u25CB'"}},".cm-completionIcon-interface":{"&:after":{content:"'\u25CC'"}},".cm-completionIcon-variable":{"&:after":{content:"'\u{1D465}'"}},".cm-completionIcon-constant":{"&:after":{content:"'\u{1D436}'"}},".cm-completionIcon-type":{"&:after":{content:"'\u{1D461}'"}},".cm-completionIcon-enum":{"&:after":{content:"'\u222A'"}},".cm-completionIcon-property":{"&:after":{content:"'\u25A1'"}},".cm-completionIcon-keyword":{"&:after":{content:"'\u{1F511}\uFE0E'"}},".cm-completionIcon-namespace":{"&:after":{content:"'\u25A2'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}}),defaults={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},closeBracketEffect=StateEffect.define({map(value,mapping){let mapped=mapping.mapPos(value,-1,MapMode.TrackAfter);return mapped??void 0}}),closedBracket=new class extends RangeValue{};closedBracket.startSide=1,closedBracket.endSide=-1;const bracketState=StateField.define({create(){return RangeSet.empty},update(value,tr){if(tr.selection){let lineStart=tr.state.doc.lineAt(tr.selection.main.head).from,prevLineStart=tr.startState.doc.lineAt(tr.startState.selection.main.head).from;lineStart!=tr.changes.mapPos(prevLineStart,-1)&&(value=RangeSet.empty)}value=value.map(tr.changes);for(let effect of tr.effects)effect.is(closeBracketEffect)&&(value=value.update({add:[closedBracket.range(effect.value,effect.value+1)]}));return value}});function closeBrackets(){return[inputHandler,bracketState]}__name(closeBrackets,"closeBrackets"),__name2(closeBrackets,"closeBrackets");const definedClosing="()[]{}<>";function closing(ch){for(let i=0;i{if((android?view.composing:view.compositionStarted)||view.state.readOnly)return!1;let sel=view.state.selection.main;if(insert2.length>2||insert2.length==2&&codePointSize(codePointAt(insert2,0))==1||from!=sel.from||to!=sel.to)return!1;let tr=insertBracket(view.state,insert2);return tr?(view.dispatch(tr),!0):!1}),deleteBracketPair=__name2(({state,dispatch})=>{if(state.readOnly)return!1;let tokens=config(state,state.selection.main.head).brackets||defaults.brackets,dont=null,changes=state.changeByRange(range=>{if(range.empty){let before=prevChar(state.doc,range.head);for(let token of tokens)if(token==before&&nextChar(state.doc,range.head)==closing(codePointAt(token,0)))return{changes:{from:range.head-token.length,to:range.head+token.length},range:EditorSelection.cursor(range.head-token.length)}}return{range:dont=range}});return dont||dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"delete.backward"})),!dont},"deleteBracketPair"),closeBracketsKeymap=[{key:"Backspace",run:deleteBracketPair}];function insertBracket(state,bracket2){let conf=config(state,state.selection.main.head),tokens=conf.brackets||defaults.brackets;for(let tok of tokens){let closed=closing(codePointAt(tok,0));if(bracket2==tok)return closed==tok?handleSame(state,tok,tokens.indexOf(tok+tok+tok)>-1,conf):handleOpen(state,tok,closed,conf.before||defaults.before);if(bracket2==closed&&closedBracketAt(state,state.selection.main.from))return handleClose(state,tok,closed)}return null}__name(insertBracket,"insertBracket"),__name2(insertBracket,"insertBracket");function closedBracketAt(state,pos){let found=!1;return state.field(bracketState).between(0,state.doc.length,from=>{from==pos&&(found=!0)}),found}__name(closedBracketAt,"closedBracketAt"),__name2(closedBracketAt,"closedBracketAt");function nextChar(doc2,pos){let next=doc2.sliceString(pos,pos+2);return next.slice(0,codePointSize(codePointAt(next,0)))}__name(nextChar,"nextChar"),__name2(nextChar,"nextChar");function prevChar(doc2,pos){let prev=doc2.sliceString(pos-2,pos);return codePointSize(codePointAt(prev,0))==prev.length?prev:prev.slice(1)}__name(prevChar,"prevChar"),__name2(prevChar,"prevChar");function handleOpen(state,open,close,closeBefore){let dont=null,changes=state.changeByRange(range=>{if(!range.empty)return{changes:[{insert:open,from:range.from},{insert:close,from:range.to}],effects:closeBracketEffect.of(range.to+open.length),range:EditorSelection.range(range.anchor+open.length,range.head+open.length)};let next=nextChar(state.doc,range.head);return!next||/\s/.test(next)||closeBefore.indexOf(next)>-1?{changes:{insert:open+close,from:range.head},effects:closeBracketEffect.of(range.head+open.length),range:EditorSelection.cursor(range.head+open.length)}:{range:dont=range}});return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}__name(handleOpen,"handleOpen"),__name2(handleOpen,"handleOpen");function handleClose(state,_open,close){let dont=null,changes=state.changeByRange(range=>range.empty&&nextChar(state.doc,range.head)==close?{changes:{from:range.head,to:range.head+close.length,insert:close},range:EditorSelection.cursor(range.head+close.length)}:dont={range});return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}__name(handleClose,"handleClose"),__name2(handleClose,"handleClose");function handleSame(state,token,allowTriple,config2){let stringPrefixes=config2.stringPrefixes||defaults.stringPrefixes,dont=null,changes=state.changeByRange(range=>{if(!range.empty)return{changes:[{insert:token,from:range.from},{insert:token,from:range.to}],effects:closeBracketEffect.of(range.to+token.length),range:EditorSelection.range(range.anchor+token.length,range.head+token.length)};let pos=range.head,next=nextChar(state.doc,pos),start;if(next==token){if(nodeStart(state,pos))return{changes:{insert:token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)};if(closedBracketAt(state,pos)){let content2=allowTriple&&state.sliceDoc(pos,pos+token.length*3)==token+token+token?token+token+token:token;return{changes:{from:pos,to:pos+content2.length,insert:content2},range:EditorSelection.cursor(pos+content2.length)}}}else{if(allowTriple&&state.sliceDoc(pos-2*token.length,pos)==token+token&&(start=canStartStringAt(state,pos-2*token.length,stringPrefixes))>-1&&nodeStart(state,start))return{changes:{insert:token+token+token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)};if(state.charCategorizer(pos)(next)!=CharCategory.Word&&canStartStringAt(state,pos,stringPrefixes)>-1&&!probablyInString(state,pos,token,stringPrefixes))return{changes:{insert:token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)}}return{range:dont=range}});return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}__name(handleSame,"handleSame"),__name2(handleSame,"handleSame");function nodeStart(state,pos){let tree=syntaxTree(state).resolveInner(pos+1);return tree.parent&&tree.from==pos}__name(nodeStart,"nodeStart"),__name2(nodeStart,"nodeStart");function probablyInString(state,pos,quoteToken,prefixes){let node=syntaxTree(state).resolveInner(pos,-1),maxPrefix=prefixes.reduce((m,p)=>Math.max(m,p.length),0);for(let i=0;i<5;i++){let start=state.sliceDoc(node.from,Math.min(node.to,node.from+quoteToken.length+maxPrefix)),quotePos=start.indexOf(quoteToken);if(!quotePos||quotePos>-1&&prefixes.indexOf(start.slice(0,quotePos))>-1){let first=node.firstChild;for(;first&&first.from==node.from&&first.to-first.from>quoteToken.length+quotePos;){if(state.sliceDoc(first.to-quoteToken.length,first.to)==quoteToken)return!1;first=first.firstChild}return!0}let parent=node.to==pos&&node.parent;if(!parent)break;node=parent}return!1}__name(probablyInString,"probablyInString"),__name2(probablyInString,"probablyInString");function canStartStringAt(state,pos,prefixes){let charCat=state.charCategorizer(pos);if(charCat(state.sliceDoc(pos-1,pos))!=CharCategory.Word)return pos;for(let prefix of prefixes){let start=pos-prefix.length;if(state.sliceDoc(start,pos)==prefix&&charCat(state.sliceDoc(start-1,start))!=CharCategory.Word)return start}return-1}__name(canStartStringAt,"canStartStringAt"),__name2(canStartStringAt,"canStartStringAt");function autocompletion(config2={}){return[completionState,completionConfig.of(config2),completionPlugin,completionKeymapExt,baseTheme$3]}__name(autocompletion,"autocompletion"),__name2(autocompletion,"autocompletion");const completionKeymap=[{key:"Ctrl-Space",run:startCompletion},{key:"Escape",run:closeCompletion},{key:"ArrowDown",run:moveCompletionSelection(!0)},{key:"ArrowUp",run:moveCompletionSelection(!1)},{key:"PageDown",run:moveCompletionSelection(!0,"page")},{key:"PageUp",run:moveCompletionSelection(!1,"page")},{key:"Enter",run:acceptCompletion}],completionKeymapExt=Prec.highest(keymap.computeN([completionConfig],state=>state.facet(completionConfig).defaultKeymap?[completionKeymap]:[])),toggleComment=__name2(target=>{let{state}=target,line=state.doc.lineAt(state.selection.main.from),config2=getConfig(target.state,line.from);return config2.line?toggleLineComment(target):config2.block?toggleBlockCommentByLine(target):!1},"toggleComment");function command(f,option2){return({state,dispatch})=>{if(state.readOnly)return!1;let tr=f(option2,state);return tr?(dispatch(state.update(tr)),!0):!1}}__name(command,"command"),__name2(command,"command");const toggleLineComment=command(changeLineComment,0),toggleBlockComment=command(changeBlockComment,0),toggleBlockCommentByLine=command((o,s2)=>changeBlockComment(o,s2,selectedLineRanges(s2)),0);function getConfig(state,pos){let data=state.languageDataAt("commentTokens",pos);return data.length?data[0]:{}}__name(getConfig,"getConfig"),__name2(getConfig,"getConfig");const SearchMargin=50;function findBlockComment(state,{open,close},from,to){let textBefore=state.sliceDoc(from-SearchMargin,from),textAfter=state.sliceDoc(to,to+SearchMargin),spaceBefore=/\s*$/.exec(textBefore)[0].length,spaceAfter=/^\s*/.exec(textAfter)[0].length,beforeOff=textBefore.length-spaceBefore;if(textBefore.slice(beforeOff-open.length,beforeOff)==open&&textAfter.slice(spaceAfter,spaceAfter+close.length)==close)return{open:{pos:from-spaceBefore,margin:spaceBefore&&1},close:{pos:to+spaceAfter,margin:spaceAfter&&1}};let startText,endText;to-from<=2*SearchMargin?startText=endText=state.sliceDoc(from,to):(startText=state.sliceDoc(from,from+SearchMargin),endText=state.sliceDoc(to-SearchMargin,to));let startSpace=/^\s*/.exec(startText)[0].length,endSpace=/\s*$/.exec(endText)[0].length,endOff=endText.length-endSpace-close.length;return startText.slice(startSpace,startSpace+open.length)==open&&endText.slice(endOff,endOff+close.length)==close?{open:{pos:from+startSpace+open.length,margin:/\s/.test(startText.charAt(startSpace+open.length))?1:0},close:{pos:to-endSpace-close.length,margin:/\s/.test(endText.charAt(endOff-1))?1:0}}:null}__name(findBlockComment,"findBlockComment"),__name2(findBlockComment,"findBlockComment");function selectedLineRanges(state){let ranges=[];for(let r of state.selection.ranges){let fromLine=state.doc.lineAt(r.from),toLine=r.to<=fromLine.to?fromLine:state.doc.lineAt(r.to),last2=ranges.length-1;last2>=0&&ranges[last2].to>fromLine.from?ranges[last2].to=toLine.to:ranges.push({from:fromLine.from+/^\s*/.exec(fromLine.text)[0].length,to:toLine.to})}return ranges}__name(selectedLineRanges,"selectedLineRanges"),__name2(selectedLineRanges,"selectedLineRanges");function changeBlockComment(option2,state,ranges=state.selection.ranges){let tokens=ranges.map(r=>getConfig(state,r.from).block);if(!tokens.every(c=>c))return null;let comments=ranges.map((r,i)=>findBlockComment(state,tokens[i],r.from,r.to));if(option2!=2&&!comments.every(c=>c))return{changes:state.changes(ranges.map((range,i)=>comments[i]?[]:[{from:range.from,insert:tokens[i].open+" "},{from:range.to,insert:" "+tokens[i].close}]))};if(option2!=1&&comments.some(c=>c)){let changes=[];for(let i=0,comment2;iprevLine&&(from==to||to>line.from)){prevLine=line.from;let indent=/^\s*/.exec(line.text)[0].length,empty2=indent==line.length,comment2=line.text.slice(indent,indent+token.length)==token?indent:-1;indentl2.comment<0&&(!l2.empty||l2.single))){let changes=[];for(let{line,token,indent,empty:empty2,single}of lines)(single||!empty2)&&changes.push({from:line.from+indent,insert:token+" "});let changeSet=state.changes(changes);return{changes:changeSet,selection:state.selection.map(changeSet,1)}}else if(option2!=1&&lines.some(l2=>l2.comment>=0)){let changes=[];for(let{line,comment:comment2,token}of lines)if(comment2>=0){let from=line.from+comment2,to=from+token.length;line.text[to-line.from]==" "&&to++,changes.push({from,to})}return{changes}}return null}__name(changeLineComment,"changeLineComment"),__name2(changeLineComment,"changeLineComment");const fromHistory=Annotation.define(),isolateHistory=Annotation.define(),invertedEffects=Facet.define(),historyConfig=Facet.define({combine(configs){return combineConfig(configs,{minDepth:100,newGroupDelay:500,joinToEvent:(_t,isAdjacent2)=>isAdjacent2},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(a,b)=>(tr,adj)=>a(tr,adj)||b(tr,adj)})}});function changeEnd(changes){let end=0;return changes.iterChangedRanges((_,to)=>end=to),end}__name(changeEnd,"changeEnd"),__name2(changeEnd,"changeEnd");const historyField_=StateField.define({create(){return HistoryState.empty},update(state,tr){let config2=tr.state.facet(historyConfig),fromHist=tr.annotation(fromHistory);if(fromHist){let selection=tr.docChanged?EditorSelection.single(changeEnd(tr.changes)):void 0,item=HistEvent.fromTransaction(tr,selection),from=fromHist.side,other=from==0?state.undone:state.done;return item?other=updateBranch(other,other.length,config2.minDepth,item):other=addSelection(other,tr.startState.selection),new HistoryState(from==0?fromHist.rest:other,from==0?other:fromHist.rest)}let isolate=tr.annotation(isolateHistory);if((isolate=="full"||isolate=="before")&&(state=state.isolate()),tr.annotation(Transaction.addToHistory)===!1)return tr.changes.empty?state:state.addMapping(tr.changes.desc);let event=HistEvent.fromTransaction(tr),time=tr.annotation(Transaction.time),userEvent=tr.annotation(Transaction.userEvent);return event?state=state.addChanges(event,time,userEvent,config2,tr):tr.selection&&(state=state.addSelection(tr.startState.selection,time,userEvent,config2.newGroupDelay)),(isolate=="full"||isolate=="after")&&(state=state.isolate()),state},toJSON(value){return{done:value.done.map(e=>e.toJSON()),undone:value.undone.map(e=>e.toJSON())}},fromJSON(json2){return new HistoryState(json2.done.map(HistEvent.fromJSON),json2.undone.map(HistEvent.fromJSON))}});function history(config2={}){return[historyField_,historyConfig.of(config2),EditorView.domEventHandlers({beforeinput(e,view){let command2=e.inputType=="historyUndo"?undo:e.inputType=="historyRedo"?redo:null;return command2?(e.preventDefault(),command2(view)):!1}})]}__name(history,"history"),__name2(history,"history");function cmd(side,selection){return function({state,dispatch}){if(!selection&&state.readOnly)return!1;let historyState=state.field(historyField_,!1);if(!historyState)return!1;let tr=historyState.pop(side,state,selection);return tr?(dispatch(tr),!0):!1}}__name(cmd,"cmd"),__name2(cmd,"cmd");const undo=cmd(0,!1),redo=cmd(1,!1),undoSelection=cmd(0,!0),redoSelection=cmd(1,!0),_HistEvent=class _HistEvent2{static{__name(this,"_HistEvent")}constructor(changes,effects,mapped,startSelection,selectionsAfter){this.changes=changes,this.effects=effects,this.mapped=mapped,this.startSelection=startSelection,this.selectionsAfter=selectionsAfter}setSelAfter(after){return new _HistEvent2(this.changes,this.effects,this.mapped,this.startSelection,after)}toJSON(){var _a3,_b2,_c2;return{changes:(_a3=this.changes)===null||_a3===void 0?void 0:_a3.toJSON(),mapped:(_b2=this.mapped)===null||_b2===void 0?void 0:_b2.toJSON(),startSelection:(_c2=this.startSelection)===null||_c2===void 0?void 0:_c2.toJSON(),selectionsAfter:this.selectionsAfter.map(s2=>s2.toJSON())}}static fromJSON(json2){return new _HistEvent2(json2.changes&&ChangeSet.fromJSON(json2.changes),[],json2.mapped&&ChangeDesc.fromJSON(json2.mapped),json2.startSelection&&EditorSelection.fromJSON(json2.startSelection),json2.selectionsAfter.map(EditorSelection.fromJSON))}static fromTransaction(tr,selection){let effects=none;for(let invert of tr.startState.facet(invertedEffects)){let result=invert(tr);result.length&&(effects=effects.concat(result))}return!effects.length&&tr.changes.empty?null:new _HistEvent2(tr.changes.invert(tr.startState.doc),effects,void 0,selection||tr.startState.selection,none)}static selection(selections){return new _HistEvent2(void 0,none,void 0,void 0,selections)}};__name2(_HistEvent,"HistEvent");let HistEvent=_HistEvent;function updateBranch(branch,to,maxLen,newEvent){let start=to+1>maxLen+20?to-maxLen-1:0,newBranch=branch.slice(start,to);return newBranch.push(newEvent),newBranch}__name(updateBranch,"updateBranch"),__name2(updateBranch,"updateBranch");function isAdjacent(a,b){let ranges=[],isAdjacent2=!1;return a.iterChangedRanges((f,t2)=>ranges.push(f,t2)),b.iterChangedRanges((_f,_t,f,t2)=>{for(let i=0;i=from&&f<=to&&(isAdjacent2=!0)}}),isAdjacent2}__name(isAdjacent,"isAdjacent"),__name2(isAdjacent,"isAdjacent");function eqSelectionShape(a,b){return a.ranges.length==b.ranges.length&&a.ranges.filter((r,i)=>r.empty!=b.ranges[i].empty).length===0}__name(eqSelectionShape,"eqSelectionShape"),__name2(eqSelectionShape,"eqSelectionShape");function conc(a,b){return a.length?b.length?a.concat(b):a:b}__name(conc,"conc"),__name2(conc,"conc");const none=[],MaxSelectionsPerEvent=200;function addSelection(branch,selection){if(branch.length){let lastEvent=branch[branch.length-1],sels=lastEvent.selectionsAfter.slice(Math.max(0,lastEvent.selectionsAfter.length-MaxSelectionsPerEvent));return sels.length&&sels[sels.length-1].eq(selection)?branch:(sels.push(selection),updateBranch(branch,branch.length-1,1e9,lastEvent.setSelAfter(sels)))}else return[HistEvent.selection([selection])]}__name(addSelection,"addSelection"),__name2(addSelection,"addSelection");function popSelection(branch){let last2=branch[branch.length-1],newBranch=branch.slice();return newBranch[branch.length-1]=last2.setSelAfter(last2.selectionsAfter.slice(0,last2.selectionsAfter.length-1)),newBranch}__name(popSelection,"popSelection"),__name2(popSelection,"popSelection");function addMappingToBranch(branch,mapping){if(!branch.length)return branch;let length=branch.length,selections=none;for(;length;){let event=mapEvent(branch[length-1],mapping,selections);if(event.changes&&!event.changes.empty||event.effects.length){let result=branch.slice(0,length);return result[length-1]=event,result}else mapping=event.mapped,length--,selections=event.selectionsAfter}return selections.length?[HistEvent.selection(selections)]:none}__name(addMappingToBranch,"addMappingToBranch"),__name2(addMappingToBranch,"addMappingToBranch");function mapEvent(event,mapping,extraSelections){let selections=conc(event.selectionsAfter.length?event.selectionsAfter.map(s2=>s2.map(mapping)):none,extraSelections);if(!event.changes)return HistEvent.selection(selections);let mappedChanges=event.changes.map(mapping),before=mapping.mapDesc(event.changes,!0),fullMapping=event.mapped?event.mapped.composeDesc(before):before;return new HistEvent(mappedChanges,StateEffect.mapEffects(event.effects,mapping),fullMapping,event.startSelection.map(before),selections)}__name(mapEvent,"mapEvent"),__name2(mapEvent,"mapEvent");const joinableUserEvent=/^(input\.type|delete)($|\.)/,_HistoryState=class _HistoryState2{static{__name(this,"_HistoryState")}constructor(done,undone,prevTime=0,prevUserEvent=void 0){this.done=done,this.undone=undone,this.prevTime=prevTime,this.prevUserEvent=prevUserEvent}isolate(){return this.prevTime?new _HistoryState2(this.done,this.undone):this}addChanges(event,time,userEvent,config2,tr){let done=this.done,lastEvent=done[done.length-1];return lastEvent&&lastEvent.changes&&!lastEvent.changes.empty&&event.changes&&(!userEvent||joinableUserEvent.test(userEvent))&&(!lastEvent.selectionsAfter.length&&time-this.prevTime0&&time-this.prevTimerange.empty?view.moveByChar(range,forward):rangeEnd(range,forward))}__name(cursorByChar,"cursorByChar"),__name2(cursorByChar,"cursorByChar");function ltrAtCursor(view){return view.textDirectionAt(view.state.selection.main.head)==Direction.LTR}__name(ltrAtCursor,"ltrAtCursor"),__name2(ltrAtCursor,"ltrAtCursor");const cursorCharLeft=__name2(view=>cursorByChar(view,!ltrAtCursor(view)),"cursorCharLeft"),cursorCharRight=__name2(view=>cursorByChar(view,ltrAtCursor(view)),"cursorCharRight");function cursorByGroup(view,forward){return moveSel(view,range=>range.empty?view.moveByGroup(range,forward):rangeEnd(range,forward))}__name(cursorByGroup,"cursorByGroup"),__name2(cursorByGroup,"cursorByGroup");const cursorGroupLeft=__name2(view=>cursorByGroup(view,!ltrAtCursor(view)),"cursorGroupLeft"),cursorGroupRight=__name2(view=>cursorByGroup(view,ltrAtCursor(view)),"cursorGroupRight");function interestingNode(state,node,bracketProp){if(node.type.prop(bracketProp))return!0;let len=node.to-node.from;return len&&(len>2||/[^\s,.;:]/.test(state.sliceDoc(node.from,node.to)))||node.firstChild}__name(interestingNode,"interestingNode"),__name2(interestingNode,"interestingNode");function moveBySyntax(state,start,forward){let pos=syntaxTree(state).resolveInner(start.head),bracketProp=forward?NodeProp.closedBy:NodeProp.openedBy;for(let at=start.head;;){let next=forward?pos.childAfter(at):pos.childBefore(at);if(!next)break;interestingNode(state,next,bracketProp)?pos=next:at=forward?next.to:next.from}let bracket2=pos.type.prop(bracketProp),match2,newPos;return bracket2&&(match2=forward?matchBrackets(state,pos.from,1):matchBrackets(state,pos.to,-1))&&match2.matched?newPos=forward?match2.end.to:match2.end.from:newPos=forward?pos.to:pos.from,EditorSelection.cursor(newPos,forward?-1:1)}__name(moveBySyntax,"moveBySyntax"),__name2(moveBySyntax,"moveBySyntax");const cursorSyntaxLeft=__name2(view=>moveSel(view,range=>moveBySyntax(view.state,range,!ltrAtCursor(view))),"cursorSyntaxLeft"),cursorSyntaxRight=__name2(view=>moveSel(view,range=>moveBySyntax(view.state,range,ltrAtCursor(view))),"cursorSyntaxRight");function cursorByLine(view,forward){return moveSel(view,range=>{if(!range.empty)return rangeEnd(range,forward);let moved2=view.moveVertically(range,forward);return moved2.head!=range.head?moved2:view.moveToLineBoundary(range,forward)})}__name(cursorByLine,"cursorByLine"),__name2(cursorByLine,"cursorByLine");const cursorLineUp=__name2(view=>cursorByLine(view,!1),"cursorLineUp"),cursorLineDown=__name2(view=>cursorByLine(view,!0),"cursorLineDown");function pageInfo(view){let selfScroll=view.scrollDOM.clientHeightrange.empty?view.moveVertically(range,forward,page.height):rangeEnd(range,forward));if(selection.eq(state.selection))return!1;let effect;if(page.selfScroll){let startPos=view.coordsAtPos(state.selection.main.head),scrollRect=view.scrollDOM.getBoundingClientRect(),scrollTop=scrollRect.top+page.marginTop,scrollBottom=scrollRect.bottom-page.marginBottom;startPos&&startPos.top>scrollTop&&startPos.bottomcursorByPage(view,!1),"cursorPageUp"),cursorPageDown=__name2(view=>cursorByPage(view,!0),"cursorPageDown");function moveByLineBoundary(view,start,forward){let line=view.lineBlockAt(start.head),moved2=view.moveToLineBoundary(start,forward);if(moved2.head==start.head&&moved2.head!=(forward?line.to:line.from)&&(moved2=view.moveToLineBoundary(start,forward,!1)),!forward&&moved2.head==line.from&&line.length){let space=/^\s*/.exec(view.state.sliceDoc(line.from,Math.min(line.from+100,line.to)))[0].length;space&&start.head!=line.from+space&&(moved2=EditorSelection.cursor(line.from+space))}return moved2}__name(moveByLineBoundary,"moveByLineBoundary"),__name2(moveByLineBoundary,"moveByLineBoundary");const cursorLineBoundaryForward=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,!0)),"cursorLineBoundaryForward"),cursorLineBoundaryBackward=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,!1)),"cursorLineBoundaryBackward"),cursorLineBoundaryLeft=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,!ltrAtCursor(view))),"cursorLineBoundaryLeft"),cursorLineBoundaryRight=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,ltrAtCursor(view))),"cursorLineBoundaryRight"),cursorLineStart=__name2(view=>moveSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).from,1)),"cursorLineStart"),cursorLineEnd=__name2(view=>moveSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).to,-1)),"cursorLineEnd");function toMatchingBracket(state,dispatch,extend2){let found=!1,selection=updateSel(state.selection,range=>{let matching=matchBrackets(state,range.head,-1)||matchBrackets(state,range.head,1)||range.head>0&&matchBrackets(state,range.head-1,1)||range.headtoMatchingBracket(state,dispatch,!1),"cursorMatchingBracket");function extendSel(view,how){let selection=updateSel(view.state.selection,range=>{let head=how(range);return EditorSelection.range(range.anchor,head.head,head.goalColumn,head.bidiLevel||void 0)});return selection.eq(view.state.selection)?!1:(view.dispatch(setSel(view.state,selection)),!0)}__name(extendSel,"extendSel"),__name2(extendSel,"extendSel");function selectByChar(view,forward){return extendSel(view,range=>view.moveByChar(range,forward))}__name(selectByChar,"selectByChar"),__name2(selectByChar,"selectByChar");const selectCharLeft=__name2(view=>selectByChar(view,!ltrAtCursor(view)),"selectCharLeft"),selectCharRight=__name2(view=>selectByChar(view,ltrAtCursor(view)),"selectCharRight");function selectByGroup(view,forward){return extendSel(view,range=>view.moveByGroup(range,forward))}__name(selectByGroup,"selectByGroup"),__name2(selectByGroup,"selectByGroup");const selectGroupLeft=__name2(view=>selectByGroup(view,!ltrAtCursor(view)),"selectGroupLeft"),selectGroupRight=__name2(view=>selectByGroup(view,ltrAtCursor(view)),"selectGroupRight"),selectSyntaxLeft=__name2(view=>extendSel(view,range=>moveBySyntax(view.state,range,!ltrAtCursor(view))),"selectSyntaxLeft"),selectSyntaxRight=__name2(view=>extendSel(view,range=>moveBySyntax(view.state,range,ltrAtCursor(view))),"selectSyntaxRight");function selectByLine(view,forward){return extendSel(view,range=>view.moveVertically(range,forward))}__name(selectByLine,"selectByLine"),__name2(selectByLine,"selectByLine");const selectLineUp=__name2(view=>selectByLine(view,!1),"selectLineUp"),selectLineDown=__name2(view=>selectByLine(view,!0),"selectLineDown");function selectByPage(view,forward){return extendSel(view,range=>view.moveVertically(range,forward,pageInfo(view).height))}__name(selectByPage,"selectByPage"),__name2(selectByPage,"selectByPage");const selectPageUp=__name2(view=>selectByPage(view,!1),"selectPageUp"),selectPageDown=__name2(view=>selectByPage(view,!0),"selectPageDown"),selectLineBoundaryForward=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,!0)),"selectLineBoundaryForward"),selectLineBoundaryBackward=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,!1)),"selectLineBoundaryBackward"),selectLineBoundaryLeft=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,!ltrAtCursor(view))),"selectLineBoundaryLeft"),selectLineBoundaryRight=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,ltrAtCursor(view))),"selectLineBoundaryRight"),selectLineStart=__name2(view=>extendSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).from)),"selectLineStart"),selectLineEnd=__name2(view=>extendSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).to)),"selectLineEnd"),cursorDocStart=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:0})),!0),"cursorDocStart"),cursorDocEnd=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:state.doc.length})),!0),"cursorDocEnd"),selectDocStart=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:state.selection.main.anchor,head:0})),!0),"selectDocStart"),selectDocEnd=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:state.selection.main.anchor,head:state.doc.length})),!0),"selectDocEnd"),selectAll=__name2(({state,dispatch})=>(dispatch(state.update({selection:{anchor:0,head:state.doc.length},userEvent:"select"})),!0),"selectAll"),selectLine=__name2(({state,dispatch})=>{let ranges=selectedLineBlocks(state).map(({from,to})=>EditorSelection.range(from,Math.min(to+1,state.doc.length)));return dispatch(state.update({selection:EditorSelection.create(ranges),userEvent:"select"})),!0},"selectLine"),selectParentSyntax=__name2(({state,dispatch})=>{let selection=updateSel(state.selection,range=>{var _a3;let context=syntaxTree(state).resolveInner(range.head,1);for(;!(context.from=range.to||context.to>range.to&&context.from<=range.from||!(!((_a3=context.parent)===null||_a3===void 0)&&_a3.parent));)context=context.parent;return EditorSelection.range(context.to,context.from)});return dispatch(setSel(state,selection)),!0},"selectParentSyntax"),simplifySelection=__name2(({state,dispatch})=>{let cur2=state.selection,selection=null;return cur2.ranges.length>1?selection=EditorSelection.create([cur2.main]):cur2.main.empty||(selection=EditorSelection.create([EditorSelection.cursor(cur2.main.head)])),selection?(dispatch(setSel(state,selection)),!0):!1},"simplifySelection");function deleteBy(target,by){if(target.state.readOnly)return!1;let event="delete.selection",{state}=target,changes=state.changeByRange(range=>{let{from,to}=range;if(from==to){let towards=by(from);towardsfrom&&(event="delete.forward",towards=skipAtomic(target,towards,!0)),from=Math.min(from,towards),to=Math.max(to,towards)}else from=skipAtomic(target,from,!1),to=skipAtomic(target,to,!0);return from==to?{range}:{changes:{from,to},range:EditorSelection.cursor(from)}});return changes.changes.empty?!1:(target.dispatch(state.update(changes,{scrollIntoView:!0,userEvent:event,effects:event=="delete.selection"?EditorView.announce.of(state.phrase("Selection deleted")):void 0})),!0)}__name(deleteBy,"deleteBy"),__name2(deleteBy,"deleteBy");function skipAtomic(target,pos,forward){if(target instanceof EditorView)for(let ranges of target.state.facet(EditorView.atomicRanges).map(f=>f(target)))ranges.between(pos,pos,(from,to)=>{frompos&&(pos=forward?to:from)});return pos}__name(skipAtomic,"skipAtomic"),__name2(skipAtomic,"skipAtomic");const deleteByChar=__name2((target,forward)=>deleteBy(target,pos=>{let{state}=target,line=state.doc.lineAt(pos),before,targetPos;if(!forward&&pos>line.from&&posdeleteByChar(view,!1),"deleteCharBackward"),deleteCharForward=__name2(view=>deleteByChar(view,!0),"deleteCharForward"),deleteByGroup=__name2((target,forward)=>deleteBy(target,start=>{let pos=start,{state}=target,line=state.doc.lineAt(pos),categorize=state.charCategorizer(pos);for(let cat=null;;){if(pos==(forward?line.to:line.from)){pos==start&&line.number!=(forward?state.doc.lines:1)&&(pos+=forward?1:-1);break}let next=findClusterBreak(line.text,pos-line.from,forward)+line.from,nextChar2=line.text.slice(Math.min(pos,next)-line.from,Math.max(pos,next)-line.from),nextCat=categorize(nextChar2);if(cat!=null&&nextCat!=cat)break;(nextChar2!=" "||pos!=start)&&(cat=nextCat),pos=next}return pos}),"deleteByGroup"),deleteGroupBackward=__name2(target=>deleteByGroup(target,!1),"deleteGroupBackward"),deleteGroupForward=__name2(target=>deleteByGroup(target,!0),"deleteGroupForward"),deleteToLineEnd=__name2(view=>deleteBy(view,pos=>{let lineEnd=view.lineBlockAt(pos).to;return posdeleteBy(view,pos=>{let lineStart=view.lineBlockAt(pos).from;return pos>lineStart?lineStart:Math.max(0,pos-1)}),"deleteToLineStart"),splitLine=__name2(({state,dispatch})=>{if(state.readOnly)return!1;let changes=state.changeByRange(range=>({changes:{from:range.from,to:range.to,insert:Text.of(["",""])},range:EditorSelection.cursor(range.from)}));return dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"input"})),!0},"splitLine"),transposeChars=__name2(({state,dispatch})=>{if(state.readOnly)return!1;let changes=state.changeByRange(range=>{if(!range.empty||range.from==0||range.from==state.doc.length)return{range};let pos=range.from,line=state.doc.lineAt(pos),from=pos==line.from?pos-1:findClusterBreak(line.text,pos-line.from,!1)+line.from,to=pos==line.to?pos+1:findClusterBreak(line.text,pos-line.from,!0)+line.from;return{changes:{from,to,insert:state.doc.slice(pos,to).append(state.doc.slice(from,pos))},range:EditorSelection.cursor(to)}});return changes.changes.empty?!1:(dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"move.character"})),!0)},"transposeChars");function selectedLineBlocks(state){let blocks=[],upto=-1;for(let range of state.selection.ranges){let startLine=state.doc.lineAt(range.from),endLine=state.doc.lineAt(range.to);if(!range.empty&&range.to==endLine.from&&(endLine=state.doc.lineAt(range.to-1)),upto>=startLine.number){let prev=blocks[blocks.length-1];prev.to=endLine.to,prev.ranges.push(range)}else blocks.push({from:startLine.from,to:endLine.to,ranges:[range]});upto=endLine.number+1}return blocks}__name(selectedLineBlocks,"selectedLineBlocks"),__name2(selectedLineBlocks,"selectedLineBlocks");function moveLine(state,dispatch,forward){if(state.readOnly)return!1;let changes=[],ranges=[];for(let block of selectedLineBlocks(state)){if(forward?block.to==state.doc.length:block.from==0)continue;let nextLine=state.doc.lineAt(forward?block.to+1:block.from-1),size=nextLine.length+1;if(forward){changes.push({from:block.to,to:nextLine.to},{from:block.from,insert:nextLine.text+state.lineBreak});for(let r of block.ranges)ranges.push(EditorSelection.range(Math.min(state.doc.length,r.anchor+size),Math.min(state.doc.length,r.head+size)))}else{changes.push({from:nextLine.from,to:block.from},{from:block.to,insert:state.lineBreak+nextLine.text});for(let r of block.ranges)ranges.push(EditorSelection.range(r.anchor-size,r.head-size))}}return changes.length?(dispatch(state.update({changes,scrollIntoView:!0,selection:EditorSelection.create(ranges,state.selection.mainIndex),userEvent:"move.line"})),!0):!1}__name(moveLine,"moveLine"),__name2(moveLine,"moveLine");const moveLineUp=__name2(({state,dispatch})=>moveLine(state,dispatch,!1),"moveLineUp"),moveLineDown=__name2(({state,dispatch})=>moveLine(state,dispatch,!0),"moveLineDown");function copyLine(state,dispatch,forward){if(state.readOnly)return!1;let changes=[];for(let block of selectedLineBlocks(state))forward?changes.push({from:block.from,insert:state.doc.slice(block.from,block.to)+state.lineBreak}):changes.push({from:block.to,insert:state.lineBreak+state.doc.slice(block.from,block.to)});return dispatch(state.update({changes,scrollIntoView:!0,userEvent:"input.copyline"})),!0}__name(copyLine,"copyLine"),__name2(copyLine,"copyLine");const copyLineUp=__name2(({state,dispatch})=>copyLine(state,dispatch,!1),"copyLineUp"),copyLineDown=__name2(({state,dispatch})=>copyLine(state,dispatch,!0),"copyLineDown"),deleteLine=__name2(view=>{if(view.state.readOnly)return!1;let{state}=view,changes=state.changes(selectedLineBlocks(state).map(({from,to})=>(from>0?from--:toview.moveVertically(range,!0)).map(changes);return view.dispatch({changes,selection,scrollIntoView:!0,userEvent:"delete.line"}),!0},"deleteLine");function isBetweenBrackets(state,pos){if(/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos-1,pos+1)))return{from:pos,to:pos};let context=syntaxTree(state).resolveInner(pos),before=context.childBefore(pos),after=context.childAfter(pos),closedBy;return before&&after&&before.to<=pos&&after.from>=pos&&(closedBy=before.type.prop(NodeProp.closedBy))&&closedBy.indexOf(after.name)>-1&&state.doc.lineAt(before.to).from==state.doc.lineAt(after.from).from?{from:before.to,to:after.from}:null}__name(isBetweenBrackets,"isBetweenBrackets"),__name2(isBetweenBrackets,"isBetweenBrackets");const insertNewlineAndIndent=newlineAndIndent(!1),insertBlankLine=newlineAndIndent(!0);function newlineAndIndent(atEof){return({state,dispatch})=>{if(state.readOnly)return!1;let changes=state.changeByRange(range=>{let{from,to}=range,line=state.doc.lineAt(from),explode=!atEof&&from==to&&isBetweenBrackets(state,from);atEof&&(from=to=(to<=line.to?line:state.doc.lineAt(to)).to);let cx=new IndentContext(state,{simulateBreak:from,simulateDoubleBreak:!!explode}),indent=getIndentation(cx,from);for(indent==null&&(indent=/^\s*/.exec(state.doc.lineAt(from).text)[0].length);toline.from&&from{let changes=[];for(let pos=range.from;pos<=range.to;){let line=state.doc.lineAt(pos);line.number>atLine&&(range.empty||range.to>line.from)&&(f(line,changes,range),atLine=line.number),pos=line.to+1}let changeSet=state.changes(changes);return{changes,range:EditorSelection.range(changeSet.mapPos(range.anchor,1),changeSet.mapPos(range.head,1))}})}__name(changeBySelectedLine,"changeBySelectedLine"),__name2(changeBySelectedLine,"changeBySelectedLine");const indentSelection=__name2(({state,dispatch})=>{if(state.readOnly)return!1;let updated=Object.create(null),context=new IndentContext(state,{overrideIndentation:start=>{let found=updated[start];return found??-1}}),changes=changeBySelectedLine(state,(line,changes2,range)=>{let indent=getIndentation(context,line.from);if(indent==null)return;/\S/.test(line.text)||(indent=0);let cur2=/^\s*/.exec(line.text)[0],norm=indentString(state,indent);(cur2!=norm||range.fromstate.readOnly?!1:(dispatch(state.update(changeBySelectedLine(state,(line,changes)=>{changes.push({from:line.from,insert:state.facet(indentUnit)})}),{userEvent:"input.indent"})),!0),"indentMore"),indentLess=__name2(({state,dispatch})=>state.readOnly?!1:(dispatch(state.update(changeBySelectedLine(state,(line,changes)=>{let space=/^\s*/.exec(line.text)[0];if(!space)return;let col=countColumn(space,state.tabSize),keep=0,insert2=indentString(state,Math.max(0,col-getIndentUnit(state)));for(;keep({mac:b.key,run:b.run,shift:b.shift}))),defaultKeymap=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:cursorSyntaxLeft,shift:selectSyntaxLeft},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:cursorSyntaxRight,shift:selectSyntaxRight},{key:"Alt-ArrowUp",run:moveLineUp},{key:"Shift-Alt-ArrowUp",run:copyLineUp},{key:"Alt-ArrowDown",run:moveLineDown},{key:"Shift-Alt-ArrowDown",run:copyLineDown},{key:"Escape",run:simplifySelection},{key:"Mod-Enter",run:insertBlankLine},{key:"Alt-l",mac:"Ctrl-l",run:selectLine},{key:"Mod-i",run:selectParentSyntax,preventDefault:!0},{key:"Mod-[",run:indentLess},{key:"Mod-]",run:indentMore},{key:"Mod-Alt-\\",run:indentSelection},{key:"Shift-Mod-k",run:deleteLine},{key:"Shift-Mod-\\",run:cursorMatchingBracket},{key:"Mod-/",run:toggleComment},{key:"Alt-A",run:toggleBlockComment}].concat(standardKeymap),indentWithTab={key:"Tab",run:indentMore,shift:indentLess},_Stack=class _Stack2{static{__name(this,"_Stack")}constructor(p,stack,state,reducePos,pos,score2,buffer,bufferBase,curContext,lookAhead=0,parent){this.p=p,this.stack=stack,this.state=state,this.reducePos=reducePos,this.pos=pos,this.score=score2,this.buffer=buffer,this.bufferBase=bufferBase,this.curContext=curContext,this.lookAhead=lookAhead,this.parent=parent}toString(){return`[${this.stack.filter((_,i)=>i%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(p,state,pos=0){let cx=p.parser.context;return new _Stack2(p,[],state,pos,pos,0,[],0,cx?new StackContext(cx,cx.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(state,start){this.stack.push(this.state,start,this.bufferBase+this.buffer.length),this.state=state}reduce(action){var _a3;let depth=action>>19,type=action&65535,{parser:parser2}=this.p,dPrec=parser2.dynamicPrecedence(type);if(dPrec&&(this.score+=dPrec),depth==0){this.pushState(parser2.getGoto(this.state,type,!0),this.reducePos),type=2e3&&!(!((_a3=this.p.parser.nodeSet.types[type])===null||_a3===void 0)&&_a3.isAnonymous)&&(start==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=size):this.p.lastBigReductionSizebase2;)this.stack.pop();this.reduceContext(type,start)}storeNode(term,start,end,size=4,isReduce=!1){if(term==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&cur2.buffer[top2-4]==0&&cur2.buffer[top2-1]>-1){if(start==end)return;if(cur2.buffer[top2-2]>=start){cur2.buffer[top2-2]=end;return}}}if(!isReduce||this.pos==end)this.buffer.push(term,start,end,size);else{let index2=this.buffer.length;if(index2>0&&this.buffer[index2-4]!=0)for(;index2>0&&this.buffer[index2-2]>end;)this.buffer[index2]=this.buffer[index2-4],this.buffer[index2+1]=this.buffer[index2-3],this.buffer[index2+2]=this.buffer[index2-2],this.buffer[index2+3]=this.buffer[index2-1],index2-=4,size>4&&(size-=4);this.buffer[index2]=term,this.buffer[index2+1]=start,this.buffer[index2+2]=end,this.buffer[index2+3]=size}}shift(action,next,nextEnd){let start=this.pos;if(action&131072)this.pushState(action&65535,this.pos);else if(action&262144)this.pos=nextEnd,this.shiftContext(next,start),next<=this.p.parser.maxNode&&this.buffer.push(next,start,nextEnd,4);else{let nextState=action,{parser:parser2}=this.p;(nextEnd>this.pos||next<=parser2.maxNode)&&(this.pos=nextEnd,parser2.stateFlag(nextState,1)||(this.reducePos=nextEnd)),this.pushState(nextState,start),this.shiftContext(next,start),next<=parser2.maxNode&&this.buffer.push(next,start,nextEnd,4)}}apply(action,next,nextEnd){action&65536?this.reduce(action):this.shift(action,next,nextEnd)}useNode(value,next){let index2=this.p.reused.length-1;(index2<0||this.p.reused[index2]!=value)&&(this.p.reused.push(value),index2++);let start=this.pos;this.reducePos=this.pos=start+value.length,this.pushState(next,start),this.buffer.push(index2,start,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,value,this,this.p.stream.reset(this.pos-value.length)))}split(){let parent=this,off2=parent.buffer.length;for(;off2>0&&parent.buffer[off2-2]>parent.reducePos;)off2-=4;let buffer=parent.buffer.slice(off2),base2=parent.bufferBase+off2;for(;parent&&base2==parent.bufferBase;)parent=parent.parent;return new _Stack2(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,buffer,base2,this.curContext,this.lookAhead,parent)}recoverByDelete(next,nextEnd){let isNode=next<=this.p.parser.maxNode;isNode&&this.storeNode(next,this.pos,nextEnd,4),this.storeNode(0,this.pos,nextEnd,isNode?8:4),this.pos=this.reducePos=nextEnd,this.score-=190}canShift(term){for(let sim=new SimulatedStack(this);;){let action=this.p.parser.stateSlot(sim.state,4)||this.p.parser.hasAction(sim.state,term);if(action==0)return!1;if(!(action&65536))return!0;sim.reduce(action)}}recoverByInsert(next){if(this.stack.length>=300)return[];let nextStates=this.p.parser.nextStates(this.state);if(nextStates.length>8||this.stack.length>=120){let best=[];for(let i=0,s2;ii2&1&&v==s2)||best.push(nextStates[i],s2)}nextStates=best}let result=[];for(let i=0;i>19,term=reduce&65535,target=this.stack.length-depth*3;if(target<0||parser2.getGoto(this.stack[target],term,!1)<0){let backup=this.findForcedReduction();if(backup==null)return!1;reduce=backup}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(reduce),!0}findForcedReduction(){let{parser:parser2}=this.p,seen=[],explore=__name2((state,depth)=>{if(!seen.includes(state))return seen.push(state),parser2.allActions(state,action=>{if(!(action&393216))if(action&65536){let rDepth=(action>>19)-depth;if(rDepth>1){let term=action&65535,target=this.stack.length-rDepth*3;if(target>=0&&parser2.getGoto(this.stack[target],term,!1)>=0)return rDepth<<19|65536|term}}else{let found=explore(action,depth+1);if(found!=null)return found}})},"explore");return explore(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:parser2}=this.p;return parser2.data[parser2.stateSlot(this.state,1)]==65535&&!parser2.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(other){if(this.state!=other.state||this.stack.length!=other.stack.length)return!1;for(let i=0;ithis.lookAhead&&(this.emitLookAhead(),this.lookAhead=lookAhead)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}};__name2(_Stack,"Stack");let Stack=_Stack;const _StackContext=class{static{__name(this,"_StackContext")}constructor(tracker,context){this.tracker=tracker,this.context=context,this.hash=tracker.strict?tracker.hash(context):0}};__name2(_StackContext,"StackContext");let StackContext=_StackContext;var Recover;(function(Recover2){Recover2[Recover2.Insert=200]="Insert",Recover2[Recover2.Delete=190]="Delete",Recover2[Recover2.Reduce=100]="Reduce",Recover2[Recover2.MaxNext=4]="MaxNext",Recover2[Recover2.MaxInsertStackDepth=300]="MaxInsertStackDepth",Recover2[Recover2.DampenInsertStackDepth=120]="DampenInsertStackDepth",Recover2[Recover2.MinBigReduction=2e3]="MinBigReduction"})(Recover||(Recover={}));const _SimulatedStack=class{static{__name(this,"_SimulatedStack")}constructor(start){this.start=start,this.state=start.state,this.stack=start.stack,this.base=this.stack.length}reduce(action){let term=action&65535,depth=action>>19;depth==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(depth-1)*3;let goto=this.start.p.parser.getGoto(this.stack[this.base-3],term,!0);this.state=goto}};__name2(_SimulatedStack,"SimulatedStack");let SimulatedStack=_SimulatedStack;const _StackBufferCursor=class _StackBufferCursor2{static{__name(this,"_StackBufferCursor")}constructor(stack,pos,index2){this.stack=stack,this.pos=pos,this.index=index2,this.buffer=stack.buffer,this.index==0&&this.maybeNext()}static create(stack,pos=stack.bufferBase+stack.buffer.length){return new _StackBufferCursor2(stack,pos,pos-stack.bufferBase)}maybeNext(){let next=this.stack.parent;next!=null&&(this.index=this.stack.bufferBase-next.bufferBase,this.stack=next,this.buffer=next.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new _StackBufferCursor2(this.stack,this.pos,this.index)}};__name2(_StackBufferCursor,"StackBufferCursor");let StackBufferCursor=_StackBufferCursor;function decodeArray(input,Type=Uint16Array){if(typeof input!="string")return input;let array=null;for(let pos=0,out=0;pos=92&&next--,next>=34&&next--;let digit=next-32;if(digit>=46&&(digit-=46,stop=!0),value+=digit,stop)break;value*=46}array?array[out++]=value:array=new Type(value)}return array}__name(decodeArray,"decodeArray"),__name2(decodeArray,"decodeArray");const _CachedToken=class{static{__name(this,"_CachedToken")}constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}};__name2(_CachedToken,"CachedToken");let CachedToken=_CachedToken;const nullToken=new CachedToken,_InputStream=class{static{__name(this,"_InputStream")}constructor(input,ranges){this.input=input,this.ranges=ranges,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=nullToken,this.rangeIndex=0,this.pos=this.chunkPos=ranges[0].from,this.range=ranges[0],this.end=ranges[ranges.length-1].to,this.readNext()}resolveOffset(offset2,assoc){let range=this.range,index2=this.rangeIndex,pos=this.pos+offset2;for(;posrange.to:pos>=range.to;){if(index2==this.ranges.length-1)return null;let next=this.ranges[++index2];pos+=next.from-range.to,range=next}return pos}clipPos(pos){if(pos>=this.range.from&&pospos)return Math.max(pos,range.from);return this.end}peek(offset2){let idx=this.chunkOff+offset2,pos,result;if(idx>=0&&idx=this.chunk2Pos&&posrange.to&&(this.chunk2=this.chunk2.slice(0,range.to-pos)),result=this.chunk2.charCodeAt(0)}}return pos>=this.token.lookAhead&&(this.token.lookAhead=pos+1),result}acceptToken(token,endOffset=0){let end=endOffset?this.resolveOffset(endOffset,-1):this.pos;if(end==null||end=this.chunk2Pos&&this.posthis.range.to?nextChunk.slice(0,this.range.to-this.pos):nextChunk,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(n2=1){for(this.chunkOff+=n2;this.pos+n2>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();n2-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=n2,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(pos,token){if(token?(this.token=token,token.start=pos,token.lookAhead=pos+1,token.value=token.extended=-1):this.token=nullToken,this.pos!=pos){if(this.pos=pos,pos==this.end)return this.setDone(),this;for(;pos=this.range.to;)this.range=this.ranges[++this.rangeIndex];pos>=this.chunkPos&&pos=this.chunkPos&&to<=this.chunkPos+this.chunk.length)return this.chunk.slice(from-this.chunkPos,to-this.chunkPos);if(from>=this.chunk2Pos&&to<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(from-this.chunk2Pos,to-this.chunk2Pos);if(from>=this.range.from&&to<=this.range.to)return this.input.read(from,to);let result="";for(let r of this.ranges){if(r.from>=to)break;r.to>from&&(result+=this.input.read(Math.max(r.from,from),Math.min(r.to,to)))}return result}};__name2(_InputStream,"InputStream");let InputStream=_InputStream;const _TokenGroup=class{static{__name(this,"_TokenGroup")}constructor(data,id){this.data=data,this.id=id}token(input,stack){let{parser:parser2}=stack.p;readToken(this.data,input,stack,this.id,parser2.data,parser2.tokenPrecTable)}};__name2(_TokenGroup,"TokenGroup");let TokenGroup=_TokenGroup;TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1,TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;function readToken(data,input,stack,group,precTable,precOffset){let state=0,groupMask=1<0){let term=data[i];if(dialect.allows(term)&&(input.token.value==-1||input.token.value==term||overrides(term,input.token.value,precTable,precOffset))){input.acceptToken(term);break}}let next=input.next,low=0,high=data[state+2];if(input.next<0&&high>low&&data[accEnd+high*3-3]==65535&&data[accEnd+high*3-3]==65535){state=data[accEnd+high*3-1];continue scan}for(;low>1,index2=accEnd+mid+(mid<<1),from=data[index2],to=data[index2+1]||65536;if(next=to)low=mid+1;else{state=data[index2+2],input.advance();continue scan}}break}}__name(readToken,"readToken"),__name2(readToken,"readToken");function findOffset(data,start,term){for(let i=start,next;(next=data[i])!=65535;i++)if(next==term)return i-start;return-1}__name(findOffset,"findOffset"),__name2(findOffset,"findOffset");function overrides(token,prev,tableData,tableOffset){let iPrev=findOffset(tableData,tableOffset,prev);return iPrev<0||findOffset(tableData,tableOffset,token)pos)&&!cursor.type.isError)return side<0?Math.max(0,Math.min(cursor.to-1,pos-25)):Math.min(tree.length,Math.max(cursor.from+1,pos+25));if(side<0?cursor.prevSibling():cursor.nextSibling())break;if(!cursor.parent())return side<0?0:tree.length}}__name(cutAt,"cutAt"),__name2(cutAt,"cutAt");const _FragmentCursor=class{static{__name(this,"_FragmentCursor")}constructor(fragments,nodeSet){this.fragments=fragments,this.nodeSet=nodeSet,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let fr=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(fr){for(this.safeFrom=fr.openStart?cutAt(fr.tree,fr.from+fr.offset,1)-fr.offset:fr.from,this.safeTo=fr.openEnd?cutAt(fr.tree,fr.to+fr.offset,-1)-fr.offset:fr.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(fr.tree),this.start.push(-fr.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(pos){if(pospos)return this.nextStart=start,null;if(next instanceof Tree){if(start==pos){if(start=Math.max(this.safeFrom,pos)&&(this.trees.push(next),this.start.push(start),this.index.push(0))}else this.index[last2]++,this.nextStart=start+next.length}}};__name2(_FragmentCursor,"FragmentCursor");let FragmentCursor=_FragmentCursor;const _TokenCache=class{static{__name(this,"_TokenCache")}constructor(parser2,stream){this.stream=stream,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=parser2.tokenizers.map(_=>new CachedToken)}getActions(stack){let actionIndex=0,main=null,{parser:parser2}=stack.p,{tokenizers}=parser2,mask=parser2.stateSlot(stack.state,3),context=stack.curContext?stack.curContext.hash:0,lookAhead=0;for(let i=0;itoken.end+25&&(lookAhead=Math.max(token.lookAhead,lookAhead)),token.value!=0)){let startIndex=actionIndex;if(token.extended>-1&&(actionIndex=this.addActions(stack,token.extended,token.end,actionIndex)),actionIndex=this.addActions(stack,token.value,token.end,actionIndex),!tokenizer.extend&&(main=token,actionIndex>startIndex))break}}for(;this.actions.length>actionIndex;)this.actions.pop();return lookAhead&&stack.setLookAhead(lookAhead),!main&&stack.pos==this.stream.end&&(main=new CachedToken,main.value=stack.p.parser.eofTerm,main.start=main.end=stack.pos,actionIndex=this.addActions(stack,main.value,main.end,actionIndex)),this.mainToken=main,this.actions}getMainToken(stack){if(this.mainToken)return this.mainToken;let main=new CachedToken,{pos,p}=stack;return main.start=pos,main.end=Math.min(pos+1,p.stream.end),main.value=pos==p.stream.end?p.parser.eofTerm:0,main}updateCachedToken(token,tokenizer,stack){let start=this.stream.clipPos(stack.pos);if(tokenizer.token(this.stream.reset(start,token),stack),token.value>-1){let{parser:parser2}=stack.p;for(let i=0;i=0&&stack.p.parser.dialect.allows(result>>1)){result&1?token.extended=result>>1:token.value=result>>1;break}}}else token.value=0,token.end=this.stream.clipPos(start+1)}putAction(action,token,end,index2){for(let i=0;iparser2.bufferLength*4?new FragmentCursor(fragments,parser2.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let stacks=this.stacks,pos=this.minStackPos,newStacks=this.stacks=[],stopped,stoppedTokens;if(this.bigReductionCount>300&&stacks.length==1){let[s2]=stacks;for(;s2.forceReduce()&&s2.stack.length&&s2.stack[s2.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let i=0;ipos)newStacks.push(stack);else{if(this.advanceStack(stack,newStacks,stacks))continue;{stopped||(stopped=[],stoppedTokens=[]),stopped.push(stack);let tok=this.tokens.getMainToken(stack);stoppedTokens.push(tok.value,tok.end)}}break}}if(!newStacks.length){let finished=stopped&&findFinished(stopped);if(finished)return this.stackToTree(finished);if(this.parser.strict)throw verbose&&stopped&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+pos);this.recovering||(this.recovering=5)}if(this.recovering&&stopped){let finished=this.stoppedAt!=null&&stopped[0].pos>this.stoppedAt?stopped[0]:this.runRecovery(stopped,stoppedTokens,newStacks);if(finished)return this.stackToTree(finished.forceAll())}if(this.recovering){let maxRemaining=this.recovering==1?1:this.recovering*3;if(newStacks.length>maxRemaining)for(newStacks.sort((a,b)=>b.score-a.score);newStacks.length>maxRemaining;)newStacks.pop();newStacks.some(s2=>s2.reducePos>pos)&&this.recovering--}else if(newStacks.length>1){outer:for(let i=0;i500&&other.buffer.length>500)if((stack.score-other.score||stack.buffer.length-other.buffer.length)>0)newStacks.splice(j--,1);else{newStacks.splice(i--,1);continue outer}}}newStacks.length>12&&newStacks.splice(12,newStacks.length-12)}this.minStackPos=newStacks[0].pos;for(let i=1;i ":"";if(this.stoppedAt!=null&&start>this.stoppedAt)return stack.forceReduce()?stack:null;if(this.fragments){let strictCx=stack.curContext&&stack.curContext.tracker.strict,cxHash=strictCx?stack.curContext.hash:0;for(let cached=this.fragments.nodeAt(start);cached;){let match2=this.parser.nodeSet.types[cached.type.id]==cached.type?parser2.getGoto(stack.state,cached.type.id):-1;if(match2>-1&&cached.length&&(!strictCx||(cached.prop(NodeProp.contextHash)||0)==cxHash))return stack.useNode(cached,match2),verbose&&console.log(base2+this.stackID(stack)+` (via reuse of ${parser2.getName(cached.type.id)})`),!0;if(!(cached instanceof Tree)||cached.children.length==0||cached.positions[0]>0)break;let inner=cached.children[0];if(inner instanceof Tree&&cached.positions[0]==0)cached=inner;else break}}let defaultReduce=parser2.stateSlot(stack.state,4);if(defaultReduce>0)return stack.reduce(defaultReduce),verbose&&console.log(base2+this.stackID(stack)+` (via always-reduce ${parser2.getName(defaultReduce&65535)})`),!0;if(stack.stack.length>=15e3)for(;stack.stack.length>9e3&&stack.forceReduce(););let actions=this.tokens.getActions(stack);for(let i=0;istart?stacks.push(localStack):split.push(localStack)}return!1}advanceFully(stack,newStacks){let pos=stack.pos;for(;;){if(!this.advanceStack(stack,null,null))return!1;if(stack.pos>pos)return pushStackDedup(stack,newStacks),!0}}runRecovery(stacks,tokens,newStacks){let finished=null,restarted=!1;for(let i=0;i ":"";if(stack.deadEnd&&(restarted||(restarted=!0,stack.restart(),verbose&&console.log(base2+this.stackID(stack)+" (restarted)"),this.advanceFully(stack,newStacks))))continue;let force=stack.split(),forceBase=base2;for(let j=0;force.forceReduce()&&j<10&&(verbose&&console.log(forceBase+this.stackID(force)+" (via force-reduce)"),!this.advanceFully(force,newStacks));j++)verbose&&(forceBase=this.stackID(force)+" -> ");for(let insert2 of stack.recoverByInsert(token))verbose&&console.log(base2+this.stackID(insert2)+" (via recover-insert)"),this.advanceFully(insert2,newStacks);this.stream.end>stack.pos?(tokenEnd==stack.pos&&(tokenEnd++,token=0),stack.recoverByDelete(token,tokenEnd),verbose&&console.log(base2+this.stackID(stack)+` (via recover-delete ${this.parser.getName(token)})`),pushStackDedup(stack,newStacks)):(!finished||finished.scorespec.topRules[r][1]),nodeProps=[];for(let i=0;i=0)setProp(next,prop,propSpec[i++]);else{let value=propSpec[i+-next];for(let j=-next;j>0;j--)setProp(propSpec[i++],prop,value);i++}}}this.nodeSet=new NodeSet(nodeNames.map((name2,i)=>NodeType.define({name:i>=this.minRepeatTerm?void 0:name2,id:i,props:nodeProps[i],top:topTerms.indexOf(i)>-1,error:i==0,skipped:spec.skippedNodes&&spec.skippedNodes.indexOf(i)>-1}))),spec.propSources&&(this.nodeSet=this.nodeSet.extend(...spec.propSources)),this.strict=!1,this.bufferLength=DefaultBufferLength;let tokenArray=decodeArray(spec.tokenData);this.context=spec.context,this.specializerSpecs=spec.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let i=0;itypeof value=="number"?new TokenGroup(tokenArray,value):value),this.topRules=spec.topRules,this.dialects=spec.dialects||{},this.dynamicPrecedences=spec.dynamicPrecedences||null,this.tokenPrecTable=spec.tokenPrec,this.termNames=spec.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(input,fragments,ranges){let parse2=new Parse(this,input,fragments,ranges);for(let w of this.wrappers)parse2=w(parse2,input,fragments,ranges);return parse2}getGoto(state,term,loose=!1){let table=this.goto;if(term>=table[0])return-1;for(let pos=table[term+1];;){let groupTag=table[pos++],last2=groupTag&1,target=table[pos++];if(last2&&loose)return target;for(let end=pos+(groupTag>>1);pos0}validAction(state,action){return!!this.allActions(state,a=>a==action?!0:null)}allActions(state,action){let deflt=this.stateSlot(state,4),result=deflt?action(deflt):void 0;for(let i=this.stateSlot(state,1);result==null;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=pair(this.data,i+2);else break;result=action(pair(this.data,i+1))}return result}nextStates(state){let result=[];for(let i=this.stateSlot(state,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=pair(this.data,i+2);else break;if(!(this.data[i+2]&1)){let value=this.data[i+1];result.some((v,i2)=>i2&1&&v==value)||result.push(this.data[i],value)}}return result}configure(config2){let copy=Object.assign(Object.create(_LRParser2.prototype),this);if(config2.props&&(copy.nodeSet=this.nodeSet.extend(...config2.props)),config2.top){let info=this.topRules[config2.top];if(!info)throw new RangeError(`Invalid top rule name ${config2.top}`);copy.top=info}return config2.tokenizers&&(copy.tokenizers=this.tokenizers.map(t2=>{let found=config2.tokenizers.find(r=>r.from==t2);return found?found.to:t2})),config2.specializers&&(copy.specializers=this.specializers.slice(),copy.specializerSpecs=this.specializerSpecs.map((s2,i)=>{let found=config2.specializers.find(r=>r.from==s2.external);if(!found)return s2;let spec=Object.assign(Object.assign({},s2),{external:found.to});return copy.specializers[i]=getSpecializer(spec),spec})),config2.contextTracker&&(copy.context=config2.contextTracker),config2.dialect&&(copy.dialect=this.parseDialect(config2.dialect)),config2.strict!=null&&(copy.strict=config2.strict),config2.wrap&&(copy.wrappers=copy.wrappers.concat(config2.wrap)),config2.bufferLength!=null&&(copy.bufferLength=config2.bufferLength),copy}hasWrappers(){return this.wrappers.length>0}getName(term){return this.termNames?this.termNames[term]:String(term<=this.maxNode&&this.nodeSet.types[term].name||term)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(term){let prec2=this.dynamicPrecedences;return prec2==null?0:prec2[term]||0}parseDialect(dialect){let values=Object.keys(this.dialects),flags=values.map(()=>!1);if(dialect)for(let part of dialect.split(" ")){let id=values.indexOf(part);id>=0&&(flags[id]=!0)}let disabled=null;for(let i=0;istopped)&&stack.p.parser.stateFlag(stack.state,2)&&(!best||best.scorespec.external(value,stack)<<1|mask}return spec.get}__name(getSpecializer,"getSpecializer"),__name2(getSpecializer,"getSpecializer");const jsonHighlighting=styleTags({String:tags.string,Number:tags.number,"True False":tags.bool,PropertyName:tags.propertyName,Null:tags.null,",":tags.separator,"[ ]":tags.squareBracket,"{ }":tags.brace}),parser=LRParser.deserialize({version:14,states:"$bOVQPOOOOQO'#Cb'#CbOnQPO'#CeOvQPO'#CjOOQO'#Cp'#CpQOQPOOOOQO'#Cg'#CgO}QPO'#CfO!SQPO'#CrOOQO,59P,59PO![QPO,59PO!aQPO'#CuOOQO,59U,59UO!iQPO,59UOVQPO,59QOqQPO'#CkO!nQPO,59^OOQO1G.k1G.kOVQPO'#ClO!vQPO,59aOOQO1G.p1G.pOOQO1G.l1G.lOOQO,59V,59VOOQO-E6i-E6iOOQO,59W,59WOOQO-E6j-E6j",stateData:"#O~OcOS~OQSORSOSSOTSOWQO]ROePO~OVXOeUO~O[[O~PVOg^O~Oh_OVfX~OVaO~OhbO[iX~O[dO~Oh_OVfa~OhbO[ia~O",goto:"!kjPPPPPPkPPkqwPPk{!RPPP!XP!ePP!hXSOR^bQWQRf_TVQ_Q`WRg`QcZRicQTOQZRQe^RhbRYQR]R",nodeNames:"\u26A0 JsonText True False Null Number String } { Object Property PropertyName ] [ Array",maxTerm:25,nodeProps:[["openedBy",7,"{",12,"["],["closedBy",8,"}",13,"]"]],propSources:[jsonHighlighting],skippedNodes:[0],repeatNodeCount:2,tokenData:"(|~RaXY!WYZ!W]^!Wpq!Wrs!]|}$u}!O$z!Q!R%T!R![&c![!]&t!}#O&y#P#Q'O#Y#Z'T#b#c'r#h#i(Z#o#p(r#q#r(w~!]Oc~~!`Wpq!]qr!]rs!xs#O!]#O#P!}#P;'S!];'S;=`$o<%lO!]~!}Oe~~#QXrs!]!P!Q!]#O#P!]#U#V!]#Y#Z!]#b#c!]#f#g!]#h#i!]#i#j#m~#pR!Q![#y!c!i#y#T#Z#y~#|R!Q![$V!c!i$V#T#Z$V~$YR!Q![$c!c!i$c#T#Z$c~$fR!Q![!]!c!i!]#T#Z!]~$rP;=`<%l!]~$zOh~~$}Q!Q!R%T!R![&c~%YRT~!O!P%c!g!h%w#X#Y%w~%fP!Q![%i~%nRT~!Q![%i!g!h%w#X#Y%w~%zR{|&T}!O&T!Q![&Z~&WP!Q![&Z~&`PT~!Q![&Z~&hST~!O!P%c!Q![&c!g!h%w#X#Y%w~&yOg~~'OO]~~'TO[~~'WP#T#U'Z~'^P#`#a'a~'dP#g#h'g~'jP#X#Y'm~'rOR~~'uP#i#j'x~'{P#`#a(O~(RP#`#a(U~(ZOS~~(^P#f#g(a~(dP#i#j(g~(jP#X#Y(m~(rOQ~~(wOW~~(|OV~",tokenizers:[0],topRules:{JsonText:[0,1]},tokenPrec:0}),jsonParseLinter=__name2(()=>view=>{try{JSON.parse(view.state.doc.toString())}catch(e){if(!(e instanceof SyntaxError))throw e;const pos=getErrorPosition(e,view.state.doc);return[{from:pos,message:e.message,severity:"error",to:pos}]}return[]},"jsonParseLinter");function getErrorPosition(error,doc2){let m;return(m=error.message.match(/at position (\d+)/))?Math.min(+m[1],doc2.length):(m=error.message.match(/at line (\d+) column (\d+)/))?Math.min(doc2.line(+m[1]).from+ +m[2]-1,doc2.length):0}__name(getErrorPosition,"getErrorPosition"),__name2(getErrorPosition,"getErrorPosition");const jsonLanguage=LRLanguage.define({name:"json",parser:parser.configure({props:[indentNodeProp.add({Object:continuedIndent({except:/^\s*\}/}),Array:continuedIndent({except:/^\s*\]/})}),foldNodeProp.add({"Object Array":foldInside})]}),languageData:{closeBrackets:{brackets:["[","{",'"']},indentOnInput:/^\s*[\}\]]$/}});function json(){return new LanguageSupport(jsonLanguage)}__name(json,"json"),__name2(json,"json");function crelt(){var elt=arguments[0];typeof elt=="string"&&(elt=document.createElement(elt));var i=1,next=arguments[1];if(next&&typeof next=="object"&&next.nodeType==null&&!Array.isArray(next)){for(var name2 in next)if(Object.prototype.hasOwnProperty.call(next,name2)){var value=next[name2];typeof value=="string"?elt.setAttribute(name2,value):value!=null&&(elt[name2]=value)}i++}for(;id.from==d.to||d.from==d.to-1&&state.doc.lineAt(d.from).to==d.from?Decoration.widget({widget:new DiagnosticWidget(d),diagnostic:d}).range(d.from):Decoration.mark({attributes:{class:"cm-lintRange cm-lintRange-"+d.severity+(d.markClass?" "+d.markClass:"")},diagnostic:d}).range(d.from,d.to)),!0);return new _LintState2(ranges,panel,findDiagnostic(ranges))}};__name2(_LintState,"LintState");let LintState=_LintState;function findDiagnostic(diagnostics,diagnostic=null,after=0){let found=null;return diagnostics.between(after,1e9,(from,to,{spec})=>{if(!(diagnostic&&spec.diagnostic!=diagnostic))return found=new SelectedDiagnostic(from,to,spec.diagnostic),!1}),found}__name(findDiagnostic,"findDiagnostic"),__name2(findDiagnostic,"findDiagnostic");function hideTooltip(tr,tooltip){let line=tr.startState.doc.lineAt(tooltip.pos);return!!(tr.effects.some(e=>e.is(setDiagnosticsEffect))||tr.changes.touchesRange(line.from,line.to))}__name(hideTooltip,"hideTooltip"),__name2(hideTooltip,"hideTooltip");function maybeEnableLint(state,effects){return state.field(lintState,!1)?effects:effects.concat(StateEffect.appendConfig.of(lintExtensions))}__name(maybeEnableLint,"maybeEnableLint"),__name2(maybeEnableLint,"maybeEnableLint");function setDiagnostics(state,diagnostics){return{effects:maybeEnableLint(state,[setDiagnosticsEffect.of(diagnostics)])}}__name(setDiagnostics,"setDiagnostics"),__name2(setDiagnostics,"setDiagnostics");const setDiagnosticsEffect=StateEffect.define(),togglePanel$1=StateEffect.define(),movePanelSelection=StateEffect.define(),lintState=StateField.define({create(){return new LintState(Decoration.none,null,null)},update(value,tr){if(tr.docChanged){let mapped=value.diagnostics.map(tr.changes),selected=null;if(value.selected){let selPos=tr.changes.mapPos(value.selected.from,1);selected=findDiagnostic(mapped,value.selected.diagnostic,selPos)||findDiagnostic(mapped,null,selPos)}value=new LintState(mapped,value.panel,selected)}for(let effect of tr.effects)effect.is(setDiagnosticsEffect)?value=LintState.init(effect.value,value.panel,tr.state):effect.is(togglePanel$1)?value=new LintState(value.diagnostics,effect.value?LintPanel.open:null,value.selected):effect.is(movePanelSelection)&&(value=new LintState(value.diagnostics,value.panel,effect.value));return value},provide:f=>[showPanel.from(f,val=>val.panel),EditorView.decorations.from(f,s2=>s2.diagnostics)]}),activeMark=Decoration.mark({class:"cm-lintRange cm-lintRange-active"});function lintTooltip(view,pos,side){let{diagnostics}=view.state.field(lintState),found=[],stackStart=2e8,stackEnd=0;diagnostics.between(pos-(side<0?1:0),pos+(side>0?1:0),(from,to,{spec})=>{pos>=from&&pos<=to&&(from==to||(pos>from||side>0)&&(posrenderDiagnostic(view,d,!1)))}__name(diagnosticsTooltip,"diagnosticsTooltip"),__name2(diagnosticsTooltip,"diagnosticsTooltip");const openLintPanel=__name2(view=>{let field=view.state.field(lintState,!1);(!field||!field.panel)&&view.dispatch({effects:maybeEnableLint(view.state,[togglePanel$1.of(!0)])});let panel=getPanel(view,LintPanel.open);return panel&&panel.dom.querySelector(".cm-panel-lint ul").focus(),!0},"openLintPanel"),closeLintPanel=__name2(view=>{let field=view.state.field(lintState,!1);return!field||!field.panel?!1:(view.dispatch({effects:togglePanel$1.of(!1)}),!0)},"closeLintPanel"),nextDiagnostic=__name2(view=>{let field=view.state.field(lintState,!1);if(!field)return!1;let sel=view.state.selection.main,next=field.diagnostics.iter(sel.to+1);return!next.value&&(next=field.diagnostics.iter(0),!next.value||next.from==sel.from&&next.to==sel.to)?!1:(view.dispatch({selection:{anchor:next.from,head:next.to},scrollIntoView:!0}),!0)},"nextDiagnostic"),lintKeymap=[{key:"Mod-Shift-m",run:openLintPanel,preventDefault:!0},{key:"F8",run:nextDiagnostic}],lintPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.timeout=-1,this.set=!0;let{delay}=view.state.facet(lintConfig);this.lintTime=Date.now()+delay,this.run=this.run.bind(this),this.timeout=setTimeout(this.run,delay)}run(){let now2=Date.now();if(now2Promise.resolve(source(this.view)))).then(annotations=>{let all=annotations.reduce((a,b)=>a.concat(b));this.view.state.doc==state.doc&&this.view.dispatch(setDiagnostics(this.view.state,all))},error=>{logException(this.view.state,error)})}}update(update){let config2=update.state.facet(lintConfig);(update.docChanged||config2!=update.startState.facet(lintConfig)||config2.needsRefresh&&config2.needsRefresh(update))&&(this.lintTime=Date.now()+config2.delay,this.set||(this.set=!0,this.timeout=setTimeout(this.run,config2.delay)))}force(){this.set&&(this.lintTime=Date.now(),this.run())}destroy(){clearTimeout(this.timeout)}}),lintConfig=Facet.define({combine(input){return Object.assign({sources:input.map(i=>i.source)},combineConfig(input.map(i=>i.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null},{needsRefresh:(a,b)=>a?b?u=>a(u)||b(u):a:b}))}});function linter(source,config2={}){return[lintConfig.of({source,config:config2}),lintPlugin,lintExtensions]}__name(linter,"linter"),__name2(linter,"linter");function assignKeys(actions){let assigned=[];if(actions)actions:for(let{name:name2}of actions){for(let i=0;ic.toLowerCase()==ch.toLowerCase())){assigned.push(ch);continue actions}}assigned.push("")}return assigned}__name(assignKeys,"assignKeys"),__name2(assignKeys,"assignKeys");function renderDiagnostic(view,diagnostic,inPanel){var _a3;let keys2=inPanel?assignKeys(diagnostic.actions):[];return crelt("li",{class:"cm-diagnostic cm-diagnostic-"+diagnostic.severity},crelt("span",{class:"cm-diagnosticText"},diagnostic.renderMessage?diagnostic.renderMessage():diagnostic.message),(_a3=diagnostic.actions)===null||_a3===void 0?void 0:_a3.map((action,i)=>{let fired=!1,click=__name2(e=>{if(e.preventDefault(),fired)return;fired=!0;let found=findDiagnostic(view.state.field(lintState).diagnostics,diagnostic);found&&action.apply(view,found.from,found.to)},"click"),{name:name2}=action,keyIndex=keys2[i]?name2.indexOf(keys2[i]):-1,nameElt=keyIndex<0?name2:[name2.slice(0,keyIndex),crelt("u",name2.slice(keyIndex,keyIndex+1)),name2.slice(keyIndex+1)];return crelt("button",{type:"button",class:"cm-diagnosticAction",onclick:click,onmousedown:click,"aria-label":` Action: ${name2}${keyIndex<0?"":` (access key "${keys2[i]})"`}.`},nameElt)}),diagnostic.source&&crelt("div",{class:"cm-diagnosticSource"},diagnostic.source))}__name(renderDiagnostic,"renderDiagnostic"),__name2(renderDiagnostic,"renderDiagnostic");const _DiagnosticWidget=class extends WidgetType{static{__name(this,"_DiagnosticWidget")}constructor(diagnostic){super(),this.diagnostic=diagnostic}eq(other){return other.diagnostic==this.diagnostic}toDOM(){return crelt("span",{class:"cm-lintPoint cm-lintPoint-"+this.diagnostic.severity})}};__name2(_DiagnosticWidget,"DiagnosticWidget");let DiagnosticWidget=_DiagnosticWidget;const _PanelItem=class{static{__name(this,"_PanelItem")}constructor(view,diagnostic){this.diagnostic=diagnostic,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=renderDiagnostic(view,diagnostic,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}};__name2(_PanelItem,"PanelItem");let PanelItem=_PanelItem;const _LintPanel=class _LintPanel2{static{__name(this,"_LintPanel")}constructor(view){this.view=view,this.items=[];let onkeydown=__name2(event=>{if(event.keyCode==27)closeLintPanel(this.view),this.view.focus();else if(event.keyCode==38||event.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(event.keyCode==40||event.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(event.keyCode==36)this.moveSelection(0);else if(event.keyCode==35)this.moveSelection(this.items.length-1);else if(event.keyCode==13)this.view.focus();else if(event.keyCode>=65&&event.keyCode<=90&&this.selectedIndex>=0){let{diagnostic}=this.items[this.selectedIndex],keys2=assignKeys(diagnostic.actions);for(let i=0;i{for(let i=0;icloseLintPanel(this.view)},"\xD7")),this.update()}get selectedIndex(){let selected=this.view.state.field(lintState).selected;if(!selected)return-1;for(let i=0;i{let found=-1,item;for(let j=i;ji&&(this.items.splice(i,found-i),needsSync=!0)),selected&&item.diagnostic==selected.diagnostic?item.dom.hasAttribute("aria-selected")||(item.dom.setAttribute("aria-selected","true"),newSelectedItem=item):item.dom.hasAttribute("aria-selected")&&item.dom.removeAttribute("aria-selected"),i++});i({sel:newSelectedItem.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel,panel})=>{sel.toppanel.bottom&&(this.list.scrollTop+=sel.bottom-panel.bottom)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),needsSync&&this.sync()}sync(){let domPos=this.list.firstChild;function rm2(){let prev=domPos;domPos=prev.nextSibling,prev.remove()}__name(rm2,"rm2"),__name2(rm2,"rm");for(let item of this.items)if(item.dom.parentNode==this.list){for(;domPos!=item.dom;)rm2();domPos=item.dom.nextSibling}else this.list.insertBefore(item.dom,domPos);for(;domPos;)rm2()}moveSelection(selectedIndex){if(this.selectedIndex<0)return;let field=this.view.state.field(lintState),selection=findDiagnostic(field.diagnostics,this.items[selectedIndex].diagnostic);selection&&this.view.dispatch({selection:{anchor:selection.from,head:selection.to},scrollIntoView:!0,effects:movePanelSelection.of(selection)})}static open(view){return new _LintPanel2(view)}};__name2(_LintPanel,"LintPanel");let LintPanel=_LintPanel;function svg(content2,attrs='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,${encodeURIComponent(content2)}')`}__name(svg,"svg"),__name2(svg,"svg");function underline(color){return svg(``,'width="6" height="3"')}__name(underline,"underline"),__name2(underline,"underline");const baseTheme$2=EditorView.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:underline("#d11")},".cm-lintRange-warning":{backgroundImage:underline("orange")},".cm-lintRange-info":{backgroundImage:underline("#999")},".cm-lintRange-hint":{backgroundImage:underline("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}}),lintExtensions=[lintState,EditorView.decorations.compute([lintState],state=>{let{selected,panel}=state.field(lintState);return!selected||!panel||selected.from==selected.to?Decoration.none:Decoration.set([activeMark.range(selected.from,selected.to)])}),hoverTooltip(lintTooltip,{hideOn:hideTooltip}),baseTheme$2],basicNormalize=typeof String.prototype.normalize=="function"?x=>x.normalize("NFKD"):x=>x,_SearchCursor=class{static{__name(this,"_SearchCursor")}constructor(text,query,from=0,to=text.length,normalize,test){this.test=test,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=text.iterRange(from,to),this.bufferStart=from,this.normalize=normalize?x=>normalize(basicNormalize(x)):basicNormalize,this.query=this.normalize(query)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return codePointAt(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let next=this.peek();if(next<0)return this.done=!0,this;let str=fromCodePoint(next),start=this.bufferStart+this.bufferPos;this.bufferPos+=codePointSize(next);let norm=this.normalize(str);for(let i=0,pos=start;;i++){let code=norm.charCodeAt(i),match2=this.match(code,pos);if(i==norm.length-1){if(match2)return this.value=match2,this;break}pos==start&&ithis.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let off2=this.matchPos-this.curLineStart;;){this.re.lastIndex=off2;let match2=this.matchPos<=this.to&&this.re.exec(this.curLine);if(match2){let from=this.curLineStart+match2.index,to=from+match2[0].length;if(this.matchPos=toCharEnd(this.text,to+(from==to?1:0)),from==this.curLineStart+this.curLine.length&&this.nextLine(),(fromthis.value.to)&&(!this.test||this.test(from,to,match2)))return this.value={from,to,match:match2},this;off2=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=to||cached.to<=from){let flat=new _FlattenedDoc2(from,doc2.sliceString(from,to));return flattened.set(doc2,flat),flat}if(cached.from==from&&cached.to==to)return cached;let{text,from:cachedFrom}=cached;return cachedFrom>from&&(text=doc2.sliceString(from,cachedFrom)+text,cachedFrom=from),cached.to=this.to?this.to:this.text.lineAt(pos).to}next(){for(;;){let off2=this.re.lastIndex=this.matchPos-this.flat.from,match2=this.re.exec(this.flat.text);if(match2&&!match2[0]&&match2.index==off2&&(this.re.lastIndex=off2+1,match2=this.re.exec(this.flat.text)),match2){let from=this.flat.from+match2.index,to=from+match2[0].length;if((this.flat.to>=this.to||match2.index+match2[0].length<=this.flat.text.length-10)&&(!this.test||this.test(from,to,match2)))return this.value={from,to,match:match2},this.matchPos=toCharEnd(this.text,to+(from==to?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=FlattenedDoc.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}};__name2(_MultilineRegExpCursor,"MultilineRegExpCursor");let MultilineRegExpCursor=_MultilineRegExpCursor;typeof Symbol<"u"&&(RegExpCursor.prototype[Symbol.iterator]=MultilineRegExpCursor.prototype[Symbol.iterator]=function(){return this});function validRegExp(source){try{return new RegExp(source,baseFlags),!0}catch{return!1}}__name(validRegExp,"validRegExp"),__name2(validRegExp,"validRegExp");function toCharEnd(text,pos){if(pos>=text.length)return pos;let line=text.lineAt(pos),next;for(;pos=56320&&next<57344;)pos++;return pos}__name(toCharEnd,"toCharEnd"),__name2(toCharEnd,"toCharEnd");function createLineDialog(view){let input=crelt("input",{class:"cm-textfield",name:"line"}),dom=crelt("form",{class:"cm-gotoLine",onkeydown:event=>{event.keyCode==27?(event.preventDefault(),view.dispatch({effects:dialogEffect.of(!1)}),view.focus()):event.keyCode==13&&(event.preventDefault(),go())},onsubmit:event=>{event.preventDefault(),go()}},crelt("label",view.state.phrase("Go to line"),": ",input)," ",crelt("button",{class:"cm-button",type:"submit"},view.state.phrase("go")));function go(){let match2=/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);if(!match2)return;let{state}=view,startLine=state.doc.lineAt(state.selection.main.head),[,sign,ln,cl,percent]=match2,col=cl?+cl.slice(1):0,line=ln?+ln:startLine.number;if(ln&&percent){let pc=line/100;sign&&(pc=pc*(sign=="-"?-1:1)+startLine.number/state.doc.lines),line=Math.round(state.doc.lines*pc)}else ln&&sign&&(line=line*(sign=="-"?-1:1)+startLine.number);let docLine=state.doc.line(Math.max(1,Math.min(state.doc.lines,line))),selection=EditorSelection.cursor(docLine.from+Math.max(0,Math.min(col,docLine.length)));view.dispatch({effects:[dialogEffect.of(!1),EditorView.scrollIntoView(selection.from,{y:"center"})],selection}),view.focus()}return __name(go,"go"),__name2(go,"go"),{dom}}__name(createLineDialog,"createLineDialog"),__name2(createLineDialog,"createLineDialog");const dialogEffect=StateEffect.define(),dialogField=StateField.define({create(){return!0},update(value,tr){for(let e of tr.effects)e.is(dialogEffect)&&(value=e.value);return value},provide:f=>showPanel.from(f,val=>val?createLineDialog:null)}),gotoLine=__name2(view=>{let panel=getPanel(view,createLineDialog);if(!panel){let effects=[dialogEffect.of(!0)];view.state.field(dialogField,!1)==null&&effects.push(StateEffect.appendConfig.of([dialogField,baseTheme$1])),view.dispatch({effects}),panel=getPanel(view,createLineDialog)}return panel&&panel.dom.querySelector("input").focus(),!0},"gotoLine"),baseTheme$1=EditorView.baseTheme({".cm-panel.cm-gotoLine":{padding:"2px 6px 4px","& label":{fontSize:"80%"}}}),defaultHighlightOptions={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},highlightConfig=Facet.define({combine(options){return combineConfig(options,defaultHighlightOptions,{highlightWordAroundCursor:(a,b)=>a||b,minSelectionLength:Math.min,maxMatches:Math.min})}});function highlightSelectionMatches(options){let ext=[defaultTheme,matchHighlighter];return options&&ext.push(highlightConfig.of(options)),ext}__name(highlightSelectionMatches,"highlightSelectionMatches"),__name2(highlightSelectionMatches,"highlightSelectionMatches");const matchDeco=Decoration.mark({class:"cm-selectionMatch"}),mainMatchDeco=Decoration.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function insideWordBoundaries(check,state,from,to){return(from==0||check(state.sliceDoc(from-1,from))!=CharCategory.Word)&&(to==state.doc.length||check(state.sliceDoc(to,to+1))!=CharCategory.Word)}__name(insideWordBoundaries,"insideWordBoundaries"),__name2(insideWordBoundaries,"insideWordBoundaries");function insideWord(check,state,from,to){return check(state.sliceDoc(from,from+1))==CharCategory.Word&&check(state.sliceDoc(to-1,to))==CharCategory.Word}__name(insideWord,"insideWord"),__name2(insideWord,"insideWord");const matchHighlighter=ViewPlugin.fromClass(class{constructor(view){this.decorations=this.getDeco(view)}update(update){(update.selectionSet||update.docChanged||update.viewportChanged)&&(this.decorations=this.getDeco(update.view))}getDeco(view){let conf=view.state.facet(highlightConfig),{state}=view,sel=state.selection;if(sel.ranges.length>1)return Decoration.none;let range=sel.main,query,check=null;if(range.empty){if(!conf.highlightWordAroundCursor)return Decoration.none;let word=state.wordAt(range.head);if(!word)return Decoration.none;check=state.charCategorizer(range.head),query=state.sliceDoc(word.from,word.to)}else{let len=range.to-range.from;if(len200)return Decoration.none;if(conf.wholeWords){if(query=state.sliceDoc(range.from,range.to),check=state.charCategorizer(range.head),!(insideWordBoundaries(check,state,range.from,range.to)&&insideWord(check,state,range.from,range.to)))return Decoration.none}else if(query=state.sliceDoc(range.from,range.to).trim(),!query)return Decoration.none}let deco=[];for(let part of view.visibleRanges){let cursor=new SearchCursor(state.doc,query,part.from,part.to);for(;!cursor.next().done;){let{from,to}=cursor.value;if((!check||insideWordBoundaries(check,state,from,to))&&(range.empty&&from<=range.from&&to>=range.to?deco.push(mainMatchDeco.range(from,to)):(from>=range.to||to<=range.from)&&deco.push(matchDeco.range(from,to)),deco.length>conf.maxMatches))return Decoration.none}}return Decoration.set(deco)}},{decorations:v=>v.decorations}),defaultTheme=EditorView.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),selectWord=__name2(({state,dispatch})=>{let{selection}=state,newSel=EditorSelection.create(selection.ranges.map(range=>state.wordAt(range.head)||EditorSelection.cursor(range.head)),selection.mainIndex);return newSel.eq(selection)?!1:(dispatch(state.update({selection:newSel})),!0)},"selectWord");function findNextOccurrence(state,query){let{main,ranges}=state.selection,word=state.wordAt(main.head),fullWord=word&&word.from==main.from&&word.to==main.to;for(let cycled=!1,cursor=new SearchCursor(state.doc,query,ranges[ranges.length-1].to);;)if(cursor.next(),cursor.done){if(cycled)return null;cursor=new SearchCursor(state.doc,query,0,Math.max(0,ranges[ranges.length-1].from-1)),cycled=!0}else{if(cycled&&ranges.some(r=>r.from==cursor.value.from))continue;if(fullWord){let word2=state.wordAt(cursor.value.from);if(!word2||word2.from!=cursor.value.from||word2.to!=cursor.value.to)continue}return cursor.value}}__name(findNextOccurrence,"findNextOccurrence"),__name2(findNextOccurrence,"findNextOccurrence");const selectNextOccurrence=__name2(({state,dispatch})=>{let{ranges}=state.selection;if(ranges.some(sel=>sel.from===sel.to))return selectWord({state,dispatch});let searchedText=state.sliceDoc(ranges[0].from,ranges[0].to);if(state.selection.ranges.some(r=>state.sliceDoc(r.from,r.to)!=searchedText))return!1;let range=findNextOccurrence(state,searchedText);return range?(dispatch(state.update({selection:state.selection.addRange(EditorSelection.range(range.from,range.to),!1),effects:EditorView.scrollIntoView(range.to)})),!0):!1},"selectNextOccurrence"),searchConfigFacet=Facet.define({combine(configs){return combineConfig(configs,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:view=>new SearchPanel(view),scrollToMatch:range=>EditorView.scrollIntoView(range)})}}),_SearchQuery=class{static{__name(this,"_SearchQuery")}constructor(config2){this.search=config2.search,this.caseSensitive=!!config2.caseSensitive,this.literal=!!config2.literal,this.regexp=!!config2.regexp,this.replace=config2.replace||"",this.valid=!!this.search&&(!this.regexp||validRegExp(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!config2.wholeWord}unquote(text){return this.literal?text:text.replace(/\\([nrt\\])/g,(_,ch)=>ch=="n"?` -`:ch=="r"?"\r":ch=="t"?" ":"\\")}eq(other){return this.search==other.search&&this.replace==other.replace&&this.caseSensitive==other.caseSensitive&&this.regexp==other.regexp&&this.wholeWord==other.wholeWord}create(){return this.regexp?new RegExpQuery(this):new StringQuery(this)}getCursor(state,from=0,to){let st=state.doc?state:EditorState.create({doc:state});return to==null&&(to=st.doc.length),this.regexp?regexpCursor(this,st,from,to):stringCursor(this,st,from,to)}};__name2(_SearchQuery,"SearchQuery");let SearchQuery=_SearchQuery;const _QueryType=class{static{__name(this,"_QueryType")}constructor(spec){this.spec=spec}};__name2(_QueryType,"QueryType");let QueryType=_QueryType;function stringCursor(spec,state,from,to){return new SearchCursor(state.doc,spec.unquoted,from,to,spec.caseSensitive?void 0:x=>x.toLowerCase(),spec.wholeWord?stringWordTest(state.doc,state.charCategorizer(state.selection.main.head)):void 0)}__name(stringCursor,"stringCursor"),__name2(stringCursor,"stringCursor");function stringWordTest(doc2,categorizer){return(from,to,buf,bufPos)=>((bufPos>from||bufPos+buf.length=limit2)return null;ranges.push(cursor.value)}return ranges}highlight(state,from,to,add2){let cursor=stringCursor(this.spec,state,Math.max(0,from-this.spec.unquoted.length),Math.min(to+this.spec.unquoted.length,state.doc.length));for(;!cursor.next().done;)add2(cursor.value.from,cursor.value.to)}};__name2(_StringQuery,"StringQuery");let StringQuery=_StringQuery;function regexpCursor(spec,state,from,to){return new RegExpCursor(state.doc,spec.search,{ignoreCase:!spec.caseSensitive,test:spec.wholeWord?regexpWordTest(state.charCategorizer(state.selection.main.head)):void 0},from,to)}__name(regexpCursor,"regexpCursor"),__name2(regexpCursor,"regexpCursor");function charBefore(str,index2){return str.slice(findClusterBreak(str,index2,!1),index2)}__name(charBefore,"charBefore"),__name2(charBefore,"charBefore");function charAfter(str,index2){return str.slice(index2,findClusterBreak(str,index2))}__name(charAfter,"charAfter"),__name2(charAfter,"charAfter");function regexpWordTest(categorizer){return(_from,_to,match2)=>!match2[0].length||(categorizer(charBefore(match2.input,match2.index))!=CharCategory.Word||categorizer(charAfter(match2.input,match2.index))!=CharCategory.Word)&&(categorizer(charAfter(match2.input,match2.index+match2[0].length))!=CharCategory.Word||categorizer(charBefore(match2.input,match2.index+match2[0].length))!=CharCategory.Word)}__name(regexpWordTest,"regexpWordTest"),__name2(regexpWordTest,"regexpWordTest");const _RegExpQuery=class extends QueryType{static{__name(this,"_RegExpQuery")}nextMatch(state,curFrom,curTo){let cursor=regexpCursor(this.spec,state,curTo,state.doc.length).next();return cursor.done&&(cursor=regexpCursor(this.spec,state,0,curFrom).next()),cursor.done?null:cursor.value}prevMatchInRange(state,from,to){for(let size=1;;size++){let start=Math.max(from,to-size*1e4),cursor=regexpCursor(this.spec,state,start,to),range=null;for(;!cursor.next().done;)range=cursor.value;if(range&&(start==from||range.from>start+10))return range;if(start==from)return null}}prevMatch(state,curFrom,curTo){return this.prevMatchInRange(state,0,curFrom)||this.prevMatchInRange(state,curTo,state.doc.length)}getReplacement(result){return this.spec.unquote(this.spec.replace.replace(/\$([$&\d+])/g,(m,i)=>i=="$"?"$":i=="&"?result.match[0]:i!="0"&&+i=limit2)return null;ranges.push(cursor.value)}return ranges}highlight(state,from,to,add2){let cursor=regexpCursor(this.spec,state,Math.max(0,from-250),Math.min(to+250,state.doc.length));for(;!cursor.next().done;)add2(cursor.value.from,cursor.value.to)}};__name2(_RegExpQuery,"RegExpQuery");let RegExpQuery=_RegExpQuery;const setSearchQuery=StateEffect.define(),togglePanel=StateEffect.define(),searchState=StateField.define({create(state){return new SearchState(defaultQuery(state).create(),null)},update(value,tr){for(let effect of tr.effects)effect.is(setSearchQuery)?value=new SearchState(effect.value.create(),value.panel):effect.is(togglePanel)&&(value=new SearchState(value.query,effect.value?createSearchPanel:null));return value},provide:f=>showPanel.from(f,val=>val.panel)}),_SearchState=class{static{__name(this,"_SearchState")}constructor(query,panel){this.query=query,this.panel=panel}};__name2(_SearchState,"SearchState");let SearchState=_SearchState;const matchMark=Decoration.mark({class:"cm-searchMatch"}),selectedMatchMark=Decoration.mark({class:"cm-searchMatch cm-searchMatch-selected"}),searchHighlighter=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.decorations=this.highlight(view.state.field(searchState))}update(update){let state=update.state.field(searchState);(state!=update.startState.field(searchState)||update.docChanged||update.selectionSet||update.viewportChanged)&&(this.decorations=this.highlight(state))}highlight({query,panel}){if(!panel||!query.spec.valid)return Decoration.none;let{view}=this,builder=new RangeSetBuilder;for(let i=0,ranges=view.visibleRanges,l2=ranges.length;iranges[i+1].from-2*250;)to=ranges[++i].to;query.highlight(view.state,from,to,(from2,to2)=>{let selected=view.state.selection.ranges.some(r=>r.from==from2&&r.to==to2);builder.add(from2,to2,selected?selectedMatchMark:matchMark)})}return builder.finish()}},{decorations:v=>v.decorations});function searchCommand(f){return view=>{let state=view.state.field(searchState,!1);return state&&state.query.spec.valid?f(view,state):openSearchPanel(view)}}__name(searchCommand,"searchCommand"),__name2(searchCommand,"searchCommand");const findNext=searchCommand((view,{query})=>{let{to}=view.state.selection.main,next=query.nextMatch(view.state,to,to);if(!next)return!1;let selection=EditorSelection.single(next.from,next.to),config2=view.state.facet(searchConfigFacet);return view.dispatch({selection,effects:[announceMatch(view,next),config2.scrollToMatch(selection.main,view)],userEvent:"select.search"}),selectSearchInput(view),!0}),findPrevious=searchCommand((view,{query})=>{let{state}=view,{from}=state.selection.main,prev=query.prevMatch(state,from,from);if(!prev)return!1;let selection=EditorSelection.single(prev.from,prev.to),config2=view.state.facet(searchConfigFacet);return view.dispatch({selection,effects:[announceMatch(view,prev),config2.scrollToMatch(selection.main,view)],userEvent:"select.search"}),selectSearchInput(view),!0}),selectMatches=searchCommand((view,{query})=>{let ranges=query.matchAll(view.state,1e3);return!ranges||!ranges.length?!1:(view.dispatch({selection:EditorSelection.create(ranges.map(r=>EditorSelection.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),selectSelectionMatches=__name2(({state,dispatch})=>{let sel=state.selection;if(sel.ranges.length>1||sel.main.empty)return!1;let{from,to}=sel.main,ranges=[],main=0;for(let cur2=new SearchCursor(state.doc,state.sliceDoc(from,to));!cur2.next().done;){if(ranges.length>1e3)return!1;cur2.value.from==from&&(main=ranges.length),ranges.push(EditorSelection.range(cur2.value.from,cur2.value.to))}return dispatch(state.update({selection:EditorSelection.create(ranges,main),userEvent:"select.search.matches"})),!0},"selectSelectionMatches"),replaceNext=searchCommand((view,{query})=>{let{state}=view,{from,to}=state.selection.main;if(state.readOnly)return!1;let next=query.nextMatch(state,from,from);if(!next)return!1;let changes=[],selection,replacement,effects=[];if(next.from==from&&next.to==to&&(replacement=state.toText(query.getReplacement(next)),changes.push({from:next.from,to:next.to,insert:replacement}),next=query.nextMatch(state,next.from,next.to),effects.push(EditorView.announce.of(state.phrase("replaced match on line $",state.doc.lineAt(from).number)+"."))),next){let off2=changes.length==0||changes[0].from>=next.to?0:next.to-next.from-replacement.length;selection=EditorSelection.single(next.from-off2,next.to-off2),effects.push(announceMatch(view,next)),effects.push(state.facet(searchConfigFacet).scrollToMatch(selection.main,view))}return view.dispatch({changes,selection,effects,userEvent:"input.replace"}),!0}),replaceAll=searchCommand((view,{query})=>{if(view.state.readOnly)return!1;let changes=query.matchAll(view.state,1e9).map(match2=>{let{from,to}=match2;return{from,to,insert:query.getReplacement(match2)}});if(!changes.length)return!1;let announceText=view.state.phrase("replaced $ matches",changes.length)+".";return view.dispatch({changes,effects:EditorView.announce.of(announceText),userEvent:"input.replace.all"}),!0});function createSearchPanel(view){return view.state.facet(searchConfigFacet).createPanel(view)}__name(createSearchPanel,"createSearchPanel"),__name2(createSearchPanel,"createSearchPanel");function defaultQuery(state,fallback){var _a3,_b2,_c2,_d,_e;let sel=state.selection.main,selText=sel.empty||sel.to>sel.from+100?"":state.sliceDoc(sel.from,sel.to);if(fallback&&!selText)return fallback;let config2=state.facet(searchConfigFacet);return new SearchQuery({search:((_a3=fallback?.literal)!==null&&_a3!==void 0?_a3:config2.literal)?selText:selText.replace(/\n/g,"\\n"),caseSensitive:(_b2=fallback?.caseSensitive)!==null&&_b2!==void 0?_b2:config2.caseSensitive,literal:(_c2=fallback?.literal)!==null&&_c2!==void 0?_c2:config2.literal,regexp:(_d=fallback?.regexp)!==null&&_d!==void 0?_d:config2.regexp,wholeWord:(_e=fallback?.wholeWord)!==null&&_e!==void 0?_e:config2.wholeWord})}__name(defaultQuery,"defaultQuery"),__name2(defaultQuery,"defaultQuery");function getSearchInput(view){let panel=getPanel(view,createSearchPanel);return panel&&panel.dom.querySelector("[main-field]")}__name(getSearchInput,"getSearchInput"),__name2(getSearchInput,"getSearchInput");function selectSearchInput(view){let input=getSearchInput(view);input&&input==view.root.activeElement&&input.select()}__name(selectSearchInput,"selectSearchInput"),__name2(selectSearchInput,"selectSearchInput");const openSearchPanel=__name2(view=>{let state=view.state.field(searchState,!1);if(state&&state.panel){let searchInput=getSearchInput(view);if(searchInput&&searchInput!=view.root.activeElement){let query=defaultQuery(view.state,state.query.spec);query.valid&&view.dispatch({effects:setSearchQuery.of(query)}),searchInput.focus(),searchInput.select()}}else view.dispatch({effects:[togglePanel.of(!0),state?setSearchQuery.of(defaultQuery(view.state,state.query.spec)):StateEffect.appendConfig.of(searchExtensions)]});return!0},"openSearchPanel"),closeSearchPanel=__name2(view=>{let state=view.state.field(searchState,!1);if(!state||!state.panel)return!1;let panel=getPanel(view,createSearchPanel);return panel&&panel.dom.contains(view.root.activeElement)&&view.focus(),view.dispatch({effects:togglePanel.of(!1)}),!0},"closeSearchPanel"),searchKeymap=[{key:"Mod-f",run:openSearchPanel,scope:"editor search-panel"},{key:"F3",run:findNext,shift:findPrevious,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:findNext,shift:findPrevious,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:closeSearchPanel,scope:"editor search-panel"},{key:"Mod-Shift-l",run:selectSelectionMatches},{key:"Alt-g",run:gotoLine},{key:"Mod-d",run:selectNextOccurrence,preventDefault:!0}],_SearchPanel=class{static{__name(this,"_SearchPanel")}constructor(view){this.view=view;let query=this.query=view.state.field(searchState).query.spec;this.commit=this.commit.bind(this),this.searchField=crelt("input",{value:query.search,placeholder:phrase(view,"Find"),"aria-label":phrase(view,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=crelt("input",{value:query.replace,placeholder:phrase(view,"Replace"),"aria-label":phrase(view,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=crelt("input",{type:"checkbox",name:"case",form:"",checked:query.caseSensitive,onchange:this.commit}),this.reField=crelt("input",{type:"checkbox",name:"re",form:"",checked:query.regexp,onchange:this.commit}),this.wordField=crelt("input",{type:"checkbox",name:"word",form:"",checked:query.wholeWord,onchange:this.commit});function button(name2,onclick,content2){return crelt("button",{class:"cm-button",name:name2,onclick,type:"button"},content2)}__name(button,"button"),__name2(button,"button"),this.dom=crelt("div",{onkeydown:e=>this.keydown(e),class:"cm-search"},[this.searchField,button("next",()=>findNext(view),[phrase(view,"next")]),button("prev",()=>findPrevious(view),[phrase(view,"previous")]),button("select",()=>selectMatches(view),[phrase(view,"all")]),crelt("label",null,[this.caseField,phrase(view,"match case")]),crelt("label",null,[this.reField,phrase(view,"regexp")]),crelt("label",null,[this.wordField,phrase(view,"by word")]),...view.state.readOnly?[]:[crelt("br"),this.replaceField,button("replace",()=>replaceNext(view),[phrase(view,"replace")]),button("replaceAll",()=>replaceAll(view),[phrase(view,"replace all")])],crelt("button",{name:"close",onclick:()=>closeSearchPanel(view),"aria-label":phrase(view,"close"),type:"button"},["\xD7"])])}commit(){let query=new SearchQuery({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});query.eq(this.query)||(this.query=query,this.view.dispatch({effects:setSearchQuery.of(query)}))}keydown(e){runScopeHandlers(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?findPrevious:findNext)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),replaceNext(this.view))}update(update){for(let tr of update.transactions)for(let effect of tr.effects)effect.is(setSearchQuery)&&!effect.value.eq(this.query)&&this.setQuery(effect.value)}setQuery(query){this.query=query,this.searchField.value=query.search,this.replaceField.value=query.replace,this.caseField.checked=query.caseSensitive,this.reField.checked=query.regexp,this.wordField.checked=query.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(searchConfigFacet).top}};__name2(_SearchPanel,"SearchPanel");let SearchPanel=_SearchPanel;function phrase(view,phrase2){return view.state.phrase(phrase2)}__name(phrase,"phrase"),__name2(phrase,"phrase");const AnnounceMargin=30,Break=/[\s\.,:;?!]/;function announceMatch(view,{from,to}){let line=view.state.doc.lineAt(from),lineEnd=view.state.doc.lineAt(to).to,start=Math.max(line.from,from-AnnounceMargin),end=Math.min(lineEnd,to+AnnounceMargin),text=view.state.sliceDoc(start,end);if(start!=line.from){for(let i=0;itext.length-AnnounceMargin;i--)if(!Break.test(text[i-1])&&Break.test(text[i])){text=text.slice(0,i);break}}return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${line.number}.`)}__name(announceMatch,"announceMatch"),__name2(announceMatch,"announceMatch");const baseTheme=EditorView.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),searchExtensions=[searchState,Prec.lowest(searchHighlighter),baseTheme],basicSetup=(()=>[lineNumbers(),highlightActiveLineGutter(),highlightSpecialChars(),history(),foldGutter(),drawSelection(),dropCursor(),EditorState.allowMultipleSelections.of(!0),indentOnInput(),syntaxHighlighting(defaultHighlightStyle,{fallback:!0}),bracketMatching(),closeBrackets(),autocompletion(),rectangularSelection(),crosshairCursor(),highlightActiveLine(),highlightSelectionMatches(),keymap.of([...closeBracketsKeymap,...defaultKeymap,...searchKeymap,...historyKeymap,...foldKeymap,...completionKeymap,...lintKeymap])])();var PipsMode;(function(PipsMode2){PipsMode2.Range="range",PipsMode2.Steps="steps",PipsMode2.Positions="positions",PipsMode2.Count="count",PipsMode2.Values="values"})(PipsMode||(PipsMode={}));var PipsType;(function(PipsType2){PipsType2[PipsType2.None=-1]="None",PipsType2[PipsType2.NoValue=0]="NoValue",PipsType2[PipsType2.LargeValue=1]="LargeValue",PipsType2[PipsType2.SmallValue=2]="SmallValue"})(PipsType||(PipsType={}));function isValidFormatter(entry){return isValidPartialFormatter(entry)&&typeof entry.from=="function"}__name(isValidFormatter,"isValidFormatter"),__name2(isValidFormatter,"isValidFormatter");function isValidPartialFormatter(entry){return typeof entry=="object"&&typeof entry.to=="function"}__name(isValidPartialFormatter,"isValidPartialFormatter"),__name2(isValidPartialFormatter,"isValidPartialFormatter");function removeElement(el){el.parentElement.removeChild(el)}__name(removeElement,"removeElement"),__name2(removeElement,"removeElement");function isSet(value){return value!=null}__name(isSet,"isSet"),__name2(isSet,"isSet");function preventDefault(e){e.preventDefault()}__name(preventDefault,"preventDefault"),__name2(preventDefault,"preventDefault");function unique(array){return array.filter(function(a){return this[a]?!1:this[a]=!0},{})}__name(unique,"unique"),__name2(unique,"unique");function closest(value,to){return Math.round(value/to)*to}__name(closest,"closest"),__name2(closest,"closest");function offset(elem,orientation){var rect=elem.getBoundingClientRect(),doc2=elem.ownerDocument,docElem=doc2.documentElement,pageOffset=getPageOffset(doc2);return/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)&&(pageOffset.x=0),orientation?rect.top+pageOffset.y-docElem.clientTop:rect.left+pageOffset.x-docElem.clientLeft}__name(offset,"offset"),__name2(offset,"offset");function isNumeric(a){return typeof a=="number"&&!isNaN(a)&&isFinite(a)}__name(isNumeric,"isNumeric"),__name2(isNumeric,"isNumeric");function addClassFor(element,className,duration){duration>0&&(addClass(element,className),setTimeout(function(){removeClass(element,className)},duration))}__name(addClassFor,"addClassFor"),__name2(addClassFor,"addClassFor");function limit(a){return Math.max(Math.min(a,100),0)}__name(limit,"limit"),__name2(limit,"limit");function asArray(a){return Array.isArray(a)?a:[a]}__name(asArray,"asArray"),__name2(asArray,"asArray");function countDecimals(numStr){numStr=String(numStr);var pieces=numStr.split(".");return pieces.length>1?pieces[1].length:0}__name(countDecimals,"countDecimals"),__name2(countDecimals,"countDecimals");function addClass(el,className){el.classList&&!/\s/.test(className)?el.classList.add(className):el.className+=" "+className}__name(addClass,"addClass"),__name2(addClass,"addClass");function removeClass(el,className){el.classList&&!/\s/.test(className)?el.classList.remove(className):el.className=el.className.replace(new RegExp("(^|\\b)"+className.split(" ").join("|")+"(\\b|$)","gi")," ")}__name(removeClass,"removeClass"),__name2(removeClass,"removeClass");function hasClass(el,className){return el.classList?el.classList.contains(className):new RegExp("\\b"+className+"\\b").test(el.className)}__name(hasClass,"hasClass"),__name2(hasClass,"hasClass");function getPageOffset(doc2){var supportPageOffset=window.pageXOffset!==void 0,isCSS1Compat=(doc2.compatMode||"")==="CSS1Compat",x=supportPageOffset?window.pageXOffset:isCSS1Compat?doc2.documentElement.scrollLeft:doc2.body.scrollLeft,y=supportPageOffset?window.pageYOffset:isCSS1Compat?doc2.documentElement.scrollTop:doc2.body.scrollTop;return{x,y}}__name(getPageOffset,"getPageOffset"),__name2(getPageOffset,"getPageOffset");function getActions(){return window.navigator.pointerEnabled?{start:"pointerdown",move:"pointermove",end:"pointerup"}:window.navigator.msPointerEnabled?{start:"MSPointerDown",move:"MSPointerMove",end:"MSPointerUp"}:{start:"mousedown touchstart",move:"mousemove touchmove",end:"mouseup touchend"}}__name(getActions,"getActions"),__name2(getActions,"getActions");function getSupportsPassive(){var supportsPassive=!1;try{var opts=Object.defineProperty({},"passive",{get:function(){supportsPassive=!0}});window.addEventListener("test",null,opts)}catch{}return supportsPassive}__name(getSupportsPassive,"getSupportsPassive"),__name2(getSupportsPassive,"getSupportsPassive");function getSupportsTouchActionNone(){return window.CSS&&CSS.supports&&CSS.supports("touch-action","none")}__name(getSupportsTouchActionNone,"getSupportsTouchActionNone"),__name2(getSupportsTouchActionNone,"getSupportsTouchActionNone");function subRangeRatio(pa,pb){return 100/(pb-pa)}__name(subRangeRatio,"subRangeRatio"),__name2(subRangeRatio,"subRangeRatio");function fromPercentage(range,value,startRange){return value*100/(range[startRange+1]-range[startRange])}__name(fromPercentage,"fromPercentage"),__name2(fromPercentage,"fromPercentage");function toPercentage(range,value){return fromPercentage(range,range[0]<0?value+Math.abs(range[0]):value-range[0],0)}__name(toPercentage,"toPercentage"),__name2(toPercentage,"toPercentage");function isPercentage(range,value){return value*(range[1]-range[0])/100+range[0]}__name(isPercentage,"isPercentage"),__name2(isPercentage,"isPercentage");function getJ(value,arr){for(var j=1;value>=arr[j];)j+=1;return j}__name(getJ,"getJ"),__name2(getJ,"getJ");function toStepping(xVal,xPct,value){if(value>=xVal.slice(-1)[0])return 100;var j=getJ(value,xVal),va=xVal[j-1],vb=xVal[j],pa=xPct[j-1],pb=xPct[j];return pa+toPercentage([va,vb],value)/subRangeRatio(pa,pb)}__name(toStepping,"toStepping"),__name2(toStepping,"toStepping");function fromStepping(xVal,xPct,value){if(value>=100)return xVal.slice(-1)[0];var j=getJ(value,xPct),va=xVal[j-1],vb=xVal[j],pa=xPct[j-1],pb=xPct[j];return isPercentage([va,vb],(value-pa)*subRangeRatio(pa,pb))}__name(fromStepping,"fromStepping"),__name2(fromStepping,"fromStepping");function getStep(xPct,xSteps,snap,value){if(value===100)return value;var j=getJ(value,xPct),a=xPct[j-1],b=xPct[j];return snap?value-a>(b-a)/2?b:a:xSteps[j-1]?xPct[j-1]+closest(value-xPct[j-1],xSteps[j-1]):value}__name(getStep,"getStep"),__name2(getStep,"getStep");var Spectrum=function(){function Spectrum2(entry,snap,singleStep){this.xPct=[],this.xVal=[],this.xSteps=[],this.xNumSteps=[],this.xHighestCompleteStep=[],this.xSteps=[singleStep||!1],this.xNumSteps=[!1],this.snap=snap;var index2,ordered=[];for(Object.keys(entry).forEach(function(index3){ordered.push([asArray(entry[index3]),index3])}),ordered.sort(function(a,b){return a[0][0]-b[0][0]}),index2=0;index2this.xPct[xPct_index+1];)xPct_index++;else value===this.xPct[this.xPct.length-1]&&(xPct_index=this.xPct.length-2);!direction&&value===this.xPct[xPct_index+1]&&xPct_index++,distances===null&&(distances=[]);var start_factor,rest_factor=1,rest_rel_distance=distances[xPct_index],range_pct=0,rel_range_distance=0,abs_distance_counter=0,range_counter=0;for(direction?start_factor=(value-this.xPct[xPct_index])/(this.xPct[xPct_index+1]-this.xPct[xPct_index]):start_factor=(this.xPct[xPct_index+1]-value)/(this.xPct[xPct_index+1]-this.xPct[xPct_index]);rest_rel_distance>0;)range_pct=this.xPct[xPct_index+1+range_counter]-this.xPct[xPct_index+range_counter],distances[xPct_index+range_counter]*rest_factor+100-start_factor*100>100?(rel_range_distance=range_pct*start_factor,rest_factor=(rest_rel_distance-100*start_factor)/distances[xPct_index+range_counter],start_factor=1):(rel_range_distance=distances[xPct_index+range_counter]*range_pct/100*rest_factor,rest_factor=0),direction?(abs_distance_counter=abs_distance_counter-rel_range_distance,this.xPct.length+range_counter>=1&&range_counter--):(abs_distance_counter=abs_distance_counter+rel_range_distance,this.xPct.length-range_counter>=1&&range_counter++),rest_rel_distance=distances[xPct_index+range_counter]*rest_factor;return value+abs_distance_counter},Spectrum2.prototype.toStepping=function(value){return value=toStepping(this.xVal,this.xPct,value),value},Spectrum2.prototype.fromStepping=function(value){return fromStepping(this.xVal,this.xPct,value)},Spectrum2.prototype.getStep=function(value){return value=getStep(this.xPct,this.xSteps,this.snap,value),value},Spectrum2.prototype.getDefaultStep=function(value,isDown,size){var j=getJ(value,this.xPct);return(value===100||isDown&&value===this.xPct[j-1])&&(j=Math.max(j-1,1)),(this.xVal[j]-this.xVal[j-1])/size},Spectrum2.prototype.getNearbySteps=function(value){var j=getJ(value,this.xPct);return{stepBefore:{startValue:this.xVal[j-2],step:this.xNumSteps[j-2],highestStep:this.xHighestCompleteStep[j-2]},thisStep:{startValue:this.xVal[j-1],step:this.xNumSteps[j-1],highestStep:this.xHighestCompleteStep[j-1]},stepAfter:{startValue:this.xVal[j],step:this.xNumSteps[j],highestStep:this.xHighestCompleteStep[j]}}},Spectrum2.prototype.countStepDecimals=function(){var stepDecimals=this.xNumSteps.map(countDecimals);return Math.max.apply(null,stepDecimals)},Spectrum2.prototype.hasNoSize=function(){return this.xVal[0]===this.xVal[this.xVal.length-1]},Spectrum2.prototype.convert=function(value){return this.getStep(this.toStepping(value))},Spectrum2.prototype.handleEntryPoint=function(index2,value){var percentage;if(index2==="min"?percentage=0:index2==="max"?percentage=100:percentage=parseFloat(index2),!isNumeric(percentage)||!isNumeric(value[0]))throw new Error("noUiSlider: 'range' value isn't numeric.");this.xPct.push(percentage),this.xVal.push(value[0]);var value1=Number(value[1]);percentage?this.xSteps.push(isNaN(value1)?!1:value1):isNaN(value1)||(this.xSteps[0]=value1),this.xHighestCompleteStep.push(0)},Spectrum2.prototype.handleStepPoint=function(i,n2){if(n2){if(this.xVal[i]===this.xVal[i+1]){this.xSteps[i]=this.xHighestCompleteStep[i]=this.xVal[i];return}this.xSteps[i]=fromPercentage([this.xVal[i],this.xVal[i+1]],n2,0)/subRangeRatio(this.xPct[i],this.xPct[i+1]);var totalSteps=(this.xVal[i+1]-this.xVal[i])/this.xNumSteps[i],highestStep=Math.ceil(Number(totalSteps.toFixed(3))-1),step=this.xVal[i]+this.xNumSteps[i]*highestStep;this.xHighestCompleteStep[i]=step}},Spectrum2}(),defaultFormatter={to:function(value){return value===void 0?"":value.toFixed(2)},from:Number},cssClasses={target:"target",base:"base",origin:"origin",handle:"handle",handleLower:"handle-lower",handleUpper:"handle-upper",touchArea:"touch-area",horizontal:"horizontal",vertical:"vertical",background:"background",connect:"connect",connects:"connects",ltr:"ltr",rtl:"rtl",textDirectionLtr:"txt-dir-ltr",textDirectionRtl:"txt-dir-rtl",draggable:"draggable",drag:"state-drag",tap:"state-tap",active:"active",tooltip:"tooltip",pips:"pips",pipsHorizontal:"pips-horizontal",pipsVertical:"pips-vertical",marker:"marker",markerHorizontal:"marker-horizontal",markerVertical:"marker-vertical",markerNormal:"marker-normal",markerLarge:"marker-large",markerSub:"marker-sub",value:"value",valueHorizontal:"value-horizontal",valueVertical:"value-vertical",valueNormal:"value-normal",valueLarge:"value-large",valueSub:"value-sub"},INTERNAL_EVENT_NS={tooltips:".__tooltips",aria:".__aria"};function testStep(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'step' is not numeric.");parsed.singleStep=entry}__name(testStep,"testStep"),__name2(testStep,"testStep");function testKeyboardPageMultiplier(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'keyboardPageMultiplier' is not numeric.");parsed.keyboardPageMultiplier=entry}__name(testKeyboardPageMultiplier,"testKeyboardPageMultiplier"),__name2(testKeyboardPageMultiplier,"testKeyboardPageMultiplier");function testKeyboardMultiplier(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'keyboardMultiplier' is not numeric.");parsed.keyboardMultiplier=entry}__name(testKeyboardMultiplier,"testKeyboardMultiplier"),__name2(testKeyboardMultiplier,"testKeyboardMultiplier");function testKeyboardDefaultStep(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'keyboardDefaultStep' is not numeric.");parsed.keyboardDefaultStep=entry}__name(testKeyboardDefaultStep,"testKeyboardDefaultStep"),__name2(testKeyboardDefaultStep,"testKeyboardDefaultStep");function testRange(parsed,entry){if(typeof entry!="object"||Array.isArray(entry))throw new Error("noUiSlider: 'range' is not an object.");if(entry.min===void 0||entry.max===void 0)throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");parsed.spectrum=new Spectrum(entry,parsed.snap||!1,parsed.singleStep)}__name(testRange,"testRange"),__name2(testRange,"testRange");function testStart(parsed,entry){if(entry=asArray(entry),!Array.isArray(entry)||!entry.length)throw new Error("noUiSlider: 'start' option is incorrect.");parsed.handles=entry.length,parsed.start=entry}__name(testStart,"testStart"),__name2(testStart,"testStart");function testSnap(parsed,entry){if(typeof entry!="boolean")throw new Error("noUiSlider: 'snap' option must be a boolean.");parsed.snap=entry}__name(testSnap,"testSnap"),__name2(testSnap,"testSnap");function testAnimate(parsed,entry){if(typeof entry!="boolean")throw new Error("noUiSlider: 'animate' option must be a boolean.");parsed.animate=entry}__name(testAnimate,"testAnimate"),__name2(testAnimate,"testAnimate");function testAnimationDuration(parsed,entry){if(typeof entry!="number")throw new Error("noUiSlider: 'animationDuration' option must be a number.");parsed.animationDuration=entry}__name(testAnimationDuration,"testAnimationDuration"),__name2(testAnimationDuration,"testAnimationDuration");function testConnect(parsed,entry){var connect=[!1],i;if(entry==="lower"?entry=[!0,!1]:entry==="upper"&&(entry=[!1,!0]),entry===!0||entry===!1){for(i=1;i1)throw new Error("noUiSlider: 'padding' option must not exceed 100% of the range.")}}__name(testPadding,"testPadding"),__name2(testPadding,"testPadding");function testDirection(parsed,entry){switch(entry){case"ltr":parsed.dir=0;break;case"rtl":parsed.dir=1;break;default:throw new Error("noUiSlider: 'direction' option was not recognized.")}}__name(testDirection,"testDirection"),__name2(testDirection,"testDirection");function testBehaviour(parsed,entry){if(typeof entry!="string")throw new Error("noUiSlider: 'behaviour' must be a string containing options.");var tap=entry.indexOf("tap")>=0,drag=entry.indexOf("drag")>=0,fixed=entry.indexOf("fixed")>=0,snap=entry.indexOf("snap")>=0,hover=entry.indexOf("hover")>=0,unconstrained=entry.indexOf("unconstrained")>=0,dragAll=entry.indexOf("drag-all")>=0,smoothSteps=entry.indexOf("smooth-steps")>=0;if(fixed){if(parsed.handles!==2)throw new Error("noUiSlider: 'fixed' behaviour must be used with 2 handles");testMargin(parsed,parsed.start[1]-parsed.start[0])}if(unconstrained&&(parsed.margin||parsed.limit))throw new Error("noUiSlider: 'unconstrained' behaviour cannot be used with margin or limit");parsed.events={tap:tap||snap,drag,dragAll,smoothSteps,fixed,snap,hover,unconstrained}}__name(testBehaviour,"testBehaviour"),__name2(testBehaviour,"testBehaviour");function testTooltips(parsed,entry){if(entry!==!1)if(entry===!0||isValidPartialFormatter(entry)){parsed.tooltips=[];for(var i=0;i= 2) required for mode 'count'.");for(var interval=pips2.values-1,spread=100/interval,values=[];interval--;)values[interval]=interval*spread;return values.push(100),mapToRange(values,pips2.stepped)}return pips2.mode===PipsMode.Positions?mapToRange(pips2.values,pips2.stepped):pips2.mode===PipsMode.Values?pips2.stepped?pips2.values.map(function(value){return scope_Spectrum.fromStepping(scope_Spectrum.getStep(scope_Spectrum.toStepping(value)))}):pips2.values:[]}__name(getGroup,"getGroup"),__name2(getGroup,"getGroup");function mapToRange(values,stepped){return values.map(function(value){return scope_Spectrum.fromStepping(stepped?scope_Spectrum.getStep(value):value)})}__name(mapToRange,"mapToRange"),__name2(mapToRange,"mapToRange");function generateSpread(pips2){function safeIncrement(value,increment){return Number((value+increment).toFixed(7))}__name(safeIncrement,"safeIncrement"),__name2(safeIncrement,"safeIncrement");var group=getGroup(pips2),indexes={},firstInRange=scope_Spectrum.xVal[0],lastInRange=scope_Spectrum.xVal[scope_Spectrum.xVal.length-1],ignoreFirst=!1,ignoreLast=!1,prevPct=0;return group=unique(group.slice().sort(function(a,b){return a-b})),group[0]!==firstInRange&&(group.unshift(firstInRange),ignoreFirst=!0),group[group.length-1]!==lastInRange&&(group.push(lastInRange),ignoreLast=!0),group.forEach(function(current,index2){var step,i,q,low=current,high=group[index2+1],newPct,pctDifference,pctPos,type,steps,realSteps,stepSize,isSteps=pips2.mode===PipsMode.Steps;for(isSteps&&(step=scope_Spectrum.xNumSteps[index2]),step||(step=high-low),high===void 0&&(high=low),step=Math.max(step,1e-7),i=low;i<=high;i=safeIncrement(i,step)){for(newPct=scope_Spectrum.toStepping(i),pctDifference=newPct-prevPct,steps=pctDifference/(pips2.density||1),realSteps=Math.round(steps),stepSize=pctDifference/realSteps,q=1;q<=realSteps;q+=1)pctPos=prevPct+q*stepSize,indexes[pctPos.toFixed(5)]=[scope_Spectrum.fromStepping(pctPos),0];type=group.indexOf(i)>-1?PipsType.LargeValue:isSteps?PipsType.SmallValue:PipsType.NoValue,!index2&&ignoreFirst&&i!==high&&(type=0),i===high&&ignoreLast||(indexes[newPct.toFixed(5)]=[i,type]),prevPct=newPct}}),indexes}__name(generateSpread,"generateSpread"),__name2(generateSpread,"generateSpread");function addMarking(spread,filterFunc,formatter){var _a3,_b2,element=scope_Document.createElement("div"),valueSizeClasses=(_a3={},_a3[PipsType.None]="",_a3[PipsType.NoValue]=options.cssClasses.valueNormal,_a3[PipsType.LargeValue]=options.cssClasses.valueLarge,_a3[PipsType.SmallValue]=options.cssClasses.valueSub,_a3),markerSizeClasses=(_b2={},_b2[PipsType.None]="",_b2[PipsType.NoValue]=options.cssClasses.markerNormal,_b2[PipsType.LargeValue]=options.cssClasses.markerLarge,_b2[PipsType.SmallValue]=options.cssClasses.markerSub,_b2),valueOrientationClasses=[options.cssClasses.valueHorizontal,options.cssClasses.valueVertical],markerOrientationClasses=[options.cssClasses.markerHorizontal,options.cssClasses.markerVertical];addClass(element,options.cssClasses.pips),addClass(element,options.ort===0?options.cssClasses.pipsHorizontal:options.cssClasses.pipsVertical);function getClasses(type,source){var a=source===options.cssClasses.value,orientationClasses=a?valueOrientationClasses:markerOrientationClasses,sizeClasses=a?valueSizeClasses:markerSizeClasses;return source+" "+orientationClasses[options.ort]+" "+sizeClasses[type]}__name(getClasses,"getClasses"),__name2(getClasses,"getClasses");function addSpread(offset2,value,type){if(type=filterFunc?filterFunc(value,type):type,type!==PipsType.None){var node=addNodeTo(element,!1);node.className=getClasses(type,options.cssClasses.marker),node.style[options.style]=offset2+"%",type>PipsType.NoValue&&(node=addNodeTo(element,!1),node.className=getClasses(type,options.cssClasses.value),node.setAttribute("data-value",String(value)),node.style[options.style]=offset2+"%",node.innerHTML=String(formatter.to(value)))}}return __name(addSpread,"addSpread"),__name2(addSpread,"addSpread"),Object.keys(spread).forEach(function(offset2){addSpread(offset2,spread[offset2][0],spread[offset2][1])}),element}__name(addMarking,"addMarking"),__name2(addMarking,"addMarking");function removePips(){scope_Pips&&(removeElement(scope_Pips),scope_Pips=null)}__name(removePips,"removePips"),__name2(removePips,"removePips");function pips(pips2){removePips();var spread=generateSpread(pips2),filter2=pips2.filter,format=pips2.format||{to:function(value){return String(Math.round(value))}};return scope_Pips=scope_Target.appendChild(addMarking(spread,filter2,format)),scope_Pips}__name(pips,"pips"),__name2(pips,"pips");function baseSize(){var rect=scope_Base.getBoundingClientRect(),alt="offset"+["Width","Height"][options.ort];return options.ort===0?rect.width||scope_Base[alt]:rect.height||scope_Base[alt]}__name(baseSize,"baseSize"),__name2(baseSize,"baseSize");function attachEvent(events,element,callback,data){var method=__name2(function(event){var e=fixEvent(event,data.pageOffset,data.target||element);if(!e||isSliderDisabled()&&!data.doNotReject||hasClass(scope_Target,options.cssClasses.tap)&&!data.doNotReject||events===actions.start&&e.buttons!==void 0&&e.buttons>1||data.hover&&e.buttons)return!1;supportsPassive||e.preventDefault(),e.calcPoint=e.points[options.ort],callback(e,data)},"method"),methods=[];return events.split(" ").forEach(function(eventName){element.addEventListener(eventName,method,supportsPassive?{passive:!0}:!1),methods.push([eventName,method])}),methods}__name(attachEvent,"attachEvent"),__name2(attachEvent,"attachEvent");function fixEvent(e,pageOffset,eventTarget){var touch=e.type.indexOf("touch")===0,mouse=e.type.indexOf("mouse")===0,pointer=e.type.indexOf("pointer")===0,x=0,y=0;if(e.type.indexOf("MSPointer")===0&&(pointer=!0),e.type==="mousedown"&&!e.buttons&&!e.touches)return!1;if(touch){var isTouchOnTarget=__name2(function(checkTouch){var target2=checkTouch.target;return target2===eventTarget||eventTarget.contains(target2)||e.composed&&e.composedPath().shift()===eventTarget},"isTouchOnTarget");if(e.type==="touchstart"){var targetTouches=Array.prototype.filter.call(e.touches,isTouchOnTarget);if(targetTouches.length>1)return!1;x=targetTouches[0].pageX,y=targetTouches[0].pageY}else{var targetTouch=Array.prototype.find.call(e.changedTouches,isTouchOnTarget);if(!targetTouch)return!1;x=targetTouch.pageX,y=targetTouch.pageY}}return pageOffset=pageOffset||getPageOffset(scope_Document),(mouse||pointer)&&(x=e.clientX+pageOffset.x,y=e.clientY+pageOffset.y),e.pageOffset=pageOffset,e.points=[x,y],e.cursor=mouse||pointer,e}__name(fixEvent,"fixEvent"),__name2(fixEvent,"fixEvent");function calcPointToPercentage(calcPoint){var location=calcPoint-offset(scope_Base,options.ort),proposal=location*100/baseSize();return proposal=limit(proposal),options.dir?100-proposal:proposal}__name(calcPointToPercentage,"calcPointToPercentage"),__name2(calcPointToPercentage,"calcPointToPercentage");function getClosestHandle(clickedPosition){var smallestDifference=100,handleNumber=!1;return scope_Handles.forEach(function(handle,index2){if(!isHandleDisabled(index2)){var handlePosition=scope_Locations[index2],differenceWithThisHandle=Math.abs(handlePosition-clickedPosition),clickAtEdge=differenceWithThisHandle===100&&smallestDifference===100,isCloser=differenceWithThisHandlehandlePosition;(isCloser||isCloserAfter||clickAtEdge)&&(handleNumber=index2,smallestDifference=differenceWithThisHandle)}}),handleNumber}__name(getClosestHandle,"getClosestHandle"),__name2(getClosestHandle,"getClosestHandle");function documentLeave(event,data){event.type==="mouseout"&&event.target.nodeName==="HTML"&&event.relatedTarget===null&&eventEnd(event,data)}__name(documentLeave,"documentLeave"),__name2(documentLeave,"documentLeave");function eventMove(event,data){if(navigator.appVersion.indexOf("MSIE 9")===-1&&event.buttons===0&&data.buttonsProperty!==0)return eventEnd(event,data);var movement=(options.dir?-1:1)*(event.calcPoint-data.startCalcPoint),proposal=movement*100/data.baseSize;moveHandles(movement>0,proposal,data.locations,data.handleNumbers,data.connect)}__name(eventMove,"eventMove"),__name2(eventMove,"eventMove");function eventEnd(event,data){data.handle&&(removeClass(data.handle,options.cssClasses.active),scope_ActiveHandlesCount-=1),data.listeners.forEach(function(c){scope_DocumentElement.removeEventListener(c[0],c[1])}),scope_ActiveHandlesCount===0&&(removeClass(scope_Target,options.cssClasses.drag),setZindex(),event.cursor&&(scope_Body.style.cursor="",scope_Body.removeEventListener("selectstart",preventDefault))),options.events.smoothSteps&&(data.handleNumbers.forEach(function(handleNumber){setHandle(handleNumber,scope_Locations[handleNumber],!0,!0,!1,!1)}),data.handleNumbers.forEach(function(handleNumber){fireEvent("update",handleNumber)})),data.handleNumbers.forEach(function(handleNumber){fireEvent("change",handleNumber),fireEvent("set",handleNumber),fireEvent("end",handleNumber)})}__name(eventEnd,"eventEnd"),__name2(eventEnd,"eventEnd");function eventStart(event,data){if(!data.handleNumbers.some(isHandleDisabled)){var handle;if(data.handleNumbers.length===1){var handleOrigin=scope_Handles[data.handleNumbers[0]];handle=handleOrigin.children[0],scope_ActiveHandlesCount+=1,addClass(handle,options.cssClasses.active)}event.stopPropagation();var listeners=[],moveEvent=attachEvent(actions.move,scope_DocumentElement,eventMove,{target:event.target,handle,connect:data.connect,listeners,startCalcPoint:event.calcPoint,baseSize:baseSize(),pageOffset:event.pageOffset,handleNumbers:data.handleNumbers,buttonsProperty:event.buttons,locations:scope_Locations.slice()}),endEvent=attachEvent(actions.end,scope_DocumentElement,eventEnd,{target:event.target,handle,listeners,doNotReject:!0,handleNumbers:data.handleNumbers}),outEvent=attachEvent("mouseout",scope_DocumentElement,documentLeave,{target:event.target,handle,listeners,doNotReject:!0,handleNumbers:data.handleNumbers});listeners.push.apply(listeners,moveEvent.concat(endEvent,outEvent)),event.cursor&&(scope_Body.style.cursor=getComputedStyle(event.target).cursor,scope_Handles.length>1&&addClass(scope_Target,options.cssClasses.drag),scope_Body.addEventListener("selectstart",preventDefault,!1)),data.handleNumbers.forEach(function(handleNumber){fireEvent("start",handleNumber)})}}__name(eventStart,"eventStart"),__name2(eventStart,"eventStart");function eventTap(event){event.stopPropagation();var proposal=calcPointToPercentage(event.calcPoint),handleNumber=getClosestHandle(proposal);handleNumber!==!1&&(options.events.snap||addClassFor(scope_Target,options.cssClasses.tap,options.animationDuration),setHandle(handleNumber,proposal,!0,!0),setZindex(),fireEvent("slide",handleNumber,!0),fireEvent("update",handleNumber,!0),options.events.snap?eventStart(event,{handleNumbers:[handleNumber]}):(fireEvent("change",handleNumber,!0),fireEvent("set",handleNumber,!0)))}__name(eventTap,"eventTap"),__name2(eventTap,"eventTap");function eventHover(event){var proposal=calcPointToPercentage(event.calcPoint),to=scope_Spectrum.getStep(proposal),value=scope_Spectrum.fromStepping(to);Object.keys(scope_Events).forEach(function(targetEvent){targetEvent.split(".")[0]==="hover"&&scope_Events[targetEvent].forEach(function(callback){callback.call(scope_Self,value)})})}__name(eventHover,"eventHover"),__name2(eventHover,"eventHover");function eventKeydown(event,handleNumber){if(isSliderDisabled()||isHandleDisabled(handleNumber))return!1;var horizontalKeys=["Left","Right"],verticalKeys=["Down","Up"],largeStepKeys=["PageDown","PageUp"],edgeKeys=["Home","End"];options.dir&&!options.ort?horizontalKeys.reverse():options.ort&&!options.dir&&(verticalKeys.reverse(),largeStepKeys.reverse());var key=event.key.replace("Arrow",""),isLargeDown=key===largeStepKeys[0],isLargeUp=key===largeStepKeys[1],isDown=key===verticalKeys[0]||key===horizontalKeys[0]||isLargeDown,isUp=key===verticalKeys[1]||key===horizontalKeys[1]||isLargeUp,isMin=key===edgeKeys[0],isMax=key===edgeKeys[1];if(!isDown&&!isUp&&!isMin&&!isMax)return!0;event.preventDefault();var to;if(isUp||isDown){var direction=isDown?0:1,steps=getNextStepsForHandle(handleNumber),step=steps[direction];if(step===null)return!1;step===!1&&(step=scope_Spectrum.getDefaultStep(scope_Locations[handleNumber],isDown,options.keyboardDefaultStep)),isLargeUp||isLargeDown?step*=options.keyboardPageMultiplier:step*=options.keyboardMultiplier,step=Math.max(step,1e-7),step=(isDown?-1:1)*step,to=scope_Values[handleNumber]+step}else isMax?to=options.spectrum.xVal[options.spectrum.xVal.length-1]:to=options.spectrum.xVal[0];return setHandle(handleNumber,scope_Spectrum.toStepping(to),!0,!0),fireEvent("slide",handleNumber),fireEvent("update",handleNumber),fireEvent("change",handleNumber),fireEvent("set",handleNumber),!1}__name(eventKeydown,"eventKeydown"),__name2(eventKeydown,"eventKeydown");function bindSliderEvents(behaviour){behaviour.fixed||scope_Handles.forEach(function(handle,index2){attachEvent(actions.start,handle.children[0],eventStart,{handleNumbers:[index2]})}),behaviour.tap&&attachEvent(actions.start,scope_Base,eventTap,{}),behaviour.hover&&attachEvent(actions.move,scope_Base,eventHover,{hover:!0}),behaviour.drag&&scope_Connects.forEach(function(connect,index2){if(!(connect===!1||index2===0||index2===scope_Connects.length-1)){var handleBefore=scope_Handles[index2-1],handleAfter=scope_Handles[index2],eventHolders=[connect],handlesToDrag=[handleBefore,handleAfter],handleNumbersToDrag=[index2-1,index2];addClass(connect,options.cssClasses.draggable),behaviour.fixed&&(eventHolders.push(handleBefore.children[0]),eventHolders.push(handleAfter.children[0])),behaviour.dragAll&&(handlesToDrag=scope_Handles,handleNumbersToDrag=scope_HandleNumbers),eventHolders.forEach(function(eventHolder){attachEvent(actions.start,eventHolder,eventStart,{handles:handlesToDrag,handleNumbers:handleNumbersToDrag,connect})})}})}__name(bindSliderEvents,"bindSliderEvents"),__name2(bindSliderEvents,"bindSliderEvents");function bindEvent(namespacedEvent,callback){scope_Events[namespacedEvent]=scope_Events[namespacedEvent]||[],scope_Events[namespacedEvent].push(callback),namespacedEvent.split(".")[0]==="update"&&scope_Handles.forEach(function(a,index2){fireEvent("update",index2)})}__name(bindEvent,"bindEvent"),__name2(bindEvent,"bindEvent");function isInternalNamespace(namespace){return namespace===INTERNAL_EVENT_NS.aria||namespace===INTERNAL_EVENT_NS.tooltips}__name(isInternalNamespace,"isInternalNamespace"),__name2(isInternalNamespace,"isInternalNamespace");function removeEvent(namespacedEvent){var event=namespacedEvent&&namespacedEvent.split(".")[0],namespace=event?namespacedEvent.substring(event.length):namespacedEvent;Object.keys(scope_Events).forEach(function(bind){var tEvent=bind.split(".")[0],tNamespace=bind.substring(tEvent.length);(!event||event===tEvent)&&(!namespace||namespace===tNamespace)&&(!isInternalNamespace(tNamespace)||namespace===tNamespace)&&delete scope_Events[bind]})}__name(removeEvent,"removeEvent"),__name2(removeEvent,"removeEvent");function fireEvent(eventName,handleNumber,tap){Object.keys(scope_Events).forEach(function(targetEvent){var eventType=targetEvent.split(".")[0];eventName===eventType&&scope_Events[targetEvent].forEach(function(callback){callback.call(scope_Self,scope_Values.map(options.format.to),handleNumber,scope_Values.slice(),tap||!1,scope_Locations.slice(),scope_Self)})})}__name(fireEvent,"fireEvent"),__name2(fireEvent,"fireEvent");function checkHandlePosition(reference,handleNumber,to,lookBackward,lookForward,getValue,smoothSteps){var distance;return scope_Handles.length>1&&!options.events.unconstrained&&(lookBackward&&handleNumber>0&&(distance=scope_Spectrum.getAbsoluteDistance(reference[handleNumber-1],options.margin,!1),to=Math.max(to,distance)),lookForward&&handleNumber1&&options.limit&&(lookBackward&&handleNumber>0&&(distance=scope_Spectrum.getAbsoluteDistance(reference[handleNumber-1],options.limit,!1),to=Math.min(to,distance)),lookForward&&handleNumber1?handleNumbers.forEach(function(handleNumber,o){var to=checkHandlePosition(proposals,handleNumber,proposals[handleNumber]+proposal,b[o],f[o],!1,smoothSteps);to===!1?proposal=0:(proposal=to-proposals[handleNumber],proposals[handleNumber]=to)}):b=f=[!0];var state=!1;handleNumbers.forEach(function(handleNumber,o){state=setHandle(handleNumber,locations[handleNumber]+proposal,b[o],f[o],!1,smoothSteps)||state}),state&&(handleNumbers.forEach(function(handleNumber){fireEvent("update",handleNumber),fireEvent("slide",handleNumber)}),connect!=null&&fireEvent("drag",firstHandle))}__name(moveHandles,"moveHandles"),__name2(moveHandles,"moveHandles");function transformDirection(a,b){return options.dir?100-a-b:a}__name(transformDirection,"transformDirection"),__name2(transformDirection,"transformDirection");function updateHandlePosition(handleNumber,to){scope_Locations[handleNumber]=to,scope_Values[handleNumber]=scope_Spectrum.fromStepping(to);var translation=transformDirection(to,0)-scope_DirOffset,translateRule="translate("+inRuleOrder(translation+"%","0")+")";scope_Handles[handleNumber].style[options.transformRule]=translateRule,updateConnect(handleNumber),updateConnect(handleNumber+1)}__name(updateHandlePosition,"updateHandlePosition"),__name2(updateHandlePosition,"updateHandlePosition");function setZindex(){scope_HandleNumbers.forEach(function(handleNumber){var dir=scope_Locations[handleNumber]>50?-1:1,zIndex=3+(scope_Handles.length+dir*handleNumber);scope_Handles[handleNumber].style.zIndex=String(zIndex)})}__name(setZindex,"setZindex"),__name2(setZindex,"setZindex");function setHandle(handleNumber,to,lookBackward,lookForward,exactInput,smoothSteps){return exactInput||(to=checkHandlePosition(scope_Locations,handleNumber,to,lookBackward,lookForward,!1,smoothSteps)),to===!1?!1:(updateHandlePosition(handleNumber,to),!0)}__name(setHandle,"setHandle"),__name2(setHandle,"setHandle");function updateConnect(index2){if(scope_Connects[index2]){var l2=0,h=100;index2!==0&&(l2=scope_Locations[index2-1]),index2!==scope_Connects.length-1&&(h=scope_Locations[index2]);var connectWidth=h-l2,translateRule="translate("+inRuleOrder(transformDirection(l2,connectWidth)+"%","0")+")",scaleRule="scale("+inRuleOrder(connectWidth/100,"1")+")";scope_Connects[index2].style[options.transformRule]=translateRule+" "+scaleRule}}__name(updateConnect,"updateConnect"),__name2(updateConnect,"updateConnect");function resolveToValue(to,handleNumber){return to===null||to===!1||to===void 0||(typeof to=="number"&&(to=String(to)),to=options.format.from(to),to!==!1&&(to=scope_Spectrum.toStepping(to)),to===!1||isNaN(to))?scope_Locations[handleNumber]:to}__name(resolveToValue,"resolveToValue"),__name2(resolveToValue,"resolveToValue");function valueSet(input,fireSetEvent,exactInput){var values=asArray(input),isInit=scope_Locations[0]===void 0;fireSetEvent=fireSetEvent===void 0?!0:fireSetEvent,options.animate&&!isInit&&addClassFor(scope_Target,options.cssClasses.tap,options.animationDuration),scope_HandleNumbers.forEach(function(handleNumber){setHandle(handleNumber,resolveToValue(values[handleNumber],handleNumber),!0,!1,exactInput)});var i=scope_HandleNumbers.length===1?0:1;if(isInit&&scope_Spectrum.hasNoSize()&&(exactInput=!0,scope_Locations[0]=0,scope_HandleNumbers.length>1)){var space_1=100/(scope_HandleNumbers.length-1);scope_HandleNumbers.forEach(function(handleNumber){scope_Locations[handleNumber]=handleNumber*space_1})}for(;i=0&&handleNumbernearbySteps.stepAfter.startValue&&(increment=nearbySteps.stepAfter.startValue-value),value>nearbySteps.thisStep.startValue?decrement=nearbySteps.thisStep.step:nearbySteps.stepBefore.step===!1?decrement=!1:decrement=value-nearbySteps.stepBefore.highestStep,location===100?increment=null:location===0&&(decrement=null);var stepDecimals=scope_Spectrum.countStepDecimals();return increment!==null&&increment!==!1&&(increment=Number(increment.toFixed(stepDecimals))),decrement!==null&&decrement!==!1&&(decrement=Number(decrement.toFixed(stepDecimals))),[decrement,increment]}__name(getNextStepsForHandle,"getNextStepsForHandle"),__name2(getNextStepsForHandle,"getNextStepsForHandle");function getNextSteps(){return scope_HandleNumbers.map(getNextStepsForHandle)}__name(getNextSteps,"getNextSteps"),__name2(getNextSteps,"getNextSteps");function updateOptions(optionsToUpdate,fireSetEvent){var v=valueGet(),updateAble=["margin","limit","padding","range","animate","snap","step","format","pips","tooltips"];updateAble.forEach(function(name2){optionsToUpdate[name2]!==void 0&&(originalOptions[name2]=optionsToUpdate[name2])});var newOptions=testOptions(originalOptions);updateAble.forEach(function(name2){optionsToUpdate[name2]!==void 0&&(options[name2]=newOptions[name2])}),scope_Spectrum=newOptions.spectrum,options.margin=newOptions.margin,options.limit=newOptions.limit,options.padding=newOptions.padding,options.pips?pips(options.pips):removePips(),options.tooltips?tooltips():removeTooltips(),scope_Locations=[],valueSet(isSet(optionsToUpdate.start)?optionsToUpdate.start:v,fireSetEvent)}__name(updateOptions,"updateOptions"),__name2(updateOptions,"updateOptions");function setupSlider(){scope_Base=addSlider(scope_Target),addElements(options.connect,scope_Base),bindSliderEvents(options.events),valueSet(options.start),options.pips&&pips(options.pips),options.tooltips&&tooltips(),aria()}__name(setupSlider,"setupSlider"),__name2(setupSlider,"setupSlider"),setupSlider();var scope_Self={destroy:destroy2,steps:getNextSteps,on:bindEvent,off:removeEvent,get:valueGet,set:valueSet,setHandle:valueSetHandle,reset:valueReset,disable,enable,__moveHandles:function(upward,proposal,handleNumbers){moveHandles(upward,proposal,scope_Locations,handleNumbers)},options:originalOptions,updateOptions,target:scope_Target,removePips,removeTooltips,getPositions:function(){return scope_Locations.slice()},getTooltips:function(){return scope_Tooltips},getOrigins:function(){return scope_Handles},pips};return scope_Self}__name(scope,"scope"),__name2(scope,"scope");function initialize(target,originalOptions){if(!target||!target.nodeName)throw new Error("noUiSlider: create requires a single element, got: "+target);if(target.noUiSlider)throw new Error("noUiSlider: Slider was already initialized.");var options=testOptions(originalOptions),api=scope(target,options,originalOptions);return target.noUiSlider=api,api}__name(initialize,"initialize"),__name2(initialize,"initialize");const noUiSlider={__spectrum:Spectrum,cssClasses,create:initialize};var __assign=__name2(function(){return __assign=Object.assign||__name2(__name(function(t2){for(var s2,i=1,n2=arguments.length;i0&&t2[t2.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t2||op[1]>t2[0]&&op[1]=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}};throw new TypeError(s2?"Object is not iterable.":"Symbol.iterator is not defined.")}__name(__values,"__values"),__name2(__values,"__values");function __read(o,n2){var m=typeof Symbol=="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{for(;(n2===void 0||n2-- >0)&&!(r=i.next()).done;)ar.push(r.value)}catch(error){e={error}}finally{try{r&&!r.done&&(m=i.return)&&m.call(i)}finally{if(e)throw e.error}}return ar}__name(__read,"__read"),__name2(__read,"__read");var ENTRIES="ENTRIES",KEYS="KEYS",VALUES="VALUES",LEAF="",TreeIterator=function(){function TreeIterator2(set,type){var node=set._tree,keys2=Array.from(node.keys());this.set=set,this._type=type,this._path=keys2.length>0?[{node,keys:keys2}]:[]}return __name(TreeIterator2,"TreeIterator2"),__name2(TreeIterator2,"TreeIterator"),TreeIterator2.prototype.next=function(){var value=this.dive();return this.backtrack(),value},TreeIterator2.prototype.dive=function(){if(this._path.length===0)return{done:!0,value:void 0};var _a3=last$1(this._path),node=_a3.node,keys2=_a3.keys;if(last$1(keys2)===LEAF)return{done:!1,value:this.result()};var child=node.get(last$1(keys2));return this._path.push({node:child,keys:Array.from(child.keys())}),this.dive()},TreeIterator2.prototype.backtrack=function(){if(this._path.length!==0){var keys2=last$1(this._path).keys;keys2.pop(),!(keys2.length>0)&&(this._path.pop(),this.backtrack())}},TreeIterator2.prototype.key=function(){return this.set._prefix+this._path.map(function(_a3){var keys2=_a3.keys;return last$1(keys2)}).filter(function(key){return key!==LEAF}).join("")},TreeIterator2.prototype.value=function(){return last$1(this._path).node.get(LEAF)},TreeIterator2.prototype.result=function(){switch(this._type){case VALUES:return this.value();case KEYS:return this.key();default:return[this.key(),this.value()]}},TreeIterator2.prototype[Symbol.iterator]=function(){return this},TreeIterator2}(),last$1=__name2(function(array){return array[array.length-1]},"last$1"),fuzzySearch=__name2(function(node,query,maxDistance){var results=new Map;if(query===void 0)return results;for(var n2=query.length+1,m=n2+maxDistance,matrix2=new Uint8Array(m*n2).fill(maxDistance+1),j=0;jmaxDistance)continue key}recurse(node.get(key),query,maxDistance,results,matrix2,i,n2,prefix+key)}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_1)throw e_1.error}}},"recurse"),SearchableMap=function(){function SearchableMap2(tree,prefix){tree===void 0&&(tree=new Map),prefix===void 0&&(prefix=""),this._size=void 0,this._tree=tree,this._prefix=prefix}return __name(SearchableMap2,"SearchableMap2"),__name2(SearchableMap2,"SearchableMap"),SearchableMap2.prototype.atPrefix=function(prefix){var e_1,_a3;if(!prefix.startsWith(this._prefix))throw new Error("Mismatched prefix");var _b2=__read(trackDown(this._tree,prefix.slice(this._prefix.length)),2),node=_b2[0],path=_b2[1];if(node===void 0){var _c2=__read(last(path),2),parentNode=_c2[0],key=_c2[1];try{for(var _d=__values(parentNode.keys()),_e=_d.next();!_e.done;_e=_d.next()){var k=_e.value;if(k!==LEAF&&k.startsWith(key)){var node_1=new Map;return node_1.set(k.slice(key.length),parentNode.get(k)),new SearchableMap2(node_1,prefix)}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_e&&!_e.done&&(_a3=_d.return)&&_a3.call(_d)}finally{if(e_1)throw e_1.error}}}return new SearchableMap2(node,prefix)},SearchableMap2.prototype.clear=function(){this._size=void 0,this._tree.clear()},SearchableMap2.prototype.delete=function(key){return this._size=void 0,remove(this._tree,key)},SearchableMap2.prototype.entries=function(){return new TreeIterator(this,ENTRIES)},SearchableMap2.prototype.forEach=function(fn){var e_2,_a3;try{for(var _b2=__values(this),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var _d=__read(_c2.value,2),key=_d[0],value=_d[1];fn(key,value,this)}}catch(e_2_1){e_2={error:e_2_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_2)throw e_2.error}}},SearchableMap2.prototype.fuzzyGet=function(key,maxEditDistance){return fuzzySearch(this._tree,key,maxEditDistance)},SearchableMap2.prototype.get=function(key){var node=lookup(this._tree,key);return node!==void 0?node.get(LEAF):void 0},SearchableMap2.prototype.has=function(key){var node=lookup(this._tree,key);return node!==void 0&&node.has(LEAF)},SearchableMap2.prototype.keys=function(){return new TreeIterator(this,KEYS)},SearchableMap2.prototype.set=function(key,value){if(typeof key!="string")throw new Error("key must be a string");this._size=void 0;var node=createPath(this._tree,key);return node.set(LEAF,value),this},Object.defineProperty(SearchableMap2.prototype,"size",{get:function(){if(this._size)return this._size;this._size=0;for(var iter=this.entries();!iter.next().done;)this._size+=1;return this._size},enumerable:!1,configurable:!0}),SearchableMap2.prototype.update=function(key,fn){if(typeof key!="string")throw new Error("key must be a string");this._size=void 0;var node=createPath(this._tree,key);return node.set(LEAF,fn(node.get(LEAF))),this},SearchableMap2.prototype.fetch=function(key,initial){if(typeof key!="string")throw new Error("key must be a string");this._size=void 0;var node=createPath(this._tree,key),value=node.get(LEAF);return value===void 0&&node.set(LEAF,value=initial()),value},SearchableMap2.prototype.values=function(){return new TreeIterator(this,VALUES)},SearchableMap2.prototype[Symbol.iterator]=function(){return this.entries()},SearchableMap2.from=function(entries){var e_3,_a3,tree=new SearchableMap2;try{for(var entries_1=__values(entries),entries_1_1=entries_1.next();!entries_1_1.done;entries_1_1=entries_1.next()){var _b2=__read(entries_1_1.value,2),key=_b2[0],value=_b2[1];tree.set(key,value)}}catch(e_3_1){e_3={error:e_3_1}}finally{try{entries_1_1&&!entries_1_1.done&&(_a3=entries_1.return)&&_a3.call(entries_1)}finally{if(e_3)throw e_3.error}}return tree},SearchableMap2.fromObject=function(object){return SearchableMap2.from(Object.entries(object))},SearchableMap2}(),trackDown=__name2(function(tree,key,path){var e_4,_a3;if(path===void 0&&(path=[]),key.length===0||tree==null)return[tree,path];try{for(var _b2=__values(tree.keys()),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var k=_c2.value;if(k!==LEAF&&key.startsWith(k))return path.push([tree,k]),trackDown(tree.get(k),key.slice(k.length),path)}}catch(e_4_1){e_4={error:e_4_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_4)throw e_4.error}}return path.push([tree,key]),trackDown(void 0,"",path)},"trackDown"),lookup=__name2(function(tree,key){var e_5,_a3;if(key.length===0||tree==null)return tree;try{for(var _b2=__values(tree.keys()),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var k=_c2.value;if(k!==LEAF&&key.startsWith(k))return lookup(tree.get(k),key.slice(k.length))}}catch(e_5_1){e_5={error:e_5_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_5)throw e_5.error}}},"lookup"),createPath=__name2(function(node,key){var e_6,_a3,keyLength=key.length;outer:for(var pos=0;node&&pos0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new SearchableMap,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}},MiniSearch2.prototype.discard=function(id){var _this=this,shortId=this._idToShortId.get(id);if(shortId==null)throw new Error("MiniSearch: cannot discard document with ID ".concat(id,": it is not in the index"));this._idToShortId.delete(id),this._documentIds.delete(shortId),this._storedFields.delete(shortId),(this._fieldLength.get(shortId)||[]).forEach(function(fieldLength,fieldId){_this.removeFieldLength(shortId,fieldId,_this._documentCount,fieldLength)}),this._fieldLength.delete(shortId),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()},MiniSearch2.prototype.maybeAutoVacuum=function(){if(this._options.autoVacuum!==!1){var _a3=this._options.autoVacuum,minDirtFactor=_a3.minDirtFactor,minDirtCount=_a3.minDirtCount,batchSize=_a3.batchSize,batchWait=_a3.batchWait;this.conditionalVacuum({batchSize,batchWait},{minDirtCount,minDirtFactor})}},MiniSearch2.prototype.discardAll=function(ids){var e_9,_a3,autoVacuum=this._options.autoVacuum;try{this._options.autoVacuum=!1;try{for(var ids_1=__values(ids),ids_1_1=ids_1.next();!ids_1_1.done;ids_1_1=ids_1.next()){var id=ids_1_1.value;this.discard(id)}}catch(e_9_1){e_9={error:e_9_1}}finally{try{ids_1_1&&!ids_1_1.done&&(_a3=ids_1.return)&&_a3.call(ids_1)}finally{if(e_9)throw e_9.error}}}finally{this._options.autoVacuum=autoVacuum}this.maybeAutoVacuum()},MiniSearch2.prototype.replace=function(updatedDocument){var _a3=this._options,idField=_a3.idField,extractField=_a3.extractField,id=extractField(updatedDocument,idField);this.discard(id),this.add(updatedDocument)},MiniSearch2.prototype.vacuum=function(options){return options===void 0&&(options={}),this.conditionalVacuum(options)},MiniSearch2.prototype.conditionalVacuum=function(options,conditions){var _this=this;return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&conditions,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(function(){var conditions2=_this._enqueuedVacuumConditions;return _this._enqueuedVacuumConditions=defaultVacuumConditions,_this.performVacuuming(options,conditions2)}),this._enqueuedVacuum)):this.vacuumConditionsMet(conditions)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(options),this._currentVacuum)},MiniSearch2.prototype.performVacuuming=function(options,conditions){return __awaiter(this,void 0,void 0,function(){var initialDirtCount,batchSize,batchWait_1,i,_a3,_b2,_c2,term,fieldsData,fieldsData_1,fieldsData_1_1,_d,fieldId,fieldIndex,fieldIndex_1,fieldIndex_1_1,_e,shortId,e_10_1,e_10,_f,e_11,_g,e_12,_h;return __generator(this,function(_j){switch(_j.label){case 0:if(initialDirtCount=this._dirtCount,!this.vacuumConditionsMet(conditions))return[3,10];batchSize=options.batchSize||defaultVacuumOptions.batchSize,batchWait_1=options.batchWait||defaultVacuumOptions.batchWait,i=1,_j.label=1;case 1:_j.trys.push([1,7,8,9]),_a3=__values(this._index),_b2=_a3.next(),_j.label=2;case 2:if(_b2.done)return[3,6];_c2=__read(_b2.value,2),term=_c2[0],fieldsData=_c2[1];try{for(fieldsData_1=(e_11=void 0,__values(fieldsData)),fieldsData_1_1=fieldsData_1.next();!fieldsData_1_1.done;fieldsData_1_1=fieldsData_1.next()){_d=__read(fieldsData_1_1.value,2),fieldId=_d[0],fieldIndex=_d[1];try{for(fieldIndex_1=(e_12=void 0,__values(fieldIndex)),fieldIndex_1_1=fieldIndex_1.next();!fieldIndex_1_1.done;fieldIndex_1_1=fieldIndex_1.next())_e=__read(fieldIndex_1_1.value,1),shortId=_e[0],!this._documentIds.has(shortId)&&(fieldIndex.size<=1?fieldsData.delete(fieldId):fieldIndex.delete(shortId))}catch(e_12_1){e_12={error:e_12_1}}finally{try{fieldIndex_1_1&&!fieldIndex_1_1.done&&(_h=fieldIndex_1.return)&&_h.call(fieldIndex_1)}finally{if(e_12)throw e_12.error}}}}catch(e_11_1){e_11={error:e_11_1}}finally{try{fieldsData_1_1&&!fieldsData_1_1.done&&(_g=fieldsData_1.return)&&_g.call(fieldsData_1)}finally{if(e_11)throw e_11.error}}return this._index.get(term).size===0&&this._index.delete(term),i%batchSize!==0?[3,4]:[4,new Promise(function(resolve){return setTimeout(resolve,batchWait_1)})];case 3:_j.sent(),_j.label=4;case 4:i+=1,_j.label=5;case 5:return _b2=_a3.next(),[3,2];case 6:return[3,9];case 7:return e_10_1=_j.sent(),e_10={error:e_10_1},[3,9];case 8:try{_b2&&!_b2.done&&(_f=_a3.return)&&_f.call(_a3)}finally{if(e_10)throw e_10.error}return[7];case 9:this._dirtCount-=initialDirtCount,_j.label=10;case 10:return[4,null];case 11:return _j.sent(),this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null,[2]}})})},MiniSearch2.prototype.vacuumConditionsMet=function(conditions){if(conditions==null)return!0;var minDirtCount=conditions.minDirtCount,minDirtFactor=conditions.minDirtFactor;return minDirtCount=minDirtCount||defaultAutoVacuumOptions.minDirtCount,minDirtFactor=minDirtFactor||defaultAutoVacuumOptions.minDirtFactor,this.dirtCount>=minDirtCount&&this.dirtFactor>=minDirtFactor},Object.defineProperty(MiniSearch2.prototype,"isVacuuming",{get:function(){return this._currentVacuum!=null},enumerable:!1,configurable:!0}),Object.defineProperty(MiniSearch2.prototype,"dirtCount",{get:function(){return this._dirtCount},enumerable:!1,configurable:!0}),Object.defineProperty(MiniSearch2.prototype,"dirtFactor",{get:function(){return this._dirtCount/(1+this._documentCount+this._dirtCount)},enumerable:!1,configurable:!0}),MiniSearch2.prototype.has=function(id){return this._idToShortId.has(id)},MiniSearch2.prototype.getStoredFields=function(id){var shortId=this._idToShortId.get(id);if(shortId!=null)return this._storedFields.get(shortId)},MiniSearch2.prototype.search=function(query,searchOptions){var e_13,_a3;searchOptions===void 0&&(searchOptions={});var combinedResults=this.executeQuery(query,searchOptions),results=[];try{for(var combinedResults_1=__values(combinedResults),combinedResults_1_1=combinedResults_1.next();!combinedResults_1_1.done;combinedResults_1_1=combinedResults_1.next()){var _b2=__read(combinedResults_1_1.value,2),docId=_b2[0],_c2=_b2[1],score2=_c2.score,terms=_c2.terms,match2=_c2.match,quality=terms.length,result={id:this._documentIds.get(docId),score:score2*quality,terms:Object.keys(match2),match:match2};Object.assign(result,this._storedFields.get(docId)),(searchOptions.filter==null||searchOptions.filter(result))&&results.push(result)}}catch(e_13_1){e_13={error:e_13_1}}finally{try{combinedResults_1_1&&!combinedResults_1_1.done&&(_a3=combinedResults_1.return)&&_a3.call(combinedResults_1)}finally{if(e_13)throw e_13.error}}return results.sort(byScore),results},MiniSearch2.prototype.autoSuggest=function(queryString,options){var e_14,_a3,e_15,_b2;options===void 0&&(options={}),options=__assign(__assign({},this._options.autoSuggestOptions),options);var suggestions=new Map;try{for(var _c2=__values(this.search(queryString,options)),_d=_c2.next();!_d.done;_d=_c2.next()){var _e=_d.value,score2=_e.score,terms=_e.terms,phrase2=terms.join(" "),suggestion=suggestions.get(phrase2);suggestion!=null?(suggestion.score+=score2,suggestion.count+=1):suggestions.set(phrase2,{score:score2,terms,count:1})}}catch(e_14_1){e_14={error:e_14_1}}finally{try{_d&&!_d.done&&(_a3=_c2.return)&&_a3.call(_c2)}finally{if(e_14)throw e_14.error}}var results=[];try{for(var suggestions_1=__values(suggestions),suggestions_1_1=suggestions_1.next();!suggestions_1_1.done;suggestions_1_1=suggestions_1.next()){var _f=__read(suggestions_1_1.value,2),suggestion=_f[0],_g=_f[1],score2=_g.score,terms=_g.terms,count=_g.count;results.push({suggestion,terms,score:score2/count})}}catch(e_15_1){e_15={error:e_15_1}}finally{try{suggestions_1_1&&!suggestions_1_1.done&&(_b2=suggestions_1.return)&&_b2.call(suggestions_1)}finally{if(e_15)throw e_15.error}}return results.sort(byScore),results},Object.defineProperty(MiniSearch2.prototype,"documentCount",{get:function(){return this._documentCount},enumerable:!1,configurable:!0}),Object.defineProperty(MiniSearch2.prototype,"termCount",{get:function(){return this._index.size},enumerable:!1,configurable:!0}),MiniSearch2.loadJSON=function(json2,options){if(options==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(json2),options)},MiniSearch2.getDefault=function(optionName){if(defaultOptions.hasOwnProperty(optionName))return getOwnProperty(defaultOptions,optionName);throw new Error('MiniSearch: unknown option "'.concat(optionName,'"'))},MiniSearch2.loadJS=function(js,options){var e_16,_a3,e_17,_b2,e_18,_c2,index2=js.index,documentCount=js.documentCount,nextId=js.nextId,documentIds=js.documentIds,fieldIds=js.fieldIds,fieldLength=js.fieldLength,averageFieldLength=js.averageFieldLength,storedFields=js.storedFields,dirtCount=js.dirtCount,serializationVersion=js.serializationVersion;if(serializationVersion!==1&&serializationVersion!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");var miniSearch=new MiniSearch2(options);miniSearch._documentCount=documentCount,miniSearch._nextId=nextId,miniSearch._documentIds=objectToNumericMap(documentIds),miniSearch._idToShortId=new Map,miniSearch._fieldIds=fieldIds,miniSearch._fieldLength=objectToNumericMap(fieldLength),miniSearch._avgFieldLength=averageFieldLength,miniSearch._storedFields=objectToNumericMap(storedFields),miniSearch._dirtCount=dirtCount||0,miniSearch._index=new SearchableMap;try{for(var _d=__values(miniSearch._documentIds),_e=_d.next();!_e.done;_e=_d.next()){var _f=__read(_e.value,2),shortId=_f[0],id=_f[1];miniSearch._idToShortId.set(id,shortId)}}catch(e_16_1){e_16={error:e_16_1}}finally{try{_e&&!_e.done&&(_a3=_d.return)&&_a3.call(_d)}finally{if(e_16)throw e_16.error}}try{for(var index_1=__values(index2),index_1_1=index_1.next();!index_1_1.done;index_1_1=index_1.next()){var _g=__read(index_1_1.value,2),term=_g[0],data=_g[1],dataMap=new Map;try{for(var _h=(e_18=void 0,__values(Object.keys(data))),_j=_h.next();!_j.done;_j=_h.next()){var fieldId=_j.value,indexEntry=data[fieldId];serializationVersion===1&&(indexEntry=indexEntry.ds),dataMap.set(parseInt(fieldId,10),objectToNumericMap(indexEntry))}}catch(e_18_1){e_18={error:e_18_1}}finally{try{_j&&!_j.done&&(_c2=_h.return)&&_c2.call(_h)}finally{if(e_18)throw e_18.error}}miniSearch._index.set(term,dataMap)}}catch(e_17_1){e_17={error:e_17_1}}finally{try{index_1_1&&!index_1_1.done&&(_b2=index_1.return)&&_b2.call(index_1)}finally{if(e_17)throw e_17.error}}return miniSearch},MiniSearch2.prototype.executeQuery=function(query,searchOptions){var _this=this;if(searchOptions===void 0&&(searchOptions={}),typeof query!="string"){var options_1=__assign(__assign(__assign({},searchOptions),query),{queries:void 0}),results_1=query.queries.map(function(subquery){return _this.executeQuery(subquery,options_1)});return this.combineResults(results_1,options_1.combineWith)}var _a3=this._options,tokenize=_a3.tokenize,processTerm=_a3.processTerm,globalSearchOptions=_a3.searchOptions,options=__assign(__assign({tokenize,processTerm},globalSearchOptions),searchOptions),searchTokenize=options.tokenize,searchProcessTerm=options.processTerm,terms=searchTokenize(query).flatMap(function(term){return searchProcessTerm(term)}).filter(function(term){return!!term}),queries=terms.map(termToQuerySpec(options)),results=queries.map(function(query2){return _this.executeQuerySpec(query2,options)});return this.combineResults(results,options.combineWith)},MiniSearch2.prototype.executeQuerySpec=function(query,searchOptions){var e_19,_a3,e_20,_b2,options=__assign(__assign({},this._options.searchOptions),searchOptions),boosts=(options.fields||this._options.fields).reduce(function(boosts2,field){var _a4;return __assign(__assign({},boosts2),(_a4={},_a4[field]=getOwnProperty(options.boost,field)||1,_a4))},{}),boostDocument=options.boostDocument,weights=options.weights,maxFuzzy=options.maxFuzzy,bm25params=options.bm25,_c2=__assign(__assign({},defaultSearchOptions.weights),weights),fuzzyWeight=_c2.fuzzy,prefixWeight=_c2.prefix,data=this._index.get(query.term),results=this.termResults(query.term,query.term,1,data,boosts,boostDocument,bm25params),prefixMatches,fuzzyMatches;if(query.prefix&&(prefixMatches=this._index.atPrefix(query.term)),query.fuzzy){var fuzzy=query.fuzzy===!0?.2:query.fuzzy,maxDistance=fuzzy<1?Math.min(maxFuzzy,Math.round(query.term.length*fuzzy)):fuzzy;maxDistance&&(fuzzyMatches=this._index.fuzzyGet(query.term,maxDistance))}if(prefixMatches)try{for(var prefixMatches_1=__values(prefixMatches),prefixMatches_1_1=prefixMatches_1.next();!prefixMatches_1_1.done;prefixMatches_1_1=prefixMatches_1.next()){var _d=__read(prefixMatches_1_1.value,2),term=_d[0],data_1=_d[1],distance=term.length-query.term.length;if(distance){fuzzyMatches?.delete(term);var weight=prefixWeight*term.length/(term.length+.3*distance);this.termResults(query.term,term,weight,data_1,boosts,boostDocument,bm25params,results)}}}catch(e_19_1){e_19={error:e_19_1}}finally{try{prefixMatches_1_1&&!prefixMatches_1_1.done&&(_a3=prefixMatches_1.return)&&_a3.call(prefixMatches_1)}finally{if(e_19)throw e_19.error}}if(fuzzyMatches)try{for(var _e=__values(fuzzyMatches.keys()),_f=_e.next();!_f.done;_f=_e.next()){var term=_f.value,_g=__read(fuzzyMatches.get(term),2),data_2=_g[0],distance=_g[1];if(distance){var weight=fuzzyWeight*term.length/(term.length+distance);this.termResults(query.term,term,weight,data_2,boosts,boostDocument,bm25params,results)}}}catch(e_20_1){e_20={error:e_20_1}}finally{try{_f&&!_f.done&&(_b2=_e.return)&&_b2.call(_e)}finally{if(e_20)throw e_20.error}}return results},MiniSearch2.prototype.combineResults=function(results,combineWith){if(combineWith===void 0&&(combineWith=OR),results.length===0)return new Map;var operator2=combineWith.toLowerCase();return results.reduce(combinators[operator2])||new Map},MiniSearch2.prototype.toJSON=function(){var e_21,_a3,e_22,_b2,index2=[];try{for(var _c2=__values(this._index),_d=_c2.next();!_d.done;_d=_c2.next()){var _e=__read(_d.value,2),term=_e[0],fieldIndex=_e[1],data={};try{for(var fieldIndex_2=(e_22=void 0,__values(fieldIndex)),fieldIndex_2_1=fieldIndex_2.next();!fieldIndex_2_1.done;fieldIndex_2_1=fieldIndex_2.next()){var _f=__read(fieldIndex_2_1.value,2),fieldId=_f[0],freqs=_f[1];data[fieldId]=Object.fromEntries(freqs)}}catch(e_22_1){e_22={error:e_22_1}}finally{try{fieldIndex_2_1&&!fieldIndex_2_1.done&&(_b2=fieldIndex_2.return)&&_b2.call(fieldIndex_2)}finally{if(e_22)throw e_22.error}}index2.push([term,data])}}catch(e_21_1){e_21={error:e_21_1}}finally{try{_d&&!_d.done&&(_a3=_c2.return)&&_a3.call(_c2)}finally{if(e_21)throw e_21.error}}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:index2,serializationVersion:2}},MiniSearch2.prototype.termResults=function(sourceTerm,derivedTerm,termWeight,fieldTermData,fieldBoosts,boostDocumentFn,bm25params,results){var e_23,_a3,e_24,_b2,_c2;if(results===void 0&&(results=new Map),fieldTermData==null)return results;try{for(var _d=__values(Object.keys(fieldBoosts)),_e=_d.next();!_e.done;_e=_d.next()){var field=_e.value,fieldBoost=fieldBoosts[field],fieldId=this._fieldIds[field],fieldTermFreqs=fieldTermData.get(fieldId);if(fieldTermFreqs!=null){var matchingFields=fieldTermFreqs.size,avgFieldLength=this._avgFieldLength[fieldId];try{for(var _f=(e_24=void 0,__values(fieldTermFreqs.keys())),_g=_f.next();!_g.done;_g=_f.next()){var docId=_g.value;if(!this._documentIds.has(docId)){this.removeTerm(fieldId,docId,derivedTerm),matchingFields-=1;continue}var docBoost=boostDocumentFn?boostDocumentFn(this._documentIds.get(docId),derivedTerm,this._storedFields.get(docId)):1;if(docBoost){var termFreq=fieldTermFreqs.get(docId),fieldLength=this._fieldLength.get(docId)[fieldId],rawScore=calcBM25Score(termFreq,matchingFields,this._documentCount,fieldLength,avgFieldLength,bm25params),weightedScore=termWeight*fieldBoost*docBoost*rawScore,result=results.get(docId);if(result){result.score+=weightedScore,assignUniqueTerm(result.terms,sourceTerm);var match2=getOwnProperty(result.match,derivedTerm);match2?match2.push(field):result.match[derivedTerm]=[field]}else results.set(docId,{score:weightedScore,terms:[sourceTerm],match:(_c2={},_c2[derivedTerm]=[field],_c2)})}}}catch(e_24_1){e_24={error:e_24_1}}finally{try{_g&&!_g.done&&(_b2=_f.return)&&_b2.call(_f)}finally{if(e_24)throw e_24.error}}}}}catch(e_23_1){e_23={error:e_23_1}}finally{try{_e&&!_e.done&&(_a3=_d.return)&&_a3.call(_d)}finally{if(e_23)throw e_23.error}}return results},MiniSearch2.prototype.addTerm=function(fieldId,documentId,term){var indexData=this._index.fetch(term,createMap),fieldIndex=indexData.get(fieldId);if(fieldIndex==null)fieldIndex=new Map,fieldIndex.set(documentId,1),indexData.set(fieldId,fieldIndex);else{var docs=fieldIndex.get(documentId);fieldIndex.set(documentId,(docs||0)+1)}},MiniSearch2.prototype.removeTerm=function(fieldId,documentId,term){if(!this._index.has(term)){this.warnDocumentChanged(documentId,fieldId,term);return}var indexData=this._index.fetch(term,createMap),fieldIndex=indexData.get(fieldId);fieldIndex==null||fieldIndex.get(documentId)==null?this.warnDocumentChanged(documentId,fieldId,term):fieldIndex.get(documentId)<=1?fieldIndex.size<=1?indexData.delete(fieldId):fieldIndex.delete(documentId):fieldIndex.set(documentId,fieldIndex.get(documentId)-1),this._index.get(term).size===0&&this._index.delete(term)},MiniSearch2.prototype.warnDocumentChanged=function(shortDocumentId,fieldId,term){var e_25,_a3;try{for(var _b2=__values(Object.keys(this._fieldIds)),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var fieldName=_c2.value;if(this._fieldIds[fieldName]===fieldId){this._options.logger("warn","MiniSearch: document with ID ".concat(this._documentIds.get(shortDocumentId),' has changed before removal: term "').concat(term,'" was not present in field "').concat(fieldName,'". Removing a document after it has changed can corrupt the index!'),"version_conflict");return}}}catch(e_25_1){e_25={error:e_25_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_25)throw e_25.error}}},MiniSearch2.prototype.addDocumentId=function(documentId){var shortDocumentId=this._nextId;return this._idToShortId.set(documentId,shortDocumentId),this._documentIds.set(shortDocumentId,documentId),this._documentCount+=1,this._nextId+=1,shortDocumentId},MiniSearch2.prototype.addFields=function(fields){for(var i=0;i{let{doc:doc2}=view.state,code=codePointAt(m[0],0);if(code==9){let line=doc2.lineAt(pos),size=view.state.tabSize,col=countColumn(line.text,size,pos-line.from);return Decoration.replace({widget:new TabWidget((size-col%size)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[code]||(this.decorationCache[code]=Decoration.replace({widget:new SpecialCharWidget(conf,code)}))},boundary:conf.replaceTabs?void 0:/[^]/})}update(update){let conf=update.state.facet(specialCharConfig);update.startState.facet(specialCharConfig)!=conf?(this.decorator=this.makeDecorator(conf),this.decorations=this.decorator.createDeco(update.view)):this.decorations=this.decorator.updateDeco(update,this.decorations)}},{decorations:v=>v.decorations}))}__name(specialCharPlugin,"specialCharPlugin"),__name2(specialCharPlugin,"specialCharPlugin");const DefaultPlaceholder="\u2022";function placeholder$1(code){return code>=32?DefaultPlaceholder:code==10?"\u2424":String.fromCharCode(9216+code)}__name(placeholder$1,"placeholder$1"),__name2(placeholder$1,"placeholder$1");const _SpecialCharWidget=class extends WidgetType{static{__name(this,"_SpecialCharWidget")}constructor(options,code){super(),this.options=options,this.code=code}eq(other){return other.code==this.code}toDOM(view){let ph=placeholder$1(this.code),desc=view.state.phrase("Control character")+" "+(Names[this.code]||"0x"+this.code.toString(16)),custom=this.options.render&&this.options.render(this.code,desc,ph);if(custom)return custom;let span=document.createElement("span");return span.textContent=ph,span.title=desc,span.setAttribute("aria-label",desc),span.className="cm-specialChar",span}ignoreEvent(){return!1}};__name2(_SpecialCharWidget,"SpecialCharWidget");let SpecialCharWidget=_SpecialCharWidget;const _TabWidget=class extends WidgetType{static{__name(this,"_TabWidget")}constructor(width){super(),this.width=width}eq(other){return other.width==this.width}toDOM(){let span=document.createElement("span");return span.textContent=" ",span.className="cm-tab",span.style.width=this.width+"px",span}ignoreEvent(){return!1}};__name2(_TabWidget,"TabWidget");let TabWidget=_TabWidget;function highlightActiveLine(){return activeLineHighlighter}__name(highlightActiveLine,"highlightActiveLine"),__name2(highlightActiveLine,"highlightActiveLine");const lineDeco=Decoration.line({class:"cm-activeLine"}),activeLineHighlighter=ViewPlugin.fromClass(class{constructor(view){this.decorations=this.getDeco(view)}update(update){(update.docChanged||update.selectionSet)&&(this.decorations=this.getDeco(update.view))}getDeco(view){let lastLineStart=-1,deco=[];for(let r of view.state.selection.ranges){let line=view.lineBlockAt(r.head);line.from>lastLineStart&&(deco.push(lineDeco.range(line.from)),lastLineStart=line.from)}return Decoration.set(deco)}},{decorations:v=>v.decorations}),MaxOff=2e3;function rectangleFor(state,a,b){let startLine=Math.min(a.line,b.line),endLine=Math.max(a.line,b.line),ranges=[];if(a.off>MaxOff||b.off>MaxOff||a.col<0||b.col<0){let startOff=Math.min(a.off,b.off),endOff=Math.max(a.off,b.off);for(let i=startLine;i<=endLine;i++){let line=state.doc.line(i);line.length<=endOff&&ranges.push(EditorSelection.range(line.from+startOff,line.to+endOff))}}else{let startCol=Math.min(a.col,b.col),endCol=Math.max(a.col,b.col);for(let i=startLine;i<=endLine;i++){let line=state.doc.line(i),start=findColumn(line.text,startCol,state.tabSize,!0);if(start<0)ranges.push(EditorSelection.cursor(line.to));else{let end=findColumn(line.text,endCol,state.tabSize);ranges.push(EditorSelection.range(line.from+start,line.from+end))}}}return ranges}__name(rectangleFor,"rectangleFor"),__name2(rectangleFor,"rectangleFor");function absoluteColumn(view,x){let ref=view.coordsAtPos(view.viewport.from);return ref?Math.round(Math.abs((ref.left-x)/view.defaultCharacterWidth)):-1}__name(absoluteColumn,"absoluteColumn"),__name2(absoluteColumn,"absoluteColumn");function getPos(view,event){let offset2=view.posAtCoords({x:event.clientX,y:event.clientY},!1),line=view.state.doc.lineAt(offset2),off2=offset2-line.from,col=off2>MaxOff?-1:off2==line.length?absoluteColumn(view,event.clientX):countColumn(line.text,view.state.tabSize,offset2-line.from);return{line:line.number,col,off:off2}}__name(getPos,"getPos"),__name2(getPos,"getPos");function rectangleSelectionStyle(view,event){let start=getPos(view,event),startSel=view.state.selection;return start?{update(update){if(update.docChanged){let newStart=update.changes.mapPos(update.startState.doc.line(start.line).from),newLine=update.state.doc.lineAt(newStart);start={line:newLine.number,col:start.col,off:Math.min(start.off,newLine.length)},startSel=startSel.map(update.changes)}},get(event2,_extend,multiple){let cur2=getPos(view,event2);if(!cur2)return startSel;let ranges=rectangleFor(view.state,start,cur2);return ranges.length?multiple?EditorSelection.create(ranges.concat(startSel.ranges)):EditorSelection.create(ranges):startSel}}:null}__name(rectangleSelectionStyle,"rectangleSelectionStyle"),__name2(rectangleSelectionStyle,"rectangleSelectionStyle");function rectangularSelection(options){let filter2=options?.eventFilter||(e=>e.altKey&&e.button==0);return EditorView.mouseSelectionStyle.of((view,event)=>filter2(event)?rectangleSelectionStyle(view,event):null)}__name(rectangularSelection,"rectangularSelection"),__name2(rectangularSelection,"rectangularSelection");const keys={Alt:[18,e=>!!e.altKey],Control:[17,e=>!!e.ctrlKey],Shift:[16,e=>!!e.shiftKey],Meta:[91,e=>!!e.metaKey]},showCrosshair={style:"cursor: crosshair"};function crosshairCursor(options={}){let[code,getter]=keys[options.key||"Alt"],plugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.isDown=!1}set(isDown){this.isDown!=isDown&&(this.isDown=isDown,this.view.update([]))}},{eventObservers:{keydown(e){this.set(e.keyCode==code||getter(e))},keyup(e){(e.keyCode==code||!getter(e))&&this.set(!1)},mousemove(e){this.set(getter(e))}}});return[plugin,EditorView.contentAttributes.of(view=>{var _a3;return!((_a3=view.plugin(plugin))===null||_a3===void 0)&&_a3.isDown?showCrosshair:null})]}__name(crosshairCursor,"crosshairCursor"),__name2(crosshairCursor,"crosshairCursor");const Outside="-10000px",_TooltipViewManager=class{static{__name(this,"_TooltipViewManager")}constructor(view,facet,createTooltipView){this.facet=facet,this.createTooltipView=createTooltipView,this.input=view.state.facet(facet),this.tooltips=this.input.filter(t2=>t2),this.tooltipViews=this.tooltips.map(createTooltipView)}update(update){var _a3;let input=update.state.facet(this.facet),tooltips=input.filter(x=>x);if(input===this.input){for(let t2 of this.tooltipViews)t2.update&&t2.update(update);return!1}let tooltipViews=[];for(let i=0;i{var _a3,_b2,_c2;return{position:browser.ios?"absolute":((_a3=values.find(conf=>conf.position))===null||_a3===void 0?void 0:_a3.position)||"fixed",parent:((_b2=values.find(conf=>conf.parent))===null||_b2===void 0?void 0:_b2.parent)||null,tooltipSpace:((_c2=values.find(conf=>conf.tooltipSpace))===null||_c2===void 0?void 0:_c2.tooltipSpace)||windowSpace}}}),knownHeight=new WeakMap,tooltipPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let config2=view.state.facet(tooltipConfig);this.position=config2.position,this.parent=config2.parent,this.classes=view.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.manager=new TooltipViewManager(view,showTooltip,t2=>this.createTooltip(t2)),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(entries=>{Date.now()>this.lastTransaction-50&&entries.length>0&&entries[entries.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),view.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let tooltip of this.manager.tooltipViews)this.intersectionObserver.observe(tooltip.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(update){update.transactions.length&&(this.lastTransaction=Date.now());let updated=this.manager.update(update);updated&&this.observeIntersection();let shouldMeasure=updated||update.geometryChanged,newConfig=update.state.facet(tooltipConfig);if(newConfig.position!=this.position&&!this.madeAbsolute){this.position=newConfig.position;for(let t2 of this.manager.tooltipViews)t2.dom.style.position=this.position;shouldMeasure=!0}if(newConfig.parent!=this.parent){this.parent&&this.container.remove(),this.parent=newConfig.parent,this.createContainer();for(let t2 of this.manager.tooltipViews)this.container.appendChild(t2.dom);shouldMeasure=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);shouldMeasure&&this.maybeMeasure()}createTooltip(tooltip){let tooltipView=tooltip.create(this.view);if(tooltipView.dom.classList.add("cm-tooltip"),tooltip.arrow&&!tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let arrow=document.createElement("div");arrow.className="cm-tooltip-arrow",tooltipView.dom.appendChild(arrow)}return tooltipView.dom.style.position=this.position,tooltipView.dom.style.top=Outside,this.container.appendChild(tooltipView.dom),tooltipView.mount&&tooltipView.mount(this.view),tooltipView}destroy(){var _a3,_b2;this.view.win.removeEventListener("resize",this.measureSoon);for(let tooltipView of this.manager.tooltipViews)tooltipView.dom.remove(),(_a3=tooltipView.destroy)===null||_a3===void 0||_a3.call(tooltipView);this.parent&&this.container.remove(),(_b2=this.intersectionObserver)===null||_b2===void 0||_b2.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let editor=this.view.dom.getBoundingClientRect(),scaleX=1,scaleY=1,makeAbsolute=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{offsetParent}=this.manager.tooltipViews[0].dom;makeAbsolute=!!(offsetParent&&offsetParent!=this.container.ownerDocument.body)}if(makeAbsolute||this.position=="absolute")if(this.parent){let rect=this.parent.getBoundingClientRect();rect.width&&rect.height&&(scaleX=rect.width/this.parent.offsetWidth,scaleY=rect.height/this.parent.offsetHeight)}else({scaleX,scaleY}=this.view.viewState);return{editor,parent:this.parent?this.container.getBoundingClientRect():editor,pos:this.manager.tooltips.map((t2,i)=>{let tv=this.manager.tooltipViews[i];return tv.getCoords?tv.getCoords(t2.pos):this.view.coordsAtPos(t2.pos)}),size:this.manager.tooltipViews.map(({dom})=>dom.getBoundingClientRect()),space:this.view.state.facet(tooltipConfig).tooltipSpace(this.view),scaleX,scaleY,makeAbsolute}}writeMeasure(measured){var _a3;if(measured.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let t2 of this.manager.tooltipViews)t2.dom.style.position="absolute"}let{editor,space,scaleX,scaleY}=measured,others=[];for(let i=0;i=Math.min(editor.bottom,space.bottom)||pos.rightMath.min(editor.right,space.right)+.1){dom.style.top=Outside;continue}let arrow=tooltip.arrow?tView.dom.querySelector(".cm-tooltip-arrow"):null,arrowHeight=arrow?7:0,width=size.right-size.left,height=(_a3=knownHeight.get(tView))!==null&&_a3!==void 0?_a3:size.bottom-size.top,offset2=tView.offset||noOffset,ltr=this.view.textDirection==Direction.LTR,left=size.width>space.right-space.left?ltr?space.left:space.right-size.width:ltr?Math.min(pos.left-(arrow?14:0)+offset2.x,space.right-width):Math.max(space.left,pos.left-width+(arrow?14:0)-offset2.x),above=!!tooltip.above;!tooltip.strictSide&&(above?pos.top-(size.bottom-size.top)-offset2.yspace.bottom)&&above==space.bottom-pos.bottom>pos.top-space.top&&(above=!above);let spaceVert=(above?pos.top-space.top:space.bottom-pos.bottom)-arrowHeight;if(spaceVertleft&&r.toptop2&&(top2=above?r.top-height-2-arrowHeight:r.bottom+arrowHeight+2);if(this.position=="absolute"?(dom.style.top=(top2-measured.parent.top)/scaleY+"px",dom.style.left=(left-measured.parent.left)/scaleX+"px"):(dom.style.top=top2/scaleY+"px",dom.style.left=left/scaleX+"px"),arrow){let arrowLeft=pos.left+(ltr?offset2.x:-offset2.x)-(left+14-7);arrow.style.left=arrowLeft/scaleX+"px"}tView.overlap!==!0&&others.push({left,top:top2,right,bottom:top2+height}),dom.classList.toggle("cm-tooltip-above",above),dom.classList.toggle("cm-tooltip-below",!above),tView.positioned&&tView.positioned(measured.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let tv of this.manager.tooltipViews)tv.dom.style.top=Outside}},{eventObservers:{scroll(){this.maybeMeasure()}}}),baseTheme$5=EditorView.baseTheme({".cm-tooltip":{zIndex:100,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:`${7*2}px`,position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),noOffset={x:0,y:0},showTooltip=Facet.define({enables:[tooltipPlugin,baseTheme$5]}),showHoverTooltip=Facet.define(),_HoverTooltipHost=class _HoverTooltipHost2{static{__name(this,"_HoverTooltipHost")}static create(view){return new _HoverTooltipHost2(view)}constructor(view){this.view=view,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new TooltipViewManager(view,showHoverTooltip,t2=>this.createHostedView(t2))}createHostedView(tooltip){let hostedView=tooltip.create(this.view);return hostedView.dom.classList.add("cm-tooltip-section"),this.dom.appendChild(hostedView.dom),this.mounted&&hostedView.mount&&hostedView.mount(this.view),hostedView}mount(view){for(let hostedView of this.manager.tooltipViews)hostedView.mount&&hostedView.mount(view);this.mounted=!0}positioned(space){for(let hostedView of this.manager.tooltipViews)hostedView.positioned&&hostedView.positioned(space)}update(update){this.manager.update(update)}destroy(){var _a3;for(let t2 of this.manager.tooltipViews)(_a3=t2.destroy)===null||_a3===void 0||_a3.call(t2)}};__name2(_HoverTooltipHost,"HoverTooltipHost");let HoverTooltipHost=_HoverTooltipHost;const showHoverTooltipHost=showTooltip.compute([showHoverTooltip],state=>{let tooltips=state.facet(showHoverTooltip).filter(t2=>t2);return tooltips.length===0?null:{pos:Math.min(...tooltips.map(t2=>t2.pos)),end:Math.max(...tooltips.filter(t2=>t2.end!=null).map(t2=>t2.end)),create:HoverTooltipHost.create,above:tooltips[0].above,arrow:tooltips.some(t2=>t2.arrow)}}),_HoverPlugin=class{static{__name(this,"_HoverPlugin")}constructor(view,source,field,setHover,hoverTime){this.view=view,this.source=source,this.field=field,this.setHover=setHover,this.hoverTime=hoverTime,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:view.dom,time:0},this.checkHover=this.checkHover.bind(this),view.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),view.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active)return;let hovered=Date.now()-this.lastMove.time;hoveredposCoords.bottom||lastMove.xposCoords.right+view.defaultCharacterWidth)return;let bidi=view.bidiSpans(view.state.doc.lineAt(pos)).find(s2=>s2.from<=pos&&s2.to>=pos),rtl=bidi&&bidi.dir==Direction.RTL?-1:1;side=lastMove.x{this.pending==pending&&(this.pending=null,result&&view.dispatch({effects:this.setHover.of(result)}))},e=>logException(view.state,e,"hover tooltip"))}else open&&view.dispatch({effects:this.setHover.of(open)})}mousemove(event){var _a3;this.lastMove={x:event.clientX,y:event.clientY,target:event.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let tooltip=this.active;if(tooltip&&!isInTooltip(this.lastMove.target)||this.pending){let{pos}=tooltip||this.pending,end=(_a3=tooltip?.end)!==null&&_a3!==void 0?_a3:pos;(pos==end?this.view.posAtCoords(this.lastMove)!=pos:!isOverRange(this.view,pos,end,event.clientX,event.clientY))&&(this.view.dispatch({effects:this.setHover.of(null)}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1,this.active&&!isInTooltip(e.relatedTarget)&&this.view.dispatch({effects:this.setHover.of(null)})}destroy(){clearTimeout(this.hoverTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}};__name2(_HoverPlugin,"HoverPlugin");let HoverPlugin=_HoverPlugin;function isInTooltip(elt){for(let cur2=elt;cur2;cur2=cur2.parentNode)if(cur2.nodeType==1&&cur2.classList.contains("cm-tooltip"))return!0;return!1}__name(isInTooltip,"isInTooltip"),__name2(isInTooltip,"isInTooltip");function isOverRange(view,from,to,x,y,margin){let rect=view.scrollDOM.getBoundingClientRect(),docBottom=view.documentTop+view.documentPadding.top+view.contentHeight;if(rect.left>x||rect.righty||Math.min(rect.bottom,docBottom)=from&&pos<=to}__name(isOverRange,"isOverRange"),__name2(isOverRange,"isOverRange");function hoverTooltip(source,options={}){let setHover=StateEffect.define(),hoverState=StateField.define({create(){return null},update(value,tr){if(value&&(options.hideOnChange&&(tr.docChanged||tr.selection)||options.hideOn&&options.hideOn(tr,value)))return null;if(value&&tr.docChanged){let newPos=tr.changes.mapPos(value.pos,-1,MapMode.TrackDel);if(newPos==null)return null;let copy=Object.assign(Object.create(null),value);copy.pos=newPos,value.end!=null&&(copy.end=tr.changes.mapPos(value.end)),value=copy}for(let effect of tr.effects)effect.is(setHover)&&(value=effect.value),effect.is(closeHoverTooltipEffect)&&(value=null);return value},provide:f=>showHoverTooltip.from(f)});return[hoverState,ViewPlugin.define(view=>new HoverPlugin(view,source,hoverState,setHover,options.hoverTime||300)),showHoverTooltipHost]}__name(hoverTooltip,"hoverTooltip"),__name2(hoverTooltip,"hoverTooltip");function getTooltip(view,tooltip){let plugin=view.plugin(tooltipPlugin);if(!plugin)return null;let found=plugin.manager.tooltips.indexOf(tooltip);return found<0?null:plugin.manager.tooltipViews[found]}__name(getTooltip,"getTooltip"),__name2(getTooltip,"getTooltip");const closeHoverTooltipEffect=StateEffect.define(),panelConfig=Facet.define({combine(configs){let topContainer,bottomContainer;for(let c of configs)topContainer=topContainer||c.topContainer,bottomContainer=bottomContainer||c.bottomContainer;return{topContainer,bottomContainer}}});function getPanel(view,panel){let plugin=view.plugin(panelPlugin),index2=plugin?plugin.specs.indexOf(panel):-1;return index2>-1?plugin.panels[index2]:null}__name(getPanel,"getPanel"),__name2(getPanel,"getPanel");const panelPlugin=ViewPlugin.fromClass(class{constructor(view){this.input=view.state.facet(showPanel),this.specs=this.input.filter(s2=>s2),this.panels=this.specs.map(spec=>spec(view));let conf=view.state.facet(panelConfig);this.top=new PanelGroup(view,!0,conf.topContainer),this.bottom=new PanelGroup(view,!1,conf.bottomContainer),this.top.sync(this.panels.filter(p=>p.top)),this.bottom.sync(this.panels.filter(p=>!p.top));for(let p of this.panels)p.dom.classList.add("cm-panel"),p.mount&&p.mount()}update(update){let conf=update.state.facet(panelConfig);this.top.container!=conf.topContainer&&(this.top.sync([]),this.top=new PanelGroup(update.view,!0,conf.topContainer)),this.bottom.container!=conf.bottomContainer&&(this.bottom.sync([]),this.bottom=new PanelGroup(update.view,!1,conf.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let input=update.state.facet(showPanel);if(input!=this.input){let specs=input.filter(x=>x),panels=[],top2=[],bottom=[],mount2=[];for(let spec of specs){let known=this.specs.indexOf(spec),panel;known<0?(panel=spec(update.view),mount2.push(panel)):(panel=this.panels[known],panel.update&&panel.update(update)),panels.push(panel),(panel.top?top2:bottom).push(panel)}this.specs=specs,this.panels=panels,this.top.sync(top2),this.bottom.sync(bottom);for(let p of mount2)p.dom.classList.add("cm-panel"),p.mount&&p.mount()}else for(let p of this.panels)p.update&&p.update(update)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:plugin=>EditorView.scrollMargins.of(view=>{let value=view.plugin(plugin);return value&&{top:value.top.scrollMargin(),bottom:value.bottom.scrollMargin()}})}),_PanelGroup=class{static{__name(this,"_PanelGroup")}constructor(view,top2,container){this.view=view,this.top=top2,this.container=container,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(panels){for(let p of this.panels)p.destroy&&panels.indexOf(p)<0&&p.destroy();this.panels=panels,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom",this.dom.style[this.top?"top":"bottom"]="0";let parent=this.container||this.view.dom;parent.insertBefore(this.dom,this.top?parent.firstChild:null)}let curDOM=this.dom.firstChild;for(let panel of this.panels)if(panel.dom.parentNode==this.dom){for(;curDOM!=panel.dom;)curDOM=rm(curDOM);curDOM=curDOM.nextSibling}else this.dom.insertBefore(panel.dom,curDOM);for(;curDOM;)curDOM=rm(curDOM)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let cls of this.classes.split(" "))cls&&this.container.classList.remove(cls);for(let cls of(this.classes=this.view.themeClasses).split(" "))cls&&this.container.classList.add(cls)}}};__name2(_PanelGroup,"PanelGroup");let PanelGroup=_PanelGroup;function rm(node){let next=node.nextSibling;return node.remove(),next}__name(rm,"rm"),__name2(rm,"rm");const showPanel=Facet.define({enables:panelPlugin}),_GutterMarker=class extends RangeValue{static{__name(this,"_GutterMarker")}compare(other){return this==other||this.constructor==other.constructor&&this.eq(other)}eq(other){return!1}destroy(dom){}};__name2(_GutterMarker,"GutterMarker");let GutterMarker=_GutterMarker;GutterMarker.prototype.elementClass="",GutterMarker.prototype.toDOM=void 0,GutterMarker.prototype.mapMode=MapMode.TrackBefore,GutterMarker.prototype.startSide=GutterMarker.prototype.endSide=-1,GutterMarker.prototype.point=!0;const gutterLineClass=Facet.define(),defaults$1={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>RangeSet.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{}},activeGutters=Facet.define();function gutter(config2){return[gutters(),activeGutters.of(Object.assign(Object.assign({},defaults$1),config2))]}__name(gutter,"gutter"),__name2(gutter,"gutter");const unfixGutters=Facet.define({combine:values=>values.some(x=>x)});function gutters(config2){let result=[gutterView];return config2&&config2.fixed===!1&&result.push(unfixGutters.of(!0)),result}__name(gutters,"gutters"),__name2(gutters,"gutters");const gutterView=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.prevViewport=view.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=view.state.facet(activeGutters).map(conf=>new SingleGutterView(view,conf));for(let gutter2 of this.gutters)this.dom.appendChild(gutter2.dom);this.fixed=!view.state.facet(unfixGutters),this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),view.scrollDOM.insertBefore(this.dom,view.contentDOM)}update(update){if(this.updateGutters(update)){let vpA=this.prevViewport,vpB=update.view.viewport,vpOverlap=Math.min(vpA.to,vpB.to)-Math.max(vpA.from,vpB.from);this.syncGutters(vpOverlap<(vpB.to-vpB.from)*.8)}update.geometryChanged&&(this.dom.style.minHeight=this.view.contentHeight+"px"),this.view.state.facet(unfixGutters)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":""),this.prevViewport=update.view.viewport}syncGutters(detach){let after=this.dom.nextSibling;detach&&this.dom.remove();let lineClasses=RangeSet.iter(this.view.state.facet(gutterLineClass),this.view.viewport.from),classSet=[],contexts=this.gutters.map(gutter2=>new UpdateContext(gutter2,this.view.viewport,-this.view.documentPadding.top));for(let line of this.view.viewportLineBlocks)if(classSet.length&&(classSet=[]),Array.isArray(line.type)){let first=!0;for(let b of line.type)if(b.type==BlockType.Text&&first){advanceCursor(lineClasses,classSet,b.from);for(let cx of contexts)cx.line(this.view,b,classSet);first=!1}else if(b.widget)for(let cx of contexts)cx.widget(this.view,b)}else if(line.type==BlockType.Text){advanceCursor(lineClasses,classSet,line.from);for(let cx of contexts)cx.line(this.view,line,classSet)}else if(line.widget)for(let cx of contexts)cx.widget(this.view,line);for(let cx of contexts)cx.finish();detach&&this.view.scrollDOM.insertBefore(this.dom,after)}updateGutters(update){let prev=update.startState.facet(activeGutters),cur2=update.state.facet(activeGutters),change=update.docChanged||update.heightChanged||update.viewportChanged||!RangeSet.eq(update.startState.facet(gutterLineClass),update.state.facet(gutterLineClass),update.view.viewport.from,update.view.viewport.to);if(prev==cur2)for(let gutter2 of this.gutters)gutter2.update(update)&&(change=!0);else{change=!0;let gutters2=[];for(let conf of cur2){let known=prev.indexOf(conf);known<0?gutters2.push(new SingleGutterView(this.view,conf)):(this.gutters[known].update(update),gutters2.push(this.gutters[known]))}for(let g of this.gutters)g.dom.remove(),gutters2.indexOf(g)<0&&g.destroy();for(let g of gutters2)this.dom.appendChild(g.dom);this.gutters=gutters2}return change}destroy(){for(let view of this.gutters)view.destroy();this.dom.remove()}},{provide:plugin=>EditorView.scrollMargins.of(view=>{let value=view.plugin(plugin);return!value||value.gutters.length==0||!value.fixed?null:view.textDirection==Direction.LTR?{left:value.dom.offsetWidth*view.scaleX}:{right:value.dom.offsetWidth*view.scaleX}})});function asArray$1(val){return Array.isArray(val)?val:[val]}__name(asArray$1,"asArray$1"),__name2(asArray$1,"asArray$1");function advanceCursor(cursor,collect,pos){for(;cursor.value&&cursor.from<=pos;)cursor.from==pos&&collect.push(cursor.value),cursor.next()}__name(advanceCursor,"advanceCursor"),__name2(advanceCursor,"advanceCursor");const _UpdateContext=class{static{__name(this,"_UpdateContext")}constructor(gutter2,viewport,height){this.gutter=gutter2,this.height=height,this.i=0,this.cursor=RangeSet.iter(gutter2.markers,viewport.from)}addElement(view,block,markers){let{gutter:gutter2}=this,above=(block.top-this.height)/view.scaleY,height=block.height/view.scaleY;if(this.i==gutter2.elements.length){let newElt=new GutterElement(view,height,above,markers);gutter2.elements.push(newElt),gutter2.dom.appendChild(newElt.dom)}else gutter2.elements[this.i].update(view,height,above,markers);this.height=block.bottom,this.i++}line(view,line,extraMarkers){let localMarkers=[];advanceCursor(this.cursor,localMarkers,line.from),extraMarkers.length&&(localMarkers=localMarkers.concat(extraMarkers));let forLine=this.gutter.config.lineMarker(view,line,localMarkers);forLine&&localMarkers.unshift(forLine);let gutter2=this.gutter;localMarkers.length==0&&!gutter2.config.renderEmptyElements||this.addElement(view,line,localMarkers)}widget(view,block){let marker=this.gutter.config.widgetMarker(view,block.widget,block);marker&&this.addElement(view,block,[marker])}finish(){let gutter2=this.gutter;for(;gutter2.elements.length>this.i;){let last2=gutter2.elements.pop();gutter2.dom.removeChild(last2.dom),last2.destroy()}}};__name2(_UpdateContext,"UpdateContext");let UpdateContext=_UpdateContext;const _SingleGutterView=class{static{__name(this,"_SingleGutterView")}constructor(view,config2){this.view=view,this.config=config2,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let prop in config2.domEventHandlers)this.dom.addEventListener(prop,event=>{let target=event.target,y;if(target!=this.dom&&this.dom.contains(target)){for(;target.parentNode!=this.dom;)target=target.parentNode;let rect=target.getBoundingClientRect();y=(rect.top+rect.bottom)/2}else y=event.clientY;let line=view.lineBlockAtHeight(y-view.documentTop);config2.domEventHandlers[prop](view,line,event)&&event.preventDefault()});this.markers=asArray$1(config2.markers(view)),config2.initialSpacer&&(this.spacer=new GutterElement(view,0,0,[config2.initialSpacer(view)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(update){let prevMarkers=this.markers;if(this.markers=asArray$1(this.config.markers(update.view)),this.spacer&&this.config.updateSpacer){let updated=this.config.updateSpacer(this.spacer.markers[0],update);updated!=this.spacer.markers[0]&&this.spacer.update(update.view,0,0,[updated])}let vp=update.view.viewport;return!RangeSet.eq(this.markers,prevMarkers,vp.from,vp.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(update):!1)}destroy(){for(let elt of this.elements)elt.destroy()}};__name2(_SingleGutterView,"SingleGutterView");let SingleGutterView=_SingleGutterView;const _GutterElement=class{static{__name(this,"_GutterElement")}constructor(view,height,above,markers){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(view,height,above,markers)}update(view,height,above,markers){this.height!=height&&(this.height=height,this.dom.style.height=height+"px"),this.above!=above&&(this.dom.style.marginTop=(this.above=above)?above+"px":""),sameMarkers(this.markers,markers)||this.setMarkers(view,markers)}setMarkers(view,markers){let cls="cm-gutterElement",domPos=this.dom.firstChild;for(let iNew=0,iOld=0;;){let skipTo=iOld,marker=iNewexists(view,line,event2)||add2(view,line,event2):add2}return result}})}}),_NumberMarker=class extends GutterMarker{static{__name(this,"_NumberMarker")}constructor(number2){super(),this.number=number2}eq(other){return this.number==other.number}toDOM(){return document.createTextNode(this.number)}};__name2(_NumberMarker,"NumberMarker");let NumberMarker=_NumberMarker;function formatNumber(view,number2){return view.state.facet(lineNumberConfig).formatNumber(number2,view.state)}__name(formatNumber,"formatNumber"),__name2(formatNumber,"formatNumber");const lineNumberGutter=activeGutters.compute([lineNumberConfig],state=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(view){return view.state.facet(lineNumberMarkers)},lineMarker(view,line,others){return others.some(m=>m.toDOM)?null:new NumberMarker(formatNumber(view,view.state.doc.lineAt(line.from).number))},widgetMarker:()=>null,lineMarkerChange:update=>update.startState.facet(lineNumberConfig)!=update.state.facet(lineNumberConfig),initialSpacer(view){return new NumberMarker(formatNumber(view,maxLineNumber(view.state.doc.lines)))},updateSpacer(spacer,update){let max=formatNumber(update.view,maxLineNumber(update.view.state.doc.lines));return max==spacer.number?spacer:new NumberMarker(max)},domEventHandlers:state.facet(lineNumberConfig).domEventHandlers}));function lineNumbers(config2={}){return[lineNumberConfig.of(config2),gutters(),lineNumberGutter]}__name(lineNumbers,"lineNumbers"),__name2(lineNumbers,"lineNumbers");function maxLineNumber(lines){let last2=9;for(;last2{let marks=[],last2=-1;for(let range of state.selection.ranges){let linePos=state.doc.lineAt(range.head).from;linePos>last2&&(last2=linePos,marks.push(activeLineGutterMarker.range(linePos)))}return RangeSet.of(marks)});function highlightActiveLineGutter(){return activeLineGutterHighlighter}__name(highlightActiveLineGutter,"highlightActiveLineGutter"),__name2(highlightActiveLineGutter,"highlightActiveLineGutter");const DefaultBufferLength=1024;let nextPropID=0;const _Range=class{static{__name(this,"_Range")}constructor(from,to){this.from=from,this.to=to}};__name2(_Range,"Range");let Range=_Range;const _NodeProp=class{static{__name(this,"_NodeProp")}constructor(config2={}){this.id=nextPropID++,this.perNode=!!config2.perNode,this.deserialize=config2.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(match2){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof match2!="function"&&(match2=NodeType.match(match2)),type=>{let result=match2(type);return result===void 0?null:[this,result]}}};__name2(_NodeProp,"NodeProp");let NodeProp=_NodeProp;NodeProp.closedBy=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.openedBy=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.group=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.contextHash=new NodeProp({perNode:!0}),NodeProp.lookAhead=new NodeProp({perNode:!0}),NodeProp.mounted=new NodeProp({perNode:!0});const noProps=Object.create(null),_NodeType=class _NodeType2{static{__name(this,"_NodeType")}constructor(name2,props,id,flags=0){this.name=name2,this.props=props,this.id=id,this.flags=flags}static define(spec){let props=spec.props&&spec.props.length?Object.create(null):noProps,flags=(spec.top?1:0)|(spec.skipped?2:0)|(spec.error?4:0)|(spec.name==null?8:0),type=new _NodeType2(spec.name||"",props,spec.id,flags);if(spec.props){for(let src of spec.props)if(Array.isArray(src)||(src=src(type)),src){if(src[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");props[src[0].id]=src[1]}}return type}prop(prop){return this.props[prop.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(name2){if(typeof name2=="string"){if(this.name==name2)return!0;let group=this.prop(NodeProp.group);return group?group.indexOf(name2)>-1:!1}return this.id==name2}static match(map2){let direct=Object.create(null);for(let prop in map2)for(let name2 of prop.split(" "))direct[name2]=map2[prop];return node=>{for(let groups=node.prop(NodeProp.group),i=-1;i<(groups?groups.length:0);i++){let found=direct[i<0?node.name:groups[i]];if(found)return found}}}};__name2(_NodeType,"NodeType");let NodeType=_NodeType;NodeType.none=new NodeType("",Object.create(null),0,8);const _NodeSet=class _NodeSet2{static{__name(this,"_NodeSet")}constructor(types2){this.types=types2;for(let i=0;i0;for(let c=this.cursor(mode|IterMode.IncludeAnonymous);;){let entered=!1;if(c.from<=to&&c.to>=from&&(!anon&&c.type.isAnonymous||enter(c)!==!1)){if(c.firstChild())continue;entered=!0}for(;entered&&leave&&(anon||!c.type.isAnonymous)&&leave(c),!c.nextSibling();){if(!c.parent())return;entered=!0}}}prop(prop){return prop.perNode?this.props?this.props[prop.id]:void 0:this.type.prop(prop)}get propValues(){let result=[];if(this.props)for(let id in this.props)result.push([+id,this.props[id]]);return result}balance(config2={}){return this.children.length<=8?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,(children,positions,length)=>new _Tree2(this.type,children,positions,length,this.propValues),config2.makeTree||((children,positions,length)=>new _Tree2(NodeType.none,children,positions,length)))}static build(data){return buildTree(data)}};__name2(_Tree,"Tree");let Tree=_Tree;Tree.empty=new Tree(NodeType.none,[],[],0);const _FlatBufferCursor=class _FlatBufferCursor2{static{__name(this,"_FlatBufferCursor")}constructor(buffer,index2){this.buffer=buffer,this.index=index2}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new _FlatBufferCursor2(this.buffer,this.index)}};__name2(_FlatBufferCursor,"FlatBufferCursor");let FlatBufferCursor=_FlatBufferCursor;const _TreeBuffer=class _TreeBuffer2{static{__name(this,"_TreeBuffer")}constructor(buffer,length,set){this.buffer=buffer,this.length=length,this.set=set}get type(){return NodeType.none}toString(){let result=[];for(let index2=0;index20));i=buffer[i+3]);return pick2}slice(startI,endI,from){let b=this.buffer,copy=new Uint16Array(endI-startI),len=0;for(let i=startI,j=0;i=pos&&frompos;case 1:return from<=pos&&to>pos;case 2:return to>pos;case 4:return!0}}__name(checkSide,"checkSide"),__name2(checkSide,"checkSide");function enterUnfinishedNodesBefore(node,pos){let scan=node.childBefore(pos);for(;scan;){let last2=scan.lastChild;if(!last2||last2.to!=scan.to)break;last2.type.isError&&last2.from==last2.to?(node=scan,scan=last2.prevSibling):scan=last2}return node}__name(enterUnfinishedNodesBefore,"enterUnfinishedNodesBefore"),__name2(enterUnfinishedNodesBefore,"enterUnfinishedNodesBefore");function resolveNode(node,pos,side,overlays){for(var _a3;node.from==node.to||(side<1?node.from>=pos:node.from>pos)||(side>-1?node.to<=pos:node.to0?children.length:-1;i!=e;i+=dir){let next=children[i],start=positions[i]+parent.from;if(checkSide(side,pos,start,start+next.length)){if(next instanceof TreeBuffer){if(mode&IterMode.ExcludeBuffers)continue;let index2=next.findChild(0,next.buffer.length,dir,pos-start,side);if(index2>-1)return new BufferNode(new BufferContext(parent,next,i,start),null,index2)}else if(mode&IterMode.IncludeAnonymous||!next.type.isAnonymous||hasChild(next)){let mounted;if(!(mode&IterMode.IgnoreMounts)&&next.props&&(mounted=next.prop(NodeProp.mounted))&&!mounted.overlay)return new _TreeNode2(mounted.tree,start,i,parent);let inner=new _TreeNode2(next,start,i,parent);return mode&IterMode.IncludeAnonymous||!inner.type.isAnonymous?inner:inner.nextChild(dir<0?next.children.length-1:0,dir,pos,side)}}}if(mode&IterMode.IncludeAnonymous||!parent.type.isAnonymous||(parent.index>=0?i=parent.index+dir:i=dir<0?-1:parent._parent._tree.children.length,parent=parent._parent,!parent))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(pos){return this.nextChild(0,1,pos,2)}childBefore(pos){return this.nextChild(this._tree.children.length-1,-1,pos,-2)}enter(pos,side,mode=0){let mounted;if(!(mode&IterMode.IgnoreOverlays)&&(mounted=this._tree.prop(NodeProp.mounted))&&mounted.overlay){let rPos=pos-this.from;for(let{from,to}of mounted.overlay)if((side>0?from<=rPos:from=rPos:to>rPos))return new _TreeNode2(mounted.tree,mounted.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,pos,side,mode)}nextSignificantParent(){let val=this;for(;val.type.isAnonymous&&val._parent;)val=val._parent;return val}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}cursor(mode=0){return new TreeCursor(this,mode)}get tree(){return this._tree}toTree(){return this._tree}resolve(pos,side=0){return resolveNode(this,pos,side,!1)}resolveInner(pos,side=0){return resolveNode(this,pos,side,!0)}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos)}getChild(type,before=null,after=null){let r=getChildren(this,type,before,after);return r.length?r[0]:null}getChildren(type,before=null,after=null){return getChildren(this,type,before,after)}toString(){return this._tree.toString()}get node(){return this}matchContext(context){return matchNodeContext(this,context)}};__name2(_TreeNode,"TreeNode");let TreeNode=_TreeNode;function getChildren(node,type,before,after){let cur2=node.cursor(),result=[];if(!cur2.firstChild())return result;if(before!=null){for(;!cur2.type.is(before);)if(!cur2.nextSibling())return result}for(;;){if(after!=null&&cur2.type.is(after))return result;if(cur2.type.is(type)&&result.push(cur2.node),!cur2.nextSibling())return after==null?result:[]}}__name(getChildren,"getChildren"),__name2(getChildren,"getChildren");function matchNodeContext(node,context,i=context.length-1){for(let p=node.parent;i>=0;p=p.parent){if(!p)return!1;if(!p.type.isAnonymous){if(context[i]&&context[i]!=p.name)return!1;i--}}return!0}__name(matchNodeContext,"matchNodeContext"),__name2(matchNodeContext,"matchNodeContext");const _BufferContext=class{static{__name(this,"_BufferContext")}constructor(parent,buffer,index2,start){this.parent=parent,this.buffer=buffer,this.index=index2,this.start=start}};__name2(_BufferContext,"BufferContext");let BufferContext=_BufferContext;const _BufferNode=class _BufferNode2{static{__name(this,"_BufferNode")}get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(context,_parent,index2){this.context=context,this._parent=_parent,this.index=index2,this.type=context.buffer.set.types[context.buffer.buffer[index2]]}child(dir,pos,side){let{buffer}=this.context,index2=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.context.start,side);return index2<0?null:new _BufferNode2(this.context,this,index2)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(pos){return this.child(1,pos,2)}childBefore(pos){return this.child(-1,pos,-2)}enter(pos,side,mode=0){if(mode&IterMode.ExcludeBuffers)return null;let{buffer}=this.context,index2=buffer.findChild(this.index+4,buffer.buffer[this.index+3],side>0?1:-1,pos-this.context.start,side);return index2<0?null:new _BufferNode2(this.context,this,index2)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(dir){return this._parent?null:this.context.parent.nextChild(this.context.index+dir,dir,0,4)}get nextSibling(){let{buffer}=this.context,after=buffer.buffer[this.index+3];return after<(this._parent?buffer.buffer[this._parent.index+3]:buffer.buffer.length)?new _BufferNode2(this.context,this._parent,after):this.externalSibling(1)}get prevSibling(){let{buffer}=this.context,parentStart=this._parent?this._parent.index+4:0;return this.index==parentStart?this.externalSibling(-1):new _BufferNode2(this.context,this._parent,buffer.findChild(parentStart,this.index,-1,0,4))}cursor(mode=0){return new TreeCursor(this,mode)}get tree(){return null}toTree(){let children=[],positions=[],{buffer}=this.context,startI=this.index+4,endI=buffer.buffer[this.index+3];if(endI>startI){let from=buffer.buffer[this.index+1];children.push(buffer.slice(startI,endI,from)),positions.push(0)}return new Tree(this.type,children,positions,this.to-this.from)}resolve(pos,side=0){return resolveNode(this,pos,side,!1)}resolveInner(pos,side=0){return resolveNode(this,pos,side,!0)}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos)}toString(){return this.context.buffer.childString(this.index)}getChild(type,before=null,after=null){let r=getChildren(this,type,before,after);return r.length?r[0]:null}getChildren(type,before=null,after=null){return getChildren(this,type,before,after)}get node(){return this}matchContext(context){return matchNodeContext(this,context)}};__name2(_BufferNode,"BufferNode");let BufferNode=_BufferNode;const _TreeCursor=class{static{__name(this,"_TreeCursor")}get name(){return this.type.name}constructor(node,mode=0){if(this.mode=mode,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,node instanceof TreeNode)this.yieldNode(node);else{this._tree=node.context.parent,this.buffer=node.context;for(let n2=node._parent;n2;n2=n2._parent)this.stack.unshift(n2.index);this.bufferNode=node,this.yieldBuf(node.index)}}yieldNode(node){return node?(this._tree=node,this.type=node.type,this.from=node.from,this.to=node.to,!0):!1}yieldBuf(index2,type){this.index=index2;let{start,buffer}=this.buffer;return this.type=type||buffer.set.types[buffer.buffer[index2]],this.from=start+buffer.buffer[index2+1],this.to=start+buffer.buffer[index2+2],!0}yield(node){return node?node instanceof TreeNode?(this.buffer=null,this.yieldNode(node)):(this.buffer=node.context,this.yieldBuf(node.index,node.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(dir,pos,side){if(!this.buffer)return this.yield(this._tree.nextChild(dir<0?this._tree._tree.children.length-1:0,dir,pos,side,this.mode));let{buffer}=this.buffer,index2=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.buffer.start,side);return index2<0?!1:(this.stack.push(this.index),this.yieldBuf(index2))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(pos){return this.enterChild(1,pos,2)}childBefore(pos){return this.enterChild(-1,pos,-2)}enter(pos,side,mode=this.mode){return this.buffer?mode&IterMode.ExcludeBuffers?!1:this.enterChild(1,pos,side):this.yield(this._tree.enter(pos,side,mode))}parent(){if(!this.buffer)return this.yieldNode(this.mode&IterMode.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let parent=this.mode&IterMode.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(parent)}sibling(dir){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+dir,dir,0,4,this.mode)):!1;let{buffer}=this.buffer,d=this.stack.length-1;if(dir<0){let parentStart=d<0?0:this.stack[d]+4;if(this.index!=parentStart)return this.yieldBuf(buffer.findChild(parentStart,this.index,-1,0,4))}else{let after=buffer.buffer[this.index+3];if(after<(d<0?buffer.buffer.length:buffer.buffer[this.stack[d]+3]))return this.yieldBuf(after)}return d<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+dir,dir,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(dir){let index2,parent,{buffer}=this;if(buffer){if(dir>0){if(this.index-1)for(let i=index2+dir,e=dir<0?-1:parent._tree.children.length;i!=e;i+=dir){let child=parent._tree.children[i];if(this.mode&IterMode.IncludeAnonymous||child instanceof TreeBuffer||!child.type.isAnonymous||hasChild(child))return!1}return!0}move(dir,enter){if(enter&&this.enterChild(dir,0,4))return!0;for(;;){if(this.sibling(dir))return!0;if(this.atLastNode(dir)||!this.parent())return!1}}next(enter=!0){return this.move(1,enter)}prev(enter=!0){return this.move(-1,enter)}moveTo(pos,side=0){for(;(this.from==this.to||(side<1?this.from>=pos:this.from>pos)||(side>-1?this.to<=pos:this.to=0;){for(let c=cache;c;c=c._parent)if(c.index==index2){if(index2==this.index)return c;result=c,depth=d+1;break scan}index2=this.stack[--d]}for(let i=depth;i=0;d--){if(d<0)return matchNodeContext(this.node,context,i);let type=types2[buffer.buffer[this.stack[d]]];if(!type.isAnonymous){if(context[i]&&context[i]!=type.name)return!1;i--}}return!0}};__name2(_TreeCursor,"TreeCursor");let TreeCursor=_TreeCursor;function hasChild(tree){return tree.children.some(ch=>ch instanceof TreeBuffer||!ch.type.isAnonymous||hasChild(ch))}__name(hasChild,"hasChild"),__name2(hasChild,"hasChild");function buildTree(data){var _a3;let{buffer,nodeSet,maxBufferLength=DefaultBufferLength,reused=[],minRepeatType=nodeSet.types.length}=data,cursor=Array.isArray(buffer)?new FlatBufferCursor(buffer,buffer.length):buffer,types2=nodeSet.types,contextHash=0,lookAhead=0;function takeNode(parentStart,minPos,children2,positions2,inRepeat){let{id,start,end,size}=cursor,lookAheadAtStart=lookAhead;for(;size<0;)if(cursor.next(),size==-1){let node2=reused[id];children2.push(node2),positions2.push(start-parentStart);return}else if(size==-3){contextHash=id;return}else if(size==-4){lookAhead=id;return}else throw new RangeError(`Unrecognized record size: ${size}`);let type=types2[id],node,buffer2,startPos=start-parentStart;if(end-start<=maxBufferLength&&(buffer2=findBufferSize(cursor.pos-minPos,inRepeat))){let data2=new Uint16Array(buffer2.size-buffer2.skip),endPos=cursor.pos-buffer2.size,index2=data2.length;for(;cursor.pos>endPos;)index2=copyToBuffer(buffer2.start,data2,index2);node=new TreeBuffer(data2,end-buffer2.start,nodeSet),startPos=buffer2.start-parentStart}else{let endPos=cursor.pos-size;cursor.next();let localChildren=[],localPositions=[],localInRepeat=id>=minRepeatType?id:-1,lastGroup=0,lastEnd=end;for(;cursor.pos>endPos;)localInRepeat>=0&&cursor.id==localInRepeat&&cursor.size>=0?(cursor.end<=lastEnd-maxBufferLength&&(makeRepeatLeaf(localChildren,localPositions,start,lastGroup,cursor.end,lastEnd,localInRepeat,lookAheadAtStart),lastGroup=localChildren.length,lastEnd=cursor.end),cursor.next()):takeNode(start,endPos,localChildren,localPositions,localInRepeat);if(localInRepeat>=0&&lastGroup>0&&lastGroup-1&&lastGroup>0){let make=makeBalanced(type);node=balanceRange(type,localChildren,localPositions,0,localChildren.length,0,end-start,make,make)}else node=makeTree(type,localChildren,localPositions,end-start,lookAheadAtStart-end)}children2.push(node),positions2.push(startPos)}__name(takeNode,"takeNode"),__name2(takeNode,"takeNode");function makeBalanced(type){return(children2,positions2,length2)=>{let lookAhead2=0,lastI=children2.length-1,last2,lookAheadProp;if(lastI>=0&&(last2=children2[lastI])instanceof Tree){if(!lastI&&last2.type==type&&last2.length==length2)return last2;(lookAheadProp=last2.prop(NodeProp.lookAhead))&&(lookAhead2=positions2[lastI]+last2.length+lookAheadProp)}return makeTree(type,children2,positions2,length2,lookAhead2)}}__name(makeBalanced,"makeBalanced"),__name2(makeBalanced,"makeBalanced");function makeRepeatLeaf(children2,positions2,base2,i,from,to,type,lookAhead2){let localChildren=[],localPositions=[];for(;children2.length>i;)localChildren.push(children2.pop()),localPositions.push(positions2.pop()+base2-from);children2.push(makeTree(nodeSet.types[type],localChildren,localPositions,to-from,lookAhead2-to)),positions2.push(from-base2)}__name(makeRepeatLeaf,"makeRepeatLeaf"),__name2(makeRepeatLeaf,"makeRepeatLeaf");function makeTree(type,children2,positions2,length2,lookAhead2=0,props){if(contextHash){let pair2=[NodeProp.contextHash,contextHash];props=props?[pair2].concat(props):[pair2]}if(lookAhead2>25){let pair2=[NodeProp.lookAhead,lookAhead2];props=props?[pair2].concat(props):[pair2]}return new Tree(type,children2,positions2,length2,props)}__name(makeTree,"makeTree"),__name2(makeTree,"makeTree");function findBufferSize(maxSize,inRepeat){let fork=cursor.fork(),size=0,start=0,skip=0,minStart=fork.end-maxBufferLength,result={size:0,start:0,skip:0};scan:for(let minPos=fork.pos-maxSize;fork.pos>minPos;){let nodeSize2=fork.size;if(fork.id==inRepeat&&nodeSize2>=0){result.size=size,result.start=start,result.skip=skip,skip+=4,size+=4,fork.next();continue}let startPos=fork.pos-nodeSize2;if(nodeSize2<0||startPos=minRepeatType?4:0,nodeStart2=fork.start;for(fork.next();fork.pos>startPos;){if(fork.size<0)if(fork.size==-3)localSkipped+=4;else break scan;else fork.id>=minRepeatType&&(localSkipped+=4);fork.next()}start=nodeStart2,size+=nodeSize2,skip+=localSkipped}return(inRepeat<0||size==maxSize)&&(result.size=size,result.start=start,result.skip=skip),result.size>4?result:void 0}__name(findBufferSize,"findBufferSize"),__name2(findBufferSize,"findBufferSize");function copyToBuffer(bufferStart,buffer2,index2){let{id,start,end,size}=cursor;if(cursor.next(),size>=0&&id4){let endPos=cursor.pos-(size-4);for(;cursor.pos>endPos;)index2=copyToBuffer(bufferStart,buffer2,index2)}buffer2[--index2]=startIndex,buffer2[--index2]=end-bufferStart,buffer2[--index2]=start-bufferStart,buffer2[--index2]=id}else size==-3?contextHash=id:size==-4&&(lookAhead=id);return index2}__name(copyToBuffer,"copyToBuffer"),__name2(copyToBuffer,"copyToBuffer");let children=[],positions=[];for(;cursor.pos>0;)takeNode(data.start||0,data.bufferStart||0,children,positions,-1);let length=(_a3=data.length)!==null&&_a3!==void 0?_a3:children.length?positions[0]+children[0].length:0;return new Tree(types2[data.topID],children.reverse(),positions.reverse(),length)}__name(buildTree,"buildTree"),__name2(buildTree,"buildTree");const nodeSizeCache=new WeakMap;function nodeSize(balanceType,node){if(!balanceType.isAnonymous||node instanceof TreeBuffer||node.type!=balanceType)return 1;let size=nodeSizeCache.get(node);if(size==null){size=1;for(let child of node.children){if(child.type!=balanceType||!(child instanceof Tree)){size=1;break}size+=nodeSize(balanceType,child)}nodeSizeCache.set(node,size)}return size}__name(nodeSize,"nodeSize"),__name2(nodeSize,"nodeSize");function balanceRange(balanceType,children,positions,from,to,start,length,mkTop,mkTree){let total=0;for(let i=from;i=maxChild)break;groupSize+=nextSize}if(i==groupFrom+1){if(groupSize>maxChild){let only=children2[groupFrom];divide(only.children,only.positions,0,only.children.length,positions2[groupFrom]+offset2);continue}localChildren.push(children2[groupFrom])}else{let length2=positions2[i-1]+children2[i-1].length-groupStart;localChildren.push(balanceRange(balanceType,children2,positions2,groupFrom,i,groupStart,length2,null,mkTree))}localPositions.push(groupStart+offset2-start)}}return __name(divide,"divide"),__name2(divide,"divide"),divide(children,positions,from,to,0),(mkTop||mkTree)(localChildren,localPositions,length)}__name(balanceRange,"balanceRange"),__name2(balanceRange,"balanceRange");const _TreeFragment=class _TreeFragment2{static{__name(this,"_TreeFragment")}constructor(from,to,tree,offset2,openStart=!1,openEnd=!1){this.from=from,this.to=to,this.tree=tree,this.offset=offset2,this.open=(openStart?1:0)|(openEnd?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(tree,fragments=[],partial=!1){let result=[new _TreeFragment2(0,tree.length,tree,0,!1,partial)];for(let f of fragments)f.to>tree.length&&result.push(f);return result}static applyChanges(fragments,changes,minGap=128){if(!changes.length)return fragments;let result=[],fI=1,nextF=fragments.length?fragments[0]:null;for(let cI=0,pos=0,off2=0;;cI++){let nextC=cI=minGap)for(;nextF&&nextF.from=cut.from||nextPos<=cut.to||off2){let fFrom=Math.max(cut.from,pos)-off2,fTo=Math.min(cut.to,nextPos)-off2;cut=fFrom>=fTo?null:new _TreeFragment2(fFrom,fTo,cut.tree,cut.offset+off2,cI>0,!!nextC)}if(cut&&result.push(cut),nextF.to>nextPos)break;nextF=fInew Range(r.from,r.to)):[new Range(0,0)]:[new Range(0,input.length)],this.createParse(input,fragments||[],ranges)}parse(input,fragments,ranges){let parse2=this.startParse(input,fragments,ranges);for(;;){let done=parse2.advance();if(done)return done}}};__name2(_Parser,"Parser");let Parser=_Parser;const _StringInput=class{static{__name(this,"_StringInput")}constructor(string2){this.string=string2}get length(){return this.string.length}chunk(from){return this.string.slice(from)}get lineChunks(){return!1}read(from,to){return this.string.slice(from,to)}};__name2(_StringInput,"StringInput");let StringInput=_StringInput;new NodeProp({perNode:!0});let nextTagID=0;const _Tag=class _Tag2{static{__name(this,"_Tag")}constructor(set,base2,modified){this.set=set,this.base=base2,this.modified=modified,this.id=nextTagID++}static define(parent){if(parent?.base)throw new Error("Can not derive from a modified tag");let tag=new _Tag2([],null,[]);if(tag.set.push(tag),parent)for(let t2 of parent.set)tag.set.push(t2);return tag}static defineModifier(){let mod=new Modifier;return tag=>tag.modified.indexOf(mod)>-1?tag:Modifier.get(tag.base||tag,tag.modified.concat(mod).sort((a,b)=>a.id-b.id))}};__name2(_Tag,"Tag");let Tag=_Tag,nextModifierID=0;const _Modifier=class _Modifier2{static{__name(this,"_Modifier")}constructor(){this.instances=[],this.id=nextModifierID++}static get(base2,mods){if(!mods.length)return base2;let exists=mods[0].instances.find(t2=>t2.base==base2&&sameArray(mods,t2.modified));if(exists)return exists;let set=[],tag=new Tag(set,base2,mods);for(let m of mods)m.instances.push(tag);let configs=powerSet(mods);for(let parent of base2.set)if(!parent.modified.length)for(let config2 of configs)set.push(_Modifier2.get(parent,config2));return tag}};__name2(_Modifier,"Modifier");let Modifier=_Modifier;function sameArray(a,b){return a.length==b.length&&a.every((x,i)=>x==b[i])}__name(sameArray,"sameArray"),__name2(sameArray,"sameArray");function powerSet(array){let sets=[[]];for(let i=0;ib.length-a.length)}__name(powerSet,"powerSet"),__name2(powerSet,"powerSet");function styleTags(spec){let byName=Object.create(null);for(let prop in spec){let tags2=spec[prop];Array.isArray(tags2)||(tags2=[tags2]);for(let part of prop.split(" "))if(part){let pieces=[],mode=2,rest=part;for(let pos=0;;){if(rest=="..."&&pos>0&&pos+3==part.length){mode=1;break}let m=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);if(!m)throw new RangeError("Invalid path: "+part);if(pieces.push(m[0]=="*"?"":m[0][0]=='"'?JSON.parse(m[0]):m[0]),pos+=m[0].length,pos==part.length)break;let next=part[pos++];if(pos==part.length&&next=="!"){mode=0;break}if(next!="/")throw new RangeError("Invalid path: "+part);rest=part.slice(pos)}let last2=pieces.length-1,inner=pieces[last2];if(!inner)throw new RangeError("Invalid path: "+part);let rule=new Rule(tags2,mode,last2>0?pieces.slice(0,last2):null);byName[inner]=rule.sort(byName[inner])}}return ruleNodeProp.add(byName)}__name(styleTags,"styleTags"),__name2(styleTags,"styleTags");const ruleNodeProp=new NodeProp,_Rule=class{static{__name(this,"_Rule")}constructor(tags2,mode,context,next){this.tags=tags2,this.mode=mode,this.context=context,this.next=next}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(other){return!other||other.depth{let cls=all;for(let tag of tags3)for(let sub of tag.set){let tagClass=map2[sub.id];if(tagClass){cls=cls?cls+" "+tagClass:tagClass;break}}return cls},scope:scope2}}__name(tagHighlighter,"tagHighlighter"),__name2(tagHighlighter,"tagHighlighter");function highlightTags(highlighters,tags2){let result=null;for(let highlighter of highlighters){let value=highlighter.style(tags2);value&&(result=result?result+" "+value:value)}return result}__name(highlightTags,"highlightTags"),__name2(highlightTags,"highlightTags");function highlightTree(tree,highlighter,putStyle,from=0,to=tree.length){let builder=new HighlightBuilder(from,Array.isArray(highlighter)?highlighter:[highlighter],putStyle);builder.highlightRange(tree.cursor(),from,to,"",builder.highlighters),builder.flush(to)}__name(highlightTree,"highlightTree"),__name2(highlightTree,"highlightTree");const _HighlightBuilder=class{static{__name(this,"_HighlightBuilder")}constructor(at,highlighters,span){this.at=at,this.highlighters=highlighters,this.span=span,this.class=""}startSpan(at,cls){cls!=this.class&&(this.flush(at),at>this.at&&(this.at=at),this.class=cls)}flush(to){to>this.at&&this.class&&this.span(this.at,to,this.class)}highlightRange(cursor,from,to,inheritedClass,highlighters){let{type,from:start,to:end}=cursor;if(start>=to||end<=from)return;type.isTop&&(highlighters=this.highlighters.filter(h=>!h.scope||h.scope(type)));let cls=inheritedClass,rule=getStyleTags(cursor)||Rule.empty,tagCls=highlightTags(highlighters,rule.tags);if(tagCls&&(cls&&(cls+=" "),cls+=tagCls,rule.mode==1&&(inheritedClass+=(inheritedClass?" ":"")+tagCls)),this.startSpan(Math.max(from,start),cls),rule.opaque)return;let mounted=cursor.tree&&cursor.tree.prop(NodeProp.mounted);if(mounted&&mounted.overlay){let inner=cursor.node.enter(mounted.overlay[0].from+start,1),innerHighlighters=this.highlighters.filter(h=>!h.scope||h.scope(mounted.tree.type)),hasChild2=cursor.firstChild();for(let i=0,pos=start;;i++){let next=i=nextPos||!cursor.nextSibling())););if(!next||nextPos>to)break;pos=next.to+start,pos>from&&(this.highlightRange(inner.cursor(),Math.max(from,next.from+start),Math.min(to,pos),"",innerHighlighters),this.startSpan(Math.min(to,pos),cls))}hasChild2&&cursor.parent()}else if(cursor.firstChild()){mounted&&(inheritedClass="");do if(!(cursor.to<=from)){if(cursor.from>=to)break;this.highlightRange(cursor,from,to,inheritedClass,highlighters),this.startSpan(Math.min(to,cursor.to),cls)}while(cursor.nextSibling());cursor.parent()}}};__name2(_HighlightBuilder,"HighlightBuilder");let HighlightBuilder=_HighlightBuilder;function getStyleTags(node){let rule=node.type.prop(ruleNodeProp);for(;rule&&rule.context&&!node.matchContext(rule.context);)rule=rule.next;return rule||null}__name(getStyleTags,"getStyleTags"),__name2(getStyleTags,"getStyleTags");const t=Tag.define,comment=t(),name=t(),typeName=t(name),propertyName=t(name),literal=t(),string=t(literal),number=t(literal),content=t(),heading=t(content),keyword=t(),operator=t(),punctuation=t(),bracket=t(punctuation),meta=t(),tags={comment,lineComment:t(comment),blockComment:t(comment),docComment:t(comment),name,variableName:t(name),typeName,tagName:t(typeName),propertyName,attributeName:t(propertyName),className:t(name),labelName:t(name),namespace:t(name),macroName:t(name),literal,string,docString:t(string),character:t(string),attributeValue:t(string),number,integer:t(number),float:t(number),bool:t(literal),regexp:t(literal),escape:t(literal),color:t(literal),url:t(literal),keyword,self:t(keyword),null:t(keyword),atom:t(keyword),unit:t(keyword),modifier:t(keyword),operatorKeyword:t(keyword),controlKeyword:t(keyword),definitionKeyword:t(keyword),moduleKeyword:t(keyword),operator,derefOperator:t(operator),arithmeticOperator:t(operator),logicOperator:t(operator),bitwiseOperator:t(operator),compareOperator:t(operator),updateOperator:t(operator),definitionOperator:t(operator),typeOperator:t(operator),controlOperator:t(operator),punctuation,separator:t(punctuation),bracket,angleBracket:t(bracket),squareBracket:t(bracket),paren:t(bracket),brace:t(bracket),content,heading,heading1:t(heading),heading2:t(heading),heading3:t(heading),heading4:t(heading),heading5:t(heading),heading6:t(heading),contentSeparator:t(content),list:t(content),quote:t(content),emphasis:t(content),strong:t(content),link:t(content),monospace:t(content),strikethrough:t(content),inserted:t(),deleted:t(),changed:t(),invalid:t(),meta,documentMeta:t(meta),annotation:t(meta),processingInstruction:t(meta),definition:Tag.defineModifier(),constant:Tag.defineModifier(),function:Tag.defineModifier(),standard:Tag.defineModifier(),local:Tag.defineModifier(),special:Tag.defineModifier()};tagHighlighter([{tag:tags.link,class:"tok-link"},{tag:tags.heading,class:"tok-heading"},{tag:tags.emphasis,class:"tok-emphasis"},{tag:tags.strong,class:"tok-strong"},{tag:tags.keyword,class:"tok-keyword"},{tag:tags.atom,class:"tok-atom"},{tag:tags.bool,class:"tok-bool"},{tag:tags.url,class:"tok-url"},{tag:tags.labelName,class:"tok-labelName"},{tag:tags.inserted,class:"tok-inserted"},{tag:tags.deleted,class:"tok-deleted"},{tag:tags.literal,class:"tok-literal"},{tag:tags.string,class:"tok-string"},{tag:tags.number,class:"tok-number"},{tag:[tags.regexp,tags.escape,tags.special(tags.string)],class:"tok-string2"},{tag:tags.variableName,class:"tok-variableName"},{tag:tags.local(tags.variableName),class:"tok-variableName tok-local"},{tag:tags.definition(tags.variableName),class:"tok-variableName tok-definition"},{tag:tags.special(tags.variableName),class:"tok-variableName2"},{tag:tags.definition(tags.propertyName),class:"tok-propertyName tok-definition"},{tag:tags.typeName,class:"tok-typeName"},{tag:tags.namespace,class:"tok-namespace"},{tag:tags.className,class:"tok-className"},{tag:tags.macroName,class:"tok-macroName"},{tag:tags.propertyName,class:"tok-propertyName"},{tag:tags.operator,class:"tok-operator"},{tag:tags.comment,class:"tok-comment"},{tag:tags.meta,class:"tok-meta"},{tag:tags.invalid,class:"tok-invalid"},{tag:tags.punctuation,class:"tok-punctuation"}]);var _a2;const languageDataProp=new NodeProp;function defineLanguageFacet(baseData){return Facet.define({combine:baseData?values=>values.concat(baseData):void 0})}__name(defineLanguageFacet,"defineLanguageFacet"),__name2(defineLanguageFacet,"defineLanguageFacet");const sublanguageProp=new NodeProp,_Language=class{static{__name(this,"_Language")}constructor(data,parser2,extraExtensions=[],name2=""){this.data=data,this.name=name2,EditorState.prototype.hasOwnProperty("tree")||Object.defineProperty(EditorState.prototype,"tree",{get(){return syntaxTree(this)}}),this.parser=parser2,this.extension=[language.of(this),EditorState.languageData.of((state,pos,side)=>{let top2=topNodeAt(state,pos,side),data2=top2.type.prop(languageDataProp);if(!data2)return[];let base2=state.facet(data2),sub=top2.type.prop(sublanguageProp);if(sub){let innerNode=top2.resolve(pos-top2.from,side);for(let sublang of sub)if(sublang.test(innerNode,state)){let data3=state.facet(sublang.facet);return sublang.type=="replace"?data3:data3.concat(base2)}}return base2})].concat(extraExtensions)}isActiveAt(state,pos,side=-1){return topNodeAt(state,pos,side).type.prop(languageDataProp)==this.data}findRegions(state){let lang=state.facet(language);if(lang?.data==this.data)return[{from:0,to:state.doc.length}];if(!lang||!lang.allowsNesting)return[];let result=[],explore=__name2((tree,from)=>{if(tree.prop(languageDataProp)==this.data){result.push({from,to:from+tree.length});return}let mount2=tree.prop(NodeProp.mounted);if(mount2){if(mount2.tree.prop(languageDataProp)==this.data){if(mount2.overlay)for(let r of mount2.overlay)result.push({from:r.from+from,to:r.to+from});else result.push({from,to:from+tree.length});return}else if(mount2.overlay){let size=result.length;if(explore(mount2.tree,mount2.overlay[0].from+from),result.length>size)return}}for(let i=0;itype.isTop?data:void 0)]}),spec.name)}configure(options,name2){return new _LRLanguage2(this.data,this.parser.configure(options),name2||this.name)}get allowsNesting(){return this.parser.hasWrappers()}};__name2(_LRLanguage,"LRLanguage");let LRLanguage=_LRLanguage;function syntaxTree(state){let field=state.field(Language.state,!1);return field?field.tree:Tree.empty}__name(syntaxTree,"syntaxTree"),__name2(syntaxTree,"syntaxTree");const _DocInput=class{static{__name(this,"_DocInput")}constructor(doc2){this.doc=doc2,this.cursorPos=0,this.string="",this.cursor=doc2.iter()}get length(){return this.doc.length}syncTo(pos){return this.string=this.cursor.next(pos-this.cursorPos).value,this.cursorPos=pos+this.string.length,this.cursorPos-this.string.length}chunk(pos){return this.syncTo(pos),this.string}get lineChunks(){return!0}read(from,to){let stringStart=this.cursorPos-this.string.length;return from=this.cursorPos?this.doc.sliceString(from,to):this.string.slice(from-stringStart,to-stringStart)}};__name2(_DocInput,"DocInput");let DocInput=_DocInput,currentContext=null;const _ParseContext=class _ParseContext2{static{__name(this,"_ParseContext")}constructor(parser2,state,fragments=[],tree,treeLen,viewport,skipped,scheduleOn){this.parser=parser2,this.state=state,this.fragments=fragments,this.tree=tree,this.treeLen=treeLen,this.viewport=viewport,this.skipped=skipped,this.scheduleOn=scheduleOn,this.parse=null,this.tempSkipped=[]}static create(parser2,state,viewport){return new _ParseContext2(parser2,state,[],Tree.empty,0,viewport,[],null)}startParse(){return this.parser.startParse(new DocInput(this.state.doc),this.fragments)}work(until,upto){return upto!=null&&upto>=this.state.doc.length&&(upto=void 0),this.tree!=Tree.empty&&this.isDone(upto??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var _a3;if(typeof until=="number"){let endTime=Date.now()+until;until=__name2(()=>Date.now()>endTime,"until")}for(this.parse||(this.parse=this.startParse()),upto!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>upto)&&upto=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>pos)&&this.parse.stopAt(pos),this.withContext(()=>{for(;!(tree=this.parse.advance()););}),this.treeLen=pos,this.tree=tree,this.fragments=this.withoutTempSkipped(TreeFragment.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(f){let prev=currentContext;currentContext=this;try{return f()}finally{currentContext=prev}}withoutTempSkipped(fragments){for(let r;r=this.tempSkipped.pop();)fragments=cutFragments(fragments,r.from,r.to);return fragments}changes(changes,newState){let{fragments,tree,treeLen,viewport,skipped}=this;if(this.takeTree(),!changes.empty){let ranges=[];if(changes.iterChangedRanges((fromA,toA,fromB,toB)=>ranges.push({fromA,toA,fromB,toB})),fragments=TreeFragment.applyChanges(fragments,ranges),tree=Tree.empty,treeLen=0,viewport={from:changes.mapPos(viewport.from,-1),to:changes.mapPos(viewport.to,1)},this.skipped.length){skipped=[];for(let r of this.skipped){let from=changes.mapPos(r.from,1),to=changes.mapPos(r.to,-1);fromviewport.from&&(this.fragments=cutFragments(this.fragments,from,to),this.skipped.splice(i--,1))}return this.skipped.length>=startLen?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(from,to){this.skipped.push({from,to})}static getSkippingParser(until){return new class extends Parser{createParse(input,fragments,ranges){let from=ranges[0].from,to=ranges[ranges.length-1].to;return{parsedPos:from,advance(){let cx=currentContext;if(cx){for(let r of ranges)cx.tempSkipped.push(r);until&&(cx.scheduleOn=cx.scheduleOn?Promise.all([cx.scheduleOn,until]):until)}return this.parsedPos=to,new Tree(NodeType.none,[],[],to-from)},stoppedAt:null,stopAt(){}}}}}isDone(upto){upto=Math.min(upto,this.state.doc.length);let frags=this.fragments;return this.treeLen>=upto&&frags.length&&frags[0].from==0&&frags[0].to>=upto}static get(){return currentContext}};__name2(_ParseContext,"ParseContext");let ParseContext=_ParseContext;function cutFragments(fragments,from,to){return TreeFragment.applyChanges(fragments,[{fromA:from,toA:to,fromB:from,toB:to}])}__name(cutFragments,"cutFragments"),__name2(cutFragments,"cutFragments");const _LanguageState=class _LanguageState2{static{__name(this,"_LanguageState")}constructor(context){this.context=context,this.tree=context.tree}apply(tr){if(!tr.docChanged&&this.tree==this.context.tree)return this;let newCx=this.context.changes(tr.changes,tr.state),upto=this.context.treeLen==tr.startState.doc.length?void 0:Math.max(tr.changes.mapPos(this.context.treeLen),newCx.viewport.to);return newCx.work(20,upto)||newCx.takeTree(),new _LanguageState2(newCx)}static init(state){let vpTo=Math.min(3e3,state.doc.length),parseState=ParseContext.create(state.facet(language).parser,state,{from:0,to:vpTo});return parseState.work(20,vpTo)||parseState.takeTree(),new _LanguageState2(parseState)}};__name2(_LanguageState,"LanguageState");let LanguageState=_LanguageState;Language.state=StateField.define({create:LanguageState.init,update(value,tr){for(let e of tr.effects)if(e.is(Language.setState))return e.value;return tr.startState.facet(language)!=tr.state.facet(language)?LanguageState.init(tr.state):value.apply(tr)}});let requestIdle=__name2(callback=>{let timeout=setTimeout(()=>callback(),500);return()=>clearTimeout(timeout)},"requestIdle");typeof requestIdleCallback<"u"&&(requestIdle=__name2(callback=>{let idle=-1,timeout=setTimeout(()=>{idle=requestIdleCallback(callback,{timeout:500-100})},100);return()=>idle<0?clearTimeout(timeout):cancelIdleCallback(idle)},"requestIdle"));const isInputPending=typeof navigator<"u"&&(!((_a2=navigator.scheduling)===null||_a2===void 0)&&_a2.isInputPending)?()=>navigator.scheduling.isInputPending():null,parseWorker=ViewPlugin.fromClass((_c=class{static{__name(this,"_c")}constructor(view){this.view=view,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(update){let cx=this.view.state.field(Language.state).context;(cx.updateViewport(update.view.viewport)||this.view.viewport.to>cx.treeLen)&&this.scheduleWork(),update.docChanged&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(cx)}scheduleWork(){if(this.working)return;let{state}=this.view,field=state.field(Language.state);(field.tree!=field.context.tree||!field.context.isDone(state.doc.length))&&(this.working=requestIdle(this.work))}work(deadline){this.working=null;let now2=Date.now();if(this.chunkEndvpTo+1e3,done=field.context.work(()=>isInputPending&&isInputPending()||Date.now()>endTime,vpTo+(viewportFirst?0:1e5));this.chunkBudget-=Date.now()-now2,(done||this.chunkBudget<=0)&&(field.context.takeTree(),this.view.dispatch({effects:Language.setState.of(new LanguageState(field.context))})),this.chunkBudget>0&&!(done&&!viewportFirst)&&this.scheduleWork(),this.checkAsyncSchedule(field.context)}checkAsyncSchedule(cx){cx.scheduleOn&&(this.workScheduled++,cx.scheduleOn.then(()=>this.scheduleWork()).catch(err=>logException(this.view.state,err)).then(()=>this.workScheduled--),cx.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},__name2(_c,"ParseWorker"),_c),{eventHandlers:{focus(){this.scheduleWork()}}}),language=Facet.define({combine(languages){return languages.length?languages[0]:null},enables:language2=>[Language.state,parseWorker,EditorView.contentAttributes.compute([language2],state=>{let lang=state.facet(language2);return lang&&lang.name?{"data-language":lang.name}:{}})]}),_LanguageSupport=class{static{__name(this,"_LanguageSupport")}constructor(language2,support=[]){this.language=language2,this.support=support,this.extension=[language2,support]}};__name2(_LanguageSupport,"LanguageSupport");let LanguageSupport=_LanguageSupport;const indentService=Facet.define(),indentUnit=Facet.define({combine:values=>{if(!values.length)return" ";let unit=values[0];if(!unit||/\S/.test(unit)||Array.from(unit).some(e=>e!=unit[0]))throw new Error("Invalid indent unit: "+JSON.stringify(values[0]));return unit}});function getIndentUnit(state){let unit=state.facet(indentUnit);return unit.charCodeAt(0)==9?state.tabSize*unit.length:unit.length}__name(getIndentUnit,"getIndentUnit"),__name2(getIndentUnit,"getIndentUnit");function indentString(state,cols){let result="",ts=state.tabSize,ch=state.facet(indentUnit)[0];if(ch==" "){for(;cols>=ts;)result+=" ",cols-=ts;ch=" "}for(let i=0;i=line.from&&simulateBreak<=line.to?simulateDoubleBreak&&simulateBreak==pos?{text:"",from:pos}:(bias<0?simulateBreak-1&&(result+=override-this.countColumn(text,text.search(/\S|$/))),result}countColumn(line,pos=line.length){return countColumn(line,this.state.tabSize,pos)}lineIndent(pos,bias=1){let{text,from}=this.lineAt(pos,bias),override=this.options.overrideIndentation;if(override){let overriden=override(from);if(overriden>-1)return overriden}return this.countColumn(text,text.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}};__name2(_IndentContext,"IndentContext");let IndentContext=_IndentContext;const indentNodeProp=new NodeProp;function syntaxIndentation(cx,ast,pos){return indentFrom(ast.resolveInner(pos).enterUnfinishedNodesBefore(pos),pos,cx)}__name(syntaxIndentation,"syntaxIndentation"),__name2(syntaxIndentation,"syntaxIndentation");function ignoreClosed(cx){return cx.pos==cx.options.simulateBreak&&cx.options.simulateDoubleBreak}__name(ignoreClosed,"ignoreClosed"),__name2(ignoreClosed,"ignoreClosed");function indentStrategy(tree){let strategy=tree.type.prop(indentNodeProp);if(strategy)return strategy;let first=tree.firstChild,close;if(first&&(close=first.type.prop(NodeProp.closedBy))){let last2=tree.lastChild,closed=last2&&close.indexOf(last2.name)>-1;return cx=>delimitedStrategy(cx,!0,1,void 0,closed&&!ignoreClosed(cx)?last2.from:void 0)}return tree.parent==null?topIndent:null}__name(indentStrategy,"indentStrategy"),__name2(indentStrategy,"indentStrategy");function indentFrom(node,pos,base2){for(;node;node=node.parent){let strategy=indentStrategy(node);if(strategy)return strategy(TreeIndentContext.create(base2,pos,node))}return null}__name(indentFrom,"indentFrom"),__name2(indentFrom,"indentFrom");function topIndent(){return 0}__name(topIndent,"topIndent"),__name2(topIndent,"topIndent");const _TreeIndentContext=class _TreeIndentContext2 extends IndentContext{static{__name(this,"_TreeIndentContext")}constructor(base2,pos,node){super(base2.state,base2.options),this.base=base2,this.pos=pos,this.node=node}static create(base2,pos,node){return new _TreeIndentContext2(base2,pos,node)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(node){let line=this.state.doc.lineAt(node.from);for(;;){let atBreak=node.resolve(line.from);for(;atBreak.parent&&atBreak.parent.from==atBreak.from;)atBreak=atBreak.parent;if(isParent(atBreak,node))break;line=this.state.doc.lineAt(atBreak.from)}return this.lineIndent(line.from)}continue(){let parent=this.node.parent;return parent?indentFrom(parent,this.pos,this.base):0}};__name2(_TreeIndentContext,"TreeIndentContext");let TreeIndentContext=_TreeIndentContext;function isParent(parent,of){for(let cur2=of;cur2;cur2=cur2.parent)if(parent==cur2)return!0;return!1}__name(isParent,"isParent"),__name2(isParent,"isParent");function bracketedAligned(context){let tree=context.node,openToken=tree.childAfter(tree.from),last2=tree.lastChild;if(!openToken)return null;let sim=context.options.simulateBreak,openLine=context.state.doc.lineAt(openToken.from),lineEnd=sim==null||sim<=openLine.from?openLine.to:Math.min(openLine.to,sim);for(let pos=openToken.to;;){let next=tree.childAfter(pos);if(!next||next==last2)return null;if(!next.type.isSkipped)return next.from{let matchExcept=except&&except.test(context.textAfter);return context.baseIndent+(matchExcept?0:units*context.unit)}}__name(continuedIndent,"continuedIndent"),__name2(continuedIndent,"continuedIndent");const DontIndentBeyond=200;function indentOnInput(){return EditorState.transactionFilter.of(tr=>{if(!tr.docChanged||!tr.isUserEvent("input.type")&&!tr.isUserEvent("input.complete"))return tr;let rules=tr.startState.languageDataAt("indentOnInput",tr.startState.selection.main.head);if(!rules.length)return tr;let doc2=tr.newDoc,{head}=tr.newSelection.main,line=doc2.lineAt(head);if(head>line.from+DontIndentBeyond)return tr;let lineStart=doc2.sliceString(line.from,head);if(!rules.some(r=>r.test(lineStart)))return tr;let{state}=tr,last2=-1,changes=[];for(let{head:head2}of state.selection.ranges){let line2=state.doc.lineAt(head2);if(line2.from==last2)continue;last2=line2.from;let indent=getIndentation(state,line2.from);if(indent==null)continue;let cur2=/^\s*/.exec(line2.text)[0],norm=indentString(state,indent);cur2!=norm&&changes.push({from:line2.from,to:line2.from+cur2.length,insert:norm})}return changes.length?[tr,{changes,sequential:!0}]:tr})}__name(indentOnInput,"indentOnInput"),__name2(indentOnInput,"indentOnInput");const foldService=Facet.define(),foldNodeProp=new NodeProp;function foldInside(node){let first=node.firstChild,last2=node.lastChild;return first&&first.toend)continue;if(found&&cur2.from=start&&value.to>end&&(found=value)}}return found}__name(syntaxFolding,"syntaxFolding"),__name2(syntaxFolding,"syntaxFolding");function isUnfinished(node){let ch=node.lastChild;return ch&&ch.to==node.to&&ch.type.isError}__name(isUnfinished,"isUnfinished"),__name2(isUnfinished,"isUnfinished");function foldable(state,lineStart,lineEnd){for(let service of state.facet(foldService)){let result=service(state,lineStart,lineEnd);if(result)return result}return syntaxFolding(state,lineStart,lineEnd)}__name(foldable,"foldable"),__name2(foldable,"foldable");function mapRange(range,mapping){let from=mapping.mapPos(range.from,1),to=mapping.mapPos(range.to,-1);return from>=to?void 0:{from,to}}__name(mapRange,"mapRange"),__name2(mapRange,"mapRange");const foldEffect=StateEffect.define({map:mapRange}),unfoldEffect=StateEffect.define({map:mapRange});function selectedLines(view){let lines=[];for(let{head}of view.state.selection.ranges)lines.some(l2=>l2.from<=head&&l2.to>=head)||lines.push(view.lineBlockAt(head));return lines}__name(selectedLines,"selectedLines"),__name2(selectedLines,"selectedLines");const foldState=StateField.define({create(){return Decoration.none},update(folded,tr){folded=folded.map(tr.changes);for(let e of tr.effects)e.is(foldEffect)&&!foldExists(folded,e.value.from,e.value.to)?folded=folded.update({add:[foldWidget.range(e.value.from,e.value.to)]}):e.is(unfoldEffect)&&(folded=folded.update({filter:(from,to)=>e.value.from!=from||e.value.to!=to,filterFrom:e.value.from,filterTo:e.value.to}));if(tr.selection){let onSelection=!1,{head}=tr.selection.main;folded.between(head,head,(a,b)=>{ahead&&(onSelection=!0)}),onSelection&&(folded=folded.update({filterFrom:head,filterTo:head,filter:(a,b)=>b<=head||a>=head}))}return folded},provide:f=>EditorView.decorations.from(f),toJSON(folded,state){let ranges=[];return folded.between(0,state.doc.length,(from,to)=>{ranges.push(from,to)}),ranges},fromJSON(value){if(!Array.isArray(value)||value.length%2)throw new RangeError("Invalid JSON for fold state");let ranges=[];for(let i=0;i{(!found||found.from>from2)&&(found={from:from2,to:to2})}),found}__name(findFold,"findFold"),__name2(findFold,"findFold");function foldExists(folded,from,to){let found=!1;return folded.between(from,from,(a,b)=>{a==from&&b==to&&(found=!0)}),found}__name(foldExists,"foldExists"),__name2(foldExists,"foldExists");function maybeEnable(state,other){return state.field(foldState,!1)?other:other.concat(StateEffect.appendConfig.of(codeFolding()))}__name(maybeEnable,"maybeEnable"),__name2(maybeEnable,"maybeEnable");const foldCode=__name2(view=>{for(let line of selectedLines(view)){let range=foldable(view.state,line.from,line.to);if(range)return view.dispatch({effects:maybeEnable(view.state,[foldEffect.of(range),announceFold(view,range)])}),!0}return!1},"foldCode"),unfoldCode=__name2(view=>{if(!view.state.field(foldState,!1))return!1;let effects=[];for(let line of selectedLines(view)){let folded=findFold(view.state,line.from,line.to);folded&&effects.push(unfoldEffect.of(folded),announceFold(view,folded,!1))}return effects.length&&view.dispatch({effects}),effects.length>0},"unfoldCode");function announceFold(view,range,fold=!0){let lineFrom=view.state.doc.lineAt(range.from).number,lineTo=view.state.doc.lineAt(range.to).number;return EditorView.announce.of(`${view.state.phrase(fold?"Folded lines":"Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`)}__name(announceFold,"announceFold"),__name2(announceFold,"announceFold");const foldAll=__name2(view=>{let{state}=view,effects=[];for(let pos=0;pos{let field=view.state.field(foldState,!1);if(!field||!field.size)return!1;let effects=[];return field.between(0,view.state.doc.length,(from,to)=>{effects.push(unfoldEffect.of({from,to}))}),view.dispatch({effects}),!0},"unfoldAll"),foldKeymap=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:foldCode},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:unfoldCode},{key:"Ctrl-Alt-[",run:foldAll},{key:"Ctrl-Alt-]",run:unfoldAll}],defaultConfig={placeholderDOM:null,placeholderText:"\u2026"},foldConfig=Facet.define({combine(values){return combineConfig(values,defaultConfig)}});function codeFolding(config2){let result=[foldState,baseTheme$1$1];return config2&&result.push(foldConfig.of(config2)),result}__name(codeFolding,"codeFolding"),__name2(codeFolding,"codeFolding");const foldWidget=Decoration.replace({widget:new class extends WidgetType{toDOM(view){let{state}=view,conf=state.facet(foldConfig),onclick=__name2(event=>{let line=view.lineBlockAt(view.posAtDOM(event.target)),folded=findFold(view.state,line.from,line.to);folded&&view.dispatch({effects:unfoldEffect.of(folded)}),event.preventDefault()},"onclick");if(conf.placeholderDOM)return conf.placeholderDOM(view,onclick);let element=document.createElement("span");return element.textContent=conf.placeholderText,element.setAttribute("aria-label",state.phrase("folded code")),element.title=state.phrase("unfold"),element.className="cm-foldPlaceholder",element.onclick=onclick,element}}}),foldGutterDefaults={openText:"\u2304",closedText:"\u203A",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1},_FoldMarker=class extends GutterMarker{static{__name(this,"_FoldMarker")}constructor(config2,open){super(),this.config=config2,this.open=open}eq(other){return this.config==other.config&&this.open==other.open}toDOM(view){if(this.config.markerDOM)return this.config.markerDOM(this.open);let span=document.createElement("span");return span.textContent=this.open?this.config.openText:this.config.closedText,span.title=view.state.phrase(this.open?"Fold line":"Unfold line"),span}};__name2(_FoldMarker,"FoldMarker");let FoldMarker=_FoldMarker;function foldGutter(config2={}){let fullConfig=Object.assign(Object.assign({},foldGutterDefaults),config2),canFold=new FoldMarker(fullConfig,!0),canUnfold=new FoldMarker(fullConfig,!1),markers=ViewPlugin.fromClass(class{constructor(view){this.from=view.viewport.from,this.markers=this.buildMarkers(view)}update(update){(update.docChanged||update.viewportChanged||update.startState.facet(language)!=update.state.facet(language)||update.startState.field(foldState,!1)!=update.state.field(foldState,!1)||syntaxTree(update.startState)!=syntaxTree(update.state)||fullConfig.foldingChanged(update))&&(this.markers=this.buildMarkers(update.view))}buildMarkers(view){let builder=new RangeSetBuilder;for(let line of view.viewportLineBlocks){let mark=findFold(view.state,line.from,line.to)?canUnfold:foldable(view.state,line.from,line.to)?canFold:null;mark&&builder.add(line.from,line.from,mark)}return builder.finish()}}),{domEventHandlers}=fullConfig;return[markers,gutter({class:"cm-foldGutter",markers(view){var _a3;return((_a3=view.plugin(markers))===null||_a3===void 0?void 0:_a3.markers)||RangeSet.empty},initialSpacer(){return new FoldMarker(fullConfig,!1)},domEventHandlers:Object.assign(Object.assign({},domEventHandlers),{click:(view,line,event)=>{if(domEventHandlers.click&&domEventHandlers.click(view,line,event))return!0;let folded=findFold(view.state,line.from,line.to);if(folded)return view.dispatch({effects:unfoldEffect.of(folded)}),!0;let range=foldable(view.state,line.from,line.to);return range?(view.dispatch({effects:foldEffect.of(range)}),!0):!1}})}),codeFolding()]}__name(foldGutter,"foldGutter"),__name2(foldGutter,"foldGutter");const baseTheme$1$1=EditorView.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}}),_HighlightStyle=class _HighlightStyle2{static{__name(this,"_HighlightStyle")}constructor(specs,options){this.specs=specs;let modSpec;function def(spec){let cls=StyleModule.newName();return(modSpec||(modSpec=Object.create(null)))["."+cls]=spec,cls}__name(def,"def"),__name2(def,"def");const all=typeof options.all=="string"?options.all:options.all?def(options.all):void 0,scopeOpt=options.scope;this.scope=scopeOpt instanceof Language?type=>type.prop(languageDataProp)==scopeOpt.data:scopeOpt?type=>type==scopeOpt:void 0,this.style=tagHighlighter(specs.map(style=>({tag:style.tag,class:style.class||def(Object.assign({},style,{tag:null}))})),{all}).style,this.module=modSpec?new StyleModule(modSpec):null,this.themeType=options.themeType}static define(specs,options){return new _HighlightStyle2(specs,options||{})}};__name2(_HighlightStyle,"HighlightStyle");let HighlightStyle=_HighlightStyle;const highlighterFacet=Facet.define(),fallbackHighlighter=Facet.define({combine(values){return values.length?[values[0]]:null}});function getHighlighters(state){let main=state.facet(highlighterFacet);return main.length?main:state.facet(fallbackHighlighter)}__name(getHighlighters,"getHighlighters"),__name2(getHighlighters,"getHighlighters");function syntaxHighlighting(highlighter,options){let ext=[treeHighlighter],themeType;return highlighter instanceof HighlightStyle&&(highlighter.module&&ext.push(EditorView.styleModule.of(highlighter.module)),themeType=highlighter.themeType),options?.fallback?ext.push(fallbackHighlighter.of(highlighter)):themeType?ext.push(highlighterFacet.computeN([EditorView.darkTheme],state=>state.facet(EditorView.darkTheme)==(themeType=="dark")?[highlighter]:[])):ext.push(highlighterFacet.of(highlighter)),ext}__name(syntaxHighlighting,"syntaxHighlighting"),__name2(syntaxHighlighting,"syntaxHighlighting");const _TreeHighlighter=class{static{__name(this,"_TreeHighlighter")}constructor(view){this.markCache=Object.create(null),this.tree=syntaxTree(view.state),this.decorations=this.buildDeco(view,getHighlighters(view.state))}update(update){let tree=syntaxTree(update.state),highlighters=getHighlighters(update.state),styleChange=highlighters!=getHighlighters(update.startState);tree.length{builder.add(from2,to2,this.markCache[style]||(this.markCache[style]=Decoration.mark({class:style})))},from,to);return builder.finish()}};__name2(_TreeHighlighter,"TreeHighlighter");let TreeHighlighter=_TreeHighlighter;const treeHighlighter=Prec.high(ViewPlugin.fromClass(TreeHighlighter,{decorations:v=>v.decorations})),defaultHighlightStyle=HighlightStyle.define([{tag:tags.meta,color:"#404740"},{tag:tags.link,textDecoration:"underline"},{tag:tags.heading,textDecoration:"underline",fontWeight:"bold"},{tag:tags.emphasis,fontStyle:"italic"},{tag:tags.strong,fontWeight:"bold"},{tag:tags.strikethrough,textDecoration:"line-through"},{tag:tags.keyword,color:"#708"},{tag:[tags.atom,tags.bool,tags.url,tags.contentSeparator,tags.labelName],color:"#219"},{tag:[tags.literal,tags.inserted],color:"#164"},{tag:[tags.string,tags.deleted],color:"#a11"},{tag:[tags.regexp,tags.escape,tags.special(tags.string)],color:"#e40"},{tag:tags.definition(tags.variableName),color:"#00f"},{tag:tags.local(tags.variableName),color:"#30a"},{tag:[tags.typeName,tags.namespace],color:"#085"},{tag:tags.className,color:"#167"},{tag:[tags.special(tags.variableName),tags.macroName],color:"#256"},{tag:tags.definition(tags.propertyName),color:"#00c"},{tag:tags.comment,color:"#940"},{tag:tags.invalid,color:"#f00"}]),baseTheme$4=EditorView.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),DefaultScanDist=1e4,DefaultBrackets="()[]{}",bracketMatchingConfig=Facet.define({combine(configs){return combineConfig(configs,{afterCursor:!0,brackets:DefaultBrackets,maxScanDistance:DefaultScanDist,renderMatch:defaultRenderMatch})}}),matchingMark=Decoration.mark({class:"cm-matchingBracket"}),nonmatchingMark=Decoration.mark({class:"cm-nonmatchingBracket"});function defaultRenderMatch(match2){let decorations2=[],mark=match2.matched?matchingMark:nonmatchingMark;return decorations2.push(mark.range(match2.start.from,match2.start.to)),match2.end&&decorations2.push(mark.range(match2.end.from,match2.end.to)),decorations2}__name(defaultRenderMatch,"defaultRenderMatch"),__name2(defaultRenderMatch,"defaultRenderMatch");const bracketMatchingState=StateField.define({create(){return Decoration.none},update(deco,tr){if(!tr.docChanged&&!tr.selection)return deco;let decorations2=[],config2=tr.state.facet(bracketMatchingConfig);for(let range of tr.state.selection.ranges){if(!range.empty)continue;let match2=matchBrackets(tr.state,range.head,-1,config2)||range.head>0&&matchBrackets(tr.state,range.head-1,1,config2)||config2.afterCursor&&(matchBrackets(tr.state,range.head,1,config2)||range.headEditorView.decorations.from(f)}),bracketMatchingUnique=[bracketMatchingState,baseTheme$4];function bracketMatching(config2={}){return[bracketMatchingConfig.of(config2),bracketMatchingUnique]}__name(bracketMatching,"bracketMatching"),__name2(bracketMatching,"bracketMatching");const bracketMatchingHandle=new NodeProp;function matchingNodes(node,dir,brackets){let byProp=node.prop(dir<0?NodeProp.openedBy:NodeProp.closedBy);if(byProp)return byProp;if(node.name.length==1){let index2=brackets.indexOf(node.name);if(index2>-1&&index2%2==(dir<0?1:0))return[brackets[index2+dir]]}return null}__name(matchingNodes,"matchingNodes"),__name2(matchingNodes,"matchingNodes");function findHandle(node){let hasHandle=node.type.prop(bracketMatchingHandle);return hasHandle?hasHandle(node.node):node}__name(findHandle,"findHandle"),__name2(findHandle,"findHandle");function matchBrackets(state,pos,dir,config2={}){let maxScanDistance=config2.maxScanDistance||DefaultScanDist,brackets=config2.brackets||DefaultBrackets,tree=syntaxTree(state),node=tree.resolveInner(pos,dir);for(let cur2=node;cur2;cur2=cur2.parent){let matches2=matchingNodes(cur2.type,dir,brackets);if(matches2&&cur2.from0?pos>=handle.from&&poshandle.from&&pos<=handle.to))return matchMarkedBrackets(state,pos,dir,cur2,handle,matches2,brackets)}}return matchPlainBrackets(state,pos,dir,tree,node.type,maxScanDistance,brackets)}__name(matchBrackets,"matchBrackets"),__name2(matchBrackets,"matchBrackets");function matchMarkedBrackets(_state,_pos,dir,token,handle,matching,brackets){let parent=token.parent,firstToken={from:handle.from,to:handle.to},depth=0,cursor=parent?.cursor();if(cursor&&(dir<0?cursor.childBefore(token.from):cursor.childAfter(token.to)))do if(dir<0?cursor.to<=token.from:cursor.from>=token.to){if(depth==0&&matching.indexOf(cursor.type.name)>-1&&cursor.from0)return null;let startToken={from:dir<0?pos-1:pos,to:dir>0?pos+1:pos},iter=state.doc.iterRange(pos,dir>0?state.doc.length:0),depth=0;for(let distance=0;!iter.next().done&&distance<=maxScanDistance;){let text=iter.value;dir<0&&(distance+=text.length);let basePos=pos+distance*dir;for(let pos2=dir>0?0:text.length-1,end=dir>0?text.length:-1;pos2!=end;pos2+=dir){let found=brackets.indexOf(text[pos2]);if(!(found<0||tree.resolveInner(basePos+pos2,1).type!=tokenType))if(found%2==0==dir>0)depth++;else{if(depth==1)return{start:startToken,end:{from:basePos+pos2,to:basePos+pos2+1},matched:found>>1==bracket2>>1};depth--}}dir>0&&(distance+=text.length)}return iter.done?{start:startToken,matched:!1}:null}__name(matchPlainBrackets,"matchPlainBrackets"),__name2(matchPlainBrackets,"matchPlainBrackets");const noTokens=Object.create(null),typeArray=[NodeType.none],warned=[],defaultTable=Object.create(null);for(let[legacyName,name2]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])defaultTable[legacyName]=createTokenType(noTokens,name2);function warnForPart(part,msg){warned.indexOf(part)>-1||(warned.push(part),console.warn(msg))}__name(warnForPart,"warnForPart"),__name2(warnForPart,"warnForPart");function createTokenType(extra,tagStr){let tag=null;for(let part of tagStr.split(".")){let value=extra[part]||tags[part];value?typeof value=="function"?tag?tag=value(tag):warnForPart(part,`Modifier ${part} used at start of tag`):tag?warnForPart(part,`Tag ${part} used as modifier`):tag=value:warnForPart(part,`Unknown highlighting tag ${part}`)}if(!tag)return 0;let name2=tagStr.replace(/ /g,"_"),type=NodeType.define({id:typeArray.length,name:name2,props:[styleTags({[name2]:tag})]});return typeArray.push(type),type.id}__name(createTokenType,"createTokenType"),__name2(createTokenType,"createTokenType");const _CompletionContext=class{static{__name(this,"_CompletionContext")}constructor(state,pos,explicit){this.state=state,this.pos=pos,this.explicit=explicit,this.abortListeners=[]}tokenBefore(types2){let token=syntaxTree(this.state).resolveInner(this.pos,-1);for(;token&&types2.indexOf(token.name)<0;)token=token.parent;return token?{from:token.from,to:this.pos,text:this.state.sliceDoc(token.from,this.pos),type:token.type}:null}matchBefore(expr){let line=this.state.doc.lineAt(this.pos),start=Math.max(line.from,this.pos-250),str=line.text.slice(start-line.from,this.pos-line.from),found=str.search(ensureAnchor(expr,!1));return found<0?null:{from:start+found,to:this.pos,text:str.slice(found)}}get aborted(){return this.abortListeners==null}addEventListener(type,listener){type=="abort"&&this.abortListeners&&this.abortListeners.push(listener)}};__name2(_CompletionContext,"CompletionContext");let CompletionContext=_CompletionContext;function toSet(chars){let flat=Object.keys(chars).join(""),words=/\w/.test(flat);return words&&(flat=flat.replace(/\w/g,"")),`[${words?"\\w":""}${flat.replace(/[^\w\s]/g,"\\$&")}]`}__name(toSet,"toSet"),__name2(toSet,"toSet");function prefixMatch(options){let first=Object.create(null),rest=Object.create(null);for(let{label}of options){first[label[0]]=!0;for(let i=1;itypeof o=="string"?{label:o}:o),[validFor,match2]=options.every(o=>/^\w+$/.test(o.label))?[/\w*$/,/\w+$/]:prefixMatch(options);return context=>{let token=context.matchBefore(match2);return token||context.explicit?{from:token?token.from:context.pos,options,validFor}:null}}__name(completeFromList,"completeFromList"),__name2(completeFromList,"completeFromList");const _Option=class{static{__name(this,"_Option")}constructor(completion,source,match2,score2){this.completion=completion,this.source=source,this.match=match2,this.score=score2}};__name2(_Option,"Option");let Option=_Option;function cur(state){return state.selection.main.from}__name(cur,"cur"),__name2(cur,"cur");function ensureAnchor(expr,start){var _a3;let{source}=expr,addStart=start&&source[0]!="^",addEnd=source[source.length-1]!="$";return!addStart&&!addEnd?expr:new RegExp(`${addStart?"^":""}(?:${source})${addEnd?"$":""}`,(_a3=expr.flags)!==null&&_a3!==void 0?_a3:expr.ignoreCase?"i":"")}__name(ensureAnchor,"ensureAnchor"),__name2(ensureAnchor,"ensureAnchor");const pickedCompletion=Annotation.define();function insertCompletionText(state,text,from,to){let{main}=state.selection,fromOff=from-main.from,toOff=to-main.from;return Object.assign(Object.assign({},state.changeByRange(range=>range!=main&&from!=to&&state.sliceDoc(range.from+fromOff,range.from+toOff)!=state.sliceDoc(from,to)?{range}:{changes:{from:range.from+fromOff,to:to==main.from?range.to:range.from+toOff,insert:text},range:EditorSelection.cursor(range.from+fromOff+text.length)})),{scrollIntoView:!0,userEvent:"input.complete"})}__name(insertCompletionText,"insertCompletionText"),__name2(insertCompletionText,"insertCompletionText");const SourceCache=new WeakMap;function asSource(source){if(!Array.isArray(source))return source;let known=SourceCache.get(source);return known||SourceCache.set(source,known=completeFromList(source)),known}__name(asSource,"asSource"),__name2(asSource,"asSource");const startCompletionEffect=StateEffect.define(),closeCompletionEffect=StateEffect.define(),_FuzzyMatcher=class{static{__name(this,"_FuzzyMatcher")}constructor(pattern){this.pattern=pattern,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let p=0;p=48&&next<=57||next>=97&&next<=122?2:next>=65&&next<=90?1:0:(ch=fromCodePoint(next))!=ch.toLowerCase()?1:ch!=ch.toUpperCase()?2:0;(!i||type==1&&hasLower||prevType==0&&type!=0)&&(chars[byWordTo]==next||folded[byWordTo]==next&&(byWordFolded=!0)?byWord[byWordTo++]=i:byWord.length&&(wordAdjacent=!1)),prevType=type,i+=codePointSize(next)}return byWordTo==len&&byWord[0]==0&&wordAdjacent?this.result(-100+(byWordFolded?-200:0),byWord,word):adjacentTo==len&&adjacentStart==0?this.ret(-200-word.length+(adjacentEnd==word.length?0:-100),[0,adjacentEnd]):direct>-1?this.ret(-700-word.length,[direct,direct+this.pattern.length]):adjacentTo==len?this.ret(-200+-700-word.length,[adjacentStart,adjacentEnd]):byWordTo==len?this.result(-100+(byWordFolded?-200:0)+-700+(wordAdjacent?0:-1100),byWord,word):chars.length==2?!1:this.result((any[0]?-700:0)+-200+-1100,any,word)}result(score2,positions,word){let result=[],i=0;for(let pos of positions){let to=pos+(this.astral?codePointSize(codePointAt(word,pos)):1);i&&result[i-1]==pos?result[i-1]=to:(result[i++]=pos,result[i++]=to)}return this.ret(score2-word.length,result)}};__name2(_FuzzyMatcher,"FuzzyMatcher");let FuzzyMatcher=_FuzzyMatcher;const completionConfig=Facet.define({combine(configs){return combineConfig(configs,{activateOnTyping:!0,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:defaultPositionInfo,compareCompletions:(a,b)=>a.label.localeCompare(b.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(a,b)=>a&&b,closeOnBlur:(a,b)=>a&&b,icons:(a,b)=>a&&b,tooltipClass:(a,b)=>c=>joinClass(a(c),b(c)),optionClass:(a,b)=>c=>joinClass(a(c),b(c)),addToOptions:(a,b)=>a.concat(b)})}});function joinClass(a,b){return a?b?a+" "+b:a:b}__name(joinClass,"joinClass"),__name2(joinClass,"joinClass");function defaultPositionInfo(view,list,option2,info,space,tooltip){let rtl=view.textDirection==Direction.RTL,left=rtl,narrow=!1,side="top",offset2,maxWidth,spaceLeft=list.left-space.left,spaceRight=space.right-list.right,infoWidth=info.right-info.left,infoHeight=info.bottom-info.top;if(left&&spaceLeft=infoHeight||spaceBelow>list.top?offset2=option2.bottom-list.top:(side="bottom",offset2=list.bottom-option2.top)}let scaleY=(list.bottom-list.top)/tooltip.offsetHeight,scaleX=(list.right-list.left)/tooltip.offsetWidth;return{style:`${side}: ${offset2/scaleY}px; max-width: ${maxWidth/scaleX}px`,class:"cm-completionInfo-"+(narrow?rtl?"left-narrow":"right-narrow":left?"left":"right")}}__name(defaultPositionInfo,"defaultPositionInfo"),__name2(defaultPositionInfo,"defaultPositionInfo");function optionContent(config2){let content2=config2.addToOptions.slice();return config2.icons&&content2.push({render(completion){let icon=document.createElement("div");return icon.classList.add("cm-completionIcon"),completion.type&&icon.classList.add(...completion.type.split(/\s+/g).map(cls=>"cm-completionIcon-"+cls)),icon.setAttribute("aria-hidden","true"),icon},position:20}),content2.push({render(completion,_s,match2){let labelElt=document.createElement("span");labelElt.className="cm-completionLabel";let label=completion.displayLabel||completion.label,off2=0;for(let j=0;joff2&&labelElt.appendChild(document.createTextNode(label.slice(off2,from)));let span=labelElt.appendChild(document.createElement("span"));span.appendChild(document.createTextNode(label.slice(from,to))),span.className="cm-completionMatchedText",off2=to}return off2a.position-b.position).map(a=>a.render)}__name(optionContent,"optionContent"),__name2(optionContent,"optionContent");function rangeAroundSelected(total,selected,max){if(total<=max)return{from:0,to:total};if(selected<0&&(selected=0),selected<=total>>1){let off3=Math.floor(selected/max);return{from:off3*max,to:(off3+1)*max}}let off2=Math.floor((total-selected)/max);return{from:total-(off2+1)*max,to:total-off2*max}}__name(rangeAroundSelected,"rangeAroundSelected"),__name2(rangeAroundSelected,"rangeAroundSelected");const _CompletionTooltip=class{static{__name(this,"_CompletionTooltip")}constructor(view,stateField,applyCompletion2){this.view=view,this.stateField=stateField,this.applyCompletion=applyCompletion2,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:pos=>this.placeInfo(pos),key:this},this.space=null,this.currentClass="";let cState=view.state.field(stateField),{options,selected}=cState.open,config2=view.state.facet(completionConfig);this.optionContent=optionContent(config2),this.optionClass=config2.optionClass,this.tooltipClass=config2.tooltipClass,this.range=rangeAroundSelected(options.length,selected,config2.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(view.state),this.dom.addEventListener("mousedown",e=>{let{options:options2}=view.state.field(stateField).open;for(let dom=e.target,match2;dom&&dom!=this.dom;dom=dom.parentNode)if(dom.nodeName=="LI"&&(match2=/-(\d+)$/.exec(dom.id))&&+match2[1]{let state=view.state.field(this.stateField,!1);state&&state.tooltip&&view.state.facet(completionConfig).closeOnBlur&&e.relatedTarget!=view.contentDOM&&view.dispatch({effects:closeCompletionEffect.of(null)})}),this.showOptions(options,cState.id)}mount(){this.updateSel()}showOptions(options,id){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(options,id,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(update){var _a3;let cState=update.state.field(this.stateField),prevState=update.startState.field(this.stateField);if(this.updateTooltipClass(update.state),cState!=prevState){let{options,selected,disabled}=cState.open;(!prevState.open||prevState.open.options!=options)&&(this.range=rangeAroundSelected(options.length,selected,update.state.facet(completionConfig).maxRenderedOptions),this.showOptions(options,cState.id)),this.updateSel(),disabled!=((_a3=prevState.open)===null||_a3===void 0?void 0:_a3.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!disabled)}}updateTooltipClass(state){let cls=this.tooltipClass(state);if(cls!=this.currentClass){for(let c of this.currentClass.split(" "))c&&this.dom.classList.remove(c);for(let c of cls.split(" "))c&&this.dom.classList.add(c);this.currentClass=cls}}positioned(space){this.space=space,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let cState=this.view.state.field(this.stateField),open=cState.open;if((open.selected>-1&&open.selected=this.range.to)&&(this.range=rangeAroundSelected(open.options.length,open.selected,this.view.state.facet(completionConfig).maxRenderedOptions),this.showOptions(open.options,cState.id)),this.updateSelectedOption(open.selected)){this.destroyInfo();let{completion}=open.options[open.selected],{info}=completion;if(!info)return;let infoResult=typeof info=="string"?document.createTextNode(info):info(completion);if(!infoResult)return;"then"in infoResult?infoResult.then(obj=>{obj&&this.view.state.field(this.stateField,!1)==cState&&this.addInfoPane(obj,completion)}).catch(e=>logException(this.view.state,e,"completion info")):this.addInfoPane(infoResult,completion)}}addInfoPane(content2,completion){this.destroyInfo();let wrap=this.info=document.createElement("div");if(wrap.className="cm-tooltip cm-completionInfo",content2.nodeType!=null)wrap.appendChild(content2),this.infoDestroy=null;else{let{dom,destroy:destroy2}=content2;wrap.appendChild(dom),this.infoDestroy=destroy2||null}this.dom.appendChild(wrap),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(selected){let set=null;for(let opt=this.list.firstChild,i=this.range.from;opt;opt=opt.nextSibling,i++)opt.nodeName!="LI"||!opt.id?i--:i==selected?opt.hasAttribute("aria-selected")||(opt.setAttribute("aria-selected","true"),set=opt):opt.hasAttribute("aria-selected")&&opt.removeAttribute("aria-selected");return set&&scrollIntoView(this.list,set),set}measureInfo(){let sel=this.dom.querySelector("[aria-selected]");if(!sel||!this.info)return null;let listRect=this.dom.getBoundingClientRect(),infoRect=this.info.getBoundingClientRect(),selRect=sel.getBoundingClientRect(),space=this.space;if(!space){let win=this.dom.ownerDocument.defaultView||window;space={left:0,top:0,right:win.innerWidth,bottom:win.innerHeight}}return selRect.top>Math.min(space.bottom,listRect.bottom)-10||selRect.bottomrange.from||range.from==0))if(curSection=name2,typeof section!="string"&§ion.header)ul.appendChild(section.header(section));else{let header=ul.appendChild(document.createElement("completion-section"));header.textContent=name2}}const li=ul.appendChild(document.createElement("li"));li.id=id+"-"+i,li.setAttribute("role","option");let cls=this.optionClass(completion);cls&&(li.className=cls);for(let source of this.optionContent){let node=source(completion,this.view.state,match2);node&&li.appendChild(node)}}return range.from&&ul.classList.add("cm-completionListIncompleteTop"),range.tonew CompletionTooltip(view,stateField,applyCompletion2)}__name(completionTooltip,"completionTooltip"),__name2(completionTooltip,"completionTooltip");function scrollIntoView(container,element){let parent=container.getBoundingClientRect(),self2=element.getBoundingClientRect(),scaleY=parent.height/container.offsetHeight;self2.topparent.bottom&&(container.scrollTop+=(self2.bottom-parent.bottom)/scaleY)}__name(scrollIntoView,"scrollIntoView"),__name2(scrollIntoView,"scrollIntoView");function score(option2){return(option2.boost||0)*100+(option2.apply?10:0)+(option2.info?5:0)+(option2.type?1:0)}__name(score,"score"),__name2(score,"score");function sortOptions(active,state){let options=[],sections=null,addOption=__name2(option2=>{options.push(option2);let{section}=option2.completion;if(section){sections||(sections=[]);let name2=typeof section=="string"?section:section.name;sections.some(s2=>s2.name==name2)||sections.push(typeof section=="string"?{name:name2}:section)}},"addOption");for(let a of active)if(a.hasResult()){let getMatch=a.result.getMatch;if(a.result.filter===!1)for(let option2 of a.result.options)addOption(new Option(option2,a.source,getMatch?getMatch(option2):[],1e9-options.length));else{let matcher=new FuzzyMatcher(state.sliceDoc(a.from,a.to));for(let option2 of a.result.options)if(matcher.match(option2.label)){let matched=option2.displayLabel?getMatch?getMatch(option2,matcher.matched):[]:matcher.matched;addOption(new Option(option2,a.source,matched,matcher.score+(option2.boost||0)))}}}if(sections){let sectionOrder=Object.create(null),pos=0,cmp=__name2((a,b)=>{var _a3,_b2;return((_a3=a.rank)!==null&&_a3!==void 0?_a3:1e9)-((_b2=b.rank)!==null&&_b2!==void 0?_b2:1e9)||(a.nameb.score-a.score||compare2(a.completion,b.completion))){let cur2=opt.completion;!prev||prev.label!=cur2.label||prev.detail!=cur2.detail||prev.type!=null&&cur2.type!=null&&prev.type!=cur2.type||prev.apply!=cur2.apply||prev.boost!=cur2.boost?result.push(opt):score(opt.completion)>score(prev)&&(result[result.length-1]=opt),prev=opt.completion}return result}__name(sortOptions,"sortOptions"),__name2(sortOptions,"sortOptions");const _CompletionDialog=class _CompletionDialog2{static{__name(this,"_CompletionDialog")}constructor(options,attrs,tooltip,timestamp,selected,disabled){this.options=options,this.attrs=attrs,this.tooltip=tooltip,this.timestamp=timestamp,this.selected=selected,this.disabled=disabled}setSelected(selected,id){return selected==this.selected||selected>=this.options.length?this:new _CompletionDialog2(this.options,makeAttrs(id,selected),this.tooltip,this.timestamp,selected,this.disabled)}static build(active,state,id,prev,conf){let options=sortOptions(active,state);if(!options.length)return prev&&active.some(a=>a.state==1)?new _CompletionDialog2(prev.options,prev.attrs,prev.tooltip,prev.timestamp,prev.selected,!0):null;let selected=state.facet(completionConfig).selectOnOpen?0:-1;if(prev&&prev.selected!=selected&&prev.selected!=-1){let selectedValue=prev.options[prev.selected].completion;for(let i=0;ib.hasResult()?Math.min(a,b.from):a,1e8),create:createTooltip,above:conf.aboveCursor},prev?prev.timestamp:Date.now(),selected,!1)}map(changes){return new _CompletionDialog2(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:changes.mapPos(this.tooltip.pos)}),this.timestamp,this.selected,this.disabled)}};__name2(_CompletionDialog,"CompletionDialog");let CompletionDialog=_CompletionDialog;const _CompletionState=class _CompletionState2{static{__name(this,"_CompletionState")}constructor(active,id,open){this.active=active,this.id=id,this.open=open}static start(){return new _CompletionState2(none$1,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(tr){let{state}=tr,conf=state.facet(completionConfig),active=(conf.override||state.languageDataAt("autocomplete",cur(state)).map(asSource)).map(source=>(this.active.find(s2=>s2.source==source)||new ActiveSource(source,this.active.some(a=>a.state!=0)?1:0)).update(tr,conf));active.length==this.active.length&&active.every((a,i)=>a==this.active[i])&&(active=this.active);let open=this.open;open&&tr.docChanged&&(open=open.map(tr.changes)),tr.selection||active.some(a=>a.hasResult()&&tr.changes.touchesRange(a.from,a.to))||!sameResults(active,this.active)?open=CompletionDialog.build(active,state,this.id,open,conf):open&&open.disabled&&!active.some(a=>a.state==1)&&(open=null),!open&&active.every(a=>a.state!=1)&&active.some(a=>a.hasResult())&&(active=active.map(a=>a.hasResult()?new ActiveSource(a.source,0):a));for(let effect of tr.effects)effect.is(setSelectedEffect)&&(open=open&&open.setSelected(effect.value,this.id));return active==this.active&&open==this.open?this:new _CompletionState2(active,this.id,open)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:baseAttrs}};__name2(_CompletionState,"CompletionState");let CompletionState=_CompletionState;function sameResults(a,b){if(a==b)return!0;for(let iA=0,iB=0;;){for(;iA-1&&(result["aria-activedescendant"]=id+"-"+selected),result}__name(makeAttrs,"makeAttrs"),__name2(makeAttrs,"makeAttrs");const none$1=[];function getUserEvent(tr){return tr.isUserEvent("input.type")?"input":tr.isUserEvent("delete.backward")?"delete":null}__name(getUserEvent,"getUserEvent"),__name2(getUserEvent,"getUserEvent");const _ActiveSource=class _ActiveSource2{static{__name(this,"_ActiveSource")}constructor(source,state,explicitPos=-1){this.source=source,this.state=state,this.explicitPos=explicitPos}hasResult(){return!1}update(tr,conf){let event=getUserEvent(tr),value=this;event?value=value.handleUserEvent(tr,event,conf):tr.docChanged?value=value.handleChange(tr):tr.selection&&value.state!=0&&(value=new _ActiveSource2(value.source,0));for(let effect of tr.effects)if(effect.is(startCompletionEffect))value=new _ActiveSource2(value.source,1,effect.value?cur(tr.state):-1);else if(effect.is(closeCompletionEffect))value=new _ActiveSource2(value.source,0);else if(effect.is(setActiveEffect))for(let active of effect.value)active.source==value.source&&(value=active);return value}handleUserEvent(tr,type,conf){return type=="delete"||!conf.activateOnTyping?this.map(tr.changes):new _ActiveSource2(this.source,1)}handleChange(tr){return tr.changes.touchesRange(cur(tr.startState))?new _ActiveSource2(this.source,0):this.map(tr.changes)}map(changes){return changes.empty||this.explicitPos<0?this:new _ActiveSource2(this.source,this.state,changes.mapPos(this.explicitPos))}};__name2(_ActiveSource,"ActiveSource");let ActiveSource=_ActiveSource;const _ActiveResult=class _ActiveResult2 extends ActiveSource{static{__name(this,"_ActiveResult")}constructor(source,explicitPos,result,from,to){super(source,2,explicitPos),this.result=result,this.from=from,this.to=to}hasResult(){return!0}handleUserEvent(tr,type,conf){var _a3;let from=tr.changes.mapPos(this.from),to=tr.changes.mapPos(this.to,1),pos=cur(tr.state);if((this.explicitPos<0?pos<=from:posto||type=="delete"&&cur(tr.startState)==this.from)return new ActiveSource(this.source,type=="input"&&conf.activateOnTyping?1:0);let explicitPos=this.explicitPos<0?-1:tr.changes.mapPos(this.explicitPos),updated;return checkValid(this.result.validFor,tr.state,from,to)?new _ActiveResult2(this.source,explicitPos,this.result,from,to):this.result.update&&(updated=this.result.update(this.result,from,to,new CompletionContext(tr.state,pos,explicitPos>=0)))?new _ActiveResult2(this.source,explicitPos,updated,updated.from,(_a3=updated.to)!==null&&_a3!==void 0?_a3:cur(tr.state)):new ActiveSource(this.source,1,explicitPos)}handleChange(tr){return tr.changes.touchesRange(this.from,this.to)?new ActiveSource(this.source,0):this.map(tr.changes)}map(mapping){return mapping.empty?this:new _ActiveResult2(this.source,this.explicitPos<0?-1:mapping.mapPos(this.explicitPos),this.result,mapping.mapPos(this.from),mapping.mapPos(this.to,1))}};__name2(_ActiveResult,"ActiveResult");let ActiveResult=_ActiveResult;function checkValid(validFor,state,from,to){if(!validFor)return!1;let text=state.sliceDoc(from,to);return typeof validFor=="function"?validFor(text,from,to,state):ensureAnchor(validFor,!0).test(text)}__name(checkValid,"checkValid"),__name2(checkValid,"checkValid");const setActiveEffect=StateEffect.define({map(sources,mapping){return sources.map(s2=>s2.map(mapping))}}),setSelectedEffect=StateEffect.define(),completionState=StateField.define({create(){return CompletionState.start()},update(value,tr){return value.update(tr)},provide:f=>[showTooltip.from(f,val=>val.tooltip),EditorView.contentAttributes.from(f,state=>state.attrs)]});function applyCompletion(view,option2){const apply=option2.completion.apply||option2.completion.label;let result=view.state.field(completionState).active.find(a=>a.source==option2.source);return result instanceof ActiveResult?(typeof apply=="string"?view.dispatch(Object.assign(Object.assign({},insertCompletionText(view.state,apply,result.from,result.to)),{annotations:pickedCompletion.of(option2.completion)})):apply(view,option2.completion,result.from,result.to),!0):!1}__name(applyCompletion,"applyCompletion"),__name2(applyCompletion,"applyCompletion");const createTooltip=completionTooltip(completionState,applyCompletion);function moveCompletionSelection(forward,by="option"){return view=>{let cState=view.state.field(completionState,!1);if(!cState||!cState.open||cState.open.disabled||Date.now()-cState.open.timestamp-1?cState.open.selected+step*(forward?1:-1):forward?0:length-1;return selected<0?selected=by=="page"?0:length-1:selected>=length&&(selected=by=="page"?length-1:0),view.dispatch({effects:setSelectedEffect.of(selected)}),!0}}__name(moveCompletionSelection,"moveCompletionSelection"),__name2(moveCompletionSelection,"moveCompletionSelection");const acceptCompletion=__name2(view=>{let cState=view.state.field(completionState,!1);return view.state.readOnly||!cState||!cState.open||cState.open.selected<0||cState.open.disabled||Date.now()-cState.open.timestampview.state.field(completionState,!1)?(view.dispatch({effects:startCompletionEffect.of(!0)}),!0):!1,"startCompletion"),closeCompletion=__name2(view=>{let cState=view.state.field(completionState,!1);return!cState||!cState.active.some(a=>a.state!=0)?!1:(view.dispatch({effects:closeCompletionEffect.of(null)}),!0)},"closeCompletion"),_RunningQuery=class{static{__name(this,"_RunningQuery")}constructor(active,context){this.active=active,this.context=context,this.time=Date.now(),this.updates=[],this.done=void 0}};__name2(_RunningQuery,"RunningQuery");let RunningQuery=_RunningQuery;const MaxUpdateCount=50,MinAbortTime=1e3,completionPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.composing=0;for(let active of view.state.field(completionState).active)active.state==1&&this.startQuery(active)}update(update){let cState=update.state.field(completionState);if(!update.selectionSet&&!update.docChanged&&update.startState.field(completionState)==cState)return;let doesReset=update.transactions.some(tr=>(tr.selection||tr.docChanged)&&!getUserEvent(tr));for(let i=0;iMaxUpdateCount&&Date.now()-query.time>MinAbortTime){for(let handler of query.context.abortListeners)try{handler()}catch(e){logException(this.view.state,e)}query.context.abortListeners=null,this.running.splice(i--,1)}else query.updates.push(...update.transactions)}if(this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),this.debounceUpdate=cState.active.some(a=>a.state==1&&!this.running.some(q=>q.active.source==a.source))?setTimeout(()=>this.startUpdate(),50):-1,this.composing!=0)for(let tr of update.transactions)getUserEvent(tr)=="input"?this.composing=2:this.composing==2&&tr.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1;let{state}=this.view,cState=state.field(completionState);for(let active of cState.active)active.state==1&&!this.running.some(r=>r.active.source==active.source)&&this.startQuery(active)}startQuery(active){let{state}=this.view,pos=cur(state),context=new CompletionContext(state,pos,active.explicitPos==pos),pending=new RunningQuery(active,context);this.running.push(pending),Promise.resolve(active.source(context)).then(result=>{pending.context.aborted||(pending.done=result||null,this.scheduleAccept())},err=>{this.view.dispatch({effects:closeCompletionEffect.of(null)}),logException(this.view.state,err)})}scheduleAccept(){this.running.every(q=>q.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(completionConfig).updateSyncTime))}accept(){var _a3;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let updated=[],conf=this.view.state.facet(completionConfig);for(let i=0;ia.source==query.active.source);if(current&¤t.state==1)if(query.done==null){let active=new ActiveSource(query.active.source,0);for(let tr of query.updates)active=active.update(tr,conf);active.state!=1&&updated.push(active)}else this.startQuery(current)}updated.length&&this.view.dispatch({effects:setActiveEffect.of(updated)})}},{eventHandlers:{blur(event){let state=this.view.state.field(completionState,!1);if(state&&state.tooltip&&this.view.state.facet(completionConfig).closeOnBlur){let dialog=state.open&&getTooltip(this.view,state.open.tooltip);(!dialog||!dialog.dom.contains(event.relatedTarget))&&this.view.dispatch({effects:closeCompletionEffect.of(null)})}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:startCompletionEffect.of(!1)}),20),this.composing=0}}}),baseTheme$3=EditorView.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"\xB7\xB7\xB7"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'\u0192'"}},".cm-completionIcon-class":{"&:after":{content:"'\u25CB'"}},".cm-completionIcon-interface":{"&:after":{content:"'\u25CC'"}},".cm-completionIcon-variable":{"&:after":{content:"'\u{1D465}'"}},".cm-completionIcon-constant":{"&:after":{content:"'\u{1D436}'"}},".cm-completionIcon-type":{"&:after":{content:"'\u{1D461}'"}},".cm-completionIcon-enum":{"&:after":{content:"'\u222A'"}},".cm-completionIcon-property":{"&:after":{content:"'\u25A1'"}},".cm-completionIcon-keyword":{"&:after":{content:"'\u{1F511}\uFE0E'"}},".cm-completionIcon-namespace":{"&:after":{content:"'\u25A2'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}}),defaults={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},closeBracketEffect=StateEffect.define({map(value,mapping){let mapped=mapping.mapPos(value,-1,MapMode.TrackAfter);return mapped??void 0}}),closedBracket=new class extends RangeValue{};closedBracket.startSide=1,closedBracket.endSide=-1;const bracketState=StateField.define({create(){return RangeSet.empty},update(value,tr){if(tr.selection){let lineStart=tr.state.doc.lineAt(tr.selection.main.head).from,prevLineStart=tr.startState.doc.lineAt(tr.startState.selection.main.head).from;lineStart!=tr.changes.mapPos(prevLineStart,-1)&&(value=RangeSet.empty)}value=value.map(tr.changes);for(let effect of tr.effects)effect.is(closeBracketEffect)&&(value=value.update({add:[closedBracket.range(effect.value,effect.value+1)]}));return value}});function closeBrackets(){return[inputHandler,bracketState]}__name(closeBrackets,"closeBrackets"),__name2(closeBrackets,"closeBrackets");const definedClosing="()[]{}<>";function closing(ch){for(let i=0;i{if((android?view.composing:view.compositionStarted)||view.state.readOnly)return!1;let sel=view.state.selection.main;if(insert2.length>2||insert2.length==2&&codePointSize(codePointAt(insert2,0))==1||from!=sel.from||to!=sel.to)return!1;let tr=insertBracket(view.state,insert2);return tr?(view.dispatch(tr),!0):!1}),deleteBracketPair=__name2(({state,dispatch})=>{if(state.readOnly)return!1;let tokens=config(state,state.selection.main.head).brackets||defaults.brackets,dont=null,changes=state.changeByRange(range=>{if(range.empty){let before=prevChar(state.doc,range.head);for(let token of tokens)if(token==before&&nextChar(state.doc,range.head)==closing(codePointAt(token,0)))return{changes:{from:range.head-token.length,to:range.head+token.length},range:EditorSelection.cursor(range.head-token.length)}}return{range:dont=range}});return dont||dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"delete.backward"})),!dont},"deleteBracketPair"),closeBracketsKeymap=[{key:"Backspace",run:deleteBracketPair}];function insertBracket(state,bracket2){let conf=config(state,state.selection.main.head),tokens=conf.brackets||defaults.brackets;for(let tok of tokens){let closed=closing(codePointAt(tok,0));if(bracket2==tok)return closed==tok?handleSame(state,tok,tokens.indexOf(tok+tok+tok)>-1,conf):handleOpen(state,tok,closed,conf.before||defaults.before);if(bracket2==closed&&closedBracketAt(state,state.selection.main.from))return handleClose(state,tok,closed)}return null}__name(insertBracket,"insertBracket"),__name2(insertBracket,"insertBracket");function closedBracketAt(state,pos){let found=!1;return state.field(bracketState).between(0,state.doc.length,from=>{from==pos&&(found=!0)}),found}__name(closedBracketAt,"closedBracketAt"),__name2(closedBracketAt,"closedBracketAt");function nextChar(doc2,pos){let next=doc2.sliceString(pos,pos+2);return next.slice(0,codePointSize(codePointAt(next,0)))}__name(nextChar,"nextChar"),__name2(nextChar,"nextChar");function prevChar(doc2,pos){let prev=doc2.sliceString(pos-2,pos);return codePointSize(codePointAt(prev,0))==prev.length?prev:prev.slice(1)}__name(prevChar,"prevChar"),__name2(prevChar,"prevChar");function handleOpen(state,open,close,closeBefore){let dont=null,changes=state.changeByRange(range=>{if(!range.empty)return{changes:[{insert:open,from:range.from},{insert:close,from:range.to}],effects:closeBracketEffect.of(range.to+open.length),range:EditorSelection.range(range.anchor+open.length,range.head+open.length)};let next=nextChar(state.doc,range.head);return!next||/\s/.test(next)||closeBefore.indexOf(next)>-1?{changes:{insert:open+close,from:range.head},effects:closeBracketEffect.of(range.head+open.length),range:EditorSelection.cursor(range.head+open.length)}:{range:dont=range}});return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}__name(handleOpen,"handleOpen"),__name2(handleOpen,"handleOpen");function handleClose(state,_open,close){let dont=null,changes=state.changeByRange(range=>range.empty&&nextChar(state.doc,range.head)==close?{changes:{from:range.head,to:range.head+close.length,insert:close},range:EditorSelection.cursor(range.head+close.length)}:dont={range});return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}__name(handleClose,"handleClose"),__name2(handleClose,"handleClose");function handleSame(state,token,allowTriple,config2){let stringPrefixes=config2.stringPrefixes||defaults.stringPrefixes,dont=null,changes=state.changeByRange(range=>{if(!range.empty)return{changes:[{insert:token,from:range.from},{insert:token,from:range.to}],effects:closeBracketEffect.of(range.to+token.length),range:EditorSelection.range(range.anchor+token.length,range.head+token.length)};let pos=range.head,next=nextChar(state.doc,pos),start;if(next==token){if(nodeStart(state,pos))return{changes:{insert:token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)};if(closedBracketAt(state,pos)){let content2=allowTriple&&state.sliceDoc(pos,pos+token.length*3)==token+token+token?token+token+token:token;return{changes:{from:pos,to:pos+content2.length,insert:content2},range:EditorSelection.cursor(pos+content2.length)}}}else{if(allowTriple&&state.sliceDoc(pos-2*token.length,pos)==token+token&&(start=canStartStringAt(state,pos-2*token.length,stringPrefixes))>-1&&nodeStart(state,start))return{changes:{insert:token+token+token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)};if(state.charCategorizer(pos)(next)!=CharCategory.Word&&canStartStringAt(state,pos,stringPrefixes)>-1&&!probablyInString(state,pos,token,stringPrefixes))return{changes:{insert:token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)}}return{range:dont=range}});return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}__name(handleSame,"handleSame"),__name2(handleSame,"handleSame");function nodeStart(state,pos){let tree=syntaxTree(state).resolveInner(pos+1);return tree.parent&&tree.from==pos}__name(nodeStart,"nodeStart"),__name2(nodeStart,"nodeStart");function probablyInString(state,pos,quoteToken,prefixes){let node=syntaxTree(state).resolveInner(pos,-1),maxPrefix=prefixes.reduce((m,p)=>Math.max(m,p.length),0);for(let i=0;i<5;i++){let start=state.sliceDoc(node.from,Math.min(node.to,node.from+quoteToken.length+maxPrefix)),quotePos=start.indexOf(quoteToken);if(!quotePos||quotePos>-1&&prefixes.indexOf(start.slice(0,quotePos))>-1){let first=node.firstChild;for(;first&&first.from==node.from&&first.to-first.from>quoteToken.length+quotePos;){if(state.sliceDoc(first.to-quoteToken.length,first.to)==quoteToken)return!1;first=first.firstChild}return!0}let parent=node.to==pos&&node.parent;if(!parent)break;node=parent}return!1}__name(probablyInString,"probablyInString"),__name2(probablyInString,"probablyInString");function canStartStringAt(state,pos,prefixes){let charCat=state.charCategorizer(pos);if(charCat(state.sliceDoc(pos-1,pos))!=CharCategory.Word)return pos;for(let prefix of prefixes){let start=pos-prefix.length;if(state.sliceDoc(start,pos)==prefix&&charCat(state.sliceDoc(start-1,start))!=CharCategory.Word)return start}return-1}__name(canStartStringAt,"canStartStringAt"),__name2(canStartStringAt,"canStartStringAt");function autocompletion(config2={}){return[completionState,completionConfig.of(config2),completionPlugin,completionKeymapExt,baseTheme$3]}__name(autocompletion,"autocompletion"),__name2(autocompletion,"autocompletion");const completionKeymap=[{key:"Ctrl-Space",run:startCompletion},{key:"Escape",run:closeCompletion},{key:"ArrowDown",run:moveCompletionSelection(!0)},{key:"ArrowUp",run:moveCompletionSelection(!1)},{key:"PageDown",run:moveCompletionSelection(!0,"page")},{key:"PageUp",run:moveCompletionSelection(!1,"page")},{key:"Enter",run:acceptCompletion}],completionKeymapExt=Prec.highest(keymap.computeN([completionConfig],state=>state.facet(completionConfig).defaultKeymap?[completionKeymap]:[])),toggleComment=__name2(target=>{let{state}=target,line=state.doc.lineAt(state.selection.main.from),config2=getConfig(target.state,line.from);return config2.line?toggleLineComment(target):config2.block?toggleBlockCommentByLine(target):!1},"toggleComment");function command(f,option2){return({state,dispatch})=>{if(state.readOnly)return!1;let tr=f(option2,state);return tr?(dispatch(state.update(tr)),!0):!1}}__name(command,"command"),__name2(command,"command");const toggleLineComment=command(changeLineComment,0),toggleBlockComment=command(changeBlockComment,0),toggleBlockCommentByLine=command((o,s2)=>changeBlockComment(o,s2,selectedLineRanges(s2)),0);function getConfig(state,pos){let data=state.languageDataAt("commentTokens",pos);return data.length?data[0]:{}}__name(getConfig,"getConfig"),__name2(getConfig,"getConfig");const SearchMargin=50;function findBlockComment(state,{open,close},from,to){let textBefore=state.sliceDoc(from-SearchMargin,from),textAfter=state.sliceDoc(to,to+SearchMargin),spaceBefore=/\s*$/.exec(textBefore)[0].length,spaceAfter=/^\s*/.exec(textAfter)[0].length,beforeOff=textBefore.length-spaceBefore;if(textBefore.slice(beforeOff-open.length,beforeOff)==open&&textAfter.slice(spaceAfter,spaceAfter+close.length)==close)return{open:{pos:from-spaceBefore,margin:spaceBefore&&1},close:{pos:to+spaceAfter,margin:spaceAfter&&1}};let startText,endText;to-from<=2*SearchMargin?startText=endText=state.sliceDoc(from,to):(startText=state.sliceDoc(from,from+SearchMargin),endText=state.sliceDoc(to-SearchMargin,to));let startSpace=/^\s*/.exec(startText)[0].length,endSpace=/\s*$/.exec(endText)[0].length,endOff=endText.length-endSpace-close.length;return startText.slice(startSpace,startSpace+open.length)==open&&endText.slice(endOff,endOff+close.length)==close?{open:{pos:from+startSpace+open.length,margin:/\s/.test(startText.charAt(startSpace+open.length))?1:0},close:{pos:to-endSpace-close.length,margin:/\s/.test(endText.charAt(endOff-1))?1:0}}:null}__name(findBlockComment,"findBlockComment"),__name2(findBlockComment,"findBlockComment");function selectedLineRanges(state){let ranges=[];for(let r of state.selection.ranges){let fromLine=state.doc.lineAt(r.from),toLine=r.to<=fromLine.to?fromLine:state.doc.lineAt(r.to),last2=ranges.length-1;last2>=0&&ranges[last2].to>fromLine.from?ranges[last2].to=toLine.to:ranges.push({from:fromLine.from+/^\s*/.exec(fromLine.text)[0].length,to:toLine.to})}return ranges}__name(selectedLineRanges,"selectedLineRanges"),__name2(selectedLineRanges,"selectedLineRanges");function changeBlockComment(option2,state,ranges=state.selection.ranges){let tokens=ranges.map(r=>getConfig(state,r.from).block);if(!tokens.every(c=>c))return null;let comments=ranges.map((r,i)=>findBlockComment(state,tokens[i],r.from,r.to));if(option2!=2&&!comments.every(c=>c))return{changes:state.changes(ranges.map((range,i)=>comments[i]?[]:[{from:range.from,insert:tokens[i].open+" "},{from:range.to,insert:" "+tokens[i].close}]))};if(option2!=1&&comments.some(c=>c)){let changes=[];for(let i=0,comment2;iprevLine&&(from==to||to>line.from)){prevLine=line.from;let indent=/^\s*/.exec(line.text)[0].length,empty2=indent==line.length,comment2=line.text.slice(indent,indent+token.length)==token?indent:-1;indentl2.comment<0&&(!l2.empty||l2.single))){let changes=[];for(let{line,token,indent,empty:empty2,single}of lines)(single||!empty2)&&changes.push({from:line.from+indent,insert:token+" "});let changeSet=state.changes(changes);return{changes:changeSet,selection:state.selection.map(changeSet,1)}}else if(option2!=1&&lines.some(l2=>l2.comment>=0)){let changes=[];for(let{line,comment:comment2,token}of lines)if(comment2>=0){let from=line.from+comment2,to=from+token.length;line.text[to-line.from]==" "&&to++,changes.push({from,to})}return{changes}}return null}__name(changeLineComment,"changeLineComment"),__name2(changeLineComment,"changeLineComment");const fromHistory=Annotation.define(),isolateHistory=Annotation.define(),invertedEffects=Facet.define(),historyConfig=Facet.define({combine(configs){return combineConfig(configs,{minDepth:100,newGroupDelay:500,joinToEvent:(_t,isAdjacent2)=>isAdjacent2},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(a,b)=>(tr,adj)=>a(tr,adj)||b(tr,adj)})}});function changeEnd(changes){let end=0;return changes.iterChangedRanges((_,to)=>end=to),end}__name(changeEnd,"changeEnd"),__name2(changeEnd,"changeEnd");const historyField_=StateField.define({create(){return HistoryState.empty},update(state,tr){let config2=tr.state.facet(historyConfig),fromHist=tr.annotation(fromHistory);if(fromHist){let selection=tr.docChanged?EditorSelection.single(changeEnd(tr.changes)):void 0,item=HistEvent.fromTransaction(tr,selection),from=fromHist.side,other=from==0?state.undone:state.done;return item?other=updateBranch(other,other.length,config2.minDepth,item):other=addSelection(other,tr.startState.selection),new HistoryState(from==0?fromHist.rest:other,from==0?other:fromHist.rest)}let isolate=tr.annotation(isolateHistory);if((isolate=="full"||isolate=="before")&&(state=state.isolate()),tr.annotation(Transaction.addToHistory)===!1)return tr.changes.empty?state:state.addMapping(tr.changes.desc);let event=HistEvent.fromTransaction(tr),time=tr.annotation(Transaction.time),userEvent=tr.annotation(Transaction.userEvent);return event?state=state.addChanges(event,time,userEvent,config2,tr):tr.selection&&(state=state.addSelection(tr.startState.selection,time,userEvent,config2.newGroupDelay)),(isolate=="full"||isolate=="after")&&(state=state.isolate()),state},toJSON(value){return{done:value.done.map(e=>e.toJSON()),undone:value.undone.map(e=>e.toJSON())}},fromJSON(json2){return new HistoryState(json2.done.map(HistEvent.fromJSON),json2.undone.map(HistEvent.fromJSON))}});function history(config2={}){return[historyField_,historyConfig.of(config2),EditorView.domEventHandlers({beforeinput(e,view){let command2=e.inputType=="historyUndo"?undo:e.inputType=="historyRedo"?redo:null;return command2?(e.preventDefault(),command2(view)):!1}})]}__name(history,"history"),__name2(history,"history");function cmd(side,selection){return function({state,dispatch}){if(!selection&&state.readOnly)return!1;let historyState=state.field(historyField_,!1);if(!historyState)return!1;let tr=historyState.pop(side,state,selection);return tr?(dispatch(tr),!0):!1}}__name(cmd,"cmd"),__name2(cmd,"cmd");const undo=cmd(0,!1),redo=cmd(1,!1),undoSelection=cmd(0,!0),redoSelection=cmd(1,!0),_HistEvent=class _HistEvent2{static{__name(this,"_HistEvent")}constructor(changes,effects,mapped,startSelection,selectionsAfter){this.changes=changes,this.effects=effects,this.mapped=mapped,this.startSelection=startSelection,this.selectionsAfter=selectionsAfter}setSelAfter(after){return new _HistEvent2(this.changes,this.effects,this.mapped,this.startSelection,after)}toJSON(){var _a3,_b2,_c2;return{changes:(_a3=this.changes)===null||_a3===void 0?void 0:_a3.toJSON(),mapped:(_b2=this.mapped)===null||_b2===void 0?void 0:_b2.toJSON(),startSelection:(_c2=this.startSelection)===null||_c2===void 0?void 0:_c2.toJSON(),selectionsAfter:this.selectionsAfter.map(s2=>s2.toJSON())}}static fromJSON(json2){return new _HistEvent2(json2.changes&&ChangeSet.fromJSON(json2.changes),[],json2.mapped&&ChangeDesc.fromJSON(json2.mapped),json2.startSelection&&EditorSelection.fromJSON(json2.startSelection),json2.selectionsAfter.map(EditorSelection.fromJSON))}static fromTransaction(tr,selection){let effects=none;for(let invert of tr.startState.facet(invertedEffects)){let result=invert(tr);result.length&&(effects=effects.concat(result))}return!effects.length&&tr.changes.empty?null:new _HistEvent2(tr.changes.invert(tr.startState.doc),effects,void 0,selection||tr.startState.selection,none)}static selection(selections){return new _HistEvent2(void 0,none,void 0,void 0,selections)}};__name2(_HistEvent,"HistEvent");let HistEvent=_HistEvent;function updateBranch(branch,to,maxLen,newEvent){let start=to+1>maxLen+20?to-maxLen-1:0,newBranch=branch.slice(start,to);return newBranch.push(newEvent),newBranch}__name(updateBranch,"updateBranch"),__name2(updateBranch,"updateBranch");function isAdjacent(a,b){let ranges=[],isAdjacent2=!1;return a.iterChangedRanges((f,t2)=>ranges.push(f,t2)),b.iterChangedRanges((_f,_t,f,t2)=>{for(let i=0;i=from&&f<=to&&(isAdjacent2=!0)}}),isAdjacent2}__name(isAdjacent,"isAdjacent"),__name2(isAdjacent,"isAdjacent");function eqSelectionShape(a,b){return a.ranges.length==b.ranges.length&&a.ranges.filter((r,i)=>r.empty!=b.ranges[i].empty).length===0}__name(eqSelectionShape,"eqSelectionShape"),__name2(eqSelectionShape,"eqSelectionShape");function conc(a,b){return a.length?b.length?a.concat(b):a:b}__name(conc,"conc"),__name2(conc,"conc");const none=[],MaxSelectionsPerEvent=200;function addSelection(branch,selection){if(branch.length){let lastEvent=branch[branch.length-1],sels=lastEvent.selectionsAfter.slice(Math.max(0,lastEvent.selectionsAfter.length-MaxSelectionsPerEvent));return sels.length&&sels[sels.length-1].eq(selection)?branch:(sels.push(selection),updateBranch(branch,branch.length-1,1e9,lastEvent.setSelAfter(sels)))}else return[HistEvent.selection([selection])]}__name(addSelection,"addSelection"),__name2(addSelection,"addSelection");function popSelection(branch){let last2=branch[branch.length-1],newBranch=branch.slice();return newBranch[branch.length-1]=last2.setSelAfter(last2.selectionsAfter.slice(0,last2.selectionsAfter.length-1)),newBranch}__name(popSelection,"popSelection"),__name2(popSelection,"popSelection");function addMappingToBranch(branch,mapping){if(!branch.length)return branch;let length=branch.length,selections=none;for(;length;){let event=mapEvent(branch[length-1],mapping,selections);if(event.changes&&!event.changes.empty||event.effects.length){let result=branch.slice(0,length);return result[length-1]=event,result}else mapping=event.mapped,length--,selections=event.selectionsAfter}return selections.length?[HistEvent.selection(selections)]:none}__name(addMappingToBranch,"addMappingToBranch"),__name2(addMappingToBranch,"addMappingToBranch");function mapEvent(event,mapping,extraSelections){let selections=conc(event.selectionsAfter.length?event.selectionsAfter.map(s2=>s2.map(mapping)):none,extraSelections);if(!event.changes)return HistEvent.selection(selections);let mappedChanges=event.changes.map(mapping),before=mapping.mapDesc(event.changes,!0),fullMapping=event.mapped?event.mapped.composeDesc(before):before;return new HistEvent(mappedChanges,StateEffect.mapEffects(event.effects,mapping),fullMapping,event.startSelection.map(before),selections)}__name(mapEvent,"mapEvent"),__name2(mapEvent,"mapEvent");const joinableUserEvent=/^(input\.type|delete)($|\.)/,_HistoryState=class _HistoryState2{static{__name(this,"_HistoryState")}constructor(done,undone,prevTime=0,prevUserEvent=void 0){this.done=done,this.undone=undone,this.prevTime=prevTime,this.prevUserEvent=prevUserEvent}isolate(){return this.prevTime?new _HistoryState2(this.done,this.undone):this}addChanges(event,time,userEvent,config2,tr){let done=this.done,lastEvent=done[done.length-1];return lastEvent&&lastEvent.changes&&!lastEvent.changes.empty&&event.changes&&(!userEvent||joinableUserEvent.test(userEvent))&&(!lastEvent.selectionsAfter.length&&time-this.prevTime0&&time-this.prevTimerange.empty?view.moveByChar(range,forward):rangeEnd(range,forward))}__name(cursorByChar,"cursorByChar"),__name2(cursorByChar,"cursorByChar");function ltrAtCursor(view){return view.textDirectionAt(view.state.selection.main.head)==Direction.LTR}__name(ltrAtCursor,"ltrAtCursor"),__name2(ltrAtCursor,"ltrAtCursor");const cursorCharLeft=__name2(view=>cursorByChar(view,!ltrAtCursor(view)),"cursorCharLeft"),cursorCharRight=__name2(view=>cursorByChar(view,ltrAtCursor(view)),"cursorCharRight");function cursorByGroup(view,forward){return moveSel(view,range=>range.empty?view.moveByGroup(range,forward):rangeEnd(range,forward))}__name(cursorByGroup,"cursorByGroup"),__name2(cursorByGroup,"cursorByGroup");const cursorGroupLeft=__name2(view=>cursorByGroup(view,!ltrAtCursor(view)),"cursorGroupLeft"),cursorGroupRight=__name2(view=>cursorByGroup(view,ltrAtCursor(view)),"cursorGroupRight");function interestingNode(state,node,bracketProp){if(node.type.prop(bracketProp))return!0;let len=node.to-node.from;return len&&(len>2||/[^\s,.;:]/.test(state.sliceDoc(node.from,node.to)))||node.firstChild}__name(interestingNode,"interestingNode"),__name2(interestingNode,"interestingNode");function moveBySyntax(state,start,forward){let pos=syntaxTree(state).resolveInner(start.head),bracketProp=forward?NodeProp.closedBy:NodeProp.openedBy;for(let at=start.head;;){let next=forward?pos.childAfter(at):pos.childBefore(at);if(!next)break;interestingNode(state,next,bracketProp)?pos=next:at=forward?next.to:next.from}let bracket2=pos.type.prop(bracketProp),match2,newPos;return bracket2&&(match2=forward?matchBrackets(state,pos.from,1):matchBrackets(state,pos.to,-1))&&match2.matched?newPos=forward?match2.end.to:match2.end.from:newPos=forward?pos.to:pos.from,EditorSelection.cursor(newPos,forward?-1:1)}__name(moveBySyntax,"moveBySyntax"),__name2(moveBySyntax,"moveBySyntax");const cursorSyntaxLeft=__name2(view=>moveSel(view,range=>moveBySyntax(view.state,range,!ltrAtCursor(view))),"cursorSyntaxLeft"),cursorSyntaxRight=__name2(view=>moveSel(view,range=>moveBySyntax(view.state,range,ltrAtCursor(view))),"cursorSyntaxRight");function cursorByLine(view,forward){return moveSel(view,range=>{if(!range.empty)return rangeEnd(range,forward);let moved2=view.moveVertically(range,forward);return moved2.head!=range.head?moved2:view.moveToLineBoundary(range,forward)})}__name(cursorByLine,"cursorByLine"),__name2(cursorByLine,"cursorByLine");const cursorLineUp=__name2(view=>cursorByLine(view,!1),"cursorLineUp"),cursorLineDown=__name2(view=>cursorByLine(view,!0),"cursorLineDown");function pageInfo(view){let selfScroll=view.scrollDOM.clientHeightrange.empty?view.moveVertically(range,forward,page.height):rangeEnd(range,forward));if(selection.eq(state.selection))return!1;let effect;if(page.selfScroll){let startPos=view.coordsAtPos(state.selection.main.head),scrollRect=view.scrollDOM.getBoundingClientRect(),scrollTop=scrollRect.top+page.marginTop,scrollBottom=scrollRect.bottom-page.marginBottom;startPos&&startPos.top>scrollTop&&startPos.bottomcursorByPage(view,!1),"cursorPageUp"),cursorPageDown=__name2(view=>cursorByPage(view,!0),"cursorPageDown");function moveByLineBoundary(view,start,forward){let line=view.lineBlockAt(start.head),moved2=view.moveToLineBoundary(start,forward);if(moved2.head==start.head&&moved2.head!=(forward?line.to:line.from)&&(moved2=view.moveToLineBoundary(start,forward,!1)),!forward&&moved2.head==line.from&&line.length){let space=/^\s*/.exec(view.state.sliceDoc(line.from,Math.min(line.from+100,line.to)))[0].length;space&&start.head!=line.from+space&&(moved2=EditorSelection.cursor(line.from+space))}return moved2}__name(moveByLineBoundary,"moveByLineBoundary"),__name2(moveByLineBoundary,"moveByLineBoundary");const cursorLineBoundaryForward=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,!0)),"cursorLineBoundaryForward"),cursorLineBoundaryBackward=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,!1)),"cursorLineBoundaryBackward"),cursorLineBoundaryLeft=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,!ltrAtCursor(view))),"cursorLineBoundaryLeft"),cursorLineBoundaryRight=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,ltrAtCursor(view))),"cursorLineBoundaryRight"),cursorLineStart=__name2(view=>moveSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).from,1)),"cursorLineStart"),cursorLineEnd=__name2(view=>moveSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).to,-1)),"cursorLineEnd");function toMatchingBracket(state,dispatch,extend2){let found=!1,selection=updateSel(state.selection,range=>{let matching=matchBrackets(state,range.head,-1)||matchBrackets(state,range.head,1)||range.head>0&&matchBrackets(state,range.head-1,1)||range.headtoMatchingBracket(state,dispatch,!1),"cursorMatchingBracket");function extendSel(view,how){let selection=updateSel(view.state.selection,range=>{let head=how(range);return EditorSelection.range(range.anchor,head.head,head.goalColumn,head.bidiLevel||void 0)});return selection.eq(view.state.selection)?!1:(view.dispatch(setSel(view.state,selection)),!0)}__name(extendSel,"extendSel"),__name2(extendSel,"extendSel");function selectByChar(view,forward){return extendSel(view,range=>view.moveByChar(range,forward))}__name(selectByChar,"selectByChar"),__name2(selectByChar,"selectByChar");const selectCharLeft=__name2(view=>selectByChar(view,!ltrAtCursor(view)),"selectCharLeft"),selectCharRight=__name2(view=>selectByChar(view,ltrAtCursor(view)),"selectCharRight");function selectByGroup(view,forward){return extendSel(view,range=>view.moveByGroup(range,forward))}__name(selectByGroup,"selectByGroup"),__name2(selectByGroup,"selectByGroup");const selectGroupLeft=__name2(view=>selectByGroup(view,!ltrAtCursor(view)),"selectGroupLeft"),selectGroupRight=__name2(view=>selectByGroup(view,ltrAtCursor(view)),"selectGroupRight"),selectSyntaxLeft=__name2(view=>extendSel(view,range=>moveBySyntax(view.state,range,!ltrAtCursor(view))),"selectSyntaxLeft"),selectSyntaxRight=__name2(view=>extendSel(view,range=>moveBySyntax(view.state,range,ltrAtCursor(view))),"selectSyntaxRight");function selectByLine(view,forward){return extendSel(view,range=>view.moveVertically(range,forward))}__name(selectByLine,"selectByLine"),__name2(selectByLine,"selectByLine");const selectLineUp=__name2(view=>selectByLine(view,!1),"selectLineUp"),selectLineDown=__name2(view=>selectByLine(view,!0),"selectLineDown");function selectByPage(view,forward){return extendSel(view,range=>view.moveVertically(range,forward,pageInfo(view).height))}__name(selectByPage,"selectByPage"),__name2(selectByPage,"selectByPage");const selectPageUp=__name2(view=>selectByPage(view,!1),"selectPageUp"),selectPageDown=__name2(view=>selectByPage(view,!0),"selectPageDown"),selectLineBoundaryForward=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,!0)),"selectLineBoundaryForward"),selectLineBoundaryBackward=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,!1)),"selectLineBoundaryBackward"),selectLineBoundaryLeft=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,!ltrAtCursor(view))),"selectLineBoundaryLeft"),selectLineBoundaryRight=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,ltrAtCursor(view))),"selectLineBoundaryRight"),selectLineStart=__name2(view=>extendSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).from)),"selectLineStart"),selectLineEnd=__name2(view=>extendSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).to)),"selectLineEnd"),cursorDocStart=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:0})),!0),"cursorDocStart"),cursorDocEnd=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:state.doc.length})),!0),"cursorDocEnd"),selectDocStart=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:state.selection.main.anchor,head:0})),!0),"selectDocStart"),selectDocEnd=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:state.selection.main.anchor,head:state.doc.length})),!0),"selectDocEnd"),selectAll=__name2(({state,dispatch})=>(dispatch(state.update({selection:{anchor:0,head:state.doc.length},userEvent:"select"})),!0),"selectAll"),selectLine=__name2(({state,dispatch})=>{let ranges=selectedLineBlocks(state).map(({from,to})=>EditorSelection.range(from,Math.min(to+1,state.doc.length)));return dispatch(state.update({selection:EditorSelection.create(ranges),userEvent:"select"})),!0},"selectLine"),selectParentSyntax=__name2(({state,dispatch})=>{let selection=updateSel(state.selection,range=>{var _a3;let context=syntaxTree(state).resolveInner(range.head,1);for(;!(context.from=range.to||context.to>range.to&&context.from<=range.from||!(!((_a3=context.parent)===null||_a3===void 0)&&_a3.parent));)context=context.parent;return EditorSelection.range(context.to,context.from)});return dispatch(setSel(state,selection)),!0},"selectParentSyntax"),simplifySelection=__name2(({state,dispatch})=>{let cur2=state.selection,selection=null;return cur2.ranges.length>1?selection=EditorSelection.create([cur2.main]):cur2.main.empty||(selection=EditorSelection.create([EditorSelection.cursor(cur2.main.head)])),selection?(dispatch(setSel(state,selection)),!0):!1},"simplifySelection");function deleteBy(target,by){if(target.state.readOnly)return!1;let event="delete.selection",{state}=target,changes=state.changeByRange(range=>{let{from,to}=range;if(from==to){let towards=by(from);towardsfrom&&(event="delete.forward",towards=skipAtomic(target,towards,!0)),from=Math.min(from,towards),to=Math.max(to,towards)}else from=skipAtomic(target,from,!1),to=skipAtomic(target,to,!0);return from==to?{range}:{changes:{from,to},range:EditorSelection.cursor(from)}});return changes.changes.empty?!1:(target.dispatch(state.update(changes,{scrollIntoView:!0,userEvent:event,effects:event=="delete.selection"?EditorView.announce.of(state.phrase("Selection deleted")):void 0})),!0)}__name(deleteBy,"deleteBy"),__name2(deleteBy,"deleteBy");function skipAtomic(target,pos,forward){if(target instanceof EditorView)for(let ranges of target.state.facet(EditorView.atomicRanges).map(f=>f(target)))ranges.between(pos,pos,(from,to)=>{frompos&&(pos=forward?to:from)});return pos}__name(skipAtomic,"skipAtomic"),__name2(skipAtomic,"skipAtomic");const deleteByChar=__name2((target,forward)=>deleteBy(target,pos=>{let{state}=target,line=state.doc.lineAt(pos),before,targetPos;if(!forward&&pos>line.from&&posdeleteByChar(view,!1),"deleteCharBackward"),deleteCharForward=__name2(view=>deleteByChar(view,!0),"deleteCharForward"),deleteByGroup=__name2((target,forward)=>deleteBy(target,start=>{let pos=start,{state}=target,line=state.doc.lineAt(pos),categorize=state.charCategorizer(pos);for(let cat=null;;){if(pos==(forward?line.to:line.from)){pos==start&&line.number!=(forward?state.doc.lines:1)&&(pos+=forward?1:-1);break}let next=findClusterBreak(line.text,pos-line.from,forward)+line.from,nextChar2=line.text.slice(Math.min(pos,next)-line.from,Math.max(pos,next)-line.from),nextCat=categorize(nextChar2);if(cat!=null&&nextCat!=cat)break;(nextChar2!=" "||pos!=start)&&(cat=nextCat),pos=next}return pos}),"deleteByGroup"),deleteGroupBackward=__name2(target=>deleteByGroup(target,!1),"deleteGroupBackward"),deleteGroupForward=__name2(target=>deleteByGroup(target,!0),"deleteGroupForward"),deleteToLineEnd=__name2(view=>deleteBy(view,pos=>{let lineEnd=view.lineBlockAt(pos).to;return posdeleteBy(view,pos=>{let lineStart=view.lineBlockAt(pos).from;return pos>lineStart?lineStart:Math.max(0,pos-1)}),"deleteToLineStart"),splitLine=__name2(({state,dispatch})=>{if(state.readOnly)return!1;let changes=state.changeByRange(range=>({changes:{from:range.from,to:range.to,insert:Text.of(["",""])},range:EditorSelection.cursor(range.from)}));return dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"input"})),!0},"splitLine"),transposeChars=__name2(({state,dispatch})=>{if(state.readOnly)return!1;let changes=state.changeByRange(range=>{if(!range.empty||range.from==0||range.from==state.doc.length)return{range};let pos=range.from,line=state.doc.lineAt(pos),from=pos==line.from?pos-1:findClusterBreak(line.text,pos-line.from,!1)+line.from,to=pos==line.to?pos+1:findClusterBreak(line.text,pos-line.from,!0)+line.from;return{changes:{from,to,insert:state.doc.slice(pos,to).append(state.doc.slice(from,pos))},range:EditorSelection.cursor(to)}});return changes.changes.empty?!1:(dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"move.character"})),!0)},"transposeChars");function selectedLineBlocks(state){let blocks=[],upto=-1;for(let range of state.selection.ranges){let startLine=state.doc.lineAt(range.from),endLine=state.doc.lineAt(range.to);if(!range.empty&&range.to==endLine.from&&(endLine=state.doc.lineAt(range.to-1)),upto>=startLine.number){let prev=blocks[blocks.length-1];prev.to=endLine.to,prev.ranges.push(range)}else blocks.push({from:startLine.from,to:endLine.to,ranges:[range]});upto=endLine.number+1}return blocks}__name(selectedLineBlocks,"selectedLineBlocks"),__name2(selectedLineBlocks,"selectedLineBlocks");function moveLine(state,dispatch,forward){if(state.readOnly)return!1;let changes=[],ranges=[];for(let block of selectedLineBlocks(state)){if(forward?block.to==state.doc.length:block.from==0)continue;let nextLine=state.doc.lineAt(forward?block.to+1:block.from-1),size=nextLine.length+1;if(forward){changes.push({from:block.to,to:nextLine.to},{from:block.from,insert:nextLine.text+state.lineBreak});for(let r of block.ranges)ranges.push(EditorSelection.range(Math.min(state.doc.length,r.anchor+size),Math.min(state.doc.length,r.head+size)))}else{changes.push({from:nextLine.from,to:block.from},{from:block.to,insert:state.lineBreak+nextLine.text});for(let r of block.ranges)ranges.push(EditorSelection.range(r.anchor-size,r.head-size))}}return changes.length?(dispatch(state.update({changes,scrollIntoView:!0,selection:EditorSelection.create(ranges,state.selection.mainIndex),userEvent:"move.line"})),!0):!1}__name(moveLine,"moveLine"),__name2(moveLine,"moveLine");const moveLineUp=__name2(({state,dispatch})=>moveLine(state,dispatch,!1),"moveLineUp"),moveLineDown=__name2(({state,dispatch})=>moveLine(state,dispatch,!0),"moveLineDown");function copyLine(state,dispatch,forward){if(state.readOnly)return!1;let changes=[];for(let block of selectedLineBlocks(state))forward?changes.push({from:block.from,insert:state.doc.slice(block.from,block.to)+state.lineBreak}):changes.push({from:block.to,insert:state.lineBreak+state.doc.slice(block.from,block.to)});return dispatch(state.update({changes,scrollIntoView:!0,userEvent:"input.copyline"})),!0}__name(copyLine,"copyLine"),__name2(copyLine,"copyLine");const copyLineUp=__name2(({state,dispatch})=>copyLine(state,dispatch,!1),"copyLineUp"),copyLineDown=__name2(({state,dispatch})=>copyLine(state,dispatch,!0),"copyLineDown"),deleteLine=__name2(view=>{if(view.state.readOnly)return!1;let{state}=view,changes=state.changes(selectedLineBlocks(state).map(({from,to})=>(from>0?from--:toview.moveVertically(range,!0)).map(changes);return view.dispatch({changes,selection,scrollIntoView:!0,userEvent:"delete.line"}),!0},"deleteLine");function isBetweenBrackets(state,pos){if(/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos-1,pos+1)))return{from:pos,to:pos};let context=syntaxTree(state).resolveInner(pos),before=context.childBefore(pos),after=context.childAfter(pos),closedBy;return before&&after&&before.to<=pos&&after.from>=pos&&(closedBy=before.type.prop(NodeProp.closedBy))&&closedBy.indexOf(after.name)>-1&&state.doc.lineAt(before.to).from==state.doc.lineAt(after.from).from?{from:before.to,to:after.from}:null}__name(isBetweenBrackets,"isBetweenBrackets"),__name2(isBetweenBrackets,"isBetweenBrackets");const insertNewlineAndIndent=newlineAndIndent(!1),insertBlankLine=newlineAndIndent(!0);function newlineAndIndent(atEof){return({state,dispatch})=>{if(state.readOnly)return!1;let changes=state.changeByRange(range=>{let{from,to}=range,line=state.doc.lineAt(from),explode=!atEof&&from==to&&isBetweenBrackets(state,from);atEof&&(from=to=(to<=line.to?line:state.doc.lineAt(to)).to);let cx=new IndentContext(state,{simulateBreak:from,simulateDoubleBreak:!!explode}),indent=getIndentation(cx,from);for(indent==null&&(indent=/^\s*/.exec(state.doc.lineAt(from).text)[0].length);toline.from&&from{let changes=[];for(let pos=range.from;pos<=range.to;){let line=state.doc.lineAt(pos);line.number>atLine&&(range.empty||range.to>line.from)&&(f(line,changes,range),atLine=line.number),pos=line.to+1}let changeSet=state.changes(changes);return{changes,range:EditorSelection.range(changeSet.mapPos(range.anchor,1),changeSet.mapPos(range.head,1))}})}__name(changeBySelectedLine,"changeBySelectedLine"),__name2(changeBySelectedLine,"changeBySelectedLine");const indentSelection=__name2(({state,dispatch})=>{if(state.readOnly)return!1;let updated=Object.create(null),context=new IndentContext(state,{overrideIndentation:start=>{let found=updated[start];return found??-1}}),changes=changeBySelectedLine(state,(line,changes2,range)=>{let indent=getIndentation(context,line.from);if(indent==null)return;/\S/.test(line.text)||(indent=0);let cur2=/^\s*/.exec(line.text)[0],norm=indentString(state,indent);(cur2!=norm||range.fromstate.readOnly?!1:(dispatch(state.update(changeBySelectedLine(state,(line,changes)=>{changes.push({from:line.from,insert:state.facet(indentUnit)})}),{userEvent:"input.indent"})),!0),"indentMore"),indentLess=__name2(({state,dispatch})=>state.readOnly?!1:(dispatch(state.update(changeBySelectedLine(state,(line,changes)=>{let space=/^\s*/.exec(line.text)[0];if(!space)return;let col=countColumn(space,state.tabSize),keep=0,insert2=indentString(state,Math.max(0,col-getIndentUnit(state)));for(;keep({mac:b.key,run:b.run,shift:b.shift}))),defaultKeymap=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:cursorSyntaxLeft,shift:selectSyntaxLeft},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:cursorSyntaxRight,shift:selectSyntaxRight},{key:"Alt-ArrowUp",run:moveLineUp},{key:"Shift-Alt-ArrowUp",run:copyLineUp},{key:"Alt-ArrowDown",run:moveLineDown},{key:"Shift-Alt-ArrowDown",run:copyLineDown},{key:"Escape",run:simplifySelection},{key:"Mod-Enter",run:insertBlankLine},{key:"Alt-l",mac:"Ctrl-l",run:selectLine},{key:"Mod-i",run:selectParentSyntax,preventDefault:!0},{key:"Mod-[",run:indentLess},{key:"Mod-]",run:indentMore},{key:"Mod-Alt-\\",run:indentSelection},{key:"Shift-Mod-k",run:deleteLine},{key:"Shift-Mod-\\",run:cursorMatchingBracket},{key:"Mod-/",run:toggleComment},{key:"Alt-A",run:toggleBlockComment}].concat(standardKeymap),indentWithTab={key:"Tab",run:indentMore,shift:indentLess},_Stack=class _Stack2{static{__name(this,"_Stack")}constructor(p,stack,state,reducePos,pos,score2,buffer,bufferBase,curContext,lookAhead=0,parent){this.p=p,this.stack=stack,this.state=state,this.reducePos=reducePos,this.pos=pos,this.score=score2,this.buffer=buffer,this.bufferBase=bufferBase,this.curContext=curContext,this.lookAhead=lookAhead,this.parent=parent}toString(){return`[${this.stack.filter((_,i)=>i%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(p,state,pos=0){let cx=p.parser.context;return new _Stack2(p,[],state,pos,pos,0,[],0,cx?new StackContext(cx,cx.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(state,start){this.stack.push(this.state,start,this.bufferBase+this.buffer.length),this.state=state}reduce(action){var _a3;let depth=action>>19,type=action&65535,{parser:parser2}=this.p,dPrec=parser2.dynamicPrecedence(type);if(dPrec&&(this.score+=dPrec),depth==0){this.pushState(parser2.getGoto(this.state,type,!0),this.reducePos),type=2e3&&!(!((_a3=this.p.parser.nodeSet.types[type])===null||_a3===void 0)&&_a3.isAnonymous)&&(start==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=size):this.p.lastBigReductionSizebase2;)this.stack.pop();this.reduceContext(type,start)}storeNode(term,start,end,size=4,isReduce=!1){if(term==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&cur2.buffer[top2-4]==0&&cur2.buffer[top2-1]>-1){if(start==end)return;if(cur2.buffer[top2-2]>=start){cur2.buffer[top2-2]=end;return}}}if(!isReduce||this.pos==end)this.buffer.push(term,start,end,size);else{let index2=this.buffer.length;if(index2>0&&this.buffer[index2-4]!=0)for(;index2>0&&this.buffer[index2-2]>end;)this.buffer[index2]=this.buffer[index2-4],this.buffer[index2+1]=this.buffer[index2-3],this.buffer[index2+2]=this.buffer[index2-2],this.buffer[index2+3]=this.buffer[index2-1],index2-=4,size>4&&(size-=4);this.buffer[index2]=term,this.buffer[index2+1]=start,this.buffer[index2+2]=end,this.buffer[index2+3]=size}}shift(action,next,nextEnd){let start=this.pos;if(action&131072)this.pushState(action&65535,this.pos);else if(action&262144)this.pos=nextEnd,this.shiftContext(next,start),next<=this.p.parser.maxNode&&this.buffer.push(next,start,nextEnd,4);else{let nextState=action,{parser:parser2}=this.p;(nextEnd>this.pos||next<=parser2.maxNode)&&(this.pos=nextEnd,parser2.stateFlag(nextState,1)||(this.reducePos=nextEnd)),this.pushState(nextState,start),this.shiftContext(next,start),next<=parser2.maxNode&&this.buffer.push(next,start,nextEnd,4)}}apply(action,next,nextEnd){action&65536?this.reduce(action):this.shift(action,next,nextEnd)}useNode(value,next){let index2=this.p.reused.length-1;(index2<0||this.p.reused[index2]!=value)&&(this.p.reused.push(value),index2++);let start=this.pos;this.reducePos=this.pos=start+value.length,this.pushState(next,start),this.buffer.push(index2,start,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,value,this,this.p.stream.reset(this.pos-value.length)))}split(){let parent=this,off2=parent.buffer.length;for(;off2>0&&parent.buffer[off2-2]>parent.reducePos;)off2-=4;let buffer=parent.buffer.slice(off2),base2=parent.bufferBase+off2;for(;parent&&base2==parent.bufferBase;)parent=parent.parent;return new _Stack2(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,buffer,base2,this.curContext,this.lookAhead,parent)}recoverByDelete(next,nextEnd){let isNode=next<=this.p.parser.maxNode;isNode&&this.storeNode(next,this.pos,nextEnd,4),this.storeNode(0,this.pos,nextEnd,isNode?8:4),this.pos=this.reducePos=nextEnd,this.score-=190}canShift(term){for(let sim=new SimulatedStack(this);;){let action=this.p.parser.stateSlot(sim.state,4)||this.p.parser.hasAction(sim.state,term);if(action==0)return!1;if(!(action&65536))return!0;sim.reduce(action)}}recoverByInsert(next){if(this.stack.length>=300)return[];let nextStates=this.p.parser.nextStates(this.state);if(nextStates.length>8||this.stack.length>=120){let best=[];for(let i=0,s2;ii2&1&&v==s2)||best.push(nextStates[i],s2)}nextStates=best}let result=[];for(let i=0;i>19,term=reduce&65535,target=this.stack.length-depth*3;if(target<0||parser2.getGoto(this.stack[target],term,!1)<0){let backup=this.findForcedReduction();if(backup==null)return!1;reduce=backup}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(reduce),!0}findForcedReduction(){let{parser:parser2}=this.p,seen=[],explore=__name2((state,depth)=>{if(!seen.includes(state))return seen.push(state),parser2.allActions(state,action=>{if(!(action&393216))if(action&65536){let rDepth=(action>>19)-depth;if(rDepth>1){let term=action&65535,target=this.stack.length-rDepth*3;if(target>=0&&parser2.getGoto(this.stack[target],term,!1)>=0)return rDepth<<19|65536|term}}else{let found=explore(action,depth+1);if(found!=null)return found}})},"explore");return explore(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:parser2}=this.p;return parser2.data[parser2.stateSlot(this.state,1)]==65535&&!parser2.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(other){if(this.state!=other.state||this.stack.length!=other.stack.length)return!1;for(let i=0;ithis.lookAhead&&(this.emitLookAhead(),this.lookAhead=lookAhead)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}};__name2(_Stack,"Stack");let Stack=_Stack;const _StackContext=class{static{__name(this,"_StackContext")}constructor(tracker,context){this.tracker=tracker,this.context=context,this.hash=tracker.strict?tracker.hash(context):0}};__name2(_StackContext,"StackContext");let StackContext=_StackContext;var Recover;(function(Recover2){Recover2[Recover2.Insert=200]="Insert",Recover2[Recover2.Delete=190]="Delete",Recover2[Recover2.Reduce=100]="Reduce",Recover2[Recover2.MaxNext=4]="MaxNext",Recover2[Recover2.MaxInsertStackDepth=300]="MaxInsertStackDepth",Recover2[Recover2.DampenInsertStackDepth=120]="DampenInsertStackDepth",Recover2[Recover2.MinBigReduction=2e3]="MinBigReduction"})(Recover||(Recover={}));const _SimulatedStack=class{static{__name(this,"_SimulatedStack")}constructor(start){this.start=start,this.state=start.state,this.stack=start.stack,this.base=this.stack.length}reduce(action){let term=action&65535,depth=action>>19;depth==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(depth-1)*3;let goto=this.start.p.parser.getGoto(this.stack[this.base-3],term,!0);this.state=goto}};__name2(_SimulatedStack,"SimulatedStack");let SimulatedStack=_SimulatedStack;const _StackBufferCursor=class _StackBufferCursor2{static{__name(this,"_StackBufferCursor")}constructor(stack,pos,index2){this.stack=stack,this.pos=pos,this.index=index2,this.buffer=stack.buffer,this.index==0&&this.maybeNext()}static create(stack,pos=stack.bufferBase+stack.buffer.length){return new _StackBufferCursor2(stack,pos,pos-stack.bufferBase)}maybeNext(){let next=this.stack.parent;next!=null&&(this.index=this.stack.bufferBase-next.bufferBase,this.stack=next,this.buffer=next.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new _StackBufferCursor2(this.stack,this.pos,this.index)}};__name2(_StackBufferCursor,"StackBufferCursor");let StackBufferCursor=_StackBufferCursor;function decodeArray(input,Type=Uint16Array){if(typeof input!="string")return input;let array=null;for(let pos=0,out=0;pos=92&&next--,next>=34&&next--;let digit=next-32;if(digit>=46&&(digit-=46,stop=!0),value+=digit,stop)break;value*=46}array?array[out++]=value:array=new Type(value)}return array}__name(decodeArray,"decodeArray"),__name2(decodeArray,"decodeArray");const _CachedToken=class{static{__name(this,"_CachedToken")}constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}};__name2(_CachedToken,"CachedToken");let CachedToken=_CachedToken;const nullToken=new CachedToken,_InputStream=class{static{__name(this,"_InputStream")}constructor(input,ranges){this.input=input,this.ranges=ranges,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=nullToken,this.rangeIndex=0,this.pos=this.chunkPos=ranges[0].from,this.range=ranges[0],this.end=ranges[ranges.length-1].to,this.readNext()}resolveOffset(offset2,assoc){let range=this.range,index2=this.rangeIndex,pos=this.pos+offset2;for(;posrange.to:pos>=range.to;){if(index2==this.ranges.length-1)return null;let next=this.ranges[++index2];pos+=next.from-range.to,range=next}return pos}clipPos(pos){if(pos>=this.range.from&&pospos)return Math.max(pos,range.from);return this.end}peek(offset2){let idx=this.chunkOff+offset2,pos,result;if(idx>=0&&idx=this.chunk2Pos&&posrange.to&&(this.chunk2=this.chunk2.slice(0,range.to-pos)),result=this.chunk2.charCodeAt(0)}}return pos>=this.token.lookAhead&&(this.token.lookAhead=pos+1),result}acceptToken(token,endOffset=0){let end=endOffset?this.resolveOffset(endOffset,-1):this.pos;if(end==null||end=this.chunk2Pos&&this.posthis.range.to?nextChunk.slice(0,this.range.to-this.pos):nextChunk,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(n2=1){for(this.chunkOff+=n2;this.pos+n2>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();n2-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=n2,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(pos,token){if(token?(this.token=token,token.start=pos,token.lookAhead=pos+1,token.value=token.extended=-1):this.token=nullToken,this.pos!=pos){if(this.pos=pos,pos==this.end)return this.setDone(),this;for(;pos=this.range.to;)this.range=this.ranges[++this.rangeIndex];pos>=this.chunkPos&&pos=this.chunkPos&&to<=this.chunkPos+this.chunk.length)return this.chunk.slice(from-this.chunkPos,to-this.chunkPos);if(from>=this.chunk2Pos&&to<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(from-this.chunk2Pos,to-this.chunk2Pos);if(from>=this.range.from&&to<=this.range.to)return this.input.read(from,to);let result="";for(let r of this.ranges){if(r.from>=to)break;r.to>from&&(result+=this.input.read(Math.max(r.from,from),Math.min(r.to,to)))}return result}};__name2(_InputStream,"InputStream");let InputStream=_InputStream;const _TokenGroup=class{static{__name(this,"_TokenGroup")}constructor(data,id){this.data=data,this.id=id}token(input,stack){let{parser:parser2}=stack.p;readToken(this.data,input,stack,this.id,parser2.data,parser2.tokenPrecTable)}};__name2(_TokenGroup,"TokenGroup");let TokenGroup=_TokenGroup;TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1,TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;function readToken(data,input,stack,group,precTable,precOffset){let state=0,groupMask=1<0){let term=data[i];if(dialect.allows(term)&&(input.token.value==-1||input.token.value==term||overrides(term,input.token.value,precTable,precOffset))){input.acceptToken(term);break}}let next=input.next,low=0,high=data[state+2];if(input.next<0&&high>low&&data[accEnd+high*3-3]==65535&&data[accEnd+high*3-3]==65535){state=data[accEnd+high*3-1];continue scan}for(;low>1,index2=accEnd+mid+(mid<<1),from=data[index2],to=data[index2+1]||65536;if(next=to)low=mid+1;else{state=data[index2+2],input.advance();continue scan}}break}}__name(readToken,"readToken"),__name2(readToken,"readToken");function findOffset(data,start,term){for(let i=start,next;(next=data[i])!=65535;i++)if(next==term)return i-start;return-1}__name(findOffset,"findOffset"),__name2(findOffset,"findOffset");function overrides(token,prev,tableData,tableOffset){let iPrev=findOffset(tableData,tableOffset,prev);return iPrev<0||findOffset(tableData,tableOffset,token)pos)&&!cursor.type.isError)return side<0?Math.max(0,Math.min(cursor.to-1,pos-25)):Math.min(tree.length,Math.max(cursor.from+1,pos+25));if(side<0?cursor.prevSibling():cursor.nextSibling())break;if(!cursor.parent())return side<0?0:tree.length}}__name(cutAt,"cutAt"),__name2(cutAt,"cutAt");const _FragmentCursor=class{static{__name(this,"_FragmentCursor")}constructor(fragments,nodeSet){this.fragments=fragments,this.nodeSet=nodeSet,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let fr=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(fr){for(this.safeFrom=fr.openStart?cutAt(fr.tree,fr.from+fr.offset,1)-fr.offset:fr.from,this.safeTo=fr.openEnd?cutAt(fr.tree,fr.to+fr.offset,-1)-fr.offset:fr.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(fr.tree),this.start.push(-fr.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(pos){if(pospos)return this.nextStart=start,null;if(next instanceof Tree){if(start==pos){if(start=Math.max(this.safeFrom,pos)&&(this.trees.push(next),this.start.push(start),this.index.push(0))}else this.index[last2]++,this.nextStart=start+next.length}}};__name2(_FragmentCursor,"FragmentCursor");let FragmentCursor=_FragmentCursor;const _TokenCache=class{static{__name(this,"_TokenCache")}constructor(parser2,stream){this.stream=stream,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=parser2.tokenizers.map(_=>new CachedToken)}getActions(stack){let actionIndex=0,main=null,{parser:parser2}=stack.p,{tokenizers}=parser2,mask=parser2.stateSlot(stack.state,3),context=stack.curContext?stack.curContext.hash:0,lookAhead=0;for(let i=0;itoken.end+25&&(lookAhead=Math.max(token.lookAhead,lookAhead)),token.value!=0)){let startIndex=actionIndex;if(token.extended>-1&&(actionIndex=this.addActions(stack,token.extended,token.end,actionIndex)),actionIndex=this.addActions(stack,token.value,token.end,actionIndex),!tokenizer.extend&&(main=token,actionIndex>startIndex))break}}for(;this.actions.length>actionIndex;)this.actions.pop();return lookAhead&&stack.setLookAhead(lookAhead),!main&&stack.pos==this.stream.end&&(main=new CachedToken,main.value=stack.p.parser.eofTerm,main.start=main.end=stack.pos,actionIndex=this.addActions(stack,main.value,main.end,actionIndex)),this.mainToken=main,this.actions}getMainToken(stack){if(this.mainToken)return this.mainToken;let main=new CachedToken,{pos,p}=stack;return main.start=pos,main.end=Math.min(pos+1,p.stream.end),main.value=pos==p.stream.end?p.parser.eofTerm:0,main}updateCachedToken(token,tokenizer,stack){let start=this.stream.clipPos(stack.pos);if(tokenizer.token(this.stream.reset(start,token),stack),token.value>-1){let{parser:parser2}=stack.p;for(let i=0;i=0&&stack.p.parser.dialect.allows(result>>1)){result&1?token.extended=result>>1:token.value=result>>1;break}}}else token.value=0,token.end=this.stream.clipPos(start+1)}putAction(action,token,end,index2){for(let i=0;iparser2.bufferLength*4?new FragmentCursor(fragments,parser2.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let stacks=this.stacks,pos=this.minStackPos,newStacks=this.stacks=[],stopped,stoppedTokens;if(this.bigReductionCount>300&&stacks.length==1){let[s2]=stacks;for(;s2.forceReduce()&&s2.stack.length&&s2.stack[s2.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let i=0;ipos)newStacks.push(stack);else{if(this.advanceStack(stack,newStacks,stacks))continue;{stopped||(stopped=[],stoppedTokens=[]),stopped.push(stack);let tok=this.tokens.getMainToken(stack);stoppedTokens.push(tok.value,tok.end)}}break}}if(!newStacks.length){let finished=stopped&&findFinished(stopped);if(finished)return this.stackToTree(finished);if(this.parser.strict)throw verbose&&stopped&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+pos);this.recovering||(this.recovering=5)}if(this.recovering&&stopped){let finished=this.stoppedAt!=null&&stopped[0].pos>this.stoppedAt?stopped[0]:this.runRecovery(stopped,stoppedTokens,newStacks);if(finished)return this.stackToTree(finished.forceAll())}if(this.recovering){let maxRemaining=this.recovering==1?1:this.recovering*3;if(newStacks.length>maxRemaining)for(newStacks.sort((a,b)=>b.score-a.score);newStacks.length>maxRemaining;)newStacks.pop();newStacks.some(s2=>s2.reducePos>pos)&&this.recovering--}else if(newStacks.length>1){outer:for(let i=0;i500&&other.buffer.length>500)if((stack.score-other.score||stack.buffer.length-other.buffer.length)>0)newStacks.splice(j--,1);else{newStacks.splice(i--,1);continue outer}}}newStacks.length>12&&newStacks.splice(12,newStacks.length-12)}this.minStackPos=newStacks[0].pos;for(let i=1;i ":"";if(this.stoppedAt!=null&&start>this.stoppedAt)return stack.forceReduce()?stack:null;if(this.fragments){let strictCx=stack.curContext&&stack.curContext.tracker.strict,cxHash=strictCx?stack.curContext.hash:0;for(let cached=this.fragments.nodeAt(start);cached;){let match2=this.parser.nodeSet.types[cached.type.id]==cached.type?parser2.getGoto(stack.state,cached.type.id):-1;if(match2>-1&&cached.length&&(!strictCx||(cached.prop(NodeProp.contextHash)||0)==cxHash))return stack.useNode(cached,match2),verbose&&console.log(base2+this.stackID(stack)+` (via reuse of ${parser2.getName(cached.type.id)})`),!0;if(!(cached instanceof Tree)||cached.children.length==0||cached.positions[0]>0)break;let inner=cached.children[0];if(inner instanceof Tree&&cached.positions[0]==0)cached=inner;else break}}let defaultReduce=parser2.stateSlot(stack.state,4);if(defaultReduce>0)return stack.reduce(defaultReduce),verbose&&console.log(base2+this.stackID(stack)+` (via always-reduce ${parser2.getName(defaultReduce&65535)})`),!0;if(stack.stack.length>=15e3)for(;stack.stack.length>9e3&&stack.forceReduce(););let actions=this.tokens.getActions(stack);for(let i=0;istart?stacks.push(localStack):split.push(localStack)}return!1}advanceFully(stack,newStacks){let pos=stack.pos;for(;;){if(!this.advanceStack(stack,null,null))return!1;if(stack.pos>pos)return pushStackDedup(stack,newStacks),!0}}runRecovery(stacks,tokens,newStacks){let finished=null,restarted=!1;for(let i=0;i ":"";if(stack.deadEnd&&(restarted||(restarted=!0,stack.restart(),verbose&&console.log(base2+this.stackID(stack)+" (restarted)"),this.advanceFully(stack,newStacks))))continue;let force=stack.split(),forceBase=base2;for(let j=0;force.forceReduce()&&j<10&&(verbose&&console.log(forceBase+this.stackID(force)+" (via force-reduce)"),!this.advanceFully(force,newStacks));j++)verbose&&(forceBase=this.stackID(force)+" -> ");for(let insert2 of stack.recoverByInsert(token))verbose&&console.log(base2+this.stackID(insert2)+" (via recover-insert)"),this.advanceFully(insert2,newStacks);this.stream.end>stack.pos?(tokenEnd==stack.pos&&(tokenEnd++,token=0),stack.recoverByDelete(token,tokenEnd),verbose&&console.log(base2+this.stackID(stack)+` (via recover-delete ${this.parser.getName(token)})`),pushStackDedup(stack,newStacks)):(!finished||finished.scorespec.topRules[r][1]),nodeProps=[];for(let i=0;i=0)setProp(next,prop,propSpec[i++]);else{let value=propSpec[i+-next];for(let j=-next;j>0;j--)setProp(propSpec[i++],prop,value);i++}}}this.nodeSet=new NodeSet(nodeNames.map((name2,i)=>NodeType.define({name:i>=this.minRepeatTerm?void 0:name2,id:i,props:nodeProps[i],top:topTerms.indexOf(i)>-1,error:i==0,skipped:spec.skippedNodes&&spec.skippedNodes.indexOf(i)>-1}))),spec.propSources&&(this.nodeSet=this.nodeSet.extend(...spec.propSources)),this.strict=!1,this.bufferLength=DefaultBufferLength;let tokenArray=decodeArray(spec.tokenData);this.context=spec.context,this.specializerSpecs=spec.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let i=0;itypeof value=="number"?new TokenGroup(tokenArray,value):value),this.topRules=spec.topRules,this.dialects=spec.dialects||{},this.dynamicPrecedences=spec.dynamicPrecedences||null,this.tokenPrecTable=spec.tokenPrec,this.termNames=spec.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(input,fragments,ranges){let parse2=new Parse(this,input,fragments,ranges);for(let w of this.wrappers)parse2=w(parse2,input,fragments,ranges);return parse2}getGoto(state,term,loose=!1){let table=this.goto;if(term>=table[0])return-1;for(let pos=table[term+1];;){let groupTag=table[pos++],last2=groupTag&1,target=table[pos++];if(last2&&loose)return target;for(let end=pos+(groupTag>>1);pos0}validAction(state,action){return!!this.allActions(state,a=>a==action?!0:null)}allActions(state,action){let deflt=this.stateSlot(state,4),result=deflt?action(deflt):void 0;for(let i=this.stateSlot(state,1);result==null;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=pair(this.data,i+2);else break;result=action(pair(this.data,i+1))}return result}nextStates(state){let result=[];for(let i=this.stateSlot(state,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=pair(this.data,i+2);else break;if(!(this.data[i+2]&1)){let value=this.data[i+1];result.some((v,i2)=>i2&1&&v==value)||result.push(this.data[i],value)}}return result}configure(config2){let copy=Object.assign(Object.create(_LRParser2.prototype),this);if(config2.props&&(copy.nodeSet=this.nodeSet.extend(...config2.props)),config2.top){let info=this.topRules[config2.top];if(!info)throw new RangeError(`Invalid top rule name ${config2.top}`);copy.top=info}return config2.tokenizers&&(copy.tokenizers=this.tokenizers.map(t2=>{let found=config2.tokenizers.find(r=>r.from==t2);return found?found.to:t2})),config2.specializers&&(copy.specializers=this.specializers.slice(),copy.specializerSpecs=this.specializerSpecs.map((s2,i)=>{let found=config2.specializers.find(r=>r.from==s2.external);if(!found)return s2;let spec=Object.assign(Object.assign({},s2),{external:found.to});return copy.specializers[i]=getSpecializer(spec),spec})),config2.contextTracker&&(copy.context=config2.contextTracker),config2.dialect&&(copy.dialect=this.parseDialect(config2.dialect)),config2.strict!=null&&(copy.strict=config2.strict),config2.wrap&&(copy.wrappers=copy.wrappers.concat(config2.wrap)),config2.bufferLength!=null&&(copy.bufferLength=config2.bufferLength),copy}hasWrappers(){return this.wrappers.length>0}getName(term){return this.termNames?this.termNames[term]:String(term<=this.maxNode&&this.nodeSet.types[term].name||term)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(term){let prec2=this.dynamicPrecedences;return prec2==null?0:prec2[term]||0}parseDialect(dialect){let values=Object.keys(this.dialects),flags=values.map(()=>!1);if(dialect)for(let part of dialect.split(" ")){let id=values.indexOf(part);id>=0&&(flags[id]=!0)}let disabled=null;for(let i=0;istopped)&&stack.p.parser.stateFlag(stack.state,2)&&(!best||best.scorespec.external(value,stack)<<1|mask}return spec.get}__name(getSpecializer,"getSpecializer"),__name2(getSpecializer,"getSpecializer");const jsonHighlighting=styleTags({String:tags.string,Number:tags.number,"True False":tags.bool,PropertyName:tags.propertyName,Null:tags.null,",":tags.separator,"[ ]":tags.squareBracket,"{ }":tags.brace}),parser=LRParser.deserialize({version:14,states:"$bOVQPOOOOQO'#Cb'#CbOnQPO'#CeOvQPO'#CjOOQO'#Cp'#CpQOQPOOOOQO'#Cg'#CgO}QPO'#CfO!SQPO'#CrOOQO,59P,59PO![QPO,59PO!aQPO'#CuOOQO,59U,59UO!iQPO,59UOVQPO,59QOqQPO'#CkO!nQPO,59^OOQO1G.k1G.kOVQPO'#ClO!vQPO,59aOOQO1G.p1G.pOOQO1G.l1G.lOOQO,59V,59VOOQO-E6i-E6iOOQO,59W,59WOOQO-E6j-E6j",stateData:"#O~OcOS~OQSORSOSSOTSOWQO]ROePO~OVXOeUO~O[[O~PVOg^O~Oh_OVfX~OVaO~OhbO[iX~O[dO~Oh_OVfa~OhbO[ia~O",goto:"!kjPPPPPPkPPkqwPPk{!RPPP!XP!ePP!hXSOR^bQWQRf_TVQ_Q`WRg`QcZRicQTOQZRQe^RhbRYQR]R",nodeNames:"\u26A0 JsonText True False Null Number String } { Object Property PropertyName ] [ Array",maxTerm:25,nodeProps:[["openedBy",7,"{",12,"["],["closedBy",8,"}",13,"]"]],propSources:[jsonHighlighting],skippedNodes:[0],repeatNodeCount:2,tokenData:"(|~RaXY!WYZ!W]^!Wpq!Wrs!]|}$u}!O$z!Q!R%T!R![&c![!]&t!}#O&y#P#Q'O#Y#Z'T#b#c'r#h#i(Z#o#p(r#q#r(w~!]Oc~~!`Wpq!]qr!]rs!xs#O!]#O#P!}#P;'S!];'S;=`$o<%lO!]~!}Oe~~#QXrs!]!P!Q!]#O#P!]#U#V!]#Y#Z!]#b#c!]#f#g!]#h#i!]#i#j#m~#pR!Q![#y!c!i#y#T#Z#y~#|R!Q![$V!c!i$V#T#Z$V~$YR!Q![$c!c!i$c#T#Z$c~$fR!Q![!]!c!i!]#T#Z!]~$rP;=`<%l!]~$zOh~~$}Q!Q!R%T!R![&c~%YRT~!O!P%c!g!h%w#X#Y%w~%fP!Q![%i~%nRT~!Q![%i!g!h%w#X#Y%w~%zR{|&T}!O&T!Q![&Z~&WP!Q![&Z~&`PT~!Q![&Z~&hST~!O!P%c!Q![&c!g!h%w#X#Y%w~&yOg~~'OO]~~'TO[~~'WP#T#U'Z~'^P#`#a'a~'dP#g#h'g~'jP#X#Y'm~'rOR~~'uP#i#j'x~'{P#`#a(O~(RP#`#a(U~(ZOS~~(^P#f#g(a~(dP#i#j(g~(jP#X#Y(m~(rOQ~~(wOW~~(|OV~",tokenizers:[0],topRules:{JsonText:[0,1]},tokenPrec:0}),jsonParseLinter=__name2(()=>view=>{try{JSON.parse(view.state.doc.toString())}catch(e){if(!(e instanceof SyntaxError))throw e;const pos=getErrorPosition(e,view.state.doc);return[{from:pos,message:e.message,severity:"error",to:pos}]}return[]},"jsonParseLinter");function getErrorPosition(error,doc2){let m;return(m=error.message.match(/at position (\d+)/))?Math.min(+m[1],doc2.length):(m=error.message.match(/at line (\d+) column (\d+)/))?Math.min(doc2.line(+m[1]).from+ +m[2]-1,doc2.length):0}__name(getErrorPosition,"getErrorPosition"),__name2(getErrorPosition,"getErrorPosition");const jsonLanguage=LRLanguage.define({name:"json",parser:parser.configure({props:[indentNodeProp.add({Object:continuedIndent({except:/^\s*\}/}),Array:continuedIndent({except:/^\s*\]/})}),foldNodeProp.add({"Object Array":foldInside})]}),languageData:{closeBrackets:{brackets:["[","{",'"']},indentOnInput:/^\s*[\}\]]$/}});function json(){return new LanguageSupport(jsonLanguage)}__name(json,"json"),__name2(json,"json");function crelt(){var elt=arguments[0];typeof elt=="string"&&(elt=document.createElement(elt));var i=1,next=arguments[1];if(next&&typeof next=="object"&&next.nodeType==null&&!Array.isArray(next)){for(var name2 in next)if(Object.prototype.hasOwnProperty.call(next,name2)){var value=next[name2];typeof value=="string"?elt.setAttribute(name2,value):value!=null&&(elt[name2]=value)}i++}for(;id.from==d.to||d.from==d.to-1&&state.doc.lineAt(d.from).to==d.from?Decoration.widget({widget:new DiagnosticWidget(d),diagnostic:d}).range(d.from):Decoration.mark({attributes:{class:"cm-lintRange cm-lintRange-"+d.severity+(d.markClass?" "+d.markClass:"")},diagnostic:d}).range(d.from,d.to)),!0);return new _LintState2(ranges,panel,findDiagnostic(ranges))}};__name2(_LintState,"LintState");let LintState=_LintState;function findDiagnostic(diagnostics,diagnostic=null,after=0){let found=null;return diagnostics.between(after,1e9,(from,to,{spec})=>{if(!(diagnostic&&spec.diagnostic!=diagnostic))return found=new SelectedDiagnostic(from,to,spec.diagnostic),!1}),found}__name(findDiagnostic,"findDiagnostic"),__name2(findDiagnostic,"findDiagnostic");function hideTooltip(tr,tooltip){let line=tr.startState.doc.lineAt(tooltip.pos);return!!(tr.effects.some(e=>e.is(setDiagnosticsEffect))||tr.changes.touchesRange(line.from,line.to))}__name(hideTooltip,"hideTooltip"),__name2(hideTooltip,"hideTooltip");function maybeEnableLint(state,effects){return state.field(lintState,!1)?effects:effects.concat(StateEffect.appendConfig.of(lintExtensions))}__name(maybeEnableLint,"maybeEnableLint"),__name2(maybeEnableLint,"maybeEnableLint");function setDiagnostics(state,diagnostics){return{effects:maybeEnableLint(state,[setDiagnosticsEffect.of(diagnostics)])}}__name(setDiagnostics,"setDiagnostics"),__name2(setDiagnostics,"setDiagnostics");const setDiagnosticsEffect=StateEffect.define(),togglePanel$1=StateEffect.define(),movePanelSelection=StateEffect.define(),lintState=StateField.define({create(){return new LintState(Decoration.none,null,null)},update(value,tr){if(tr.docChanged){let mapped=value.diagnostics.map(tr.changes),selected=null;if(value.selected){let selPos=tr.changes.mapPos(value.selected.from,1);selected=findDiagnostic(mapped,value.selected.diagnostic,selPos)||findDiagnostic(mapped,null,selPos)}value=new LintState(mapped,value.panel,selected)}for(let effect of tr.effects)effect.is(setDiagnosticsEffect)?value=LintState.init(effect.value,value.panel,tr.state):effect.is(togglePanel$1)?value=new LintState(value.diagnostics,effect.value?LintPanel.open:null,value.selected):effect.is(movePanelSelection)&&(value=new LintState(value.diagnostics,value.panel,effect.value));return value},provide:f=>[showPanel.from(f,val=>val.panel),EditorView.decorations.from(f,s2=>s2.diagnostics)]}),activeMark=Decoration.mark({class:"cm-lintRange cm-lintRange-active"});function lintTooltip(view,pos,side){let{diagnostics}=view.state.field(lintState),found=[],stackStart=2e8,stackEnd=0;diagnostics.between(pos-(side<0?1:0),pos+(side>0?1:0),(from,to,{spec})=>{pos>=from&&pos<=to&&(from==to||(pos>from||side>0)&&(posrenderDiagnostic(view,d,!1)))}__name(diagnosticsTooltip,"diagnosticsTooltip"),__name2(diagnosticsTooltip,"diagnosticsTooltip");const openLintPanel=__name2(view=>{let field=view.state.field(lintState,!1);(!field||!field.panel)&&view.dispatch({effects:maybeEnableLint(view.state,[togglePanel$1.of(!0)])});let panel=getPanel(view,LintPanel.open);return panel&&panel.dom.querySelector(".cm-panel-lint ul").focus(),!0},"openLintPanel"),closeLintPanel=__name2(view=>{let field=view.state.field(lintState,!1);return!field||!field.panel?!1:(view.dispatch({effects:togglePanel$1.of(!1)}),!0)},"closeLintPanel"),nextDiagnostic=__name2(view=>{let field=view.state.field(lintState,!1);if(!field)return!1;let sel=view.state.selection.main,next=field.diagnostics.iter(sel.to+1);return!next.value&&(next=field.diagnostics.iter(0),!next.value||next.from==sel.from&&next.to==sel.to)?!1:(view.dispatch({selection:{anchor:next.from,head:next.to},scrollIntoView:!0}),!0)},"nextDiagnostic"),lintKeymap=[{key:"Mod-Shift-m",run:openLintPanel,preventDefault:!0},{key:"F8",run:nextDiagnostic}],lintPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.timeout=-1,this.set=!0;let{delay}=view.state.facet(lintConfig);this.lintTime=Date.now()+delay,this.run=this.run.bind(this),this.timeout=setTimeout(this.run,delay)}run(){let now2=Date.now();if(now2Promise.resolve(source(this.view)))).then(annotations=>{let all=annotations.reduce((a,b)=>a.concat(b));this.view.state.doc==state.doc&&this.view.dispatch(setDiagnostics(this.view.state,all))},error=>{logException(this.view.state,error)})}}update(update){let config2=update.state.facet(lintConfig);(update.docChanged||config2!=update.startState.facet(lintConfig)||config2.needsRefresh&&config2.needsRefresh(update))&&(this.lintTime=Date.now()+config2.delay,this.set||(this.set=!0,this.timeout=setTimeout(this.run,config2.delay)))}force(){this.set&&(this.lintTime=Date.now(),this.run())}destroy(){clearTimeout(this.timeout)}}),lintConfig=Facet.define({combine(input){return Object.assign({sources:input.map(i=>i.source)},combineConfig(input.map(i=>i.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null},{needsRefresh:(a,b)=>a?b?u=>a(u)||b(u):a:b}))}});function linter(source,config2={}){return[lintConfig.of({source,config:config2}),lintPlugin,lintExtensions]}__name(linter,"linter"),__name2(linter,"linter");function assignKeys(actions){let assigned=[];if(actions)actions:for(let{name:name2}of actions){for(let i=0;ic.toLowerCase()==ch.toLowerCase())){assigned.push(ch);continue actions}}assigned.push("")}return assigned}__name(assignKeys,"assignKeys"),__name2(assignKeys,"assignKeys");function renderDiagnostic(view,diagnostic,inPanel){var _a3;let keys2=inPanel?assignKeys(diagnostic.actions):[];return crelt("li",{class:"cm-diagnostic cm-diagnostic-"+diagnostic.severity},crelt("span",{class:"cm-diagnosticText"},diagnostic.renderMessage?diagnostic.renderMessage():diagnostic.message),(_a3=diagnostic.actions)===null||_a3===void 0?void 0:_a3.map((action,i)=>{let fired=!1,click=__name2(e=>{if(e.preventDefault(),fired)return;fired=!0;let found=findDiagnostic(view.state.field(lintState).diagnostics,diagnostic);found&&action.apply(view,found.from,found.to)},"click"),{name:name2}=action,keyIndex=keys2[i]?name2.indexOf(keys2[i]):-1,nameElt=keyIndex<0?name2:[name2.slice(0,keyIndex),crelt("u",name2.slice(keyIndex,keyIndex+1)),name2.slice(keyIndex+1)];return crelt("button",{type:"button",class:"cm-diagnosticAction",onclick:click,onmousedown:click,"aria-label":` Action: ${name2}${keyIndex<0?"":` (access key "${keys2[i]})"`}.`},nameElt)}),diagnostic.source&&crelt("div",{class:"cm-diagnosticSource"},diagnostic.source))}__name(renderDiagnostic,"renderDiagnostic"),__name2(renderDiagnostic,"renderDiagnostic");const _DiagnosticWidget=class extends WidgetType{static{__name(this,"_DiagnosticWidget")}constructor(diagnostic){super(),this.diagnostic=diagnostic}eq(other){return other.diagnostic==this.diagnostic}toDOM(){return crelt("span",{class:"cm-lintPoint cm-lintPoint-"+this.diagnostic.severity})}};__name2(_DiagnosticWidget,"DiagnosticWidget");let DiagnosticWidget=_DiagnosticWidget;const _PanelItem=class{static{__name(this,"_PanelItem")}constructor(view,diagnostic){this.diagnostic=diagnostic,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=renderDiagnostic(view,diagnostic,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}};__name2(_PanelItem,"PanelItem");let PanelItem=_PanelItem;const _LintPanel=class _LintPanel2{static{__name(this,"_LintPanel")}constructor(view){this.view=view,this.items=[];let onkeydown=__name2(event=>{if(event.keyCode==27)closeLintPanel(this.view),this.view.focus();else if(event.keyCode==38||event.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(event.keyCode==40||event.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(event.keyCode==36)this.moveSelection(0);else if(event.keyCode==35)this.moveSelection(this.items.length-1);else if(event.keyCode==13)this.view.focus();else if(event.keyCode>=65&&event.keyCode<=90&&this.selectedIndex>=0){let{diagnostic}=this.items[this.selectedIndex],keys2=assignKeys(diagnostic.actions);for(let i=0;i{for(let i=0;icloseLintPanel(this.view)},"\xD7")),this.update()}get selectedIndex(){let selected=this.view.state.field(lintState).selected;if(!selected)return-1;for(let i=0;i{let found=-1,item;for(let j=i;ji&&(this.items.splice(i,found-i),needsSync=!0)),selected&&item.diagnostic==selected.diagnostic?item.dom.hasAttribute("aria-selected")||(item.dom.setAttribute("aria-selected","true"),newSelectedItem=item):item.dom.hasAttribute("aria-selected")&&item.dom.removeAttribute("aria-selected"),i++});i({sel:newSelectedItem.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel,panel})=>{sel.toppanel.bottom&&(this.list.scrollTop+=sel.bottom-panel.bottom)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),needsSync&&this.sync()}sync(){let domPos=this.list.firstChild;function rm2(){let prev=domPos;domPos=prev.nextSibling,prev.remove()}__name(rm2,"rm2"),__name2(rm2,"rm");for(let item of this.items)if(item.dom.parentNode==this.list){for(;domPos!=item.dom;)rm2();domPos=item.dom.nextSibling}else this.list.insertBefore(item.dom,domPos);for(;domPos;)rm2()}moveSelection(selectedIndex){if(this.selectedIndex<0)return;let field=this.view.state.field(lintState),selection=findDiagnostic(field.diagnostics,this.items[selectedIndex].diagnostic);selection&&this.view.dispatch({selection:{anchor:selection.from,head:selection.to},scrollIntoView:!0,effects:movePanelSelection.of(selection)})}static open(view){return new _LintPanel2(view)}};__name2(_LintPanel,"LintPanel");let LintPanel=_LintPanel;function svg(content2,attrs='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,${encodeURIComponent(content2)}')`}__name(svg,"svg"),__name2(svg,"svg");function underline(color){return svg(``,'width="6" height="3"')}__name(underline,"underline"),__name2(underline,"underline");const baseTheme$2=EditorView.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:underline("#d11")},".cm-lintRange-warning":{backgroundImage:underline("orange")},".cm-lintRange-info":{backgroundImage:underline("#999")},".cm-lintRange-hint":{backgroundImage:underline("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}}),lintExtensions=[lintState,EditorView.decorations.compute([lintState],state=>{let{selected,panel}=state.field(lintState);return!selected||!panel||selected.from==selected.to?Decoration.none:Decoration.set([activeMark.range(selected.from,selected.to)])}),hoverTooltip(lintTooltip,{hideOn:hideTooltip}),baseTheme$2],basicNormalize=typeof String.prototype.normalize=="function"?x=>x.normalize("NFKD"):x=>x,_SearchCursor=class{static{__name(this,"_SearchCursor")}constructor(text,query,from=0,to=text.length,normalize,test){this.test=test,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=text.iterRange(from,to),this.bufferStart=from,this.normalize=normalize?x=>normalize(basicNormalize(x)):basicNormalize,this.query=this.normalize(query)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return codePointAt(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let next=this.peek();if(next<0)return this.done=!0,this;let str=fromCodePoint(next),start=this.bufferStart+this.bufferPos;this.bufferPos+=codePointSize(next);let norm=this.normalize(str);for(let i=0,pos=start;;i++){let code=norm.charCodeAt(i),match2=this.match(code,pos);if(i==norm.length-1){if(match2)return this.value=match2,this;break}pos==start&&ithis.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let off2=this.matchPos-this.curLineStart;;){this.re.lastIndex=off2;let match2=this.matchPos<=this.to&&this.re.exec(this.curLine);if(match2){let from=this.curLineStart+match2.index,to=from+match2[0].length;if(this.matchPos=toCharEnd(this.text,to+(from==to?1:0)),from==this.curLineStart+this.curLine.length&&this.nextLine(),(fromthis.value.to)&&(!this.test||this.test(from,to,match2)))return this.value={from,to,match:match2},this;off2=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=to||cached.to<=from){let flat=new _FlattenedDoc2(from,doc2.sliceString(from,to));return flattened.set(doc2,flat),flat}if(cached.from==from&&cached.to==to)return cached;let{text,from:cachedFrom}=cached;return cachedFrom>from&&(text=doc2.sliceString(from,cachedFrom)+text,cachedFrom=from),cached.to=this.to?this.to:this.text.lineAt(pos).to}next(){for(;;){let off2=this.re.lastIndex=this.matchPos-this.flat.from,match2=this.re.exec(this.flat.text);if(match2&&!match2[0]&&match2.index==off2&&(this.re.lastIndex=off2+1,match2=this.re.exec(this.flat.text)),match2){let from=this.flat.from+match2.index,to=from+match2[0].length;if((this.flat.to>=this.to||match2.index+match2[0].length<=this.flat.text.length-10)&&(!this.test||this.test(from,to,match2)))return this.value={from,to,match:match2},this.matchPos=toCharEnd(this.text,to+(from==to?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=FlattenedDoc.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}};__name2(_MultilineRegExpCursor,"MultilineRegExpCursor");let MultilineRegExpCursor=_MultilineRegExpCursor;typeof Symbol<"u"&&(RegExpCursor.prototype[Symbol.iterator]=MultilineRegExpCursor.prototype[Symbol.iterator]=function(){return this});function validRegExp(source){try{return new RegExp(source,baseFlags),!0}catch{return!1}}__name(validRegExp,"validRegExp"),__name2(validRegExp,"validRegExp");function toCharEnd(text,pos){if(pos>=text.length)return pos;let line=text.lineAt(pos),next;for(;pos=56320&&next<57344;)pos++;return pos}__name(toCharEnd,"toCharEnd"),__name2(toCharEnd,"toCharEnd");function createLineDialog(view){let input=crelt("input",{class:"cm-textfield",name:"line"}),dom=crelt("form",{class:"cm-gotoLine",onkeydown:event=>{event.keyCode==27?(event.preventDefault(),view.dispatch({effects:dialogEffect.of(!1)}),view.focus()):event.keyCode==13&&(event.preventDefault(),go())},onsubmit:event=>{event.preventDefault(),go()}},crelt("label",view.state.phrase("Go to line"),": ",input)," ",crelt("button",{class:"cm-button",type:"submit"},view.state.phrase("go")));function go(){let match2=/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);if(!match2)return;let{state}=view,startLine=state.doc.lineAt(state.selection.main.head),[,sign,ln,cl,percent]=match2,col=cl?+cl.slice(1):0,line=ln?+ln:startLine.number;if(ln&&percent){let pc=line/100;sign&&(pc=pc*(sign=="-"?-1:1)+startLine.number/state.doc.lines),line=Math.round(state.doc.lines*pc)}else ln&&sign&&(line=line*(sign=="-"?-1:1)+startLine.number);let docLine=state.doc.line(Math.max(1,Math.min(state.doc.lines,line))),selection=EditorSelection.cursor(docLine.from+Math.max(0,Math.min(col,docLine.length)));view.dispatch({effects:[dialogEffect.of(!1),EditorView.scrollIntoView(selection.from,{y:"center"})],selection}),view.focus()}return __name(go,"go"),__name2(go,"go"),{dom}}__name(createLineDialog,"createLineDialog"),__name2(createLineDialog,"createLineDialog");const dialogEffect=StateEffect.define(),dialogField=StateField.define({create(){return!0},update(value,tr){for(let e of tr.effects)e.is(dialogEffect)&&(value=e.value);return value},provide:f=>showPanel.from(f,val=>val?createLineDialog:null)}),gotoLine=__name2(view=>{let panel=getPanel(view,createLineDialog);if(!panel){let effects=[dialogEffect.of(!0)];view.state.field(dialogField,!1)==null&&effects.push(StateEffect.appendConfig.of([dialogField,baseTheme$1])),view.dispatch({effects}),panel=getPanel(view,createLineDialog)}return panel&&panel.dom.querySelector("input").focus(),!0},"gotoLine"),baseTheme$1=EditorView.baseTheme({".cm-panel.cm-gotoLine":{padding:"2px 6px 4px","& label":{fontSize:"80%"}}}),defaultHighlightOptions={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},highlightConfig=Facet.define({combine(options){return combineConfig(options,defaultHighlightOptions,{highlightWordAroundCursor:(a,b)=>a||b,minSelectionLength:Math.min,maxMatches:Math.min})}});function highlightSelectionMatches(options){let ext=[defaultTheme,matchHighlighter];return options&&ext.push(highlightConfig.of(options)),ext}__name(highlightSelectionMatches,"highlightSelectionMatches"),__name2(highlightSelectionMatches,"highlightSelectionMatches");const matchDeco=Decoration.mark({class:"cm-selectionMatch"}),mainMatchDeco=Decoration.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function insideWordBoundaries(check,state,from,to){return(from==0||check(state.sliceDoc(from-1,from))!=CharCategory.Word)&&(to==state.doc.length||check(state.sliceDoc(to,to+1))!=CharCategory.Word)}__name(insideWordBoundaries,"insideWordBoundaries"),__name2(insideWordBoundaries,"insideWordBoundaries");function insideWord(check,state,from,to){return check(state.sliceDoc(from,from+1))==CharCategory.Word&&check(state.sliceDoc(to-1,to))==CharCategory.Word}__name(insideWord,"insideWord"),__name2(insideWord,"insideWord");const matchHighlighter=ViewPlugin.fromClass(class{constructor(view){this.decorations=this.getDeco(view)}update(update){(update.selectionSet||update.docChanged||update.viewportChanged)&&(this.decorations=this.getDeco(update.view))}getDeco(view){let conf=view.state.facet(highlightConfig),{state}=view,sel=state.selection;if(sel.ranges.length>1)return Decoration.none;let range=sel.main,query,check=null;if(range.empty){if(!conf.highlightWordAroundCursor)return Decoration.none;let word=state.wordAt(range.head);if(!word)return Decoration.none;check=state.charCategorizer(range.head),query=state.sliceDoc(word.from,word.to)}else{let len=range.to-range.from;if(len200)return Decoration.none;if(conf.wholeWords){if(query=state.sliceDoc(range.from,range.to),check=state.charCategorizer(range.head),!(insideWordBoundaries(check,state,range.from,range.to)&&insideWord(check,state,range.from,range.to)))return Decoration.none}else if(query=state.sliceDoc(range.from,range.to).trim(),!query)return Decoration.none}let deco=[];for(let part of view.visibleRanges){let cursor=new SearchCursor(state.doc,query,part.from,part.to);for(;!cursor.next().done;){let{from,to}=cursor.value;if((!check||insideWordBoundaries(check,state,from,to))&&(range.empty&&from<=range.from&&to>=range.to?deco.push(mainMatchDeco.range(from,to)):(from>=range.to||to<=range.from)&&deco.push(matchDeco.range(from,to)),deco.length>conf.maxMatches))return Decoration.none}}return Decoration.set(deco)}},{decorations:v=>v.decorations}),defaultTheme=EditorView.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),selectWord=__name2(({state,dispatch})=>{let{selection}=state,newSel=EditorSelection.create(selection.ranges.map(range=>state.wordAt(range.head)||EditorSelection.cursor(range.head)),selection.mainIndex);return newSel.eq(selection)?!1:(dispatch(state.update({selection:newSel})),!0)},"selectWord");function findNextOccurrence(state,query){let{main,ranges}=state.selection,word=state.wordAt(main.head),fullWord=word&&word.from==main.from&&word.to==main.to;for(let cycled=!1,cursor=new SearchCursor(state.doc,query,ranges[ranges.length-1].to);;)if(cursor.next(),cursor.done){if(cycled)return null;cursor=new SearchCursor(state.doc,query,0,Math.max(0,ranges[ranges.length-1].from-1)),cycled=!0}else{if(cycled&&ranges.some(r=>r.from==cursor.value.from))continue;if(fullWord){let word2=state.wordAt(cursor.value.from);if(!word2||word2.from!=cursor.value.from||word2.to!=cursor.value.to)continue}return cursor.value}}__name(findNextOccurrence,"findNextOccurrence"),__name2(findNextOccurrence,"findNextOccurrence");const selectNextOccurrence=__name2(({state,dispatch})=>{let{ranges}=state.selection;if(ranges.some(sel=>sel.from===sel.to))return selectWord({state,dispatch});let searchedText=state.sliceDoc(ranges[0].from,ranges[0].to);if(state.selection.ranges.some(r=>state.sliceDoc(r.from,r.to)!=searchedText))return!1;let range=findNextOccurrence(state,searchedText);return range?(dispatch(state.update({selection:state.selection.addRange(EditorSelection.range(range.from,range.to),!1),effects:EditorView.scrollIntoView(range.to)})),!0):!1},"selectNextOccurrence"),searchConfigFacet=Facet.define({combine(configs){return combineConfig(configs,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:view=>new SearchPanel(view),scrollToMatch:range=>EditorView.scrollIntoView(range)})}}),_SearchQuery=class{static{__name(this,"_SearchQuery")}constructor(config2){this.search=config2.search,this.caseSensitive=!!config2.caseSensitive,this.literal=!!config2.literal,this.regexp=!!config2.regexp,this.replace=config2.replace||"",this.valid=!!this.search&&(!this.regexp||validRegExp(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!config2.wholeWord}unquote(text){return this.literal?text:text.replace(/\\([nrt\\])/g,(_,ch)=>ch=="n"?` +`:ch=="r"?"\r":ch=="t"?" ":"\\")}eq(other){return this.search==other.search&&this.replace==other.replace&&this.caseSensitive==other.caseSensitive&&this.regexp==other.regexp&&this.wholeWord==other.wholeWord}create(){return this.regexp?new RegExpQuery(this):new StringQuery(this)}getCursor(state,from=0,to){let st=state.doc?state:EditorState.create({doc:state});return to==null&&(to=st.doc.length),this.regexp?regexpCursor(this,st,from,to):stringCursor(this,st,from,to)}};__name2(_SearchQuery,"SearchQuery");let SearchQuery=_SearchQuery;const _QueryType=class{static{__name(this,"_QueryType")}constructor(spec){this.spec=spec}};__name2(_QueryType,"QueryType");let QueryType=_QueryType;function stringCursor(spec,state,from,to){return new SearchCursor(state.doc,spec.unquoted,from,to,spec.caseSensitive?void 0:x=>x.toLowerCase(),spec.wholeWord?stringWordTest(state.doc,state.charCategorizer(state.selection.main.head)):void 0)}__name(stringCursor,"stringCursor"),__name2(stringCursor,"stringCursor");function stringWordTest(doc2,categorizer){return(from,to,buf,bufPos)=>((bufPos>from||bufPos+buf.length=limit2)return null;ranges.push(cursor.value)}return ranges}highlight(state,from,to,add2){let cursor=stringCursor(this.spec,state,Math.max(0,from-this.spec.unquoted.length),Math.min(to+this.spec.unquoted.length,state.doc.length));for(;!cursor.next().done;)add2(cursor.value.from,cursor.value.to)}};__name2(_StringQuery,"StringQuery");let StringQuery=_StringQuery;function regexpCursor(spec,state,from,to){return new RegExpCursor(state.doc,spec.search,{ignoreCase:!spec.caseSensitive,test:spec.wholeWord?regexpWordTest(state.charCategorizer(state.selection.main.head)):void 0},from,to)}__name(regexpCursor,"regexpCursor"),__name2(regexpCursor,"regexpCursor");function charBefore(str,index2){return str.slice(findClusterBreak(str,index2,!1),index2)}__name(charBefore,"charBefore"),__name2(charBefore,"charBefore");function charAfter(str,index2){return str.slice(index2,findClusterBreak(str,index2))}__name(charAfter,"charAfter"),__name2(charAfter,"charAfter");function regexpWordTest(categorizer){return(_from,_to,match2)=>!match2[0].length||(categorizer(charBefore(match2.input,match2.index))!=CharCategory.Word||categorizer(charAfter(match2.input,match2.index))!=CharCategory.Word)&&(categorizer(charAfter(match2.input,match2.index+match2[0].length))!=CharCategory.Word||categorizer(charBefore(match2.input,match2.index+match2[0].length))!=CharCategory.Word)}__name(regexpWordTest,"regexpWordTest"),__name2(regexpWordTest,"regexpWordTest");const _RegExpQuery=class extends QueryType{static{__name(this,"_RegExpQuery")}nextMatch(state,curFrom,curTo){let cursor=regexpCursor(this.spec,state,curTo,state.doc.length).next();return cursor.done&&(cursor=regexpCursor(this.spec,state,0,curFrom).next()),cursor.done?null:cursor.value}prevMatchInRange(state,from,to){for(let size=1;;size++){let start=Math.max(from,to-size*1e4),cursor=regexpCursor(this.spec,state,start,to),range=null;for(;!cursor.next().done;)range=cursor.value;if(range&&(start==from||range.from>start+10))return range;if(start==from)return null}}prevMatch(state,curFrom,curTo){return this.prevMatchInRange(state,0,curFrom)||this.prevMatchInRange(state,curTo,state.doc.length)}getReplacement(result){return this.spec.unquote(this.spec.replace.replace(/\$([$&\d+])/g,(m,i)=>i=="$"?"$":i=="&"?result.match[0]:i!="0"&&+i=limit2)return null;ranges.push(cursor.value)}return ranges}highlight(state,from,to,add2){let cursor=regexpCursor(this.spec,state,Math.max(0,from-250),Math.min(to+250,state.doc.length));for(;!cursor.next().done;)add2(cursor.value.from,cursor.value.to)}};__name2(_RegExpQuery,"RegExpQuery");let RegExpQuery=_RegExpQuery;const setSearchQuery=StateEffect.define(),togglePanel=StateEffect.define(),searchState=StateField.define({create(state){return new SearchState(defaultQuery(state).create(),null)},update(value,tr){for(let effect of tr.effects)effect.is(setSearchQuery)?value=new SearchState(effect.value.create(),value.panel):effect.is(togglePanel)&&(value=new SearchState(value.query,effect.value?createSearchPanel:null));return value},provide:f=>showPanel.from(f,val=>val.panel)}),_SearchState=class{static{__name(this,"_SearchState")}constructor(query,panel){this.query=query,this.panel=panel}};__name2(_SearchState,"SearchState");let SearchState=_SearchState;const matchMark=Decoration.mark({class:"cm-searchMatch"}),selectedMatchMark=Decoration.mark({class:"cm-searchMatch cm-searchMatch-selected"}),searchHighlighter=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.decorations=this.highlight(view.state.field(searchState))}update(update){let state=update.state.field(searchState);(state!=update.startState.field(searchState)||update.docChanged||update.selectionSet||update.viewportChanged)&&(this.decorations=this.highlight(state))}highlight({query,panel}){if(!panel||!query.spec.valid)return Decoration.none;let{view}=this,builder=new RangeSetBuilder;for(let i=0,ranges=view.visibleRanges,l2=ranges.length;iranges[i+1].from-2*250;)to=ranges[++i].to;query.highlight(view.state,from,to,(from2,to2)=>{let selected=view.state.selection.ranges.some(r=>r.from==from2&&r.to==to2);builder.add(from2,to2,selected?selectedMatchMark:matchMark)})}return builder.finish()}},{decorations:v=>v.decorations});function searchCommand(f){return view=>{let state=view.state.field(searchState,!1);return state&&state.query.spec.valid?f(view,state):openSearchPanel(view)}}__name(searchCommand,"searchCommand"),__name2(searchCommand,"searchCommand");const findNext=searchCommand((view,{query})=>{let{to}=view.state.selection.main,next=query.nextMatch(view.state,to,to);if(!next)return!1;let selection=EditorSelection.single(next.from,next.to),config2=view.state.facet(searchConfigFacet);return view.dispatch({selection,effects:[announceMatch(view,next),config2.scrollToMatch(selection.main,view)],userEvent:"select.search"}),selectSearchInput(view),!0}),findPrevious=searchCommand((view,{query})=>{let{state}=view,{from}=state.selection.main,prev=query.prevMatch(state,from,from);if(!prev)return!1;let selection=EditorSelection.single(prev.from,prev.to),config2=view.state.facet(searchConfigFacet);return view.dispatch({selection,effects:[announceMatch(view,prev),config2.scrollToMatch(selection.main,view)],userEvent:"select.search"}),selectSearchInput(view),!0}),selectMatches=searchCommand((view,{query})=>{let ranges=query.matchAll(view.state,1e3);return!ranges||!ranges.length?!1:(view.dispatch({selection:EditorSelection.create(ranges.map(r=>EditorSelection.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),selectSelectionMatches=__name2(({state,dispatch})=>{let sel=state.selection;if(sel.ranges.length>1||sel.main.empty)return!1;let{from,to}=sel.main,ranges=[],main=0;for(let cur2=new SearchCursor(state.doc,state.sliceDoc(from,to));!cur2.next().done;){if(ranges.length>1e3)return!1;cur2.value.from==from&&(main=ranges.length),ranges.push(EditorSelection.range(cur2.value.from,cur2.value.to))}return dispatch(state.update({selection:EditorSelection.create(ranges,main),userEvent:"select.search.matches"})),!0},"selectSelectionMatches"),replaceNext=searchCommand((view,{query})=>{let{state}=view,{from,to}=state.selection.main;if(state.readOnly)return!1;let next=query.nextMatch(state,from,from);if(!next)return!1;let changes=[],selection,replacement,effects=[];if(next.from==from&&next.to==to&&(replacement=state.toText(query.getReplacement(next)),changes.push({from:next.from,to:next.to,insert:replacement}),next=query.nextMatch(state,next.from,next.to),effects.push(EditorView.announce.of(state.phrase("replaced match on line $",state.doc.lineAt(from).number)+"."))),next){let off2=changes.length==0||changes[0].from>=next.to?0:next.to-next.from-replacement.length;selection=EditorSelection.single(next.from-off2,next.to-off2),effects.push(announceMatch(view,next)),effects.push(state.facet(searchConfigFacet).scrollToMatch(selection.main,view))}return view.dispatch({changes,selection,effects,userEvent:"input.replace"}),!0}),replaceAll=searchCommand((view,{query})=>{if(view.state.readOnly)return!1;let changes=query.matchAll(view.state,1e9).map(match2=>{let{from,to}=match2;return{from,to,insert:query.getReplacement(match2)}});if(!changes.length)return!1;let announceText=view.state.phrase("replaced $ matches",changes.length)+".";return view.dispatch({changes,effects:EditorView.announce.of(announceText),userEvent:"input.replace.all"}),!0});function createSearchPanel(view){return view.state.facet(searchConfigFacet).createPanel(view)}__name(createSearchPanel,"createSearchPanel"),__name2(createSearchPanel,"createSearchPanel");function defaultQuery(state,fallback){var _a3,_b2,_c2,_d,_e;let sel=state.selection.main,selText=sel.empty||sel.to>sel.from+100?"":state.sliceDoc(sel.from,sel.to);if(fallback&&!selText)return fallback;let config2=state.facet(searchConfigFacet);return new SearchQuery({search:((_a3=fallback?.literal)!==null&&_a3!==void 0?_a3:config2.literal)?selText:selText.replace(/\n/g,"\\n"),caseSensitive:(_b2=fallback?.caseSensitive)!==null&&_b2!==void 0?_b2:config2.caseSensitive,literal:(_c2=fallback?.literal)!==null&&_c2!==void 0?_c2:config2.literal,regexp:(_d=fallback?.regexp)!==null&&_d!==void 0?_d:config2.regexp,wholeWord:(_e=fallback?.wholeWord)!==null&&_e!==void 0?_e:config2.wholeWord})}__name(defaultQuery,"defaultQuery"),__name2(defaultQuery,"defaultQuery");function getSearchInput(view){let panel=getPanel(view,createSearchPanel);return panel&&panel.dom.querySelector("[main-field]")}__name(getSearchInput,"getSearchInput"),__name2(getSearchInput,"getSearchInput");function selectSearchInput(view){let input=getSearchInput(view);input&&input==view.root.activeElement&&input.select()}__name(selectSearchInput,"selectSearchInput"),__name2(selectSearchInput,"selectSearchInput");const openSearchPanel=__name2(view=>{let state=view.state.field(searchState,!1);if(state&&state.panel){let searchInput=getSearchInput(view);if(searchInput&&searchInput!=view.root.activeElement){let query=defaultQuery(view.state,state.query.spec);query.valid&&view.dispatch({effects:setSearchQuery.of(query)}),searchInput.focus(),searchInput.select()}}else view.dispatch({effects:[togglePanel.of(!0),state?setSearchQuery.of(defaultQuery(view.state,state.query.spec)):StateEffect.appendConfig.of(searchExtensions)]});return!0},"openSearchPanel"),closeSearchPanel=__name2(view=>{let state=view.state.field(searchState,!1);if(!state||!state.panel)return!1;let panel=getPanel(view,createSearchPanel);return panel&&panel.dom.contains(view.root.activeElement)&&view.focus(),view.dispatch({effects:togglePanel.of(!1)}),!0},"closeSearchPanel"),searchKeymap=[{key:"Mod-f",run:openSearchPanel,scope:"editor search-panel"},{key:"F3",run:findNext,shift:findPrevious,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:findNext,shift:findPrevious,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:closeSearchPanel,scope:"editor search-panel"},{key:"Mod-Shift-l",run:selectSelectionMatches},{key:"Alt-g",run:gotoLine},{key:"Mod-d",run:selectNextOccurrence,preventDefault:!0}],_SearchPanel=class{static{__name(this,"_SearchPanel")}constructor(view){this.view=view;let query=this.query=view.state.field(searchState).query.spec;this.commit=this.commit.bind(this),this.searchField=crelt("input",{value:query.search,placeholder:phrase(view,"Find"),"aria-label":phrase(view,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=crelt("input",{value:query.replace,placeholder:phrase(view,"Replace"),"aria-label":phrase(view,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=crelt("input",{type:"checkbox",name:"case",form:"",checked:query.caseSensitive,onchange:this.commit}),this.reField=crelt("input",{type:"checkbox",name:"re",form:"",checked:query.regexp,onchange:this.commit}),this.wordField=crelt("input",{type:"checkbox",name:"word",form:"",checked:query.wholeWord,onchange:this.commit});function button(name2,onclick,content2){return crelt("button",{class:"cm-button",name:name2,onclick,type:"button"},content2)}__name(button,"button"),__name2(button,"button"),this.dom=crelt("div",{onkeydown:e=>this.keydown(e),class:"cm-search"},[this.searchField,button("next",()=>findNext(view),[phrase(view,"next")]),button("prev",()=>findPrevious(view),[phrase(view,"previous")]),button("select",()=>selectMatches(view),[phrase(view,"all")]),crelt("label",null,[this.caseField,phrase(view,"match case")]),crelt("label",null,[this.reField,phrase(view,"regexp")]),crelt("label",null,[this.wordField,phrase(view,"by word")]),...view.state.readOnly?[]:[crelt("br"),this.replaceField,button("replace",()=>replaceNext(view),[phrase(view,"replace")]),button("replaceAll",()=>replaceAll(view),[phrase(view,"replace all")])],crelt("button",{name:"close",onclick:()=>closeSearchPanel(view),"aria-label":phrase(view,"close"),type:"button"},["\xD7"])])}commit(){let query=new SearchQuery({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});query.eq(this.query)||(this.query=query,this.view.dispatch({effects:setSearchQuery.of(query)}))}keydown(e){runScopeHandlers(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?findPrevious:findNext)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),replaceNext(this.view))}update(update){for(let tr of update.transactions)for(let effect of tr.effects)effect.is(setSearchQuery)&&!effect.value.eq(this.query)&&this.setQuery(effect.value)}setQuery(query){this.query=query,this.searchField.value=query.search,this.replaceField.value=query.replace,this.caseField.checked=query.caseSensitive,this.reField.checked=query.regexp,this.wordField.checked=query.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(searchConfigFacet).top}};__name2(_SearchPanel,"SearchPanel");let SearchPanel=_SearchPanel;function phrase(view,phrase2){return view.state.phrase(phrase2)}__name(phrase,"phrase"),__name2(phrase,"phrase");const AnnounceMargin=30,Break=/[\s\.,:;?!]/;function announceMatch(view,{from,to}){let line=view.state.doc.lineAt(from),lineEnd=view.state.doc.lineAt(to).to,start=Math.max(line.from,from-AnnounceMargin),end=Math.min(lineEnd,to+AnnounceMargin),text=view.state.sliceDoc(start,end);if(start!=line.from){for(let i=0;itext.length-AnnounceMargin;i--)if(!Break.test(text[i-1])&&Break.test(text[i])){text=text.slice(0,i);break}}return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${line.number}.`)}__name(announceMatch,"announceMatch"),__name2(announceMatch,"announceMatch");const baseTheme=EditorView.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),searchExtensions=[searchState,Prec.lowest(searchHighlighter),baseTheme],basicSetup=(()=>[lineNumbers(),highlightActiveLineGutter(),highlightSpecialChars(),history(),foldGutter(),drawSelection(),dropCursor(),EditorState.allowMultipleSelections.of(!0),indentOnInput(),syntaxHighlighting(defaultHighlightStyle,{fallback:!0}),bracketMatching(),closeBrackets(),autocompletion(),rectangularSelection(),crosshairCursor(),highlightActiveLine(),highlightSelectionMatches(),keymap.of([...closeBracketsKeymap,...defaultKeymap,...searchKeymap,...historyKeymap,...foldKeymap,...completionKeymap,...lintKeymap])])();var PipsMode;(function(PipsMode2){PipsMode2.Range="range",PipsMode2.Steps="steps",PipsMode2.Positions="positions",PipsMode2.Count="count",PipsMode2.Values="values"})(PipsMode||(PipsMode={}));var PipsType;(function(PipsType2){PipsType2[PipsType2.None=-1]="None",PipsType2[PipsType2.NoValue=0]="NoValue",PipsType2[PipsType2.LargeValue=1]="LargeValue",PipsType2[PipsType2.SmallValue=2]="SmallValue"})(PipsType||(PipsType={}));function isValidFormatter(entry){return isValidPartialFormatter(entry)&&typeof entry.from=="function"}__name(isValidFormatter,"isValidFormatter"),__name2(isValidFormatter,"isValidFormatter");function isValidPartialFormatter(entry){return typeof entry=="object"&&typeof entry.to=="function"}__name(isValidPartialFormatter,"isValidPartialFormatter"),__name2(isValidPartialFormatter,"isValidPartialFormatter");function removeElement(el){el.parentElement.removeChild(el)}__name(removeElement,"removeElement"),__name2(removeElement,"removeElement");function isSet(value){return value!=null}__name(isSet,"isSet"),__name2(isSet,"isSet");function preventDefault(e){e.preventDefault()}__name(preventDefault,"preventDefault"),__name2(preventDefault,"preventDefault");function unique(array){return array.filter(function(a){return this[a]?!1:this[a]=!0},{})}__name(unique,"unique"),__name2(unique,"unique");function closest(value,to){return Math.round(value/to)*to}__name(closest,"closest"),__name2(closest,"closest");function offset(elem,orientation){var rect=elem.getBoundingClientRect(),doc2=elem.ownerDocument,docElem=doc2.documentElement,pageOffset=getPageOffset(doc2);return/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)&&(pageOffset.x=0),orientation?rect.top+pageOffset.y-docElem.clientTop:rect.left+pageOffset.x-docElem.clientLeft}__name(offset,"offset"),__name2(offset,"offset");function isNumeric(a){return typeof a=="number"&&!isNaN(a)&&isFinite(a)}__name(isNumeric,"isNumeric"),__name2(isNumeric,"isNumeric");function addClassFor(element,className,duration){duration>0&&(addClass(element,className),setTimeout(function(){removeClass(element,className)},duration))}__name(addClassFor,"addClassFor"),__name2(addClassFor,"addClassFor");function limit(a){return Math.max(Math.min(a,100),0)}__name(limit,"limit"),__name2(limit,"limit");function asArray(a){return Array.isArray(a)?a:[a]}__name(asArray,"asArray"),__name2(asArray,"asArray");function countDecimals(numStr){numStr=String(numStr);var pieces=numStr.split(".");return pieces.length>1?pieces[1].length:0}__name(countDecimals,"countDecimals"),__name2(countDecimals,"countDecimals");function addClass(el,className){el.classList&&!/\s/.test(className)?el.classList.add(className):el.className+=" "+className}__name(addClass,"addClass"),__name2(addClass,"addClass");function removeClass(el,className){el.classList&&!/\s/.test(className)?el.classList.remove(className):el.className=el.className.replace(new RegExp("(^|\\b)"+className.split(" ").join("|")+"(\\b|$)","gi")," ")}__name(removeClass,"removeClass"),__name2(removeClass,"removeClass");function hasClass(el,className){return el.classList?el.classList.contains(className):new RegExp("\\b"+className+"\\b").test(el.className)}__name(hasClass,"hasClass"),__name2(hasClass,"hasClass");function getPageOffset(doc2){var supportPageOffset=window.pageXOffset!==void 0,isCSS1Compat=(doc2.compatMode||"")==="CSS1Compat",x=supportPageOffset?window.pageXOffset:isCSS1Compat?doc2.documentElement.scrollLeft:doc2.body.scrollLeft,y=supportPageOffset?window.pageYOffset:isCSS1Compat?doc2.documentElement.scrollTop:doc2.body.scrollTop;return{x,y}}__name(getPageOffset,"getPageOffset"),__name2(getPageOffset,"getPageOffset");function getActions(){return window.navigator.pointerEnabled?{start:"pointerdown",move:"pointermove",end:"pointerup"}:window.navigator.msPointerEnabled?{start:"MSPointerDown",move:"MSPointerMove",end:"MSPointerUp"}:{start:"mousedown touchstart",move:"mousemove touchmove",end:"mouseup touchend"}}__name(getActions,"getActions"),__name2(getActions,"getActions");function getSupportsPassive(){var supportsPassive=!1;try{var opts=Object.defineProperty({},"passive",{get:function(){supportsPassive=!0}});window.addEventListener("test",null,opts)}catch{}return supportsPassive}__name(getSupportsPassive,"getSupportsPassive"),__name2(getSupportsPassive,"getSupportsPassive");function getSupportsTouchActionNone(){return window.CSS&&CSS.supports&&CSS.supports("touch-action","none")}__name(getSupportsTouchActionNone,"getSupportsTouchActionNone"),__name2(getSupportsTouchActionNone,"getSupportsTouchActionNone");function subRangeRatio(pa,pb){return 100/(pb-pa)}__name(subRangeRatio,"subRangeRatio"),__name2(subRangeRatio,"subRangeRatio");function fromPercentage(range,value,startRange){return value*100/(range[startRange+1]-range[startRange])}__name(fromPercentage,"fromPercentage"),__name2(fromPercentage,"fromPercentage");function toPercentage(range,value){return fromPercentage(range,range[0]<0?value+Math.abs(range[0]):value-range[0],0)}__name(toPercentage,"toPercentage"),__name2(toPercentage,"toPercentage");function isPercentage(range,value){return value*(range[1]-range[0])/100+range[0]}__name(isPercentage,"isPercentage"),__name2(isPercentage,"isPercentage");function getJ(value,arr){for(var j=1;value>=arr[j];)j+=1;return j}__name(getJ,"getJ"),__name2(getJ,"getJ");function toStepping(xVal,xPct,value){if(value>=xVal.slice(-1)[0])return 100;var j=getJ(value,xVal),va=xVal[j-1],vb=xVal[j],pa=xPct[j-1],pb=xPct[j];return pa+toPercentage([va,vb],value)/subRangeRatio(pa,pb)}__name(toStepping,"toStepping"),__name2(toStepping,"toStepping");function fromStepping(xVal,xPct,value){if(value>=100)return xVal.slice(-1)[0];var j=getJ(value,xPct),va=xVal[j-1],vb=xVal[j],pa=xPct[j-1],pb=xPct[j];return isPercentage([va,vb],(value-pa)*subRangeRatio(pa,pb))}__name(fromStepping,"fromStepping"),__name2(fromStepping,"fromStepping");function getStep(xPct,xSteps,snap,value){if(value===100)return value;var j=getJ(value,xPct),a=xPct[j-1],b=xPct[j];return snap?value-a>(b-a)/2?b:a:xSteps[j-1]?xPct[j-1]+closest(value-xPct[j-1],xSteps[j-1]):value}__name(getStep,"getStep"),__name2(getStep,"getStep");var Spectrum=function(){function Spectrum2(entry,snap,singleStep){this.xPct=[],this.xVal=[],this.xSteps=[],this.xNumSteps=[],this.xHighestCompleteStep=[],this.xSteps=[singleStep||!1],this.xNumSteps=[!1],this.snap=snap;var index2,ordered=[];for(Object.keys(entry).forEach(function(index3){ordered.push([asArray(entry[index3]),index3])}),ordered.sort(function(a,b){return a[0][0]-b[0][0]}),index2=0;index2this.xPct[xPct_index+1];)xPct_index++;else value===this.xPct[this.xPct.length-1]&&(xPct_index=this.xPct.length-2);!direction&&value===this.xPct[xPct_index+1]&&xPct_index++,distances===null&&(distances=[]);var start_factor,rest_factor=1,rest_rel_distance=distances[xPct_index],range_pct=0,rel_range_distance=0,abs_distance_counter=0,range_counter=0;for(direction?start_factor=(value-this.xPct[xPct_index])/(this.xPct[xPct_index+1]-this.xPct[xPct_index]):start_factor=(this.xPct[xPct_index+1]-value)/(this.xPct[xPct_index+1]-this.xPct[xPct_index]);rest_rel_distance>0;)range_pct=this.xPct[xPct_index+1+range_counter]-this.xPct[xPct_index+range_counter],distances[xPct_index+range_counter]*rest_factor+100-start_factor*100>100?(rel_range_distance=range_pct*start_factor,rest_factor=(rest_rel_distance-100*start_factor)/distances[xPct_index+range_counter],start_factor=1):(rel_range_distance=distances[xPct_index+range_counter]*range_pct/100*rest_factor,rest_factor=0),direction?(abs_distance_counter=abs_distance_counter-rel_range_distance,this.xPct.length+range_counter>=1&&range_counter--):(abs_distance_counter=abs_distance_counter+rel_range_distance,this.xPct.length-range_counter>=1&&range_counter++),rest_rel_distance=distances[xPct_index+range_counter]*rest_factor;return value+abs_distance_counter},Spectrum2.prototype.toStepping=function(value){return value=toStepping(this.xVal,this.xPct,value),value},Spectrum2.prototype.fromStepping=function(value){return fromStepping(this.xVal,this.xPct,value)},Spectrum2.prototype.getStep=function(value){return value=getStep(this.xPct,this.xSteps,this.snap,value),value},Spectrum2.prototype.getDefaultStep=function(value,isDown,size){var j=getJ(value,this.xPct);return(value===100||isDown&&value===this.xPct[j-1])&&(j=Math.max(j-1,1)),(this.xVal[j]-this.xVal[j-1])/size},Spectrum2.prototype.getNearbySteps=function(value){var j=getJ(value,this.xPct);return{stepBefore:{startValue:this.xVal[j-2],step:this.xNumSteps[j-2],highestStep:this.xHighestCompleteStep[j-2]},thisStep:{startValue:this.xVal[j-1],step:this.xNumSteps[j-1],highestStep:this.xHighestCompleteStep[j-1]},stepAfter:{startValue:this.xVal[j],step:this.xNumSteps[j],highestStep:this.xHighestCompleteStep[j]}}},Spectrum2.prototype.countStepDecimals=function(){var stepDecimals=this.xNumSteps.map(countDecimals);return Math.max.apply(null,stepDecimals)},Spectrum2.prototype.hasNoSize=function(){return this.xVal[0]===this.xVal[this.xVal.length-1]},Spectrum2.prototype.convert=function(value){return this.getStep(this.toStepping(value))},Spectrum2.prototype.handleEntryPoint=function(index2,value){var percentage;if(index2==="min"?percentage=0:index2==="max"?percentage=100:percentage=parseFloat(index2),!isNumeric(percentage)||!isNumeric(value[0]))throw new Error("noUiSlider: 'range' value isn't numeric.");this.xPct.push(percentage),this.xVal.push(value[0]);var value1=Number(value[1]);percentage?this.xSteps.push(isNaN(value1)?!1:value1):isNaN(value1)||(this.xSteps[0]=value1),this.xHighestCompleteStep.push(0)},Spectrum2.prototype.handleStepPoint=function(i,n2){if(n2){if(this.xVal[i]===this.xVal[i+1]){this.xSteps[i]=this.xHighestCompleteStep[i]=this.xVal[i];return}this.xSteps[i]=fromPercentage([this.xVal[i],this.xVal[i+1]],n2,0)/subRangeRatio(this.xPct[i],this.xPct[i+1]);var totalSteps=(this.xVal[i+1]-this.xVal[i])/this.xNumSteps[i],highestStep=Math.ceil(Number(totalSteps.toFixed(3))-1),step=this.xVal[i]+this.xNumSteps[i]*highestStep;this.xHighestCompleteStep[i]=step}},Spectrum2}(),defaultFormatter={to:function(value){return value===void 0?"":value.toFixed(2)},from:Number},cssClasses={target:"target",base:"base",origin:"origin",handle:"handle",handleLower:"handle-lower",handleUpper:"handle-upper",touchArea:"touch-area",horizontal:"horizontal",vertical:"vertical",background:"background",connect:"connect",connects:"connects",ltr:"ltr",rtl:"rtl",textDirectionLtr:"txt-dir-ltr",textDirectionRtl:"txt-dir-rtl",draggable:"draggable",drag:"state-drag",tap:"state-tap",active:"active",tooltip:"tooltip",pips:"pips",pipsHorizontal:"pips-horizontal",pipsVertical:"pips-vertical",marker:"marker",markerHorizontal:"marker-horizontal",markerVertical:"marker-vertical",markerNormal:"marker-normal",markerLarge:"marker-large",markerSub:"marker-sub",value:"value",valueHorizontal:"value-horizontal",valueVertical:"value-vertical",valueNormal:"value-normal",valueLarge:"value-large",valueSub:"value-sub"},INTERNAL_EVENT_NS={tooltips:".__tooltips",aria:".__aria"};function testStep(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'step' is not numeric.");parsed.singleStep=entry}__name(testStep,"testStep"),__name2(testStep,"testStep");function testKeyboardPageMultiplier(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'keyboardPageMultiplier' is not numeric.");parsed.keyboardPageMultiplier=entry}__name(testKeyboardPageMultiplier,"testKeyboardPageMultiplier"),__name2(testKeyboardPageMultiplier,"testKeyboardPageMultiplier");function testKeyboardMultiplier(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'keyboardMultiplier' is not numeric.");parsed.keyboardMultiplier=entry}__name(testKeyboardMultiplier,"testKeyboardMultiplier"),__name2(testKeyboardMultiplier,"testKeyboardMultiplier");function testKeyboardDefaultStep(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'keyboardDefaultStep' is not numeric.");parsed.keyboardDefaultStep=entry}__name(testKeyboardDefaultStep,"testKeyboardDefaultStep"),__name2(testKeyboardDefaultStep,"testKeyboardDefaultStep");function testRange(parsed,entry){if(typeof entry!="object"||Array.isArray(entry))throw new Error("noUiSlider: 'range' is not an object.");if(entry.min===void 0||entry.max===void 0)throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");parsed.spectrum=new Spectrum(entry,parsed.snap||!1,parsed.singleStep)}__name(testRange,"testRange"),__name2(testRange,"testRange");function testStart(parsed,entry){if(entry=asArray(entry),!Array.isArray(entry)||!entry.length)throw new Error("noUiSlider: 'start' option is incorrect.");parsed.handles=entry.length,parsed.start=entry}__name(testStart,"testStart"),__name2(testStart,"testStart");function testSnap(parsed,entry){if(typeof entry!="boolean")throw new Error("noUiSlider: 'snap' option must be a boolean.");parsed.snap=entry}__name(testSnap,"testSnap"),__name2(testSnap,"testSnap");function testAnimate(parsed,entry){if(typeof entry!="boolean")throw new Error("noUiSlider: 'animate' option must be a boolean.");parsed.animate=entry}__name(testAnimate,"testAnimate"),__name2(testAnimate,"testAnimate");function testAnimationDuration(parsed,entry){if(typeof entry!="number")throw new Error("noUiSlider: 'animationDuration' option must be a number.");parsed.animationDuration=entry}__name(testAnimationDuration,"testAnimationDuration"),__name2(testAnimationDuration,"testAnimationDuration");function testConnect(parsed,entry){var connect=[!1],i;if(entry==="lower"?entry=[!0,!1]:entry==="upper"&&(entry=[!1,!0]),entry===!0||entry===!1){for(i=1;i1)throw new Error("noUiSlider: 'padding' option must not exceed 100% of the range.")}}__name(testPadding,"testPadding"),__name2(testPadding,"testPadding");function testDirection(parsed,entry){switch(entry){case"ltr":parsed.dir=0;break;case"rtl":parsed.dir=1;break;default:throw new Error("noUiSlider: 'direction' option was not recognized.")}}__name(testDirection,"testDirection"),__name2(testDirection,"testDirection");function testBehaviour(parsed,entry){if(typeof entry!="string")throw new Error("noUiSlider: 'behaviour' must be a string containing options.");var tap=entry.indexOf("tap")>=0,drag=entry.indexOf("drag")>=0,fixed=entry.indexOf("fixed")>=0,snap=entry.indexOf("snap")>=0,hover=entry.indexOf("hover")>=0,unconstrained=entry.indexOf("unconstrained")>=0,dragAll=entry.indexOf("drag-all")>=0,smoothSteps=entry.indexOf("smooth-steps")>=0;if(fixed){if(parsed.handles!==2)throw new Error("noUiSlider: 'fixed' behaviour must be used with 2 handles");testMargin(parsed,parsed.start[1]-parsed.start[0])}if(unconstrained&&(parsed.margin||parsed.limit))throw new Error("noUiSlider: 'unconstrained' behaviour cannot be used with margin or limit");parsed.events={tap:tap||snap,drag,dragAll,smoothSteps,fixed,snap,hover,unconstrained}}__name(testBehaviour,"testBehaviour"),__name2(testBehaviour,"testBehaviour");function testTooltips(parsed,entry){if(entry!==!1)if(entry===!0||isValidPartialFormatter(entry)){parsed.tooltips=[];for(var i=0;i= 2) required for mode 'count'.");for(var interval=pips2.values-1,spread=100/interval,values=[];interval--;)values[interval]=interval*spread;return values.push(100),mapToRange(values,pips2.stepped)}return pips2.mode===PipsMode.Positions?mapToRange(pips2.values,pips2.stepped):pips2.mode===PipsMode.Values?pips2.stepped?pips2.values.map(function(value){return scope_Spectrum.fromStepping(scope_Spectrum.getStep(scope_Spectrum.toStepping(value)))}):pips2.values:[]}__name(getGroup,"getGroup"),__name2(getGroup,"getGroup");function mapToRange(values,stepped){return values.map(function(value){return scope_Spectrum.fromStepping(stepped?scope_Spectrum.getStep(value):value)})}__name(mapToRange,"mapToRange"),__name2(mapToRange,"mapToRange");function generateSpread(pips2){function safeIncrement(value,increment){return Number((value+increment).toFixed(7))}__name(safeIncrement,"safeIncrement"),__name2(safeIncrement,"safeIncrement");var group=getGroup(pips2),indexes={},firstInRange=scope_Spectrum.xVal[0],lastInRange=scope_Spectrum.xVal[scope_Spectrum.xVal.length-1],ignoreFirst=!1,ignoreLast=!1,prevPct=0;return group=unique(group.slice().sort(function(a,b){return a-b})),group[0]!==firstInRange&&(group.unshift(firstInRange),ignoreFirst=!0),group[group.length-1]!==lastInRange&&(group.push(lastInRange),ignoreLast=!0),group.forEach(function(current,index2){var step,i,q,low=current,high=group[index2+1],newPct,pctDifference,pctPos,type,steps,realSteps,stepSize,isSteps=pips2.mode===PipsMode.Steps;for(isSteps&&(step=scope_Spectrum.xNumSteps[index2]),step||(step=high-low),high===void 0&&(high=low),step=Math.max(step,1e-7),i=low;i<=high;i=safeIncrement(i,step)){for(newPct=scope_Spectrum.toStepping(i),pctDifference=newPct-prevPct,steps=pctDifference/(pips2.density||1),realSteps=Math.round(steps),stepSize=pctDifference/realSteps,q=1;q<=realSteps;q+=1)pctPos=prevPct+q*stepSize,indexes[pctPos.toFixed(5)]=[scope_Spectrum.fromStepping(pctPos),0];type=group.indexOf(i)>-1?PipsType.LargeValue:isSteps?PipsType.SmallValue:PipsType.NoValue,!index2&&ignoreFirst&&i!==high&&(type=0),i===high&&ignoreLast||(indexes[newPct.toFixed(5)]=[i,type]),prevPct=newPct}}),indexes}__name(generateSpread,"generateSpread"),__name2(generateSpread,"generateSpread");function addMarking(spread,filterFunc,formatter){var _a3,_b2,element=scope_Document.createElement("div"),valueSizeClasses=(_a3={},_a3[PipsType.None]="",_a3[PipsType.NoValue]=options.cssClasses.valueNormal,_a3[PipsType.LargeValue]=options.cssClasses.valueLarge,_a3[PipsType.SmallValue]=options.cssClasses.valueSub,_a3),markerSizeClasses=(_b2={},_b2[PipsType.None]="",_b2[PipsType.NoValue]=options.cssClasses.markerNormal,_b2[PipsType.LargeValue]=options.cssClasses.markerLarge,_b2[PipsType.SmallValue]=options.cssClasses.markerSub,_b2),valueOrientationClasses=[options.cssClasses.valueHorizontal,options.cssClasses.valueVertical],markerOrientationClasses=[options.cssClasses.markerHorizontal,options.cssClasses.markerVertical];addClass(element,options.cssClasses.pips),addClass(element,options.ort===0?options.cssClasses.pipsHorizontal:options.cssClasses.pipsVertical);function getClasses(type,source){var a=source===options.cssClasses.value,orientationClasses=a?valueOrientationClasses:markerOrientationClasses,sizeClasses=a?valueSizeClasses:markerSizeClasses;return source+" "+orientationClasses[options.ort]+" "+sizeClasses[type]}__name(getClasses,"getClasses"),__name2(getClasses,"getClasses");function addSpread(offset2,value,type){if(type=filterFunc?filterFunc(value,type):type,type!==PipsType.None){var node=addNodeTo(element,!1);node.className=getClasses(type,options.cssClasses.marker),node.style[options.style]=offset2+"%",type>PipsType.NoValue&&(node=addNodeTo(element,!1),node.className=getClasses(type,options.cssClasses.value),node.setAttribute("data-value",String(value)),node.style[options.style]=offset2+"%",node.innerHTML=String(formatter.to(value)))}}return __name(addSpread,"addSpread"),__name2(addSpread,"addSpread"),Object.keys(spread).forEach(function(offset2){addSpread(offset2,spread[offset2][0],spread[offset2][1])}),element}__name(addMarking,"addMarking"),__name2(addMarking,"addMarking");function removePips(){scope_Pips&&(removeElement(scope_Pips),scope_Pips=null)}__name(removePips,"removePips"),__name2(removePips,"removePips");function pips(pips2){removePips();var spread=generateSpread(pips2),filter2=pips2.filter,format=pips2.format||{to:function(value){return String(Math.round(value))}};return scope_Pips=scope_Target.appendChild(addMarking(spread,filter2,format)),scope_Pips}__name(pips,"pips"),__name2(pips,"pips");function baseSize(){var rect=scope_Base.getBoundingClientRect(),alt="offset"+["Width","Height"][options.ort];return options.ort===0?rect.width||scope_Base[alt]:rect.height||scope_Base[alt]}__name(baseSize,"baseSize"),__name2(baseSize,"baseSize");function attachEvent(events,element,callback,data){var method=__name2(function(event){var e=fixEvent(event,data.pageOffset,data.target||element);if(!e||isSliderDisabled()&&!data.doNotReject||hasClass(scope_Target,options.cssClasses.tap)&&!data.doNotReject||events===actions.start&&e.buttons!==void 0&&e.buttons>1||data.hover&&e.buttons)return!1;supportsPassive||e.preventDefault(),e.calcPoint=e.points[options.ort],callback(e,data)},"method"),methods=[];return events.split(" ").forEach(function(eventName){element.addEventListener(eventName,method,supportsPassive?{passive:!0}:!1),methods.push([eventName,method])}),methods}__name(attachEvent,"attachEvent"),__name2(attachEvent,"attachEvent");function fixEvent(e,pageOffset,eventTarget){var touch=e.type.indexOf("touch")===0,mouse=e.type.indexOf("mouse")===0,pointer=e.type.indexOf("pointer")===0,x=0,y=0;if(e.type.indexOf("MSPointer")===0&&(pointer=!0),e.type==="mousedown"&&!e.buttons&&!e.touches)return!1;if(touch){var isTouchOnTarget=__name2(function(checkTouch){var target2=checkTouch.target;return target2===eventTarget||eventTarget.contains(target2)||e.composed&&e.composedPath().shift()===eventTarget},"isTouchOnTarget");if(e.type==="touchstart"){var targetTouches=Array.prototype.filter.call(e.touches,isTouchOnTarget);if(targetTouches.length>1)return!1;x=targetTouches[0].pageX,y=targetTouches[0].pageY}else{var targetTouch=Array.prototype.find.call(e.changedTouches,isTouchOnTarget);if(!targetTouch)return!1;x=targetTouch.pageX,y=targetTouch.pageY}}return pageOffset=pageOffset||getPageOffset(scope_Document),(mouse||pointer)&&(x=e.clientX+pageOffset.x,y=e.clientY+pageOffset.y),e.pageOffset=pageOffset,e.points=[x,y],e.cursor=mouse||pointer,e}__name(fixEvent,"fixEvent"),__name2(fixEvent,"fixEvent");function calcPointToPercentage(calcPoint){var location=calcPoint-offset(scope_Base,options.ort),proposal=location*100/baseSize();return proposal=limit(proposal),options.dir?100-proposal:proposal}__name(calcPointToPercentage,"calcPointToPercentage"),__name2(calcPointToPercentage,"calcPointToPercentage");function getClosestHandle(clickedPosition){var smallestDifference=100,handleNumber=!1;return scope_Handles.forEach(function(handle,index2){if(!isHandleDisabled(index2)){var handlePosition=scope_Locations[index2],differenceWithThisHandle=Math.abs(handlePosition-clickedPosition),clickAtEdge=differenceWithThisHandle===100&&smallestDifference===100,isCloser=differenceWithThisHandlehandlePosition;(isCloser||isCloserAfter||clickAtEdge)&&(handleNumber=index2,smallestDifference=differenceWithThisHandle)}}),handleNumber}__name(getClosestHandle,"getClosestHandle"),__name2(getClosestHandle,"getClosestHandle");function documentLeave(event,data){event.type==="mouseout"&&event.target.nodeName==="HTML"&&event.relatedTarget===null&&eventEnd(event,data)}__name(documentLeave,"documentLeave"),__name2(documentLeave,"documentLeave");function eventMove(event,data){if(navigator.appVersion.indexOf("MSIE 9")===-1&&event.buttons===0&&data.buttonsProperty!==0)return eventEnd(event,data);var movement=(options.dir?-1:1)*(event.calcPoint-data.startCalcPoint),proposal=movement*100/data.baseSize;moveHandles(movement>0,proposal,data.locations,data.handleNumbers,data.connect)}__name(eventMove,"eventMove"),__name2(eventMove,"eventMove");function eventEnd(event,data){data.handle&&(removeClass(data.handle,options.cssClasses.active),scope_ActiveHandlesCount-=1),data.listeners.forEach(function(c){scope_DocumentElement.removeEventListener(c[0],c[1])}),scope_ActiveHandlesCount===0&&(removeClass(scope_Target,options.cssClasses.drag),setZindex(),event.cursor&&(scope_Body.style.cursor="",scope_Body.removeEventListener("selectstart",preventDefault))),options.events.smoothSteps&&(data.handleNumbers.forEach(function(handleNumber){setHandle(handleNumber,scope_Locations[handleNumber],!0,!0,!1,!1)}),data.handleNumbers.forEach(function(handleNumber){fireEvent("update",handleNumber)})),data.handleNumbers.forEach(function(handleNumber){fireEvent("change",handleNumber),fireEvent("set",handleNumber),fireEvent("end",handleNumber)})}__name(eventEnd,"eventEnd"),__name2(eventEnd,"eventEnd");function eventStart(event,data){if(!data.handleNumbers.some(isHandleDisabled)){var handle;if(data.handleNumbers.length===1){var handleOrigin=scope_Handles[data.handleNumbers[0]];handle=handleOrigin.children[0],scope_ActiveHandlesCount+=1,addClass(handle,options.cssClasses.active)}event.stopPropagation();var listeners=[],moveEvent=attachEvent(actions.move,scope_DocumentElement,eventMove,{target:event.target,handle,connect:data.connect,listeners,startCalcPoint:event.calcPoint,baseSize:baseSize(),pageOffset:event.pageOffset,handleNumbers:data.handleNumbers,buttonsProperty:event.buttons,locations:scope_Locations.slice()}),endEvent=attachEvent(actions.end,scope_DocumentElement,eventEnd,{target:event.target,handle,listeners,doNotReject:!0,handleNumbers:data.handleNumbers}),outEvent=attachEvent("mouseout",scope_DocumentElement,documentLeave,{target:event.target,handle,listeners,doNotReject:!0,handleNumbers:data.handleNumbers});listeners.push.apply(listeners,moveEvent.concat(endEvent,outEvent)),event.cursor&&(scope_Body.style.cursor=getComputedStyle(event.target).cursor,scope_Handles.length>1&&addClass(scope_Target,options.cssClasses.drag),scope_Body.addEventListener("selectstart",preventDefault,!1)),data.handleNumbers.forEach(function(handleNumber){fireEvent("start",handleNumber)})}}__name(eventStart,"eventStart"),__name2(eventStart,"eventStart");function eventTap(event){event.stopPropagation();var proposal=calcPointToPercentage(event.calcPoint),handleNumber=getClosestHandle(proposal);handleNumber!==!1&&(options.events.snap||addClassFor(scope_Target,options.cssClasses.tap,options.animationDuration),setHandle(handleNumber,proposal,!0,!0),setZindex(),fireEvent("slide",handleNumber,!0),fireEvent("update",handleNumber,!0),options.events.snap?eventStart(event,{handleNumbers:[handleNumber]}):(fireEvent("change",handleNumber,!0),fireEvent("set",handleNumber,!0)))}__name(eventTap,"eventTap"),__name2(eventTap,"eventTap");function eventHover(event){var proposal=calcPointToPercentage(event.calcPoint),to=scope_Spectrum.getStep(proposal),value=scope_Spectrum.fromStepping(to);Object.keys(scope_Events).forEach(function(targetEvent){targetEvent.split(".")[0]==="hover"&&scope_Events[targetEvent].forEach(function(callback){callback.call(scope_Self,value)})})}__name(eventHover,"eventHover"),__name2(eventHover,"eventHover");function eventKeydown(event,handleNumber){if(isSliderDisabled()||isHandleDisabled(handleNumber))return!1;var horizontalKeys=["Left","Right"],verticalKeys=["Down","Up"],largeStepKeys=["PageDown","PageUp"],edgeKeys=["Home","End"];options.dir&&!options.ort?horizontalKeys.reverse():options.ort&&!options.dir&&(verticalKeys.reverse(),largeStepKeys.reverse());var key=event.key.replace("Arrow",""),isLargeDown=key===largeStepKeys[0],isLargeUp=key===largeStepKeys[1],isDown=key===verticalKeys[0]||key===horizontalKeys[0]||isLargeDown,isUp=key===verticalKeys[1]||key===horizontalKeys[1]||isLargeUp,isMin=key===edgeKeys[0],isMax=key===edgeKeys[1];if(!isDown&&!isUp&&!isMin&&!isMax)return!0;event.preventDefault();var to;if(isUp||isDown){var direction=isDown?0:1,steps=getNextStepsForHandle(handleNumber),step=steps[direction];if(step===null)return!1;step===!1&&(step=scope_Spectrum.getDefaultStep(scope_Locations[handleNumber],isDown,options.keyboardDefaultStep)),isLargeUp||isLargeDown?step*=options.keyboardPageMultiplier:step*=options.keyboardMultiplier,step=Math.max(step,1e-7),step=(isDown?-1:1)*step,to=scope_Values[handleNumber]+step}else isMax?to=options.spectrum.xVal[options.spectrum.xVal.length-1]:to=options.spectrum.xVal[0];return setHandle(handleNumber,scope_Spectrum.toStepping(to),!0,!0),fireEvent("slide",handleNumber),fireEvent("update",handleNumber),fireEvent("change",handleNumber),fireEvent("set",handleNumber),!1}__name(eventKeydown,"eventKeydown"),__name2(eventKeydown,"eventKeydown");function bindSliderEvents(behaviour){behaviour.fixed||scope_Handles.forEach(function(handle,index2){attachEvent(actions.start,handle.children[0],eventStart,{handleNumbers:[index2]})}),behaviour.tap&&attachEvent(actions.start,scope_Base,eventTap,{}),behaviour.hover&&attachEvent(actions.move,scope_Base,eventHover,{hover:!0}),behaviour.drag&&scope_Connects.forEach(function(connect,index2){if(!(connect===!1||index2===0||index2===scope_Connects.length-1)){var handleBefore=scope_Handles[index2-1],handleAfter=scope_Handles[index2],eventHolders=[connect],handlesToDrag=[handleBefore,handleAfter],handleNumbersToDrag=[index2-1,index2];addClass(connect,options.cssClasses.draggable),behaviour.fixed&&(eventHolders.push(handleBefore.children[0]),eventHolders.push(handleAfter.children[0])),behaviour.dragAll&&(handlesToDrag=scope_Handles,handleNumbersToDrag=scope_HandleNumbers),eventHolders.forEach(function(eventHolder){attachEvent(actions.start,eventHolder,eventStart,{handles:handlesToDrag,handleNumbers:handleNumbersToDrag,connect})})}})}__name(bindSliderEvents,"bindSliderEvents"),__name2(bindSliderEvents,"bindSliderEvents");function bindEvent(namespacedEvent,callback){scope_Events[namespacedEvent]=scope_Events[namespacedEvent]||[],scope_Events[namespacedEvent].push(callback),namespacedEvent.split(".")[0]==="update"&&scope_Handles.forEach(function(a,index2){fireEvent("update",index2)})}__name(bindEvent,"bindEvent"),__name2(bindEvent,"bindEvent");function isInternalNamespace(namespace){return namespace===INTERNAL_EVENT_NS.aria||namespace===INTERNAL_EVENT_NS.tooltips}__name(isInternalNamespace,"isInternalNamespace"),__name2(isInternalNamespace,"isInternalNamespace");function removeEvent(namespacedEvent){var event=namespacedEvent&&namespacedEvent.split(".")[0],namespace=event?namespacedEvent.substring(event.length):namespacedEvent;Object.keys(scope_Events).forEach(function(bind){var tEvent=bind.split(".")[0],tNamespace=bind.substring(tEvent.length);(!event||event===tEvent)&&(!namespace||namespace===tNamespace)&&(!isInternalNamespace(tNamespace)||namespace===tNamespace)&&delete scope_Events[bind]})}__name(removeEvent,"removeEvent"),__name2(removeEvent,"removeEvent");function fireEvent(eventName,handleNumber,tap){Object.keys(scope_Events).forEach(function(targetEvent){var eventType=targetEvent.split(".")[0];eventName===eventType&&scope_Events[targetEvent].forEach(function(callback){callback.call(scope_Self,scope_Values.map(options.format.to),handleNumber,scope_Values.slice(),tap||!1,scope_Locations.slice(),scope_Self)})})}__name(fireEvent,"fireEvent"),__name2(fireEvent,"fireEvent");function checkHandlePosition(reference,handleNumber,to,lookBackward,lookForward,getValue,smoothSteps){var distance;return scope_Handles.length>1&&!options.events.unconstrained&&(lookBackward&&handleNumber>0&&(distance=scope_Spectrum.getAbsoluteDistance(reference[handleNumber-1],options.margin,!1),to=Math.max(to,distance)),lookForward&&handleNumber1&&options.limit&&(lookBackward&&handleNumber>0&&(distance=scope_Spectrum.getAbsoluteDistance(reference[handleNumber-1],options.limit,!1),to=Math.min(to,distance)),lookForward&&handleNumber1?handleNumbers.forEach(function(handleNumber,o){var to=checkHandlePosition(proposals,handleNumber,proposals[handleNumber]+proposal,b[o],f[o],!1,smoothSteps);to===!1?proposal=0:(proposal=to-proposals[handleNumber],proposals[handleNumber]=to)}):b=f=[!0];var state=!1;handleNumbers.forEach(function(handleNumber,o){state=setHandle(handleNumber,locations[handleNumber]+proposal,b[o],f[o],!1,smoothSteps)||state}),state&&(handleNumbers.forEach(function(handleNumber){fireEvent("update",handleNumber),fireEvent("slide",handleNumber)}),connect!=null&&fireEvent("drag",firstHandle))}__name(moveHandles,"moveHandles"),__name2(moveHandles,"moveHandles");function transformDirection(a,b){return options.dir?100-a-b:a}__name(transformDirection,"transformDirection"),__name2(transformDirection,"transformDirection");function updateHandlePosition(handleNumber,to){scope_Locations[handleNumber]=to,scope_Values[handleNumber]=scope_Spectrum.fromStepping(to);var translation=transformDirection(to,0)-scope_DirOffset,translateRule="translate("+inRuleOrder(translation+"%","0")+")";scope_Handles[handleNumber].style[options.transformRule]=translateRule,updateConnect(handleNumber),updateConnect(handleNumber+1)}__name(updateHandlePosition,"updateHandlePosition"),__name2(updateHandlePosition,"updateHandlePosition");function setZindex(){scope_HandleNumbers.forEach(function(handleNumber){var dir=scope_Locations[handleNumber]>50?-1:1,zIndex=3+(scope_Handles.length+dir*handleNumber);scope_Handles[handleNumber].style.zIndex=String(zIndex)})}__name(setZindex,"setZindex"),__name2(setZindex,"setZindex");function setHandle(handleNumber,to,lookBackward,lookForward,exactInput,smoothSteps){return exactInput||(to=checkHandlePosition(scope_Locations,handleNumber,to,lookBackward,lookForward,!1,smoothSteps)),to===!1?!1:(updateHandlePosition(handleNumber,to),!0)}__name(setHandle,"setHandle"),__name2(setHandle,"setHandle");function updateConnect(index2){if(scope_Connects[index2]){var l2=0,h=100;index2!==0&&(l2=scope_Locations[index2-1]),index2!==scope_Connects.length-1&&(h=scope_Locations[index2]);var connectWidth=h-l2,translateRule="translate("+inRuleOrder(transformDirection(l2,connectWidth)+"%","0")+")",scaleRule="scale("+inRuleOrder(connectWidth/100,"1")+")";scope_Connects[index2].style[options.transformRule]=translateRule+" "+scaleRule}}__name(updateConnect,"updateConnect"),__name2(updateConnect,"updateConnect");function resolveToValue(to,handleNumber){return to===null||to===!1||to===void 0||(typeof to=="number"&&(to=String(to)),to=options.format.from(to),to!==!1&&(to=scope_Spectrum.toStepping(to)),to===!1||isNaN(to))?scope_Locations[handleNumber]:to}__name(resolveToValue,"resolveToValue"),__name2(resolveToValue,"resolveToValue");function valueSet(input,fireSetEvent,exactInput){var values=asArray(input),isInit=scope_Locations[0]===void 0;fireSetEvent=fireSetEvent===void 0?!0:fireSetEvent,options.animate&&!isInit&&addClassFor(scope_Target,options.cssClasses.tap,options.animationDuration),scope_HandleNumbers.forEach(function(handleNumber){setHandle(handleNumber,resolveToValue(values[handleNumber],handleNumber),!0,!1,exactInput)});var i=scope_HandleNumbers.length===1?0:1;if(isInit&&scope_Spectrum.hasNoSize()&&(exactInput=!0,scope_Locations[0]=0,scope_HandleNumbers.length>1)){var space_1=100/(scope_HandleNumbers.length-1);scope_HandleNumbers.forEach(function(handleNumber){scope_Locations[handleNumber]=handleNumber*space_1})}for(;i=0&&handleNumbernearbySteps.stepAfter.startValue&&(increment=nearbySteps.stepAfter.startValue-value),value>nearbySteps.thisStep.startValue?decrement=nearbySteps.thisStep.step:nearbySteps.stepBefore.step===!1?decrement=!1:decrement=value-nearbySteps.stepBefore.highestStep,location===100?increment=null:location===0&&(decrement=null);var stepDecimals=scope_Spectrum.countStepDecimals();return increment!==null&&increment!==!1&&(increment=Number(increment.toFixed(stepDecimals))),decrement!==null&&decrement!==!1&&(decrement=Number(decrement.toFixed(stepDecimals))),[decrement,increment]}__name(getNextStepsForHandle,"getNextStepsForHandle"),__name2(getNextStepsForHandle,"getNextStepsForHandle");function getNextSteps(){return scope_HandleNumbers.map(getNextStepsForHandle)}__name(getNextSteps,"getNextSteps"),__name2(getNextSteps,"getNextSteps");function updateOptions(optionsToUpdate,fireSetEvent){var v=valueGet(),updateAble=["margin","limit","padding","range","animate","snap","step","format","pips","tooltips"];updateAble.forEach(function(name2){optionsToUpdate[name2]!==void 0&&(originalOptions[name2]=optionsToUpdate[name2])});var newOptions=testOptions(originalOptions);updateAble.forEach(function(name2){optionsToUpdate[name2]!==void 0&&(options[name2]=newOptions[name2])}),scope_Spectrum=newOptions.spectrum,options.margin=newOptions.margin,options.limit=newOptions.limit,options.padding=newOptions.padding,options.pips?pips(options.pips):removePips(),options.tooltips?tooltips():removeTooltips(),scope_Locations=[],valueSet(isSet(optionsToUpdate.start)?optionsToUpdate.start:v,fireSetEvent)}__name(updateOptions,"updateOptions"),__name2(updateOptions,"updateOptions");function setupSlider(){scope_Base=addSlider(scope_Target),addElements(options.connect,scope_Base),bindSliderEvents(options.events),valueSet(options.start),options.pips&&pips(options.pips),options.tooltips&&tooltips(),aria()}__name(setupSlider,"setupSlider"),__name2(setupSlider,"setupSlider"),setupSlider();var scope_Self={destroy:destroy2,steps:getNextSteps,on:bindEvent,off:removeEvent,get:valueGet,set:valueSet,setHandle:valueSetHandle,reset:valueReset,disable,enable,__moveHandles:function(upward,proposal,handleNumbers){moveHandles(upward,proposal,scope_Locations,handleNumbers)},options:originalOptions,updateOptions,target:scope_Target,removePips,removeTooltips,getPositions:function(){return scope_Locations.slice()},getTooltips:function(){return scope_Tooltips},getOrigins:function(){return scope_Handles},pips};return scope_Self}__name(scope,"scope"),__name2(scope,"scope");function initialize(target,originalOptions){if(!target||!target.nodeName)throw new Error("noUiSlider: create requires a single element, got: "+target);if(target.noUiSlider)throw new Error("noUiSlider: Slider was already initialized.");var options=testOptions(originalOptions),api=scope(target,options,originalOptions);return target.noUiSlider=api,api}__name(initialize,"initialize"),__name2(initialize,"initialize");const noUiSlider={__spectrum:Spectrum,cssClasses,create:initialize};export{sumBy as A,pipe as B,filter as C,Duration as D,EditorView as E,map as F,DateTime as G,noUiSlider as H,Interval as I,findLast as J,omitBy as K,MiniSearch as M,PipsMode as P,Sortable as S,Tagify as T,mapValues as a,isObject as b,compact as c,isEmpty as d,equals as e,uniqBy as f,groupBy as g,difference as h,isNil as i,meanBy as j,keys$1 as k,basicSetup as l,mapToObj as m,json as n,omit as o,pick$1 as p,linter as q,keymap as r,sortBy as s,indentWithTab as t,uniq as u,autocompletion as v,syntaxTree as w,jsonParseLinter as x,fromPairs as y,maxBy as z}; diff --git a/Data/worlds/the-fall-of-plaguestone/data/actors/000028.log b/Data/worlds/the-fall-of-plaguestone/data/actors/000028.log deleted file mode 100644 index e103b2df..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/actors/000028.log and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/actors/000026.ldb b/Data/worlds/the-fall-of-plaguestone/data/actors/000031.ldb similarity index 57% rename from Data/worlds/the-fall-of-plaguestone/data/actors/000026.ldb rename to Data/worlds/the-fall-of-plaguestone/data/actors/000031.ldb index 3f4c080b..103c115b 100644 Binary files a/Data/worlds/the-fall-of-plaguestone/data/actors/000026.ldb and b/Data/worlds/the-fall-of-plaguestone/data/actors/000031.ldb differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/actors/000033.log b/Data/worlds/the-fall-of-plaguestone/data/actors/000033.log new file mode 100644 index 00000000..1190f608 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/actors/000033.log differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/actors/CURRENT b/Data/worlds/the-fall-of-plaguestone/data/actors/CURRENT index 3bf51646..259cf53c 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/actors/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/data/actors/CURRENT @@ -1 +1 @@ -MANIFEST-000027 +MANIFEST-000032 diff --git a/Data/worlds/the-fall-of-plaguestone/data/actors/LOG b/Data/worlds/the-fall-of-plaguestone/data/actors/LOG index 3c8d7f1a..afa9bf69 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/actors/LOG +++ b/Data/worlds/the-fall-of-plaguestone/data/actors/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:09.607108 ffff86fdf0a0 Recovering log #24 -2023/10/20-07:55:09.616217 ffff86fdf0a0 Delete type=3 #22 -2023/10/20-07:55:09.616245 ffff86fdf0a0 Delete type=0 #24 +2023/10/23-05:12:15.921796 ffff87fff0a0 Recovering log #29 +2023/10/23-05:12:15.930062 ffff87fff0a0 Delete type=3 #27 +2023/10/23-05:12:15.930091 ffff87fff0a0 Delete type=0 #29 diff --git a/Data/worlds/the-fall-of-plaguestone/data/actors/LOG.old b/Data/worlds/the-fall-of-plaguestone/data/actors/LOG.old index ab075548..aeb6c15e 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/actors/LOG.old +++ b/Data/worlds/the-fall-of-plaguestone/data/actors/LOG.old @@ -1,15 +1,15 @@ -2023/10/20-07:41:10.442744 ffff867cf0a0 Recovering log #19 -2023/10/20-07:41:10.452101 ffff867cf0a0 Delete type=0 #19 -2023/10/20-07:41:10.452130 ffff867cf0a0 Delete type=3 #17 -2023/10/20-07:49:07.378852 ffff85fbf0a0 Level-0 table #25: started -2023/10/20-07:49:07.382243 ffff85fbf0a0 Level-0 table #25: 19318 bytes OK -2023/10/20-07:49:07.384515 ffff85fbf0a0 Delete type=0 #23 -2023/10/20-07:49:07.391616 ffff85fbf0a0 Manual compaction at level-0 from '!actors!02rlf2KufFToDPNj' @ 72057594037927935 : 1 .. '!actors.items!zsMKDLiAFU6XMVGC.ybVy82D41OJgh19C' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.391728 ffff85fbf0a0 Manual compaction at level-1 from '!actors!02rlf2KufFToDPNj' @ 72057594037927935 : 1 .. '!actors.items!zsMKDLiAFU6XMVGC.ybVy82D41OJgh19C' @ 0 : 0; will stop at '!actors.items!xelguAx6Lp7XzoYl.slCMgd2stlwxBKdg' @ 5172 : 0 -2023/10/20-07:49:07.391731 ffff85fbf0a0 Compacting 1@1 + 1@2 files -2023/10/20-07:49:07.403744 ffff85fbf0a0 Generated table #26@1: 768 keys, 804474 bytes -2023/10/20-07:49:07.403755 ffff85fbf0a0 Compacted 1@1 + 1@2 files => 804474 bytes -2023/10/20-07:49:07.405614 ffff85fbf0a0 compacted to: files[ 0 0 1 0 0 0 0 ] -2023/10/20-07:49:07.405671 ffff85fbf0a0 Delete type=2 #25 -2023/10/20-07:49:07.405897 ffff85fbf0a0 Delete type=2 #21 -2023/10/20-07:49:07.408643 ffff85fbf0a0 Manual compaction at level-1 from '!actors.items!xelguAx6Lp7XzoYl.slCMgd2stlwxBKdg' @ 5172 : 0 .. '!actors.items!zsMKDLiAFU6XMVGC.ybVy82D41OJgh19C' @ 0 : 0; will stop at (end) +2023/10/20-07:55:09.607108 ffff86fdf0a0 Recovering log #24 +2023/10/20-07:55:09.616217 ffff86fdf0a0 Delete type=3 #22 +2023/10/20-07:55:09.616245 ffff86fdf0a0 Delete type=0 #24 +2023/10/23-05:11:51.253475 ffff85fbf0a0 Level-0 table #30: started +2023/10/23-05:11:51.266129 ffff85fbf0a0 Level-0 table #30: 1044720 bytes OK +2023/10/23-05:11:51.268051 ffff85fbf0a0 Delete type=0 #28 +2023/10/23-05:11:51.279486 ffff85fbf0a0 Manual compaction at level-0 from '!actors!02rlf2KufFToDPNj' @ 72057594037927935 : 1 .. '!actors.items!zsMKDLiAFU6XMVGC.ybVy82D41OJgh19C' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.279680 ffff85fbf0a0 Manual compaction at level-1 from '!actors!02rlf2KufFToDPNj' @ 72057594037927935 : 1 .. '!actors.items!zsMKDLiAFU6XMVGC.ybVy82D41OJgh19C' @ 0 : 0; will stop at '!actors.items!yLp8jLn2IBHd5bVJ.u3YnULJ9YqMBkD6D' @ 5314 : 1 +2023/10/23-05:11:51.279684 ffff85fbf0a0 Compacting 1@1 + 1@2 files +2023/10/23-05:11:51.294166 ffff85fbf0a0 Generated table #31@1: 878 keys, 895202 bytes +2023/10/23-05:11:51.294176 ffff85fbf0a0 Compacted 1@1 + 1@2 files => 895202 bytes +2023/10/23-05:11:51.295736 ffff85fbf0a0 compacted to: files[ 0 0 1 0 0 0 0 ] +2023/10/23-05:11:51.295967 ffff85fbf0a0 Delete type=2 #26 +2023/10/23-05:11:51.296237 ffff85fbf0a0 Delete type=2 #30 +2023/10/23-05:11:51.377884 ffff85fbf0a0 Manual compaction at level-1 from '!actors.items!yLp8jLn2IBHd5bVJ.u3YnULJ9YqMBkD6D' @ 5314 : 1 .. '!actors.items!zsMKDLiAFU6XMVGC.ybVy82D41OJgh19C' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/data/actors/MANIFEST-000027 b/Data/worlds/the-fall-of-plaguestone/data/actors/MANIFEST-000027 deleted file mode 100644 index 7fc2661f..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/actors/MANIFEST-000027 and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/actors/MANIFEST-000032 b/Data/worlds/the-fall-of-plaguestone/data/actors/MANIFEST-000032 new file mode 100644 index 00000000..146a800f Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/actors/MANIFEST-000032 differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/cards/000019.log b/Data/worlds/the-fall-of-plaguestone/data/cards/000023.log similarity index 100% rename from Data/worlds/the-fall-of-plaguestone/data/cards/000019.log rename to Data/worlds/the-fall-of-plaguestone/data/cards/000023.log diff --git a/Data/worlds/the-fall-of-plaguestone/data/cards/CURRENT b/Data/worlds/the-fall-of-plaguestone/data/cards/CURRENT index e417a51c..5af92b2b 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/cards/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/data/cards/CURRENT @@ -1 +1 @@ -MANIFEST-000018 +MANIFEST-000022 diff --git a/Data/worlds/the-fall-of-plaguestone/data/cards/LOG b/Data/worlds/the-fall-of-plaguestone/data/cards/LOG index 43070298..e607e5f4 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/cards/LOG +++ b/Data/worlds/the-fall-of-plaguestone/data/cards/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:09.624898 ffff87fff0a0 Recovering log #16 -2023/10/20-07:55:09.630080 ffff87fff0a0 Delete type=3 #14 -2023/10/20-07:55:09.630105 ffff87fff0a0 Delete type=0 #16 +2023/10/23-05:12:15.977308 ffff877ef0a0 Recovering log #20 +2023/10/23-05:12:15.982853 ffff877ef0a0 Delete type=0 #20 +2023/10/23-05:12:15.982877 ffff877ef0a0 Delete type=3 #18 diff --git a/Data/worlds/the-fall-of-plaguestone/data/cards/LOG.old b/Data/worlds/the-fall-of-plaguestone/data/cards/LOG.old index 54f5cddc..fb7ddefc 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/cards/LOG.old +++ b/Data/worlds/the-fall-of-plaguestone/data/cards/LOG.old @@ -1,7 +1,7 @@ -2023/10/20-07:41:10.462389 ffff867cf0a0 Recovering log #12 -2023/10/20-07:41:10.467665 ffff867cf0a0 Delete type=0 #12 -2023/10/20-07:41:10.467692 ffff867cf0a0 Delete type=3 #10 -2023/10/20-07:49:07.384575 ffff85fbf0a0 Level-0 table #17: started -2023/10/20-07:49:07.384591 ffff85fbf0a0 Level-0 table #17: 0 bytes OK -2023/10/20-07:49:07.387006 ffff85fbf0a0 Delete type=0 #15 -2023/10/20-07:49:07.391625 ffff85fbf0a0 Manual compaction at level-0 from 'undefined' @ 72057594037927935 : 1 .. 'undefined' @ 0 : 0; will stop at (end) +2023/10/20-07:55:09.624898 ffff87fff0a0 Recovering log #16 +2023/10/20-07:55:09.630080 ffff87fff0a0 Delete type=3 #14 +2023/10/20-07:55:09.630105 ffff87fff0a0 Delete type=0 #16 +2023/10/23-05:11:51.268451 ffff85fbf0a0 Level-0 table #21: started +2023/10/23-05:11:51.268471 ffff85fbf0a0 Level-0 table #21: 0 bytes OK +2023/10/23-05:11:51.270764 ffff85fbf0a0 Delete type=0 #19 +2023/10/23-05:11:51.279501 ffff85fbf0a0 Manual compaction at level-0 from 'undefined' @ 72057594037927935 : 1 .. 'undefined' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/data/cards/MANIFEST-000018 b/Data/worlds/the-fall-of-plaguestone/data/cards/MANIFEST-000018 deleted file mode 100644 index 1f89f0da..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/cards/MANIFEST-000018 and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/cards/MANIFEST-000022 b/Data/worlds/the-fall-of-plaguestone/data/cards/MANIFEST-000022 new file mode 100644 index 00000000..405e4abb Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/cards/MANIFEST-000022 differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/combats/000020.log b/Data/worlds/the-fall-of-plaguestone/data/combats/000024.log similarity index 100% rename from Data/worlds/the-fall-of-plaguestone/data/combats/000020.log rename to Data/worlds/the-fall-of-plaguestone/data/combats/000024.log diff --git a/Data/worlds/the-fall-of-plaguestone/data/combats/CURRENT b/Data/worlds/the-fall-of-plaguestone/data/combats/CURRENT index 43c22f0a..7fbb6234 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/combats/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/data/combats/CURRENT @@ -1 +1 @@ -MANIFEST-000019 +MANIFEST-000023 diff --git a/Data/worlds/the-fall-of-plaguestone/data/combats/LOG b/Data/worlds/the-fall-of-plaguestone/data/combats/LOG index ba6a0170..761111a0 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/combats/LOG +++ b/Data/worlds/the-fall-of-plaguestone/data/combats/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:09.653695 ffff877ef0a0 Recovering log #17 -2023/10/20-07:55:09.659171 ffff877ef0a0 Delete type=0 #17 -2023/10/20-07:55:09.659193 ffff877ef0a0 Delete type=3 #15 +2023/10/23-05:12:16.049795 ffff877ef0a0 Recovering log #21 +2023/10/23-05:12:16.054988 ffff877ef0a0 Delete type=0 #21 +2023/10/23-05:12:16.055012 ffff877ef0a0 Delete type=3 #19 diff --git a/Data/worlds/the-fall-of-plaguestone/data/combats/LOG.old b/Data/worlds/the-fall-of-plaguestone/data/combats/LOG.old index 9c3ea668..bf8a1360 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/combats/LOG.old +++ b/Data/worlds/the-fall-of-plaguestone/data/combats/LOG.old @@ -1,8 +1,8 @@ -2023/10/20-07:41:10.491589 ffff867cf0a0 Recovering log #13 -2023/10/20-07:41:10.496742 ffff867cf0a0 Delete type=0 #13 -2023/10/20-07:41:10.496767 ffff867cf0a0 Delete type=3 #11 -2023/10/20-07:49:07.389340 ffff85fbf0a0 Level-0 table #18: started -2023/10/20-07:49:07.389355 ffff85fbf0a0 Level-0 table #18: 0 bytes OK -2023/10/20-07:49:07.391585 ffff85fbf0a0 Delete type=0 #16 -2023/10/20-07:49:07.391717 ffff85fbf0a0 Manual compaction at level-0 from '!combats!NibfWYwSFXBWARgJ' @ 72057594037927935 : 1 .. '!combats!NibfWYwSFXBWARgJ' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.408395 ffff85fbf0a0 Manual compaction at level-1 from '!combats!NibfWYwSFXBWARgJ' @ 72057594037927935 : 1 .. '!combats!NibfWYwSFXBWARgJ' @ 0 : 0; will stop at (end) +2023/10/20-07:55:09.653695 ffff877ef0a0 Recovering log #17 +2023/10/20-07:55:09.659171 ffff877ef0a0 Delete type=0 #17 +2023/10/20-07:55:09.659193 ffff877ef0a0 Delete type=3 #15 +2023/10/23-05:11:51.277525 ffff85fbf0a0 Level-0 table #22: started +2023/10/23-05:11:51.277542 ffff85fbf0a0 Level-0 table #22: 0 bytes OK +2023/10/23-05:11:51.279445 ffff85fbf0a0 Delete type=0 #20 +2023/10/23-05:11:51.279665 ffff85fbf0a0 Manual compaction at level-0 from '!combats!NibfWYwSFXBWARgJ' @ 72057594037927935 : 1 .. '!combats!NibfWYwSFXBWARgJ' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.377627 ffff85fbf0a0 Manual compaction at level-1 from '!combats!NibfWYwSFXBWARgJ' @ 72057594037927935 : 1 .. '!combats!NibfWYwSFXBWARgJ' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/data/combats/MANIFEST-000019 b/Data/worlds/the-fall-of-plaguestone/data/combats/MANIFEST-000023 similarity index 88% rename from Data/worlds/the-fall-of-plaguestone/data/combats/MANIFEST-000019 rename to Data/worlds/the-fall-of-plaguestone/data/combats/MANIFEST-000023 index 8a4c53f1..625864e2 100644 Binary files a/Data/worlds/the-fall-of-plaguestone/data/combats/MANIFEST-000019 and b/Data/worlds/the-fall-of-plaguestone/data/combats/MANIFEST-000023 differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/drawings/000019.log b/Data/worlds/the-fall-of-plaguestone/data/drawings/000023.log similarity index 100% rename from Data/worlds/the-fall-of-plaguestone/data/drawings/000019.log rename to Data/worlds/the-fall-of-plaguestone/data/drawings/000023.log diff --git a/Data/worlds/the-fall-of-plaguestone/data/drawings/CURRENT b/Data/worlds/the-fall-of-plaguestone/data/drawings/CURRENT index e417a51c..5af92b2b 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/drawings/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/data/drawings/CURRENT @@ -1 +1 @@ -MANIFEST-000018 +MANIFEST-000022 diff --git a/Data/worlds/the-fall-of-plaguestone/data/drawings/LOG b/Data/worlds/the-fall-of-plaguestone/data/drawings/LOG index 4afcbd75..b90b29ab 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/drawings/LOG +++ b/Data/worlds/the-fall-of-plaguestone/data/drawings/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:09.666684 ffff867cf0a0 Recovering log #16 -2023/10/20-07:55:09.672067 ffff867cf0a0 Delete type=3 #14 -2023/10/20-07:55:09.672091 ffff867cf0a0 Delete type=0 #16 +2023/10/23-05:12:16.065214 ffff87fff0a0 Recovering log #20 +2023/10/23-05:12:16.070567 ffff87fff0a0 Delete type=0 #20 +2023/10/23-05:12:16.070589 ffff87fff0a0 Delete type=3 #18 diff --git a/Data/worlds/the-fall-of-plaguestone/data/drawings/LOG.old b/Data/worlds/the-fall-of-plaguestone/data/drawings/LOG.old index ea620aed..deabad82 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/drawings/LOG.old +++ b/Data/worlds/the-fall-of-plaguestone/data/drawings/LOG.old @@ -1,7 +1,7 @@ -2023/10/20-07:41:10.506083 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:41:10.511642 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:41:10.511664 ffff86fdf0a0 Delete type=3 #10 -2023/10/20-07:49:07.406049 ffff85fbf0a0 Level-0 table #17: started -2023/10/20-07:49:07.406066 ffff85fbf0a0 Level-0 table #17: 0 bytes OK -2023/10/20-07:49:07.408183 ffff85fbf0a0 Delete type=0 #15 -2023/10/20-07:49:07.408742 ffff85fbf0a0 Manual compaction at level-0 from 'undefined' @ 72057594037927935 : 1 .. 'undefined' @ 0 : 0; will stop at (end) +2023/10/20-07:55:09.666684 ffff867cf0a0 Recovering log #16 +2023/10/20-07:55:09.672067 ffff867cf0a0 Delete type=3 #14 +2023/10/20-07:55:09.672091 ffff867cf0a0 Delete type=0 #16 +2023/10/23-05:11:51.296394 ffff85fbf0a0 Level-0 table #21: started +2023/10/23-05:11:51.296412 ffff85fbf0a0 Level-0 table #21: 0 bytes OK +2023/10/23-05:11:51.298587 ffff85fbf0a0 Delete type=0 #19 +2023/10/23-05:11:51.378007 ffff85fbf0a0 Manual compaction at level-0 from 'undefined' @ 72057594037927935 : 1 .. 'undefined' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/data/drawings/MANIFEST-000018 b/Data/worlds/the-fall-of-plaguestone/data/drawings/MANIFEST-000018 deleted file mode 100644 index 1f89f0da..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/drawings/MANIFEST-000018 and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/drawings/MANIFEST-000022 b/Data/worlds/the-fall-of-plaguestone/data/drawings/MANIFEST-000022 new file mode 100644 index 00000000..405e4abb Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/drawings/MANIFEST-000022 differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/fog/000025.log b/Data/worlds/the-fall-of-plaguestone/data/fog/000025.log deleted file mode 100644 index 2165a6e5..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/fog/000025.log and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/fog/000023.ldb b/Data/worlds/the-fall-of-plaguestone/data/fog/000028.ldb similarity index 99% rename from Data/worlds/the-fall-of-plaguestone/data/fog/000023.ldb rename to Data/worlds/the-fall-of-plaguestone/data/fog/000028.ldb index 66b75e24..15c04293 100644 Binary files a/Data/worlds/the-fall-of-plaguestone/data/fog/000023.ldb and b/Data/worlds/the-fall-of-plaguestone/data/fog/000028.ldb differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/playlists/000019.log b/Data/worlds/the-fall-of-plaguestone/data/fog/000030.log similarity index 100% rename from Data/worlds/the-fall-of-plaguestone/data/playlists/000019.log rename to Data/worlds/the-fall-of-plaguestone/data/fog/000030.log diff --git a/Data/worlds/the-fall-of-plaguestone/data/fog/CURRENT b/Data/worlds/the-fall-of-plaguestone/data/fog/CURRENT index 1e21b78c..52f34bed 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/fog/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/data/fog/CURRENT @@ -1 +1 @@ -MANIFEST-000024 +MANIFEST-000029 diff --git a/Data/worlds/the-fall-of-plaguestone/data/fog/LOG b/Data/worlds/the-fall-of-plaguestone/data/fog/LOG index 66e7863c..544b0dca 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/fog/LOG +++ b/Data/worlds/the-fall-of-plaguestone/data/fog/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:09.673766 ffff877ef0a0 Recovering log #21 -2023/10/20-07:55:09.678474 ffff877ef0a0 Delete type=0 #21 -2023/10/20-07:55:09.678495 ffff877ef0a0 Delete type=3 #19 +2023/10/23-05:12:16.072387 ffff877ef0a0 Recovering log #26 +2023/10/23-05:12:16.077759 ffff877ef0a0 Delete type=3 #24 +2023/10/23-05:12:16.077784 ffff877ef0a0 Delete type=0 #26 diff --git a/Data/worlds/the-fall-of-plaguestone/data/fog/LOG.old b/Data/worlds/the-fall-of-plaguestone/data/fog/LOG.old index 8c6ef3c7..3173bef2 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/fog/LOG.old +++ b/Data/worlds/the-fall-of-plaguestone/data/fog/LOG.old @@ -1,15 +1,15 @@ -2023/10/20-07:41:10.513367 ffff867cf0a0 Recovering log #16 -2023/10/20-07:41:10.518404 ffff867cf0a0 Delete type=0 #16 -2023/10/20-07:41:10.518426 ffff867cf0a0 Delete type=3 #11 -2023/10/20-07:49:07.408871 ffff85fbf0a0 Level-0 table #22: started -2023/10/20-07:49:07.411088 ffff85fbf0a0 Level-0 table #22: 1780 bytes OK -2023/10/20-07:49:07.412883 ffff85fbf0a0 Delete type=0 #20 -2023/10/20-07:49:07.419357 ffff85fbf0a0 Manual compaction at level-0 from '!fog!1GQeqKyap7VEMQAr' @ 72057594037927935 : 1 .. '!fog!ybjeUj9MnqH1PhLM' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.419405 ffff85fbf0a0 Manual compaction at level-1 from '!fog!1GQeqKyap7VEMQAr' @ 72057594037927935 : 1 .. '!fog!ybjeUj9MnqH1PhLM' @ 0 : 0; will stop at '!fog!cQtGedzUidMSA8v0' @ 154 : 1 -2023/10/20-07:49:07.419408 ffff85fbf0a0 Compacting 1@1 + 1@2 files -2023/10/20-07:49:07.436098 ffff85fbf0a0 Generated table #23@1: 32 keys, 1718239 bytes -2023/10/20-07:49:07.436109 ffff85fbf0a0 Compacted 1@1 + 1@2 files => 1718239 bytes -2023/10/20-07:49:07.437760 ffff85fbf0a0 compacted to: files[ 0 0 1 0 0 0 0 ] -2023/10/20-07:49:07.437815 ffff85fbf0a0 Delete type=2 #22 -2023/10/20-07:49:07.438190 ffff85fbf0a0 Delete type=2 #18 -2023/10/20-07:49:07.438813 ffff85fbf0a0 Manual compaction at level-1 from '!fog!cQtGedzUidMSA8v0' @ 154 : 1 .. '!fog!ybjeUj9MnqH1PhLM' @ 0 : 0; will stop at (end) +2023/10/20-07:55:09.673766 ffff877ef0a0 Recovering log #21 +2023/10/20-07:55:09.678474 ffff877ef0a0 Delete type=0 #21 +2023/10/20-07:55:09.678495 ffff877ef0a0 Delete type=3 #19 +2023/10/23-05:11:51.378227 ffff85fbf0a0 Level-0 table #27: started +2023/10/23-05:11:51.380860 ffff85fbf0a0 Level-0 table #27: 6759 bytes OK +2023/10/23-05:11:51.382755 ffff85fbf0a0 Delete type=0 #25 +2023/10/23-05:11:51.397589 ffff85fbf0a0 Manual compaction at level-0 from '!fog!1GQeqKyap7VEMQAr' @ 72057594037927935 : 1 .. '!fog!ybjeUj9MnqH1PhLM' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.397642 ffff85fbf0a0 Manual compaction at level-1 from '!fog!1GQeqKyap7VEMQAr' @ 72057594037927935 : 1 .. '!fog!ybjeUj9MnqH1PhLM' @ 0 : 0; will stop at '!fog!cQtGedzUidMSA8v0' @ 155 : 1 +2023/10/23-05:11:51.397645 ffff85fbf0a0 Compacting 1@1 + 1@2 files +2023/10/23-05:11:51.417261 ffff85fbf0a0 Generated table #28@1: 32 keys, 1718239 bytes +2023/10/23-05:11:51.417273 ffff85fbf0a0 Compacted 1@1 + 1@2 files => 1718239 bytes +2023/10/23-05:11:51.418931 ffff85fbf0a0 compacted to: files[ 0 0 1 0 0 0 0 ] +2023/10/23-05:11:51.419302 ffff85fbf0a0 Delete type=2 #23 +2023/10/23-05:11:51.419564 ffff85fbf0a0 Delete type=2 #27 +2023/10/23-05:11:51.433605 ffff85fbf0a0 Manual compaction at level-1 from '!fog!cQtGedzUidMSA8v0' @ 155 : 1 .. '!fog!ybjeUj9MnqH1PhLM' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/data/fog/MANIFEST-000024 b/Data/worlds/the-fall-of-plaguestone/data/fog/MANIFEST-000024 deleted file mode 100644 index 08c370fd..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/fog/MANIFEST-000024 and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/fog/MANIFEST-000029 b/Data/worlds/the-fall-of-plaguestone/data/fog/MANIFEST-000029 new file mode 100644 index 00000000..ac977f39 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/fog/MANIFEST-000029 differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/folders/000015.ldb b/Data/worlds/the-fall-of-plaguestone/data/folders/000015.ldb deleted file mode 100644 index bcc4a7d7..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/folders/000015.ldb and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/folders/000021.log b/Data/worlds/the-fall-of-plaguestone/data/folders/000021.log deleted file mode 100644 index d63942df..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/folders/000021.log and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/folders/000024.ldb b/Data/worlds/the-fall-of-plaguestone/data/folders/000024.ldb new file mode 100644 index 00000000..71b04672 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/folders/000024.ldb differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/tables/000019.log b/Data/worlds/the-fall-of-plaguestone/data/folders/000026.log similarity index 100% rename from Data/worlds/the-fall-of-plaguestone/data/tables/000019.log rename to Data/worlds/the-fall-of-plaguestone/data/folders/000026.log diff --git a/Data/worlds/the-fall-of-plaguestone/data/folders/CURRENT b/Data/worlds/the-fall-of-plaguestone/data/folders/CURRENT index f180e911..f6220906 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/folders/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/data/folders/CURRENT @@ -1 +1 @@ -MANIFEST-000020 +MANIFEST-000025 diff --git a/Data/worlds/the-fall-of-plaguestone/data/folders/LOG b/Data/worlds/the-fall-of-plaguestone/data/folders/LOG index 36c60d47..5d7fcafe 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/folders/LOG +++ b/Data/worlds/the-fall-of-plaguestone/data/folders/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:09.681679 ffff867cf0a0 Recovering log #18 -2023/10/20-07:55:09.686522 ffff867cf0a0 Delete type=3 #16 -2023/10/20-07:55:09.686544 ffff867cf0a0 Delete type=0 #18 +2023/10/23-05:12:16.081235 ffff87fff0a0 Recovering log #22 +2023/10/23-05:12:16.086200 ffff87fff0a0 Delete type=0 #22 +2023/10/23-05:12:16.086221 ffff87fff0a0 Delete type=3 #20 diff --git a/Data/worlds/the-fall-of-plaguestone/data/folders/LOG.old b/Data/worlds/the-fall-of-plaguestone/data/folders/LOG.old index dc2800e5..7722fcba 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/folders/LOG.old +++ b/Data/worlds/the-fall-of-plaguestone/data/folders/LOG.old @@ -1,8 +1,15 @@ -2023/10/20-07:41:10.521725 ffff86fdf0a0 Recovering log #13 -2023/10/20-07:41:10.528621 ffff86fdf0a0 Delete type=0 #13 -2023/10/20-07:41:10.528642 ffff86fdf0a0 Delete type=3 #11 -2023/10/20-07:49:07.412939 ffff85fbf0a0 Level-0 table #19: started -2023/10/20-07:49:07.412953 ffff85fbf0a0 Level-0 table #19: 0 bytes OK -2023/10/20-07:49:07.415232 ffff85fbf0a0 Delete type=0 #17 -2023/10/20-07:49:07.419370 ffff85fbf0a0 Manual compaction at level-0 from '!folders!3qGGMtsFfQWRe0FU' @ 72057594037927935 : 1 .. '!folders!x9xlg2Jc6S6R4GiD' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.438460 ffff85fbf0a0 Manual compaction at level-1 from '!folders!3qGGMtsFfQWRe0FU' @ 72057594037927935 : 1 .. '!folders!x9xlg2Jc6S6R4GiD' @ 0 : 0; will stop at (end) +2023/10/20-07:55:09.681679 ffff867cf0a0 Recovering log #18 +2023/10/20-07:55:09.686522 ffff867cf0a0 Delete type=3 #16 +2023/10/20-07:55:09.686544 ffff867cf0a0 Delete type=0 #18 +2023/10/23-05:11:51.382870 ffff85fbf0a0 Level-0 table #23: started +2023/10/23-05:11:51.385236 ffff85fbf0a0 Level-0 table #23: 729 bytes OK +2023/10/23-05:11:51.387079 ffff85fbf0a0 Delete type=0 #21 +2023/10/23-05:11:51.397604 ffff85fbf0a0 Manual compaction at level-0 from '!folders!3qGGMtsFfQWRe0FU' @ 72057594037927935 : 1 .. '!folders!x9xlg2Jc6S6R4GiD' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.419609 ffff85fbf0a0 Manual compaction at level-1 from '!folders!3qGGMtsFfQWRe0FU' @ 72057594037927935 : 1 .. '!folders!x9xlg2Jc6S6R4GiD' @ 0 : 0; will stop at '!folders!jQJUxvg9G3VIvLDh' @ 62 : 1 +2023/10/23-05:11:51.419615 ffff85fbf0a0 Compacting 1@1 + 1@2 files +2023/10/23-05:11:51.421720 ffff85fbf0a0 Generated table #24@1: 36 keys, 4011 bytes +2023/10/23-05:11:51.421730 ffff85fbf0a0 Compacted 1@1 + 1@2 files => 4011 bytes +2023/10/23-05:11:51.423736 ffff85fbf0a0 compacted to: files[ 0 0 1 0 0 0 0 ] +2023/10/23-05:11:51.423788 ffff85fbf0a0 Delete type=2 #15 +2023/10/23-05:11:51.423830 ffff85fbf0a0 Delete type=2 #23 +2023/10/23-05:11:51.433828 ffff85fbf0a0 Manual compaction at level-1 from '!folders!jQJUxvg9G3VIvLDh' @ 62 : 1 .. '!folders!x9xlg2Jc6S6R4GiD' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/data/folders/MANIFEST-000020 b/Data/worlds/the-fall-of-plaguestone/data/folders/MANIFEST-000020 deleted file mode 100644 index b2e501fa..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/folders/MANIFEST-000020 and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/folders/MANIFEST-000025 b/Data/worlds/the-fall-of-plaguestone/data/folders/MANIFEST-000025 new file mode 100644 index 00000000..04e39728 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/folders/MANIFEST-000025 differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/items/000015.ldb b/Data/worlds/the-fall-of-plaguestone/data/items/000015.ldb deleted file mode 100644 index 83181feb..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/items/000015.ldb and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/items/000021.log b/Data/worlds/the-fall-of-plaguestone/data/items/000021.log deleted file mode 100644 index 64b0f027..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/items/000021.log and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/items/000024.ldb b/Data/worlds/the-fall-of-plaguestone/data/items/000024.ldb new file mode 100644 index 00000000..3aa53bc6 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/items/000024.ldb differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/items/000026.log b/Data/worlds/the-fall-of-plaguestone/data/items/000026.log new file mode 100644 index 00000000..40ffdf84 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/items/000026.log differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/items/CURRENT b/Data/worlds/the-fall-of-plaguestone/data/items/CURRENT index f180e911..f6220906 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/items/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/data/items/CURRENT @@ -1 +1 @@ -MANIFEST-000020 +MANIFEST-000025 diff --git a/Data/worlds/the-fall-of-plaguestone/data/items/LOG b/Data/worlds/the-fall-of-plaguestone/data/items/LOG index b32e1353..39f32de8 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/items/LOG +++ b/Data/worlds/the-fall-of-plaguestone/data/items/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:09.688717 ffff877ef0a0 Recovering log #18 -2023/10/20-07:55:09.693669 ffff877ef0a0 Delete type=3 #16 -2023/10/20-07:55:09.693691 ffff877ef0a0 Delete type=0 #18 +2023/10/23-05:12:16.088110 ffff877ef0a0 Recovering log #22 +2023/10/23-05:12:16.092893 ffff877ef0a0 Delete type=0 #22 +2023/10/23-05:12:16.092912 ffff877ef0a0 Delete type=3 #20 diff --git a/Data/worlds/the-fall-of-plaguestone/data/items/LOG.old b/Data/worlds/the-fall-of-plaguestone/data/items/LOG.old index 8519559b..a1c4ec63 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/items/LOG.old +++ b/Data/worlds/the-fall-of-plaguestone/data/items/LOG.old @@ -1,8 +1,15 @@ -2023/10/20-07:41:10.530401 ffff867cf0a0 Recovering log #13 -2023/10/20-07:41:10.535699 ffff867cf0a0 Delete type=0 #13 -2023/10/20-07:41:10.535719 ffff867cf0a0 Delete type=3 #11 -2023/10/20-07:49:07.415269 ffff85fbf0a0 Level-0 table #19: started -2023/10/20-07:49:07.415285 ffff85fbf0a0 Level-0 table #19: 0 bytes OK -2023/10/20-07:49:07.417272 ffff85fbf0a0 Delete type=0 #17 -2023/10/20-07:49:07.419382 ffff85fbf0a0 Manual compaction at level-0 from '!items!0ocdnQF0BBfpeRrQ' @ 72057594037927935 : 1 .. '!items!qihB0L3oIHAgpbiT' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.438627 ffff85fbf0a0 Manual compaction at level-1 from '!items!0ocdnQF0BBfpeRrQ' @ 72057594037927935 : 1 .. '!items!qihB0L3oIHAgpbiT' @ 0 : 0; will stop at (end) +2023/10/20-07:55:09.688717 ffff877ef0a0 Recovering log #18 +2023/10/20-07:55:09.693669 ffff877ef0a0 Delete type=3 #16 +2023/10/20-07:55:09.693691 ffff877ef0a0 Delete type=0 #18 +2023/10/23-05:11:51.387129 ffff85fbf0a0 Level-0 table #23: started +2023/10/23-05:11:51.390863 ffff85fbf0a0 Level-0 table #23: 118094 bytes OK +2023/10/23-05:11:51.392585 ffff85fbf0a0 Delete type=0 #21 +2023/10/23-05:11:51.397618 ffff85fbf0a0 Manual compaction at level-0 from '!items!0ocdnQF0BBfpeRrQ' @ 72057594037927935 : 1 .. '!items!sxzflAlx11OUD2wf' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.423869 ffff85fbf0a0 Manual compaction at level-1 from '!items!0ocdnQF0BBfpeRrQ' @ 72057594037927935 : 1 .. '!items!sxzflAlx11OUD2wf' @ 0 : 0; will stop at '!items!u5wL9UdxsdjSUgSw' @ 520 : 1 +2023/10/23-05:11:51.423875 ffff85fbf0a0 Compacting 1@1 + 1@2 files +2023/10/23-05:11:51.427454 ffff85fbf0a0 Generated table #24@1: 50 keys, 62030 bytes +2023/10/23-05:11:51.427464 ffff85fbf0a0 Compacted 1@1 + 1@2 files => 62030 bytes +2023/10/23-05:11:51.429307 ffff85fbf0a0 compacted to: files[ 0 0 1 0 0 0 0 ] +2023/10/23-05:11:51.429366 ffff85fbf0a0 Delete type=2 #15 +2023/10/23-05:11:51.429426 ffff85fbf0a0 Delete type=2 #23 +2023/10/23-05:11:51.433938 ffff85fbf0a0 Manual compaction at level-1 from '!items!u5wL9UdxsdjSUgSw' @ 520 : 1 .. '!items!sxzflAlx11OUD2wf' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/data/items/MANIFEST-000020 b/Data/worlds/the-fall-of-plaguestone/data/items/MANIFEST-000020 deleted file mode 100644 index f4ee9c12..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/items/MANIFEST-000020 and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/items/MANIFEST-000025 b/Data/worlds/the-fall-of-plaguestone/data/items/MANIFEST-000025 new file mode 100644 index 00000000..36597516 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/items/MANIFEST-000025 differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/journal/000020.log b/Data/worlds/the-fall-of-plaguestone/data/journal/000020.log deleted file mode 100644 index 13b85c25..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/journal/000020.log and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/journal/000010.ldb b/Data/worlds/the-fall-of-plaguestone/data/journal/000023.ldb similarity index 71% rename from Data/worlds/the-fall-of-plaguestone/data/journal/000010.ldb rename to Data/worlds/the-fall-of-plaguestone/data/journal/000023.ldb index 73904ba7..233a8c5d 100644 Binary files a/Data/worlds/the-fall-of-plaguestone/data/journal/000010.ldb and b/Data/worlds/the-fall-of-plaguestone/data/journal/000023.ldb differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/journal/000025.log b/Data/worlds/the-fall-of-plaguestone/data/journal/000025.log new file mode 100644 index 00000000..e69de29b diff --git a/Data/worlds/the-fall-of-plaguestone/data/journal/CURRENT b/Data/worlds/the-fall-of-plaguestone/data/journal/CURRENT index 43c22f0a..1e21b78c 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/journal/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/data/journal/CURRENT @@ -1 +1 @@ -MANIFEST-000019 +MANIFEST-000024 diff --git a/Data/worlds/the-fall-of-plaguestone/data/journal/LOG b/Data/worlds/the-fall-of-plaguestone/data/journal/LOG index b3a2b0e4..a73a696c 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/journal/LOG +++ b/Data/worlds/the-fall-of-plaguestone/data/journal/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:09.698633 ffff867cf0a0 Recovering log #17 -2023/10/20-07:55:09.703454 ffff867cf0a0 Delete type=0 #17 -2023/10/20-07:55:09.703474 ffff867cf0a0 Delete type=3 #15 +2023/10/23-05:12:16.095583 ffff87fff0a0 Recovering log #21 +2023/10/23-05:12:16.100718 ffff87fff0a0 Delete type=0 #21 +2023/10/23-05:12:16.100738 ffff87fff0a0 Delete type=3 #19 diff --git a/Data/worlds/the-fall-of-plaguestone/data/journal/LOG.old b/Data/worlds/the-fall-of-plaguestone/data/journal/LOG.old index 5cba7477..918f8c74 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/journal/LOG.old +++ b/Data/worlds/the-fall-of-plaguestone/data/journal/LOG.old @@ -1,8 +1,15 @@ -2023/10/20-07:41:10.538083 ffff86fdf0a0 Recovering log #13 -2023/10/20-07:41:10.542961 ffff86fdf0a0 Delete type=0 #13 -2023/10/20-07:41:10.542981 ffff86fdf0a0 Delete type=3 #11 -2023/10/20-07:49:07.417310 ffff85fbf0a0 Level-0 table #18: started -2023/10/20-07:49:07.417324 ffff85fbf0a0 Level-0 table #18: 0 bytes OK -2023/10/20-07:49:07.419318 ffff85fbf0a0 Delete type=0 #16 -2023/10/20-07:49:07.419393 ffff85fbf0a0 Manual compaction at level-0 from '!journal!J2lwLDi7MmEljzVd' @ 72057594037927935 : 1 .. '!journal.pages!SuZq6SKKFo06HTk6.T5SQiWV8tdKzqGuX' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.438724 ffff85fbf0a0 Manual compaction at level-1 from '!journal!J2lwLDi7MmEljzVd' @ 72057594037927935 : 1 .. '!journal.pages!SuZq6SKKFo06HTk6.T5SQiWV8tdKzqGuX' @ 0 : 0; will stop at (end) +2023/10/20-07:55:09.698633 ffff867cf0a0 Recovering log #17 +2023/10/20-07:55:09.703454 ffff867cf0a0 Delete type=0 #17 +2023/10/20-07:55:09.703474 ffff867cf0a0 Delete type=3 #15 +2023/10/23-05:11:51.392731 ffff85fbf0a0 Level-0 table #22: started +2023/10/23-05:11:51.395226 ffff85fbf0a0 Level-0 table #22: 813 bytes OK +2023/10/23-05:11:51.397537 ffff85fbf0a0 Delete type=0 #20 +2023/10/23-05:11:51.397630 ffff85fbf0a0 Manual compaction at level-0 from '!journal!J2lwLDi7MmEljzVd' @ 72057594037927935 : 1 .. '!journal.pages!swKJr3McajLVwJzu.ZruQRmn1HtQ9av5Z' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.429480 ffff85fbf0a0 Manual compaction at level-1 from '!journal!J2lwLDi7MmEljzVd' @ 72057594037927935 : 1 .. '!journal.pages!swKJr3McajLVwJzu.ZruQRmn1HtQ9av5Z' @ 0 : 0; will stop at '!journal.pages!swKJr3McajLVwJzu.ZruQRmn1HtQ9av5Z' @ 49 : 1 +2023/10/23-05:11:51.429486 ffff85fbf0a0 Compacting 1@1 + 1@2 files +2023/10/23-05:11:51.431824 ffff85fbf0a0 Generated table #23@1: 8 keys, 6715 bytes +2023/10/23-05:11:51.431837 ffff85fbf0a0 Compacted 1@1 + 1@2 files => 6715 bytes +2023/10/23-05:11:51.433473 ffff85fbf0a0 compacted to: files[ 0 0 1 0 0 0 0 ] +2023/10/23-05:11:51.433524 ffff85fbf0a0 Delete type=2 #10 +2023/10/23-05:11:51.433571 ffff85fbf0a0 Delete type=2 #22 +2023/10/23-05:11:51.434236 ffff85fbf0a0 Manual compaction at level-1 from '!journal.pages!swKJr3McajLVwJzu.ZruQRmn1HtQ9av5Z' @ 49 : 1 .. '!journal.pages!swKJr3McajLVwJzu.ZruQRmn1HtQ9av5Z' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/data/journal/MANIFEST-000019 b/Data/worlds/the-fall-of-plaguestone/data/journal/MANIFEST-000019 deleted file mode 100644 index 71406332..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/journal/MANIFEST-000019 and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/journal/MANIFEST-000024 b/Data/worlds/the-fall-of-plaguestone/data/journal/MANIFEST-000024 new file mode 100644 index 00000000..c2f68e3d Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/journal/MANIFEST-000024 differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/macros/000015.ldb b/Data/worlds/the-fall-of-plaguestone/data/macros/000015.ldb deleted file mode 100644 index 57b392a0..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/macros/000015.ldb and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/macros/000021.log b/Data/worlds/the-fall-of-plaguestone/data/macros/000021.log deleted file mode 100644 index b8a820bd..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/macros/000021.log and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/macros/000024.ldb b/Data/worlds/the-fall-of-plaguestone/data/macros/000024.ldb new file mode 100644 index 00000000..ae876283 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/macros/000024.ldb differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/macros/000026.log b/Data/worlds/the-fall-of-plaguestone/data/macros/000026.log new file mode 100644 index 00000000..e69de29b diff --git a/Data/worlds/the-fall-of-plaguestone/data/macros/CURRENT b/Data/worlds/the-fall-of-plaguestone/data/macros/CURRENT index f180e911..f6220906 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/macros/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/data/macros/CURRENT @@ -1 +1 @@ -MANIFEST-000020 +MANIFEST-000025 diff --git a/Data/worlds/the-fall-of-plaguestone/data/macros/LOG b/Data/worlds/the-fall-of-plaguestone/data/macros/LOG index 0046f370..6b2614cf 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/macros/LOG +++ b/Data/worlds/the-fall-of-plaguestone/data/macros/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:09.705445 ffff877ef0a0 Recovering log #18 -2023/10/20-07:55:09.710139 ffff877ef0a0 Delete type=3 #16 -2023/10/20-07:55:09.710162 ffff877ef0a0 Delete type=0 #18 +2023/10/23-05:12:16.102937 ffff877ef0a0 Recovering log #22 +2023/10/23-05:12:16.107810 ffff877ef0a0 Delete type=0 #22 +2023/10/23-05:12:16.107830 ffff877ef0a0 Delete type=3 #20 diff --git a/Data/worlds/the-fall-of-plaguestone/data/macros/LOG.old b/Data/worlds/the-fall-of-plaguestone/data/macros/LOG.old index 201da1e0..9f456f63 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/macros/LOG.old +++ b/Data/worlds/the-fall-of-plaguestone/data/macros/LOG.old @@ -1,8 +1,15 @@ -2023/10/20-07:41:10.545115 ffff867cf0a0 Recovering log #13 -2023/10/20-07:41:10.549880 ffff867cf0a0 Delete type=0 #13 -2023/10/20-07:41:10.549900 ffff867cf0a0 Delete type=3 #11 -2023/10/20-07:49:07.438910 ffff85fbf0a0 Level-0 table #19: started -2023/10/20-07:49:07.438929 ffff85fbf0a0 Level-0 table #19: 0 bytes OK -2023/10/20-07:49:07.441220 ffff85fbf0a0 Delete type=0 #17 -2023/10/20-07:49:07.451978 ffff85fbf0a0 Manual compaction at level-0 from '!macros!29l1EAyQi58YCKEX' @ 72057594037927935 : 1 .. '!macros!xMSZbxJxoRSrW8s5' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.452185 ffff85fbf0a0 Manual compaction at level-1 from '!macros!29l1EAyQi58YCKEX' @ 72057594037927935 : 1 .. '!macros!xMSZbxJxoRSrW8s5' @ 0 : 0; will stop at (end) +2023/10/20-07:55:09.705445 ffff877ef0a0 Recovering log #18 +2023/10/20-07:55:09.710139 ffff877ef0a0 Delete type=3 #16 +2023/10/20-07:55:09.710162 ffff877ef0a0 Delete type=0 #18 +2023/10/23-05:11:51.434357 ffff85fbf0a0 Level-0 table #23: started +2023/10/23-05:11:51.436615 ffff85fbf0a0 Level-0 table #23: 828 bytes OK +2023/10/23-05:11:51.438667 ffff85fbf0a0 Delete type=0 #21 +2023/10/23-05:11:51.455909 ffff85fbf0a0 Manual compaction at level-0 from '!macros!29l1EAyQi58YCKEX' @ 72057594037927935 : 1 .. '!macros!xMSZbxJxoRSrW8s5' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.456148 ffff85fbf0a0 Manual compaction at level-1 from '!macros!29l1EAyQi58YCKEX' @ 72057594037927935 : 1 .. '!macros!xMSZbxJxoRSrW8s5' @ 0 : 0; will stop at '!macros!QZ6jS2LpZqAOor0c' @ 73 : 1 +2023/10/23-05:11:51.456152 ffff85fbf0a0 Compacting 1@1 + 1@2 files +2023/10/23-05:11:51.458926 ffff85fbf0a0 Generated table #24@1: 45 keys, 12631 bytes +2023/10/23-05:11:51.458935 ffff85fbf0a0 Compacted 1@1 + 1@2 files => 12631 bytes +2023/10/23-05:11:51.460950 ffff85fbf0a0 compacted to: files[ 0 0 1 0 0 0 0 ] +2023/10/23-05:11:51.461006 ffff85fbf0a0 Delete type=2 #15 +2023/10/23-05:11:51.461046 ffff85fbf0a0 Delete type=2 #23 +2023/10/23-05:11:51.475602 ffff85fbf0a0 Manual compaction at level-1 from '!macros!QZ6jS2LpZqAOor0c' @ 73 : 1 .. '!macros!xMSZbxJxoRSrW8s5' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/data/macros/MANIFEST-000020 b/Data/worlds/the-fall-of-plaguestone/data/macros/MANIFEST-000020 deleted file mode 100644 index 16fef2cb..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/macros/MANIFEST-000020 and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/macros/MANIFEST-000025 b/Data/worlds/the-fall-of-plaguestone/data/macros/MANIFEST-000025 new file mode 100644 index 00000000..cca05fb5 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/macros/MANIFEST-000025 differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/messages/000025.log b/Data/worlds/the-fall-of-plaguestone/data/messages/000025.log deleted file mode 100644 index f4847db8..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/messages/000025.log and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/messages/000017.ldb b/Data/worlds/the-fall-of-plaguestone/data/messages/000028.ldb similarity index 89% rename from Data/worlds/the-fall-of-plaguestone/data/messages/000017.ldb rename to Data/worlds/the-fall-of-plaguestone/data/messages/000028.ldb index 6e1916eb..3f9157ea 100644 Binary files a/Data/worlds/the-fall-of-plaguestone/data/messages/000017.ldb and b/Data/worlds/the-fall-of-plaguestone/data/messages/000028.ldb differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/messages/000018.ldb b/Data/worlds/the-fall-of-plaguestone/data/messages/000029.ldb similarity index 86% rename from Data/worlds/the-fall-of-plaguestone/data/messages/000018.ldb rename to Data/worlds/the-fall-of-plaguestone/data/messages/000029.ldb index 0fd84e0e..b9ad32ba 100644 Binary files a/Data/worlds/the-fall-of-plaguestone/data/messages/000018.ldb and b/Data/worlds/the-fall-of-plaguestone/data/messages/000029.ldb differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/messages/000019.ldb b/Data/worlds/the-fall-of-plaguestone/data/messages/000030.ldb similarity index 68% rename from Data/worlds/the-fall-of-plaguestone/data/messages/000019.ldb rename to Data/worlds/the-fall-of-plaguestone/data/messages/000030.ldb index 45e669d3..8396cfd8 100644 Binary files a/Data/worlds/the-fall-of-plaguestone/data/messages/000019.ldb and b/Data/worlds/the-fall-of-plaguestone/data/messages/000030.ldb differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/messages/000032.log b/Data/worlds/the-fall-of-plaguestone/data/messages/000032.log new file mode 100644 index 00000000..e69de29b diff --git a/Data/worlds/the-fall-of-plaguestone/data/messages/CURRENT b/Data/worlds/the-fall-of-plaguestone/data/messages/CURRENT index 1e21b78c..d95f0273 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/messages/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/data/messages/CURRENT @@ -1 +1 @@ -MANIFEST-000024 +MANIFEST-000031 diff --git a/Data/worlds/the-fall-of-plaguestone/data/messages/LOG b/Data/worlds/the-fall-of-plaguestone/data/messages/LOG index b2b51981..ad59f003 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/messages/LOG +++ b/Data/worlds/the-fall-of-plaguestone/data/messages/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:09.632102 ffff86fdf0a0 Recovering log #22 -2023/10/20-07:55:09.637699 ffff86fdf0a0 Delete type=0 #22 -2023/10/20-07:55:09.637718 ffff86fdf0a0 Delete type=3 #20 +2023/10/23-05:12:16.002255 ffff87fff0a0 Recovering log #26 +2023/10/23-05:12:16.007848 ffff87fff0a0 Delete type=3 #24 +2023/10/23-05:12:16.007880 ffff87fff0a0 Delete type=0 #26 diff --git a/Data/worlds/the-fall-of-plaguestone/data/messages/LOG.old b/Data/worlds/the-fall-of-plaguestone/data/messages/LOG.old index 9d739ae2..31ed3a9e 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/messages/LOG.old +++ b/Data/worlds/the-fall-of-plaguestone/data/messages/LOG.old @@ -1,8 +1,19 @@ -2023/10/20-07:41:10.470329 ffff86fdf0a0 Recovering log #15 -2023/10/20-07:41:10.475425 ffff86fdf0a0 Delete type=3 #13 -2023/10/20-07:41:10.475451 ffff86fdf0a0 Delete type=0 #15 -2023/10/20-07:49:07.387039 ffff85fbf0a0 Level-0 table #23: started -2023/10/20-07:49:07.387055 ffff85fbf0a0 Level-0 table #23: 0 bytes OK -2023/10/20-07:49:07.389310 ffff85fbf0a0 Delete type=0 #21 -2023/10/20-07:49:07.391632 ffff85fbf0a0 Manual compaction at level-0 from '!messages!03btKbJDMB0AvWkC' @ 72057594037927935 : 1 .. '!messages!zxFeJ3Aat4lnl86f' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.408223 ffff85fbf0a0 Manual compaction at level-1 from '!messages!03btKbJDMB0AvWkC' @ 72057594037927935 : 1 .. '!messages!zxFeJ3Aat4lnl86f' @ 0 : 0; will stop at (end) +2023/10/20-07:55:09.632102 ffff86fdf0a0 Recovering log #22 +2023/10/20-07:55:09.637699 ffff86fdf0a0 Delete type=0 #22 +2023/10/20-07:55:09.637718 ffff86fdf0a0 Delete type=3 #20 +2023/10/23-05:11:51.270819 ffff85fbf0a0 Level-0 table #27: started +2023/10/23-05:11:51.275497 ffff85fbf0a0 Level-0 table #27: 145292 bytes OK +2023/10/23-05:11:51.277392 ffff85fbf0a0 Delete type=0 #25 +2023/10/23-05:11:51.279646 ffff85fbf0a0 Manual compaction at level-0 from '!messages!03btKbJDMB0AvWkC' @ 72057594037927935 : 1 .. '!messages!zxFeJ3Aat4lnl86f' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.298632 ffff85fbf0a0 Manual compaction at level-1 from '!messages!03btKbJDMB0AvWkC' @ 72057594037927935 : 1 .. '!messages!zxFeJ3Aat4lnl86f' @ 0 : 0; will stop at '!messages!zMi5amOiGpEhYj2U' @ 2778 : 1 +2023/10/23-05:11:51.298639 ffff85fbf0a0 Compacting 1@1 + 3@2 files +2023/10/23-05:11:51.330906 ffff85fbf0a0 Generated table #28@1: 1233 keys, 2123341 bytes +2023/10/23-05:11:51.364465 ffff85fbf0a0 Generated table #29@1: 1266 keys, 2121767 bytes +2023/10/23-05:11:51.374729 ffff85fbf0a0 Generated table #30@1: 343 keys, 585382 bytes +2023/10/23-05:11:51.374741 ffff85fbf0a0 Compacted 1@1 + 3@2 files => 4830490 bytes +2023/10/23-05:11:51.376417 ffff85fbf0a0 compacted to: files[ 0 0 3 0 0 0 0 ] +2023/10/23-05:11:51.376514 ffff85fbf0a0 Delete type=2 #27 +2023/10/23-05:11:51.376691 ffff85fbf0a0 Delete type=2 #17 +2023/10/23-05:11:51.377160 ffff85fbf0a0 Delete type=2 #18 +2023/10/23-05:11:51.377529 ffff85fbf0a0 Delete type=2 #19 +2023/10/23-05:11:51.378125 ffff85fbf0a0 Manual compaction at level-1 from '!messages!zMi5amOiGpEhYj2U' @ 2778 : 1 .. '!messages!zxFeJ3Aat4lnl86f' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/data/messages/MANIFEST-000024 b/Data/worlds/the-fall-of-plaguestone/data/messages/MANIFEST-000024 deleted file mode 100644 index 25b994b7..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/messages/MANIFEST-000024 and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/messages/MANIFEST-000031 b/Data/worlds/the-fall-of-plaguestone/data/messages/MANIFEST-000031 new file mode 100644 index 00000000..de5166ed Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/messages/MANIFEST-000031 differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/playlists/000023.log b/Data/worlds/the-fall-of-plaguestone/data/playlists/000023.log new file mode 100644 index 00000000..e69de29b diff --git a/Data/worlds/the-fall-of-plaguestone/data/playlists/CURRENT b/Data/worlds/the-fall-of-plaguestone/data/playlists/CURRENT index e417a51c..5af92b2b 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/playlists/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/data/playlists/CURRENT @@ -1 +1 @@ -MANIFEST-000018 +MANIFEST-000022 diff --git a/Data/worlds/the-fall-of-plaguestone/data/playlists/LOG b/Data/worlds/the-fall-of-plaguestone/data/playlists/LOG index bdfda1b0..e773bdee 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/playlists/LOG +++ b/Data/worlds/the-fall-of-plaguestone/data/playlists/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:09.711862 ffff867cf0a0 Recovering log #16 -2023/10/20-07:55:09.716950 ffff867cf0a0 Delete type=3 #14 -2023/10/20-07:55:09.716973 ffff867cf0a0 Delete type=0 #16 +2023/10/23-05:12:16.109736 ffff87fff0a0 Recovering log #20 +2023/10/23-05:12:16.114493 ffff87fff0a0 Delete type=0 #20 +2023/10/23-05:12:16.114512 ffff87fff0a0 Delete type=3 #18 diff --git a/Data/worlds/the-fall-of-plaguestone/data/playlists/LOG.old b/Data/worlds/the-fall-of-plaguestone/data/playlists/LOG.old index b7aa9570..25112e22 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/playlists/LOG.old +++ b/Data/worlds/the-fall-of-plaguestone/data/playlists/LOG.old @@ -1,7 +1,7 @@ -2023/10/20-07:41:10.551766 ffff86fdf0a0 Recovering log #12 -2023/10/20-07:41:10.556761 ffff86fdf0a0 Delete type=0 #12 -2023/10/20-07:41:10.556815 ffff86fdf0a0 Delete type=3 #10 -2023/10/20-07:49:07.441259 ffff85fbf0a0 Level-0 table #17: started -2023/10/20-07:49:07.441273 ffff85fbf0a0 Level-0 table #17: 0 bytes OK -2023/10/20-07:49:07.443171 ffff85fbf0a0 Delete type=0 #15 -2023/10/20-07:49:07.451993 ffff85fbf0a0 Manual compaction at level-0 from 'undefined' @ 72057594037927935 : 1 .. 'undefined' @ 0 : 0; will stop at (end) +2023/10/20-07:55:09.711862 ffff867cf0a0 Recovering log #16 +2023/10/20-07:55:09.716950 ffff867cf0a0 Delete type=3 #14 +2023/10/20-07:55:09.716973 ffff867cf0a0 Delete type=0 #16 +2023/10/23-05:11:51.438717 ffff85fbf0a0 Level-0 table #21: started +2023/10/23-05:11:51.438735 ffff85fbf0a0 Level-0 table #21: 0 bytes OK +2023/10/23-05:11:51.441124 ffff85fbf0a0 Delete type=0 #19 +2023/10/23-05:11:51.455926 ffff85fbf0a0 Manual compaction at level-0 from 'undefined' @ 72057594037927935 : 1 .. 'undefined' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/data/playlists/MANIFEST-000018 b/Data/worlds/the-fall-of-plaguestone/data/playlists/MANIFEST-000018 deleted file mode 100644 index 1f89f0da..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/playlists/MANIFEST-000018 and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/playlists/MANIFEST-000022 b/Data/worlds/the-fall-of-plaguestone/data/playlists/MANIFEST-000022 new file mode 100644 index 00000000..405e4abb Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/playlists/MANIFEST-000022 differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/scenes/000032.log b/Data/worlds/the-fall-of-plaguestone/data/scenes/000032.log deleted file mode 100644 index e1bbfab1..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/scenes/000032.log and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/scenes/000034.ldb b/Data/worlds/the-fall-of-plaguestone/data/scenes/000034.ldb deleted file mode 100644 index 17e3277a..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/scenes/000034.ldb and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/scenes/000037.ldb b/Data/worlds/the-fall-of-plaguestone/data/scenes/000037.ldb new file mode 100644 index 00000000..752d8c72 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/scenes/000037.ldb differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/scenes/000039.log b/Data/worlds/the-fall-of-plaguestone/data/scenes/000039.log new file mode 100644 index 00000000..8bfd05c7 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/scenes/000039.log differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/scenes/CURRENT b/Data/worlds/the-fall-of-plaguestone/data/scenes/CURRENT index caa721af..59611b0f 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/scenes/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/data/scenes/CURRENT @@ -1 +1 @@ -MANIFEST-000030 +MANIFEST-000038 diff --git a/Data/worlds/the-fall-of-plaguestone/data/scenes/LOG b/Data/worlds/the-fall-of-plaguestone/data/scenes/LOG index c120a994..ef6458b0 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/scenes/LOG +++ b/Data/worlds/the-fall-of-plaguestone/data/scenes/LOG @@ -1,12 +1,3 @@ -2023/10/20-07:55:09.726376 ffff867cf0a0 Recovering log #27 -2023/10/20-07:55:09.731978 ffff867cf0a0 Delete type=3 #25 -2023/10/20-07:55:09.732001 ffff867cf0a0 Delete type=0 #27 -2023/10/21-22:19:19.335528 ffff85fbf0a0 Level-0 table #33: started -2023/10/21-22:19:19.378129 ffff85fbf0a0 Level-0 table #33: 3624943 bytes OK -2023/10/21-22:19:19.380072 ffff85fbf0a0 Delete type=0 #31 -2023/10/22-19:34:48.842409 ffff85fbf0a0 Compacting 1@1 + 1@2 files -2023/10/22-19:34:48.867974 ffff85fbf0a0 Generated table #34@1: 1356 keys, 320014 bytes -2023/10/22-19:34:48.867989 ffff85fbf0a0 Compacted 1@1 + 1@2 files => 320014 bytes -2023/10/22-19:34:48.869702 ffff85fbf0a0 compacted to: files[ 0 0 1 0 0 0 0 ] -2023/10/22-19:34:48.869813 ffff85fbf0a0 Delete type=2 #29 -2023/10/22-19:34:48.870072 ffff85fbf0a0 Delete type=2 #33 +2023/10/23-05:12:16.124536 ffff87fff0a0 Recovering log #35 +2023/10/23-05:12:16.129969 ffff87fff0a0 Delete type=3 #30 +2023/10/23-05:12:16.129992 ffff87fff0a0 Delete type=0 #35 diff --git a/Data/worlds/the-fall-of-plaguestone/data/scenes/LOG.old b/Data/worlds/the-fall-of-plaguestone/data/scenes/LOG.old index db791ebd..01b09c7a 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/scenes/LOG.old +++ b/Data/worlds/the-fall-of-plaguestone/data/scenes/LOG.old @@ -1,15 +1,24 @@ -2023/10/20-07:41:10.566874 ffff86fdf0a0 Recovering log #22 -2023/10/20-07:41:10.572480 ffff86fdf0a0 Delete type=0 #22 -2023/10/20-07:41:10.572502 ffff86fdf0a0 Delete type=3 #11 -2023/10/20-07:49:07.445208 ffff85fbf0a0 Level-0 table #28: started -2023/10/20-07:49:07.450040 ffff85fbf0a0 Level-0 table #28: 318323 bytes OK -2023/10/20-07:49:07.451838 ffff85fbf0a0 Delete type=0 #26 -2023/10/20-07:49:07.452174 ffff85fbf0a0 Manual compaction at level-0 from '!scenes!1XLyv9WINaQhsN8t' @ 72057594037927935 : 1 .. '!scenes.walls!uXsZNSvjADpuoXnj.zquvhm4c4L3e6YRS' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.456444 ffff85fbf0a0 Manual compaction at level-1 from '!scenes!1XLyv9WINaQhsN8t' @ 72057594037927935 : 1 .. '!scenes.walls!uXsZNSvjADpuoXnj.zquvhm4c4L3e6YRS' @ 0 : 0; will stop at '!scenes.walls!nMt3xldg0P4TGh3y.Wo1MeuPvvzFk4cuE' @ 9082 : 1 -2023/10/20-07:49:07.456455 ffff85fbf0a0 Compacting 1@1 + 1@2 files -2023/10/20-07:49:07.463149 ffff85fbf0a0 Generated table #29@1: 1291 keys, 277510 bytes -2023/10/20-07:49:07.463160 ffff85fbf0a0 Compacted 1@1 + 1@2 files => 277510 bytes -2023/10/20-07:49:07.464850 ffff85fbf0a0 compacted to: files[ 0 0 1 0 0 0 0 ] -2023/10/20-07:49:07.464946 ffff85fbf0a0 Delete type=2 #24 -2023/10/20-07:49:07.465067 ffff85fbf0a0 Delete type=2 #28 -2023/10/20-07:49:07.469021 ffff85fbf0a0 Manual compaction at level-1 from '!scenes.walls!nMt3xldg0P4TGh3y.Wo1MeuPvvzFk4cuE' @ 9082 : 1 .. '!scenes.walls!uXsZNSvjADpuoXnj.zquvhm4c4L3e6YRS' @ 0 : 0; will stop at (end) +2023/10/20-07:55:09.726376 ffff867cf0a0 Recovering log #27 +2023/10/20-07:55:09.731978 ffff867cf0a0 Delete type=3 #25 +2023/10/20-07:55:09.732001 ffff867cf0a0 Delete type=0 #27 +2023/10/21-22:19:19.335528 ffff85fbf0a0 Level-0 table #33: started +2023/10/21-22:19:19.378129 ffff85fbf0a0 Level-0 table #33: 3624943 bytes OK +2023/10/21-22:19:19.380072 ffff85fbf0a0 Delete type=0 #31 +2023/10/22-19:34:48.842409 ffff85fbf0a0 Compacting 1@1 + 1@2 files +2023/10/22-19:34:48.867974 ffff85fbf0a0 Generated table #34@1: 1356 keys, 320014 bytes +2023/10/22-19:34:48.867989 ffff85fbf0a0 Compacted 1@1 + 1@2 files => 320014 bytes +2023/10/22-19:34:48.869702 ffff85fbf0a0 compacted to: files[ 0 0 1 0 0 0 0 ] +2023/10/22-19:34:48.869813 ffff85fbf0a0 Delete type=2 #29 +2023/10/22-19:34:48.870072 ffff85fbf0a0 Delete type=2 #33 +2023/10/23-05:11:51.443420 ffff85fbf0a0 Level-0 table #36: started +2023/10/23-05:11:51.453693 ffff85fbf0a0 Level-0 table #36: 972303 bytes OK +2023/10/23-05:11:51.455654 ffff85fbf0a0 Delete type=0 #32 +2023/10/23-05:11:51.456134 ffff85fbf0a0 Manual compaction at level-0 from '!scenes!1XLyv9WINaQhsN8t' @ 72057594037927935 : 1 .. '!scenes.walls!uXsZNSvjADpuoXnj.zquvhm4c4L3e6YRS' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.465416 ffff85fbf0a0 Manual compaction at level-1 from '!scenes!1XLyv9WINaQhsN8t' @ 72057594037927935 : 1 .. '!scenes.walls!uXsZNSvjADpuoXnj.zquvhm4c4L3e6YRS' @ 0 : 0; will stop at '!scenes.walls!nMt3xldg0P4TGh3y.zb4tBvbGdPbt1t0T' @ 10449 : 1 +2023/10/23-05:11:51.465425 ffff85fbf0a0 Compacting 1@1 + 1@2 files +2023/10/23-05:11:51.472891 ffff85fbf0a0 Generated table #37@1: 1364 keys, 327804 bytes +2023/10/23-05:11:51.472902 ffff85fbf0a0 Compacted 1@1 + 1@2 files => 327804 bytes +2023/10/23-05:11:51.474803 ffff85fbf0a0 compacted to: files[ 0 0 1 0 0 0 0 ] +2023/10/23-05:11:51.474932 ffff85fbf0a0 Delete type=2 #34 +2023/10/23-05:11:51.475442 ffff85fbf0a0 Delete type=2 #36 +2023/10/23-05:11:51.480748 ffff85fbf0a0 Manual compaction at level-1 from '!scenes.walls!nMt3xldg0P4TGh3y.zb4tBvbGdPbt1t0T' @ 10449 : 1 .. '!scenes.walls!uXsZNSvjADpuoXnj.zquvhm4c4L3e6YRS' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/data/scenes/MANIFEST-000030 b/Data/worlds/the-fall-of-plaguestone/data/scenes/MANIFEST-000030 deleted file mode 100644 index 48973506..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/scenes/MANIFEST-000030 and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/scenes/MANIFEST-000038 b/Data/worlds/the-fall-of-plaguestone/data/scenes/MANIFEST-000038 new file mode 100644 index 00000000..94d292f1 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/scenes/MANIFEST-000038 differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/settings/000020.ldb b/Data/worlds/the-fall-of-plaguestone/data/settings/000020.ldb deleted file mode 100644 index 11cbd6bc..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/settings/000020.ldb and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/settings/000022.log b/Data/worlds/the-fall-of-plaguestone/data/settings/000022.log deleted file mode 100644 index b234cc98..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/settings/000022.log and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/settings/000025.ldb b/Data/worlds/the-fall-of-plaguestone/data/settings/000025.ldb new file mode 100644 index 00000000..54a97e22 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/settings/000025.ldb differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/settings/000027.log b/Data/worlds/the-fall-of-plaguestone/data/settings/000027.log new file mode 100644 index 00000000..0b14f890 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/settings/000027.log differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/settings/CURRENT b/Data/worlds/the-fall-of-plaguestone/data/settings/CURRENT index e60e1543..8b152150 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/settings/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/data/settings/CURRENT @@ -1 +1 @@ -MANIFEST-000021 +MANIFEST-000026 diff --git a/Data/worlds/the-fall-of-plaguestone/data/settings/LOG b/Data/worlds/the-fall-of-plaguestone/data/settings/LOG index c9e464b7..1e82ba65 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/settings/LOG +++ b/Data/worlds/the-fall-of-plaguestone/data/settings/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:09.746956 ffff87fff0a0 Recovering log #18 -2023/10/20-07:55:09.752874 ffff87fff0a0 Delete type=3 #16 -2023/10/20-07:55:09.752898 ffff87fff0a0 Delete type=0 #18 +2023/10/23-05:12:16.144850 ffff86fdf0a0 Recovering log #23 +2023/10/23-05:12:16.150049 ffff86fdf0a0 Delete type=0 #23 +2023/10/23-05:12:16.150071 ffff86fdf0a0 Delete type=3 #21 diff --git a/Data/worlds/the-fall-of-plaguestone/data/settings/LOG.old b/Data/worlds/the-fall-of-plaguestone/data/settings/LOG.old index c52599e3..0b740faa 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/settings/LOG.old +++ b/Data/worlds/the-fall-of-plaguestone/data/settings/LOG.old @@ -1,15 +1,15 @@ -2023/10/20-07:41:10.588216 ffff877ef0a0 Recovering log #13 -2023/10/20-07:41:10.593777 ffff877ef0a0 Delete type=0 #13 -2023/10/20-07:41:10.593799 ffff877ef0a0 Delete type=3 #11 -2023/10/20-07:49:07.452275 ffff85fbf0a0 Level-0 table #19: started -2023/10/20-07:49:07.454337 ffff85fbf0a0 Level-0 table #19: 5011 bytes OK -2023/10/20-07:49:07.455994 ffff85fbf0a0 Delete type=0 #17 -2023/10/20-07:49:07.467327 ffff85fbf0a0 Manual compaction at level-0 from '!settings!19RutMPqnS84jhcn' @ 72057594037927935 : 1 .. '!settings!zU0EeWmAvFtbs8Te' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.469228 ffff85fbf0a0 Manual compaction at level-1 from '!settings!19RutMPqnS84jhcn' @ 72057594037927935 : 1 .. '!settings!zU0EeWmAvFtbs8Te' @ 0 : 0; will stop at '!settings!j5FCUKj7y48FhuCN' @ 109 : 1 -2023/10/20-07:49:07.469232 ffff85fbf0a0 Compacting 1@1 + 1@2 files -2023/10/20-07:49:07.471599 ffff85fbf0a0 Generated table #20@1: 59 keys, 18842 bytes -2023/10/20-07:49:07.471611 ffff85fbf0a0 Compacted 1@1 + 1@2 files => 18842 bytes -2023/10/20-07:49:07.473097 ffff85fbf0a0 compacted to: files[ 0 0 1 0 0 0 0 ] -2023/10/20-07:49:07.473152 ffff85fbf0a0 Delete type=2 #15 -2023/10/20-07:49:07.473197 ffff85fbf0a0 Delete type=2 #19 -2023/10/20-07:49:07.475585 ffff85fbf0a0 Manual compaction at level-1 from '!settings!j5FCUKj7y48FhuCN' @ 109 : 1 .. '!settings!zU0EeWmAvFtbs8Te' @ 0 : 0; will stop at (end) +2023/10/20-07:55:09.746956 ffff87fff0a0 Recovering log #18 +2023/10/20-07:55:09.752874 ffff87fff0a0 Delete type=3 #16 +2023/10/20-07:55:09.752898 ffff87fff0a0 Delete type=0 #18 +2023/10/23-05:11:51.461079 ffff85fbf0a0 Level-0 table #24: started +2023/10/23-05:11:51.463559 ffff85fbf0a0 Level-0 table #24: 16196 bytes OK +2023/10/23-05:11:51.465182 ffff85fbf0a0 Delete type=0 #22 +2023/10/23-05:11:51.476036 ffff85fbf0a0 Manual compaction at level-0 from '!settings!19RutMPqnS84jhcn' @ 72057594037927935 : 1 .. '!settings!zU0EeWmAvFtbs8Te' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.483329 ffff85fbf0a0 Manual compaction at level-1 from '!settings!19RutMPqnS84jhcn' @ 72057594037927935 : 1 .. '!settings!zU0EeWmAvFtbs8Te' @ 0 : 0; will stop at '!settings!qf7t8ZyqmGX9dH5O' @ 120 : 1 +2023/10/23-05:11:51.483335 ffff85fbf0a0 Compacting 1@1 + 1@2 files +2023/10/23-05:11:51.486197 ffff85fbf0a0 Generated table #25@1: 74 keys, 22422 bytes +2023/10/23-05:11:51.486207 ffff85fbf0a0 Compacted 1@1 + 1@2 files => 22422 bytes +2023/10/23-05:11:51.487965 ffff85fbf0a0 compacted to: files[ 0 0 1 0 0 0 0 ] +2023/10/23-05:11:51.488016 ffff85fbf0a0 Delete type=2 #24 +2023/10/23-05:11:51.488058 ffff85fbf0a0 Delete type=2 #20 +2023/10/23-05:11:51.490425 ffff85fbf0a0 Manual compaction at level-1 from '!settings!qf7t8ZyqmGX9dH5O' @ 120 : 1 .. '!settings!zU0EeWmAvFtbs8Te' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/data/settings/MANIFEST-000021 b/Data/worlds/the-fall-of-plaguestone/data/settings/MANIFEST-000021 deleted file mode 100644 index dc6a193a..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/settings/MANIFEST-000021 and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/settings/MANIFEST-000026 b/Data/worlds/the-fall-of-plaguestone/data/settings/MANIFEST-000026 new file mode 100644 index 00000000..f3d2c82e Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/settings/MANIFEST-000026 differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/tables/000023.log b/Data/worlds/the-fall-of-plaguestone/data/tables/000023.log new file mode 100644 index 00000000..e69de29b diff --git a/Data/worlds/the-fall-of-plaguestone/data/tables/CURRENT b/Data/worlds/the-fall-of-plaguestone/data/tables/CURRENT index e417a51c..5af92b2b 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/tables/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/data/tables/CURRENT @@ -1 +1 @@ -MANIFEST-000018 +MANIFEST-000022 diff --git a/Data/worlds/the-fall-of-plaguestone/data/tables/LOG b/Data/worlds/the-fall-of-plaguestone/data/tables/LOG index eebd21f7..a249c3fb 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/tables/LOG +++ b/Data/worlds/the-fall-of-plaguestone/data/tables/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:09.718759 ffff877ef0a0 Recovering log #16 -2023/10/20-07:55:09.723878 ffff877ef0a0 Delete type=3 #14 -2023/10/20-07:55:09.723900 ffff877ef0a0 Delete type=0 #16 +2023/10/23-05:12:16.116494 ffff877ef0a0 Recovering log #20 +2023/10/23-05:12:16.121668 ffff877ef0a0 Delete type=0 #20 +2023/10/23-05:12:16.121689 ffff877ef0a0 Delete type=3 #18 diff --git a/Data/worlds/the-fall-of-plaguestone/data/tables/LOG.old b/Data/worlds/the-fall-of-plaguestone/data/tables/LOG.old index a34571c6..9bace543 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/tables/LOG.old +++ b/Data/worlds/the-fall-of-plaguestone/data/tables/LOG.old @@ -1,8 +1,8 @@ -2023/10/20-07:41:10.558776 ffff867cf0a0 Recovering log #12 -2023/10/20-07:41:10.564142 ffff867cf0a0 Delete type=0 #12 -2023/10/20-07:41:10.564163 ffff867cf0a0 Delete type=3 #10 -2023/10/20-07:49:07.443210 ffff85fbf0a0 Level-0 table #17: started -2023/10/20-07:49:07.443224 ffff85fbf0a0 Level-0 table #17: 0 bytes OK -2023/10/20-07:49:07.445169 ffff85fbf0a0 Delete type=0 #15 -2023/10/20-07:49:07.452155 ffff85fbf0a0 Manual compaction at level-0 from '!tables!CvNQ7CO1j3iX2F6H' @ 72057594037927935 : 1 .. '!tables.results!stX6qaw7RhF43EVi.xlKuEatC1y15q34j' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.456052 ffff85fbf0a0 Manual compaction at level-1 from '!tables!CvNQ7CO1j3iX2F6H' @ 72057594037927935 : 1 .. '!tables.results!stX6qaw7RhF43EVi.xlKuEatC1y15q34j' @ 0 : 0; will stop at (end) +2023/10/20-07:55:09.718759 ffff877ef0a0 Recovering log #16 +2023/10/20-07:55:09.723878 ffff877ef0a0 Delete type=3 #14 +2023/10/20-07:55:09.723900 ffff877ef0a0 Delete type=0 #16 +2023/10/23-05:11:51.441163 ffff85fbf0a0 Level-0 table #21: started +2023/10/23-05:11:51.441179 ffff85fbf0a0 Level-0 table #21: 0 bytes OK +2023/10/23-05:11:51.443381 ffff85fbf0a0 Delete type=0 #19 +2023/10/23-05:11:51.456111 ffff85fbf0a0 Manual compaction at level-0 from '!tables!CvNQ7CO1j3iX2F6H' @ 72057594037927935 : 1 .. '!tables.results!stX6qaw7RhF43EVi.xlKuEatC1y15q34j' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.465266 ffff85fbf0a0 Manual compaction at level-1 from '!tables!CvNQ7CO1j3iX2F6H' @ 72057594037927935 : 1 .. '!tables.results!stX6qaw7RhF43EVi.xlKuEatC1y15q34j' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/data/tables/MANIFEST-000018 b/Data/worlds/the-fall-of-plaguestone/data/tables/MANIFEST-000022 similarity index 87% rename from Data/worlds/the-fall-of-plaguestone/data/tables/MANIFEST-000018 rename to Data/worlds/the-fall-of-plaguestone/data/tables/MANIFEST-000022 index 8bbe100d..cd6df971 100644 Binary files a/Data/worlds/the-fall-of-plaguestone/data/tables/MANIFEST-000018 and b/Data/worlds/the-fall-of-plaguestone/data/tables/MANIFEST-000022 differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/users/000021.log b/Data/worlds/the-fall-of-plaguestone/data/users/000021.log deleted file mode 100644 index 0598d569..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/users/000021.log and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/users/000015.ldb b/Data/worlds/the-fall-of-plaguestone/data/users/000024.ldb similarity index 78% rename from Data/worlds/the-fall-of-plaguestone/data/users/000015.ldb rename to Data/worlds/the-fall-of-plaguestone/data/users/000024.ldb index a174e969..7b44475a 100644 Binary files a/Data/worlds/the-fall-of-plaguestone/data/users/000015.ldb and b/Data/worlds/the-fall-of-plaguestone/data/users/000024.ldb differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/users/000026.log b/Data/worlds/the-fall-of-plaguestone/data/users/000026.log new file mode 100644 index 00000000..e69de29b diff --git a/Data/worlds/the-fall-of-plaguestone/data/users/CURRENT b/Data/worlds/the-fall-of-plaguestone/data/users/CURRENT index f180e911..f6220906 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/users/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/data/users/CURRENT @@ -1 +1 @@ -MANIFEST-000020 +MANIFEST-000025 diff --git a/Data/worlds/the-fall-of-plaguestone/data/users/LOG b/Data/worlds/the-fall-of-plaguestone/data/users/LOG index 081d0434..ed25d937 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/users/LOG +++ b/Data/worlds/the-fall-of-plaguestone/data/users/LOG @@ -1,3 +1,3 @@ -2023/10/20-07:55:09.754680 ffff86fdf0a0 Recovering log #18 -2023/10/20-07:55:09.759965 ffff86fdf0a0 Delete type=3 #16 -2023/10/20-07:55:09.759988 ffff86fdf0a0 Delete type=0 #18 +2023/10/23-05:12:16.152182 ffff867cf0a0 Recovering log #22 +2023/10/23-05:12:16.157007 ffff867cf0a0 Delete type=0 #22 +2023/10/23-05:12:16.157027 ffff867cf0a0 Delete type=3 #20 diff --git a/Data/worlds/the-fall-of-plaguestone/data/users/LOG.old b/Data/worlds/the-fall-of-plaguestone/data/users/LOG.old index c56acff7..17b2be5a 100644 --- a/Data/worlds/the-fall-of-plaguestone/data/users/LOG.old +++ b/Data/worlds/the-fall-of-plaguestone/data/users/LOG.old @@ -1,8 +1,15 @@ -2023/10/20-07:41:10.595774 ffff87fff0a0 Recovering log #13 -2023/10/20-07:41:10.601162 ffff87fff0a0 Delete type=0 #13 -2023/10/20-07:41:10.601182 ffff87fff0a0 Delete type=3 #11 -2023/10/20-07:49:07.465135 ffff85fbf0a0 Level-0 table #19: started -2023/10/20-07:49:07.465151 ffff85fbf0a0 Level-0 table #19: 0 bytes OK -2023/10/20-07:49:07.467287 ffff85fbf0a0 Delete type=0 #17 -2023/10/20-07:49:07.469205 ffff85fbf0a0 Manual compaction at level-0 from '!users!F6OOcfsURwMn6MBE' @ 72057594037927935 : 1 .. '!users!y7YPsIEiZsHrU0id' @ 0 : 0; will stop at (end) -2023/10/20-07:49:07.475425 ffff85fbf0a0 Manual compaction at level-1 from '!users!F6OOcfsURwMn6MBE' @ 72057594037927935 : 1 .. '!users!y7YPsIEiZsHrU0id' @ 0 : 0; will stop at (end) +2023/10/20-07:55:09.754680 ffff86fdf0a0 Recovering log #18 +2023/10/20-07:55:09.759965 ffff86fdf0a0 Delete type=3 #16 +2023/10/20-07:55:09.759988 ffff86fdf0a0 Delete type=0 #18 +2023/10/23-05:11:51.476054 ffff85fbf0a0 Level-0 table #23: started +2023/10/23-05:11:51.478544 ffff85fbf0a0 Level-0 table #23: 1073 bytes OK +2023/10/23-05:11:51.480697 ffff85fbf0a0 Delete type=0 #21 +2023/10/23-05:11:51.488100 ffff85fbf0a0 Manual compaction at level-0 from '!users!F6OOcfsURwMn6MBE' @ 72057594037927935 : 1 .. '!users!y7YPsIEiZsHrU0id' @ 0 : 0; will stop at (end) +2023/10/23-05:11:51.490638 ffff85fbf0a0 Manual compaction at level-1 from '!users!F6OOcfsURwMn6MBE' @ 72057594037927935 : 1 .. '!users!y7YPsIEiZsHrU0id' @ 0 : 0; will stop at '!users!ss0rDetCRdrD9OsR' @ 19 : 1 +2023/10/23-05:11:51.490648 ffff85fbf0a0 Compacting 1@1 + 1@2 files +2023/10/23-05:11:51.492849 ffff85fbf0a0 Generated table #24@1: 8 keys, 5724 bytes +2023/10/23-05:11:51.492859 ffff85fbf0a0 Compacted 1@1 + 1@2 files => 5724 bytes +2023/10/23-05:11:51.494781 ffff85fbf0a0 compacted to: files[ 0 0 1 0 0 0 0 ] +2023/10/23-05:11:51.494850 ffff85fbf0a0 Delete type=2 #15 +2023/10/23-05:11:51.494891 ffff85fbf0a0 Delete type=2 #23 +2023/10/23-05:11:51.499428 ffff85fbf0a0 Manual compaction at level-1 from '!users!ss0rDetCRdrD9OsR' @ 19 : 1 .. '!users!y7YPsIEiZsHrU0id' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/data/users/MANIFEST-000020 b/Data/worlds/the-fall-of-plaguestone/data/users/MANIFEST-000020 deleted file mode 100644 index 2dd8b964..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/data/users/MANIFEST-000020 and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/data/users/MANIFEST-000025 b/Data/worlds/the-fall-of-plaguestone/data/users/MANIFEST-000025 new file mode 100644 index 00000000..396ef1f2 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/data/users/MANIFEST-000025 differ diff --git a/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/000003.log b/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/000003.log deleted file mode 100644 index f0b2175c..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/000003.log and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/000005.ldb b/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/000005.ldb new file mode 100644 index 00000000..bcf8a3f1 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/000005.ldb differ diff --git a/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/000007.log b/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/000007.log new file mode 100644 index 00000000..e69de29b diff --git a/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/CURRENT b/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/CURRENT index 1a848522..f7753e22 100644 --- a/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/CURRENT +++ b/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/CURRENT @@ -1 +1 @@ -MANIFEST-000002 +MANIFEST-000006 diff --git a/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/LOG b/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/LOG index 0bbe81d2..963dc233 100644 --- a/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/LOG +++ b/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/LOG @@ -1 +1,3 @@ -2023/10/22-19:40:49.835824 ffff877ef0a0 Delete type=3 #1 +2023/10/23-05:12:16.173436 ffff877ef0a0 Recovering log #4 +2023/10/23-05:12:16.178197 ffff877ef0a0 Delete type=3 #2 +2023/10/23-05:12:16.178222 ffff877ef0a0 Delete type=0 #4 diff --git a/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/LOG.old b/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/LOG.old new file mode 100644 index 00000000..1f0339bb --- /dev/null +++ b/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/LOG.old @@ -0,0 +1,5 @@ +2023/10/22-19:40:49.835824 ffff877ef0a0 Delete type=3 #1 +2023/10/23-05:11:51.693100 ffff85fbf0a0 Level-0 table #5: started +2023/10/23-05:11:51.698443 ffff85fbf0a0 Level-0 table #5: 5343 bytes OK +2023/10/23-05:11:51.700245 ffff85fbf0a0 Delete type=0 #3 +2023/10/23-05:11:51.703264 ffff85fbf0a0 Manual compaction at level-0 from '!items!aYrq9AUaMq6cslH6' @ 72057594037927935 : 1 .. '!items!aYrq9AUaMq6cslH6' @ 0 : 0; will stop at (end) diff --git a/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/MANIFEST-000002 b/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/MANIFEST-000002 deleted file mode 100644 index bbbc5856..00000000 Binary files a/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/MANIFEST-000002 and /dev/null differ diff --git a/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/MANIFEST-000006 b/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/MANIFEST-000006 new file mode 100644 index 00000000..3dbf7a43 Binary files /dev/null and b/Data/worlds/the-fall-of-plaguestone/packs/new-familiar-abilities/MANIFEST-000006 differ diff --git a/Data/worlds/the-fall-of-plaguestone/world.json b/Data/worlds/the-fall-of-plaguestone/world.json index 1adfcef0..a1591707 100644 --- a/Data/worlds/the-fall-of-plaguestone/world.json +++ b/Data/worlds/the-fall-of-plaguestone/world.json @@ -8,11 +8,11 @@ "minimum": "11", "verified": "11.313" }, - "systemVersion": "5.7.2", + "systemVersion": "5.7.3", "nextSession": "2023-03-12T22:00:00.000Z", "description": "

        A group of new adventurers traveling through the village of Etran's Folly—also known as Plaguestone—must come together to solve the murder of a friend. What starts as a simple investigation quickly turns sinister with the discovery of forbidden alchemy, mutant animals, and a nearby forest rotting away due to a mysterious blight. It becomes clear that if these heroes don't intervene to stop whatever evil is brewing, the fall of Plaguestone is all but certain!

        The Fall of Plaguestone is the first standalone adventure for Pathfinder Second Edition, designed for 1st-level characters. It tells the story of how a group of strangers band together to form a group of adventurers while saving the town of Etran's Folly from a terrifying fate, serving as a perfect introduction to a new Pathfinder campaign!

        ", - "lastPlayed": "Fri Oct 20 2023 07:55:09 GMT+0000 (Coordinated Universal Time)", - "playtime": 889566, + "lastPlayed": "Mon Oct 23 2023 05:12:16 GMT+0000 (Coordinated Universal Time)", + "playtime": 1138961, "safeMode": false, "packs": [ { @@ -25,8 +25,7 @@ "PLAYER": "OBSERVER", "ASSISTANT": "OWNER" }, - "flags": {}, - "package": "world" + "flags": {} } ] } \ No newline at end of file