Browse Source

Include to Wekan packages directory contents, so that meteor command would build all directly.
This also simplifies build scripts.

Thanks to xet7 !

Lauri Ojansivu 1 month ago
parent
commit
73e265d8fd
100 changed files with 11005 additions and 13 deletions
  1. 13 1
      .gitignore
  2. 13 12
      Dockerfile
  3. 3 0
      packages/kadira-flow-router/.gitignore
  4. 8 0
      packages/kadira-flow-router/.travis.yml
  5. 155 0
      packages/kadira-flow-router/CHANGELOG.md
  6. 16 0
      packages/kadira-flow-router/CONTRIBUTING.md
  7. 21 0
      packages/kadira-flow-router/LICENSE
  8. 777 0
      packages/kadira-flow-router/README.md
  9. 11 0
      packages/kadira-flow-router/client/_init.js
  10. 57 0
      packages/kadira-flow-router/client/group.js
  11. 2 0
      packages/kadira-flow-router/client/modules.js
  12. 125 0
      packages/kadira-flow-router/client/route.js
  13. 587 0
      packages/kadira-flow-router/client/router.js
  14. 112 0
      packages/kadira-flow-router/client/triggers.js
  15. 9 0
      packages/kadira-flow-router/lib/router.js
  16. 81 0
      packages/kadira-flow-router/package.js
  17. 4 0
      packages/kadira-flow-router/server/_init.js
  18. 18 0
      packages/kadira-flow-router/server/group.js
  19. 40 0
      packages/kadira-flow-router/server/plugins/fast_render.js
  20. 28 0
      packages/kadira-flow-router/server/route.js
  21. 146 0
      packages/kadira-flow-router/server/router.js
  22. 10 0
      packages/kadira-flow-router/test/client/_helpers.js
  23. 113 0
      packages/kadira-flow-router/test/client/group.spec.js
  24. 17 0
      packages/kadira-flow-router/test/client/loader.spec.js
  25. 158 0
      packages/kadira-flow-router/test/client/route.reactivity.spec.js
  26. 632 0
      packages/kadira-flow-router/test/client/router.core.spec.js
  27. 208 0
      packages/kadira-flow-router/test/client/router.reactivity.spec.js
  28. 225 0
      packages/kadira-flow-router/test/client/router.subs_ready.spec.js
  29. 570 0
      packages/kadira-flow-router/test/client/trigger.spec.js
  30. 297 0
      packages/kadira-flow-router/test/client/triggers.js
  31. 48 0
      packages/kadira-flow-router/test/common/fast_render_route.js
  32. 16 0
      packages/kadira-flow-router/test/common/group.spec.js
  33. 15 0
      packages/kadira-flow-router/test/common/route.spec.js
  34. 30 0
      packages/kadira-flow-router/test/common/router.addons.spec.js
  35. 135 0
      packages/kadira-flow-router/test/common/router.path.spec.js
  36. 11 0
      packages/kadira-flow-router/test/common/router.url.spec.js
  37. 38 0
      packages/kadira-flow-router/test/server/_helpers.js
  38. 35 0
      packages/kadira-flow-router/test/server/plugins/fast_render.js
  39. 1 0
      packages/markdown/.gitignore
  40. 40 0
      packages/markdown/README.md
  41. 9 0
      packages/markdown/markdown.js
  42. 16 0
      packages/markdown/marked/.editorconfig
  43. 1 0
      packages/markdown/marked/.eslintignore
  44. 29 0
      packages/markdown/marked/.eslintrc.json
  45. 2 0
      packages/markdown/marked/.gitattributes
  46. 42 0
      packages/markdown/marked/.github/ISSUE_TEMPLATE.md
  47. 27 0
      packages/markdown/marked/.github/ISSUE_TEMPLATE/Bug_report.md
  48. 14 0
      packages/markdown/marked/.github/ISSUE_TEMPLATE/Feature_request.md
  49. 11 0
      packages/markdown/marked/.github/ISSUE_TEMPLATE/Proposal.md
  50. 53 0
      packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE.md
  51. 50 0
      packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE/badges.md
  52. 25 0
      packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE/release.md
  53. 3 0
      packages/markdown/marked/.gitignore
  54. 46 0
      packages/markdown/marked/.travis.yml
  55. 43 0
      packages/markdown/marked/LICENSE.md
  56. 15 0
      packages/markdown/marked/Makefile
  57. 76 0
      packages/markdown/marked/README.md
  58. 215 0
      packages/markdown/marked/bin/marked
  59. 23 0
      packages/markdown/marked/bower.json
  60. 10 0
      packages/markdown/marked/component.json
  61. 269 0
      packages/markdown/marked/docs/AUTHORS.md
  62. 1 0
      packages/markdown/marked/docs/CNAME
  63. 74 0
      packages/markdown/marked/docs/CODE_OF_CONDUCT.md
  64. 92 0
      packages/markdown/marked/docs/CONTRIBUTING.md
  65. 24 0
      packages/markdown/marked/docs/PUBLISHING.md
  66. 85 0
      packages/markdown/marked/docs/README.md
  67. 78 0
      packages/markdown/marked/docs/USING_ADVANCED.md
  68. 163 0
      packages/markdown/marked/docs/USING_PRO.md
  69. 426 0
      packages/markdown/marked/docs/broken.md
  70. 72 0
      packages/markdown/marked/docs/demo/demo.css
  71. 534 0
      packages/markdown/marked/docs/demo/demo.js
  72. 78 0
      packages/markdown/marked/docs/demo/index.html
  73. 36 0
      packages/markdown/marked/docs/demo/initial.md
  74. 12 0
      packages/markdown/marked/docs/demo/preview.html
  75. 167 0
      packages/markdown/marked/docs/demo/quickref.md
  76. 105 0
      packages/markdown/marked/docs/demo/worker.js
  77. 133 0
      packages/markdown/marked/docs/img/logo-black-and-white.svg
  78. 32 0
      packages/markdown/marked/docs/img/logo-black.svg
  79. 269 0
      packages/markdown/marked/docs/index.html
  80. 1 0
      packages/markdown/marked/index.js
  81. 11 0
      packages/markdown/marked/jasmine.json
  82. 1689 0
      packages/markdown/marked/lib/marked.js
  83. 114 0
      packages/markdown/marked/man/marked.1
  84. 99 0
      packages/markdown/marked/man/marked.1.txt
  85. 6 0
      packages/markdown/marked/marked.min.js
  86. 69 0
      packages/markdown/marked/package.json
  87. 10 0
      packages/markdown/marked/test/README
  88. 5 0
      packages/markdown/marked/test/browser/index.html
  89. 39 0
      packages/markdown/marked/test/browser/index.js
  90. 66 0
      packages/markdown/marked/test/browser/test.js
  91. 26 0
      packages/markdown/marked/test/helpers/helpers.js
  92. 38 0
      packages/markdown/marked/test/helpers/html-differ.js
  93. 551 0
      packages/markdown/marked/test/index.js
  94. 62 0
      packages/markdown/marked/test/json-to-files.js
  95. 9 0
      packages/markdown/marked/test/new/adjacent_lists.html
  96. 5 0
      packages/markdown/marked/test/new/adjacent_lists.md
  97. 3 0
      packages/markdown/marked/test/new/autolink_lines.html
  98. 2 0
      packages/markdown/marked/test/new/autolink_lines.md
  99. 15 0
      packages/markdown/marked/test/new/autolinks.html
  100. 0 0
      packages/markdown/marked/test/new/autolinks.md

+ 13 - 1
.gitignore

@@ -8,7 +8,6 @@ npm-debug.log
 .vscode/
 .idea/
 .build/*
-packages/
 package-lock.json
 **/parts/
 **/stage
@@ -17,3 +16,16 @@ package-lock.json
 snap/.snapcraft/
 .idea
 .DS_Store
+.DS_Store?
+.build*
+*.browserify.js.cached
+*.browserify.js.map
+.build*
+versions.json
+.versions
+.npm
+.build*
+._*
+.Trashes
+Thumbs.db
+ehthumbs.db

+ 13 - 12
Dockerfile

@@ -191,19 +191,20 @@ RUN \
     fi; \
     \
     # Get additional packages
-    mkdir -p /home/wekan/app/packages && \
+    #mkdir -p /home/wekan/app/packages && \
     chown wekan:wekan --recursive /home/wekan && \
-    cd /home/wekan/app/packages && \
-    gosu wekan:wekan git clone --depth 1 -b master https://github.com/wekan/flow-router.git kadira-flow-router && \
-    gosu wekan:wekan git clone --depth 1 -b master https://github.com/meteor-useraccounts/core.git meteor-useraccounts-core && \
-    gosu wekan:wekan git clone --depth 1 -b master https://github.com/wekan/meteor-accounts-cas.git && \
-    gosu wekan:wekan git clone --depth 1 -b master https://github.com/wekan/wekan-ldap.git && \
-    gosu wekan:wekan git clone --depth 1 -b master https://github.com/wekan/wekan-scrollbar.git && \
-    gosu wekan:wekan git clone --depth 1 -b master https://github.com/wekan/meteor-accounts-oidc.git && \
-    gosu wekan:wekan git clone --depth 1 -b master --recurse-submodules https://github.com/wekan/markdown.git && \
-    gosu wekan:wekan mv meteor-accounts-oidc/packages/switch_accounts-oidc wekan-accounts-oidc && \
-    gosu wekan:wekan mv meteor-accounts-oidc/packages/switch_oidc wekan-oidc && \
-    gosu wekan:wekan rm -rf meteor-accounts-oidc && \
+    # REPOS BELOW ARE INCLUDED TO WEKAN REPO
+    #cd /home/wekan/app/packages && \
+    #gosu wekan:wekan git clone --depth 1 -b master https://github.com/wekan/flow-router.git kadira-flow-router && \
+    #gosu wekan:wekan git clone --depth 1 -b master https://github.com/meteor-useraccounts/core.git meteor-useraccounts-core && \
+    #gosu wekan:wekan git clone --depth 1 -b master https://github.com/wekan/meteor-accounts-cas.git && \
+    #gosu wekan:wekan git clone --depth 1 -b master https://github.com/wekan/wekan-ldap.git && \
+    #gosu wekan:wekan git clone --depth 1 -b master https://github.com/wekan/wekan-scrollbar.git && \
+    #gosu wekan:wekan git clone --depth 1 -b master https://github.com/wekan/meteor-accounts-oidc.git && \
+    #gosu wekan:wekan git clone --depth 1 -b master --recurse-submodules https://github.com/wekan/markdown.git && \
+    #gosu wekan:wekan mv meteor-accounts-oidc/packages/switch_accounts-oidc wekan-accounts-oidc && \
+    #gosu wekan:wekan mv meteor-accounts-oidc/packages/switch_oidc wekan-oidc && \
+    #gosu wekan:wekan rm -rf meteor-accounts-oidc && \
     sed -i 's/api\.versionsFrom/\/\/api.versionsFrom/' /home/wekan/app/packages/meteor-useraccounts-core/package.js && \
     cd /home/wekan/.meteor && \
     gosu wekan:wekan /home/wekan/.meteor/meteor -- help; \

+ 3 - 0
packages/kadira-flow-router/.gitignore

@@ -0,0 +1,3 @@
+.build*
+*.browserify.js.cached
+*.browserify.js.map

+ 8 - 0
packages/kadira-flow-router/.travis.yml

@@ -0,0 +1,8 @@
+sudo: required
+language: node_js
+node_js:
+  - "0.10"
+before_install:
+  - "curl -L http://git.io/ejPSng | /bin/sh"
+env:
+  - TEST_COMMAND=meteor

+ 155 - 0
packages/kadira-flow-router/CHANGELOG.md

@@ -0,0 +1,155 @@
+# Changelog
+
+### v2.12.1
+
+* Add NPM modules back. Fixes: [#602](https://github.com/kadirahq/flow-router/issues/602)
+
+### v2.12.0
+
+* Update Fast Render to v2.14.0
+
+### v2.11.0
+
+* Add support for Meteor 1.3 RC-1.
+* Removes browserify and get modules from Meteor 1.3.
+
+### v2.10.1
+* Fix the url generation for prefixed paths. See: [#508](https://github.com/kadirahq/flow-router/issues/508)
+
+### v2.10.0
+* Update few dependencies to the latest versions: pagejs, qs, cosmos:browserify
+
+### v2.9.0
+* Add FlowRouter.url() See: [#374](https://github.com/kadirahq/flow-router/pull/374)
+
+### v2.8.0
+* Allow to access options in groups as well. See: [#378](https://github.com/kadirahq/flow-router/pull/378)
+
+### v2.7.0
+* Add Path Prefix support. See: [#329](https://github.com/kadirahq/flow-router/pull/329)
+
+### v2.6.2
+* Now .current() sends a cloned version of the internal current object. Which prevent outside mutations to params and queryParams
+
+### v2.6.1
+
+* Fix [#143](https://github.com/kadirahq/flow-router/issues/314).
+  This says that when we are doing a trigger redirect,
+  We won't get reactive changes like: `getRouteName()`
+
+### v2.6.0
+* Add hashbang support. See [#311](https://github.com/kadirahq/flow-router/pull/311)
+
+### v2.5.0
+* Add a stop callback on the triggers. See: [#306](https://github.com/kadirahq/flow-router/pull/306).
+
+### v2.4.0
+
+* Add a name to the route groups. See: [#290](https://github.com/kadirahq/flow-router/pull/290)
+
+### v2.3.0
+* We've used `path` for both the current path and for the pathDef earlier. Now we differentiate it. See: [#272](https://github.com/kadirahq/flow-router/issues/272) and [#273](https://github.com/kadirahq/flow-router/pull/273) for more information.
+
+### v2.2.0
+* Add the first addOn api: FlowRouter.onRouteRegister(cb)
+
+### v2.1.1
+* There was an issue in IE9 support. We fix it with this version.
+
+### v2.1.0
+* Add IE9 Support. See this issue [#111](https://github.com/kadirahq/flow-router/issues/111) for more info.
+
+### v2.0.2
+
+* Add missing queryParams object in the subscriptions method (with FR on the server)
+* With that, [#237](https://github.com/kadirahq/flow-router/issues/237) is partially fixed.
+
+### v2.0.1
+
+* Use pagejs.redirect() for our redirection process.
+* Above fixes [#239](https://github.com/kadirahq/flow-router/issues/239)
+
+### v2.0.0
+
+* Released 2.0  :)
+* Now flow-router comes as `kadira:flow-router`
+* Remove deprecated APIs
+    - `FlowRouter.reactiveCurrent()`
+    - Middlewares
+    - `FlowRouter.current().params.query`
+* Follow the [migration guide](https://github.com/kadirahq/flow-router#migrating-into-20) for more information.
+
+### v1.18.0
+
+* Implement idempotent routing on withReplaceState. See: [#197](https://github.com/meteorhacks/flow-router/issues/197)
+* Add an [API](https://github.com/meteorhacks/flow-router#flowrouterwithtrailingslashfn) to set trailing slashes.
+
+### v1.17.2
+* Fix [#182](https://github.com/meteorhacks/flow-router/issues/182) - Now trigger's redirect function support `FlowRouter.go()` syntax.
+
+### v1.17.1
+
+* Fix [#164](https://github.com/meteorhacks/flow-router/issues/164) - It's an issue when using `check` with flow router query params.
+* Fix [#168](https://github.com/meteorhacks/flow-router/pull/168) - It's URL encoding issue.
+
+### v1.17.0
+
+* Add an API called `FlowRouter.wait()` to wait the initialization and pass it back to the app. Fixes issue [180](https://github.com/meteorhacks/flow-router/issues/180).
+
+### v1.16.3
+
+* Fix a crazy context switching issue. For more information see commit [6ca54cc](https://github.com/meteorhacks/flow-router/commit/6ca54cc7969b3a8aa71d63c98c99a20b175125a2)
+
+### v1.16.2
+* Fix issue [#167](https://github.com/meteorhacks/flow-router/issues/167) via [#175](https://github.com/meteorhacks/flow-router/pull/175)
+* Fix [#176](https://github.com/meteorhacks/flow-router/issues/176) by the removal of `Tracker.flush` usage.
+
+### v1.16.1
+* Fix [issue](https://github.com/meteorhacks/flow-router/pull/173) of overwriting global triggers when written multiple times.
+
+### v1.16.0
+
+* [Refactor](https://github.com/meteorhacks/flow-router/pull/172) triggers API for clean code
+* Added [redirect](https://github.com/meteorhacks/flow-router#redirecting-with-triggers) functionality for triggers
+* Now we are API complete for the 2.x release
+
+### v1.15.0
+
+* Now all our routes are idempotent.
+* If some one needs to re-run the route, he needs to use our `FlowRouter.reload()` API.
+
+### v1.14.1
+
+* Fix regression came from v1.11.0. With that, `FlowRouter.go("/")` does not work. More information on [#147](https://github.com/meteorhacks/flow-router/issues/147).
+
+### v1.14.0
+* Bring browserify back with the updated version of `cosmos:browserify` which fixes some size issues. See [more info](https://github.com/meteorhacks/flow-router/issues/128#issuecomment-109799953).
+
+### v1.13.0
+* Remove browserified pagejs and qs dependency loading. With that we could reduce ~10kb of data size (without compression). We can look for a bower integration in the future. For now, here are the dependencies we have.
+    - [email protected]: https://github.com/visionmedia/page.js
+    - [email protected]: https://github.com/hapijs/qs
+
+### v1.12.0
+* Add [`FlowRouter.withReplaceState`](https://github.com/meteorhacks/flow-router#flowrouterwithreplcaestatefn) api to use replaceState when changing routes via FlowRouter apis.
+
+### v1.11.0
+* Fix [#145](https://github.com/meteorhacks/flow-router/issues/145) by changing how safeToRun works.
+* Add `FlowRouter.path()` to the server side
+* Fix [#130](https://github.com/meteorhacks/flow-router/issues/130)
+
+### v1.10.0
+Add support for [triggers](https://github.com/meteorhacks/flow-router#triggers). This is something similar to middlewares but not as middlewares. Visit [here](https://github.com/meteorhacks/flow-router/pull/59) to learn about design decisions.
+
+_**Now, middlewares are deprecated.**_
+
+### v1.9.0
+Fix [#120](https://github.com/meteorhacks/flow-router/issues/120) and added callback support for `FlowRouter.subsReady()`.
+
+### v1.8.0
+
+This release comes with improvements to the reactive API.
+
+* Fixed [#77](https://github.com/meteorhacks/flow-router/issues/77), [#85](https://github.com/meteorhacks/flow-router/issues/85), [#95](https://github.com/meteorhacks/flow-router/issues/95), [#96](https://github.com/meteorhacks/flow-router/issues/96), [#103](https://github.com/meteorhacks/flow-router/issues/103)
+* Add a new API called `FlowRouter.watchPathChange()`
+* Deprecated `FlowRouter.reactiveCurrent()` in the favour of `FlowRouter.watchPathChange()`

+ 16 - 0
packages/kadira-flow-router/CONTRIBUTING.md

@@ -0,0 +1,16 @@
+## Whether to submit an issue or not?
+
+We've very limited time to answer all the issues and respond them in a proper manner. 
+So, this repo's issue list only used to report **bugs** and **new features.**
+
+For any other questions, issues or asking for best practices use [Meteor Forums](https://forums.meteor.com/). 
+Even before you ask a question on Meteor Forums, make sure you read the [Meteor Routing Guide](https://kadira.io/academy/meteor-routing-guide).
+
+## Implementing Feature and Bug Fixes
+
+We are welcome and greedy for PRs. So, 
+
+* If you wanna fix a bug, simply submit it. 
+* If you wanna implement feature or support with contributions, just drop a message to arunoda [at] kadira.io.
+
+

+ 21 - 0
packages/kadira-flow-router/LICENSE

@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 MeteorHacks Pvt Ltd (Sri Lanka). <[email protected]>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.

+ 777 - 0
packages/kadira-flow-router/README.md

@@ -0,0 +1,777 @@
+# FlowRouter [![Build Status](https://travis-ci.org/kadirahq/flow-router.svg?branch=master)](https://travis-ci.org/kadirahq/flow-router) [![Stories in Ready](https://badge.waffle.io/kadirahq/flow-router.svg?label=doing&title=Activities)](http://waffle.io/kadirahq/flow-router)
+
+Forked for bug fixes
+
+Carefully Designed Client Side Router for Meteor.
+
+FlowRouter is a very simple router for Meteor. It does routing for client-side apps and does not handle rendering itself.
+
+It exposes a great API for changing the URL and reactively getting data from the URL. However, inside the router, it's not reactive. Most importantly, FlowRouter is designed with performance in mind and it focuses on what it does best: **routing**.
+
+> We've released 2.0 and follow this [migration guide](#migrating-into-20) if you are already using FlowRouter.
+
+## TOC
+
+* [Meteor Routing Guide](#meteor-routing-guide)
+* [Getting Started](#getting-started)
+* [Routes Definition](#routes-definition)
+* [Group Routes](#group-routes)
+* [Rendering and Layout Management](#rendering-and-layout-management)
+* [Triggers](#triggers)
+* [Not Found Routes](#not-found-routes)
+* [API](#api)
+* [Subscription Management](#subscription-management)
+* [IE9 Support](#ie9-support)
+* [Hashbang URLs](#hashbang-urls)
+* [Prefixed paths](#prefixed-paths)
+* [Add-ons](#add-ons)
+* [Difference with Iron Router](#difference-with-iron-router)
+* [Migrating into 2.0](#migrating-into-20)
+
+## Meteor Routing Guide
+
+[Meteor Routing Guide](https://kadira.io/academy/meteor-routing-guide) is a completed guide into **routing** and related topics in Meteor. It talks about how to use FlowRouter properly and use it with **Blaze and React**. It also shows how to manage **subscriptions** and implement **auth logic** in the view layer.
+
+[![Meteor Routing Guide](https://cldup.com/AxlPfoxXmR.png)](https://kadira.io/academy/meteor-routing-guide)
+
+## Getting Started
+
+Add FlowRouter to your app:
+
+~~~shell
+meteor add kadira:flow-router
+~~~
+
+Let's write our first route (add this file to `lib/router.js`):
+
+~~~js
+FlowRouter.route('/blog/:postId', {
+    action: function(params, queryParams) {
+        console.log("Yeah! We are on the post:", params.postId);
+    }
+});
+~~~
+
+Then visit `/blog/my-post-id` from the browser or invoke the following command from the browser console:
+
+~~~js
+FlowRouter.go('/blog/my-post-id');
+~~~
+
+Then you can see some messages printed in the console.
+
+## Routes Definition
+
+FlowRouter routes are very simple and based on the syntax of [path-to-regexp](https://github.com/pillarjs/path-to-regexp) which is used in both [Express](http://expressjs.com/) and `iron:router`.
+
+Here's the syntax for a simple route:
+
+~~~js
+FlowRouter.route('/blog/:postId', {
+    // do some action for this route
+    action: function(params, queryParams) {
+        console.log("Params:", params);
+        console.log("Query Params:", queryParams);
+    },
+
+    name: "<name for the route>" // optional
+});
+~~~
+
+So, this route will be activated when you visit a url like below:
+
+~~~js
+FlowRouter.go('/blog/my-post?comments=on&color=dark');
+~~~
+
+After you've visit the route, this will be printed in the console:
+
+~~~
+Params: {postId: "my-post"}
+Query Params: {comments: "on", color: "dark"}
+~~~
+
+For a single interaction, the router only runs once. That means, after you've visit a route, first it will call `triggers`, then `subscriptions` and finally `action`. After that happens, none of those methods will be called again for that route visit.
+
+You can define routes anywhere in the `client` directory. But, we recommend to add them in the `lib` directory. Then `fast-render` can detect subscriptions and send them for you (we'll talk about this is a moment).
+
+### Group Routes
+
+You can group routes for better route organization. Here's an example:
+
+~~~js
+var adminRoutes = FlowRouter.group({
+  prefix: '/admin',
+  name: 'admin',
+  triggersEnter: [function(context, redirect) {
+    console.log('running group triggers');
+  }]
+});
+
+// handling /admin route
+adminRoutes.route('/', {
+  action: function() {
+    BlazeLayout.render('componentLayout', {content: 'admin'});
+  },
+  triggersEnter: [function(context, redirect) {
+    console.log('running /admin trigger');
+  }]
+});
+
+// handling /admin/posts
+adminRoutes.route('/posts', {
+  action: function() {
+    BlazeLayout.render('componentLayout', {content: 'posts'});
+  }
+});
+~~~
+
+**All of the options for the `FlowRouter.group()` are optional.**
+
+You can even have nested group routes as shown below:
+
+~~~js
+var adminRoutes = FlowRouter.group({
+    prefix: "/admin",
+    name: "admin"
+});
+
+var superAdminRoutes = adminRoutes.group({
+    prefix: "/super",
+    name: "superadmin"
+});
+
+// handling /admin/super/post
+superAdminRoutes.route('/post', {
+    action: function() {
+
+    }
+});
+~~~
+
+You can determine which group the current route is in using:
+
+~~~js
+FlowRouter.current().route.group.name
+~~~
+
+This can be useful for determining if the current route is in a specific group (e.g. *admin*, *public*, *loggedIn*) without needing to use prefixes if you don't want to. If it's a nested group, you can get the parent group's name with:
+
+~~~js
+FlowRouter.current().route.group.parent.name
+~~~
+
+As with all current route properties, these are not reactive, but can be combined with `FlowRouter.watchPathChange()` to get group names reactively.
+
+## Rendering and Layout Management
+
+FlowRouter does not handle rendering or layout management. For that, you can use:
+
+  * [Blaze Layout for Blaze](https://github.com/kadirahq/blaze-layout)
+  * [React Layout for React](https://github.com/kadirahq/meteor-react-layout)
+
+Then you can invoke the layout manager inside the `action` method in the router.
+
+~~~js
+FlowRouter.route('/blog/:postId', {
+    action: function(params) {
+        BlazeLayout.render("mainLayout", {area: "blog"});
+    }
+});
+~~~
+
+## Triggers
+
+Triggers are the way FlowRouter allows you to perform tasks before you **enter** into a route and after you **exit** from a route.
+
+#### Defining triggers for a route
+
+Here's how you can define triggers for a route:
+
+~~~js
+FlowRouter.route('/home', {
+  // calls just before the action
+  triggersEnter: [trackRouteEntry],
+  action: function() {
+    // do something you like
+  },
+  // calls when we decide to move to another route
+  // but calls before the next route started
+  triggersExit: [trackRouteClose]
+});
+
+function trackRouteEntry(context) {
+  // context is the output of `FlowRouter.current()`
+  Mixpanel.track("visit-to-home", context.queryParams);
+}
+
+function trackRouteClose(context) {
+  Mixpanel.track("move-from-home", context.queryParams);
+}
+~~~
+
+#### Defining triggers for a group route
+
+This is how you can define triggers on a group definition.
+
+~~~js
+var adminRoutes = FlowRouter.group({
+  prefix: '/admin',
+  triggersEnter: [trackRouteEntry],
+  triggersExit: [trackRouteEntry]
+});
+~~~
+
+> You can add triggers to individual routes in the group too.
+
+#### Defining Triggers Globally
+
+You can also define triggers globally. Here's how to do it:
+
+~~~js
+FlowRouter.triggers.enter([cb1, cb2]);
+FlowRouter.triggers.exit([cb1, cb2]);
+
+// filtering
+FlowRouter.triggers.enter([trackRouteEntry], {only: ["home"]});
+FlowRouter.triggers.exit([trackRouteExit], {except: ["home"]});
+~~~
+
+As you can see from the last two examples, you can filter routes using the `only` or `except` keywords. But, you can't use both `only` and `except` at once.
+
+> If you'd like to learn more about triggers and design decisions, visit [here](https://github.com/meteorhacks/flow-router/pull/59).
+
+#### Redirecting With Triggers
+
+You can redirect to a different route using triggers. You can do it from both enter and exit triggers. See how to do it:
+
+~~~js
+FlowRouter.route('/', {
+  triggersEnter: [function(context, redirect) {
+    redirect('/some-other-path');
+  }],
+  action: function(_params) {
+    throw new Error("this should not get called");
+  }
+});
+~~~
+
+Every trigger callback comes with a second argument: a function you can use to redirect to a different route. Redirect also has few properties to make sure it's not blocking the router.
+
+* redirect must be called with an URL
+* redirect must be called within the same event loop cycle (no async or called inside a Tracker)
+* redirect cannot be called multiple times
+
+Check this [PR](https://github.com/meteorhacks/flow-router/pull/172) to learn more about our redirect API.
+
+#### Stopping the Callback With Triggers
+
+In some cases, you may need to stop the route callback from firing using triggers. You can do this in **before** triggers, using the third argument: the `stop` function. For example, you can check the prefix and if it fails, show the notFound layout and stop before the action fires.
+
+```js
+var localeGroup = FlowRouter.group({
+  prefix: '/:locale?',
+  triggersEnter: [localeCheck]
+});
+
+localeGroup.route('/login', {
+  action: function (params, queryParams) {
+    BlazeLayout.render('componentLayout', {content: 'login'});
+  }
+});
+
+function localeCheck(context, redirect, stop) {
+  var locale = context.params.locale;
+
+  if (locale !== undefined && locale !== 'fr') {
+    BlazeLayout.render('notFound');
+    stop();
+  }
+}
+```
+
+> **Note**: When using the stop function, you should always pass the second **redirect** argument, even if you won't use it.
+
+## Not Found Routes
+
+You can configure Not Found routes like this:
+
+~~~js
+FlowRouter.notFound = {
+    // Subscriptions registered here don't have Fast Render support.
+    subscriptions: function() {
+
+    },
+    action: function() {
+
+    }
+};
+~~~
+
+## API
+
+FlowRouter has a rich API to help you to navigate the router and reactively get information from the router.
+
+#### FlowRouter.getParam(paramName);
+
+Reactive function which you can use to get a parameter from the URL.
+
+~~~js
+// route def: /apps/:appId
+// url: /apps/this-is-my-app
+
+var appId = FlowRouter.getParam("appId");
+console.log(appId); // prints "this-is-my-app"
+~~~
+
+#### FlowRouter.getQueryParam(queryStringKey);
+
+Reactive function which you can use to get a value from the queryString.
+
+~~~js
+// route def: /apps/:appId
+// url: /apps/this-is-my-app?show=yes&color=red
+
+var color = FlowRouter.getQueryParam("color");
+console.log(color); // prints "red"
+~~~
+
+#### FlowRouter.path(pathDef, params, queryParams)
+
+Generate a path from a path definition. Both `params` and `queryParams` are optional.
+
+Special characters in `params` and `queryParams` will be URL encoded.
+
+~~~js
+var pathDef = "/blog/:cat/:id";
+var params = {cat: "met eor", id: "abc"};
+var queryParams = {show: "y+e=s", color: "black"};
+
+var path = FlowRouter.path(pathDef, params, queryParams);
+console.log(path); // prints "/blog/met%20eor/abc?show=y%2Be%3Ds&color=black"
+~~~
+
+If there are no params or queryParams, this will simply return the pathDef as it is.
+
+##### Using Route name instead of the pathDef
+
+You can also use the route's name instead of the pathDef. Then, FlowRouter will pick the pathDef from the given route. See the following example:
+
+~~~js
+FlowRouter.route("/blog/:cat/:id", {
+    name: "blogPostRoute",
+    action: function(params) {
+        //...
+    }
+})
+
+var params = {cat: "meteor", id: "abc"};
+var queryParams = {show: "yes", color: "black"};
+
+var path = FlowRouter.path("blogPostRoute", params, queryParams);
+console.log(path); // prints "/blog/meteor/abc?show=yes&color=black"
+~~~
+
+#### FlowRouter.go(pathDef, params, queryParams);
+
+This will get the path via `FlowRouter.path` based on the arguments and re-route to that path.
+
+You can call `FlowRouter.go` like this as well:
+
+~~~js
+FlowRouter.go("/blog");
+~~~
+
+
+#### FlowRouter.url(pathDef, params, queryParams)
+
+Just like `FlowRouter.path`, but gives the absolute url. (Uses `Meteor.absoluteUrl` behind the scenes.)
+
+#### FlowRouter.setParams(newParams)
+
+This will change the current params with the newParams and re-route to the new path.
+
+~~~js
+// route def: /apps/:appId
+// url: /apps/this-is-my-app?show=yes&color=red
+
+FlowRouter.setParams({appId: "new-id"});
+// Then the user will be redirected to the following path
+//      /apps/new-id?show=yes&color=red
+~~~
+
+#### FlowRouter.setQueryParams(newQueryParams)
+
+Just like `FlowRouter.setParams`, but for queryString params.
+
+To remove a query param set it to `null` like below:
+
+~~~js
+FlowRouter.setQueryParams({paramToRemove: null});
+~~~
+
+#### FlowRouter.getRouteName()
+
+To get the name of the route reactively.
+
+~~~js
+Tracker.autorun(function() {
+  var routeName = FlowRouter.getRouteName();
+  console.log("Current route name is: ", routeName);
+});
+~~~
+
+#### FlowRouter.current()
+
+Get the current state of the router. **This API is not reactive**.
+If you need to watch the changes in the path simply use `FlowRouter.watchPathChange()`.
+
+This gives an object like this:
+
+~~~js
+// route def: /apps/:appId
+// url: /apps/this-is-my-app?show=yes&color=red
+
+var current = FlowRouter.current();
+console.log(current);
+
+// prints following object
+// {
+//     path: "/apps/this-is-my-app?show=yes&color=red",
+//     params: {appId: "this-is-my-app"},
+//     queryParams: {show: "yes", color: "red"}
+//     route: {pathDef: "/apps/:appId", name: "name-of-the-route"}
+// }
+~~~
+
+#### FlowRouter.watchPathChange()
+
+Reactively watch the changes in the path. If you need to simply get the params or queryParams use dedicated APIs like `FlowRouter.getQueryParam()`.
+
+~~~js
+Tracker.autorun(function() {
+  FlowRouter.watchPathChange();
+  var currentContext = FlowRouter.current();
+  // do anything with the current context
+  // or anything you wish
+});
+~~~
+
+#### FlowRouter.withReplaceState(fn)
+Normally, all the route changes made via APIs like `FlowRouter.go` and `FlowRouter.setParams()` add a URL item to the browser history. For example, run the following code:
+
+~~~js
+FlowRouter.setParams({id: "the-id-1"});
+FlowRouter.setParams({id: "the-id-2"});
+FlowRouter.setParams({id: "the-id-3"});
+~~~
+
+Now you can hit the back button of your browser two times. This is normal behavior since users may click the back button and expect to see the previous state of the app.
+
+But sometimes, this is not something you want. You don't need to pollute the browser history. Then, you can use the following syntax.
+
+~~~js
+FlowRouter.withReplaceState(function() {
+  FlowRouter.setParams({id: "the-id-1"});
+  FlowRouter.setParams({id: "the-id-2"});
+  FlowRouter.setParams({id: "the-id-3"});
+});
+~~~
+
+Now, there is no item in the browser history. Just like `FlowRouter.setParams`, you can use any FlowRouter API inside `FlowRouter.withReplaceState`.
+
+> We named this function as `withReplaceState` because, replaceState is the underline API used for this functionality. Read more about [replace state & the history API](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history).
+
+#### FlowRouter.reload()
+
+FlowRouter routes are idempotent. That means, even if you call `FlowRouter.go()` to the same URL multiple times, it only activates in the first run. This is also true for directly clicking on paths.
+
+So, if you really need to reload the route, this is the API you want.
+
+#### FlowRouter.wait() and FlowRouter.initialize()
+
+By default, FlowRouter initializes the routing process in a `Meteor.startup()` callback. This works for most of the apps. But, some apps have custom initializations and FlowRouter needs to initialize after that.
+
+So, that's where `FlowRouter.wait()` comes to save you. You need to call it directly inside your JavaScript file. After that, whenever your app is ready call `FlowRouter.initialize()`.
+
+eg:-
+
+~~~js
+// file: app.js
+FlowRouter.wait();
+WhenEverYourAppIsReady(function() {
+  FlowRouter.initialize();
+});
+~~~
+
+For more information visit [issue #180](https://github.com/meteorhacks/flow-router/issues/180).
+
+#### FlowRouter.onRouteRegister(cb)
+
+This API is specially designed for add-on developers. They can listen for any registered route and add custom functionality to FlowRouter. This works on both server and client alike.
+
+~~~js
+FlowRouter.onRouteRegister(function(route) {
+  // do anything with the route object
+  console.log(route);
+});
+~~~
+
+Let's say a user defined a route like this:
+
+~~~js
+FlowRouter.route('/blog/:post', {
+  name: 'postList',
+  triggersEnter: [function() {}],
+  subscriptions: function() {},
+  action: function() {},
+  triggersExit: [function() {}],
+  customField: 'customName'
+});
+~~~
+
+Then the route object will be something like this:
+
+~~~js
+{
+  pathDef: '/blog/:post',
+  name: 'postList',
+  options: {customField: 'customName'}
+}
+~~~
+
+So, it's not the internal route object we are using.
+
+## Subscription Management
+
+For Subscription Management, we highly suggest you to follow [Template/Component level subscriptions](https://kadira.io/academy/meteor-routing-guide/content/subscriptions-and-data-management). Visit this [guide](https://kadira.io/academy/meteor-routing-guide/content/subscriptions-and-data-management) for that.
+
+FlowRouter also has it's own subscription registration mechanism. We will remove this in version 3.0. We don't remove or deprecate it in version 2.x because this is the easiest way to implement FastRender support for your app. In 3.0 we've better support for FastRender with Server Side Rendering.
+
+FlowRouter only deals with registration of subscriptions. It does not wait until subscription becomes ready. This is how to register a subscription.
+
+~~~js
+FlowRouter.route('/blog/:postId', {
+    subscriptions: function(params, queryParams) {
+        this.register('myPost', Meteor.subscribe('blogPost', params.postId));
+    }
+});
+~~~
+
+We can also register global subscriptions like this:
+
+~~~js
+FlowRouter.subscriptions = function() {
+  this.register('myCourses', Meteor.subscribe('courses'));
+};
+~~~
+
+All these global subscriptions run on every route. So, pay special attention to names when registering subscriptions.
+
+After you've registered your subscriptions, you can reactively check for the status of those subscriptions like this:
+
+~~~js
+Tracker.autorun(function() {
+    console.log("Is myPost ready?:", FlowRouter.subsReady("myPost"));
+    console.log("Are all subscriptions ready?:", FlowRouter.subsReady());
+});
+~~~
+
+So, you can use `FlowRouter.subsReady` inside template helpers to show the loading status and act accordingly.
+
+### FlowRouter.subsReady() with a callback
+
+Sometimes, we need to use `FlowRouter.subsReady()` in places where an autorun is not available. One such example is inside an event handler. For such places, we can use the callback API of `FlowRouter.subsReady()`.
+
+~~~js
+Template.myTemplate.events({
+   "click #id": function(){
+      FlowRouter.subsReady("myPost", function() {
+         // do something
+      });
+  }
+});
+~~~
+
+> Arunoda has discussed more about Subscription Management in FlowRouter in [this](https://meteorhacks.com/flow-router-and-subscription-management.html#subscription-management) blog post about [FlowRouter and Subscription Management](https://meteorhacks.com/flow-router-and-subscription-management.html).
+
+> He's showing how to build an app like this:
+
+>![FlowRouter's Subscription Management](https://cldup.com/esLzM8cjEL.gif)
+
+#### Fast Render
+FlowRouter has built in support for [Fast Render](https://github.com/meteorhacks/fast-render).
+
+- `meteor add meteorhacks:fast-render`
+- Put `router.js` in a shared location. We suggest `lib/router.js`.
+
+You can exclude Fast Render support by wrapping the subscription registration in an `isClient` block:
+
+~~~js
+FlowRouter.route('/blog/:postId', {
+    subscriptions: function(params, queryParams) {
+        // using Fast Render
+        this.register('myPost', Meteor.subscribe('blogPost', params.postId));
+
+        // not using Fast Render
+        if(Meteor.isClient) {
+            this.register('data', Meteor.subscribe('bootstrap-data');
+        }
+    }
+});
+~~~
+
+#### Subscription Caching
+
+You can also use [Subs Manager](https://github.com/meteorhacks/subs-manager) for caching subscriptions on the client. We haven't done anything special to make it work. It should work as it works with other routers.
+
+## IE9 Support
+
+FlowRouter has IE9 support. But it does not ship the **HTML5 history polyfill** out of the box. That's because most apps do not require it.
+
+If you need to support IE9, add the **HTML5 history polyfill** with the following package.
+
+~~~shell
+meteor add tomwasd:history-polyfill
+~~~
+
+## Hashbang URLs
+
+To enable hashbang urls like `mydomain.com/#!/mypath` simple set the `hashbang` option to `true` in the initialize function:
+
+~~~js
+// file: app.js
+FlowRouter.wait();
+WhenEverYourAppIsReady(function() {
+  FlowRouter.initialize({hashbang: true});
+});
+~~~
+
+## Prefixed paths
+
+In cases you wish to run multiple web application on the same domain name, you’ll probably want to serve your particular meteor application under a sub-path (eg `example.com/myapp`). In this case simply include the path prefix in the meteor `ROOT_URL` environment variable and FlowRouter will handle it transparently without any additional configuration.
+
+## Add-ons
+
+Router is a base package for an app. Other projects like [useraccounts](http://useraccounts.meteor.com/)  should have support for FlowRouter. Otherwise, it's hard to use  FlowRouter in a real project. Now a lot of packages have [started to support FlowRouter](https://kadira.io/blog/meteor/addon-packages-for-flowrouter).
+
+So, you can use your your favorite package with FlowRouter as well. If not, there is an [easy process](https://kadira.io/blog/meteor/addon-packages-for-flowrouter#what-if-project-xxx-still-doesn-t-support-flowrouter-) to convert them to FlowRouter.
+
+**Add-on API**
+
+We have also released a [new API](https://github.com/kadirahq/flow-router#flowrouteronrouteregistercb) to support add-on developers. With that add-on packages can get a notification, when the user created a route in their app.
+
+If you've more ideas for the add-on API, [let us know](https://github.com/kadirahq/flow-router/issues).
+
+## Difference with Iron Router
+
+FlowRouter and Iron Router are two different routers. Iron Router tries to be a full featured solution. It tries to do everything including routing, subscriptions, rendering and layout management.
+
+FlowRouter is a minimalistic solution focused on routing with UI performance in mind. It exposes APIs for related functionality.
+
+Let's learn more about the differences:
+
+### Rendering
+
+FlowRouter doesn't handle rendering. By decoupling rendering from the router it's possible to use any rendering framework, such as [Blaze Layout](https://github.com/kadirahq/blaze-layout) to render with Blaze's Dynamic Templates. Rendering calls are made in the the route's action. We have a layout manager for [React](https://github.com/kadirahq/meteor-react-layout) as well.
+
+### Subscriptions
+
+With FlowRouter, we highly suggest using template/component layer subscriptions. But, if you need to do routing in the router layer, FlowRouter has [subscription registration](#subscription-management) mechanism. Even with that, FlowRouter never waits for the subscriptions and view layer to do it.
+
+### Reactive Content
+
+In Iron Router you can use reactive content inside the router, but any hook or method can re-run in an unpredictable manner. FlowRouter limits reactive data sources to a single run; when it is first called.
+
+We think that's the way to go. Router is just a user action. We can work with reactive content in the rendering layer.
+
+### router.current() is evil
+
+`Router.current()` is evil. Why? Let's look at following example. Imagine we have a route like this in our app:
+
+~~~
+/apps/:appId/:section
+~~~
+
+Now let's say, we need to get `appId` from the URL. Then we will do, something like this in Iron Router.
+
+~~~js
+Templates['foo'].helpers({
+    "someData": function() {
+        var appId = Router.current().params.appId;
+        return doSomething(appId);
+    }
+});
+~~~
+
+Let's say we changed `:section` in the route. Then the above helper also gets rerun. If we add a query param to the URL, it gets rerun. That's because `Router.current()` looks for changes in the route(or URL). But in any of above cases, `appId` didn't get changed.
+
+Because of this, a lot parts of our app get re-run and re-rendered. This creates unpredictable rendering behavior in our app.
+
+FlowRouter fixes this issue by providing the `Router.getParam()` API. See how to use it:
+
+~~~js
+Templates['foo'].helpers({
+    "someData": function() {
+        var appId = FlowRouter.getParam('appId');
+        return doSomething(appId);
+    }
+});
+~~~
+
+### No data context
+
+FlowRouter does not have a data context. Data context has the same problem as reactive `.current()`. We believe, it'll possible to get data directly in the template (component) layer.
+
+### Built in Fast Render Support
+
+FlowRouter has built in [Fast Render](https://github.com/meteorhacks/fast-render) support. Just add Fast Render to your app and it'll work. Nothing to change in the router.
+
+For more information check [docs](#fast-render).
+
+### Server Side Routing
+
+FlowRouter is a client side router and it **does not** support server side routing at all. But `subscriptions` run on the server to enable Fast Render support.
+
+#### Reason behind that
+
+Meteor is not a traditional framework where you can send HTML directly from the server. Meteor needs to send a special set of HTML to the client initially. So, you can't directly send something to the client yourself.
+
+Also, in the server we need look for different things compared with the client. For example:
+
+* In the server we have to deal with headers.
+* In the server we have to deal with methods like `GET`, `POST`, etc.
+* In the server we have Cookies.
+
+So, it's better to use a dedicated server-side router like [`meteorhacks:picker`](https://github.com/meteorhacks/picker). It supports connect and express middlewares and has a very easy to use route syntax.
+
+### Server Side Rendering
+
+FlowRouter 3.0 will have server side rendering support. We've already started the initial version and check our [`ssr`](https://github.com/meteorhacks/flow-router/tree/ssr) branch for that.
+
+It's currently very usable and Kadira already using it for <https://kadira.io>
+
+### Better Initial Loading Support
+
+In Meteor, we have to wait until all the JS and other resources send before rendering anything. This is an issue. In 3.0, with the support from Server Side Rendering we are going to fix it.
+
+## Migrating into 2.0
+
+Migrating into version 2.0 is easy and you don't need to change any application code since you are already using 2.0 features and the APIs. In 2.0, we've changed names and removed some deprecated APIs.
+
+Here are the steps to migrate your app into 2.0.
+
+#### Use the New FlowRouter Package
+* Now FlowRouter comes as `kadira:flow-router`
+* So, remove `meteorhacks:flow-router` with : `meteor remove meteorhacks:flow-router`
+* Then, add `kadira:flow-router` with `meteor add kadira:flow-router`
+
+#### Change FlowLayout into BlazeLayout
+* We've also renamed FlowLayout as [BlazeLayout](https://github.com/kadirahq/blaze-layout).
+* So, remove `meteorhacks:flow-layout` and add `kadira:blaze-layout` instead.
+* You need to use `BlazeLayout.render()` instead of `FlowLayout.render()`
+
+#### Stop using deprecated Apis
+* There is no middleware support. Use triggers instead.
+* There is no API called `.reactiveCurrent()`, use `.watchPathChange()` instead.
+* Earlier, you can access query params with `FlowRouter.current().params.query`. But, now you can't do that. Use `FlowRouter.current().queryParams` instead.

+ 11 - 0
packages/kadira-flow-router/client/_init.js

@@ -0,0 +1,11 @@
+// Export Router Instance
+FlowRouter = new Router();
+FlowRouter.Router = Router;
+FlowRouter.Route = Route;
+
+// Initialize FlowRouter
+Meteor.startup(function () {
+  if(!FlowRouter._askedToWait) {
+    FlowRouter.initialize();
+  }
+});

+ 57 - 0
packages/kadira-flow-router/client/group.js

@@ -0,0 +1,57 @@
+Group = function(router, options, parent) {
+  options = options || {};
+
+  if (options.prefix && !/^\/.*/.test(options.prefix)) {
+    var message = "group's prefix must start with '/'";
+    throw new Error(message);
+  }
+
+  this._router = router;
+  this.prefix = options.prefix || '';
+  this.name = options.name;
+  this.options = options;
+
+  this._triggersEnter = options.triggersEnter || [];
+  this._triggersExit = options.triggersExit || [];
+  this._subscriptions = options.subscriptions || Function.prototype;
+
+  this.parent = parent;
+  if (this.parent) {
+    this.prefix = parent.prefix + this.prefix;
+
+    this._triggersEnter = parent._triggersEnter.concat(this._triggersEnter);
+    this._triggersExit = this._triggersExit.concat(parent._triggersExit);
+  }
+};
+
+Group.prototype.route = function(pathDef, options, group) {
+  options = options || {};
+
+  if (!/^\/.*/.test(pathDef)) {
+    var message = "route's path must start with '/'";
+    throw new Error(message);
+  }
+
+  group = group || this;
+  pathDef = this.prefix + pathDef;
+
+  var triggersEnter = options.triggersEnter || [];
+  options.triggersEnter = this._triggersEnter.concat(triggersEnter);
+
+  var triggersExit = options.triggersExit || [];
+  options.triggersExit = triggersExit.concat(this._triggersExit);
+
+  return this._router.route(pathDef, options, group);
+};
+
+Group.prototype.group = function(options) {
+  return new Group(this._router, options, this);
+};
+
+Group.prototype.callSubscriptions = function(current) {
+  if (this.parent) {
+    this.parent.callSubscriptions(current);
+  }
+
+  this._subscriptions.call(current.route, current.params, current.queryParams);
+};

+ 2 - 0
packages/kadira-flow-router/client/modules.js

@@ -0,0 +1,2 @@
+page = require('page');
+qs   = require('qs');

+ 125 - 0
packages/kadira-flow-router/client/route.js

@@ -0,0 +1,125 @@
+Route = function(router, pathDef, options, group) {
+  options = options || {};
+
+  this.options = options;
+  this.pathDef = pathDef
+
+  // Route.path is deprecated and will be removed in 3.0
+  this.path = pathDef;
+
+  if (options.name) {
+    this.name = options.name;
+  }
+
+  this._action = options.action || Function.prototype;
+  this._subscriptions = options.subscriptions || Function.prototype;
+  this._triggersEnter = options.triggersEnter || [];
+  this._triggersExit = options.triggersExit || [];
+  this._subsMap = {};
+  this._router = router;
+
+  this._params = new ReactiveDict();
+  this._queryParams = new ReactiveDict();
+  this._routeCloseDep = new Tracker.Dependency();
+
+  // tracks the changes in the URL
+  this._pathChangeDep = new Tracker.Dependency();
+
+  this.group = group;
+};
+
+Route.prototype.clearSubscriptions = function() {
+  this._subsMap = {};
+};
+
+Route.prototype.register = function(name, sub, options) {
+  this._subsMap[name] = sub;
+};
+
+
+Route.prototype.getSubscription = function(name) {
+  return this._subsMap[name];
+};
+
+
+Route.prototype.getAllSubscriptions = function() {
+  return this._subsMap;
+};
+
+Route.prototype.callAction = function(current) {
+  var self = this;
+  self._action(current.params, current.queryParams);
+};
+
+Route.prototype.callSubscriptions = function(current) {
+  this.clearSubscriptions();
+  if (this.group) {
+    this.group.callSubscriptions(current);
+  }
+
+  this._subscriptions(current.params, current.queryParams);
+};
+
+Route.prototype.getRouteName = function() {
+  this._routeCloseDep.depend();
+  return this.name;
+};
+
+Route.prototype.getParam = function(key) {
+  this._routeCloseDep.depend();
+  return this._params.get(key);
+};
+
+Route.prototype.getQueryParam = function(key) {
+  this._routeCloseDep.depend();
+  return this._queryParams.get(key);
+};
+
+Route.prototype.watchPathChange = function() {
+  this._pathChangeDep.depend();
+};
+
+Route.prototype.registerRouteClose = function() {
+  this._params = new ReactiveDict();
+  this._queryParams = new ReactiveDict();
+  this._routeCloseDep.changed();
+  this._pathChangeDep.changed();
+};
+
+Route.prototype.registerRouteChange = function(currentContext, routeChanging) {
+  // register params
+  var params = currentContext.params;
+  this._updateReactiveDict(this._params, params);
+
+  // register query params
+  var queryParams = currentContext.queryParams;
+  this._updateReactiveDict(this._queryParams, queryParams);
+
+  // if the route is changing, we need to defer triggering path changing
+  // if we did this, old route's path watchers will detect this
+  // Real issue is, above watcher will get removed with the new route
+  // So, we don't need to trigger it now
+  // We are doing it on the route close event. So, if they exists they'll 
+  // get notify that
+  if(!routeChanging) {
+    this._pathChangeDep.changed();
+  }
+};
+
+Route.prototype._updateReactiveDict = function(dict, newValues) {
+  var currentKeys = _.keys(newValues);
+  var oldKeys = _.keys(dict.keyDeps);
+
+  // set new values
+  //  params is an array. So, _.each(params) does not works
+  //  to iterate params
+  _.each(currentKeys, function(key) {
+    dict.set(key, newValues[key]);
+  });
+
+  // remove keys which does not exisits here
+  var removedKeys = _.difference(oldKeys, currentKeys);
+  _.each(removedKeys, function(key) {
+    dict.set(key, undefined);
+  });
+};

+ 587 - 0
packages/kadira-flow-router/client/router.js

@@ -0,0 +1,587 @@
+Router = function () {
+  var self = this;
+  this.globals = [];
+  this.subscriptions = Function.prototype;
+
+  this._tracker = this._buildTracker();
+  this._current = {};
+
+  // tracks the current path change
+  this._onEveryPath = new Tracker.Dependency();
+
+  this._globalRoute = new Route(this);
+
+  // holds onRoute callbacks
+  this._onRouteCallbacks = [];
+
+  // if _askedToWait is true. We don't automatically start the router
+  // in Meteor.startup callback. (see client/_init.js)
+  // Instead user need to call `.initialize()
+  this._askedToWait = false;
+  this._initialized = false;
+  this._triggersEnter = [];
+  this._triggersExit = [];
+  this._routes = [];
+  this._routesMap = {};
+  this._updateCallbacks();
+  this.notFound = this.notfound = null;
+  // indicate it's okay (or not okay) to run the tracker
+  // when doing subscriptions
+  // using a number and increment it help us to support FlowRouter.go()
+  // and legitimate reruns inside tracker on the same event loop.
+  // this is a solution for #145
+  this.safeToRun = 0;
+
+  // Meteor exposes to the client the path prefix that was defined using the
+  // ROOT_URL environement variable on the server using the global runtime
+  // configuration. See #315.
+  this._basePath = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || '';
+
+  // this is a chain contains a list of old routes
+  // most of the time, there is only one old route
+  // but when it's the time for a trigger redirect we've a chain
+  this._oldRouteChain = [];
+
+  this.env = {
+    replaceState: new Meteor.EnvironmentVariable(),
+    reload: new Meteor.EnvironmentVariable(),
+    trailingSlash: new Meteor.EnvironmentVariable()
+  };
+
+  // redirect function used inside triggers
+  this._redirectFn = function(pathDef, fields, queryParams) {
+    if (/^http(s)?:\/\//.test(pathDef)) {
+        var message = "Redirects to URLs outside of the app are not supported in this version of Flow Router. Use 'window.location = yourUrl' instead";
+        throw new Error(message);
+    }
+    self.withReplaceState(function() {
+      var path = FlowRouter.path(pathDef, fields, queryParams);
+      self._page.redirect(path);
+    });
+  };
+  this._initTriggersAPI();
+};
+
+Router.prototype.route = function(pathDef, options, group) {
+  if (!/^\/.*/.test(pathDef)) {
+    var message = "route's path must start with '/'";
+    throw new Error(message);
+  }
+
+  options = options || {};
+  var self = this;
+  var route = new Route(this, pathDef, options, group);
+
+  // calls when the page route being activates
+  route._actionHandle = function (context, next) {
+    var oldRoute = self._current.route;
+    self._oldRouteChain.push(oldRoute);
+
+    var queryParams = self._qs.parse(context.querystring);
+    // _qs.parse() gives us a object without prototypes,
+    // created with Object.create(null)
+    // Meteor's check doesn't play nice with it.
+    // So, we need to fix it by cloning it.
+    // see more: https://github.com/meteorhacks/flow-router/issues/164
+    queryParams = JSON.parse(JSON.stringify(queryParams));
+
+    self._current = {
+      path: context.path,
+      context: context,
+      params: context.params,
+      queryParams: queryParams,
+      route: route,
+      oldRoute: oldRoute
+    };
+
+    // we need to invalidate if all the triggers have been completed
+    // if not that means, we've been redirected to another path
+    // then we don't need to invalidate
+    var afterAllTriggersRan = function() {
+      self._invalidateTracker();
+    };
+
+    var triggers = self._triggersEnter.concat(route._triggersEnter);
+    Triggers.runTriggers(
+      triggers,
+      self._current,
+      self._redirectFn,
+      afterAllTriggersRan
+    );
+  };
+
+  // calls when you exit from the page js route
+  route._exitHandle = function(context, next) {
+    var triggers = self._triggersExit.concat(route._triggersExit);
+    Triggers.runTriggers(
+      triggers,
+      self._current,
+      self._redirectFn,
+      next
+    );
+  };
+
+  this._routes.push(route);
+  if (options.name) {
+    this._routesMap[options.name] = route;
+  }
+
+  this._updateCallbacks();
+  this._triggerRouteRegister(route);
+
+  return route;
+};
+
+Router.prototype.group = function(options) {
+  return new Group(this, options);
+};
+
+Router.prototype.path = function(pathDef, fields, queryParams) {
+  if (this._routesMap[pathDef]) {
+    pathDef = this._routesMap[pathDef].pathDef;
+  }
+
+  var path = "";
+
+  // Prefix the path with the router global prefix
+  if (this._basePath) {
+    path += "/" + this._basePath + "/";
+  }
+
+  fields = fields || {};
+  var regExp = /(:[\w\(\)\\\+\*\.\?]+)+/g;
+  path += pathDef.replace(regExp, function(key) {
+    var firstRegexpChar = key.indexOf("(");
+    // get the content behind : and (\\d+/)
+    key = key.substring(1, (firstRegexpChar > 0)? firstRegexpChar: undefined);
+    // remove +?*
+    key = key.replace(/[\+\*\?]+/g, "");
+
+    // this is to allow page js to keep the custom characters as it is
+    // we need to encode 2 times otherwise "/" char does not work properly
+    // So, in that case, when I includes "/" it will think it's a part of the
+    // route. encoding 2times fixes it
+    return encodeURIComponent(encodeURIComponent(fields[key] || ""));
+  });
+
+  // Replace multiple slashes with single slash
+  path = path.replace(/\/\/+/g, "/");
+
+  // remove trailing slash
+  // but keep the root slash if it's the only one
+  path = path.match(/^\/{1}$/) ? path: path.replace(/\/$/, "");
+
+  // explictly asked to add a trailing slash
+  if(this.env.trailingSlash.get() && _.last(path) !== "/") {
+    path += "/";
+  }
+
+  var strQueryParams = this._qs.stringify(queryParams || {});
+  if(strQueryParams) {
+    path += "?" + strQueryParams;
+  }
+
+  return path;
+};
+
+Router.prototype.go = function(pathDef, fields, queryParams) {
+  var path = this.path(pathDef, fields, queryParams);
+
+  var useReplaceState = this.env.replaceState.get();
+  if(useReplaceState) {
+    this._page.replace(path);
+  } else {
+    this._page(path);
+  }
+};
+
+Router.prototype.reload = function() {
+  var self = this;
+
+  self.env.reload.withValue(true, function() {
+    self._page.replace(self._current.path);
+  });
+};
+
+Router.prototype.redirect = function(path) {
+  this._page.redirect(path);
+};
+
+Router.prototype.setParams = function(newParams) {
+  if(!this._current.route) {return false;}
+
+  var pathDef = this._current.route.pathDef;
+  var existingParams = this._current.params;
+  var params = {};
+  _.each(_.keys(existingParams), function(key) {
+    params[key] = existingParams[key];
+  });
+
+  params = _.extend(params, newParams);
+  var queryParams = this._current.queryParams;
+
+  this.go(pathDef, params, queryParams);
+  return true;
+};
+
+Router.prototype.setQueryParams = function(newParams) {
+  if(!this._current.route) {return false;}
+
+  var queryParams = _.clone(this._current.queryParams);
+  _.extend(queryParams, newParams);
+
+  for (var k in queryParams) {
+    if (queryParams[k] === null || queryParams[k] === undefined) {
+      delete queryParams[k];
+    }
+  }
+
+  var pathDef = this._current.route.pathDef;
+  var params = this._current.params;
+  this.go(pathDef, params, queryParams);
+  return true;
+};
+
+// .current is not reactive
+// This is by design. use .getParam() instead
+// If you really need to watch the path change, use .watchPathChange()
+Router.prototype.current = function() {
+  // We can't trust outside, that's why we clone this
+  // Anyway, we can't clone the whole object since it has non-jsonable values
+  // That's why we clone what's really needed.
+  var current = _.clone(this._current);
+  current.queryParams = EJSON.clone(current.queryParams);
+  current.params = EJSON.clone(current.params);
+  return current;
+};
+
+// Implementing Reactive APIs
+var reactiveApis = [
+  'getParam', 'getQueryParam',
+  'getRouteName', 'watchPathChange'
+];
+reactiveApis.forEach(function(api) {
+  Router.prototype[api] = function(arg1) {
+    // when this is calling, there may not be any route initiated
+    // so we need to handle it
+    var currentRoute = this._current.route;
+    if(!currentRoute) {
+      this._onEveryPath.depend();
+      return;
+    }
+
+    // currently, there is only one argument. If we've more let's add more args
+    // this is not clean code, but better in performance
+    return currentRoute[api].call(currentRoute, arg1);
+  };
+});
+
+Router.prototype.subsReady = function() {
+  var callback = null;
+  var args = _.toArray(arguments);
+
+  if (typeof _.last(args) === "function") {
+    callback = args.pop();
+  }
+
+  var currentRoute = this.current().route;
+  var globalRoute = this._globalRoute;
+
+  // we need to depend for every route change and
+  // rerun subscriptions to check the ready state
+  this._onEveryPath.depend();
+
+  if(!currentRoute) {
+    return false;
+  }
+
+  var subscriptions;
+  if(args.length === 0) {
+    subscriptions = _.values(globalRoute.getAllSubscriptions());
+    subscriptions = subscriptions.concat(_.values(currentRoute.getAllSubscriptions()));
+  } else {
+    subscriptions = _.map(args, function(subName) {
+      return globalRoute.getSubscription(subName) || currentRoute.getSubscription(subName);
+    });
+  }
+
+  var isReady = function() {
+    var ready =  _.every(subscriptions, function(sub) {
+      return sub && sub.ready();
+    });
+
+    return ready;
+  };
+
+  if (callback) {
+    Tracker.autorun(function(c) {
+      if (isReady()) {
+        callback();
+        c.stop();
+      }
+    });
+  } else {
+    return isReady();
+  }
+};
+
+Router.prototype.withReplaceState = function(fn) {
+  return this.env.replaceState.withValue(true, fn);
+};
+
+Router.prototype.withTrailingSlash = function(fn) {
+  return this.env.trailingSlash.withValue(true, fn);
+};
+
+Router.prototype._notfoundRoute = function(context) {
+  this._current = {
+    path: context.path,
+    context: context,
+    params: [],
+    queryParams: {},
+  };
+
+  // XXX this.notfound kept for backwards compatibility
+  this.notFound = this.notFound || this.notfound;
+  if(!this.notFound) {
+    console.error("There is no route for the path:", context.path);
+    return;
+  }
+
+  this._current.route = new Route(this, "*", this.notFound);
+  this._invalidateTracker();
+};
+
+Router.prototype.initialize = function(options) {
+  options = options || {};
+
+  if(this._initialized) {
+    throw new Error("FlowRouter is already initialized");
+  }
+
+  var self = this;
+  this._updateCallbacks();
+
+  // Implementing idempotent routing
+  // by overriding page.js`s "show" method.
+  // Why?
+  // It is impossible to bypass exit triggers,
+  // because they execute before the handler and
+  // can not know what the next path is, inside exit trigger.
+  //
+  // we need override both show, replace to make this work
+  // since we use redirect when we are talking about withReplaceState
+  _.each(['show', 'replace'], function(fnName) {
+    var original = self._page[fnName];
+    self._page[fnName] = function(path, state, dispatch, push) {
+      var reload = self.env.reload.get();
+      if (!reload && self._current.path === path) {
+        return;
+      }
+
+      original.call(this, path, state, dispatch, push);
+    };
+  });
+
+  // this is very ugly part of pagejs and it does decoding few times
+  // in unpredicatable manner. See #168
+  // this is the default behaviour and we need keep it like that
+  // we are doing a hack. see .path()
+  this._page.base(this._basePath);
+  this._page({
+    decodeURLComponents: true,
+    hashbang: !!options.hashbang
+  });
+
+  this._initialized = true;
+};
+
+Router.prototype._buildTracker = function() {
+  var self = this;
+
+  // main autorun function
+  var tracker = Tracker.autorun(function () {
+    if(!self._current || !self._current.route) {
+      return;
+    }
+
+    // see the definition of `this._processingContexts`
+    var currentContext = self._current;
+    var route = currentContext.route;
+    var path = currentContext.path;
+
+    if(self.safeToRun === 0) {
+      var message =
+        "You can't use reactive data sources like Session" +
+        " inside the `.subscriptions` method!";
+      throw new Error(message);
+    }
+
+    // We need to run subscriptions inside a Tracker
+    // to stop subs when switching between routes
+    // But we don't need to run this tracker with
+    // other reactive changes inside the .subscription method
+    // We tackle this with the `safeToRun` variable
+    self._globalRoute.clearSubscriptions();
+    self.subscriptions.call(self._globalRoute, path);
+    route.callSubscriptions(currentContext);
+
+    // otherwise, computations inside action will trigger to re-run
+    // this computation. which we do not need.
+    Tracker.nonreactive(function() {
+      var isRouteChange = currentContext.oldRoute !== currentContext.route;
+      var isFirstRoute = !currentContext.oldRoute;
+      // first route is not a route change
+      if(isFirstRoute) {
+        isRouteChange = false;
+      }
+
+      // Clear oldRouteChain just before calling the action
+      // We still need to get a copy of the oldestRoute first
+      // It's very important to get the oldest route and registerRouteClose() it
+      // See: https://github.com/kadirahq/flow-router/issues/314
+      var oldestRoute = self._oldRouteChain[0];
+      self._oldRouteChain = [];
+
+      currentContext.route.registerRouteChange(currentContext, isRouteChange);
+      route.callAction(currentContext);
+
+      Tracker.afterFlush(function() {
+        self._onEveryPath.changed();
+        if(isRouteChange) {
+          // We need to trigger that route (definition itself) has changed.
+          // So, we need to re-run all the register callbacks to current route
+          // This is pretty important, otherwise tracker
+          // can't identify new route's items
+
+          // We also need to afterFlush, otherwise this will re-run
+          // helpers on templates which are marked for destroying
+          if(oldestRoute) {
+            oldestRoute.registerRouteClose();
+          }
+        }
+      });
+    });
+
+    self.safeToRun--;
+  });
+
+  return tracker;
+};
+
+Router.prototype._invalidateTracker = function() {
+  var self = this;
+  this.safeToRun++;
+  this._tracker.invalidate();
+  // After the invalidation we need to flush to make changes imediately
+  // otherwise, we have face some issues context mix-maches and so on.
+  // But there are some cases we can't flush. So we need to ready for that.
+
+  // we clearly know, we can't flush inside an autorun
+  // this may leads some issues on flow-routing
+  // we may need to do some warning
+  if(!Tracker.currentComputation) {
+    // Still there are some cases where we can't flush
+    //  eg:- when there is a flush currently
+    // But we've no public API or hacks to get that state
+    // So, this is the only solution
+    try {
+      Tracker.flush();
+    } catch(ex) {
+      // only handling "while flushing" errors
+      if(!/Tracker\.flush while flushing/.test(ex.message)) {
+        return;
+      }
+
+      // XXX: fix this with a proper solution by removing subscription mgt.
+      // from the router. Then we don't need to run invalidate using a tracker
+
+      // this happens when we are trying to invoke a route change
+      // with inside a route chnage. (eg:- Template.onCreated)
+      // Since we use page.js and tracker, we don't have much control
+      // over this process.
+      // only solution is to defer route execution.
+
+      // It's possible to have more than one path want to defer
+      // But, we only need to pick the last one.
+      // self._nextPath = self._current.path;
+      Meteor.defer(function() {
+        var path = self._nextPath;
+        if(!path) {
+          return;
+        }
+
+        delete self._nextPath;
+        self.env.reload.withValue(true, function() {
+          self.go(path);
+        });
+      });
+    }
+  }
+};
+
+Router.prototype._updateCallbacks = function () {
+  var self = this;
+
+  self._page.callbacks = [];
+  self._page.exits = [];
+
+  _.each(self._routes, function(route) {
+    self._page(route.pathDef, route._actionHandle);
+    self._page.exit(route.pathDef, route._exitHandle);
+  });
+
+  self._page("*", function(context) {
+    self._notfoundRoute(context);
+  });
+};
+
+Router.prototype._initTriggersAPI = function() {
+  var self = this;
+  this.triggers = {
+    enter: function(triggers, filter) {
+      triggers = Triggers.applyFilters(triggers, filter);
+      if(triggers.length) {
+        self._triggersEnter = self._triggersEnter.concat(triggers);
+      }
+    },
+
+    exit: function(triggers, filter) {
+      triggers = Triggers.applyFilters(triggers, filter);
+      if(triggers.length) {
+        self._triggersExit = self._triggersExit.concat(triggers);
+      }
+    }
+  };
+};
+
+Router.prototype.wait = function() {
+  if(this._initialized) {
+    throw new Error("can't wait after FlowRouter has been initialized");
+  }
+
+  this._askedToWait = true;
+};
+
+Router.prototype.onRouteRegister = function(cb) {
+  this._onRouteCallbacks.push(cb);
+};
+
+Router.prototype._triggerRouteRegister = function(currentRoute) {
+  // We should only need to send a safe set of fields on the route
+  // object.
+  // This is not to hide what's inside the route object, but to show
+  // these are the public APIs
+  var routePublicApi = _.pick(currentRoute, 'name', 'pathDef', 'path');
+  var omittingOptionFields = [
+    'triggersEnter', 'triggersExit', 'action', 'subscriptions', 'name'
+  ];
+  routePublicApi.options = _.omit(currentRoute.options, omittingOptionFields);
+
+  _.each(this._onRouteCallbacks, function(cb) {
+    cb(routePublicApi);
+  });
+};
+
+Router.prototype._page = page;
+Router.prototype._qs = qs;

+ 112 - 0
packages/kadira-flow-router/client/triggers.js

@@ -0,0 +1,112 @@
+// a set of utility functions for triggers
+
+Triggers = {};
+
+// Apply filters for a set of triggers
+// @triggers - a set of triggers
+// @filter - filter with array fileds with `only` and `except` 
+//           support only either `only` or `except`, but not both
+Triggers.applyFilters = function(triggers, filter) {
+  if(!(triggers instanceof Array)) {
+    triggers = [triggers];
+  }
+
+  if(!filter) {
+    return triggers;
+  }
+
+  if(filter.only && filter.except) {
+    throw new Error("Triggers don't support only and except filters at once");
+  }
+
+  if(filter.only && !(filter.only instanceof Array)) {
+    throw new Error("only filters needs to be an array");
+  }
+
+  if(filter.except && !(filter.except instanceof Array)) {
+    throw new Error("except filters needs to be an array");
+  }
+
+  if(filter.only) {
+    return Triggers.createRouteBoundTriggers(triggers, filter.only);
+  }
+
+  if(filter.except) {
+    return Triggers.createRouteBoundTriggers(triggers, filter.except, true);
+  }
+
+  throw new Error("Provided a filter but not supported");
+};
+
+//  create triggers by bounding them to a set of route names
+//  @triggers - a set of triggers 
+//  @names - list of route names to be bound (trigger runs only for these names)
+//  @negate - negate the result (triggers won't run for above names)
+Triggers.createRouteBoundTriggers = function(triggers, names, negate) {
+  var namesMap = {};
+  _.each(names, function(name) {
+    namesMap[name] = true;
+  });
+
+  var filteredTriggers = _.map(triggers, function(originalTrigger) {
+    var modifiedTrigger = function(context, next) {
+      var routeName = context.route.name;
+      var matched = (namesMap[routeName])? 1: -1;
+      matched = (negate)? matched * -1 : matched;
+
+      if(matched === 1) {
+        originalTrigger(context, next);
+      }
+    };
+    return modifiedTrigger;
+  });
+
+  return filteredTriggers;
+};
+
+//  run triggers and abort if redirected or callback stopped
+//  @triggers - a set of triggers 
+//  @context - context we need to pass (it must have the route)
+//  @redirectFn - function which used to redirect 
+//  @after - called after if only all the triggers runs
+Triggers.runTriggers = function(triggers, context, redirectFn, after) {
+  var abort = false;
+  var inCurrentLoop = true;
+  var alreadyRedirected = false;
+
+  for(var lc=0; lc<triggers.length; lc++) {
+    var trigger = triggers[lc];
+    trigger(context, doRedirect, doStop);
+
+    if(abort) {
+      return;
+    }
+  }
+
+  // mark that, we've exceeds the currentEventloop for
+  // this set of triggers.
+  inCurrentLoop = false;
+  after();
+
+  function doRedirect(url, params, queryParams) {
+    if(alreadyRedirected) {
+      throw new Error("already redirected");
+    }
+
+    if(!inCurrentLoop) {
+      throw new Error("redirect needs to be done in sync");
+    }
+
+    if(!url) {
+      throw new Error("trigger redirect requires an URL");
+    }
+
+    abort = true;
+    alreadyRedirected = true;
+    redirectFn(url, params, queryParams);
+  }
+
+  function doStop() {
+    abort = true;
+  }
+};

+ 9 - 0
packages/kadira-flow-router/lib/router.js

@@ -0,0 +1,9 @@
+Router.prototype.url = function() {
+  // We need to remove the leading base path, or "/", as it will be inserted
+  // automatically by `Meteor.absoluteUrl` as documented in:
+  // http://docs.meteor.com/#/full/meteor_absoluteurl
+  var completePath = this.path.apply(this, arguments);
+  var basePath = this._basePath || '/';
+  var pathWithoutBase = completePath.replace(new RegExp('^' + basePath + '\/|(\/)'), '');
+  return Meteor.absoluteUrl(pathWithoutBase);
+};

+ 81 - 0
packages/kadira-flow-router/package.js

@@ -0,0 +1,81 @@
+Package.describe({
+  name: 'kadira:flow-router',
+  summary: 'Carefully Designed Client Side Router for Meteor, fixed by Serubin',
+  version: '2.12.1',
+  git: 'https://github.com/serubin/flow-router.git'
+});
+
+Npm.depends({
+  // In order to support IE9, we had to fork pagejs and apply
+  // this PR: https://github.com/visionmedia/page.js/pull/288
+  'page':'https://github.com/kadirahq/page.js/archive/34ddf45ea8e4c37269ce3df456b44fc0efc595c6.tar.gz',
+  'qs':'5.2.0'
+ });
+
+Package.onUse(function(api) {
+  configure(api);
+  api.export('FlowRouter');
+});
+
+Package.onTest(function(api) {
+  configure(api);
+  api.use('tinytest');
+  api.use('check');
+  api.use('mongo');
+  api.use('http');
+  api.use('random');
+  api.use('meteorhacks:fast-render');
+  api.use('meteorhacks:inject-data');
+  api.use('tmeasday:html5-history-api');
+
+  api.addFiles('test/common/fast_render_route.js', ['client', 'server']);
+
+  api.addFiles('test/client/_helpers.js', 'client');
+  api.addFiles('test/server/_helpers.js', 'server');
+
+  api.addFiles('test/client/loader.spec.js', 'client');
+  api.addFiles('test/client/route.reactivity.spec.js', 'client');
+  api.addFiles('test/client/router.core.spec.js', 'client');
+  api.addFiles('test/client/router.subs_ready.spec.js', 'client');
+  api.addFiles('test/client/router.reactivity.spec.js', 'client');
+  api.addFiles('test/client/group.spec.js', 'client');
+  api.addFiles('test/client/trigger.spec.js', 'client');
+  api.addFiles('test/client/triggers.js', 'client');
+
+  api.addFiles('test/server/plugins/fast_render.js', 'server');
+
+  api.addFiles('test/common/router.path.spec.js', ['client', 'server']);
+  api.addFiles('test/common/router.url.spec.js', ['client', 'server']);
+  api.addFiles('test/common/router.addons.spec.js', ['client', 'server']);
+  api.addFiles('test/common/route.spec.js', ['client', 'server']);
+  api.addFiles('test/common/group.spec.js', ['client', 'server']);
+});
+
+function configure(api) {
+  //api.versionsFrom('[email protected]');
+
+  api.use('underscore');
+  api.use('tracker');
+  api.use('reactive-dict');
+  api.use('reactive-var');
+  api.use('ejson');
+  api.use('modules');
+
+  api.use('meteorhacks:[email protected]', ['client', 'server'], {weak: true});
+
+  api.addFiles('client/modules.js', 'client');
+  api.addFiles('client/triggers.js', 'client');
+  api.addFiles('client/router.js', 'client');
+  api.addFiles('client/group.js', 'client');
+  api.addFiles('client/route.js', 'client');
+  api.addFiles('client/_init.js', 'client');
+
+  api.addFiles('server/router.js', 'server');
+  api.addFiles('server/group.js', 'server');
+  api.addFiles('server/route.js', 'server');
+  api.addFiles('server/_init.js', 'server');
+
+  api.addFiles('server/plugins/fast_render.js', 'server');
+
+  api.addFiles('lib/router.js', ['client', 'server']);
+}

+ 4 - 0
packages/kadira-flow-router/server/_init.js

@@ -0,0 +1,4 @@
+// Export Router Instance
+FlowRouter = new Router();
+FlowRouter.Router = Router;
+FlowRouter.Route = Route;

+ 18 - 0
packages/kadira-flow-router/server/group.js

@@ -0,0 +1,18 @@
+Group = function(router, options) {
+  options = options || {};
+  this.prefix = options.prefix || '';
+  this.options = options;
+  this._router = router;
+};
+
+Group.prototype.route = function(pathDef, options) {
+  pathDef = this.prefix + pathDef;
+  return this._router.route(pathDef, options);
+};
+
+Group.prototype.group = function(options) {
+  var group = new Group(this._router, options);
+  group.parent = this;
+
+  return group;
+};

+ 40 - 0
packages/kadira-flow-router/server/plugins/fast_render.js

@@ -0,0 +1,40 @@
+if(!Package['meteorhacks:fast-render']) {
+  return;
+}
+
+FastRender = Package['meteorhacks:fast-render'].FastRender;
+
+// hack to run after eveything else on startup
+Meteor.startup(function () {
+  Meteor.startup(function () {
+    setupFastRender();
+  });
+});
+
+function setupFastRender () {
+  _.each(FlowRouter._routes, function (route) {
+    FastRender.route(route.pathDef, function (routeParams, path) {
+      var self = this;
+
+      // anyone using Meteor.subscribe for something else?
+      var original = Meteor.subscribe;
+      Meteor.subscribe = function () {
+        return _.toArray(arguments);
+      };
+
+      route._subsMap = {};
+      FlowRouter.subscriptions.call(route, path);
+      if(route.subscriptions) {
+        var queryParams = routeParams.query;
+        var params = _.omit(routeParams, 'query');
+        route.subscriptions(params, queryParams);
+      }
+      _.each(route._subsMap, function (args) {
+        self.subscribe.apply(self, args);
+      });
+
+      // restore Meteor.subscribe, ... on server side
+      Meteor.subscribe = original;
+    });
+  });
+}

+ 28 - 0
packages/kadira-flow-router/server/route.js

@@ -0,0 +1,28 @@
+Route = function(router, pathDef, options) {
+  options = options || {};
+  this.options = options;
+  this.name = options.name;
+  this.pathDef = pathDef;
+
+  // Route.path is deprecated and will be removed in 3.0
+  this.path = pathDef;
+
+  this.action = options.action || Function.prototype;
+  this.subscriptions = options.subscriptions || Function.prototype;
+  this._subsMap = {};
+};
+
+
+Route.prototype.register = function(name, sub, options) {
+  this._subsMap[name] = sub;
+};
+
+
+Route.prototype.subscription = function(name) {
+  return this._subsMap[name];
+};
+
+
+Route.prototype.middleware = function(middleware) {
+ 
+};

+ 146 - 0
packages/kadira-flow-router/server/router.js

@@ -0,0 +1,146 @@
+var Qs = Npm.require('qs');
+
+Router = function () {
+  this._routes = [];
+  this._routesMap = {};
+  this.subscriptions = Function.prototype;
+
+  // holds onRoute callbacks
+  this._onRouteCallbacks = [];
+};
+
+Router.prototype.route = function(pathDef, options) {
+  if (!/^\/.*/.test(pathDef)) {
+    var message = "route's path must start with '/'";
+    throw new Error(message);
+  }
+  
+  options = options || {};
+  var route = new Route(this, pathDef, options);
+  this._routes.push(route);
+
+  if (options.name) {
+    this._routesMap[options.name] = route;
+  }
+
+  this._triggerRouteRegister(route);
+  return route;
+};
+
+Router.prototype.group = function(options) {
+  return new Group(this, options);
+};
+
+Router.prototype.path = function(pathDef, fields, queryParams) {
+  if (this._routesMap[pathDef]) {
+    pathDef = this._routesMap[pathDef].path;
+  }
+
+  fields = fields || {};
+  var regExp = /(:[\w\(\)\\\+\*\.\?]+)+/g;
+  var path = pathDef.replace(regExp, function(key) {
+    var firstRegexpChar = key.indexOf("(");
+    // get the content behind : and (\\d+/)
+    key = key.substring(1, (firstRegexpChar > 0)? firstRegexpChar: undefined);
+    // remove +?*
+    key = key.replace(/[\+\*\?]+/g, "");
+
+    return fields[key] || "";
+  });
+
+  path = path.replace(/\/\/+/g, "/"); // Replace multiple slashes with single slash
+
+  // remove trailing slash
+  // but keep the root slash if it's the only one
+  path = path.match(/^\/{1}$/) ? path: path.replace(/\/$/, "");
+
+  var strQueryParams = Qs.stringify(queryParams || {});
+  if(strQueryParams) {
+    path += "?" + strQueryParams;
+  }
+
+  return path;
+};
+
+Router.prototype.onRouteRegister = function(cb) {
+  this._onRouteCallbacks.push(cb);
+};
+
+Router.prototype._triggerRouteRegister = function(currentRoute) {
+  // We should only need to send a safe set of fields on the route
+  // object.
+  // This is not to hide what's inside the route object, but to show 
+  // these are the public APIs
+  var routePublicApi = _.pick(currentRoute, 'name', 'pathDef', 'path');
+  var omittingOptionFields = [
+    'triggersEnter', 'triggersExit', 'action', 'subscriptions', 'name'
+  ];
+  routePublicApi.options = _.omit(currentRoute.options, omittingOptionFields);
+
+  _.each(this._onRouteCallbacks, function(cb) {
+    cb(routePublicApi);
+  });
+};
+
+
+Router.prototype.go = function() {
+  // client only
+};
+
+
+Router.prototype.current = function() {
+  // client only
+};
+
+
+Router.prototype.triggers = {
+  enter: function() {
+    // client only
+  },
+  exit: function() {
+    // client only
+  }
+};
+
+Router.prototype.middleware = function() {
+  // client only
+};
+
+
+Router.prototype.getState = function() {
+  // client only
+};
+
+
+Router.prototype.getAllStates = function() {
+  // client only
+};
+
+
+Router.prototype.setState = function() {
+  // client only
+};
+
+
+Router.prototype.removeState = function() {
+  // client only
+};
+
+
+Router.prototype.clearStates = function() {
+  // client only
+};
+
+
+Router.prototype.ready = function() {
+  // client only
+};
+
+
+Router.prototype.initialize = function() {
+  // client only
+};
+
+Router.prototype.wait = function() {
+  // client only
+};

+ 10 - 0
packages/kadira-flow-router/test/client/_helpers.js

@@ -0,0 +1,10 @@
+GetSub = function (name) {
+  for(var id in Meteor.connection._subscriptions) {
+    var sub = Meteor.connection._subscriptions[id];
+    if(name === sub.name) {
+      return sub;
+    }
+  }
+};
+
+FlowRouter.route('/');

+ 113 - 0
packages/kadira-flow-router/test/client/group.spec.js

@@ -0,0 +1,113 @@
+Tinytest.add('Client - Group - validate path definition', function (test, next) {
+  // path & prefix must start with '/'
+  test.throws(function() {
+    new Group(null, {prefix: Random.id()});
+  });
+
+  var group = FlowRouter.group({prefix: '/' + Random.id()});
+
+  test.throws(function() {
+    group.route(Random.id());
+  });
+});
+
+Tinytest.addAsync('Client - Group - define and go to route with prefix', function (test, next) {
+  var prefix = Random.id();
+  var rand = Random.id();
+  var rendered = 0;
+
+  var group = FlowRouter.group({prefix: '/' + prefix});
+
+  group.route('/' + rand, {
+    action: function(_params) {
+      rendered++;
+    }
+  });
+
+  FlowRouter.go('/' + prefix + '/' + rand);
+
+  setTimeout(function() {
+    test.equal(rendered, 1);
+    setTimeout(next, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Group - define and go to route without prefix', function (test, next) {
+  var rand = Random.id();
+  var rendered = 0;
+
+  var group = FlowRouter.group();
+
+  group.route('/' + rand, {
+    action: function(_params) {
+      rendered++;
+    }
+  });
+
+  FlowRouter.go('/' + rand);
+
+  setTimeout(function() {
+    test.equal(rendered, 1);
+    setTimeout(next, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Group - subscribe', function (test, next) {
+  var rand = Random.id();
+
+  var group = FlowRouter.group({
+    subscriptions: function (params) {
+      this.register('baz', Meteor.subscribe('baz'));
+    }
+  });
+
+  group.route('/' + rand);
+
+  FlowRouter.go('/' + rand);
+  setTimeout(function() {
+    test.isTrue(!!GetSub('baz'));
+    next();
+  }, 100);
+});
+
+
+Tinytest.addAsync('Client - Group - set and retrieve group name', function (test, next) {
+  var rand = Random.id();
+  var name = Random.id();
+
+  var group = FlowRouter.group({
+    name: name
+  });
+
+  group.route('/' + rand);
+
+  FlowRouter.go('/' + rand);
+  setTimeout(function() {
+    test.isTrue(FlowRouter.current().route.group.name === name);
+    next();
+  }, 100);
+});
+
+Tinytest.add('Client - Group - expose group options on a route', function (test) {
+  var pathDef = "/" + Random.id();
+  var name = Random.id();
+  var groupName = Random.id();
+  var data = {aa: 10};
+  var layout = 'blah';
+
+  var group = FlowRouter.group({
+    name: groupName,
+    prefix: '/admin',
+    layout: layout,
+    someData: data
+  });
+
+  group.route(pathDef, {
+    name: name
+  });
+
+  var route = FlowRouter._routesMap[name];
+
+  test.equal(route.group.options.someData, data);
+  test.equal(route.group.options.layout, layout);
+});

+ 17 - 0
packages/kadira-flow-router/test/client/loader.spec.js

@@ -0,0 +1,17 @@
+Router = FlowRouter.Router;
+
+
+Tinytest.add('Client - import page.js', function (test) {
+  test.isTrue(!!Router.prototype._page);
+  test.isFalse(!!window.page);
+});
+
+
+Tinytest.add('Client - import query.js', function (test) {
+  test.isTrue(!!Router.prototype._qs);
+});
+
+
+Tinytest.add('Client - create FlowRouter', function (test) {
+  test.isTrue(!!FlowRouter);
+});

+ 158 - 0
packages/kadira-flow-router/test/client/route.reactivity.spec.js

@@ -0,0 +1,158 @@
+Route = FlowRouter.Route;
+
+
+Tinytest.addAsync('Client - Route - Reactivity - getParam', function (test, done) {
+  var r = new Route();
+  Tracker.autorun(function(c) {
+    var param = r.getParam("id");
+    if(param) {
+      test.equal(param, "hello");
+      c.stop();
+      Meteor.defer(done);
+    }
+  });
+  
+  setTimeout(function() {
+    var context = {
+      params: {id: "hello"},
+      queryParams: {}
+    };
+    r.registerRouteChange(context);
+  }, 10);
+});
+
+Tinytest.addAsync('Client - Route - Reactivity - getParam on route close', function (test, done) {
+  var r = new Route();
+  var closeTriggered = false;
+  Tracker.autorun(function(c) {
+    var param = r.getParam("id");
+    if(closeTriggered) {
+      test.equal(param, undefined);
+      c.stop();
+      Meteor.defer(done);
+    }
+  });
+  
+  setTimeout(function() {
+    closeTriggered = true;
+    r.registerRouteClose();
+  }, 10);
+});
+
+Tinytest.addAsync('Client - Route - Reactivity - getQueryParam', function (test, done) {
+  var r = new Route();
+  Tracker.autorun(function(c) {
+    var param = r.getQueryParam("id");
+    if(param) {
+      test.equal(param, "hello");
+      c.stop();
+      Meteor.defer(done);
+    }
+  });
+  
+  setTimeout(function() {
+    var context = {
+      params: {},
+      queryParams: {id: "hello"}
+    };
+    r.registerRouteChange(context);
+  }, 10);
+});
+
+Tinytest.addAsync('Client - Route - Reactivity - getQueryParam on route close', function (test, done) {
+  var r = new Route();
+  var closeTriggered = false;
+  Tracker.autorun(function(c) {
+    var param = r.getQueryParam("id");
+    if(closeTriggered) {
+      test.equal(param, undefined);
+      c.stop();
+      Meteor.defer(done);
+    }
+  });
+  
+  setTimeout(function() {
+    closeTriggered = true;
+    r.registerRouteClose();
+  }, 10);
+});
+
+Tinytest.addAsync('Client - Route - Reactivity - getRouteName rerun when route closed', function (test, done) {
+  var r = new Route();
+  r.name = "my-route";
+  var closeTriggered = false;
+
+  Tracker.autorun(function(c) {
+    var name = r.getRouteName();
+    test.equal(name, r.name);
+
+    if(closeTriggered) {
+      c.stop();
+      Meteor.defer(done);
+    }
+  });
+  
+  setTimeout(function() {
+    closeTriggered = true;
+    r.registerRouteClose();
+  }, 10);
+});
+
+Tinytest.addAsync('Client - Route - Reactivity - watchPathChange when routeChange', function (test, done) {
+  var r = new Route();
+  var pathChangeCounts = 0;
+
+  var c = Tracker.autorun(function() {
+    r.watchPathChange();
+    pathChangeCounts++;
+  });
+
+  var context = {
+    params: {},
+    queryParams: {}
+  };
+
+  setTimeout(function() {
+    r.registerRouteChange(context);
+    setTimeout(checkAfterNormalRouteChange, 50);
+  }, 10);
+
+  function checkAfterNormalRouteChange() {
+    test.equal(pathChangeCounts, 2);
+    var lastRouteChange = true;
+    r.registerRouteChange(context, lastRouteChange);
+    setTimeout(checkAfterLastRouteChange, 10);
+  }
+
+  function checkAfterLastRouteChange() {
+    test.equal(pathChangeCounts, 2);
+    c.stop();
+    Meteor.defer(done);
+  }
+});
+
+Tinytest.addAsync('Client - Route - Reactivity - watchPathChange when routeClose', function (test, done) {
+  var r = new Route();
+  var pathChangeCounts = 0;
+
+  var c = Tracker.autorun(function() {
+    r.watchPathChange();
+    pathChangeCounts++;
+  });
+
+  var context = {
+    params: {},
+    queryParams: {}
+  };
+  
+  setTimeout(function() {
+    r.registerRouteClose();
+    setTimeout(checkAfterRouteClose, 10);
+  }, 10);
+
+  function checkAfterRouteClose() {
+    test.equal(pathChangeCounts, 2);
+    c.stop();
+    Meteor.defer(done);
+  }
+});

+ 632 - 0
packages/kadira-flow-router/test/client/router.core.spec.js

@@ -0,0 +1,632 @@
+Router = FlowRouter.Router;
+
+Tinytest.addAsync('Client - Router - define and go to route', function (test, next) {
+  var rand = Random.id();
+  var rendered = 0;
+
+  FlowRouter.route('/' + rand, {
+    action: function(_params) {
+      rendered++;
+    }
+  });
+
+  FlowRouter.go('/' + rand);
+
+  setTimeout(function() {
+    test.equal(rendered, 1);
+    setTimeout(next, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Router - define and go to route with fields',
+function (test, next) {
+  var rand = Random.id();
+  var pathDef = "/" + rand + "/:key";
+  var rendered = 0;
+
+  FlowRouter.route(pathDef, {
+    action: function(params) {
+      test.equal(params.key, "abc [email protected]%");
+      rendered++;
+    }
+  });
+
+  FlowRouter.go(pathDef, {key: "abc [email protected]%"});
+
+  setTimeout(function() {
+    test.equal(rendered, 1);
+    setTimeout(next, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Router - parse params and query', function (test, next) {
+  var rand = Random.id();
+  var rendered = 0;
+  var params = null;
+
+  FlowRouter.route('/' + rand + '/:foo', {
+    action: function(_params) {
+      rendered++;
+      params = _params;
+    }
+  });
+
+  FlowRouter.go('/' + rand + '/bar');
+
+  setTimeout(function() {
+    test.equal(rendered, 1);
+    test.equal(params.foo, 'bar');
+    setTimeout(next, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Router - redirect using FlowRouter.go', function (test, next) {
+  var rand = Random.id(), rand2 = Random.id();
+  var log = [];
+  var paths = ['/' + rand2, '/' + rand];
+  var done = false;
+
+  FlowRouter.route(paths[0], {
+    action: function(_params) {
+      log.push(1);
+      FlowRouter.go(paths[1]);
+    }
+  });
+
+  FlowRouter.route(paths[1], {
+    action: function(_params) {
+      log.push(2);
+    }
+  });
+
+  FlowRouter.go(paths[0]);
+
+  setTimeout(function() {
+    test.equal(log, [1, 2]);
+    done = true;
+    next();
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Router - get current route path', function (test, next) {
+  var value = Random.id();
+  var randomValue = Random.id();
+  var pathDef = "/" + randomValue + '/:_id';
+  var path = "/" + randomValue + "/" + value;
+
+  var detectedValue = null;
+
+  FlowRouter.route(pathDef, {
+    action: function(params) {
+      detectedValue = params._id;
+    }
+  });
+
+  FlowRouter.go(path);
+
+  Meteor.setTimeout(function() {
+    test.equal(detectedValue, value);
+    test.equal(FlowRouter.current().path, path);
+    next();
+  }, 50);
+});
+
+Tinytest.addAsync('Client - Router - subscribe to global subs', function (test, next) {
+  var rand = Random.id();
+  FlowRouter.route('/' + rand);
+
+  FlowRouter.subscriptions = function (path) {
+    test.equal(path, '/' + rand);
+    this.register('baz', Meteor.subscribe('baz'));
+  };
+
+  FlowRouter.go('/' + rand);
+  setTimeout(function() {
+    test.isTrue(!!GetSub('baz'));
+    FlowRouter.subscriptions = Function.prototype;
+    next();
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Router - setParams - generic', function (test, done) {
+  var randomKey = Random.id();
+  var pathDef = "/" + randomKey + "/:cat/:id";
+  var paramsList = [];
+  FlowRouter.route(pathDef, {
+    action: function(params) {
+      paramsList.push(params);
+    }
+  });
+
+  FlowRouter.go(pathDef, {cat: "meteor", id: "200"});
+  setTimeout(function() {
+    // return done();
+    var success = FlowRouter.setParams({id: "700"});
+    test.isTrue(success);
+    setTimeout(validate, 50);
+  }, 50);
+
+  function validate() {
+    test.equal(paramsList.length, 2);
+    test.equal(_.pick(paramsList[0], "id", "cat"), {cat: "meteor", id: "200"});
+    test.equal(_.pick(paramsList[1], "id", "cat"), {cat: "meteor", id: "700"});
+    done();
+  }
+});
+
+Tinytest.addAsync('Client - Router - setParams - preserve query strings', function (test, done) {
+  var randomKey = Random.id();
+  var pathDef = "/" + randomKey + "/:cat/:id";
+  var paramsList = [];
+  var queryParamsList = [];
+
+  FlowRouter.route(pathDef, {
+    action: function(params, queryParams) {
+      paramsList.push(params);
+      queryParamsList.push(queryParams);
+    }
+  });
+
+  FlowRouter.go(pathDef, {cat: "meteor", id: "200 +% / ad"}, {aa: "20 +%"});
+  setTimeout(function() {
+    // return done();
+    var success = FlowRouter.setParams({id: "700 +% / ad"});
+    test.isTrue(success);
+    setTimeout(validate, 50);
+  }, 50);
+
+  function validate() {
+    test.equal(paramsList.length, 2);
+    test.equal(queryParamsList.length, 2);
+
+    test.equal(_.pick(paramsList[0], "id", "cat"), {cat: "meteor", id: "200 +% / ad"});
+    test.equal(_.pick(paramsList[1], "id", "cat"), {cat: "meteor", id: "700 +% / ad"});
+    test.equal(queryParamsList, [{aa: "20 +%"}, {aa: "20 +%"}]);
+    done();
+  }
+});
+
+Tinytest.add('Client - Router - setParams - no route selected', function (test) {
+  var originalRoute = FlowRouter._current.route;
+  FlowRouter._current.route = undefined;
+  var success = FlowRouter.setParams({id: "800"});
+  test.isFalse(success);
+  FlowRouter._current.route = originalRoute;
+});
+
+Tinytest.addAsync('Client - Router - setQueryParams - using check', function (test, done) {
+  var randomKey = Random.id();
+  var pathDef = "/" + randomKey + "";
+  var queryParamsList = [];
+  FlowRouter.route(pathDef, {
+    action: function(params, queryParams) {
+      queryParamsList.push(queryParams);
+    }
+  });
+
+  FlowRouter.go(pathDef, {}, {cat: "meteor", id: "200"});
+  setTimeout(function() {
+    check(FlowRouter.current().queryParams, {cat: String, id: String});
+    done();
+  }, 50);
+});
+
+Tinytest.addAsync('Client - Router - setQueryParams - generic', function (test, done) {
+  var randomKey = Random.id();
+  var pathDef = "/" + randomKey + "";
+  var queryParamsList = [];
+  FlowRouter.route(pathDef, {
+    action: function(params, queryParams) {
+      queryParamsList.push(queryParams);
+    }
+  });
+
+  FlowRouter.go(pathDef, {}, {cat: "meteor", id: "200"});
+  setTimeout(function() {
+    // return done();
+    var success = FlowRouter.setQueryParams({id: "700"});
+    test.isTrue(success);
+    setTimeout(validate, 50);
+  }, 50);
+
+  function validate() {
+    test.equal(queryParamsList.length, 2);
+    test.equal(_.pick(queryParamsList[0], "id", "cat"), {cat: "meteor", id: "200"});
+    test.equal(_.pick(queryParamsList[1], "id", "cat"), {cat: "meteor", id: "700"});
+    done();
+  }
+});
+
+Tinytest.addAsync('Client - Router - setQueryParams - remove query param null', function (test, done) {
+  var randomKey = Random.id();
+  var pathDef = "/" + randomKey + "";
+  var queryParamsList = [];
+  FlowRouter.route(pathDef, {
+    action: function(params, queryParams) {
+      queryParamsList.push(queryParams);
+    }
+  });
+
+  FlowRouter.go(pathDef, {}, {cat: "meteor", id: "200"});
+  setTimeout(function() {
+    var success = FlowRouter.setQueryParams({id: "700", cat: null});
+    test.isTrue(success);
+    setTimeout(validate, 50);
+  }, 50);
+
+  function validate() {
+    test.equal(queryParamsList.length, 2);
+    test.equal(_.pick(queryParamsList[0], "id", "cat"), {cat: "meteor", id: "200"});
+    test.equal(queryParamsList[1], {id: "700"});
+    done();
+  }
+});
+
+Tinytest.addAsync('Client - Router - setQueryParams - remove query param undefined', function (test, done) {
+  var randomKey = Random.id();
+  var pathDef = "/" + randomKey + "";
+  var queryParamsList = [];
+  FlowRouter.route(pathDef, {
+    action: function(params, queryParams) {
+      queryParamsList.push(queryParams);
+    }
+  });
+
+  FlowRouter.go(pathDef, {}, {cat: "meteor", id: "200"});
+  setTimeout(function() {
+    var success = FlowRouter.setQueryParams({id: "700", cat: undefined});
+    test.isTrue(success);
+    setTimeout(validate, 50);
+  }, 50);
+
+  function validate() {
+    test.equal(queryParamsList.length, 2);
+    test.equal(_.pick(queryParamsList[0], "id", "cat"), {cat: "meteor", id: "200"});
+    test.equal(queryParamsList[1], {id: "700"});
+    done();
+  }
+});
+
+Tinytest.addAsync('Client - Router - setQueryParams - preserve params', function (test, done) {
+  var randomKey = Random.id();
+  var pathDef = "/" + randomKey + "/:abc";
+  var queryParamsList = [];
+  var paramsList = [];
+  FlowRouter.route(pathDef, {
+    action: function(params, queryParams) {
+      paramsList.push(params);
+      queryParamsList.push(queryParams);
+    }
+  });
+
+  FlowRouter.go(pathDef, {abc: "20"}, {cat: "meteor", id: "200"});
+  setTimeout(function() {
+    // return done();
+    var success = FlowRouter.setQueryParams({id: "700"});
+    test.isTrue(success);
+    setTimeout(validate, 50);
+  }, 50);
+
+  function validate() {
+    test.equal(queryParamsList.length, 2);
+    test.equal(queryParamsList, [
+      {cat: "meteor", id: "200"}, {cat: "meteor", id: "700"}
+    ]);
+
+    test.equal(paramsList.length, 2);
+    test.equal(_.pick(paramsList[0], "abc"), {abc: "20"});
+    test.equal(_.pick(paramsList[1], "abc"), {abc: "20"});
+    done();
+  }
+});
+
+Tinytest.add('Client - Router - setQueryParams - no route selected', function (test) {
+  var originalRoute = FlowRouter._current.route;
+  FlowRouter._current.route = undefined;
+  var success = FlowRouter.setQueryParams({id: "800"});
+  test.isFalse(success);
+  FlowRouter._current.route = originalRoute;
+});
+
+Tinytest.addAsync('Client - Router - notFound', function (test, done) {
+  var data = [];
+  FlowRouter.notFound = {
+    subscriptions: function() {
+      data.push("subscriptions");
+    },
+    action: function() {
+      data.push("action");
+    }
+  };
+
+  FlowRouter.go("/" + Random.id());
+  setTimeout(function() {
+    test.equal(data, ["subscriptions", "action"]);
+    done();
+  }, 50);
+});
+
+Tinytest.addAsync('Client - Router - withReplaceState - enabled',
+function (test, done) {
+  var pathDef = "/" + Random.id() + "/:id";
+  var originalRedirect = FlowRouter._page.replace;
+  var callCount = 0;
+  FlowRouter._page.replace = function(path) {
+    callCount++;
+    originalRedirect.call(FlowRouter._page, path);
+  };
+
+  FlowRouter.route(pathDef, {
+    name: name,
+    action: function(params) {
+      test.equal(params.id, "awesome");
+      test.equal(callCount, 1);
+      FlowRouter._page.replace = originalRedirect;
+      // We don't use Meteor.defer here since it carries
+      // Meteor.Environment vars too
+      // Which breaks our test below
+      setTimeout(done, 0);
+    }
+  });
+
+  FlowRouter.withReplaceState(function() {
+    FlowRouter.go(pathDef, {id: "awesome"});
+  });
+});
+
+Tinytest.addAsync('Client - Router - withReplaceState - disabled',
+function (test, done) {
+  var pathDef = "/" + Random.id() + "/:id";
+  var originalRedirect = FlowRouter._page.replace;
+  var callCount = 0;
+  FlowRouter._page.replace = function(path) {
+    callCount++;
+    originalRedirect.call(FlowRouter._page, path);
+  };
+
+  FlowRouter.route(pathDef, {
+    name: name,
+    action: function(params) {
+      test.equal(params.id, "awesome");
+      test.equal(callCount, 0);
+      FlowRouter._page.replace = originalRedirect;
+      Meteor.defer(done);
+    }
+  });
+
+  FlowRouter.go(pathDef, {id: "awesome"});
+});
+
+Tinytest.addAsync('Client - Router - withTrailingSlash - enabled', function (test, next) {
+  var rand = Random.id();
+  var rendered = 0;
+
+  FlowRouter.route('/' + rand, {
+    action: function(_params) {
+      rendered++;
+    }
+  });
+
+  FlowRouter.withTrailingSlash(function() {
+    FlowRouter.go('/' + rand);
+  });
+
+  setTimeout(function() {
+    test.equal(rendered, 1);
+    test.equal(_.last(location.href), '/');
+    setTimeout(next, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Router - idempotent routing - action',
+function (test, done) {
+  var rand = Random.id();
+  var pathDef = "/" + rand;
+  var rendered = 0;
+
+  FlowRouter.route(pathDef, {
+    action: function(params) {
+      rendered++;
+    }
+  });
+
+  FlowRouter.go(pathDef);
+
+  Meteor.defer(function() {
+    FlowRouter.go(pathDef);
+
+    Meteor.defer(function() {
+      test.equal(rendered, 1);
+      done();
+    });
+  });
+});
+
+Tinytest.addAsync('Client - Router - idempotent routing - triggers',
+function (test, next) {
+  var rand = Random.id();
+  var pathDef = "/" + rand;
+  var runnedTriggers = 0;
+  var done = false;
+
+  var triggerFns = [function(params) {
+    if (done) return;
+
+    runnedTriggers++;
+  }];
+
+  FlowRouter.triggers.enter(triggerFns);
+
+  FlowRouter.route(pathDef, {
+    triggersEnter: triggerFns,
+    triggersExit: triggerFns
+  });
+
+  FlowRouter.go(pathDef);
+
+  FlowRouter.triggers.exit(triggerFns);
+
+  Meteor.defer(function() {
+    FlowRouter.go(pathDef);
+
+    Meteor.defer(function() {
+      test.equal(runnedTriggers, 2);
+      done = true;
+      next();
+    });
+  });
+});
+
+Tinytest.addAsync('Client - Router - reload - action',
+function (test, done) {
+  var rand = Random.id();
+  var pathDef = "/" + rand;
+  var rendered = 0;
+
+  FlowRouter.route(pathDef, {
+    action: function(params) {
+      rendered++;
+    }
+  });
+
+  FlowRouter.go(pathDef);
+
+  Meteor.defer(function() {
+    FlowRouter.reload();
+
+    Meteor.defer(function() {
+      test.equal(rendered, 2);
+      done();
+    });
+  });
+});
+
+Tinytest.addAsync('Client - Router - reload - triggers',
+function (test, next) {
+  var rand = Random.id();
+  var pathDef = "/" + rand;
+  var runnedTriggers = 0;
+  var done = false;
+
+  var triggerFns = [function(params) {
+    if (done) return;
+
+    runnedTriggers++;
+  }];
+
+  FlowRouter.triggers.enter(triggerFns);
+
+  FlowRouter.route(pathDef, {
+    triggersEnter: triggerFns,
+    triggersExit: triggerFns
+  });
+
+  FlowRouter.go(pathDef);
+
+  FlowRouter.triggers.exit(triggerFns);
+
+  Meteor.defer(function() {
+    FlowRouter.reload();
+
+    Meteor.defer(function() {
+      test.equal(runnedTriggers, 6);
+      done = true;
+      next();
+    });
+  });
+});
+
+Tinytest.addAsync(
+'Client - Router - wait - before initialize',
+function(test, done) {
+  FlowRouter._initialized = false;
+  FlowRouter.wait();
+  test.equal(FlowRouter._askedToWait, true);
+
+  FlowRouter._initialized = true;
+  FlowRouter._askedToWait = false;
+  done();
+});
+
+Tinytest.addAsync(
+'Client - Router - wait - after initialized',
+function(test, done) {
+  try {
+    FlowRouter.wait();
+  } catch(ex) {
+    test.isTrue(/can't wait/.test(ex.message));
+    done();
+  }
+});
+
+Tinytest.addAsync(
+'Client - Router - initialize - after initialized',
+function(test, done) {
+  try {
+    FlowRouter.initialize();
+  } catch(ex) {
+    test.isTrue(/already initialized/.test(ex.message));
+    done();
+  }
+});
+
+Tinytest.addAsync(
+'Client - Router - base path - url updated',
+function(test, done) {
+  var simulatedBasePath = '/flow';
+  var rand = Random.id();
+  FlowRouter.route('/' + rand, { action: function() {} });
+
+  setBasePath(simulatedBasePath);
+  FlowRouter.go('/' + rand);
+  setTimeout(function() {