[
  {
    "path": ".gitignore",
    "content": "node_modules\ntesting\n.jshint\ncoverage.html\nnpm-debug.log\nindex-cov.js\n.DS_Store\npackage-lock.json\n"
  },
  {
    "path": ".jshintrc",
    "content": "{\n  \"browser\": true,\n  \"node\":true,\n  \"expr\": true,\n  \"eqnull\": true,\n  \"laxcomma\": true,\n  \"-W079\": true,\n  \"-W014\": true,\n  \"curly\": false,\n  \"eqeqeq\": true,\n  \"immed\": true,\n  \"latedef\": true,\n  \"newcap\": true,\n  \"noarg\": true,\n  \"quotmark\": \"single\",\n  \"regexp\": true,\n  \"undef\": true,\n  \"unused\": false,\n  \"strict\": true,\n  \"trailing\": false,\n  \"smarttabs\": true,\n  \"latedef\": false,\n  \"indent\": 2,\n  \"validthis\": true\n}\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: node_js\nnode_js:\n  - 0.10\n  - node\nbefore_script:\n  - npm run engine-deps\nafter_success:\n  - ./node_modules/.bin/jscoverage index.js index-cov.js\n  - PAGE_COV=1 ./node_modules/.bin/mocha test/tests.js -R mocha-lcov-reporter | ./node_modules/coveralls/bin/coveralls.js\nsudo: false\n"
  },
  {
    "path": "History.md",
    "content": "1.8.3 / 2018-01-22\n==================\n\nThis is a patch release which switches the build to rollup. Switching shaves 2k off of the gzipped size. In addition to this benefit, this also fixes a couple of small issues:\n\n## Issues\n\n* [#444] - Closure compiler warnings\n* [#458] - unsafe-eval error\n\n[#444]: https://github.com/visionmedia/page.js/issues/444\n[#458]: https://github.com/visionmedia/page.js/issues/458\n\n1.8.2 / 2018-01-22\n==================\n\nThis is a patch release fixing an issue that was meant to be solved in 1.8.1. page.js now runs in Node.js again, when there isn't a window environment.\n\n1.8.1 / 2018-01-22\n==================\n\nThis is a patch release, fixing an issue with Node.js usage.\n\n1.8.0 / 2018-01-17\n==================\n\nThis is a minor release, adding one new (minor) feature and a few bug fixes and documentation improvements.\n\n## Controlling other pages\n\nThe new feature of this release is that page.js can now control other pages (windows) besides the main window. This makes it possible to control an iframe's routing. You can use it by passing the window option to start:\n\n    page('/', function(){\n      // Whoa, I'm inside an iframe!\n    });\n\npage.start({ window: myiFrame.contentWindow });\n\nNote that page is still a singleton, which means you can only have 1 page, so you can't control both an iframe and the main window at the same time.\n\nThis change was made to improve our testing, but in the future we'll make it possible to have multiple page objects so you really will be able to control multiple iframes and the main window all at the same time.\n\n## Better hashbang support\n\nHashbang support has never been very good in page.js. But we're slowly improving it! In 1.8.0 we've fixed the problem where the app's full URL would show up in the hashbang upon start. http://example.com/my/page#!/my/page. Gross! No longer happens thanks to #447.\n\n## Pull Requests\n\nThose are the big things, but here's a list of all of the pull requests merged into 1.8.0:\n\n* [#445] - Prevent hash from being part of the ctx.pathname\n* [#447] - Prevent going to the root when setting up the initial hashchange route\n* [#446] - Add a note about usage with a CDN\n* [#443] - Change test infrastructure to run inside of iframes\n* [#303] - page.exit callback example missing context param\n* [#267] - Added clarification for decoded plus signs in urls\n\n[#445]: https://github.com/visionmedia/page.js/pull/4445\n[#447]: https://github.com/visionmedia/page.js/pull/4447\n[#446]: https://github.com/visionmedia/page.js/pull/4446\n[#443]: https://github.com/visionmedia/page.js/pull/4443\n[#303]: https://github.com/visionmedia/page.js/pull/4303\n[#267]: https://github.com/visionmedia/page.js/pull/4267\n\n1.7.3 / 2018-01-15\n==================\n\nThis is a patch release making an improvement to how page.js works on pages that use the file protocol, such as Electron and nw.js apps.\n\n## Pull Requests\n\n* [#441] - Set the page's base to be the current location when used under the file protocol with hashbang routing.\n\n[#441]: https://github.com/visionmedia/page.js/pull/441\n\n1.7.2 / 2018-01-15\n==================\n\nOur first release in almost 2 years! This is a long overdue patch release that contains various bug fixes that have taken place over the course of the last couple of years. As releases will become much more often in the future (containing only a few fixes in most cases), I will be listing the closed issues in releases, but because there are 2 years worth it is not practical to do so in this release.\n\nWhile you're here, if you haven't checked out page.js in a long time now is a great time. I've recently taken over maintenance and have a plan in place to take this great small library into the future. For now I am concentrating on stabilizing 1.x by fixing as many of the backlog of issues that have built up as I can. Once that is complete we'll start thinking about 2.0.\n\nIf you've submitted a PR here in the past and seen it be ignored, please come back! Your contributions are invaluable, and I promise that as long as I'm maintaining this project I'll do my best to always at least comment on pull requests and try to get them resolved.\n\nThat's all for now! Please report any issues you find in 1.7.2.\n\n1.7.1 / 2016-03-17\n==================\n\n* [#363] - Reinstate shadow DOM fixes which were reverted\n\n[#363]: https://github.com/visionmedia/page.js/issues/363\n\n1.7.0 / 2016-03-12\n==================\n\n* [#284] - Use shadow dom when available ([@mwalid])\n* [#329] - Add type annotations for full closure-compiler advanced optimization support ([@chadkillingsworth])\n* [#328] - Include ctx in page.after example, fixes [#290]() ([@aaronshaf])\n\n[#284]: https://github.com/visionmedia/page.js/issues/284\n[#329]: https://github.com/visionmedia/page.js/issues/329\n[#328]: https://github.com/visionmedia/page.js/issues/328\n[#290]: https://github.com/visionmedia/page.js/issues/290\n[@mwalid]: https://github.com/mwalid\n[@chadkillingsworth]: https://github.com/chadkillingsworth\n[@aaronshaf]: https://github.com/aaronshaf\n\n1.6.4 / 2015-10-09\n==================\n\n* fix wildcard route support (update path-to-regexp to v1.2.1)\n\n1.6.3 / 2015-04-19\n==================\n\n* fix including page.js on server side\n* fix including page.js if the document is already loaded\n* fix bug with click-event in Firefox\n\n1.6.2 / 2015-03-06\n==================\n\n* fix touch support #236\n* fix nw.js support #238\n* fix popstate issue in Safari #213\n\n1.6.1 / 2015-02-16\n==================\n\n* added `page.js` to npm files\n* back button works correct with hash links in Firefox  #218\n\n1.6.0./ 2015-01-27\n==================\n\n* added `page.back` feature #157\n* added `decodeURLComponents` option #187\n* now `ctx.params` is object like in express #203\n* skip route processing if another one is called #172\n* docs improved\n* tests improved\n\n\n1.5.0 / 2014-11-29\n==================\n\n* added page.exit(path, callback[, callback...])\n* added page.redirect(url)\n* fix: ignore links with `download` attribute\n* fix: remove URL encoding before parsing paths\n\n1.4.1 / 2014-11-14\n==================\n\n* fixed: hashbang navigation\n* added hashbang example\n* added tests\n\n1.4.0 / 2014-11-12\n==================\n\n * add hashbang support. Closes #112\n * add page.redirect() method\n * add plugins list to readme\n * add Context#handled option\n * Fix an issue where redirects in dispatch can be overwritten by ctx.save()\n * add support HTML5-History-API polyfill\n * make sameOrigin public\n * update path-to-regexp\n * allow for missing href in anchors.\n * update examples\n\n\n1.3.7 / 2013-09-09\n==================\n\n * fix removal of fragment\n\n1.3.6 / 2013-03-12\n==================\n\n  * fix links with target attribute\n\n1.3.5 / 2013-02-12\n==================\n\n  * fix ctrl/cmd/shift clicks\n\n1.3.4 / 2013-02-04\n==================\n\n  * add tmp .show() dispatch argument\n  * add keywords to component.json\n\n1.3.3 / 2012-12-14\n==================\n\n  * remove + support from path regexps\n\n1.3.2 / 2012-11-26\n==================\n\n  * add explicit \"#\" check\n  * add `window` to `addEventListener` calls\n\n1.3.1 / 2012-09-21\n==================\n\n  * fix: onclick only when e.which == 1\n\n1.3.0 / 2012-08-29\n==================\n\n  * add `page(fn)` support. Closes #27\n  * add component.json\n  * fix tests\n  * fix examples\n\n1.2.1 / 2012-08-02\n==================\n\n  * add transitions example\n  * add exposing of `Context` and `Route` constructors\n  * fix infinite loop issue unhandled paths containing query-strings\n\n1.2.0 / 2012-07-05\n==================\n\n  * add `ctx.pathname`\n  * add `ctx.querystring`\n  * add support for passing a query-string through the dispatcher [ovaillancourt]\n  * add `.defaultPrevented` support, ignoring page.js handling [ovaillancourt]\n\n1.1.3 / 2012-06-18\n==================\n\n  * Added some basic client-side tests\n  * Fixed initial dispatch in Firefox\n  * Changed: no-op on subsequent `page()` calls. Closes #16\n\n1.1.2 / 2012-06-13\n==================\n\n  * Fixed origin portno bug preventing :80 and :443 from working properly\n  * Fixed: prevent cyclic refreshes. Closes #17\n\n1.1.1 / 2012-06-11\n==================\n\n  * Added enterprisejs example\n  * Added: join base for `.canonicalPath`. Closes #12\n  * Fixed `location.origin` usage [fisch42]\n  * Fixed `pushState()` when unhandled\n\n1.1.0 / 2012-06-06\n==================\n\n  * Added `+` support to pathtoRegexp()\n  * Added `page.base(path)` support\n  * Added dispatch option to `page()`. Closes #10\n  * Added `Context#originalPath`\n  * Fixed unhandled links when .base is present. Closes #11\n  * Fixed: `Context#path` to \"/\"\n\n0.0.2 / 2012-06-05\n==================\n\n  * Added `make clean`\n  * Added some mocha tests\n  * Fixed: ignore fragments\n  * Fixed: do not pushState on initial load\n"
  },
  {
    "path": "Makefile",
    "content": "ROLLUP=node_modules/.bin/rollup\nINFOLOG := \\033[34m ▸\\033[0m\n\nall: page.js page.mjs\n.PHONY: all\n\npage.js: index.js\n\t@echo \"$(INFOLOG) Building page.js..\"\n\t@$(ROLLUP) -c rollup.config.js\n\npage.mjs: index.js\n\t@echo \"$(INFOLOG) Building page.mjs..\"\n\t@$(ROLLUP) -c rollup.config.js -f es -o $@\n\nwatch:\n\tfind index.js | entr make page.js\n.PHONY: watch\n\nclean:\n\t@rm page.js page.mjs\n.PHONY: clean\n"
  },
  {
    "path": "Readme.md",
    "content": " ![page router logo](http://f.cl.ly/items/3i3n001d0s1Q031r2q1P/page.png)\n\nTiny Express-inspired client-side router.\n\n [![Build Status](https://travis-ci.org/visionmedia/page.js.svg?branch=master)](https://travis-ci.org/visionmedia/page.js)\n[![Coverage Status](https://coveralls.io/repos/visionmedia/page.js/badge.svg?branch=master)](https://coveralls.io/r/visionmedia/page.js?branch=master)\n[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/visionmedia/page.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)\n\n```js\npage('/', index)\npage('/user/:user', show)\npage('/user/:user/edit', edit)\npage('/user/:user/album', album)\npage('/user/:user/album/sort', sort)\npage('*', notfound)\npage()\n```\n\n## Installation\n\n  There are multiple ways to install `page.js`.\n  With package managers:\n\n  ```bash\n  $ npm install page # for browserify\n  $ component install visionmedia/page.js\n  $ bower install visionmedia/page.js\n  ```\n\n  Or use with a CDN. We support:\n\n  * [cdnjs](https://cdnjs.com/libraries/page.js)\n  * [unpkg](https://unpkg.com/page/page.js)\n\n  Using with global script tags:\n\n  ```html\n  <script src=\"https://unpkg.com/page/page.js\"></script>\n  <script>\n    page('/about', function(){\n      // Do stuff\n    });\n  </script>\n  ```\n\n  Or with modules, in modern browsers:\n\n  ```html\n  <script type=\"module\">\n    import page from \"//unpkg.com/page/page.mjs\";\n\n    page('/home', () => { ... });\n  </script>\n  ```\n\n## Running examples\n\n  To run examples do the following to install dev dependencies and run the example server:\n\n    $ git clone git://github.com/visionmedia/page.js\n    $ cd page.js\n    $ npm install\n    $ node examples\n    $ open http://localhost:4000\n\n Currently we have examples for:\n\n   - `basic` minimal application showing basic routing\n   - `notfound` similar to `basic` with single-page 404 support\n   - `album` showing pagination and external links\n   - `profile` simple user profiles\n   - `query-string` shows how you can integrate plugins using the router\n   - `state` illustrates how the history state may be used to cache data\n   - `server` illustrates how to use the dispatch option to server initial content\n   - `chrome` Google Chrome style administration interface\n   - `transitions` Shows off a simple technique for adding transitions between \"pages\"\n   - `partials` using hogan.js to render mustache partials client side\n\n  __NOTE__: keep in mind these examples do not use jQuery or similar, so\n  portions of the examples may be relatively verbose, though they're not\n  directly related to page.js in any way.\n\n## API\n\n### page(path, callback[, callback ...])\n\n  Defines a route mapping `path` to the given `callback(s)`.\n  Each callback is invoked with two arguments, [context](#context) and `next`. Much like Express invoking next will call the next registered callback with the given path.\n\n```js\npage('/', user.list)\npage('/user/:id', user.load, user.show)\npage('/user/:id/edit', user.load, user.edit)\npage('*', notfound)\n```\n\n  Under certain conditions, links will be disregarded\n  and will not be dispatched, such as:\n\n  - Links that are not of the same origin\n  - Links with the `download` attribute\n  - Links with the `target` attribute\n  - Links with the `rel=\"external\"` attribute\n\n### page(callback)\n\n  This is equivalent to `page('*', callback)` for generic \"middleware\".\n\n### page(path)\n\n  Navigate to the given `path`.\n\n```js\n$('.view').click(function(e){\n  page('/user/12')\n  e.preventDefault()\n})\n```\n\n### page(fromPath, toPath)\n\n  Setup redirect from one path to another.\n\n### page.redirect(fromPath, toPath)\n\n  Identical to `page(fromPath, toPath)`\n\n### page.redirect(path)\n  Calling page.redirect with only a string as the first parameter\n  redirects to another route.\n  Waits for the current route to push state and after replaces it\n  with the new one leaving the browser history clean.\n\n```js\npage('/default', function(){\n  // some logic to decide which route to redirect to\n  if(admin) {\n    page.redirect('/admin');\n  } else {\n    page.redirect('/guest');\n  }\n});\n\npage('/default');\n```\n\n### page.show(path)\n\n  Identical to `page(path)` above.\n\n### page([options])\n\n  Register page's `popstate` / `click` bindings. If you're\n  doing selective binding you'll like want to pass `{ click: false }`\n  to specify this yourself. The following options are available:\n\n  - `click` bind to click events [__true__]\n  - `popstate` bind to popstate [__true__]\n  - `dispatch` perform initial dispatch [__true__]\n  - `hashbang` add `#!` before urls [__false__]\n  - `decodeURLComponents` remove URL encoding from path components (query string, pathname, hash) [__true__]\n  - `window` provide a window to control (by default it will control the main window)\n\n  If you wish to load serve initial content\n  from the server you likely will want to\n  set `dispatch` to __false__.\n\n### page.start([options])\n\n  Identical to `page([options])` above.\n\n### page.stop()\n\n  Unbind both the `popstate` and `click` handlers.\n\n### page.base([path])\n\n  Get or set the base `path`. For example if page.js\n  is operating within `/blog/*` set the base path to \"/blog\".\n\n### page.strict([enable])\n\n  Get or set the strict path matching mode to `enable`. If enabled\n  `/blog` will not match \"/blog/\" and `/blog/` will not match \"/blog\".\n\n### page.exit(path, callback[, callback ...])\n\n  Defines an exit route mapping `path` to the given `callback(s)`.\n\n  Exit routes are called when a page changes, using the context\n  from the previous change. For example:\n\n```js\npage('/sidebar', function(ctx, next) {\n  sidebar.open = true\n  next()\n})\n\npage.exit('/sidebar', function(ctx, next) {\n  sidebar.open = false\n  next()\n})\n```\n\n### page.exit(callback)\n\nEquivalent to `page.exit('*', callback)`.\n\n### page.create([options])\n\nCreate a new page instance with the given options. Options provided\nare the same as provided in `page([options])` above. Use this if you need\nto control multiple windows (like iframes or popups) in addition\nto the main window.\n\n```js\nvar otherPage = page.create({ window: iframe.contentWindow });\notherPage('/', main);\n```\n\n### page.clickHandler\n\nThis is the click handler used by page to handle routing when a user clicks an anchor like `<a href=\"/user/profile\">`. This is exported for those who want to disable the click handling behavior with `page.start({ click: false })`, but still might want to dispatch based on the click handler's logic in some scenarios.\n\n### Context\n\n  Routes are passed `Context` objects, these may\n  be used to share state, for example `ctx.user =`,\n  as well as the history \"state\" `ctx.state` that\n  the `pushState` API provides.\n\n#### Context#save()\n\n  Saves the context using `replaceState()`. For example\n  this is useful for caching HTML or other resources\n  that were loaded for when a user presses \"back\".\n\n#### Context#handled\n\n  If `true`, marks the context as handled to prevent [default 404 behaviour][404].\n  For example this is useful for the routes with interminate quantity of the\n  callbacks.\n\n[404]: https://github.com/visionmedia/page.js#default-404-behaviour\n\n#### Context#canonicalPath\n\n  Pathname including the \"base\" (if any) and query string \"/admin/login?foo=bar\".\n\n#### Context#path\n\n  Pathname and query string \"/login?foo=bar\".\n\n#### Context#querystring\n\n  Query string void of leading `?` such as \"foo=bar\", defaults to \"\".\n\n#### Context#pathname\n\n  The pathname void of query string \"/login\".\n\n#### Context#state\n\n  The `pushState` state object.\n\n#### Context#title\n\n  The `pushState` title.\n\n## Routing\n\n  The router uses the same string-to-regexp conversion\n  that Express does, so things like \":id\", \":id?\", and \"*\" work\n  as you might expect.\n\n  Another aspect that is much like Express is the ability to\n  pass multiple callbacks. You can use this to your advantage\n  to flatten nested callbacks, or simply to abstract components.\n\n### Separating concerns\n\n  For example suppose you have a route to _edit_ users, and a\n  route to _view_ users. In both cases you need to load the user.\n  One way to achieve this is with several callbacks as shown here:\n\n```js\npage('/user/:user', load, show)\npage('/user/:user/edit', load, edit)\n```\n\n  Using the `*` character we can alter this to match all\n  routes prefixed with \"/user\" to achieve the same result:\n\n```js\npage('/user/*', load)\npage('/user/:user', show)\npage('/user/:user/edit', edit)\n```\n\n  Likewise `*` can be used as catch-alls after all routes\n  acting as a 404 handler, before all routes, in-between and\n  so on. For example:\n\n```js\npage('/user/:user', load, show)\npage('*', function(){\n  $('body').text('Not found!')\n})\n```\n\n### Default 404 behaviour\n\n  By default when a route is not matched,\n  page.js invokes `page.stop()` to unbind\n  itself, and proceed with redirecting to the\n  location requested. This means you may use\n  page.js with a multi-page application _without_\n  explicitly binding to certain links.\n\n### Working with parameters and contexts\n\n  Much like `request` and `response` objects are\n  passed around in Express, page.js has a single\n  \"Context\" object. Using the previous examples\n  of `load` and `show` for a user, we can assign\n  arbitrary properties to `ctx` to maintain state\n  between callbacks.\n\n  To build a `load` function that will load\n  the user for subsequent routes you'll need to\n  access the \":id\" passed. You can do this with\n  `ctx.params.NAME` much like Express:\n\n```js\nfunction load(ctx, next){\n  var id = ctx.params.id\n}\n```\n\n  Then perform some kind of action against the server,\n  assigning the user to `ctx.user` for other routes to\n  utilize. `next()` is then invoked to pass control to\n  the following matching route in sequence, if any.\n\n```js\nfunction load(ctx, next){\n  var id = ctx.params.id\n  $.getJSON('/user/' + id + '.json', function(user){\n    ctx.user = user\n    next()\n  })\n}\n```\n\n  The \"show\" function might look something like this,\n  however you may render templates or do anything you\n  want. Note that here `next()` is _not_ invoked, because\n  this is considered the \"end point\", and no routes\n  will be matched until another link is clicked or\n  `page(path)` is called.\n\n```js\nfunction show(ctx){\n  $('body')\n    .empty()\n    .append('<h1>' + ctx.user.name + '<h1>');\n}\n```\n\n  Finally using them like so:\n\n```js\npage('/user/:id', load, show)\n```\n\n**NOTE:** The value of `ctx.params.NAME` is decoded via `decodeURIComponent(sliceOfUrl)`. One exception though is the use of the plus sign (+) in the url, e.g. `/user/john+doe`, which is decoded to a space: `ctx.params.id == 'john doe'`. Also an encoded plus sign (`%2B`) is decoded to a space.\n\n### Working with state\n\n  When working with the `pushState` API,\n  and page.js you may optionally provide\n  state objects available when the user navigates\n  the history.\n\n  For example if you had a photo application\n  and you performed a relatively extensive\n  search to populate a list of images,\n  normally when a user clicks \"back\" in\n  the browser the route would be invoked\n  and the query would be made yet-again.\n\n  An example implementation might look as follows:\n\n```js\nfunction show(ctx){\n  $.getJSON('/photos', function(images){\n    displayImages(images)\n  })\n}\n```\n\n   You may utilize the history's state\n   object to cache this result, or any\n   other values you wish. This makes it\n   possible to completely omit the query\n   when a user presses back, providing\n   a much nicer experience.\n\n```js\nfunction show(ctx){\n  if (ctx.state.images) {\n    displayImages(ctx.state.images)\n  } else {\n    $.getJSON('/photos', function(images){\n      ctx.state.images = images\n      ctx.save()\n      displayImages(images)\n    })\n  }\n}\n```\n\n  __NOTE__: `ctx.save()` must be used\n  if the state changes _after_ the first\n  tick (xhr, setTimeout, etc), otherwise\n  it is optional and the state will be\n  saved after dispatching.\n\n### Matching paths\n\n  Here are some examples of what's possible\n  with the string to `RegExp` conversion.\n\n  Match an explicit path:\n\n```js\npage('/about', callback)\n```\n\n  Match with required parameter accessed via `ctx.params.name`:\n\n```js\npage('/user/:name', callback)\n```\n\n  Match with several params, for example `/user/tj/edit` or\n  `/user/tj/view`.\n\n```js\npage('/user/:name/:operation', callback)\n```\n\n  Match with one optional and one required, now `/user/tj`\n  will match the same route as `/user/tj/show` etc:\n\n```js\npage('/user/:name/:operation?', callback)\n```\n\n  Use the wildcard char `*` to match across segments,\n  available via `ctx.params[N]` where __N__ is the\n  index of `*` since you may use several. For example\n  the following will match `/user/12/edit`, `/user/12/albums/2/admin`\n  and so on.\n\n```js\npage('/user/*', loadUser)\n```\n\n  Named wildcard accessed, for example `/file/javascripts/jquery.js`\n  would provide \"/javascripts/jquery.js\" as `ctx.params.file`:\n\n```js\npage('/file/:file(.*)', loadUser)\n```\n\n  And of course `RegExp` literals, where the capture\n  groups are available via `ctx.params[N]` where __N__\n  is the index of the capture group.\n\n```js\npage(/^\\/commits\\/(\\d+)\\.\\.(\\d+)/, loadUser)\n```\n\n## Plugins\n\n  An example plugin _examples/query-string/query.js_\n  demonstrates how to make plugins. It will provide a parsed `ctx.query` object\n  derived from [node-querystring](https://github.com/visionmedia/node-querystring).\n\n  Usage by using \"*\" to match any path\n  in order to parse the query-string:\n\n```js\npage('*', parse)\npage('/', show)\npage()\n\nfunction parse(ctx, next) {\n  ctx.query = qs.parse(location.search.slice(1));\n  next();\n}\n\nfunction show(ctx) {\n  if (Object.keys(ctx.query).length) {\n    document\n      .querySelector('pre')\n      .textContent = JSON.stringify(ctx.query, null, 2);\n  }\n}\n```\n\n### Available plugins\n\n- [querystring](https://github.com/visionmedia/page.js/blob/master/examples/query-string/query.js): provides a parsed `ctx.query` object derived from [node-querystring](https://github.com/visionmedia/node-querystring).\n- [body-parser](https://github.com/kethinov/page.js-body-parser.js): provides a `req.body` object for routes derived from [body-parser](https://github.com/expressjs/body-parser).\n- [express-mapper](https://github.com/kethinov/page.js-express-mapper.js): provides a direct imitation of the [Express](http://expressjs.com/) API so you can share controller code on the client and the server with your Express application without modification.\n\nPlease submit pull requests to add more to this list.\n\n### Running tests\n\nIn the console:\n\n```\n$ npm install\n$ npm test\n```\n\nIn the browser:\n\n```\n$ npm install\n$ npm run serve\n$ open http://localhost:3000/\n```\n\n### Support in IE8+\n\nIf you want the router to work in older version of Internet Explorer that don't support pushState, you can use the [HTML5-History-API](https://github.com/devote/HTML5-History-API) polyfill:\n```bash\n  npm install html5-history-api\n```\n\n##### How to use a Polyfill together with router (OPTIONAL):\nIf your web app is located within a nested basepath, you will need to specify the `basepath` for the HTML5-History-API polyfill.\nBefore calling `page.base()` use: `history.redirect([prefixType], [basepath])` - Translation link if required.\n  * `prefixType`: `[string|null]` - Substitute the string after the anchor (#) by default \"/\".\n  * `basepath`: `[string|null]` - Set the base path. See `page.base()` by default \"/\". (Note: Slash after `pathname` required)\n\n### Pull Requests\n\n  * Break commits into a single objective.\n  * An objective should be a chunk of code that is related but requires explanation.\n  * Commits should be in the form of what-it-is: how-it-does-it and or why-it's-needed or what-it-is for trivial changes\n  * Pull requests and commits should be a guide to the code.\n\n## Server configuration\n\n  In order to load and update any URL managed by page.js, you need to configure your environment to point to your project's main file (index.html, for example) for each non-existent URL. Below you will find examples for most common server scenarios.\n\n### Nginx\n\nIf using Nginx, add this to the .conf file related to your project (inside the \"server\" part), and **reload** your Nginx server:\n\n```nginx\nlocation / {\n    try_files $uri $uri/ /index.html?$args;\n}\n```\n\n### Apache\n\nIf using Apache, create (or add to) the `.htaccess` file in the root of your public folder, with the code:\n\n```apache\nOptions +FollowSymLinks\nRewriteEngine On\n\nRewriteCond %{SCRIPT_FILENAME} !-d\nRewriteCond %{SCRIPT_FILENAME} !-f\n\nRewriteRule ^.*$ ./index.html\n```\n\n### Node.js - Express\n\nFor development and/or production, using **Express**, you need to use `express-history-api-fallback` package. An example:\n\n```js\nimport { join } from 'path';\nimport express from 'express';\nimport history from 'express-history-api-fallback';\n\nconst app = express();\nconst root = join(__dirname, '../public');\n\napp.use(express.static(root));\napp.use(history('index.html', { root }));\n\nconst server = app.listen(process.env.PORT || 3000);\n\nexport default server;\n```\n\n### Node.js - Browsersync\n\nFor development using **Browsersync**, you need to use `history-api-fallback` package. An example:\n\n```js\nvar browserSync = require(\"browser-sync\").create();\nvar historyApiFallback = require('connect-history-api-fallback');\n\nbrowserSync.init({\n\tfiles: [\"*.html\", \"css/*.css\", \"js/*.js\"],\n\tserver: {\n\t\tbaseDir: \".\",\n\t\tmiddleware: [ historyApiFallback() ]\n\t},\n\tport: 3030\n});\n```\n\n## Integrations\n\n## License\n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk &lt;tj@vision-media.ca&gt;\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "bower.json",
    "content": "{\n  \"name\": \"page\",\n  \"description\": \"Tiny client-side router\",\n  \"keywords\": [\"page\", \"route\", \"router\", \"routes\", \"pushState\"],\n  \"main\": \"page.js\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git://github.com/visionmedia/page.js\"\n  },\n  \"ignore\": [\n    \".gitignore\",\n    \".npmignore\",\n    \".travis.yml\",\n    \"component.json\",\n    \"examples\",\n    \"History.md\",\n    \"Makefile\",\n    \"package.json\",\n    \"Readme.md\",\n    \"test\"\n  ],\n  \"license\": \"MIT\"\n}\n"
  },
  {
    "path": "component.json",
    "content": "{\n  \"name\": \"page\",\n  \"repo\": \"visionmedia/page.js\",\n  \"version\": \"1.6.4\",\n  \"description\": \"Tiny client-side router\",\n  \"keywords\": [\"page\", \"route\", \"router\", \"routes\", \"pushState\"],\n  \"scripts\": [\"index.js\"],\n  \"license\": \"MIT\",\n  \"dependencies\": {\n    \"pillarjs/path-to-regexp\": \"v1.2.1\"\n  }\n}\n"
  },
  {
    "path": "examples/album/app.js",
    "content": "var perPage = 6\n  , prev = document.querySelector('#prev')\n  , next = document.querySelector('#next');\n\npage.base('/album');\npage('/', '/photos/0');\npage('/photos/:page', photos)\npage('*', notfound);\npage();\n\nfunction photos(ctx) {\n  var page = ~~ctx.params.page;\n  var from = page * perPage;\n  var to = from + perPage;\n  console.log('showing page %s : %s..%s', page, from, to);\n  var photos = images.slice(from, to);\n  display(photos);\n  adjustPager(page);\n}\n\nfunction notfound() {\n  document.querySelector('p')\n    .textContent = 'not found';\n}\n\nfunction display(photos) {\n  var el = document.querySelector('#photos');\n  el.innerHTML = '';\n  photos.forEach(function(photo){\n    var img = document.createElement('img');\n    img.src = photo;\n    el.appendChild(img);\n  });\n}\n\nfunction adjustPager(page) {\n  if (page) {\n    prev.style.display = 'inline-block';\n    prev.setAttribute('href', '/album/photos/' + (page - 1));\n  } else {\n    prev.style.display = 'none';\n  }\n\n  next.setAttribute('href', '/album/photos/' + (page + 1));\n}\n\nvar images = [\n    'http://upload.wikimedia.org/wikipedia/en/7/76/Grim_Fandango_artwork.jpg'\n  , 'http://www.xblafans.com/wp-content/uploads//2011/08/Grim-Fandango1.jpg'\n  , 'http://media.giantbomb.com/uploads/0/1371/190604-grimfandango106_super.jpg'\n  , 'http://gamejunkienz.files.wordpress.com/2012/02/grimfandango.jpg'\n  , 'http://onlyhdwallpapers.com/wallpaper/video_games_grim_fandango_lucas_arts_desktop_1024x768_wallpaper-305343.jpg'\n  , 'http://lparchive.org/Grim-Fandango-(Screenshot)/Update%207/02176.gif'\n  , 'http://bulk2.destructoid.com/ul/128679-GrimFandangoActionFigures.jpg'\n  , 'http://www.gamasutra.com/features/20061103/grimfandango02.jpg'\n  , 'http://metavideogame.files.wordpress.com/2011/05/grimhof_03_1081459316.jpg'\n  , 'http://3.bp.blogspot.com/_zBnIHQUy4r4/SpxdDw1Z8tI/AAAAAAAABJM/FoCWfc8imnc/s400/GrimFandango1024x768.jpg'\n  , 'http://www.deviantart.com/download/184571597/grim_fandango_by_domigorgon-d31w0ct.jpg'\n  , 'http://vgboxart.com/boxes/PC/29535-grim-fandango.png?t=1243105773'\n  , 'http://kastatic.com/i2/games/1/3/13230/10.png'\n  , 'http://www.thunderboltgames.com/s/img600/grimfandango.jpg'\n  , 'http://i2.listal.com/image/1425291/936full-grim-fandango-artwork.jpg'\n  , 'http://www.xblafans.com/wp-content/uploads//2011/08/Grim-Fandango1.jpg'\n  , 'http://media.giantbomb.com/uploads/0/1371/190604-grimfandango106_super.jpg'\n  , 'http://gamejunkienz.files.wordpress.com/2012/02/grimfandango.jpg'\n  , 'http://onlyhdwallpapers.com/wallpaper/video_games_grim_fandango_lucas_arts_desktop_1024x768_wallpaper-305343.jpg'\n  , 'http://lparchive.org/Grim-Fandango-(Screenshot)/Update%207/02176.gif'\n  , 'http://bulk2.destructoid.com/ul/128679-GrimFandangoActionFigures.jpg'\n  , 'http://www.gamasutra.com/features/20061103/grimfandango02.jpg'\n  , 'http://metavideogame.files.wordpress.com/2011/05/grimhof_03_1081459316.jpg'\n  , 'http://3.bp.blogspot.com/_zBnIHQUy4r4/SpxdDw1Z8tI/AAAAAAAABJM/FoCWfc8imnc/s400/GrimFandango1024x768.jpg'\n  , 'http://www.deviantart.com/download/184571597/grim_fandango_by_domigorgon-d31w0ct.jpg'\n  , 'http://vgboxart.com/boxes/PC/29535-grim-fandango.png?t=1243105773'\n  , 'http://kastatic.com/i2/games/1/3/13230/10.png'\n  , 'http://www.thunderboltgames.com/s/img600/grimfandango.jpg'\n  , 'http://i2.listal.com/image/1425291/936full-grim-fandango-artwork.jpg'\n  , 'http://www.xblafans.com/wp-content/uploads//2011/08/Grim-Fandango1.jpg'\n  , 'http://media.giantbomb.com/uploads/0/1371/190604-grimfandango106_super.jpg'\n  , 'http://gamejunkienz.files.wordpress.com/2012/02/grimfandango.jpg'\n  , 'http://onlyhdwallpapers.com/wallpaper/video_games_grim_fandango_lucas_arts_desktop_1024x768_wallpaper-305343.jpg'\n  , 'http://lparchive.org/Grim-Fandango-(Screenshot)/Update%207/02176.gif'\n  , 'http://bulk2.destructoid.com/ul/128679-GrimFandangoActionFigures.jpg'\n  , 'http://www.gamasutra.com/features/20061103/grimfandango02.jpg'\n  , 'http://metavideogame.files.wordpress.com/2011/05/grimhof_03_1081459316.jpg'\n  , 'http://3.bp.blogspot.com/_zBnIHQUy4r4/SpxdDw1Z8tI/AAAAAAAABJM/FoCWfc8imnc/s400/GrimFandango1024x768.jpg'\n  , 'http://www.deviantart.com/download/184571597/grim_fandango_by_domigorgon-d31w0ct.jpg'\n  , 'http://vgboxart.com/boxes/PC/29535-grim-fandango.png?t=1243105773'\n  , 'http://kastatic.com/i2/games/1/3/13230/10.png'\n  , 'http://www.thunderboltgames.com/s/img600/grimfandango.jpg'\n  , 'http://i2.listal.com/image/1425291/936full-grim-fandango-artwork.jpg'\n];\n"
  },
  {
    "path": "examples/album/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>Album</title>\n    <script src=\"/page.js\"></script>\n    <link rel=\"stylesheet\" href=\"/album/style.css\" />\n  </head>\n  <body>\n    <h1>Album</h1>\n    <p></p>\n    <ul id=\"photos\"></ul>\n    <div id=\"pager\">\n      <a id=\"prev\" href=\"/\">prev</a>\n      <a id=\"next\" href=\"/\">next</a>\n    </div>\n    <p>View more <a href=\"https://www.google.com/search?q=grim+fandango\">Grim Fandango</a> photos.</p>\n    <script src=\"/album/app.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/album/style.css",
    "content": "body {\n  padding: 50px;\n  font: 200 16px \"Helvetica Neue\", Helvetica, Arial;\n}\n\nh1 {\n  font-weight: 300;\n}\n\na {\n  color: #036dff;\n  text-decoration: none;\n}\n\na:hover {\n  text-decoration: underline;\n}\n\nimg {\n  margin: 5px;\n  width: 150px;\n  height: 100px;\n}"
  },
  {
    "path": "examples/basic/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>Basic</title>\n    <script src=\"/page.js\"></script>\n    <base href=\"/basic/\" >\n  </head>\n  <body>\n    <h1>Basic</h1>\n    <p></p>\n    <ul>\n      <li><a href=\"./\">/</a></li>\n      <li><a href=\"#whoop\">#whoop</a></li>\n      <li><a href=\"./about\">/about</a></li>\n      <li><a href=\"./contact\">/contact</a></li>\n      <li><a href=\"./contact/me\">/contact/me</a></li>\n      <li><a href=\"./not-found?foo=bar\">/not-found</a></li>\n    </ul>\n\n    <script>\n      // the \"notfound\" implements a catch-all\n      // with page('*', notfound). Here we have\n      // no catch-all, so page.js will redirect\n      // to the location of paths which do not\n      // match any of the following routes\n      //\n      page.base('/basic');\n\n      page('/', index);\n      page('/about', about);\n      page('/contact', contact);\n      page('/contact/:contactName', contact);\n      page();\n\n      function index() {\n        document.querySelector('p')\n          .textContent = 'viewing index';\n      }\n\n      function about() {\n        document.querySelector('p')\n          .textContent = 'viewing about';\n      }\n\n      function contact(ctx) {\n        document.querySelector('p')\n          .textContent = 'viewing contact ' + (ctx.params.contactName || '');\n      }\n    </script>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/chrome/chrome.css",
    "content": "\n* {\n  -webkit-box-sizing: border-box;\n  box-sizing: border-box;\n}\n\naside {\n  float: left;\n  width: 120px;\n}\n\nbody {\n  margin: 0;\n  font: 16px Helvetica, \"Helvetica Neue\", Arial, sans-serif;\n  color: #5C6166;\n}\n\nh1,h2,h3 {\n  margin: 0;\n  font-weight: normal;\n}\n\nh1 {\n  font-size: 18px;\n  font-weight: 100;\n  margin: 20px;\n}\n\nnav ul {\n  margin: 0;\n  padding: 0;\n}\n\nnav ul li {\n  list-style: none;\n  margin: 5px 0;\n  padding: 0;\n  padding-left: 15px;\n  border-color: white;\n  -webkit-transition: border-left 400ms;\n  -moz-transition: border-left 400ms;\n}\n\nnav ul li.active {\n  border-left: 5px solid #5C6166;\n  padding-left: 10px;\n}\n\nnav ul li.active a {\n  color: #5C6166;\n}\n\nnav ul li a {\n  font-size: 13px;\n  text-decoration: none;\n  color: #999;\n  font-weight: 100;\n}\n\n#content {\n  padding: 20px;\n  width: 500px;\n  float: left;\n  font-size: 14px;\n  font-weight: 100;\n  opacity: 1;\n  margin-left: 0;\n  -webkit-transition: opacity 200ms, margin-left 300ms;\n  -moz-transition: opacity 200ms, margin-left 300ms;\n}\n\n#content.hide {\n  opacity: 0;\n  margin-left: -40px;\n}\n\nh2 {\n  font-weight: normal;\n  letter-spacing: 1px;\n  font-size: 18px;\n  border-bottom: 1px solid #eee;\n}"
  },
  {
    "path": "examples/chrome/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>Basic</title>\n    <link rel=\"stylesheet\" href=\"/chrome/chrome.css\" type=\"text/css\">\n    <script src=\"/page.js\"></script>\n  </head>\n  <body>\n    <aside>\n      <h1>Chrome</h1>\n      <nav>\n        <ul>\n          <li><a href=\"./\">History</a></li>\n          <li><a href=\"./extensions\">Extensions</a></li>\n          <li><a href=\"./settings\">Settings</a></li>\n        </ul>\n      </nav>\n    </aside>\n\n    <section id=\"content\"></section>\n\n    <script id=\"settings-template\" type=\"text/x-template\">\n      <h2>Settings</h2>\n      <p>The default browser is currently Google Chrome.</p>\n    </script>\n\n    <script id=\"extensions-template\" type=\"text/x-template\">\n      <h2>Extensions</h2>\n      <p>You currently have no browser extensions installed.</p>\n    </script>\n\n    <script id=\"history-template\" type=\"text/x-template\">\n      <h2>History</h2>\n      <p>Your browsing history will display here.</p>\n    </script>\n\n    <script id=\"not-found-template\" type=\"text/x-template\">\n      <h2>Not Found</h2>\n      <p>Sorry! I cannot find that page.</p>\n    </script>\n\n    <script>\n      page.base('/chrome');\n      page('*', showActiveLink);\n      page('/', showHistory);\n      page('/extensions', showExtensions);\n      page('/settings', showSettings);\n      page('*', notfound);\n      page();\n\n      function showActiveLink(ctx, next) {\n        deactiveate();\n        a(ctx.path).parentNode.classList.add('active');\n        next();\n      }\n\n      function showHistory(ctx) {\n        // !ctx.init tells render() not to\n        // add the .hide class so that the\n        // transition animation is ignored\n        // for the initial page\n        render(template('history'), !ctx.init);\n      }\n      \n      function showExtensions(ctx) {\n        render(template('extensions'), !ctx.init);\n      }\n\n      function showSettings(ctx) {\n        render(template('settings'), !ctx.init);\n      }\n\n      function notfound(ctx) {\n        render(template('not-found'), !ctx.init);\n      }\n\n      function render(html, hide) {\n        var el = document.getElementById('content');\n        if (hide) {\n          el.classList.add('hide');\n          setTimeout(function(){\n            el.innerHTML = html;\n            el.classList.remove('hide');\n          }, 300);\n        } else {\n          el.innerHTML = html;\n        }\n      }\n\n      function deactiveate() {\n        var el = document.querySelector('.active')\n        if (el) el.classList.remove('active');\n      }\n\n      function a(href) {\n        return document.querySelector('[href=\".' + href + '\"]');\n      }\n\n      function template(name) {\n        return document\n          .getElementById(name + '-template')\n          .innerHTML;\n      }\n    </script>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/enterprisejs/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>EnterpriseJS</title>\n    <script src=\"/page.js\"></script>\n  </head>\n  <body>\n    <h1>EnterpriseJS</h1>\n    <p></p>\n    <ul>\n      <li><a href=\"./\">/</a></li>\n      <li><a href=\"./about\">/about</a></li>\n      <li><a href=\"./contact\">/contact</a></li>\n    </ul>\n\n    <script>\n      // if you're scared by non-\"classes\":\n\n      function Router(obj) {\n        var self = this;\n        page.base('/enterprisejs');\n\n        // define routes\n        for (var key in obj) {\n          if ('string' == typeof obj[key]) {\n            ;(function(route, fn){\n              page(key, function(){\n                fn.apply(self, arguments);\n              });\n            })(key, obj[obj[key]]);\n          }\n        }\n\n        this.render = function(text){\n          document.querySelector('p').textContent = text;\n        };\n\n        this.start = page;\n      }\n\n      var router = new Router({\n        '/': 'index',\n        '/about': 'about',\n        '/contact': 'contact',\n        index: function(){ this.render('viewing index') },\n        about: function(){ this.render('viewing about') },\n        contact: function(){ this.render('viewing contact') }\n      }).start();\n\n    </script>\n  </body>\n</html>"
  },
  {
    "path": "examples/hash/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>Hash</title>\n    <style>\n      body p {\n        color: #333;\n        font-family: verdana;\n      }\n      #sections p {\n        height: 500px;\n        margin: 30px;\n        padding: 30px;\n        line-height: 40px;\n        background-color: #eee;\n        border: 1px solid #ccb;\n        font-size: 30px;\n      }\n\n      #sections p a {\n        display: block;\n        float: right;\n        font-size: 14px;\n      }\n\n    </style>\n    <script src=\"/page.js\"></script>\n  </head>\n  <body>\n    <h1 id=\"top\">Hash</h1>\n\n    <ul>\n      <li><a href=\"#\">#</a></li>\n      <li><a href=\"#subsection\">#subsection</a></li>\n      <li><a href=\"section?name=tana\">section?name=tana</a></li>\n      <li><a href=\"section?name=tana#subsection\">section?name=tana#subsection</a></li>\n    </ul>\n\n    <div id=\"sections\">\n      <p><strong>A</strong><a href=\"#top\">top</a></p>\n      <p><strong>B</strong><a href=\"#top\">top</a></p>\n      <p id=\"subsection\"><strong>C</strong><a href=\"#top\">top</a></p>\n    </div>\n\n    <script>\n      page.base('/hash');\n      page('/:section', section);\n      page();\n\n      function section(ctx, next) {\n        console.log('path: ', ctx.path);\n        console.log('querystring: ', ctx.querystring);\n        console.log('hash: ', ctx.hash);\n        console.log(' ');\n      }\n    </script>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/hashbang/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>Hashbang</title>\n    <script src=\"/page.js\"></script>\n    <base href=\"/hashbang/\">\n  </head>\n  <body>\n    <h1>Hashbang</h1>\n    <p></p>\n    <ul>\n      <li><a href=\"./\">/</a></li>\n      <li><a href=\"#whoop\">#whoop</a></li>\n      <li><a href=\"./about\">/about</a></li>\n      <li><a href=\"./contact\">/contact</a></li>\n      <li><a href=\"./contact/me\">/contact/me</a></li>\n      <li><a href=\"./not-found?foo=bar\">/not-found</a></li>\n    </ul>\n\n    <script>\n      page.base('/hashbang');\n      page('/', index);\n      page('/about', about);\n      page('/contact', contact);\n      page('/contact/:contactName', contact);\n      page({\n        hashbang:true\n      });\n\n      function index() {\n        document.querySelector('p')\n          .textContent = 'viewing index';\n      }\n\n      function about() {\n        document.querySelector('p')\n          .textContent = 'viewing about';\n      }\n\n      function contact(ctx) {\n        document.querySelector('p')\n          .textContent = 'viewing contact ' + (ctx.params.contactName || '');\n      }\n    </script>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/index.js",
    "content": "\n/**\n * Module dependencies.\n */\n\nvar express = require('express')\n  , join = require('path').join\n  , fs = require('fs');\n\nvar app = express();\n\n\n// deprecated express methods\n// app.use(express.favicon());\n// app.use(express.logger('dev'));\n\napp.set('views', __dirname);\napp.set('view engine', 'jade');\napp.enable('strict routing');\n\n// load examples\n\nvar examples = fs.readdirSync(__dirname).filter(function(file){\n  return fs.statSync(__dirname + '/' + file).isDirectory();\n});\n\n// routes\n\n/**\n * GET page.js\n */\n\napp.get('/page.js', function(req, res){\n  res.sendFile(join(__dirname, '..', 'page.js'));\n});\n\n/**\n * GET test libraries.\n */\n\napp.get(/^\\/(mocha|chai)\\.(css|js)$/i, function(req, res){\n  res.sendFile(join(__dirname, '../test/', req.params.join('.')));\n});\n\n/**\n * GET list of examples.\n */\n\napp.get('/', function(req, res){\n  res.render('list', { examples: examples });\n});\n\n/**\n * GET /:example -> /:example/\n */\n\napp.get('/:example', function(req, res){\n  res.redirect('/' + req.params.example + '/');\n});\n\n/**\n * GET /:example/* as a file if it exists.\n */\n\napp.get('/:example/:file(*)', function(req, res, next){\n  var file = req.params.file;\n  if (!file) return next();\n  var name = req.params.example;\n  var path = join(__dirname, name, file);\n  fs.stat(path, function(err, stat){\n    if (err) return next();\n    res.sendFile(path);\n  });\n});\n\n/**\n * GET /:example/* as index.html\n */\n\napp.get('/:example/*', function(req, res){\n  var name = req.params.example;\n  res.sendFile(join(__dirname, name, 'index.html'));\n});\n\napp.listen(4000);\nconsole.log('Example server listening on port 4000');\n"
  },
  {
    "path": "examples/list.jade",
    "content": "doctype html\nhtml\n  head\n    title page.js examples\n  body\n    h1 Examples\n    ul\n      for name in examples\n        li\n          a(href='/#{name}')= name\n          if ('hash' == name)\n            span\n              |  -\n              a(href=\"/hash/section?query=string\") section\n            span\n              |  -\n              a(href=\"/hash/section?query=string#subsection\") subsection\n"
  },
  {
    "path": "examples/notfound/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>Not Found</title>\n    <script src=\"/page.js\"></script>\n  </head>\n  <body>\n    <h1>Not Found</h1>\n    <p></p>\n    <ul>\n      <li><a href=\"./\">/</a></li>\n      <li><a href=\"./about\">/about</a></li>\n      <li><a href=\"./contact\">/contact</a></li>\n      <li><a href=\"./not-found\">/not-found</a></li>\n    </ul>\n\n    <script>\n      page.base('/notfound');\n      page('/', index);\n      page('/about', about);\n      page('/contact', contact);\n      page('*', notfound);\n      page();\n\n      function index() {\n        document.querySelector('p')\n          .textContent = 'viewing index';\n      }\n      \n      function about() {\n        document.querySelector('p')\n          .textContent = 'viewing about';\n      }\n\n      function contact() {\n        document.querySelector('p')\n          .textContent = 'viewing contact';\n      }\n\n      function notfound() {\n        document.querySelector('p')\n          .textContent = 'not found';\n      }\n    </script>\n  </body>\n</html>"
  },
  {
    "path": "examples/partials/app.js",
    "content": "\npage.base(location.pathname.replace('/partials/', ''));\npage('*', init.ctx);\npage('/partials/home', route.home);\npage('/partials/portfolio', route.portfolio);\npage('/partials/about', route.about);\npage('/partials/test', route.test);\npage('/partials/examples', route.examples);\npage('*', render.content);\npage();\n"
  },
  {
    "path": "examples/partials/index.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" />\n  <title>page.js partials</title>\n  <link href=\"public/css/style.css\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />\n\n  <script src=\"http://cdnjs.cloudflare.com/ajax/libs/hogan.js/2.0.0/hogan.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n  <script src=\"http://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n\n  <script src=\"/page.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n\n  <script src=\"public/js/events.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n  <script src=\"routes/index.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n  <script src=\"app.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n</head>\n<body>\n<div class=\"shell\">\n\n  <nav id=\"navigation\">\n    <ul>\n      <li><a href=\"home\">home</a></li>\n      <li><a href=\"portfolio\">portfolio</a></li>\n      <li><a href=\"about\">about</a></li>\n    </ul>\n    <ul>\n      <li><a href=\"test\">show tests</a></li>\n      <li><a href=\"examples\">back to examples index</a></li>\n    </ul>\n  </nav>\n  <section id=\"content\">\n    \n  </section>\n\n</div>\n</body>\n</html>\n"
  },
  {
    "path": "examples/partials/public/css/style.css",
    "content": "* { margin: 0; padding: 0; outline: 0; }\n\nbody { font-family: Arial, Helvetica, Sans-Serif; }\n\n\n.shell { width: 800px; margin: 0 auto; }\n\n#navigation { height: 100%; overflow: hidden; }\n#navigation ul { list-style: none; display: inline-block; padding: 20px 0; }\n#navigation li { display: inline; font-size: 16px; line-height: 19px; padding-right: 10px; }\n#navigation li.active a { color: #c06; }\n#navigation a { display: inline-block; color: #39f; text-decoration: none; }\n#navigation ul:last-child { float: right; }\n#navigation ul:first-child { float: none; }\n"
  },
  {
    "path": "examples/partials/public/js/events.js",
    "content": "\n$(function () {\n  var navLinks = $('#navigation li');\n\n  $('#navigation a').on('click', function (e) {\t\n    changeActive(navLinks.index(this));\n  });\n\n  window.changeActive = function (index) {\n    navLinks.removeClass('active').eq(index).addClass('active');\n  }\n});\n"
  },
  {
    "path": "examples/partials/routes/index.js",
    "content": "\n(function () {\n  // private api\n\n  var cache = {};\n\n  function get (url, cb) {\n    if (cache[url]) return cb(cache[url]);\n    $.ajax({\n      url: url,\n      success: function(data) {\n        cache[url] = data;\n        cb(data);\n      },\n      error: function(jqXHR, textStatus, errorThrown) {\n        console.log(jqXHR, textStatus, errorThrown);\n      },\n      dataType: 'text'\n    });\n  }\n\n  // public api\n\n  window.init = {\n    ctx: function (ctx, next) {\n      ctx.data = {};\n      ctx.partials = {};\n      next();\n    }\n  };\n\n  window.route = {\n    home: function (ctx, next) {\n      get('views/home.html', function (html) {\n        ctx.data.index = 0;\n        ctx.partials.content = html;\n        next();\n      });\n    },\n    portfolio: function (ctx, next) {\n      get('views/portfolio.html', function (html) {\n        ctx.data.index = 1;\n        ctx.partials.content = html;\n        next();\n      });\n    },\n    about: function (ctx, next) {\n      get('views/about.html', function (html) {\n        ctx.data.index = 2;\n        ctx.partials.content = html;\n        next();\n      });\n    },\n    test: function (ctx, next) {\n      window.location.href = 'http://localhost:4000/partials/test/';\n    },\n    examples: function (ctx, next) {\n      window.location.href = 'http://localhost:4000/';\n    }\n  };\n\n  window.render = {\n    content: function (ctx, next) {\n      get('views/content.html', function (html) {\n        var template = Hogan.compile(html),\n          content = template.render(ctx.data, ctx.partials);\n        //\n        $('#content').empty().append(content);\n        changeActive(ctx.data.index);\n        if (typeof done === 'function') done(ctx.data.index);\n      });\n    }\n  };\n\n  window.done = null;\n}());\n"
  },
  {
    "path": "examples/partials/test/index.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" />\n  <title>page.js partials tests</title>\n  <link href=\"../public/css/style.css\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />\n  <link href=\"/mocha.css\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />\n  <!-- test libs -->\n  <script src=\"/mocha.js\"></script>\n  <script src=\"/chai.js\"></script>\n  <!-- test files -->\n  <script src=\"tests.js\"></script>\n</head>\n<body>\n  <nav id=\"navigation\">\n    <ul>\n      <li><a href=\"/partials\">back to partials example</a></li>\n      <li><a href=\"/\">back to examples index</a></li>\n    </ul>\n  </nav>\n  <iframe src=\"../index.html\" id=\"site\"></iframe>\n  <div id=\"mocha\"></div>\n</body>\n</html>\n"
  },
  {
    "path": "examples/partials/test/tests.js",
    "content": "\nvar expect = chai.expect;\nmocha.setup({\n  ui: 'bdd',\n  globals: ['']\n});\n\nvar site = null;\nwindow.addEventListener('load', function (e) {\n  site = document.getElementById('site');\n  mocha.run();\n});\n\ndescribe('site', function () {\n  function expected (index, idx, header) {\n    expect(index).to.equal(idx);\n    var h = site.contentDocument.querySelector('#content h1');\n    expect(h.innerHTML).to.equal(header);\n    var p = site.contentDocument.querySelector('#content p');\n    expect(p.innerHTML).to.equal('page '+index);\n  }\n  \n  it('should load home page', function (done) {\n    site.contentWindow.done = function (index) {\n      expected(index, 0, 'Home');\n      done();\n    }\n    site.contentWindow.page('/partials/home');\n  });\n  it('should load portfolio page', function (done) {\n    site.contentWindow.done = function (index) {\n      expected(index, 1, 'Portfolio');\n      done();\n    }\n    site.contentWindow.page('/partials/portfolio');\n  });\n  it('should load about page', function (done) {\n    site.contentWindow.done = function (index) {\n      expected(index, 2, 'About');\n      done();\n    }\n    site.contentWindow.page('/partials/about');\n  });\n\n  after(function (done) {\n    site.contentWindow.done = null;\n    done();\n  });\n});\n"
  },
  {
    "path": "examples/partials/views/about.html",
    "content": "<h1>About</h1>\n<p>page {{index}}</p>"
  },
  {
    "path": "examples/partials/views/content.html",
    "content": "{{>content}}"
  },
  {
    "path": "examples/partials/views/home.html",
    "content": "<h1>Home</h1>\n<p>page {{index}}</p>"
  },
  {
    "path": "examples/partials/views/portfolio.html",
    "content": "<h1>Portfolio</h1>\n<p>page {{index}}</p>"
  },
  {
    "path": "examples/profile/app.js",
    "content": "\nvar avatars = {\n  glottis: 'http://homepage.ntlworld.com/stureek/images/glottis03.jpg',\n  manny: 'http://kprojekt.net/wp-content/uploads/manny.jpg',\n  sal: 'http://homepage.ntlworld.com/stureek/images/sal01.jpg'\n};\n\npage.base('/profile');\npage('/', index);\n// display the index page again after 5s\n// only for user related pages\npage('/user/*', displayIndexAfter(5000));\n// you dont need to use two,\n// but this demonstrates how\n// you can \"filter\" requests\n// then move on to the next callback\n// to separate concerns\npage('/user/:name', load);\npage('/user/:name', show);\n// or:\n// page('/user/:name', load, show);\npage('*', notfound);\npage();\n\n// everything below is not part of page.js\n// just callbacks etc..\n\ndocument.querySelector('#cycle').onclick = function(e){\n  var i = 0;\n  var names = Object.keys(avatars);\n  setInterval(function(){\n    var name = names[i++ % names.length];\n    page('/user/' + name);\n  }, 1500);\n};\n\nfunction text(str) {\n  document.querySelector('p').textContent = str;\n}\n\nfunction displayIndexAfter(ms) {\n  var id;\n  return function(ctx, next){\n    id && clearTimeout(id);\n\n    if ('/' != ctx.path) {\n      id = setTimeout(function(){\n        page('/');\n      }, ms);\n    }\n    next();\n  }\n}\n\nfunction index() {\n  text('Click a user below to load their avatar');\n  document.querySelector('img')\n    .style.display = 'none';\n}\n\nfunction load(ctx, next) {\n  ctx.avatar = avatars[ctx.params.name];\n  next();\n}\n\nfunction show(ctx) {\n  var img = document.querySelector('img');\n  img.src = ctx.avatar;\n  img.style.display = 'block';\n  text('Showing ' + ctx.params.name);\n}\n\nfunction notfound() {\n  document.querySelector('p')\n    .textContent = 'not found';\n}"
  },
  {
    "path": "examples/profile/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>Profile</title>\n    <script src=\"/page.js\"></script>\n    <link rel=\"stylesheet\" href=\"/profile/style.css\" />\n  </head>\n  <body>\n    <h1>Profile</h1>\n    <p></p>\n    <img width=150 />\n\n    <ul>\n      <li><a href=\"/profile/user/manny\">Manny</a></li>\n      <li><a href=\"/profile/user/glottis\">Glottis</a></li>\n      <li><a href=\"/profile/user/sal\">Sal</a></li>\n    </ul>\n\n    <a href=\"#\" id=\"cycle\">Cycle through users</a>\n    <script src=\"/profile/app.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/profile/style.css",
    "content": "body {\n  padding: 50px;\n  font: 200 16px \"Helvetica Neue\", Helvetica, Arial;\n}\n\nh1 {\n  font-weight: 300;\n}\n\na {\n  color: #036dff;\n  text-decoration: none;\n}\n\na:hover {\n  text-decoration: underline;\n}"
  },
  {
    "path": "examples/query-string/app.js",
    "content": "\npage.base('/query-string');\npage('*', parse)\npage('/', show)\npage()\n\nfunction parse(ctx, next) {\n  ctx.query = qs.parse(location.search.slice(1));\n  next();\n}\n\nfunction show(ctx) {\n  if (Object.keys(ctx.query).length) {\n    document\n      .querySelector('pre')\n      .textContent = JSON.stringify(ctx.query, null, 2);\n  }\n}"
  },
  {
    "path": "examples/query-string/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>Query string</title>\n    <link rel=\"stylesheet\" href=\"/query-string/style.css\" />\n  </head>\n  <body>\n    <h1>Query string</h1>\n    <pre>Add a query-string! Maybe: user[name]=tobi</pre>\n    <script src=\"/page.js\"></script>\n    <script src=\"/query-string/query.js\"></script>\n    <script src=\"/query-string/app.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query-string/query.js",
    "content": "(function(exports){\n\n/**\n * Library version.\n */\n\nexports.version = '0.4.2';\n\n/**\n * Object#toString() ref for stringify().\n */\n\nvar toString = Object.prototype.toString;\n\n/**\n * Cache non-integer test regexp.\n */\n\nvar isint = /^[0-9]+$/;\n\nfunction promote(parent, key) {\n  if (parent[key].length == 0) return parent[key] = {};\n  var t = {};\n  for (var i in parent[key]) t[i] = parent[key][i];\n  parent[key] = t;\n  return t;\n}\n\nfunction parse(parts, parent, key, val) {\n  var part = parts.shift();\n  // end\n  if (!part) {\n    if (Array.isArray(parent[key])) {\n      parent[key].push(val);\n    } else if ('object' == typeof parent[key]) {\n      parent[key] = val;\n    } else if ('undefined' == typeof parent[key]) {\n      parent[key] = val;\n    } else {\n      parent[key] = [parent[key], val];\n    }\n    // array\n  } else {\n    var obj = parent[key] = parent[key] || [];\n    if (']' == part) {\n      if (Array.isArray(obj)) {\n        if ('' != val) obj.push(val);\n      } else if ('object' == typeof obj) {\n        obj[Object.keys(obj).length] = val;\n      } else {\n        obj = parent[key] = [parent[key], val];\n      }\n      // prop\n    } else if (~part.indexOf(']')) {\n      part = part.substr(0, part.length - 1);\n      if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key);\n      parse(parts, obj, part, val);\n      // key\n    } else {\n      if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key);\n      parse(parts, obj, part, val);\n    }\n  }\n}\n\n/**\n * Merge parent key/val pair.\n */\n\nfunction merge(parent, key, val){\n  if (~key.indexOf(']')) {\n    var parts = key.split('[')\n      , len = parts.length\n      , last = len - 1;\n    parse(parts, parent, 'base', val);\n    // optimize\n  } else {\n    if (!isint.test(key) && Array.isArray(parent.base)) {\n      var t = {};\n      for (var k in parent.base) t[k] = parent.base[k];\n      parent.base = t;\n    }\n    set(parent.base, key, val);\n  }\n\n  return parent;\n}\n\n/**\n * Parse the given obj.\n */\n\nfunction parseObject(obj){\n  var ret = { base: {} };\n  Object.keys(obj).forEach(function(name){\n    merge(ret, name, obj[name]);\n  });\n  return ret.base;\n}\n\n/**\n * Parse the given str.\n */\n\nfunction parseString(str){\n  return String(str)\n    .split('&')\n    .reduce(function(ret, pair){\n      try{\n        pair = decodeURIComponent(pair.replace(/\\+/g, ' '));\n      } catch(e) {\n        // ignore\n      }\n\n      var eql = pair.indexOf('=')\n        , brace = lastBraceInKey(pair)\n        , key = pair.substr(0, brace || eql)\n        , val = pair.substr(brace || eql, pair.length)\n        , val = val.substr(val.indexOf('=') + 1, val.length);\n\n      // ?foo\n      if ('' == key) key = pair, val = '';\n\n      return merge(ret, key, val);\n    }, { base: {} }).base;\n}\n\n/**\n * Parse the given query `str` or `obj`, returning an object.\n *\n * @param {String} str | {Object} obj\n * @return {Object}\n * @api public\n */\n\nexports.parse = function(str){\n  if (null == str || '' == str) return {};\n  return 'object' == typeof str\n    ? parseObject(str)\n    : parseString(str);\n};\n\n/**\n * Turn the given `obj` into a query string\n *\n * @param {Object} obj\n * @return {String}\n * @api public\n */\n\nvar stringify = exports.stringify = function(obj, prefix) {\n  if (Array.isArray(obj)) {\n    return stringifyArray(obj, prefix);\n  } else if ('[object Object]' == toString.call(obj)) {\n    return stringifyObject(obj, prefix);\n  } else if ('string' == typeof obj) {\n    return stringifyString(obj, prefix);\n  } else {\n    return prefix + '=' + obj;\n  }\n};\n\n/**\n * Stringify the given `str`.\n *\n * @param {String} str\n * @param {String} prefix\n * @return {String}\n * @api private\n */\n\nfunction stringifyString(str, prefix) {\n  if (!prefix) throw new TypeError('stringify expects an object');\n  return prefix + '=' + encodeURIComponent(str);\n}\n\n/**\n * Stringify the given `arr`.\n *\n * @param {Array} arr\n * @param {String} prefix\n * @return {String}\n * @api private\n */\n\nfunction stringifyArray(arr, prefix) {\n  var ret = [];\n  if (!prefix) throw new TypeError('stringify expects an object');\n  for (var i = 0; i < arr.length; i++) {\n    ret.push(stringify(arr[i], prefix + '['+i+']'));\n  }\n  return ret.join('&');\n}\n\n/**\n * Stringify the given `obj`.\n *\n * @param {Object} obj\n * @param {String} prefix\n * @return {String}\n * @api private\n */\n\nfunction stringifyObject(obj, prefix) {\n  var ret = []\n    , keys = Object.keys(obj)\n    , key;\n\n  for (var i = 0, len = keys.length; i < len; ++i) {\n    key = keys[i];\n    ret.push(stringify(obj[key], prefix\n      ? prefix + '[' + encodeURIComponent(key) + ']'\n      : encodeURIComponent(key)));\n  }\n\n  return ret.join('&');\n}\n\n/**\n * Set `obj`'s `key` to `val` respecting\n * the weird and wonderful syntax of a qs,\n * where \"foo=bar&foo=baz\" becomes an array.\n *\n * @param {Object} obj\n * @param {String} key\n * @param {String} val\n * @api private\n */\n\nfunction set(obj, key, val) {\n  var v = obj[key];\n  if (undefined === v) {\n    obj[key] = val;\n  } else if (Array.isArray(v)) {\n    v.push(val);\n  } else {\n    obj[key] = [v, val];\n  }\n}\n\n/**\n * Locate last brace in `str` within the key.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction lastBraceInKey(str) {\n  var len = str.length\n    , brace\n    , c;\n  for (var i = 0; i < len; ++i) {\n    c = str[i];\n    if (']' == c) brace = false;\n    if ('[' == c) brace = true;\n    if ('=' == c && !brace) return i;\n  }\n}\n})('undefined' == typeof exports ? qs = {} : exports);"
  },
  {
    "path": "examples/query-string/style.css",
    "content": "body {\n  padding: 50px;\n  font: 200 16px \"Helvetica Neue\", Helvetica, Arial;\n}\n\nh1 {\n  font-weight: 300;\n}\n\na {\n  color: #036dff;\n  text-decoration: none;\n}\n\na:hover {\n  text-decoration: underline;\n}"
  },
  {
    "path": "examples/server/app.js",
    "content": "\npage.base('/server');\npage('/', index)\npage('/contact', contact)\npage({ dispatch: false })\n\nfunction index() {\n  document.querySelector('p')\n    .textContent = 'Index page generated on the client!';\n}\n\nfunction contact() {\n  document.querySelector('p')\n    .textContent = 'Contact page generated on the client!';\n}"
  },
  {
    "path": "examples/server/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>Server</title>\n    <script src=\"/page.js\"></script>\n  </head>\n  <body>\n    <h1>Server</h1>\n    <p>Initial content generated by the server!</p>\n    <ul>\n      <li><a href=\"./\">Home</a></li>\n      <li><a href=\"./contact\">Contact</a></li>\n    </ul>\n\n    <script src=\"/server/app.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/server/style.css",
    "content": "body {\n  padding: 50px;\n  font: 200 16px \"Helvetica Neue\", Helvetica, Arial;\n}\n\nh1 {\n  font-weight: 300;\n}\n\na {\n  color: #036dff;\n  text-decoration: none;\n}\n\na:hover {\n  text-decoration: underline;\n}\n"
  },
  {
    "path": "examples/state/app.js",
    "content": "\nvar avatars = {\n  glottis: 'http://homepage.ntlworld.com/stureek/images/glottis03.jpg',\n  manny: 'http://kprojekt.net/wp-content/uploads/manny.jpg',\n  sal: 'http://homepage.ntlworld.com/stureek/images/sal01.jpg'\n};\n\npage.base('/state');\npage('/', index);\npage('/user/:name', load, show);\npage('*', notfound);\npage();\n\n// everything below is not part of page.js\n// just callbacks etc..\n\nfunction text(str) {\n  document.querySelector('p').textContent = str;\n}\n\nfunction index() {\n  text('Click a user below to load their avatar');\n  document.querySelector('img')\n    .style.display = 'none';\n}\n\nfunction load(ctx, next) {\n  // check if we have .state.avatar already available\n  // this could for example be a cached html fragment.\n  if (ctx.state.avatar) {\n    ctx.avatar = ctx.state.avatar;\n    next();\n    return;\n  }\n\n  // pretend we're querying some database etc\n  setTimeout(function(){\n    // you can assign properties to the context\n    // for use between these functions. The .state\n    // property is what's saved in history.\n    ctx.state.avatar = ctx.avatar = avatars[ctx.params.name];\n    ctx.save();\n    next();\n  }, 600);\n}\n\nfunction show(ctx) {\n  var img = document.querySelector('img');\n  img.src = ctx.avatar;\n  img.style.display = 'block';\n  text('Showing ' + ctx.params.name);\n}\n\nfunction notfound() {\n  document.querySelector('p')\n    .textContent = 'not found';\n}"
  },
  {
    "path": "examples/state/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>Profile</title>\n    <script src=\"/page.js\"></script>\n    <link rel=\"stylesheet\" href=\"/state/style.css\" />\n  </head>\n  <body>\n    <h1>Profile</h1>\n    <p></p>\n    <img width=150 />\n\n    <ul>\n      <li><a href=\"/state/user/manny\">Manny</a></li>\n      <li><a href=\"/state/user/glottis\">Glottis</a></li>\n      <li><a href=\"/state/user/sal\">Sal</a></li>\n    </ul>\n\n    <script src=\"/state/app.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/state/style.css",
    "content": "body {\n  padding: 50px;\n  font: 200 16px \"Helvetica Neue\", Helvetica, Arial;\n}\n\nh1 {\n  font-weight: 300;\n}\n\na {\n  color: #036dff;\n  text-decoration: none;\n}\n\na:hover {\n  text-decoration: underline;\n}\n"
  },
  {
    "path": "examples/transitions/app.js",
    "content": "\n// content\n\nvar content = document.querySelector('#content');\n\n// current page indicator\n\nvar p = document.querySelector('#page');\n\n// \"mount\" it\n\npage.base('/transitions');\n\n// transition \"middleware\"\n\npage('*', function(ctx,  next){\n  if (ctx.init) {\n    next();\n  } else {\n    content.classList.add('transition');\n    setTimeout(function(){\n      content.classList.remove('transition');\n      next();\n    }, 300);\n  }\n})\n\n// regular pages\n\npage('/', function(){\n  p.textContent = '';\n});\n\npage('/contact', function(){\n  p.textContent = 'contact page';\n});\n\npage('/about', function(){\n  p.textContent = 'about page';\n});\n\npage()"
  },
  {
    "path": "examples/transitions/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>Page.js - transitions</title>\n    <script src=\"/page.js\"></script>\n    <link rel=\"stylesheet\" href=\"/transitions/style.css\" />\n  </head>\n  <body>\n    <section id=\"content\">\n      <img src=\"/transitions/logo.png\" id=\"logo\" />\n\n      <p id=\"page\"></p>\n\n      <nav>\n        <a href=\"/transitions\">home</a>\n        <a href=\"/transitions/contact\">contact</a>\n        <a href=\"/transitions/about\">about</a>\n      </nav>\n    </section>\n    <script src=\"/transitions/app.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/transitions/style.css",
    "content": "\nbody {\n  background: url(/transitions/bg.png);\n  text-align: center;\n  font: 200 14px \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n  letter-spacing: .1em;\n}\n\n#content {\n  margin: 100px auto;\n  padding: 100px 50px 80px 50px;\n  width: 500px;\n  background: white;\n  position: relative;\n  opacity: 1;\n  -webkit-border-radius: 2px;\n  -webkit-box-shadow: 0 0 10px black;\n  -webkit-transition: -webkit-transform 300ms ease-out, opacity 300ms ease-out;\n}\n\n#content.transition {\n  -webkit-transform: translateX(100px);\n  opacity: 0;\n}\n\n#page {\n  margin-top: 40px;\n}\n\nnav {\n  position: absolute;\n  bottom: -26px;\n  left: 0;\n}\n\nnav a {\n  text-decoration: none;\n  color: rgba(255,255,255,.3);\n  background: -webkit-linear-gradient(#444, #3a3a3a);\n  display: inline-block;\n  padding: 5px 10px;\n  font-size: 12px;\n  -webkit-box-shadow: 0 1px 3px rgba(0,0,0,.6), inset 0 -1px 0 rgba(255,255,255,.05);\n  -webkit-border-radius: 0 0 2px 2px;\n}\n\nnav a:hover {\n  color: white;\n}\n\nnav a:active {\n  -webkit-box-shadow: 0 0 2px rgba(0,0,0,.6), inset 0 1px 0 rgba(255,255,255,.05);\n}"
  },
  {
    "path": "index.js",
    "content": "  /* globals require, module */\n\n  'use strict';\n\n  /**\n   * Module dependencies.\n   */\n\n  var pathtoRegexp = require('path-to-regexp');\n\n  /**\n   * Short-cuts for global-object checks\n   */\n\n  var hasDocument = ('undefined' !== typeof document);\n  var hasWindow = ('undefined' !== typeof window);\n  var hasHistory = ('undefined' !== typeof history);\n  var hasProcess = typeof process !== 'undefined';\n\n  /**\n   * Detect click event\n   */\n  var clickEvent = hasDocument && document.ontouchstart ? 'touchstart' : 'click';\n\n  /**\n   * To work properly with the URL\n   * history.location generated polyfill in https://github.com/devote/HTML5-History-API\n   */\n\n  var isLocation = hasWindow && !!(window.history.location || window.location);\n\n  /**\n   * The page instance\n   * @api private\n   */\n  function Page() {\n    // public things\n    this.callbacks = [];\n    this.exits = [];\n    this.current = '';\n    this.len = 0;\n\n    // private things\n    this._decodeURLComponents = true;\n    this._base = '';\n    this._strict = false;\n    this._running = false;\n    this._hashbang = false;\n\n    // bound functions\n    this.clickHandler = this.clickHandler.bind(this);\n    this._onpopstate = this._onpopstate.bind(this);\n  }\n\n  /**\n   * Configure the instance of page. This can be called multiple times.\n   *\n   * @param {Object} options\n   * @api public\n   */\n\n  Page.prototype.configure = function(options) {\n    var opts = options || {};\n\n    this._window = opts.window || (hasWindow && window);\n    this._decodeURLComponents = opts.decodeURLComponents !== false;\n    this._popstate = opts.popstate !== false && hasWindow;\n    this._click = opts.click !== false && hasDocument;\n    this._hashbang = !!opts.hashbang;\n\n    var _window = this._window;\n    if(this._popstate) {\n      _window.addEventListener('popstate', this._onpopstate, false);\n    } else if(hasWindow) {\n      _window.removeEventListener('popstate', this._onpopstate, false);\n    }\n\n    if (this._click) {\n      _window.document.addEventListener(clickEvent, this.clickHandler, false);\n    } else if(hasDocument) {\n      _window.document.removeEventListener(clickEvent, this.clickHandler, false);\n    }\n\n    if(this._hashbang && hasWindow && !hasHistory) {\n      _window.addEventListener('hashchange', this._onpopstate, false);\n    } else if(hasWindow) {\n      _window.removeEventListener('hashchange', this._onpopstate, false);\n    }\n  };\n\n  /**\n   * Get or set basepath to `path`.\n   *\n   * @param {string} path\n   * @api public\n   */\n\n  Page.prototype.base = function(path) {\n    if (0 === arguments.length) return this._base;\n    this._base = path;\n  };\n\n  /**\n   * Gets the `base`, which depends on whether we are using History or\n   * hashbang routing.\n\n   * @api private\n   */\n  Page.prototype._getBase = function() {\n    var base = this._base;\n    if(!!base) return base;\n    var loc = hasWindow && this._window && this._window.location;\n\n    if(hasWindow && this._hashbang && loc && loc.protocol === 'file:') {\n      base = loc.pathname;\n    }\n\n    return base;\n  };\n\n  /**\n   * Get or set strict path matching to `enable`\n   *\n   * @param {boolean} enable\n   * @api public\n   */\n\n  Page.prototype.strict = function(enable) {\n    if (0 === arguments.length) return this._strict;\n    this._strict = enable;\n  };\n\n\n  /**\n   * Bind with the given `options`.\n   *\n   * Options:\n   *\n   *    - `click` bind to click events [true]\n   *    - `popstate` bind to popstate [true]\n   *    - `dispatch` perform initial dispatch [true]\n   *\n   * @param {Object} options\n   * @api public\n   */\n\n  Page.prototype.start = function(options) {\n    var opts = options || {};\n    this.configure(opts);\n\n    if (false === opts.dispatch) return;\n    this._running = true;\n\n    var url;\n    if(isLocation) {\n      var window = this._window;\n      var loc = window.location;\n\n      if(this._hashbang && ~loc.hash.indexOf('#!')) {\n        url = loc.hash.substr(2) + loc.search;\n      } else if (this._hashbang) {\n        url = loc.search + loc.hash;\n      } else {\n        url = loc.pathname + loc.search + loc.hash;\n      }\n    }\n\n    this.replace(url, null, true, opts.dispatch);\n  };\n\n  /**\n   * Unbind click and popstate event handlers.\n   *\n   * @api public\n   */\n\n  Page.prototype.stop = function() {\n    if (!this._running) return;\n    this.current = '';\n    this.len = 0;\n    this._running = false;\n\n    var window = this._window;\n    this._click && window.document.removeEventListener(clickEvent, this.clickHandler, false);\n    hasWindow && window.removeEventListener('popstate', this._onpopstate, false);\n    hasWindow && window.removeEventListener('hashchange', this._onpopstate, false);\n  };\n\n  /**\n   * Show `path` with optional `state` object.\n   *\n   * @param {string} path\n   * @param {Object=} state\n   * @param {boolean=} dispatch\n   * @param {boolean=} push\n   * @return {!Context}\n   * @api public\n   */\n\n  Page.prototype.show = function(path, state, dispatch, push) {\n    var ctx = new Context(path, state, this),\n      prev = this.prevContext;\n    this.prevContext = ctx;\n    this.current = ctx.path;\n    if (false !== dispatch) this.dispatch(ctx, prev);\n    if (false !== ctx.handled && false !== push) ctx.pushState();\n    return ctx;\n  };\n\n  /**\n   * Goes back in the history\n   * Back should always let the current route push state and then go back.\n   *\n   * @param {string} path - fallback path to go back if no more history exists, if undefined defaults to page.base\n   * @param {Object=} state\n   * @api public\n   */\n\n  Page.prototype.back = function(path, state) {\n    var page = this;\n    if (this.len > 0) {\n      var window = this._window;\n      // this may need more testing to see if all browsers\n      // wait for the next tick to go back in history\n      hasHistory && window.history.back();\n      this.len--;\n    } else if (path) {\n      setTimeout(function() {\n        page.show(path, state);\n      });\n    } else {\n      setTimeout(function() {\n        page.show(page._getBase(), state);\n      });\n    }\n  };\n\n  /**\n   * Register route to redirect from one path to other\n   * or just redirect to another route\n   *\n   * @param {string} from - if param 'to' is undefined redirects to 'from'\n   * @param {string=} to\n   * @api public\n   */\n  Page.prototype.redirect = function(from, to) {\n    var inst = this;\n\n    // Define route from a path to another\n    if ('string' === typeof from && 'string' === typeof to) {\n      page.call(this, from, function(e) {\n        setTimeout(function() {\n          inst.replace(/** @type {!string} */ (to));\n        }, 0);\n      });\n    }\n\n    // Wait for the push state and replace it with another\n    if ('string' === typeof from && 'undefined' === typeof to) {\n      setTimeout(function() {\n        inst.replace(from);\n      }, 0);\n    }\n  };\n\n  /**\n   * Replace `path` with optional `state` object.\n   *\n   * @param {string} path\n   * @param {Object=} state\n   * @param {boolean=} init\n   * @param {boolean=} dispatch\n   * @return {!Context}\n   * @api public\n   */\n\n\n  Page.prototype.replace = function(path, state, init, dispatch) {\n    var ctx = new Context(path, state, this),\n      prev = this.prevContext;\n    this.prevContext = ctx;\n    this.current = ctx.path;\n    ctx.init = init;\n    ctx.save(); // save before dispatching, which may redirect\n    if (false !== dispatch) this.dispatch(ctx, prev);\n    return ctx;\n  };\n\n  /**\n   * Dispatch the given `ctx`.\n   *\n   * @param {Context} ctx\n   * @api private\n   */\n\n  Page.prototype.dispatch = function(ctx, prev) {\n    var i = 0, j = 0, page = this;\n\n    function nextExit() {\n      var fn = page.exits[j++];\n      if (!fn) return nextEnter();\n      fn(prev, nextExit);\n    }\n\n    function nextEnter() {\n      var fn = page.callbacks[i++];\n\n      if (ctx.path !== page.current) {\n        ctx.handled = false;\n        return;\n      }\n      if (!fn) return unhandled.call(page, ctx);\n      fn(ctx, nextEnter);\n    }\n\n    if (prev) {\n      nextExit();\n    } else {\n      nextEnter();\n    }\n  };\n\n  /**\n   * Register an exit route on `path` with\n   * callback `fn()`, which will be called\n   * on the previous context when a new\n   * page is visited.\n   */\n  Page.prototype.exit = function(path, fn) {\n    if (typeof path === 'function') {\n      return this.exit('*', path);\n    }\n\n    var route = new Route(path, null, this);\n    for (var i = 1; i < arguments.length; ++i) {\n      this.exits.push(route.middleware(arguments[i]));\n    }\n  };\n\n  /**\n   * Handle \"click\" events.\n   */\n\n  /* jshint +W054 */\n  Page.prototype.clickHandler = function(e) {\n    if (1 !== this._which(e)) return;\n\n    if (e.metaKey || e.ctrlKey || e.shiftKey) return;\n    if (e.defaultPrevented) return;\n\n    // ensure link\n    // use shadow dom when available if not, fall back to composedPath()\n    // for browsers that only have shady\n    var el = e.target;\n    var eventPath = e.path || (e.composedPath ? e.composedPath() : null);\n\n    if(eventPath) {\n      for (var i = 0; i < eventPath.length; i++) {\n        if (!eventPath[i].nodeName) continue;\n        if (eventPath[i].nodeName.toUpperCase() !== 'A') continue;\n        if (!eventPath[i].href) continue;\n\n        el = eventPath[i];\n        break;\n      }\n    }\n\n    // continue ensure link\n    // el.nodeName for svg links are 'a' instead of 'A'\n    while (el && 'A' !== el.nodeName.toUpperCase()) el = el.parentNode;\n    if (!el || 'A' !== el.nodeName.toUpperCase()) return;\n\n    // check if link is inside an svg\n    // in this case, both href and target are always inside an object\n    var svg = (typeof el.href === 'object') && el.href.constructor.name === 'SVGAnimatedString';\n\n    // Ignore if tag has\n    // 1. \"download\" attribute\n    // 2. rel=\"external\" attribute\n    if (el.hasAttribute('download') || el.getAttribute('rel') === 'external') return;\n\n    // ensure non-hash for the same path\n    var link = el.getAttribute('href');\n    if(!this._hashbang && this._samePath(el) && (el.hash || '#' === link)) return;\n\n    // Check for mailto: in the href\n    if (link && link.indexOf('mailto:') > -1) return;\n\n    // check target\n    // svg target is an object and its desired value is in .baseVal property\n    if (svg ? el.target.baseVal : el.target) return;\n\n    // x-origin\n    // note: svg links that are not relative don't call click events (and skip page.js)\n    // consequently, all svg links tested inside page.js are relative and in the same origin\n    if (!svg && !this.sameOrigin(el.href)) return;\n\n    // rebuild path\n    // There aren't .pathname and .search properties in svg links, so we use href\n    // Also, svg href is an object and its desired value is in .baseVal property\n    var path = svg ? el.href.baseVal : (el.pathname + el.search + (el.hash || ''));\n\n    path = path[0] !== '/' ? '/' + path : path;\n\n    // strip leading \"/[drive letter]:\" on NW.js on Windows\n    if (hasProcess && path.match(/^\\/[a-zA-Z]:\\//)) {\n      path = path.replace(/^\\/[a-zA-Z]:\\//, '/');\n    }\n\n    // same page\n    var orig = path;\n    var pageBase = this._getBase();\n\n    if (path.indexOf(pageBase) === 0) {\n      path = path.substr(pageBase.length);\n    }\n\n    if (this._hashbang) path = path.replace('#!', '');\n\n    if (pageBase && orig === path && (!isLocation || this._window.location.protocol !== 'file:')) {\n      return;\n    }\n\n    e.preventDefault();\n    this.show(orig);\n  };\n\n  /**\n   * Handle \"populate\" events.\n   * @api private\n   */\n\n  Page.prototype._onpopstate = (function () {\n    var loaded = false;\n    if ( ! hasWindow ) {\n      return function () {};\n    }\n    if (hasDocument && document.readyState === 'complete') {\n      loaded = true;\n    } else {\n      window.addEventListener('load', function() {\n        setTimeout(function() {\n          loaded = true;\n        }, 0);\n      });\n    }\n    return function onpopstate(e) {\n      if (!loaded) return;\n      var page = this;\n      if (e.state) {\n        var path = e.state.path;\n        page.replace(path, e.state);\n      } else if (isLocation) {\n        var loc = page._window.location;\n        page.show(loc.pathname + loc.search + loc.hash, undefined, undefined, false);\n      }\n    };\n  })();\n\n  /**\n   * Event button.\n   */\n  Page.prototype._which = function(e) {\n    e = e || (hasWindow && this._window.event);\n    return null == e.which ? e.button : e.which;\n  };\n\n  /**\n   * Convert to a URL object\n   * @api private\n   */\n  Page.prototype._toURL = function(href) {\n    var window = this._window;\n    if(typeof URL === 'function' && isLocation) {\n      return new URL(href, window.location.toString());\n    } else if (hasDocument) {\n      var anc = window.document.createElement('a');\n      anc.href = href;\n      return anc;\n    }\n  };\n\n  /**\n   * Check if `href` is the same origin.\n   * @param {string} href\n   * @api public\n   */\n  Page.prototype.sameOrigin = function(href) {\n    if(!href || !isLocation) return false;\n\n    var url = this._toURL(href);\n    var window = this._window;\n\n    var loc = window.location;\n\n    /*\n       When the port is the default http port 80 for http, or 443 for\n       https, internet explorer 11 returns an empty string for loc.port,\n       so we need to compare loc.port with an empty string if url.port\n       is the default port 80 or 443.\n       Also the comparition with `port` is changed from `===` to `==` because\n       `port` can be a string sometimes. This only applies to ie11.\n    */\n    return loc.protocol === url.protocol &&\n      loc.hostname === url.hostname &&\n      (loc.port === url.port || loc.port === '' && (url.port == 80 || url.port == 443)); // jshint ignore:line\n  };\n\n  /**\n   * @api private\n   */\n  Page.prototype._samePath = function(url) {\n    if(!isLocation) return false;\n    var window = this._window;\n    var loc = window.location;\n    return url.pathname === loc.pathname &&\n      url.search === loc.search;\n  };\n\n  /**\n   * Remove URL encoding from the given `str`.\n   * Accommodates whitespace in both x-www-form-urlencoded\n   * and regular percent-encoded form.\n   *\n   * @param {string} val - URL component to decode\n   * @api private\n   */\n  Page.prototype._decodeURLEncodedURIComponent = function(val) {\n    if (typeof val !== 'string') { return val; }\n    return this._decodeURLComponents ? decodeURIComponent(val.replace(/\\+/g, ' ')) : val;\n  };\n\n  /**\n   * Create a new `page` instance and function\n   */\n  function createPage() {\n    var pageInstance = new Page();\n\n    function pageFn(/* args */) {\n      return page.apply(pageInstance, arguments);\n    }\n\n    // Copy all of the things over. In 2.0 maybe we use setPrototypeOf\n    pageFn.callbacks = pageInstance.callbacks;\n    pageFn.exits = pageInstance.exits;\n    pageFn.base = pageInstance.base.bind(pageInstance);\n    pageFn.strict = pageInstance.strict.bind(pageInstance);\n    pageFn.start = pageInstance.start.bind(pageInstance);\n    pageFn.stop = pageInstance.stop.bind(pageInstance);\n    pageFn.show = pageInstance.show.bind(pageInstance);\n    pageFn.back = pageInstance.back.bind(pageInstance);\n    pageFn.redirect = pageInstance.redirect.bind(pageInstance);\n    pageFn.replace = pageInstance.replace.bind(pageInstance);\n    pageFn.dispatch = pageInstance.dispatch.bind(pageInstance);\n    pageFn.exit = pageInstance.exit.bind(pageInstance);\n    pageFn.configure = pageInstance.configure.bind(pageInstance);\n    pageFn.sameOrigin = pageInstance.sameOrigin.bind(pageInstance);\n    pageFn.clickHandler = pageInstance.clickHandler.bind(pageInstance);\n\n    pageFn.create = createPage;\n\n    Object.defineProperty(pageFn, 'len', {\n      get: function(){\n        return pageInstance.len;\n      },\n      set: function(val) {\n        pageInstance.len = val;\n      }\n    });\n\n    Object.defineProperty(pageFn, 'current', {\n      get: function(){\n        return pageInstance.current;\n      },\n      set: function(val) {\n        pageInstance.current = val;\n      }\n    });\n\n    // In 2.0 these can be named exports\n    pageFn.Context = Context;\n    pageFn.Route = Route;\n\n    return pageFn;\n  }\n\n  /**\n   * Register `path` with callback `fn()`,\n   * or route `path`, or redirection,\n   * or `page.start()`.\n   *\n   *   page(fn);\n   *   page('*', fn);\n   *   page('/user/:id', load, user);\n   *   page('/user/' + user.id, { some: 'thing' });\n   *   page('/user/' + user.id);\n   *   page('/from', '/to')\n   *   page();\n   *\n   * @param {string|!Function|!Object} path\n   * @param {Function=} fn\n   * @api public\n   */\n\n  function page(path, fn) {\n    // <callback>\n    if ('function' === typeof path) {\n      return page.call(this, '*', path);\n    }\n\n    // route <path> to <callback ...>\n    if ('function' === typeof fn) {\n      var route = new Route(/** @type {string} */ (path), null, this);\n      for (var i = 1; i < arguments.length; ++i) {\n        this.callbacks.push(route.middleware(arguments[i]));\n      }\n      // show <path> with [state]\n    } else if ('string' === typeof path) {\n      this['string' === typeof fn ? 'redirect' : 'show'](path, fn);\n      // start [options]\n    } else {\n      this.start(path);\n    }\n  }\n\n  /**\n   * Unhandled `ctx`. When it's not the initial\n   * popstate then redirect. If you wish to handle\n   * 404s on your own use `page('*', callback)`.\n   *\n   * @param {Context} ctx\n   * @api private\n   */\n  function unhandled(ctx) {\n    if (ctx.handled) return;\n    var current;\n    var page = this;\n    var window = page._window;\n\n    if (page._hashbang) {\n      current = isLocation && this._getBase() + window.location.hash.replace('#!', '');\n    } else {\n      current = isLocation && window.location.pathname + window.location.search;\n    }\n\n    if (current === ctx.canonicalPath) return;\n    page.stop();\n    ctx.handled = false;\n    isLocation && (window.location.href = ctx.canonicalPath);\n  }\n\n  /**\n   * Escapes RegExp characters in the given string.\n   *\n   * @param {string} s\n   * @api private\n   */\n  function escapeRegExp(s) {\n    return s.replace(/([.+*?=^!:${}()[\\]|/\\\\])/g, '\\\\$1');\n  }\n\n  /**\n   * Initialize a new \"request\" `Context`\n   * with the given `path` and optional initial `state`.\n   *\n   * @constructor\n   * @param {string} path\n   * @param {Object=} state\n   * @api public\n   */\n\n  function Context(path, state, pageInstance) {\n    var _page = this.page = pageInstance || page;\n    var window = _page._window;\n    var hashbang = _page._hashbang;\n\n    var pageBase = _page._getBase();\n    if ('/' === path[0] && 0 !== path.indexOf(pageBase)) path = pageBase + (hashbang ? '#!' : '') + path;\n    var i = path.indexOf('?');\n\n    this.canonicalPath = path;\n    var re = new RegExp('^' + escapeRegExp(pageBase));\n    this.path = path.replace(re, '') || '/';\n    if (hashbang) this.path = this.path.replace('#!', '') || '/';\n\n    this.title = (hasDocument && window.document.title);\n    this.state = state || {};\n    this.state.path = path;\n    this.querystring = ~i ? _page._decodeURLEncodedURIComponent(path.slice(i + 1)) : '';\n    this.pathname = _page._decodeURLEncodedURIComponent(~i ? path.slice(0, i) : path);\n    this.params = {};\n\n    // fragment\n    this.hash = '';\n    if (!hashbang) {\n      if (!~this.path.indexOf('#')) return;\n      var parts = this.path.split('#');\n      this.path = this.pathname = parts[0];\n      this.hash = _page._decodeURLEncodedURIComponent(parts[1]) || '';\n      this.querystring = this.querystring.split('#')[0];\n    }\n  }\n\n  /**\n   * Push state.\n   *\n   * @api private\n   */\n\n  Context.prototype.pushState = function() {\n    var page = this.page;\n    var window = page._window;\n    var hashbang = page._hashbang;\n\n    page.len++;\n    if (hasHistory) {\n        window.history.pushState(this.state, this.title,\n          hashbang && this.path !== '/' ? '#!' + this.path : this.canonicalPath);\n    }\n  };\n\n  /**\n   * Save the context state.\n   *\n   * @api public\n   */\n\n  Context.prototype.save = function() {\n    var page = this.page;\n    if (hasHistory) {\n        page._window.history.replaceState(this.state, this.title,\n          page._hashbang && this.path !== '/' ? '#!' + this.path : this.canonicalPath);\n    }\n  };\n\n  /**\n   * Initialize `Route` with the given HTTP `path`,\n   * and an array of `callbacks` and `options`.\n   *\n   * Options:\n   *\n   *   - `sensitive`    enable case-sensitive routes\n   *   - `strict`       enable strict matching for trailing slashes\n   *\n   * @constructor\n   * @param {string} path\n   * @param {Object=} options\n   * @api private\n   */\n\n  function Route(path, options, page) {\n    var _page = this.page = page || globalPage;\n    var opts = options || {};\n    opts.strict = opts.strict || _page._strict;\n    this.path = (path === '*') ? '(.*)' : path;\n    this.method = 'GET';\n    this.regexp = pathtoRegexp(this.path, this.keys = [], opts);\n  }\n\n  /**\n   * Return route middleware with\n   * the given callback `fn()`.\n   *\n   * @param {Function} fn\n   * @return {Function}\n   * @api public\n   */\n\n  Route.prototype.middleware = function(fn) {\n    var self = this;\n    return function(ctx, next) {\n      if (self.match(ctx.path, ctx.params)) {\n        ctx.routePath = self.path;\n        return fn(ctx, next);\n      }\n      next();\n    };\n  };\n\n  /**\n   * Check if this route matches `path`, if so\n   * populate `params`.\n   *\n   * @param {string} path\n   * @param {Object} params\n   * @return {boolean}\n   * @api private\n   */\n\n  Route.prototype.match = function(path, params) {\n    var keys = this.keys,\n      qsIndex = path.indexOf('?'),\n      pathname = ~qsIndex ? path.slice(0, qsIndex) : path,\n      m = this.regexp.exec(decodeURIComponent(pathname));\n\n    if (!m) return false;\n\n    delete params[0];\n\n    for (var i = 1, len = m.length; i < len; ++i) {\n      var key = keys[i - 1];\n      var val = this.page._decodeURLEncodedURIComponent(m[i]);\n      if (val !== undefined || !(hasOwnProperty.call(params, key.name))) {\n        params[key.name] = val;\n      }\n    }\n\n    return true;\n  };\n\n\n  /**\n   * Module exports.\n   */\n\n  var globalPage = createPage();\n  module.exports = globalPage;\n  module.exports.default = globalPage;\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"page\",\n  \"description\": \"Tiny client-side router\",\n  \"version\": \"1.11.6\",\n  \"license\": \"MIT\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git://github.com/visionmedia/page.js.git\"\n  },\n  \"component\": {\n    \"scripts\": {\n      \"page\": \"index.js\"\n    }\n  },\n  \"main\": \"index.js\",\n  \"browser\": \"page.js\",\n  \"module\": \"page.mjs\",\n  \"scripts\": {\n    \"engine-deps\": \"install-engine-dependencies\",\n    \"test\": \"jshint index.js test/tests.js && mocha test/tests.js\",\n    \"serve\": \"serve test --symlinks\",\n    \"test-cov\": \"jscoverage index.js index-cov.js; PAGE_COV=1 mocha test/tests.js -R html-cov > coverage.html\",\n    \"make\": \"rollup -c rollup.config.js\"\n  },\n  \"dependencies\": {\n    \"path-to-regexp\": \"~1.2.1\"\n  },\n  \"devDependencies\": {\n    \"chai\": \"^1.10.0\",\n    \"coveralls\": \"^2.11.2\",\n    \"engine-dependencies\": \"^0.2.12\",\n    \"express\": \"^4.10.2\",\n    \"jade\": \"^1.7.0\",\n    \"jscoverage\": \"^0.5.9\",\n    \"jsdom\": \"^11.5.1\",\n    \"jshint\": \"^2.5.10\",\n    \"mocha\": \"^2.0.1\",\n    \"mocha-lcov-reporter\": \"0.0.1\",\n    \"rollup\": \"^0.54.1\",\n    \"rollup-plugin-commonjs\": \"^8.2.6\",\n    \"rollup-plugin-node-resolve\": \"^3.0.2\",\n    \"serve\": \"*\",\n    \"should\": \"*\"\n  },\n  \"engineDependencies\": {\n    \"node\": {\n      \"0.10.x\": {\n        \"devDependencies\": {\n          \"jsdom\": \"^1.3.1\"\n        }\n      }\n    }\n  },\n  \"files\": [\n    \"index.js\",\n    \"page.js\",\n    \"page.mjs\"\n  ]\n}\n"
  },
  {
    "path": "page.js",
    "content": "(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n\ttypeof define === 'function' && define.amd ? define(factory) :\n\t(global.page = factory());\n}(this, (function () { 'use strict';\n\nvar isarray = Array.isArray || function (arr) {\n  return Object.prototype.toString.call(arr) == '[object Array]';\n};\n\n/**\n * Expose `pathToRegexp`.\n */\nvar pathToRegexp_1 = pathToRegexp;\nvar parse_1 = parse;\nvar compile_1 = compile;\nvar tokensToFunction_1 = tokensToFunction;\nvar tokensToRegExp_1 = tokensToRegExp;\n\n/**\n * The main path matching regexp utility.\n *\n * @type {RegExp}\n */\nvar PATH_REGEXP = new RegExp([\n  // Match escaped characters that would otherwise appear in future matches.\n  // This allows the user to escape special characters that won't transform.\n  '(\\\\\\\\.)',\n  // Match Express-style parameters and un-named parameters with a prefix\n  // and optional suffixes. Matches appear as:\n  //\n  // \"/:test(\\\\d+)?\" => [\"/\", \"test\", \"\\d+\", undefined, \"?\", undefined]\n  // \"/route(\\\\d+)\"  => [undefined, undefined, undefined, \"\\d+\", undefined, undefined]\n  // \"/*\"            => [\"/\", undefined, undefined, undefined, undefined, \"*\"]\n  '([\\\\/.])?(?:(?:\\\\:(\\\\w+)(?:\\\\(((?:\\\\\\\\.|[^()])+)\\\\))?|\\\\(((?:\\\\\\\\.|[^()])+)\\\\))([+*?])?|(\\\\*))'\n].join('|'), 'g');\n\n/**\n * Parse a string for the raw tokens.\n *\n * @param  {String} str\n * @return {Array}\n */\nfunction parse (str) {\n  var tokens = [];\n  var key = 0;\n  var index = 0;\n  var path = '';\n  var res;\n\n  while ((res = PATH_REGEXP.exec(str)) != null) {\n    var m = res[0];\n    var escaped = res[1];\n    var offset = res.index;\n    path += str.slice(index, offset);\n    index = offset + m.length;\n\n    // Ignore already escaped sequences.\n    if (escaped) {\n      path += escaped[1];\n      continue\n    }\n\n    // Push the current path onto the tokens.\n    if (path) {\n      tokens.push(path);\n      path = '';\n    }\n\n    var prefix = res[2];\n    var name = res[3];\n    var capture = res[4];\n    var group = res[5];\n    var suffix = res[6];\n    var asterisk = res[7];\n\n    var repeat = suffix === '+' || suffix === '*';\n    var optional = suffix === '?' || suffix === '*';\n    var delimiter = prefix || '/';\n    var pattern = capture || group || (asterisk ? '.*' : '[^' + delimiter + ']+?');\n\n    tokens.push({\n      name: name || key++,\n      prefix: prefix || '',\n      delimiter: delimiter,\n      optional: optional,\n      repeat: repeat,\n      pattern: escapeGroup(pattern)\n    });\n  }\n\n  // Match any characters still remaining.\n  if (index < str.length) {\n    path += str.substr(index);\n  }\n\n  // If the path exists, push it onto the end.\n  if (path) {\n    tokens.push(path);\n  }\n\n  return tokens\n}\n\n/**\n * Compile a string to a template function for the path.\n *\n * @param  {String}   str\n * @return {Function}\n */\nfunction compile (str) {\n  return tokensToFunction(parse(str))\n}\n\n/**\n * Expose a method for transforming tokens into the path function.\n */\nfunction tokensToFunction (tokens) {\n  // Compile all the tokens into regexps.\n  var matches = new Array(tokens.length);\n\n  // Compile all the patterns before compilation.\n  for (var i = 0; i < tokens.length; i++) {\n    if (typeof tokens[i] === 'object') {\n      matches[i] = new RegExp('^' + tokens[i].pattern + '$');\n    }\n  }\n\n  return function (obj) {\n    var path = '';\n    var data = obj || {};\n\n    for (var i = 0; i < tokens.length; i++) {\n      var token = tokens[i];\n\n      if (typeof token === 'string') {\n        path += token;\n\n        continue\n      }\n\n      var value = data[token.name];\n      var segment;\n\n      if (value == null) {\n        if (token.optional) {\n          continue\n        } else {\n          throw new TypeError('Expected \"' + token.name + '\" to be defined')\n        }\n      }\n\n      if (isarray(value)) {\n        if (!token.repeat) {\n          throw new TypeError('Expected \"' + token.name + '\" to not repeat, but received \"' + value + '\"')\n        }\n\n        if (value.length === 0) {\n          if (token.optional) {\n            continue\n          } else {\n            throw new TypeError('Expected \"' + token.name + '\" to not be empty')\n          }\n        }\n\n        for (var j = 0; j < value.length; j++) {\n          segment = encodeURIComponent(value[j]);\n\n          if (!matches[i].test(segment)) {\n            throw new TypeError('Expected all \"' + token.name + '\" to match \"' + token.pattern + '\", but received \"' + segment + '\"')\n          }\n\n          path += (j === 0 ? token.prefix : token.delimiter) + segment;\n        }\n\n        continue\n      }\n\n      segment = encodeURIComponent(value);\n\n      if (!matches[i].test(segment)) {\n        throw new TypeError('Expected \"' + token.name + '\" to match \"' + token.pattern + '\", but received \"' + segment + '\"')\n      }\n\n      path += token.prefix + segment;\n    }\n\n    return path\n  }\n}\n\n/**\n * Escape a regular expression string.\n *\n * @param  {String} str\n * @return {String}\n */\nfunction escapeString (str) {\n  return str.replace(/([.+*?=^!:${}()[\\]|\\/])/g, '\\\\$1')\n}\n\n/**\n * Escape the capturing group by escaping special characters and meaning.\n *\n * @param  {String} group\n * @return {String}\n */\nfunction escapeGroup (group) {\n  return group.replace(/([=!:$\\/()])/g, '\\\\$1')\n}\n\n/**\n * Attach the keys as a property of the regexp.\n *\n * @param  {RegExp} re\n * @param  {Array}  keys\n * @return {RegExp}\n */\nfunction attachKeys (re, keys) {\n  re.keys = keys;\n  return re\n}\n\n/**\n * Get the flags for a regexp from the options.\n *\n * @param  {Object} options\n * @return {String}\n */\nfunction flags (options) {\n  return options.sensitive ? '' : 'i'\n}\n\n/**\n * Pull out keys from a regexp.\n *\n * @param  {RegExp} path\n * @param  {Array}  keys\n * @return {RegExp}\n */\nfunction regexpToRegexp (path, keys) {\n  // Use a negative lookahead to match only capturing groups.\n  var groups = path.source.match(/\\((?!\\?)/g);\n\n  if (groups) {\n    for (var i = 0; i < groups.length; i++) {\n      keys.push({\n        name: i,\n        prefix: null,\n        delimiter: null,\n        optional: false,\n        repeat: false,\n        pattern: null\n      });\n    }\n  }\n\n  return attachKeys(path, keys)\n}\n\n/**\n * Transform an array into a regexp.\n *\n * @param  {Array}  path\n * @param  {Array}  keys\n * @param  {Object} options\n * @return {RegExp}\n */\nfunction arrayToRegexp (path, keys, options) {\n  var parts = [];\n\n  for (var i = 0; i < path.length; i++) {\n    parts.push(pathToRegexp(path[i], keys, options).source);\n  }\n\n  var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));\n\n  return attachKeys(regexp, keys)\n}\n\n/**\n * Create a path regexp from string input.\n *\n * @param  {String} path\n * @param  {Array}  keys\n * @param  {Object} options\n * @return {RegExp}\n */\nfunction stringToRegexp (path, keys, options) {\n  var tokens = parse(path);\n  var re = tokensToRegExp(tokens, options);\n\n  // Attach keys back to the regexp.\n  for (var i = 0; i < tokens.length; i++) {\n    if (typeof tokens[i] !== 'string') {\n      keys.push(tokens[i]);\n    }\n  }\n\n  return attachKeys(re, keys)\n}\n\n/**\n * Expose a function for taking tokens and returning a RegExp.\n *\n * @param  {Array}  tokens\n * @param  {Array}  keys\n * @param  {Object} options\n * @return {RegExp}\n */\nfunction tokensToRegExp (tokens, options) {\n  options = options || {};\n\n  var strict = options.strict;\n  var end = options.end !== false;\n  var route = '';\n  var lastToken = tokens[tokens.length - 1];\n  var endsWithSlash = typeof lastToken === 'string' && /\\/$/.test(lastToken);\n\n  // Iterate over the tokens and create our regexp string.\n  for (var i = 0; i < tokens.length; i++) {\n    var token = tokens[i];\n\n    if (typeof token === 'string') {\n      route += escapeString(token);\n    } else {\n      var prefix = escapeString(token.prefix);\n      var capture = token.pattern;\n\n      if (token.repeat) {\n        capture += '(?:' + prefix + capture + ')*';\n      }\n\n      if (token.optional) {\n        if (prefix) {\n          capture = '(?:' + prefix + '(' + capture + '))?';\n        } else {\n          capture = '(' + capture + ')?';\n        }\n      } else {\n        capture = prefix + '(' + capture + ')';\n      }\n\n      route += capture;\n    }\n  }\n\n  // In non-strict mode we allow a slash at the end of match. If the path to\n  // match already ends with a slash, we remove it for consistency. The slash\n  // is valid at the end of a path match, not in the middle. This is important\n  // in non-ending mode, where \"/test/\" shouldn't match \"/test//route\".\n  if (!strict) {\n    route = (endsWithSlash ? route.slice(0, -2) : route) + '(?:\\\\/(?=$))?';\n  }\n\n  if (end) {\n    route += '$';\n  } else {\n    // In non-ending mode, we need the capturing groups to match as much as\n    // possible by using a positive lookahead to the end or next path segment.\n    route += strict && endsWithSlash ? '' : '(?=\\\\/|$)';\n  }\n\n  return new RegExp('^' + route, flags(options))\n}\n\n/**\n * Normalize the given path string, returning a regular expression.\n *\n * An empty array can be passed in for the keys, which will hold the\n * placeholder key descriptions. For example, using `/user/:id`, `keys` will\n * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.\n *\n * @param  {(String|RegExp|Array)} path\n * @param  {Array}                 [keys]\n * @param  {Object}                [options]\n * @return {RegExp}\n */\nfunction pathToRegexp (path, keys, options) {\n  keys = keys || [];\n\n  if (!isarray(keys)) {\n    options = keys;\n    keys = [];\n  } else if (!options) {\n    options = {};\n  }\n\n  if (path instanceof RegExp) {\n    return regexpToRegexp(path, keys, options)\n  }\n\n  if (isarray(path)) {\n    return arrayToRegexp(path, keys, options)\n  }\n\n  return stringToRegexp(path, keys, options)\n}\n\npathToRegexp_1.parse = parse_1;\npathToRegexp_1.compile = compile_1;\npathToRegexp_1.tokensToFunction = tokensToFunction_1;\npathToRegexp_1.tokensToRegExp = tokensToRegExp_1;\n\n/**\n   * Module dependencies.\n   */\n\n  \n\n  /**\n   * Short-cuts for global-object checks\n   */\n\n  var hasDocument = ('undefined' !== typeof document);\n  var hasWindow = ('undefined' !== typeof window);\n  var hasHistory = ('undefined' !== typeof history);\n  var hasProcess = typeof process !== 'undefined';\n\n  /**\n   * Detect click event\n   */\n  var clickEvent = hasDocument && document.ontouchstart ? 'touchstart' : 'click';\n\n  /**\n   * To work properly with the URL\n   * history.location generated polyfill in https://github.com/devote/HTML5-History-API\n   */\n\n  var isLocation = hasWindow && !!(window.history.location || window.location);\n\n  /**\n   * The page instance\n   * @api private\n   */\n  function Page() {\n    // public things\n    this.callbacks = [];\n    this.exits = [];\n    this.current = '';\n    this.len = 0;\n\n    // private things\n    this._decodeURLComponents = true;\n    this._base = '';\n    this._strict = false;\n    this._running = false;\n    this._hashbang = false;\n\n    // bound functions\n    this.clickHandler = this.clickHandler.bind(this);\n    this._onpopstate = this._onpopstate.bind(this);\n  }\n\n  /**\n   * Configure the instance of page. This can be called multiple times.\n   *\n   * @param {Object} options\n   * @api public\n   */\n\n  Page.prototype.configure = function(options) {\n    var opts = options || {};\n\n    this._window = opts.window || (hasWindow && window);\n    this._decodeURLComponents = opts.decodeURLComponents !== false;\n    this._popstate = opts.popstate !== false && hasWindow;\n    this._click = opts.click !== false && hasDocument;\n    this._hashbang = !!opts.hashbang;\n\n    var _window = this._window;\n    if(this._popstate) {\n      _window.addEventListener('popstate', this._onpopstate, false);\n    } else if(hasWindow) {\n      _window.removeEventListener('popstate', this._onpopstate, false);\n    }\n\n    if (this._click) {\n      _window.document.addEventListener(clickEvent, this.clickHandler, false);\n    } else if(hasDocument) {\n      _window.document.removeEventListener(clickEvent, this.clickHandler, false);\n    }\n\n    if(this._hashbang && hasWindow && !hasHistory) {\n      _window.addEventListener('hashchange', this._onpopstate, false);\n    } else if(hasWindow) {\n      _window.removeEventListener('hashchange', this._onpopstate, false);\n    }\n  };\n\n  /**\n   * Get or set basepath to `path`.\n   *\n   * @param {string} path\n   * @api public\n   */\n\n  Page.prototype.base = function(path) {\n    if (0 === arguments.length) return this._base;\n    this._base = path;\n  };\n\n  /**\n   * Gets the `base`, which depends on whether we are using History or\n   * hashbang routing.\n\n   * @api private\n   */\n  Page.prototype._getBase = function() {\n    var base = this._base;\n    if(!!base) return base;\n    var loc = hasWindow && this._window && this._window.location;\n\n    if(hasWindow && this._hashbang && loc && loc.protocol === 'file:') {\n      base = loc.pathname;\n    }\n\n    return base;\n  };\n\n  /**\n   * Get or set strict path matching to `enable`\n   *\n   * @param {boolean} enable\n   * @api public\n   */\n\n  Page.prototype.strict = function(enable) {\n    if (0 === arguments.length) return this._strict;\n    this._strict = enable;\n  };\n\n\n  /**\n   * Bind with the given `options`.\n   *\n   * Options:\n   *\n   *    - `click` bind to click events [true]\n   *    - `popstate` bind to popstate [true]\n   *    - `dispatch` perform initial dispatch [true]\n   *\n   * @param {Object} options\n   * @api public\n   */\n\n  Page.prototype.start = function(options) {\n    var opts = options || {};\n    this.configure(opts);\n\n    if (false === opts.dispatch) return;\n    this._running = true;\n\n    var url;\n    if(isLocation) {\n      var window = this._window;\n      var loc = window.location;\n\n      if(this._hashbang && ~loc.hash.indexOf('#!')) {\n        url = loc.hash.substr(2) + loc.search;\n      } else if (this._hashbang) {\n        url = loc.search + loc.hash;\n      } else {\n        url = loc.pathname + loc.search + loc.hash;\n      }\n    }\n\n    this.replace(url, null, true, opts.dispatch);\n  };\n\n  /**\n   * Unbind click and popstate event handlers.\n   *\n   * @api public\n   */\n\n  Page.prototype.stop = function() {\n    if (!this._running) return;\n    this.current = '';\n    this.len = 0;\n    this._running = false;\n\n    var window = this._window;\n    this._click && window.document.removeEventListener(clickEvent, this.clickHandler, false);\n    hasWindow && window.removeEventListener('popstate', this._onpopstate, false);\n    hasWindow && window.removeEventListener('hashchange', this._onpopstate, false);\n  };\n\n  /**\n   * Show `path` with optional `state` object.\n   *\n   * @param {string} path\n   * @param {Object=} state\n   * @param {boolean=} dispatch\n   * @param {boolean=} push\n   * @return {!Context}\n   * @api public\n   */\n\n  Page.prototype.show = function(path, state, dispatch, push) {\n    var ctx = new Context(path, state, this),\n      prev = this.prevContext;\n    this.prevContext = ctx;\n    this.current = ctx.path;\n    if (false !== dispatch) this.dispatch(ctx, prev);\n    if (false !== ctx.handled && false !== push) ctx.pushState();\n    return ctx;\n  };\n\n  /**\n   * Goes back in the history\n   * Back should always let the current route push state and then go back.\n   *\n   * @param {string} path - fallback path to go back if no more history exists, if undefined defaults to page.base\n   * @param {Object=} state\n   * @api public\n   */\n\n  Page.prototype.back = function(path, state) {\n    var page = this;\n    if (this.len > 0) {\n      var window = this._window;\n      // this may need more testing to see if all browsers\n      // wait for the next tick to go back in history\n      hasHistory && window.history.back();\n      this.len--;\n    } else if (path) {\n      setTimeout(function() {\n        page.show(path, state);\n      });\n    } else {\n      setTimeout(function() {\n        page.show(page._getBase(), state);\n      });\n    }\n  };\n\n  /**\n   * Register route to redirect from one path to other\n   * or just redirect to another route\n   *\n   * @param {string} from - if param 'to' is undefined redirects to 'from'\n   * @param {string=} to\n   * @api public\n   */\n  Page.prototype.redirect = function(from, to) {\n    var inst = this;\n\n    // Define route from a path to another\n    if ('string' === typeof from && 'string' === typeof to) {\n      page.call(this, from, function(e) {\n        setTimeout(function() {\n          inst.replace(/** @type {!string} */ (to));\n        }, 0);\n      });\n    }\n\n    // Wait for the push state and replace it with another\n    if ('string' === typeof from && 'undefined' === typeof to) {\n      setTimeout(function() {\n        inst.replace(from);\n      }, 0);\n    }\n  };\n\n  /**\n   * Replace `path` with optional `state` object.\n   *\n   * @param {string} path\n   * @param {Object=} state\n   * @param {boolean=} init\n   * @param {boolean=} dispatch\n   * @return {!Context}\n   * @api public\n   */\n\n\n  Page.prototype.replace = function(path, state, init, dispatch) {\n    var ctx = new Context(path, state, this),\n      prev = this.prevContext;\n    this.prevContext = ctx;\n    this.current = ctx.path;\n    ctx.init = init;\n    ctx.save(); // save before dispatching, which may redirect\n    if (false !== dispatch) this.dispatch(ctx, prev);\n    return ctx;\n  };\n\n  /**\n   * Dispatch the given `ctx`.\n   *\n   * @param {Context} ctx\n   * @api private\n   */\n\n  Page.prototype.dispatch = function(ctx, prev) {\n    var i = 0, j = 0, page = this;\n\n    function nextExit() {\n      var fn = page.exits[j++];\n      if (!fn) return nextEnter();\n      fn(prev, nextExit);\n    }\n\n    function nextEnter() {\n      var fn = page.callbacks[i++];\n\n      if (ctx.path !== page.current) {\n        ctx.handled = false;\n        return;\n      }\n      if (!fn) return unhandled.call(page, ctx);\n      fn(ctx, nextEnter);\n    }\n\n    if (prev) {\n      nextExit();\n    } else {\n      nextEnter();\n    }\n  };\n\n  /**\n   * Register an exit route on `path` with\n   * callback `fn()`, which will be called\n   * on the previous context when a new\n   * page is visited.\n   */\n  Page.prototype.exit = function(path, fn) {\n    if (typeof path === 'function') {\n      return this.exit('*', path);\n    }\n\n    var route = new Route(path, null, this);\n    for (var i = 1; i < arguments.length; ++i) {\n      this.exits.push(route.middleware(arguments[i]));\n    }\n  };\n\n  /**\n   * Handle \"click\" events.\n   */\n\n  /* jshint +W054 */\n  Page.prototype.clickHandler = function(e) {\n    if (1 !== this._which(e)) return;\n\n    if (e.metaKey || e.ctrlKey || e.shiftKey) return;\n    if (e.defaultPrevented) return;\n\n    // ensure link\n    // use shadow dom when available if not, fall back to composedPath()\n    // for browsers that only have shady\n    var el = e.target;\n    var eventPath = e.path || (e.composedPath ? e.composedPath() : null);\n\n    if(eventPath) {\n      for (var i = 0; i < eventPath.length; i++) {\n        if (!eventPath[i].nodeName) continue;\n        if (eventPath[i].nodeName.toUpperCase() !== 'A') continue;\n        if (!eventPath[i].href) continue;\n\n        el = eventPath[i];\n        break;\n      }\n    }\n\n    // continue ensure link\n    // el.nodeName for svg links are 'a' instead of 'A'\n    while (el && 'A' !== el.nodeName.toUpperCase()) el = el.parentNode;\n    if (!el || 'A' !== el.nodeName.toUpperCase()) return;\n\n    // check if link is inside an svg\n    // in this case, both href and target are always inside an object\n    var svg = (typeof el.href === 'object') && el.href.constructor.name === 'SVGAnimatedString';\n\n    // Ignore if tag has\n    // 1. \"download\" attribute\n    // 2. rel=\"external\" attribute\n    if (el.hasAttribute('download') || el.getAttribute('rel') === 'external') return;\n\n    // ensure non-hash for the same path\n    var link = el.getAttribute('href');\n    if(!this._hashbang && this._samePath(el) && (el.hash || '#' === link)) return;\n\n    // Check for mailto: in the href\n    if (link && link.indexOf('mailto:') > -1) return;\n\n    // check target\n    // svg target is an object and its desired value is in .baseVal property\n    if (svg ? el.target.baseVal : el.target) return;\n\n    // x-origin\n    // note: svg links that are not relative don't call click events (and skip page.js)\n    // consequently, all svg links tested inside page.js are relative and in the same origin\n    if (!svg && !this.sameOrigin(el.href)) return;\n\n    // rebuild path\n    // There aren't .pathname and .search properties in svg links, so we use href\n    // Also, svg href is an object and its desired value is in .baseVal property\n    var path = svg ? el.href.baseVal : (el.pathname + el.search + (el.hash || ''));\n\n    path = path[0] !== '/' ? '/' + path : path;\n\n    // strip leading \"/[drive letter]:\" on NW.js on Windows\n    if (hasProcess && path.match(/^\\/[a-zA-Z]:\\//)) {\n      path = path.replace(/^\\/[a-zA-Z]:\\//, '/');\n    }\n\n    // same page\n    var orig = path;\n    var pageBase = this._getBase();\n\n    if (path.indexOf(pageBase) === 0) {\n      path = path.substr(pageBase.length);\n    }\n\n    if (this._hashbang) path = path.replace('#!', '');\n\n    if (pageBase && orig === path && (!isLocation || this._window.location.protocol !== 'file:')) {\n      return;\n    }\n\n    e.preventDefault();\n    this.show(orig);\n  };\n\n  /**\n   * Handle \"populate\" events.\n   * @api private\n   */\n\n  Page.prototype._onpopstate = (function () {\n    var loaded = false;\n    if ( ! hasWindow ) {\n      return function () {};\n    }\n    if (hasDocument && document.readyState === 'complete') {\n      loaded = true;\n    } else {\n      window.addEventListener('load', function() {\n        setTimeout(function() {\n          loaded = true;\n        }, 0);\n      });\n    }\n    return function onpopstate(e) {\n      if (!loaded) return;\n      var page = this;\n      if (e.state) {\n        var path = e.state.path;\n        page.replace(path, e.state);\n      } else if (isLocation) {\n        var loc = page._window.location;\n        page.show(loc.pathname + loc.search + loc.hash, undefined, undefined, false);\n      }\n    };\n  })();\n\n  /**\n   * Event button.\n   */\n  Page.prototype._which = function(e) {\n    e = e || (hasWindow && this._window.event);\n    return null == e.which ? e.button : e.which;\n  };\n\n  /**\n   * Convert to a URL object\n   * @api private\n   */\n  Page.prototype._toURL = function(href) {\n    var window = this._window;\n    if(typeof URL === 'function' && isLocation) {\n      return new URL(href, window.location.toString());\n    } else if (hasDocument) {\n      var anc = window.document.createElement('a');\n      anc.href = href;\n      return anc;\n    }\n  };\n\n  /**\n   * Check if `href` is the same origin.\n   * @param {string} href\n   * @api public\n   */\n  Page.prototype.sameOrigin = function(href) {\n    if(!href || !isLocation) return false;\n\n    var url = this._toURL(href);\n    var window = this._window;\n\n    var loc = window.location;\n\n    /*\n       When the port is the default http port 80 for http, or 443 for\n       https, internet explorer 11 returns an empty string for loc.port,\n       so we need to compare loc.port with an empty string if url.port\n       is the default port 80 or 443.\n       Also the comparition with `port` is changed from `===` to `==` because\n       `port` can be a string sometimes. This only applies to ie11.\n    */\n    return loc.protocol === url.protocol &&\n      loc.hostname === url.hostname &&\n      (loc.port === url.port || loc.port === '' && (url.port == 80 || url.port == 443)); // jshint ignore:line\n  };\n\n  /**\n   * @api private\n   */\n  Page.prototype._samePath = function(url) {\n    if(!isLocation) return false;\n    var window = this._window;\n    var loc = window.location;\n    return url.pathname === loc.pathname &&\n      url.search === loc.search;\n  };\n\n  /**\n   * Remove URL encoding from the given `str`.\n   * Accommodates whitespace in both x-www-form-urlencoded\n   * and regular percent-encoded form.\n   *\n   * @param {string} val - URL component to decode\n   * @api private\n   */\n  Page.prototype._decodeURLEncodedURIComponent = function(val) {\n    if (typeof val !== 'string') { return val; }\n    return this._decodeURLComponents ? decodeURIComponent(val.replace(/\\+/g, ' ')) : val;\n  };\n\n  /**\n   * Create a new `page` instance and function\n   */\n  function createPage() {\n    var pageInstance = new Page();\n\n    function pageFn(/* args */) {\n      return page.apply(pageInstance, arguments);\n    }\n\n    // Copy all of the things over. In 2.0 maybe we use setPrototypeOf\n    pageFn.callbacks = pageInstance.callbacks;\n    pageFn.exits = pageInstance.exits;\n    pageFn.base = pageInstance.base.bind(pageInstance);\n    pageFn.strict = pageInstance.strict.bind(pageInstance);\n    pageFn.start = pageInstance.start.bind(pageInstance);\n    pageFn.stop = pageInstance.stop.bind(pageInstance);\n    pageFn.show = pageInstance.show.bind(pageInstance);\n    pageFn.back = pageInstance.back.bind(pageInstance);\n    pageFn.redirect = pageInstance.redirect.bind(pageInstance);\n    pageFn.replace = pageInstance.replace.bind(pageInstance);\n    pageFn.dispatch = pageInstance.dispatch.bind(pageInstance);\n    pageFn.exit = pageInstance.exit.bind(pageInstance);\n    pageFn.configure = pageInstance.configure.bind(pageInstance);\n    pageFn.sameOrigin = pageInstance.sameOrigin.bind(pageInstance);\n    pageFn.clickHandler = pageInstance.clickHandler.bind(pageInstance);\n\n    pageFn.create = createPage;\n\n    Object.defineProperty(pageFn, 'len', {\n      get: function(){\n        return pageInstance.len;\n      },\n      set: function(val) {\n        pageInstance.len = val;\n      }\n    });\n\n    Object.defineProperty(pageFn, 'current', {\n      get: function(){\n        return pageInstance.current;\n      },\n      set: function(val) {\n        pageInstance.current = val;\n      }\n    });\n\n    // In 2.0 these can be named exports\n    pageFn.Context = Context;\n    pageFn.Route = Route;\n\n    return pageFn;\n  }\n\n  /**\n   * Register `path` with callback `fn()`,\n   * or route `path`, or redirection,\n   * or `page.start()`.\n   *\n   *   page(fn);\n   *   page('*', fn);\n   *   page('/user/:id', load, user);\n   *   page('/user/' + user.id, { some: 'thing' });\n   *   page('/user/' + user.id);\n   *   page('/from', '/to')\n   *   page();\n   *\n   * @param {string|!Function|!Object} path\n   * @param {Function=} fn\n   * @api public\n   */\n\n  function page(path, fn) {\n    // <callback>\n    if ('function' === typeof path) {\n      return page.call(this, '*', path);\n    }\n\n    // route <path> to <callback ...>\n    if ('function' === typeof fn) {\n      var route = new Route(/** @type {string} */ (path), null, this);\n      for (var i = 1; i < arguments.length; ++i) {\n        this.callbacks.push(route.middleware(arguments[i]));\n      }\n      // show <path> with [state]\n    } else if ('string' === typeof path) {\n      this['string' === typeof fn ? 'redirect' : 'show'](path, fn);\n      // start [options]\n    } else {\n      this.start(path);\n    }\n  }\n\n  /**\n   * Unhandled `ctx`. When it's not the initial\n   * popstate then redirect. If you wish to handle\n   * 404s on your own use `page('*', callback)`.\n   *\n   * @param {Context} ctx\n   * @api private\n   */\n  function unhandled(ctx) {\n    if (ctx.handled) return;\n    var current;\n    var page = this;\n    var window = page._window;\n\n    if (page._hashbang) {\n      current = isLocation && this._getBase() + window.location.hash.replace('#!', '');\n    } else {\n      current = isLocation && window.location.pathname + window.location.search;\n    }\n\n    if (current === ctx.canonicalPath) return;\n    page.stop();\n    ctx.handled = false;\n    isLocation && (window.location.href = ctx.canonicalPath);\n  }\n\n  /**\n   * Escapes RegExp characters in the given string.\n   *\n   * @param {string} s\n   * @api private\n   */\n  function escapeRegExp(s) {\n    return s.replace(/([.+*?=^!:${}()[\\]|/\\\\])/g, '\\\\$1');\n  }\n\n  /**\n   * Initialize a new \"request\" `Context`\n   * with the given `path` and optional initial `state`.\n   *\n   * @constructor\n   * @param {string} path\n   * @param {Object=} state\n   * @api public\n   */\n\n  function Context(path, state, pageInstance) {\n    var _page = this.page = pageInstance || page;\n    var window = _page._window;\n    var hashbang = _page._hashbang;\n\n    var pageBase = _page._getBase();\n    if ('/' === path[0] && 0 !== path.indexOf(pageBase)) path = pageBase + (hashbang ? '#!' : '') + path;\n    var i = path.indexOf('?');\n\n    this.canonicalPath = path;\n    var re = new RegExp('^' + escapeRegExp(pageBase));\n    this.path = path.replace(re, '') || '/';\n    if (hashbang) this.path = this.path.replace('#!', '') || '/';\n\n    this.title = (hasDocument && window.document.title);\n    this.state = state || {};\n    this.state.path = path;\n    this.querystring = ~i ? _page._decodeURLEncodedURIComponent(path.slice(i + 1)) : '';\n    this.pathname = _page._decodeURLEncodedURIComponent(~i ? path.slice(0, i) : path);\n    this.params = {};\n\n    // fragment\n    this.hash = '';\n    if (!hashbang) {\n      if (!~this.path.indexOf('#')) return;\n      var parts = this.path.split('#');\n      this.path = this.pathname = parts[0];\n      this.hash = _page._decodeURLEncodedURIComponent(parts[1]) || '';\n      this.querystring = this.querystring.split('#')[0];\n    }\n  }\n\n  /**\n   * Push state.\n   *\n   * @api private\n   */\n\n  Context.prototype.pushState = function() {\n    var page = this.page;\n    var window = page._window;\n    var hashbang = page._hashbang;\n\n    page.len++;\n    if (hasHistory) {\n        window.history.pushState(this.state, this.title,\n          hashbang && this.path !== '/' ? '#!' + this.path : this.canonicalPath);\n    }\n  };\n\n  /**\n   * Save the context state.\n   *\n   * @api public\n   */\n\n  Context.prototype.save = function() {\n    var page = this.page;\n    if (hasHistory) {\n        page._window.history.replaceState(this.state, this.title,\n          page._hashbang && this.path !== '/' ? '#!' + this.path : this.canonicalPath);\n    }\n  };\n\n  /**\n   * Initialize `Route` with the given HTTP `path`,\n   * and an array of `callbacks` and `options`.\n   *\n   * Options:\n   *\n   *   - `sensitive`    enable case-sensitive routes\n   *   - `strict`       enable strict matching for trailing slashes\n   *\n   * @constructor\n   * @param {string} path\n   * @param {Object=} options\n   * @api private\n   */\n\n  function Route(path, options, page) {\n    var _page = this.page = page || globalPage;\n    var opts = options || {};\n    opts.strict = opts.strict || _page._strict;\n    this.path = (path === '*') ? '(.*)' : path;\n    this.method = 'GET';\n    this.regexp = pathToRegexp_1(this.path, this.keys = [], opts);\n  }\n\n  /**\n   * Return route middleware with\n   * the given callback `fn()`.\n   *\n   * @param {Function} fn\n   * @return {Function}\n   * @api public\n   */\n\n  Route.prototype.middleware = function(fn) {\n    var self = this;\n    return function(ctx, next) {\n      if (self.match(ctx.path, ctx.params)) {\n        ctx.routePath = self.path;\n        return fn(ctx, next);\n      }\n      next();\n    };\n  };\n\n  /**\n   * Check if this route matches `path`, if so\n   * populate `params`.\n   *\n   * @param {string} path\n   * @param {Object} params\n   * @return {boolean}\n   * @api private\n   */\n\n  Route.prototype.match = function(path, params) {\n    var keys = this.keys,\n      qsIndex = path.indexOf('?'),\n      pathname = ~qsIndex ? path.slice(0, qsIndex) : path,\n      m = this.regexp.exec(decodeURIComponent(pathname));\n\n    if (!m) return false;\n\n    delete params[0];\n\n    for (var i = 1, len = m.length; i < len; ++i) {\n      var key = keys[i - 1];\n      var val = this.page._decodeURLEncodedURIComponent(m[i]);\n      if (val !== undefined || !(hasOwnProperty.call(params, key.name))) {\n        params[key.name] = val;\n      }\n    }\n\n    return true;\n  };\n\n\n  /**\n   * Module exports.\n   */\n\n  var globalPage = createPage();\n  var page_js = globalPage;\n  var default_1 = globalPage;\n\npage_js.default = default_1;\n\nreturn page_js;\n\n})));\n"
  },
  {
    "path": "page.mjs",
    "content": "var isarray = Array.isArray || function (arr) {\n  return Object.prototype.toString.call(arr) == '[object Array]';\n};\n\n/**\n * Expose `pathToRegexp`.\n */\nvar pathToRegexp_1 = pathToRegexp;\nvar parse_1 = parse;\nvar compile_1 = compile;\nvar tokensToFunction_1 = tokensToFunction;\nvar tokensToRegExp_1 = tokensToRegExp;\n\n/**\n * The main path matching regexp utility.\n *\n * @type {RegExp}\n */\nvar PATH_REGEXP = new RegExp([\n  // Match escaped characters that would otherwise appear in future matches.\n  // This allows the user to escape special characters that won't transform.\n  '(\\\\\\\\.)',\n  // Match Express-style parameters and un-named parameters with a prefix\n  // and optional suffixes. Matches appear as:\n  //\n  // \"/:test(\\\\d+)?\" => [\"/\", \"test\", \"\\d+\", undefined, \"?\", undefined]\n  // \"/route(\\\\d+)\"  => [undefined, undefined, undefined, \"\\d+\", undefined, undefined]\n  // \"/*\"            => [\"/\", undefined, undefined, undefined, undefined, \"*\"]\n  '([\\\\/.])?(?:(?:\\\\:(\\\\w+)(?:\\\\(((?:\\\\\\\\.|[^()])+)\\\\))?|\\\\(((?:\\\\\\\\.|[^()])+)\\\\))([+*?])?|(\\\\*))'\n].join('|'), 'g');\n\n/**\n * Parse a string for the raw tokens.\n *\n * @param  {String} str\n * @return {Array}\n */\nfunction parse (str) {\n  var tokens = [];\n  var key = 0;\n  var index = 0;\n  var path = '';\n  var res;\n\n  while ((res = PATH_REGEXP.exec(str)) != null) {\n    var m = res[0];\n    var escaped = res[1];\n    var offset = res.index;\n    path += str.slice(index, offset);\n    index = offset + m.length;\n\n    // Ignore already escaped sequences.\n    if (escaped) {\n      path += escaped[1];\n      continue\n    }\n\n    // Push the current path onto the tokens.\n    if (path) {\n      tokens.push(path);\n      path = '';\n    }\n\n    var prefix = res[2];\n    var name = res[3];\n    var capture = res[4];\n    var group = res[5];\n    var suffix = res[6];\n    var asterisk = res[7];\n\n    var repeat = suffix === '+' || suffix === '*';\n    var optional = suffix === '?' || suffix === '*';\n    var delimiter = prefix || '/';\n    var pattern = capture || group || (asterisk ? '.*' : '[^' + delimiter + ']+?');\n\n    tokens.push({\n      name: name || key++,\n      prefix: prefix || '',\n      delimiter: delimiter,\n      optional: optional,\n      repeat: repeat,\n      pattern: escapeGroup(pattern)\n    });\n  }\n\n  // Match any characters still remaining.\n  if (index < str.length) {\n    path += str.substr(index);\n  }\n\n  // If the path exists, push it onto the end.\n  if (path) {\n    tokens.push(path);\n  }\n\n  return tokens\n}\n\n/**\n * Compile a string to a template function for the path.\n *\n * @param  {String}   str\n * @return {Function}\n */\nfunction compile (str) {\n  return tokensToFunction(parse(str))\n}\n\n/**\n * Expose a method for transforming tokens into the path function.\n */\nfunction tokensToFunction (tokens) {\n  // Compile all the tokens into regexps.\n  var matches = new Array(tokens.length);\n\n  // Compile all the patterns before compilation.\n  for (var i = 0; i < tokens.length; i++) {\n    if (typeof tokens[i] === 'object') {\n      matches[i] = new RegExp('^' + tokens[i].pattern + '$');\n    }\n  }\n\n  return function (obj) {\n    var path = '';\n    var data = obj || {};\n\n    for (var i = 0; i < tokens.length; i++) {\n      var token = tokens[i];\n\n      if (typeof token === 'string') {\n        path += token;\n\n        continue\n      }\n\n      var value = data[token.name];\n      var segment;\n\n      if (value == null) {\n        if (token.optional) {\n          continue\n        } else {\n          throw new TypeError('Expected \"' + token.name + '\" to be defined')\n        }\n      }\n\n      if (isarray(value)) {\n        if (!token.repeat) {\n          throw new TypeError('Expected \"' + token.name + '\" to not repeat, but received \"' + value + '\"')\n        }\n\n        if (value.length === 0) {\n          if (token.optional) {\n            continue\n          } else {\n            throw new TypeError('Expected \"' + token.name + '\" to not be empty')\n          }\n        }\n\n        for (var j = 0; j < value.length; j++) {\n          segment = encodeURIComponent(value[j]);\n\n          if (!matches[i].test(segment)) {\n            throw new TypeError('Expected all \"' + token.name + '\" to match \"' + token.pattern + '\", but received \"' + segment + '\"')\n          }\n\n          path += (j === 0 ? token.prefix : token.delimiter) + segment;\n        }\n\n        continue\n      }\n\n      segment = encodeURIComponent(value);\n\n      if (!matches[i].test(segment)) {\n        throw new TypeError('Expected \"' + token.name + '\" to match \"' + token.pattern + '\", but received \"' + segment + '\"')\n      }\n\n      path += token.prefix + segment;\n    }\n\n    return path\n  }\n}\n\n/**\n * Escape a regular expression string.\n *\n * @param  {String} str\n * @return {String}\n */\nfunction escapeString (str) {\n  return str.replace(/([.+*?=^!:${}()[\\]|\\/])/g, '\\\\$1')\n}\n\n/**\n * Escape the capturing group by escaping special characters and meaning.\n *\n * @param  {String} group\n * @return {String}\n */\nfunction escapeGroup (group) {\n  return group.replace(/([=!:$\\/()])/g, '\\\\$1')\n}\n\n/**\n * Attach the keys as a property of the regexp.\n *\n * @param  {RegExp} re\n * @param  {Array}  keys\n * @return {RegExp}\n */\nfunction attachKeys (re, keys) {\n  re.keys = keys;\n  return re\n}\n\n/**\n * Get the flags for a regexp from the options.\n *\n * @param  {Object} options\n * @return {String}\n */\nfunction flags (options) {\n  return options.sensitive ? '' : 'i'\n}\n\n/**\n * Pull out keys from a regexp.\n *\n * @param  {RegExp} path\n * @param  {Array}  keys\n * @return {RegExp}\n */\nfunction regexpToRegexp (path, keys) {\n  // Use a negative lookahead to match only capturing groups.\n  var groups = path.source.match(/\\((?!\\?)/g);\n\n  if (groups) {\n    for (var i = 0; i < groups.length; i++) {\n      keys.push({\n        name: i,\n        prefix: null,\n        delimiter: null,\n        optional: false,\n        repeat: false,\n        pattern: null\n      });\n    }\n  }\n\n  return attachKeys(path, keys)\n}\n\n/**\n * Transform an array into a regexp.\n *\n * @param  {Array}  path\n * @param  {Array}  keys\n * @param  {Object} options\n * @return {RegExp}\n */\nfunction arrayToRegexp (path, keys, options) {\n  var parts = [];\n\n  for (var i = 0; i < path.length; i++) {\n    parts.push(pathToRegexp(path[i], keys, options).source);\n  }\n\n  var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));\n\n  return attachKeys(regexp, keys)\n}\n\n/**\n * Create a path regexp from string input.\n *\n * @param  {String} path\n * @param  {Array}  keys\n * @param  {Object} options\n * @return {RegExp}\n */\nfunction stringToRegexp (path, keys, options) {\n  var tokens = parse(path);\n  var re = tokensToRegExp(tokens, options);\n\n  // Attach keys back to the regexp.\n  for (var i = 0; i < tokens.length; i++) {\n    if (typeof tokens[i] !== 'string') {\n      keys.push(tokens[i]);\n    }\n  }\n\n  return attachKeys(re, keys)\n}\n\n/**\n * Expose a function for taking tokens and returning a RegExp.\n *\n * @param  {Array}  tokens\n * @param  {Array}  keys\n * @param  {Object} options\n * @return {RegExp}\n */\nfunction tokensToRegExp (tokens, options) {\n  options = options || {};\n\n  var strict = options.strict;\n  var end = options.end !== false;\n  var route = '';\n  var lastToken = tokens[tokens.length - 1];\n  var endsWithSlash = typeof lastToken === 'string' && /\\/$/.test(lastToken);\n\n  // Iterate over the tokens and create our regexp string.\n  for (var i = 0; i < tokens.length; i++) {\n    var token = tokens[i];\n\n    if (typeof token === 'string') {\n      route += escapeString(token);\n    } else {\n      var prefix = escapeString(token.prefix);\n      var capture = token.pattern;\n\n      if (token.repeat) {\n        capture += '(?:' + prefix + capture + ')*';\n      }\n\n      if (token.optional) {\n        if (prefix) {\n          capture = '(?:' + prefix + '(' + capture + '))?';\n        } else {\n          capture = '(' + capture + ')?';\n        }\n      } else {\n        capture = prefix + '(' + capture + ')';\n      }\n\n      route += capture;\n    }\n  }\n\n  // In non-strict mode we allow a slash at the end of match. If the path to\n  // match already ends with a slash, we remove it for consistency. The slash\n  // is valid at the end of a path match, not in the middle. This is important\n  // in non-ending mode, where \"/test/\" shouldn't match \"/test//route\".\n  if (!strict) {\n    route = (endsWithSlash ? route.slice(0, -2) : route) + '(?:\\\\/(?=$))?';\n  }\n\n  if (end) {\n    route += '$';\n  } else {\n    // In non-ending mode, we need the capturing groups to match as much as\n    // possible by using a positive lookahead to the end or next path segment.\n    route += strict && endsWithSlash ? '' : '(?=\\\\/|$)';\n  }\n\n  return new RegExp('^' + route, flags(options))\n}\n\n/**\n * Normalize the given path string, returning a regular expression.\n *\n * An empty array can be passed in for the keys, which will hold the\n * placeholder key descriptions. For example, using `/user/:id`, `keys` will\n * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.\n *\n * @param  {(String|RegExp|Array)} path\n * @param  {Array}                 [keys]\n * @param  {Object}                [options]\n * @return {RegExp}\n */\nfunction pathToRegexp (path, keys, options) {\n  keys = keys || [];\n\n  if (!isarray(keys)) {\n    options = keys;\n    keys = [];\n  } else if (!options) {\n    options = {};\n  }\n\n  if (path instanceof RegExp) {\n    return regexpToRegexp(path, keys, options)\n  }\n\n  if (isarray(path)) {\n    return arrayToRegexp(path, keys, options)\n  }\n\n  return stringToRegexp(path, keys, options)\n}\n\npathToRegexp_1.parse = parse_1;\npathToRegexp_1.compile = compile_1;\npathToRegexp_1.tokensToFunction = tokensToFunction_1;\npathToRegexp_1.tokensToRegExp = tokensToRegExp_1;\n\n/**\n   * Module dependencies.\n   */\n\n  \n\n  /**\n   * Short-cuts for global-object checks\n   */\n\n  var hasDocument = ('undefined' !== typeof document);\n  var hasWindow = ('undefined' !== typeof window);\n  var hasHistory = ('undefined' !== typeof history);\n  var hasProcess = typeof process !== 'undefined';\n\n  /**\n   * Detect click event\n   */\n  var clickEvent = hasDocument && document.ontouchstart ? 'touchstart' : 'click';\n\n  /**\n   * To work properly with the URL\n   * history.location generated polyfill in https://github.com/devote/HTML5-History-API\n   */\n\n  var isLocation = hasWindow && !!(window.history.location || window.location);\n\n  /**\n   * The page instance\n   * @api private\n   */\n  function Page() {\n    // public things\n    this.callbacks = [];\n    this.exits = [];\n    this.current = '';\n    this.len = 0;\n\n    // private things\n    this._decodeURLComponents = true;\n    this._base = '';\n    this._strict = false;\n    this._running = false;\n    this._hashbang = false;\n\n    // bound functions\n    this.clickHandler = this.clickHandler.bind(this);\n    this._onpopstate = this._onpopstate.bind(this);\n  }\n\n  /**\n   * Configure the instance of page. This can be called multiple times.\n   *\n   * @param {Object} options\n   * @api public\n   */\n\n  Page.prototype.configure = function(options) {\n    var opts = options || {};\n\n    this._window = opts.window || (hasWindow && window);\n    this._decodeURLComponents = opts.decodeURLComponents !== false;\n    this._popstate = opts.popstate !== false && hasWindow;\n    this._click = opts.click !== false && hasDocument;\n    this._hashbang = !!opts.hashbang;\n\n    var _window = this._window;\n    if(this._popstate) {\n      _window.addEventListener('popstate', this._onpopstate, false);\n    } else if(hasWindow) {\n      _window.removeEventListener('popstate', this._onpopstate, false);\n    }\n\n    if (this._click) {\n      _window.document.addEventListener(clickEvent, this.clickHandler, false);\n    } else if(hasDocument) {\n      _window.document.removeEventListener(clickEvent, this.clickHandler, false);\n    }\n\n    if(this._hashbang && hasWindow && !hasHistory) {\n      _window.addEventListener('hashchange', this._onpopstate, false);\n    } else if(hasWindow) {\n      _window.removeEventListener('hashchange', this._onpopstate, false);\n    }\n  };\n\n  /**\n   * Get or set basepath to `path`.\n   *\n   * @param {string} path\n   * @api public\n   */\n\n  Page.prototype.base = function(path) {\n    if (0 === arguments.length) return this._base;\n    this._base = path;\n  };\n\n  /**\n   * Gets the `base`, which depends on whether we are using History or\n   * hashbang routing.\n\n   * @api private\n   */\n  Page.prototype._getBase = function() {\n    var base = this._base;\n    if(!!base) return base;\n    var loc = hasWindow && this._window && this._window.location;\n\n    if(hasWindow && this._hashbang && loc && loc.protocol === 'file:') {\n      base = loc.pathname;\n    }\n\n    return base;\n  };\n\n  /**\n   * Get or set strict path matching to `enable`\n   *\n   * @param {boolean} enable\n   * @api public\n   */\n\n  Page.prototype.strict = function(enable) {\n    if (0 === arguments.length) return this._strict;\n    this._strict = enable;\n  };\n\n\n  /**\n   * Bind with the given `options`.\n   *\n   * Options:\n   *\n   *    - `click` bind to click events [true]\n   *    - `popstate` bind to popstate [true]\n   *    - `dispatch` perform initial dispatch [true]\n   *\n   * @param {Object} options\n   * @api public\n   */\n\n  Page.prototype.start = function(options) {\n    var opts = options || {};\n    this.configure(opts);\n\n    if (false === opts.dispatch) return;\n    this._running = true;\n\n    var url;\n    if(isLocation) {\n      var window = this._window;\n      var loc = window.location;\n\n      if(this._hashbang && ~loc.hash.indexOf('#!')) {\n        url = loc.hash.substr(2) + loc.search;\n      } else if (this._hashbang) {\n        url = loc.search + loc.hash;\n      } else {\n        url = loc.pathname + loc.search + loc.hash;\n      }\n    }\n\n    this.replace(url, null, true, opts.dispatch);\n  };\n\n  /**\n   * Unbind click and popstate event handlers.\n   *\n   * @api public\n   */\n\n  Page.prototype.stop = function() {\n    if (!this._running) return;\n    this.current = '';\n    this.len = 0;\n    this._running = false;\n\n    var window = this._window;\n    this._click && window.document.removeEventListener(clickEvent, this.clickHandler, false);\n    hasWindow && window.removeEventListener('popstate', this._onpopstate, false);\n    hasWindow && window.removeEventListener('hashchange', this._onpopstate, false);\n  };\n\n  /**\n   * Show `path` with optional `state` object.\n   *\n   * @param {string} path\n   * @param {Object=} state\n   * @param {boolean=} dispatch\n   * @param {boolean=} push\n   * @return {!Context}\n   * @api public\n   */\n\n  Page.prototype.show = function(path, state, dispatch, push) {\n    var ctx = new Context(path, state, this),\n      prev = this.prevContext;\n    this.prevContext = ctx;\n    this.current = ctx.path;\n    if (false !== dispatch) this.dispatch(ctx, prev);\n    if (false !== ctx.handled && false !== push) ctx.pushState();\n    return ctx;\n  };\n\n  /**\n   * Goes back in the history\n   * Back should always let the current route push state and then go back.\n   *\n   * @param {string} path - fallback path to go back if no more history exists, if undefined defaults to page.base\n   * @param {Object=} state\n   * @api public\n   */\n\n  Page.prototype.back = function(path, state) {\n    var page = this;\n    if (this.len > 0) {\n      var window = this._window;\n      // this may need more testing to see if all browsers\n      // wait for the next tick to go back in history\n      hasHistory && window.history.back();\n      this.len--;\n    } else if (path) {\n      setTimeout(function() {\n        page.show(path, state);\n      });\n    } else {\n      setTimeout(function() {\n        page.show(page._getBase(), state);\n      });\n    }\n  };\n\n  /**\n   * Register route to redirect from one path to other\n   * or just redirect to another route\n   *\n   * @param {string} from - if param 'to' is undefined redirects to 'from'\n   * @param {string=} to\n   * @api public\n   */\n  Page.prototype.redirect = function(from, to) {\n    var inst = this;\n\n    // Define route from a path to another\n    if ('string' === typeof from && 'string' === typeof to) {\n      page.call(this, from, function(e) {\n        setTimeout(function() {\n          inst.replace(/** @type {!string} */ (to));\n        }, 0);\n      });\n    }\n\n    // Wait for the push state and replace it with another\n    if ('string' === typeof from && 'undefined' === typeof to) {\n      setTimeout(function() {\n        inst.replace(from);\n      }, 0);\n    }\n  };\n\n  /**\n   * Replace `path` with optional `state` object.\n   *\n   * @param {string} path\n   * @param {Object=} state\n   * @param {boolean=} init\n   * @param {boolean=} dispatch\n   * @return {!Context}\n   * @api public\n   */\n\n\n  Page.prototype.replace = function(path, state, init, dispatch) {\n    var ctx = new Context(path, state, this),\n      prev = this.prevContext;\n    this.prevContext = ctx;\n    this.current = ctx.path;\n    ctx.init = init;\n    ctx.save(); // save before dispatching, which may redirect\n    if (false !== dispatch) this.dispatch(ctx, prev);\n    return ctx;\n  };\n\n  /**\n   * Dispatch the given `ctx`.\n   *\n   * @param {Context} ctx\n   * @api private\n   */\n\n  Page.prototype.dispatch = function(ctx, prev) {\n    var i = 0, j = 0, page = this;\n\n    function nextExit() {\n      var fn = page.exits[j++];\n      if (!fn) return nextEnter();\n      fn(prev, nextExit);\n    }\n\n    function nextEnter() {\n      var fn = page.callbacks[i++];\n\n      if (ctx.path !== page.current) {\n        ctx.handled = false;\n        return;\n      }\n      if (!fn) return unhandled.call(page, ctx);\n      fn(ctx, nextEnter);\n    }\n\n    if (prev) {\n      nextExit();\n    } else {\n      nextEnter();\n    }\n  };\n\n  /**\n   * Register an exit route on `path` with\n   * callback `fn()`, which will be called\n   * on the previous context when a new\n   * page is visited.\n   */\n  Page.prototype.exit = function(path, fn) {\n    if (typeof path === 'function') {\n      return this.exit('*', path);\n    }\n\n    var route = new Route(path, null, this);\n    for (var i = 1; i < arguments.length; ++i) {\n      this.exits.push(route.middleware(arguments[i]));\n    }\n  };\n\n  /**\n   * Handle \"click\" events.\n   */\n\n  /* jshint +W054 */\n  Page.prototype.clickHandler = function(e) {\n    if (1 !== this._which(e)) return;\n\n    if (e.metaKey || e.ctrlKey || e.shiftKey) return;\n    if (e.defaultPrevented) return;\n\n    // ensure link\n    // use shadow dom when available if not, fall back to composedPath()\n    // for browsers that only have shady\n    var el = e.target;\n    var eventPath = e.path || (e.composedPath ? e.composedPath() : null);\n\n    if(eventPath) {\n      for (var i = 0; i < eventPath.length; i++) {\n        if (!eventPath[i].nodeName) continue;\n        if (eventPath[i].nodeName.toUpperCase() !== 'A') continue;\n        if (!eventPath[i].href) continue;\n\n        el = eventPath[i];\n        break;\n      }\n    }\n\n    // continue ensure link\n    // el.nodeName for svg links are 'a' instead of 'A'\n    while (el && 'A' !== el.nodeName.toUpperCase()) el = el.parentNode;\n    if (!el || 'A' !== el.nodeName.toUpperCase()) return;\n\n    // check if link is inside an svg\n    // in this case, both href and target are always inside an object\n    var svg = (typeof el.href === 'object') && el.href.constructor.name === 'SVGAnimatedString';\n\n    // Ignore if tag has\n    // 1. \"download\" attribute\n    // 2. rel=\"external\" attribute\n    if (el.hasAttribute('download') || el.getAttribute('rel') === 'external') return;\n\n    // ensure non-hash for the same path\n    var link = el.getAttribute('href');\n    if(!this._hashbang && this._samePath(el) && (el.hash || '#' === link)) return;\n\n    // Check for mailto: in the href\n    if (link && link.indexOf('mailto:') > -1) return;\n\n    // check target\n    // svg target is an object and its desired value is in .baseVal property\n    if (svg ? el.target.baseVal : el.target) return;\n\n    // x-origin\n    // note: svg links that are not relative don't call click events (and skip page.js)\n    // consequently, all svg links tested inside page.js are relative and in the same origin\n    if (!svg && !this.sameOrigin(el.href)) return;\n\n    // rebuild path\n    // There aren't .pathname and .search properties in svg links, so we use href\n    // Also, svg href is an object and its desired value is in .baseVal property\n    var path = svg ? el.href.baseVal : (el.pathname + el.search + (el.hash || ''));\n\n    path = path[0] !== '/' ? '/' + path : path;\n\n    // strip leading \"/[drive letter]:\" on NW.js on Windows\n    if (hasProcess && path.match(/^\\/[a-zA-Z]:\\//)) {\n      path = path.replace(/^\\/[a-zA-Z]:\\//, '/');\n    }\n\n    // same page\n    var orig = path;\n    var pageBase = this._getBase();\n\n    if (path.indexOf(pageBase) === 0) {\n      path = path.substr(pageBase.length);\n    }\n\n    if (this._hashbang) path = path.replace('#!', '');\n\n    if (pageBase && orig === path && (!isLocation || this._window.location.protocol !== 'file:')) {\n      return;\n    }\n\n    e.preventDefault();\n    this.show(orig);\n  };\n\n  /**\n   * Handle \"populate\" events.\n   * @api private\n   */\n\n  Page.prototype._onpopstate = (function () {\n    var loaded = false;\n    if ( ! hasWindow ) {\n      return function () {};\n    }\n    if (hasDocument && document.readyState === 'complete') {\n      loaded = true;\n    } else {\n      window.addEventListener('load', function() {\n        setTimeout(function() {\n          loaded = true;\n        }, 0);\n      });\n    }\n    return function onpopstate(e) {\n      if (!loaded) return;\n      var page = this;\n      if (e.state) {\n        var path = e.state.path;\n        page.replace(path, e.state);\n      } else if (isLocation) {\n        var loc = page._window.location;\n        page.show(loc.pathname + loc.search + loc.hash, undefined, undefined, false);\n      }\n    };\n  })();\n\n  /**\n   * Event button.\n   */\n  Page.prototype._which = function(e) {\n    e = e || (hasWindow && this._window.event);\n    return null == e.which ? e.button : e.which;\n  };\n\n  /**\n   * Convert to a URL object\n   * @api private\n   */\n  Page.prototype._toURL = function(href) {\n    var window = this._window;\n    if(typeof URL === 'function' && isLocation) {\n      return new URL(href, window.location.toString());\n    } else if (hasDocument) {\n      var anc = window.document.createElement('a');\n      anc.href = href;\n      return anc;\n    }\n  };\n\n  /**\n   * Check if `href` is the same origin.\n   * @param {string} href\n   * @api public\n   */\n  Page.prototype.sameOrigin = function(href) {\n    if(!href || !isLocation) return false;\n\n    var url = this._toURL(href);\n    var window = this._window;\n\n    var loc = window.location;\n\n    /*\n       When the port is the default http port 80 for http, or 443 for\n       https, internet explorer 11 returns an empty string for loc.port,\n       so we need to compare loc.port with an empty string if url.port\n       is the default port 80 or 443.\n       Also the comparition with `port` is changed from `===` to `==` because\n       `port` can be a string sometimes. This only applies to ie11.\n    */\n    return loc.protocol === url.protocol &&\n      loc.hostname === url.hostname &&\n      (loc.port === url.port || loc.port === '' && (url.port == 80 || url.port == 443)); // jshint ignore:line\n  };\n\n  /**\n   * @api private\n   */\n  Page.prototype._samePath = function(url) {\n    if(!isLocation) return false;\n    var window = this._window;\n    var loc = window.location;\n    return url.pathname === loc.pathname &&\n      url.search === loc.search;\n  };\n\n  /**\n   * Remove URL encoding from the given `str`.\n   * Accommodates whitespace in both x-www-form-urlencoded\n   * and regular percent-encoded form.\n   *\n   * @param {string} val - URL component to decode\n   * @api private\n   */\n  Page.prototype._decodeURLEncodedURIComponent = function(val) {\n    if (typeof val !== 'string') { return val; }\n    return this._decodeURLComponents ? decodeURIComponent(val.replace(/\\+/g, ' ')) : val;\n  };\n\n  /**\n   * Create a new `page` instance and function\n   */\n  function createPage() {\n    var pageInstance = new Page();\n\n    function pageFn(/* args */) {\n      return page.apply(pageInstance, arguments);\n    }\n\n    // Copy all of the things over. In 2.0 maybe we use setPrototypeOf\n    pageFn.callbacks = pageInstance.callbacks;\n    pageFn.exits = pageInstance.exits;\n    pageFn.base = pageInstance.base.bind(pageInstance);\n    pageFn.strict = pageInstance.strict.bind(pageInstance);\n    pageFn.start = pageInstance.start.bind(pageInstance);\n    pageFn.stop = pageInstance.stop.bind(pageInstance);\n    pageFn.show = pageInstance.show.bind(pageInstance);\n    pageFn.back = pageInstance.back.bind(pageInstance);\n    pageFn.redirect = pageInstance.redirect.bind(pageInstance);\n    pageFn.replace = pageInstance.replace.bind(pageInstance);\n    pageFn.dispatch = pageInstance.dispatch.bind(pageInstance);\n    pageFn.exit = pageInstance.exit.bind(pageInstance);\n    pageFn.configure = pageInstance.configure.bind(pageInstance);\n    pageFn.sameOrigin = pageInstance.sameOrigin.bind(pageInstance);\n    pageFn.clickHandler = pageInstance.clickHandler.bind(pageInstance);\n\n    pageFn.create = createPage;\n\n    Object.defineProperty(pageFn, 'len', {\n      get: function(){\n        return pageInstance.len;\n      },\n      set: function(val) {\n        pageInstance.len = val;\n      }\n    });\n\n    Object.defineProperty(pageFn, 'current', {\n      get: function(){\n        return pageInstance.current;\n      },\n      set: function(val) {\n        pageInstance.current = val;\n      }\n    });\n\n    // In 2.0 these can be named exports\n    pageFn.Context = Context;\n    pageFn.Route = Route;\n\n    return pageFn;\n  }\n\n  /**\n   * Register `path` with callback `fn()`,\n   * or route `path`, or redirection,\n   * or `page.start()`.\n   *\n   *   page(fn);\n   *   page('*', fn);\n   *   page('/user/:id', load, user);\n   *   page('/user/' + user.id, { some: 'thing' });\n   *   page('/user/' + user.id);\n   *   page('/from', '/to')\n   *   page();\n   *\n   * @param {string|!Function|!Object} path\n   * @param {Function=} fn\n   * @api public\n   */\n\n  function page(path, fn) {\n    // <callback>\n    if ('function' === typeof path) {\n      return page.call(this, '*', path);\n    }\n\n    // route <path> to <callback ...>\n    if ('function' === typeof fn) {\n      var route = new Route(/** @type {string} */ (path), null, this);\n      for (var i = 1; i < arguments.length; ++i) {\n        this.callbacks.push(route.middleware(arguments[i]));\n      }\n      // show <path> with [state]\n    } else if ('string' === typeof path) {\n      this['string' === typeof fn ? 'redirect' : 'show'](path, fn);\n      // start [options]\n    } else {\n      this.start(path);\n    }\n  }\n\n  /**\n   * Unhandled `ctx`. When it's not the initial\n   * popstate then redirect. If you wish to handle\n   * 404s on your own use `page('*', callback)`.\n   *\n   * @param {Context} ctx\n   * @api private\n   */\n  function unhandled(ctx) {\n    if (ctx.handled) return;\n    var current;\n    var page = this;\n    var window = page._window;\n\n    if (page._hashbang) {\n      current = isLocation && this._getBase() + window.location.hash.replace('#!', '');\n    } else {\n      current = isLocation && window.location.pathname + window.location.search;\n    }\n\n    if (current === ctx.canonicalPath) return;\n    page.stop();\n    ctx.handled = false;\n    isLocation && (window.location.href = ctx.canonicalPath);\n  }\n\n  /**\n   * Escapes RegExp characters in the given string.\n   *\n   * @param {string} s\n   * @api private\n   */\n  function escapeRegExp(s) {\n    return s.replace(/([.+*?=^!:${}()[\\]|/\\\\])/g, '\\\\$1');\n  }\n\n  /**\n   * Initialize a new \"request\" `Context`\n   * with the given `path` and optional initial `state`.\n   *\n   * @constructor\n   * @param {string} path\n   * @param {Object=} state\n   * @api public\n   */\n\n  function Context(path, state, pageInstance) {\n    var _page = this.page = pageInstance || page;\n    var window = _page._window;\n    var hashbang = _page._hashbang;\n\n    var pageBase = _page._getBase();\n    if ('/' === path[0] && 0 !== path.indexOf(pageBase)) path = pageBase + (hashbang ? '#!' : '') + path;\n    var i = path.indexOf('?');\n\n    this.canonicalPath = path;\n    var re = new RegExp('^' + escapeRegExp(pageBase));\n    this.path = path.replace(re, '') || '/';\n    if (hashbang) this.path = this.path.replace('#!', '') || '/';\n\n    this.title = (hasDocument && window.document.title);\n    this.state = state || {};\n    this.state.path = path;\n    this.querystring = ~i ? _page._decodeURLEncodedURIComponent(path.slice(i + 1)) : '';\n    this.pathname = _page._decodeURLEncodedURIComponent(~i ? path.slice(0, i) : path);\n    this.params = {};\n\n    // fragment\n    this.hash = '';\n    if (!hashbang) {\n      if (!~this.path.indexOf('#')) return;\n      var parts = this.path.split('#');\n      this.path = this.pathname = parts[0];\n      this.hash = _page._decodeURLEncodedURIComponent(parts[1]) || '';\n      this.querystring = this.querystring.split('#')[0];\n    }\n  }\n\n  /**\n   * Push state.\n   *\n   * @api private\n   */\n\n  Context.prototype.pushState = function() {\n    var page = this.page;\n    var window = page._window;\n    var hashbang = page._hashbang;\n\n    page.len++;\n    if (hasHistory) {\n        window.history.pushState(this.state, this.title,\n          hashbang && this.path !== '/' ? '#!' + this.path : this.canonicalPath);\n    }\n  };\n\n  /**\n   * Save the context state.\n   *\n   * @api public\n   */\n\n  Context.prototype.save = function() {\n    var page = this.page;\n    if (hasHistory) {\n        page._window.history.replaceState(this.state, this.title,\n          page._hashbang && this.path !== '/' ? '#!' + this.path : this.canonicalPath);\n    }\n  };\n\n  /**\n   * Initialize `Route` with the given HTTP `path`,\n   * and an array of `callbacks` and `options`.\n   *\n   * Options:\n   *\n   *   - `sensitive`    enable case-sensitive routes\n   *   - `strict`       enable strict matching for trailing slashes\n   *\n   * @constructor\n   * @param {string} path\n   * @param {Object=} options\n   * @api private\n   */\n\n  function Route(path, options, page) {\n    var _page = this.page = page || globalPage;\n    var opts = options || {};\n    opts.strict = opts.strict || _page._strict;\n    this.path = (path === '*') ? '(.*)' : path;\n    this.method = 'GET';\n    this.regexp = pathToRegexp_1(this.path, this.keys = [], opts);\n  }\n\n  /**\n   * Return route middleware with\n   * the given callback `fn()`.\n   *\n   * @param {Function} fn\n   * @return {Function}\n   * @api public\n   */\n\n  Route.prototype.middleware = function(fn) {\n    var self = this;\n    return function(ctx, next) {\n      if (self.match(ctx.path, ctx.params)) {\n        ctx.routePath = self.path;\n        return fn(ctx, next);\n      }\n      next();\n    };\n  };\n\n  /**\n   * Check if this route matches `path`, if so\n   * populate `params`.\n   *\n   * @param {string} path\n   * @param {Object} params\n   * @return {boolean}\n   * @api private\n   */\n\n  Route.prototype.match = function(path, params) {\n    var keys = this.keys,\n      qsIndex = path.indexOf('?'),\n      pathname = ~qsIndex ? path.slice(0, qsIndex) : path,\n      m = this.regexp.exec(decodeURIComponent(pathname));\n\n    if (!m) return false;\n\n    delete params[0];\n\n    for (var i = 1, len = m.length; i < len; ++i) {\n      var key = keys[i - 1];\n      var val = this.page._decodeURLEncodedURIComponent(m[i]);\n      if (val !== undefined || !(hasOwnProperty.call(params, key.name))) {\n        params[key.name] = val;\n      }\n    }\n\n    return true;\n  };\n\n\n  /**\n   * Module exports.\n   */\n\n  var globalPage = createPage();\n  var page_js = globalPage;\n  var default_1 = globalPage;\n\npage_js.default = default_1;\n\nexport default page_js;\n"
  },
  {
    "path": "rollup.config.js",
    "content": "import commonjs from 'rollup-plugin-commonjs';\nimport nodeResolve from 'rollup-plugin-node-resolve';\n\nexport default {\n  input: 'index.js',\n  output: {\n    file: 'page.js',\n    format: 'umd',\n    name: 'page'\n  },\n  plugins: [\n    nodeResolve({\n      jsnext: true,\n      main: true\n    }),\n    commonjs({\n      include: ['node_modules/**', '**']\n    })\n  ]\n};\n"
  },
  {
    "path": "test/demos/back-demo.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n<title>Blank page</title>\n<body>\n  <ul class=\"links\">\n    <li><a class=\"current-page\" href=\"./back-demo.html?key=val#hash\">Click me</a></li>\n  </ul>\n\n  <script src=\"../page.js\"></script>\n  <script>\n    page(\"/test/demos/back-demo.html\", function(ctx){\n      console.assert(ctx.querystring === \"key=val\");\n    });\n  </script>\n</body>\n"
  },
  {
    "path": "test/index.html",
    "content": "<html>\n  <head>\n    <title>page.js - tests</title>\n    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n    <link rel=\"stylesheet\" href=\"https://cdn.rawgit.com/visionmedia/mocha/1.20.1/mocha.css\" />\n  </head>\n  <body>\n    <div id=\"mocha\"></div>\n    <script src=\"https://cdn.rawgit.com/visionmedia/mocha/1.20.1/mocha.js\"></script>\n    <script src=\"https://cdn.rawgit.com/chaijs/chai/1.9.1/chai.js\"></script>\n    <script>mocha.setup('bdd')</script>\n    <script src=\"page.js\"></script>\n    <script src=\"tests.js\"></script>\n    <script>\n      mocha.run();\n    </script>\n  </body>\n</html>\n"
  },
  {
    "path": "test/mocha.opts",
    "content": "-R spec\n"
  },
  {
    "path": "test/support/jsdom.js",
    "content": "\nfunction setupJsdom(options, next) {\n  options = options || {};\n\n  var jsdom = require('jsdom');\n  var html = '<!doctype html><html><head></head><body></body></html>';\n\n  function setupGlobals(window) {\n    window.console = console;\n    if(window.location.protocol !== 'file:')\n      window.history.replaceState(null, '', '/');\n    global.window = window;\n    global.location = window.location;\n    global.document = window.document;\n    global.history = window.history;\n    window._$jscoverage = global._$jscoverage;\n  }\n\n  if(jsdom.env) {\n    jsdom.env({\n      html: html,\n      url: options.url || 'http://example.com',\n      done: function(errors, window) {\n        setupGlobals(window);\n        if (errors) {\n          errors.forEach(console.log);\n          throw new Error(errors[0].data.error);\n        }\n        next();\n      }\n    });\n  } else {\n    var dom = new jsdom.JSDOM(html, {\n      url: options.url || 'http://example.com'\n    });\n    setupGlobals(dom.window);\n    next();\n  }\n}\n\nexports.setup = setupJsdom;\n\nbefore(function(next) {\n  setupJsdom({}, next);\n});\n"
  },
  {
    "path": "test/test-page.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n<title>Blank page</title>\n<body>\n  <ul class=\"links\">\n    <li><a class=\"index\" href=\"./\">/</a></li>\n    <li><a class=\"whoop\" href=\"#whoop\">#whoop</a></li>\n    <li><a class=\"about\" href=\"./about\">/about</a></li>\n    <li><a class=\"query\" href=\"./query?foo=bar\">/query?foo=bar</a></li>\n    <li><a class=\"query-hash\" href=\"./query#page\">/query#page</a></li>\n    <li><a class=\"link-trailing\" href=\"./link-trailing/\">/link-trailing/</a></li>\n    <li><a class=\"link-no-trailing\" href=\"./link-no-trailing\">/link-no-trailing</a></li>\n    <li><a class=\"contact\" href=\"./contact\">/contact</a></li>\n    <li><a class=\"contact-me\" href=\"./contact/me\">/contact/me</a></li>\n    <li><a class=\"not-found\" href=\"./not-found?foo=bar\">/not-found</a></li>\n    <li><a class=\"diff-domain\" href=\"http://example.com.uk/diff/domain\">another domain</a></li>\n    <li><a class=\"shadow-path\" href=\"./shadow\">/shadow</a></li>\n  </ul>\n</body>\n"
  },
  {
    "path": "test/tests.js",
    "content": "/* globals before, after, chai, expect, page, describe, it */\n(function() {\n\n  'use strict';\n\n  var isNode = typeof window !== 'object',\n    global = this,\n    called = false,\n    baseRoute = Function.prototype, // noop\n    html = '',\n    base = '',\n    setbase = true,\n    hashbang = false,\n    decodeURLComponents = true,\n    chai = this.chai,\n    expect = this.expect,\n    page = this.page,\n    globalPage = this.page,\n    baseTag,\n    frame,\n    $,\n    jsdomSupport;\n\n  if (isNode) {\n    jsdomSupport = require('./support/jsdom');\n  }\n\n  before(function() {\n    if (isNode) {\n      chai = require('chai');\n      expect = chai.expect;\n      globalPage = process.env.PAGE_COV ?\n        require('../index-cov') : require('../index');\n    } else {\n      globalPage = window.page;\n      expect = chai.expect;\n    }\n\n    $ = function(sel) {\n      return frame.contentWindow.document.querySelector(sel);\n    };\n\n  });\n\n  var fireEvent = function(node, eventName, path) {\n      var event;\n\n      if(typeof testWindow().Event === 'function') {\n        var MouseEvent = testWindow().MouseEvent;\n        event = new MouseEvent(eventName, {\n          bubbles: true,\n          button: 1\n        });\n        Object.defineProperty(event, 'which', { value: null });\n      } else {\n        event = testWindow().document.createEvent('MouseEvents');\n\n        // https://developer.mozilla.org/en-US/docs/Web/API/event.initMouseEvent\n        event.initEvent(\n          eventName, true, true, this, 0,\n          event.screenX, event.screenY, event.clientX, event.clientY,\n          false, false, false, false,\n          0, null);\n\n        event.button = 1;\n        event.which = null;\n      }\n\n      if(path) {\n        Object.defineProperty(event, 'path', {\n          value: path\n        });\n      }\n\n      node.dispatchEvent(event);\n    },\n    testWindow = function(){\n      return frame.contentWindow;\n    },\n    beforeTests = function(options, done) {\n      options = options || {};\n      page = globalPage.create();\n\n      page('/', function(ctx) {\n        called = true;\n        baseRoute(ctx);\n      });\n\n      function onFrameLoad(){\n        if(setbase) {\n          if(options.base)\n            page.base(options.base);\n          var baseTag = frame.contentWindow.document.createElement('base');\n          frame.contentWindow.document.head.appendChild(baseTag);\n\n          baseTag.setAttribute('href', (base ? base + '/' : '/'));\n        }\n\n        options.window = frame.contentWindow;\n        if(options.strict != null)\n          page.strict(options.strict);\n        page.start(options);\n        page(base ? base + '/' : '/');\n        done();\n      }\n\n      frame = document.createElement('iframe');\n      document.body.appendChild(frame);\n      if(isNode) {\n        var cntn = require('fs').readFileSync(__dirname + '/test-page.html', 'utf8');\n        cntn = cntn.replace('<!doctype html>', '').trim();\n        cntn = cntn.replace('<html lang=\"en\">', '');\n        frame.contentWindow.document.documentElement.innerHTML = cntn;\n        onFrameLoad();\n      } else {\n        frame.src = './test-page.html';\n        frame.addEventListener('load', onFrameLoad);\n      }\n    },\n    replaceable = function(route) {\n      function realCallback(ctx) {\n        obj.callback(ctx);\n      }\n\n      var obj = {\n        callback: Function.prototype,\n        replace: function(cb){\n          obj.callback = cb;\n        },\n        once: function(cb){\n          obj.replace(function(ctx){\n            obj.callback = Function.prototype;\n            cb(ctx);\n          });\n        }\n      };\n\n      page(route, realCallback);\n\n      return obj;\n    },\n    tests = function() {\n      describe('on page load', function() {\n        it('should invoke the matching callback', function() {\n          expect(called).to.equal(true);\n        });\n\n        it('should invoke the matching async callbacks', function(done) {\n          page('/async', function(ctx, next) {\n            setTimeout(function() {\n              next();\n            }, 10);\n          }, function(ctx, next) {\n            setTimeout(function() {\n              done();\n            }, 10);\n          });\n          page('/async');\n        });\n      });\n\n      describe('on redirect', function() {\n        it('should load destination page', function(done) {\n          page.redirect('/from', '/to');\n          page('/to', function() {\n            done();\n          });\n          page('/from');\n        });\n        it('should work with short alias', function(done) {\n          page('/one', '/two');\n          page('/two', function() {\n            done();\n          });\n          page('/one');\n        });\n        it('should load done within redirect', function(done) {\n          page('/redirect', function() {\n            page.redirect('/done');\n          });\n          page('/done', function() {\n            done();\n          });\n          page('/redirect');\n        });\n      });\n\n      describe('on exit', function() {\n        it('should run when exiting the page', function(done) {\n          var visited = false;\n          page('/exit', function() {\n            visited = true;\n          });\n\n          page.exit('/exit', function() {\n            expect(visited).to.equal(true);\n            done();\n          });\n\n          page('/exit');\n          page('/');\n        });\n\n        it('should run async callbacks when exiting the page', function(done) {\n          var visited = false;\n          page('/async-exit', function() {\n            visited = true;\n          });\n\n          page.exit('/async-exit', function(ctx, next) {\n            setTimeout(function() {\n              next();\n            }, 10);\n          }, function(ctx, next) {\n            setTimeout(function () {\n              expect(visited).to.equal(true);\n              done();\n            }, 10);\n          });\n\n          page('/async-exit');\n          page('/');\n        });\n\n        it('should only run on matched routes', function(done) {\n          page('/should-exit', function() {});\n          page('/', function() {});\n\n          page.exit('/should-not-exit', function() {\n            throw new Error('This exit route should not have been called');\n          });\n\n          page.exit('/should-exit', function() {\n            done();\n          });\n\n          page('/should-exit');\n          page('/');\n        });\n\n        it('should use the previous context', function(done) {\n          var unique;\n\n          page('/', function() {});\n          page('/bootstrap', function(ctx) {\n            unique = ctx.unique = {};\n          });\n\n          page.exit('/bootstrap', function(ctx) {\n            expect(ctx.unique).to.equal(unique);\n            done();\n          });\n\n          page('/bootstrap');\n          page('/');\n        });\n      });\n\n      describe('no dispatch', function() {\n        it('should use the previous context when not dispatching', function(done) {\n          var count = 0;\n\n          page('/', function() {});\n\n          page.exit(function(context) {\n            var path = context.path;\n            setTimeout( function() {\n              expect(path).to.equal('/');\n              page.replace( '/', null, false, false);\n              if ( count === 2 ) {\n                done();\n                return;\n              }\n              count++;\n            }, 0);\n          });\n\n          page('/');\n\n          page('/bootstrap');\n\n          setTimeout( function() {\n            page('/bootstrap');\n          }, 0 );\n        });\n\n\n        after(function() {\n          // remove exit handler that was added\n          page.exits.pop();\n        });\n      });\n\n      describe('page.back', function() {\n        var first;\n\n        before(function() {\n          first = replaceable('/first', function(){});\n          page('/second', function() {});\n          page('/first');\n          page('/second');\n        });\n\n        it('should move back to history', function(done) {\n          first.once(function(){\n            var path = hashbang\n              ? testWindow().location.hash.replace('#!', '')\n              : testWindow().location.pathname;\n            path = path.replace(base, '');\n            expect(path).to.be.equal('/first');\n            done();\n          });\n\n          page.back('/first');\n\n        });\n\n        it('should decrement page.len on back()', function() {\n          var lenAtFirst = page.len;\n          page('/second');\n          page.back('/first');\n          expect(page.len).to.be.equal(lenAtFirst);\n        });\n\n        it('calling back() when there is nothing in the history should go to the given path', function(done){\n          page('/fourth', function(){\n            expect(page.len).to.be.equal(0);\n            done();\n          });\n          page.len = 0;\n          page.back('/fourth');\n        });\n\n        it('calling back with nothing in the history and no path should go to the base', function(done){\n          baseRoute = function(){\n            expect(page.len).to.be.equal(0);\n            baseRoute = Function.prototype;\n            done();\n          };\n          page.len = 0;\n          page.back();\n        });\n      });\n\n      describe('ctx.querystring', function() {\n        it('should default to \"\"', function(done) {\n          page('/querystring-default', function(ctx) {\n            expect(ctx.querystring).to.equal('');\n            done();\n          });\n\n          page('/querystring-default');\n        });\n\n        it('should expose the query string', function(done) {\n          page('/querystring', function(ctx) {\n            expect(ctx.querystring).to.equal('hello=there');\n            done();\n          });\n\n          page('/querystring?hello=there');\n        });\n\n        it('should accommodate URL encoding', function(done) {\n          page('/whatever', function(ctx) {\n            var expected = decodeURLComponents\n              ? 'queryParam=string with whitespace'\n              : 'queryParam=string%20with%20whitespace';\n            expect(ctx.querystring).to.equal(expected);\n            done();\n          });\n\n          page('/whatever?queryParam=string%20with%20whitespace');\n        });\n      });\n\n      describe('ctx.pathname', function() {\n        it('should default to ctx.path', function(done) {\n          page('/pathname-default', function(ctx) {\n            expect(ctx.pathname).to.equal(base + (base && hashbang ? '#!' : '') + '/pathname-default');\n            done();\n          });\n\n          page('/pathname-default');\n        });\n\n        it('should omit the query string', function(done) {\n          page('/pathname', function(ctx) {\n            expect(ctx.pathname).to.equal(base + (base && hashbang ? '#!' : '') + '/pathname');\n            done();\n          });\n\n          page('/pathname?hello=there');\n        });\n\n        it('should accommodate URL encoding', function(done) {\n          page('/long path with whitespace', function(ctx) {\n            expect(ctx.pathname).to.equal(base + (base && hashbang ? '#!' : '') +\n              (decodeURLComponents ? '/long path with whitespace' : '/long%20path%20with%20whitespace'));\n            done();\n          });\n\n          page('/long%20path%20with%20whitespace');\n        });\n      });\n\n      describe('ctx.params', function() {\n        it('should always be URL-decoded', function(done) {\n          page('/whatever/:param', function(ctx) {\n            expect(ctx.params.param).to.equal('param with whitespace');\n            done();\n          });\n\n          page('/whatever/param%20with%20whitespace');\n        });\n\n        it('should be an object', function(done) {\n          page('/ctxparams/:param/', function(ctx) {\n            expect(ctx.params).to.not.be.an('array');\n            expect(ctx.params).to.be.an('object');\n            done();\n          });\n          page('/ctxparams/test/');\n        });\n        \n        it('should handle optional first param', function(done) {\n          page(/^\\/ctxparams\\/(option1|option2)?$/, function(ctx) {\n            expect(ctx.params[0]).to.be.undefined;\n            done();\n          });\n          page('/ctxparams/');\n        });\n\n        it('should have the original routePath', function(done) {\n          page('/route/:param', function(ctx) {\n            expect(ctx.routePath).to.equal('/route/:param');\n            done();\n          });\n          page('/route/value');\n        });\n      });\n\n      describe('ctx.handled', function() {\n        it('should skip unhandled redirect if exists', function() {\n          page('/page/:page', function(ctx, next) {\n            ctx.handled = true;\n            next();\n          });\n          var ctx = page.show('/page/1');\n          expect(ctx.handled).to.be.ok;\n        });\n      });\n\n      describe('links dispatcher', function() {\n        it('should invoke the callback', function(done) {\n          page('/about', function() {\n            done();\n          });\n\n          fireEvent($('.about'), 'click');\n        });\n\n        it('should handle trailing slashes in URL', function(done) {\n          page('/link-trailing', function() {\n            expect(page.strict()).to.equal(false);\n            done();\n          });\n          page('/link-trailing/', function() {\n            expect(page.strict()).to.equal(true);\n            done();\n          });\n          fireEvent($('.link-trailing'), 'click');\n        });\n\n        it('should handle trailing slashes in route', function(done) {\n          page('/link-no-trailing/', function() {\n            expect(page.strict()).to.equal(false);\n            done();\n          });\n          page('/link-no-trailing', function() {\n            expect(page.strict()).to.equal(true);\n            done();\n          });\n          fireEvent($('.link-no-trailing'), 'click');\n        });\n\n        it('should invoke the callback with the right params', function(done) {\n          page('/contact/:name', function(ctx) {\n            expect(ctx.params.name).to.equal('me');\n            done();\n          });\n          fireEvent($('.contact-me'), 'click');\n        });\n\n        it('should not invoke the callback', function() {\n          page('/whoop', function(ctx) {\n            expect(true).to.equal(false);\n          });\n          fireEvent($('.whoop'), 'click');\n        });\n\n        it('should not fire when navigating to a different domain', function(done){\n          page('/diff-domain', function(ctx){\n            expect(true).to.equal(false);\n          });\n\n          testWindow().document.addEventListener('click', function onDocClick(ev){\n            ev.preventDefault();\n            testWindow().document.removeEventListener('click', onDocClick);\n            done();\n          });\n\n          fireEvent($('.diff-domain'), 'click');\n        });\n\n        it('works with shadow paths', function() {\n          page('/shadow', function() {\n            expect(true).to.equal(true);\n            page('/');\n          });\n\n          fireEvent($('.shadow-path'), 'click', [$('.shadow-path')]);\n        });\n      });\n\n\n      describe('dispatcher', function() {\n        it('should ignore query strings', function(done) {\n          page('/qs', function(ctx) {\n            done();\n          });\n\n          page('/qs?test=true');\n        });\n\n        it('should ignore query strings with params', function(done) {\n          page('/qs/:name', function(ctx) {\n            expect(ctx.params.name).to.equal('tobi');\n            done();\n          });\n\n          page('/qs/tobi?test=true');\n        });\n\n        it('should invoke the matching callback', function(done) {\n          page('/user/:name', function(ctx) {\n            done();\n          });\n\n          page('/user/tj');\n        });\n\n        it('should handle trailing slashes in path', function(done) {\n          page('/no-trailing', function() {\n            expect(page.strict()).to.equal(false);\n            done();\n          });\n          page('/no-trailing/', function() {\n            expect(page.strict()).to.equal(true);\n            done();\n          });\n          page('/no-trailing/');\n        });\n\n        it('should handle trailing slashes in route', function(done) {\n          page('/trailing/', function() {\n            expect(page.strict()).to.equal(false);\n            done();\n          });\n          page('/trailing', function() {\n            expect(page.strict()).to.equal(true);\n            done();\n          });\n          page('/trailing');\n        });\n\n        it('should populate ctx.params', function(done) {\n          page('/blog/post/:name', function(ctx) {\n            expect(ctx.params.name).to.equal('something');\n            done();\n          });\n\n          page('/blog/post/something');\n        });\n\n        it('should not include hash in ctx.pathname', function(done){\n          page('/contact', function(ctx){\n            expect(ctx.pathname).to.equal('/contact');\n            done();\n          });\n\n          page(hashbang ? '/contact' : '/contact#bang');\n        });\n\n        describe('when next() is invoked', function() {\n          it('should invoke subsequent matching middleware', function(done) {\n\n            var visistedFirst = false;\n            page('/forum/*', function(ctx, next) {\n              visistedFirst = true;\n              next();\n            });\n\n            page('/forum/:fid/thread/:tid', function(ctx) {\n              expect(visistedFirst).to.equal(true);\n              done();\n            });\n\n            page('/forum/1/thread/2');\n          });\n        });\n\n        describe('not found', function() {\n          it('should invoke the not found callback', function(done) {\n            page(function() {\n              done();\n            });\n            page('/whathever');\n          });\n        });\n      });\n    },\n    afterTests = function() {\n      called = false;\n      page.stop();\n      page.base('');\n      page.strict(false);\n      //page('/');\n      base = '';\n      baseRoute = Function.prototype; // noop\n      setbase = true;\n      decodeURLComponents = true;\n      document.body.removeChild(frame);\n    };\n\n  describe('Html5 history navigation', function() {\n\n    before(function(done) {\n      beforeTests(null, done);\n    });\n\n    tests();\n\n    it('Should dispatch when going to a hash on same path', function(done){\n      var cnt = 0;\n      page('/query', function(){\n        cnt++;\n        if(cnt === 2) {\n          done();\n        }\n      });\n\n      fireEvent($('.query'), 'click');\n      fireEvent($('.query-hash'), 'click');\n    });\n\n    after(function() {\n      afterTests();\n    });\n\n  });\n\n  describe('Configuration', function() {\n    before(function(done) {\n      beforeTests(null, done);\n    });\n\n    it('Can disable popstate', function() {\n      page.configure({ popstate: false });\n    });\n\n    it('Can disable click handler', function() {\n      page.configure({ click: false });\n    });\n\n    after(function() {\n      afterTests();\n    });\n  });\n\n  describe('Hashbang option enabled', function() {\n\n    before(function(done) {\n      hashbang = true;\n      beforeTests({\n        hashbang: hashbang\n      }, done);\n    });\n\n    tests();\n\n    it('Using hashbang, url\\'s pathname not included in path', function(done){\n      page.stop();\n      baseRoute = function(ctx){\n        expect(ctx.path).to.equal('/');\n        done();\n      };\n      page({ hashbang: true, window: frame.contentWindow });\n    });\n\n    after(function() {\n      hashbang = false;\n      afterTests();\n    });\n\n  });\n\n  describe('Different Base', function() {\n\n    before(function(done) {\n      base = '/newBase';\n      beforeTests({\n        base: '/newBase'\n      }, done);\n    });\n\n    tests();\n\n    after(function() {\n      afterTests();\n    });\n\n  });\n\n  describe('URL path component decoding disabled', function() {\n    before(function(done) {\n      decodeURLComponents = false;\n      beforeTests({\n        decodeURLComponents: decodeURLComponents\n      }, done);\n    });\n\n    tests();\n\n    after(function() {\n      afterTests();\n    });\n  });\n\n  describe('Strict path matching enabled', function() {\n    before(function(done) {\n      beforeTests({\n        strict: true\n      }, done);\n    });\n\n    tests();\n\n    after(function() {\n      afterTests();\n    });\n  });\n\n  describe('.clickHandler', function() {\n    it('is exported by the global page', function() {\n      expect(typeof page.clickHandler).to.equal('function');\n    });\n  });\n\n  describe('Environments without the URL constructor', function() {\n    var URLC;\n    before(function(done) {\n      URLC = global.URL;\n      global.URL = undefined;\n      beforeTests(null, done);\n    });\n\n    tests();\n\n    after(function() {\n      global.URL = URLC;\n      afterTests();\n    });\n  });\n\n  var describei = jsdomSupport ? describe : describe.skip;\n\n  describei('File protocol', function() {\n    before(function(done){\n      jsdomSupport.setup({\n        url: 'file:///var/html/index.html'\n      }, Function.prototype);\n\n      setbase = false;\n      hashbang = true;\n      beforeTests({\n        hashbang: hashbang\n      }, done);\n    });\n\n    after(function(){\n      hashbang = false;\n    });\n\n    it('simple route call', function(){\n      page('/about', function(ctx){\n        expect(ctx.path).to.equal('/about');\n      });\n      page('/about');\n    });\n  });\n\n  describe('Route', function() {\n    before(function(done) {\n      beforeTests(null, done);\n    });\n\n    it('Can create Route', function() {\n      var r = new page.Route('/');\n    });\n\n    after(function() {\n      afterTests();\n    });\n  });\n\n}).call(this);\n"
  }
]