This file is indexed.

/usr/share/perl5/Dancer2/Core/App.pm is in libdancer2-perl 0.204002+dfsg-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
# ABSTRACT: encapsulation of Dancer2 packages
package Dancer2::Core::App;
$Dancer2::Core::App::VERSION = '0.204002';
use Moo;
use Carp               qw<croak carp>;
use Scalar::Util       'blessed';
use Module::Runtime    'is_module_name';
use Return::MultiLevel ();
use Safe::Isa;
use Sub::Quote;
use File::Spec;
use Module::Runtime    'use_module';
use List::Util         ();

use Plack::App::File;
use Plack::Middleware::FixMissingBodyInRedirect;
use Plack::Middleware::Head;
use Plack::Middleware::Conditional;
use Plack::Middleware::ConditionalGET;

use Dancer2::FileUtils 'path';
use Dancer2::Core;
use Dancer2::Core::Cookie;
use Dancer2::Core::Error;
use Dancer2::Core::Types;
use Dancer2::Core::Route;
use Dancer2::Core::Hook;
use Dancer2::Core::Request;
use Dancer2::Core::Factory;

use Dancer2::Handler::File;

our $EVAL_SHIM = sub {
    my $code = shift;
    $code->(@_);
};


# we have hooks here
with qw<
    Dancer2::Core::Role::Hookable
    Dancer2::Core::Role::ConfigReader
>;

sub supported_engines { [ qw<logger serializer session template> ] }

sub with_plugins {
    my ( $self, @plugins ) = @_;
    return map $self->_with_plugin($_), @plugins;

}

sub _with_plugin {
    my( $self, $plugin ) = @_;

    if ( ref $plugin ) {
        # passing the plugin as an already-created object

        # already loaded?
        if( my ( $already ) = grep { ref($plugin) eq ref $_; } @{ $self->plugins } ) {
                die "trying to load two different objects for plugin ". ref $plugin
                    if refaddr($plugin) != refaddr $already ;

        }
        else {
            push @{ $self->plugins }, $plugin;
        }

        return $plugin;
    }

    # short plugin names get Dancer2::Plugin:: prefix
    # plugin names starting with a '+' are full package names
    if ( $plugin !~ s/^\+// ) {
        $plugin =~ s/^(?!Dancer2::Plugin::)/Dancer2::Plugin::/;
    }

    # check if it's already there
    if( my ( $already ) = grep { $plugin eq ref $_ } @{ $self->plugins } ) {
        return $already;
    }

    push @{ $self->plugins }, 
         $plugin = use_module($plugin)->new( app => $self );

    return $plugin;
}

sub with_plugin {
    my( $self, $plugin ) = @_;

    croak "expected a single argument"
        unless @_ == 2;

    ( $self->with_plugins($plugin) )[0];
}

has _factory => (
    is      => 'ro',
    isa     => InstanceOf['Dancer2::Core::Factory'],
    lazy    => 1,
    default => sub { Dancer2::Core::Factory->new },
);

has logger_engine => (
    is        => 'ro',
    isa       => ConsumerOf['Dancer2::Core::Role::Logger'],
    lazy      => 1,
    builder   => '_build_logger_engine',
    writer    => 'set_logger_engine',
);

has session_engine => (
    is      => 'ro',
    isa     => ConsumerOf['Dancer2::Core::Role::SessionFactory'],
    lazy    => 1,
    builder => '_build_session_engine',
    writer  => 'set_session_engine',
);

has template_engine => (
    is      => 'ro',
    isa     => ConsumerOf['Dancer2::Core::Role::Template'],
    lazy    => 1,
    builder => '_build_template_engine',
    writer  => 'set_template_engine',
);

has serializer_engine => (
    is      => 'ro',
    isa     => ConsumerOf['Dancer2::Core::Role::Serializer'],
    lazy    => 1,
    builder => '_build_serializer_engine',
    writer  => 'set_serializer_engine',
    predicate => 'has_serializer_engine',
);

has '+local_triggers' => (
    default => sub {
        my $self     = shift;
        my $triggers = {
            # general triggers we want to allow, besides engines
            views => sub {
                my $self  = shift;
                my $value = shift;
                $self->template_engine->views($value);
            },

            layout => sub {
                my $self  = shift;
                my $value = shift;
                $self->template_engine->layout($value);
            },

            log => sub {
                my ( $self, $value, $config ) = @_;

                # This will allow to set the log level
                # using: set log => warning
                $self->logger_engine->log_level($value);
            },
        };

        foreach my $engine ( @{ $self->supported_engines } ) {
            $triggers->{$engine} = sub {
                my $self   = shift;
                my $value  = shift;
                my $config = shift;

                ref $value and return $value;

                my $build_method    = "_build_${engine}_engine";
                my $setter_method   = "set_${engine}_engine";
                my $engine_instance = $self->$build_method( $value, $config );

                # set the engine with the new value from the builder
                $self->$setter_method($engine_instance);

                return $engine_instance;
            };
        }

        return $triggers;
    },
);

sub _build_logger_engine {
    my $self   = shift;
    my $value  = shift;
    my $config = shift;

    defined $config or $config = $self->config;
    defined $value  or $value  = $config->{logger};

    ref $value and return $value;

    # XXX This is needed for the tests that create an app without
    # a runner.
    defined $value or $value = 'console';

    is_module_name($value)
        or croak "Cannot load logger engine '$value': illegal module name";

    my $engine_options =
        $self->_get_config_for_engine( logger => $value, $config );

    my $logger = $self->_factory->create(
        logger          => $value,
        %{$engine_options},
        location        => $self->config_location,
        environment     => $self->environment,
        app_name        => $self->name,
        postponed_hooks => $self->postponed_hooks
    );

    exists $config->{log} and $logger->log_level($config->{log});

    return $logger;
}

sub _build_session_engine {
    my $self   = shift;
    my $value  = shift;
    my $config = shift;

    defined $config or $config = $self->config;
    defined $value  or $value  = $config->{'session'} || 'simple';

    ref $value and return $value;

    is_module_name($value)
        or croak "Cannot load session engine '$value': illegal module name";

    my $engine_options =
          $self->_get_config_for_engine( session => $value, $config );

    Scalar::Util::weaken( my $weak_self = $self );

    # Note that engine options will replace the default session_dir (if provided).
    return $self->_factory->create(
        session         => $value,
        session_dir     => path( $self->config->{appdir}, 'sessions' ),
        %{$engine_options},
        postponed_hooks => $self->postponed_hooks,

        log_cb => sub { $weak_self->logger_engine->log(@_) },
    );
}

sub _build_template_engine {
    my $self   = shift;
    my $value  = shift;
    my $config = shift;

    defined $config or $config = $self->config;
    defined $value  or $value  = $config->{'template'};

    defined $value or return;
    ref $value    and return $value;

    is_module_name($value)
        or croak "Cannot load template engine '$value': illegal module name";

    my $engine_options =
          $self->_get_config_for_engine( template => $value, $config );

    my $engine_attrs = { config => $engine_options };
    $engine_attrs->{layout} ||= $config->{layout};
    $engine_attrs->{views}  ||= $config->{views}
        || path( $self->location, 'views' );

    Scalar::Util::weaken( my $weak_self = $self );

    return $self->_factory->create(
        template        => $value,
        %{$engine_attrs},
        postponed_hooks => $self->postponed_hooks,

        log_cb => sub { $weak_self->logger_engine->log(@_) },
    );
}

sub _build_serializer_engine {
    my $self   = shift;
    my $value  = shift;
    my $config = shift;

    defined $config or $config = $self->config;
    defined $value  or $value  = $config->{serializer};

    defined $value or return;
    ref $value    and return $value;

    my $engine_options =
        $self->_get_config_for_engine( serializer => $value, $config );

    Scalar::Util::weaken( my $weak_self = $self );

    return $self->_factory->create(
        serializer      => $value,
        config          => $engine_options,
        postponed_hooks => $self->postponed_hooks,

        log_cb => sub { $weak_self->logger_engine->log(@_) },
    );
}

sub _get_config_for_engine {
    my $self   = shift;
    my $engine = shift;
    my $name   = shift;
    my $config = shift;

    defined $config->{'engines'} && defined $config->{'engines'}{$engine}
        or return {};

    # try both camelized name and regular name
    my $engine_config = {};
    foreach my $engine_name ( $name, Dancer2::Core::camelize($name) ) {
        if ( defined $config->{'engines'}{$engine}{$engine_name} ) {
            $engine_config = $config->{'engines'}{$engine}{$engine_name};
            last;
        }
    }

    return $engine_config;
}

has postponed_hooks => (
    is      => 'ro',
    isa     => HashRef,
    default => sub { {} },
);

# TODO I'd be happier with a HashRef, really
has plugins => (
    is      => 'rw',
    isa     => ArrayRef,
    default => sub { [] },
);

has route_handlers => (
    is      => 'rw',
    isa     => ArrayRef,
    default => sub { [] },
);

has name => (
    is      => 'ro',
    isa     => Str,
    default => sub { (caller(1))[0] },
);

has request => (
    is        => 'ro',
    isa       => InstanceOf['Dancer2::Core::Request'],
    writer    => '_set_request',
    clearer   => 'clear_request',
    predicate => 'has_request',
);

sub set_request {
    my ($self, $request, $defined_engines) = @_;
    # typically this is passed in as an optimization within the
    # dispatch loop but may be called elsewhere
    $defined_engines ||= $self->defined_engines;
    # populate request in app and all engines
    $self->_set_request($request);
    $_->set_request( $request ) for @{$defined_engines};
}

has response => (
    is        => 'ro',
    isa       => InstanceOf['Dancer2::Core::Response'],
    lazy      => 1,
    writer    => 'set_response',
    clearer   => 'clear_response',
    builder   => '_build_response',
    predicate => 'has_response',
);

has with_return => (
    is        => 'ro',
    predicate => 1,
    writer    => 'set_with_return',
    clearer   => 'clear_with_return',
);

has session => (
    is        => 'ro',
    isa       => InstanceOf['Dancer2::Core::Session'],
    lazy      => 1,
    builder   => '_build_session',
    writer    => 'set_session',
    clearer   => 'clear_session',
    predicate => '_has_session',
);

around _build_config => sub {
    my ( $orig, $self ) = @_;
    my $config          = $self->$orig;

    if ( $config && $config->{'engines'} ) {
        $self->_validate_engine($_) for keys %{ $config->{'engines'} };
    }

    return $config;
};

sub _build_response {
    my $self = shift;
    return Dancer2::Core::Response->new(
        server_tokens => !$self->config->{'no_server_tokens'},
        $self->has_serializer_engine
            ? ( serializer => $self->serializer_engine )
            : (),
    );
}

sub _build_session {
    my $self = shift;
    my $session;

    # Find the session engine
    my $engine = $self->session_engine;

    # find the session cookie if any
    if ( !$self->has_destroyed_session ) {
        my $session_id;
        my $session_cookie = $self->cookie( $engine->cookie_name );
        defined $session_cookie and
            $session_id = $session_cookie->value;

        # if we have a session cookie, try to retrieve the session
        if ( defined $session_id ) {
            eval  {
                $EVAL_SHIM->(sub {
                    $session = $engine->retrieve( id => $session_id );
                });
                1;
            }
            or do {
                my $err = $@ || "Zombie Error";
                if ( $err !~ /Unable to retrieve session/ ) {
                    croak "Failed to retrieve session: $err"
                } else {
                    # XXX we throw away the error entirely? Why?
                }
            };
        }
    }

    # create the session if none retrieved
    return $session ||= $engine->create();
}

sub has_session {
    my $self = shift;

    my $engine = $self->session_engine;

    return $self->_has_session
        || ( $self->cookie( $engine->cookie_name )
             && !$self->has_destroyed_session );
}

has destroyed_session => (
    is        => 'ro',
    isa       => InstanceOf ['Dancer2::Core::Session'],
    predicate => 1,
    writer    => 'set_destroyed_session',
    clearer   => 'clear_destroyed_session',
);

sub find_plugin {
    my ( $self, $name ) = @_;
    my $plugin = List::Util::first { ref($_) eq $name } @{ $self->plugins };
    $plugin or return;
    return $plugin;
}

sub destroy_session {
    my $self = shift;

    # Find the session engine
    my $engine = $self->session_engine;

    # Expire session, set the expired cookie and destroy the session
    # Setting the cookie ensures client gets an expired cookie unless
    # a new session is created and supercedes it
    my $session = $self->session;
    $session->expires(-86400);    # yesterday
    $engine->destroy( id => $session->id );

    # Invalidate session cookie in request
    # and clear session in app and engines
    $self->set_destroyed_session($session);
    $self->clear_session;
    $_->clear_session for @{ $self->defined_engines };

    return;
}

sub setup_session {
    my $self = shift;

    for my $engine ( @{ $self->defined_engines } ) {
        $self->has_session                         ?
            $engine->set_session( $self->session ) :
            $engine->clear_session;
    }
}

sub change_session_id {
    my $self = shift;

    my $session = $self->session;

    # Find the session engine
    my $engine = $self->session_engine;

    if ($engine->can('_change_id')) {

        # session engine can change session ID
        $engine->change_id( session => $session );
    }
    else {

        # Method order is important in here...
        #
        # On session build if there is no destroyed session then the session
        # builder tries to recreate the session using the existing session
        # cookie. We really don't want to do that in this case so it is
        # important to create the new session before the
        # clear_destroyed_session method is called.
        #
        # This sucks.
        #
        # Sawyer suggested:
        #
        # What if you take the session cookie logic out of that attribute into
        # another attribute and clear that attribute?
        # That would force the session rebuilt to rebuilt the attribute and
        # get a different cookie value, no?
        #
        # TODO: think about this some more.

        # grab data, destroy session and store data again
        my %data = %{$session->data};

        # destroy existing session
        $self->destroy_session;

        # get new session
        $session = $self->session;

        # write data from old session into new
        # Some engines add session id to data so skip id.
        while (my ($key, $value) = each %data ) {
            $session->write($key => $value) unless $key eq 'id';
        }

        # clear out destroyed session - no longer relevant
        $self->clear_destroyed_session;
    }

    return $session->id;
}

has prefix => (
    is        => 'rw',
    isa       => Maybe [Dancer2Prefix],
    predicate => 1,
    coerce    => sub {
        my $prefix = shift;
        defined($prefix) and $prefix eq "/" and return;
        return $prefix;
    },
);

# routes registry, stored by method:
has routes => (
    is      => 'rw',
    isa     => HashRef,
    default => sub {
        {   get     => [],
            head    => [],
            post    => [],
            put     => [],
            del     => [],
            options => [],
        };
    },
);

# add_hook will add the hook to the first "hook candidate" it finds that support
# it. If none, then it will try to add the hook to the current application.
around add_hook => sub {
    my $orig = shift;
    my $self = shift;

    # saving caller information
    my ( $package, $file, $line ) = caller(4);    # deep to 4 : user's app code
    my $add_hook_caller = [ $package, $file, $line ];

    my ($hook)       = @_;
    my $name         = $hook->name;
    my $hook_aliases = $self->all_hook_aliases;

    # look for an alias
    defined $hook_aliases->{$name} and $name = $hook_aliases->{$name};
    $hook->name($name);

    # if that hook belongs to the app, register it now and return
    $self->has_hook($name) and return $self->$orig(@_);

    # at this point the hook name must be formatted like:
    # '$type.$candidate.$name', eg: 'engine.template.before_render' or
    # 'plugin.database.before_dbi_connect'
    my ( $hookable_type, $hookable_name, $hook_name ) = split( /\./, $name );

    ( defined $hookable_name && defined $hook_name )
        or croak "Invalid hook name `$name'";

    grep /^$hookable_type$/, qw(core engine handler plugin)
        or croak "Unknown hook type `$hookable_type'";

    # register the hooks for existing hookable candidates
    foreach my $hookable ( $self->hook_candidates ) {
        $hookable->has_hook($name) and $hookable->add_hook(@_);
    }

    # we register the hook for upcoming objects;
    # that way, each components that can claim the hook will have a chance
    # to register it.

    my $postponed_hooks = $self->postponed_hooks;

    # Hmm, so the hook was not claimed, at this point we'll cache it and
    # register it when the owner is instantiated
    $postponed_hooks->{$hookable_type}{$hookable_name} ||= {};
    $postponed_hooks->{$hookable_type}{$hookable_name}{$name} ||= {};
    $postponed_hooks->{$hookable_type}{$hookable_name}{$name}{hook} = $hook;
    $postponed_hooks->{$hookable_type}{$hookable_name}{$name}{caller} =
      $add_hook_caller;

};

around execute_hook => sub {
    my $orig = shift;
    my $self = shift;

    local $Dancer2::Core::Route::REQUEST  = $self->request;
    local $Dancer2::Core::Route::RESPONSE = $self->response;

    my ( $hook, @args ) = @_;
    if ( !$self->has_hook($hook) ) {
        foreach my $cand ( $self->hook_candidates ) {
            $cand->has_hook($hook) and return $cand->execute_hook(@_);
        }
    }

    return $self->$orig(@_);
};

sub _build_default_config {
    my $self = shift;

    my $public = $ENV{DANCER_PUBLIC} || path( $self->location, 'public' );
    return {
        content_type   => ( $ENV{DANCER_CONTENT_TYPE} || 'text/html' ),
        charset        => ( $ENV{DANCER_CHARSET}      || '' ),
        logger         => ( $ENV{DANCER_LOGGER}       || 'console' ),
        views          => ( $ENV{DANCER_VIEWS}
                            || path( $self->config_location, 'views' ) ),
        environment    => $self->environment,
        appdir         => $self->location,
        public_dir     => $public,
        template       => 'Tiny',
        route_handlers => [
            [
                AutoPage => 1
            ],
        ],
    };
}

sub _init_hooks {
    my $self = shift;

    # Hook to flush the session at the end of the request,
    # this way, we're sure we flush only once per request
    #
    # Note: we create a weakened copy $self
    # before closing over the weakened copy
    # to avoid circular memory refs.
    Scalar::Util::weaken(my $app = $self);

    $self->add_hook(
        Dancer2::Core::Hook->new(
            name => 'core.app.after_request',
            code => sub {
                my $response = $Dancer2::Core::Route::RESPONSE;

                # make sure an engine is defined, if not, nothing to do
                my $engine = $app->session_engine;
                defined $engine or return;

                # if a session has been instantiated or we already had a
                # session, first flush the session so cookie-based sessions can
                # update the session ID if needed, then set the session cookie
                # in the response
                #
                # if there is NO session object but the request has a cookie with
                # a session key, create a dummy session with the same ID (without
                # actually retrieving and flushing immediately) and generate the
                # cookie header from the dummy session. Lazy Sessions FTW!

                if ( $app->has_session ) {
                    my $session;
                    if ( $app->_has_session ) { # Session object exists
                        $session = $app->session;
                        $session->is_dirty and $engine->flush( session => $session );
                    }
                    else { # Cookie header exists. Create a dummy session object
                        my $cookie = $app->cookie( $engine->cookie_name );
                        my $session_id = $cookie->value;
                        $session = Dancer2::Core::Session->new( id => $session_id );
                    }
                    $engine->set_cookie_header(
                        response => $response,
                        session  => $session
                    );
                }
                elsif ( $app->has_destroyed_session ) {
                    my $session = $app->destroyed_session;
                    $engine->set_cookie_header(
                        response  => $response,
                        session   => $session,
                        destroyed => 1
                    );
                }
            },
        )
    );
}

sub supported_hooks {
    qw/
      core.app.before_request
      core.app.after_request
      core.app.route_exception
      core.app.before_file_render
      core.app.after_file_render
      core.error.before
      core.error.after
      core.error.init
      /;
}

sub hook_aliases {
    my $self = shift;
    $self->{'hook_aliases'} ||= {
        before                 => 'core.app.before_request',
        before_request         => 'core.app.before_request',
        after                  => 'core.app.after_request',
        after_request          => 'core.app.after_request',
        init_error             => 'core.error.init',
        before_error           => 'core.error.before',
        after_error            => 'core.error.after',
        on_route_exception     => 'core.app.route_exception',

        before_file_render         => 'core.app.before_file_render',
        after_file_render          => 'core.app.after_file_render',
        before_handler_file_render => 'handler.file.before_render',
        after_handler_file_render  => 'handler.file.after_render',


        # compatibility from Dancer1
        before_error_render    => 'core.error.before',
        after_error_render     => 'core.error.after',
        before_error_init      => 'core.error.init',

        # TODO: call $engine->hook_aliases as needed
        # But.. currently there are use cases where hook_aliases
        # are needed before the engines are intiialized :(
        before_template_render => 'engine.template.before_render',
        after_template_render  => 'engine.template.after_render',
        before_layout_render   => 'engine.template.before_layout_render',
        after_layout_render    => 'engine.template.after_layout_render',
        before_serializer      => 'engine.serializer.before',
        after_serializer       => 'engine.serializer.after',
    };
}

sub defined_engines {
    my $self = shift;
    return [
        $self->template_engine,
        $self->session_engine,
        $self->logger_engine,
        $self->has_serializer_engine
            ? $self->serializer_engine
            : (),
    ];
}

# FIXME not needed anymore, I suppose...
sub api_version {2}

sub register_plugin {
    my $self   = shift;
    my $plugin = shift;

    $self->log( core => "Registered $plugin");

    push @{ $self->plugins }, $plugin;
}

# This method overrides the default one from Role::ConfigReader
sub settings {
    my $self = shift;
    +{ %{ Dancer2::runner()->config }, %{ $self->config } };
}

sub cleanup {
    my $self = shift;
    $self->clear_request;
    $self->clear_response;
    $self->clear_session;
    $self->clear_destroyed_session;
    # Clear engine attributes
    for my $engine ( @{ $self->defined_engines } ) {
        $engine->clear_session;
        $engine->clear_request;
    }
}

sub _validate_engine {
    my $self = shift;
    my $name = shift;

    grep +( $_ eq $name ), @{ $self->supported_engines }
        or croak "Engine '$name' is not supported.";
}

sub engine {
    my $self = shift;
    my $name = shift;

    $self->_validate_engine($name);

    my $attr_name = "${name}_engine";
    return $self->$attr_name;
}

sub template {
    my $self = shift;

    my $template = $self->template_engine;
    $template->set_settings( $self->config );

    # A session will not exist if there is no request (global keyword)
    #
    # A session may exist but the route code may not have instantiated
    # the session object (sessions are lazy). If this is the case, do
    # that now, so the templates have the session data for rendering.
    $self->has_request && $self->has_session && ! $template->has_session
        and $self->setup_session;

    # return content
    return $template->process( @_ );
}

sub hook_candidates {
    my $self = shift;

    my @engines = @{ $self->defined_engines };

    my @route_handlers;
    for my $handler ( @{ $self->route_handlers } ) {
        my $handler_code = $handler->{handler};
        blessed $handler_code and $handler_code->can('supported_hooks')
            and push @route_handlers, $handler_code;
    }

    # TODO : get the list of all plugins registered
    my @plugins = @{ $self->plugins };

    ( @route_handlers, @engines, @plugins );
}

sub all_hook_aliases {
    my $self = shift;

    my $aliases = $self->hook_aliases;
    for my $plugin ( grep { $_->can('hook_aliases') } @{ $self->plugins } ) {
        $aliases = { %{$aliases}, %{ $plugin->hook_aliases } };
    }

    return $aliases;
}

sub mime_type {
    my $self   = shift;
    my $runner = Dancer2::runner();

    exists $self->config->{default_mime_type}
        ? $runner->mime_type->default( $self->config->{default_mime_type} )
        : $runner->mime_type->reset_default;

    $runner->mime_type;
}

sub log {
    my $self  = shift;
    my $level = shift;

    my $logger = $self->logger_engine
      or croak "No logger defined";

    $logger->$level(@_);
}

sub send_as {
    my $self = shift;
    my ( $type, $data, $options ) = @_;
    $options ||= {};

    $type or croak "Can not send_as using an undefined type";

    if ( lc($type) eq 'html' ) {
        if ( $type ne 'html' ) {
            local $Carp::CarpLevel = 2;
            carp "Please use 'html' as the type for 'send_as', not $type";
        }

        $options->{charset} = $self->config->{charset} || 'UTF-8';
        my $content = Encode::encode( $options->{charset}, $data );
        $options->{content_type} ||= 'text/html';
        $self->send_file( \$content, %$options );     # returns from sub
    }

    # Try and load the serializer class
    my $serializer_class = "Dancer2::Serializer::$type";
    eval {
        $EVAL_SHIM->(sub {
            require_module( $serializer_class );
        });
        1;
    } or do {
        my $err = $@ || "Zombie Error";
        croak "Unable to load serializer class for $type: $err";
    };

    # load any serializer engine config
    my $engine_options =
        $self->_get_config_for_engine( serializer => $type, {} ) || {};
    my $serializer = $serializer_class->new( config => $engine_options );
    my $content = $serializer->serialize( $data );
    $options->{content_type} ||= $serializer->content_type;
    $self->send_file( \$content, %$options );
}

sub send_error {
    my $self = shift;
    my ( $message, $status ) = @_;

    my $err = Dancer2::Core::Error->new(
          message    => $message,
          app        => $self,
        ( status     => $status     )x!! $status,

        $self->has_serializer_engine
            ? ( serializer => $self->serializer_engine )
            : (),
    )->throw;

    # Immediately return to dispatch if with_return coderef exists
    $self->has_with_return && $self->with_return->($err);
    return $err;
}

sub send_file {
    my $self    = shift;
    my $thing   = shift;
    my %options = @_;

    my ($content_type, $charset, $file_path);

    # are we're given a filehandle? (based on what Plack::Middleware::Lint accepts)
    my $is_filehandle = Plack::Util::is_real_fh($thing)
      || ( ref $thing eq 'GLOB' && *{$thing}{IO} && *{$thing}{IO}->can('getline') )
      || ( Scalar::Util::blessed($thing) && $thing->can('getline') );
    my ($fh) = ($thing)x!! $is_filehandle;

    # if we're given an IO::Scalar object, DTRT (take the scalar ref from it)
    if (Scalar::Util::blessed($thing) && $thing->isa('IO::Scalar')) {
        $thing = $thing->sref;
    }

    # if we're given a SCALAR reference, build a filehandle to it
    if ( ref $thing eq 'SCALAR' ) {
        ## no critic qw(InputOutput::RequireCheckedOpen)
        open $fh, "<", $thing;
    }

    # If we haven't got a filehandle, create one to the requested content
    if (! $fh) {
        my $path = $thing;
        # remove prefix from given path (if not a filehandle)
        my $prefix = $self->prefix;
        if ( $prefix && $prefix ne '/' ) {
            $path =~ s/^\Q$prefix\E//;
        }
        # static file dir - either system root or public_dir
        my $dir = $options{system_path}
            ? File::Spec->rootdir
            : $ENV{DANCER_PUBLIC}
                || $self->config->{public_dir}
                || path( $self->location, 'public' );

        $file_path = Dancer2::Handler::File->merge_paths( $path, $dir );
        my $err_response = sub {
            my $status = shift;
            $self->response->status($status);
            $self->response->header( 'Content-Type', 'text/plain' );
            $self->response->content( Dancer2::Core::HTTP->status_message($status) );
            $self->with_return->( $self->response );
        };
        $err_response->(403) if !defined $file_path;
        $err_response->(404) if !-f $file_path;
        $err_response->(403) if !-r $file_path;

        # Read file content as bytes
        $fh = Dancer2::FileUtils::open_file( "<", $file_path );
        binmode $fh;
        $content_type = Dancer2::runner()->mime_type->for_file($file_path) || 'text/plain';
        if ( $content_type =~ m!^text/! ) {
            $charset = $self->config->{charset} || "utf-8";
        }
    }

    # Now we are sure we can render the file...
    $self->execute_hook( 'core.app.before_file_render', $file_path );

    # response content type and charset
    ( exists $options{'content_type'} ) and $content_type = $options{'content_type'};
    ( exists $options{'charset'} ) and $charset = $options{'charset'};
    $content_type .= "; charset=$charset" if $content_type and $charset;
    ( defined $content_type )
      and $self->response->header('Content-Type' => $content_type );

    # content disposition
    ( exists $options{filename} )
      and $self->response->header( 'Content-Disposition' =>
          "attachment; filename=\"$options{filename}\"" );

    # use a delayed response unless server does not support streaming
    my $use_streaming = exists $options{streaming} ? $options{streaming} : 1;
    my $response;
    my $env = $self->request->env;
    if ( $env->{'psgi.streaming'} && $use_streaming ) {
        my $cb = sub {
            my $responder = $Dancer2::Core::Route::RESPONDER;
            my $res = $Dancer2::Core::Route::RESPONSE;
            return $responder->(
                [ $res->status, $res->headers_to_array, $fh ]
            );
        };

        Scalar::Util::weaken( my $weak_self = $self );

        $response = Dancer2::Core::Response::Delayed->new(
            error_cb => sub { $weak_self->logger_engine->log( warning => @_ ) },
            cb       => $cb,
            request  => $Dancer2::Core::Route::REQUEST,
            response => $Dancer2::Core::Route::RESPONSE,
        );
    }
    else {
        $response = $self->response;
        # direct assignment to hash element, avoids around modifier
        # trying to serialise this this content.
        $response->{content} = Dancer2::FileUtils::read_glob_content($fh);
        $response->is_encoded(1);    # bytes are already encoded
    }

    $self->execute_hook( 'core.app.after_file_render', $response );
    $self->with_return->( $response );
}

sub BUILD {
    my $self = shift;
    $self->init_route_handlers();
    $self->_init_hooks();
}

sub finish {
    my $self = shift;

    # normalize some values that require calculations
    defined $self->config->{'static_handler'}
        or $self->config->{'static_handler'} = -d $self->config->{'public_dir'};

    $self->register_route_handlers;
    $self->compile_hooks;

    @{$self->plugins}
        && $self->plugins->[0]->can('_add_postponed_plugin_hooks')
        && $self->plugins->[0]->_add_postponed_plugin_hooks(
            $self->postponed_hooks
        );
}

sub init_route_handlers {
    my $self = shift;

    my $handlers_config = $self->config->{route_handlers};
    for my $handler_data ( @{$handlers_config} ) {
        my ($handler_name, $config) = @{$handler_data};
        $config = {} if !ref($config);

        my $handler = $self->_factory->create(
            Handler         => $handler_name,
            app             => $self,
            %$config,
            postponed_hooks => $self->postponed_hooks,
        );

        push @{ $self->route_handlers }, {
            name    => $handler_name,
            handler => $handler,
        };
    }
}

sub register_route_handlers {
    my $self = shift;
    for my $handler ( @{$self->route_handlers} ) {
        my $handler_code = $handler->{handler};
        $handler_code->register($self);
    }
}

sub compile_hooks {
    my ($self) = @_;

    for my $position ( $self->supported_hooks ) {
        my $compiled_hooks = [];
        for my $hook ( @{ $self->hooks->{$position} } ) {
            Scalar::Util::weaken( my $app = $self );
            my $compiled = sub {
                # don't run the filter if halt has been used
                $Dancer2::Core::Route::RESPONSE &&
                $Dancer2::Core::Route::RESPONSE->is_halted
                    and return;

                eval  { $EVAL_SHIM->($hook,@_); 1; }
                or do {
                    my $err = $@ || "Zombie Error";
                    $app->cleanup;
                    $app->log('error', "Exception caught in '$position' filter: $err");
                    croak "Exception caught in '$position' filter: $err";
                };
            };

            push @{$compiled_hooks}, $compiled;
        }
        $self->replace_hook( $position, $compiled_hooks );
    }
}

sub lexical_prefix {
    my $self   = shift;
    my $prefix = shift;
    my $cb     = shift;

    $prefix eq '/' and undef $prefix;

    # save the app prefix
    my $app_prefix = $self->prefix;

    # alter the prefix for the callback
    my $new_prefix =
        ( defined $app_prefix ? $app_prefix : '' )
      . ( defined $prefix     ? $prefix     : '' );

    # if the new prefix is empty, it's a meaningless prefix, just ignore it
    length $new_prefix and $self->prefix($new_prefix);

    my $err;
    my $ok= eval { $EVAL_SHIM->($cb); 1 }
            or do { $err = $@ || "Zombie Error"; };

    # restore app prefix
    $self->prefix($app_prefix);

    $ok or croak "Unable to run the callback for prefix '$prefix': $err";
}

sub add_route {
    my $self        = shift;
    my %route_attrs = @_;

    my $route =
      Dancer2::Core::Route->new( %route_attrs, prefix => $self->prefix );

    my $method = $route->method;

    push @{ $self->routes->{$method} }, $route;

    return $route;
}

sub route_exists {
    my $self  = shift;
    my $route = shift;

    my $routes = $self->routes->{ $route->method };

    foreach my $existing_route (@$routes) {
        $existing_route->spec_route eq $route->spec_route
            and return 1;
    }

    return 0;
}

sub routes_regexps_for {
    my $self   = shift;
    my $method = shift;

    return [ map $_->regexp, @{ $self->routes->{$method} } ];
}

sub cookie {
    my $self = shift;

    @_ == 1 and return $self->request->cookies->{ $_[0] };

    # writer
    my ( $name, $value, %options ) = @_;
    my $c =
      Dancer2::Core::Cookie->new( name => $name, value => $value, %options );
    $self->response->push_header( 'Set-Cookie' => $c->to_header );
}

sub redirect {
    my $self        = shift;
    my $destination = shift;
    my $status      = shift;

    # RFC 2616 requires an absolute URI with a scheme,
    # turn the URI into that if it needs it

    # Scheme grammar as defined in RFC 2396
    #  scheme = alpha *( alpha | digit | "+" | "-" | "." )
    my $scheme_re = qr{ [a-z][a-z0-9\+\-\.]* }ix;
    if ( $destination !~ m{^ $scheme_re : }x ) {
        $destination = $self->request->uri_for( $destination, {}, 1 );
    }

    $self->response->redirect( $destination, $status );

    # Short circuit any remaining before hook / route code
    # ('pass' and after hooks are still processed)
    $self->has_with_return
        and $self->with_return->($self->response);
}

sub halt {
   my $self = shift;
   $self->response->halt( @_ );

   # Short citcuit any remaining hook/route code
   $self->has_with_return
       and $self->with_return->($self->response);
}

sub pass {
   my $self = shift;
   $self->response->pass;

   # Short citcuit any remaining hook/route code
   $self->has_with_return
       and $self->with_return->($self->response);
}

sub forward {
    my $self    = shift;
    my $url     = shift;
    my $params  = shift;
    my $options = shift;

    my $new_request = $self->make_forward_to( $url, $params, $options );

    $self->has_with_return
        and $self->with_return->($new_request);

    # nothing else will run after this
}

# Create a new request which is a clone of the current one, apart
# from the path location, which points instead to the new location
sub make_forward_to {
    my $self    = shift;
    my $url     = shift;
    my $params  = shift;
    my $options = shift;

    my $overrides = { PATH_INFO => $url };
    exists $options->{method} and
        $overrides->{REQUEST_METHOD} = $options->{method};

    # "clone" the existing request
    my $new_request = $self->request->_shallow_clone( $params, $overrides );

    # If a session object was created during processing of the original request
    # i.e. a session object exists but no cookie existed
    # add a cookie so the dispatcher can assign the session to the appropriate app
    my $engine = $self->session_engine;
    $engine && $self->_has_session or return $new_request;
    my $name = $engine->cookie_name;
    exists $new_request->cookies->{$name} and return $new_request;
    $new_request->cookies->{$name} =
        Dancer2::Core::Cookie->new( name => $name, value => $self->session->id );

    return $new_request;
}

sub app { shift }

# DISPATCHER
sub to_app {
    my $self = shift;

    # build engines
    {
        for ( qw<logger session template> ) {
            my $attr = "${_}_engine";
            $self->$attr;
        }

        # the serializer engine does not have a default
        # and is the only engine that can actually not have a value
        if ( $self->config->{'serializer'} ) {
            $self->serializer_engine;
        }
    }

    $self->finish;

    my $psgi = sub {
        my $env = shift;

        # pre-request sanity check
        my $method = uc $env->{'REQUEST_METHOD'};
        $Dancer2::Core::Types::supported_http_methods{$method}
            or return [
                405,
                [ 'Content-Type' => 'text/plain' ],
                [ "Method Not Allowed\n\n$method is not supported." ]
            ];

        my $response;
        eval {
            $EVAL_SHIM->(sub{ $response = $self->dispatch($env)->to_psgi });
            1;
        } or do {
            my $err = $@ || "Zombie Error";
            return [
                500,
                [ 'Content-Type' => 'text/plain' ],
                [ "Internal Server Error\n\n$err"  ],
            ];
        };

        return $response;
    };

    # Wrap with common middleware
    # FixMissingBodyInRedirect
    $psgi = Plack::Middleware::FixMissingBodyInRedirect->wrap( $psgi );

    # Only add static content handler if requires
    if ( $self->config->{'static_handler'} ) {
        # Use App::File to "serve" the static content
        my $static_app = Plack::App::File->new(
            root         => $self->config->{public_dir},
            content_type => sub { $self->mime_type->for_name(shift) },
        )->to_app;
        # Conditionally use the static handler wrapped with ConditionalGET
        # when the file exists. Otherwise the request passes into our app.
        $psgi = Plack::Middleware::Conditional->wrap(
            $psgi,
            condition => sub { -f path( $self->config->{public_dir}, shift->{PATH_INFO} ) },
            builder   => sub { Plack::Middleware::ConditionalGET->wrap( $static_app ) },
        );
    }

    # Apply Head. After static so a HEAD request on static content DWIM.
    $psgi = Plack::Middleware::Head->wrap( $psgi );
    return $psgi;
}

sub dispatch {
    my $self = shift;
    my $env  = shift;

    my $runner  = Dancer2::runner();
    my $request = $runner->{'internal_request'} ||
                  $self->build_request($env);
    my $cname   = $self->session_engine->cookie_name;

    my $defined_engines = $self->defined_engines;

DISPATCH:
    while (1) {
        my $http_method = lc $request->method;
        my $path_info   =    $request->path_info;

        # Add request to app and engines
        $self->set_request($request, $defined_engines);

        $self->log( core => "looking for $http_method $path_info" );

        ROUTE:
        foreach my $route ( @{ $self->routes->{$http_method} } ) {
            #warn "testing route " . $route->regexp . "\n";
            # TODO store in route cache

            # go to the next route if no match
            my $match = $route->match($request)
                or next ROUTE;

            $request->_set_route_params($match);
            $request->_set_route_parameters($match);

            # Add session to app *if* we have a session and the request
            # has the appropriate cookie header for _this_ app.
            if ( my $sess = $runner->{'internal_sessions'}{$cname} ) {
                $self->set_session($sess);
            }

            # calling the actual route
            my $response = Return::MultiLevel::with_return {
                my ($return) = @_;

                # stash the multilevel return coderef in the app
                $self->has_with_return
                    or $self->set_with_return($return);

                return $self->_dispatch_route($route);
            };

            # ensure we clear the with_return handler
            $self->clear_with_return;

            # handle forward requests
            if ( ref $response eq 'Dancer2::Core::Request' ) {
                # this is actually a request, not response
                # however, we need to clean up the request & response
                $self->clear_request;
                $self->clear_response;

                # this is in case we're asked for an old-style dispatching
                if ( $runner->{'internal_dispatch'} ) {
                    # Get the session object from the app before we clean up
                    # the request context, so we can propagate this to the
                    # next dispatch cycle (if required).
                    $self->_has_session
                        and $runner->{'internal_sessions'}{$cname} =
                            $self->session;

                    $runner->{'internal_forward'} = 1;
                    $runner->{'internal_request'} = $response;
                    return $self->response_not_found($request);
                }

                $request = $response;
                next DISPATCH;
            }

            # from here we assume the response is a Dancer2::Core::Response

            # halted response, don't process further
            if ( $response->is_halted ) {
                $self->cleanup;
                delete $runner->{'internal_request'};
                return $response;
            }

            # pass the baton if the response says so...
            if ( $response->has_passed ) {
                ## A previous route might have used splat, failed
                ## this needs to be cleaned from the request.
                exists $request->{_params}{splat}
                    and delete $request->{_params}{splat};

                $response->has_passed(0); # clear for the next round

                # clear the content because if you pass it,
                # the next route is in charge of catching it
                $response->clear_content;
                next ROUTE;
            }

            # it's just a regular response
            $self->execute_hook( 'core.app.after_request', $response );
            $self->cleanup;
            delete $runner->{'internal_request'};

            return $response;
        }

        # we don't actually want to continue the loop
        last;
    }

    # No response! ensure Core::Dispatcher recognizes this failure
    # so it can try the next Core::App
    # and set the created request so we don't create it again
    # (this is important so we don't ignore the previous body)
    if ( $runner->{'internal_dispatch'} ) {
        $runner->{'internal_404'}     = 1;
        $runner->{'internal_request'} = $request;
    }

    # Render 404 response, cleanup, and return the response.
    my $response = $self->response_not_found($request);
    $self->cleanup;
    return $response;
}

sub build_request {
    my ( $self, $env ) = @_;

    # If we have an app, send the serialization engine
    my $request = Dancer2::Core::Request->new(
          env             => $env,
          is_behind_proxy => $self->settings->{'behind_proxy'} || 0,

          $self->has_serializer_engine
              ? ( serializer => $self->serializer_engine )
              : (),
    );

    return $request;
}

# Call any before hooks then the matched route.
sub _dispatch_route {
    my ( $self, $route ) = @_;

    local $@;
    eval {
        $EVAL_SHIM->(sub {
            $self->execute_hook( 'core.app.before_request', $self );
        });
        1;
    } or do {
        my $err = $@ || "Zombie Error";
        return $self->response_internal_error($err);
    };
    my $response = $self->response;

    if ( $response->is_halted ) {
        return $self->_prep_response( $response );
    }

    eval {
        $EVAL_SHIM->(sub{ $response = $route->execute($self) });
        1;
    } or do {
        my $err = $@ || "Zombie Error";
        return $self->response_internal_error($err);
    };

    return $response;
}

sub _prep_response {
    my ( $self, $response, $content ) = @_;

    # The response object has no back references to the content or app
    # Update the default_content_type of the response if any value set in
    # config so it can be applied when the response is encoded/returned.
    my $config = $self->config;
    if ( exists $config->{content_type}
      and my $ct = $config->{content_type} ) {
        $response->default_content_type($ct);
    }

    # if we were passed any content, set it in the response
    defined $content && $response->content($content);
    return $response;
}

sub response_internal_error {
    my ( $self, $error ) = @_;

    $self->log( error => "Route exception: $error" );
    $self->execute_hook( 'core.app.route_exception', $self, $error );

    local $Dancer2::Core::Route::REQUEST  = $self->request;
    local $Dancer2::Core::Route::RESPONSE = $self->response;

    return Dancer2::Core::Error->new(
        app       => $self,
        status    => 500,
        exception => $error,
    )->throw;
}

sub response_not_found {
    my ( $self, $request ) = @_;

    $self->set_request($request);

    local $Dancer2::Core::Route::REQUEST  = $self->request;
    local $Dancer2::Core::Route::RESPONSE = $self->response;

    my $response = Dancer2::Core::Error->new(
        app    => $self,
        status  => 404,
        message => $request->path,
    )->throw;

    $self->cleanup;

    return $response;
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Dancer2::Core::App - encapsulation of Dancer2 packages

=head1 VERSION

version 0.204002

=head1 DESCRIPTION

Everything a package that uses Dancer2 does is encapsulated into a
C<Dancer2::Core::App> instance. This class defines all that can be done in such
objects.

Mainly, it will contain all the route handlers, the configuration settings and
the hooks that are defined in the calling package.

Note that with Dancer2, everything that is done within a package is scoped to
that package, thanks to that encapsulation.

=head1 ATTRIBUTES

=head2 plugins

=head2 runner_config

=head2 default_config

=head2 with_return

Used to cache the coderef from L<Return::MultiLevel> within the dispatcher.

=head2 destroyed_session

We cache a destroyed session here; once this is set we must not attempt to
retrieve the session from the cookie in the request.  If no new session is
created, this is set (with expiration) as a cookie to force the browser to
expire the cookie.

=head1 METHODS

=head2 has_session

Returns true if session engine has been defined and if either a session
object has been instantiated or if a session cookie was found and not
subsequently invalidated.

=head2 destroy_session

Destroys the current session and ensures any subsequent session is created
from scratch and not from the request session cookie

=head2 register_plugin

=head2 with_plugins( @plugin_names )

Creates instances of the given plugins and tie them to the app.
The plugin classes are automatically loaded.
Returns the newly created plugins.

The plugin names are expected to be without the leading C<Dancer2::Plugin>.
I.e., use C<Foo> to mean C<Dancer2::Plugin::Foo>.

If a given plugin is already tied to the app, the already-existing
instance will be used and returned by C<with_plugins> (think of it
as using a role).

    my @plugins = $app->with_plugins( 'Foo', 'Bar' );

    # now $app uses the plugins Dancer2::Plugin::Foo
    # and Dancer2::Plugin::Bar

=head2 with_plugin( $plugin_name )

Just like C<with_plugin>, but for a single plugin.

    my $plugin = $app->with_plugin('Foo');

=head2 redirect($destination, $status)

Sets a redirect in the response object.  If $destination is not an absolute URI, then it will
be made into an absolute URI, relative to the URI in the request.

=head2 halt

Flag the response object as 'halted'.

If called during request dispatch, immediately returns the response
to the dispatcher and after hooks will not be run.

=head2 pass

Flag the response object as 'passed'.

If called during request dispatch, immediately returns the response
to the dispatcher.

=head2 forward

Create a new request which is a clone of the current one, apart
from the path location, which points instead to the new location.
This is used internally to chain requests using the forward keyword.

This method takes 3 parameters: the url to forward to, followed by an
optional hashref of parameters added to the current request parameters,
followed by a hashref of options regarding the redirect, such as
C<method> to change the request method.

For example:

    forward '/login', { login_failed => 1 }, { method => 'GET' });

=head2 lexical_prefix

Allow for setting a lexical prefix

    $app->lexical_prefix('/blog', sub {
        ...
    });

All the route defined within the callback will have a prefix appended to the
current one.

=head2 add_route

Register a new route handler.

    $app->add_route(
        method  => 'get',
        regexp  => '/somewhere',
        code    => sub { ... },
        options => $conditions,
    );

=head2 route_exists

Check if a route already exists.

    my $route = Dancer2::Core::Route->new(...);
    if ($app->route_exists($route)) {
        ...
    }

=head2 routes_regexps_for

Sugar for getting the ordered list of all registered route regexps by method.

    my $regexps = $app->routes_regexps_for( 'get' );

Returns an ArrayRef with the results.

=head2 app

Returns itself. This is simply available as a shim to help transition from
a previous version in which hooks were sent a context object (originally
C<Dancer2::Core::Context>) which has since been removed.

    # before
    hook before => sub {
        my $ctx = shift;
        my $app = $ctx->app;
    };

    # after
    hook before => sub {
        my $app = shift;
    };

This meant that C<< $app->app >> would fail, so this method has been provided
to make it work.

    # now
    hook before => sub {
        my $WannaBeCtx = shift;
        my $app        = $WannaBeContext->app; # works
    };

=head2 C< $SIG{__DIE__} > Compatibility via C< $Dancer2::Core::App::EVAL_SHIM >

If an installation wishes to use C< $SIG{__DIE__} > hooks to enhance
their error handling then it may be required to ensure that certain
bookkeeping code is executed within every C<eval BLOCK> that Dancer2
performs. This can be accomplished by overriding the global variable
C<$Dancer2::Core::App::EVAL_SHIM> with a subroutine which does whatever
logic is required.

This routine must perform the equivalent of the following subroutine:

    our $EVAL_SHIM = sub {
        my $code = shift;
        return $code->(@_);
    };

An example of overriding this sub might be as follows:

    $Dancer2::Core::App::EVAL_SHIM = sub {
        my $code = shift;
        local $IGNORE_EVAL_COUNTER = $IGNORE_EVAL_COUNTER + 1;
        return $code->(@_);
    };

B<Note:> that this is a GLOBAL setting, which must be set up before
any form of dispatch or use of Dancer2.

=head1 AUTHOR

Dancer Core Developers

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2016 by Alexis Sukrieh.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut