Ver Fonte

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

Thanks to xet7 !

Lauri Ojansivu há 6 anos atrás
pai
commit
73e265d8fd
100 ficheiros alterados com 11019 adições e 13 exclusões
  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. 5 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. 15 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.
+    - page@1.6.3: https://github.com/visionmedia/page.js
+    - qs@3.1.0: 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). <hello@meteorhacks.com>
+
+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('METEOR@1.3-rc.1');
+
+  api.use('underscore');
+  api.use('tracker');
+  api.use('reactive-dict');
+  api.use('reactive-var');
+  api.use('ejson');
+  api.use('modules');
+
+  api.use('meteorhacks:fast-render@2.14.0', ['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 +@%");
+      rendered++;
+    }
+  });
+
+  FlowRouter.go(pathDef, {key: "abc +@%"});
+
+  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() {
+    test.equal(location.pathname, simulatedBasePath + '/' + rand);
+    resetBasePath();
+    done();
+  }, 100);
+});
+
+Tinytest.addAsync(
+'Client - Router - base path - route action called',
+function(test, done) {
+  var simulatedBasePath = '/flow';
+  var rand = Random.id();
+  FlowRouter.route('/' + rand, {
+    action: function() {
+      resetBasePath();
+      done();
+    }
+  });
+
+  setBasePath(simulatedBasePath);
+  FlowRouter.go('/' + rand);
+});
+
+Tinytest.add(
+'Client - Router - base path - path generation',
+function(test, done) {
+  _.each(['/flow', '/flow/', 'flow/', 'flow'], function(simulatedBasePath) {
+    var rand = Random.id();
+    setBasePath(simulatedBasePath);
+    test.equal(FlowRouter.path('/' + rand), '/flow/' + rand);
+  });
+  resetBasePath();
+});
+
+
+function setBasePath(path) {
+  FlowRouter._initialized = false;
+  FlowRouter._basePath = path;
+  FlowRouter.initialize();
+}
+
+var defaultBasePath = FlowRouter._basePath;
+function resetBasePath() {
+  setBasePath(defaultBasePath);
+}
+
+function bind(obj, method) {
+  return function() {
+    obj[method].apply(obj, arguments);
+  };
+}

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

@@ -0,0 +1,208 @@
+Tinytest.addAsync(
+'Client - Router - Reactivity - detectChange only once', 
+function (test, done) {
+  var route = "/" + Random.id();
+  var name = Random.id();
+  FlowRouter.route(route, {name: name});
+  
+  var ranCount = 0;
+  var pickedId = null;
+  var c = Tracker.autorun(function() {
+    ranCount++;
+    pickedId = FlowRouter.getQueryParam("id");
+    if(pickedId) {
+      test.equal(pickedId, "hello");
+      test.equal(ranCount, 2);
+      c.stop();
+      Meteor.defer(done);
+    }
+  });
+
+  setTimeout(function() {
+    FlowRouter.go(name, {}, {id: "hello"});
+  }, 2);
+});
+
+Tinytest.addAsync(
+'Client - Router - Reactivity - detectChange in the action', 
+function (test, done) {
+  var route = "/" + Random.id();
+  var name = Random.id();
+  FlowRouter.route(route, {
+    name: name,
+    action: function() {
+      var id = FlowRouter.getQueryParam("id");
+      test.equal(id, "hello");
+      Meteor.defer(done);
+    }
+  });
+
+  setTimeout(function() {
+    FlowRouter.go(name, {}, {id: "hello"});
+  }, 2);
+});
+
+Tinytest.addAsync(
+'Client - Router - Reactivity - detect prev routeChange after new action', 
+function (test, done) {
+  var route1 = "/" + Random.id();
+  var name1 = Random.id();
+  var pickedName1 = null;
+
+  var route2 = "/" + Random.id();
+  var name2 = Random.id();
+  var pickedName2 = Random.id();
+
+  FlowRouter.route(route1, {
+    name: name1,
+    action: function() {
+      Tracker.autorun(function(c) {
+        pickedName1 = FlowRouter.getRouteName();
+        if(pickedName1 == name2) {
+          test.equal(pickedName1, pickedName2);
+          c.stop();
+          Meteor.defer(done);
+        }
+      });
+    }
+  });
+
+  FlowRouter.route(route2, {
+    name: name2,
+    action: function() {
+      pickedName2 = FlowRouter.getRouteName();
+      test.equal(pickedName1, name1);
+      test.equal(pickedName2, name2);
+    }
+  });
+
+  FlowRouter.go(name1);
+  Meteor.setTimeout(function() {
+    FlowRouter.go(name2);
+  }, 10);
+});
+
+Tinytest.addAsync(
+'Client - Router - Reactivity - defer watchPathChange until new route rendered',
+function(test, done) {
+  var route1 = "/" + Random.id();
+  var name1 = Random.id();
+  var pickedName1 = null;
+
+  var route2 = "/" + Random.id();
+  var name2 = Random.id();
+  var pickedName2 = Random.id();
+
+  FlowRouter.route(route1, {
+    name: name1,
+    action: function() {
+      Tracker.autorun(function(c) {
+        FlowRouter.watchPathChange();
+        pickedName1 = FlowRouter.current().route.name;
+        if(pickedName1 == name2) {
+          test.equal(pickedName1, pickedName2);
+          c.stop();
+          Meteor.defer(done);
+        }
+      });
+    }
+  });
+
+  FlowRouter.route(route2, {
+    name: name2,
+    action: function() {
+      pickedName2 = FlowRouter.current().route.name;
+      test.equal(pickedName1, name1);
+      test.equal(pickedName2, name2);
+    }
+  });
+
+  FlowRouter.go(name1);
+  Meteor.setTimeout(function() {
+    FlowRouter.go(name2);
+  }, 10);
+});
+
+Tinytest.addAsync(
+'Client - Router - Reactivity - reactive changes and trigger redirects',
+function(test, done) {
+  var name1 = Random.id();
+  var route1 = "/" + name1;
+  FlowRouter.route(route1, {
+    name: name1
+  });
+
+  var name2 = Random.id();
+  var route2 = "/" + name2;
+  FlowRouter.route(route2, {
+    name: name2,
+    triggersEnter: [function(context, redirect) {
+      redirect(name3);
+    }]
+  });
+
+
+  var name3 = Random.id();
+  var route3 = "/" + name3;
+  FlowRouter.route(route3, {
+    name: name3
+  });
+
+  var routeNamesFired = [];
+  FlowRouter.go(name1);
+
+  var c = null;
+  setTimeout(function() {
+    c = Tracker.autorun(function(c) {
+      routeNamesFired.push(FlowRouter.getRouteName());
+    });
+    FlowRouter.go(name2);
+  }, 50);
+
+  setTimeout(function() {
+    c.stop();
+    test.equal(routeNamesFired, [name1, name3]);
+    Meteor.defer(done);
+  }, 250);
+});
+
+Tinytest.addAsync(
+'Client - Router - Reactivity - watchPathChange for every route change',
+function(test, done) {
+  var route1 = "/" + Random.id();
+  var name1 = Random.id();
+  var pickedName1 = null;
+
+  var route2 = "/" + Random.id();
+  var name2 = Random.id();
+  var pickedName2 = Random.id();
+
+  FlowRouter.route(route1, {
+    name: name1
+  });
+
+  FlowRouter.route(route2, {
+    name: name2
+  });
+
+  var ids = [];
+  var c = Tracker.autorun(function() {
+    FlowRouter.watchPathChange();
+    ids.push(FlowRouter.current().queryParams['id']);
+  });
+
+  FlowRouter.go(name1, {}, {id: "one"});
+  Meteor.setTimeout(function() {
+    FlowRouter.go(name1, {}, {id: "two"});
+  }, 10);
+
+  Meteor.setTimeout(function() {
+    FlowRouter.go(name2, {}, {id: "three"});
+  }, 20);
+
+  Meteor.setTimeout(function() {
+    test.equal(ids, [undefined, "one", "two", "three"]);
+    c.stop();
+    done();
+  }, 40);
+});

+ 225 - 0
packages/kadira-flow-router/test/client/router.subs_ready.spec.js

@@ -0,0 +1,225 @@
+Tinytest.addAsync('Client - Router - subsReady - with no args - all subscriptions ready', function (test, next) {
+  var rand = Random.id();
+  FlowRouter.route('/' + rand, {
+    subscriptions: function(params) {
+      this.register('bar', Meteor.subscribe('bar'));
+      this.register('foo', Meteor.subscribe('foo'));
+    }
+  });
+
+  FlowRouter.subscriptions = function () {
+    this.register('baz', Meteor.subscribe('baz'));
+  };
+
+  FlowRouter.go('/' + rand);
+
+  Tracker.autorun(function(c) {
+    if(FlowRouter.subsReady()) {
+      FlowRouter.subscriptions = Function.prototype;
+      next();
+      c.stop();
+    }
+  });
+});
+
+Tinytest.addAsync('Client - Router - subsReady - with no args - all subscriptions does not ready', function (test, next) {
+  var rand = Random.id();
+  FlowRouter.route('/' + rand, {
+    subscriptions: function(params) {
+      this.register('fooNotReady', Meteor.subscribe('fooNotReady'));
+    }
+  });
+
+  FlowRouter.subscriptions = function () {
+    this.register('bazNotReady', Meteor.subscribe('bazNotReady'));
+  };
+
+  FlowRouter.go('/' + rand);
+  setTimeout(function() {
+    test.isTrue(!FlowRouter.subsReady());
+    FlowRouter.subscriptions = Function.prototype;
+    next();
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Router - subsReady - with no args - global subscriptions does not ready', function (test, next) {
+  var rand = Random.id();
+  FlowRouter.route('/' + rand, {
+    subscriptions: function(params) {
+      this.register('bar', Meteor.subscribe('bar'));
+      this.register('foo', Meteor.subscribe('foo'));
+    }
+  });
+
+  FlowRouter.subscriptions = function () {
+    this.register('bazNotReady', Meteor.subscribe('bazNotReady'));
+  };
+
+  FlowRouter.go('/' + rand);
+  setTimeout(function() {
+    test.isTrue(!FlowRouter.subsReady());
+    FlowRouter.subscriptions = Function.prototype;
+    next();
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Router - subsReady - with no args - current subscriptions does not ready', function (test, next) {
+  var rand = Random.id();
+  FlowRouter.route('/' + rand, {
+    subscriptions: function(params) {
+      this.register('bar', Meteor.subscribe('bar'));
+      this.register('fooNotReady', Meteor.subscribe('fooNotReady'));
+    }
+  });
+
+  FlowRouter.subscriptions = function () {
+    this.register('baz', Meteor.subscribe('baz'));
+  };
+
+  FlowRouter.go('/' + rand);
+  setTimeout(function() {
+    test.isTrue(!FlowRouter.subsReady());
+    FlowRouter.subscriptions = Function.prototype;
+    next();
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Router - subsReady - with args - all subscriptions ready', function (test, next) {
+  var rand = Random.id();
+  FlowRouter.route('/' + rand, {
+    subscriptions: function(params) {
+      this.register('bar', Meteor.subscribe('bar'));
+      this.register('foo', Meteor.subscribe('foo'));
+    }
+  });
+
+  FlowRouter.subscriptions = function () {
+    this.register('baz', Meteor.subscribe('baz'));
+  };
+
+  FlowRouter.go('/' + rand);
+  Tracker.autorun(function(c) {
+    if(FlowRouter.subsReady('foo', 'baz')) {
+      FlowRouter.subscriptions = Function.prototype;
+      next();
+      c.stop();
+    }
+  });
+});
+
+Tinytest.addAsync('Client - Router - subsReady - with args - all subscriptions does not ready', function (test, next) {
+  var rand = Random.id();
+  FlowRouter.route('/' + rand, {
+    subscriptions: function(params) {
+      this.register('fooNotReady', Meteor.subscribe('fooNotReady'));
+    }
+  });
+
+  FlowRouter.subscriptions = function () {
+    this.register('bazNotReady', Meteor.subscribe('bazNotReady'));
+  };
+
+  FlowRouter.go('/' + rand);
+  setTimeout(function() {
+    test.isTrue(!FlowRouter.subsReady('fooNotReady', 'bazNotReady'));
+    FlowRouter.subscriptions = Function.prototype;
+    next();
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Router - subsReady - with args - global subscriptions does not ready', function (test, next) {
+  var rand = Random.id();
+  FlowRouter.route('/' + rand, {
+    subscriptions: function(params) {
+      this.register('bar', Meteor.subscribe('bar'));
+      this.register('foo', Meteor.subscribe('foo'));
+    }
+  });
+
+  FlowRouter.subscriptions = function () {
+    this.register('bazNotReady', Meteor.subscribe('bazNotReady'));
+  };
+
+  FlowRouter.go('/' + rand);
+  setTimeout(function() {
+    test.isTrue(!FlowRouter.subsReady('foo', 'bazNotReady'));
+    FlowRouter.subscriptions = Function.prototype;
+    next();
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Router - subsReady - with args - current subscriptions does not ready', function (test, next) {
+  var rand = Random.id();
+  FlowRouter.route('/' + rand, {
+    subscriptions: function(params) {
+      this.register('bar', Meteor.subscribe('bar'));
+      this.register('fooNotReady', Meteor.subscribe('fooNotReady'));
+    }
+  });
+
+  FlowRouter.subscriptions = function () {
+    this.register('baz', Meteor.subscribe('baz'));
+  };
+
+  FlowRouter.go('/' + rand);
+  setTimeout(function() {
+    test.isTrue(!FlowRouter.subsReady('fooNotReady', 'baz'));
+    FlowRouter.subscriptions = Function.prototype;
+    next();
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Router - subsReady - with args - subscribe with wrong name', function (test, next) {
+  var rand = Random.id();
+  FlowRouter.route('/' + rand, {
+    subscriptions: function(params) {
+      this.register('bar', Meteor.subscribe('bar'));
+    }
+  });
+
+  FlowRouter.subscriptions = function () {
+    this.register('baz', Meteor.subscribe('baz'));
+  };
+
+  FlowRouter.go('/' + rand);
+  setTimeout(function() {
+    test.isTrue(!FlowRouter.subsReady('baz', 'xxx', 'baz'));
+    FlowRouter.subscriptions = Function.prototype;
+    next();
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Router - subsReady - with args - same route two different subs', function (test, next) {
+  var rand = Random.id();
+  var count = 0;
+  FlowRouter.route('/' + rand, {
+    subscriptions: function(params) {
+      if(++count == 1) {
+        this.register('not-exisitng', Meteor.subscribe('not-exisitng'));
+      }
+    }
+  });
+
+  FlowRouter.subscriptions = Function.prototype;
+  FlowRouter.go('/' + rand);
+  setTimeout(function() {
+    test.isFalse(FlowRouter.subsReady());
+    FlowRouter.go('/' + rand, {}, {param: "111"});
+    setTimeout(function() {
+      test.isTrue(FlowRouter.subsReady());
+      next();
+    }, 100)
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Router - subsReady - no subscriptions - simple', function (test, next) {
+  var rand = Random.id();
+  FlowRouter.route('/' + rand, {});
+  FlowRouter.subscriptions = Function.prototype;
+
+  FlowRouter.go('/' + rand);
+  setTimeout(function() {
+    test.isTrue(FlowRouter.subsReady());
+    next();
+  }, 100);
+});

+ 570 - 0
packages/kadira-flow-router/test/client/trigger.spec.js

@@ -0,0 +1,570 @@
+Tinytest.addAsync('Client - Triggers - global enter triggers', function(test, next) {
+  var rand = Random.id(), rand2 = Random.id();
+  var log = [];
+  var paths = ['/' + rand2, '/' + rand];
+  var done = false;
+
+  FlowRouter.route('/' + rand, {
+    action: function(_params) {
+      log.push(1);
+    }
+  });
+
+  FlowRouter.route('/' + rand2, {
+    action: function(_params) {
+      log.push(2);
+    }
+  });
+
+  FlowRouter.triggers.enter([function(context) {
+    if(done) return;
+    test.equal(context.path, paths.pop());
+    log.push(0);
+  }]);
+
+  FlowRouter.go('/' + rand);
+
+  setTimeout(function() {
+    FlowRouter.go('/' + rand2);
+
+    setTimeout(function() {
+      test.equal(log, [0, 1, 0, 2]);
+      done = true;
+      setTimeout(next, 100);
+    }, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Triggers - global enter triggers with "only"', function (test, next) {
+  var rand = Random.id(), rand2 = Random.id();
+  var log = [];
+  var done = false;
+
+  FlowRouter.route('/' + rand, {
+    action: function(_params) {
+      log.push(1);
+    }
+  });
+
+  FlowRouter.route('/' + rand2, {
+    name: 'foo',
+    action: function(_params) {
+      log.push(2);
+    }
+  });
+
+  FlowRouter.triggers.enter([function(context) {
+    if(done) return;
+    test.equal(context.path, '/' + rand2);
+    log.push(8);
+  }], {only: ['foo']});
+
+  FlowRouter.go('/' + rand);
+
+  setTimeout(function() {
+    FlowRouter.go('/' + rand2);
+
+    setTimeout(function() {
+      test.equal(log, [1, 8, 2]);
+      done = true;
+      setTimeout(next, 100);
+    }, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Triggers - global enter triggers with "except"', function (test, next) {
+  var rand = Random.id(), rand2 = Random.id();
+  var log = [];
+  var done = false;
+
+  FlowRouter.route('/' + rand, {
+    action: function(_params) {
+      log.push(1);
+    }
+  });
+
+  FlowRouter.route('/' + rand2, {
+    name: 'foo',
+    action: function(_params) {
+      log.push(2);
+    }
+  });
+
+  FlowRouter.triggers.enter([function(context) {
+    if(done) return;
+    test.equal(context.path, '/' + rand);
+    log.push(8);
+  }], {except: ['foo']});
+
+  FlowRouter.go('/' + rand);
+
+  setTimeout(function() {
+    FlowRouter.go('/' + rand2);
+
+    setTimeout(function() {
+      test.equal(log, [8, 1, 2]);
+      done = true;
+      setTimeout(next, 100);
+    }, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Triggers - global exit triggers', function (test, next) {
+  var rand = Random.id(), rand2 = Random.id();
+  var log = [];
+  var done =false;
+
+  FlowRouter.route('/' + rand, {
+    action: function(_params) {
+      log.push(1);
+    }
+  });
+
+  FlowRouter.route('/' + rand2, {
+    action: function(_params) {
+      log.push(2);
+    }
+  });
+
+  FlowRouter.go('/' + rand);
+
+  FlowRouter.triggers.exit([function(context) {
+    if(done) return;
+    test.equal(context.path, '/' + rand);
+    log.push(0);
+  }]);
+
+  setTimeout(function() {
+    FlowRouter.go('/' + rand2);
+
+    setTimeout(function() {
+      test.equal(log, [1, 0, 2]);
+      done = true;
+      setTimeout(next, 100);
+    }, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Triggers - global exit triggers with "only"', function (test, next) {
+  var rand = Random.id(), rand2 = Random.id();
+  var log = [];
+  var done = false;
+
+  FlowRouter.route('/' + rand, {
+    action: function(_params) {
+      log.push(1);
+    }
+  });
+
+  FlowRouter.route('/' + rand2, {
+    name: 'foo',
+    action: function(_params) {
+      log.push(2);
+    }
+  });
+
+  FlowRouter.triggers.exit([function(context) {
+    if(done) return;
+    test.equal(context.path, '/' + rand2);
+    log.push(8);
+  }], {only: ['foo']});
+
+  FlowRouter.go('/' + rand);
+
+  setTimeout(function() {
+    FlowRouter.go('/' + rand2);
+
+    setTimeout(function() {
+      FlowRouter.go('/' + rand);
+
+      setTimeout(function() {
+        test.equal(log, [1, 2, 8, 1]);
+        done = true;
+        setTimeout(next, 100);
+      }, 100);
+    }, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Triggers - global exit triggers with "except"', function (test, next) {
+  var rand = Random.id(), rand2 = Random.id();
+  var log = [];
+  var done = false;
+
+  FlowRouter.route('/' + rand, {
+    action: function(_params) {
+      log.push(1);
+    }
+  });
+
+  FlowRouter.route('/' + rand2, {
+    name: 'foo',
+    action: function(_params) {
+      log.push(2);
+    }
+  });
+
+  FlowRouter.go('/' + rand);
+
+  FlowRouter.triggers.exit([function(context) {
+    if(done) return;
+    test.equal(context.path, '/' + rand);
+    log.push(9);
+  }], {except: ['foo']});
+
+
+  setTimeout(function() {
+    FlowRouter.go('/' + rand2);
+
+    setTimeout(function() {
+      FlowRouter.go('/' + rand);
+
+      setTimeout(function() {
+        test.equal(log, [1, 9, 2, 1]);
+        done = true;
+        setTimeout(next, 100);
+      }, 100);
+    }, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Triggers - route enter triggers', function (test, next) {
+  var rand = Random.id();
+  var log = [];
+
+  var triggerFn = function (context) {
+    test.equal(context.path, '/' + rand);
+    log.push(5);
+  };
+
+  FlowRouter.route('/' + rand, {
+    triggersEnter: [triggerFn],
+    action: function(_params) {
+      log.push(1);
+    }
+  });
+
+  FlowRouter.go('/' + rand);
+
+  setTimeout(function() {
+    test.equal(log, [5, 1]);
+    setTimeout(next, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Triggers - router exit triggers', function (test, next) {
+  var rand = Random.id();
+  var log = [];
+
+  var triggerFn = function (context) {
+    test.equal(context.path, '/' + rand);
+    log.push(6);
+  };
+
+  FlowRouter.route('/' + rand, {
+    triggersExit: [triggerFn],
+    action: function(_params) {
+      log.push(1);
+    }
+  });
+
+  FlowRouter.go('/' + rand);
+
+  setTimeout(function() {
+    FlowRouter.go('/' + Random.id());
+
+    setTimeout(function() {
+      test.equal(log, [1, 6]);
+      setTimeout(next, 100);
+    }, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Triggers - group enter triggers', function (test, next) {
+  var rand = Random.id(), rand2 = Random.id();
+  var log = [];
+  var paths = ['/' + rand2, '/' + rand];
+
+  var triggerFn = function (context) {
+    test.equal(context.path, paths.pop());
+    log.push(3);
+  };
+
+  var group = FlowRouter.group({
+    triggersEnter: [triggerFn]
+  });
+
+  group.route('/' + rand, {
+    action: function(_params) {
+      log.push(1);
+    }
+  });
+
+  group.route('/' + rand2, {
+    action: function(_params) {
+      log.push(2);
+    }
+  });
+
+  FlowRouter.go('/' + rand);
+
+  setTimeout(function() {
+    FlowRouter.go('/' + rand2);
+
+    setTimeout(function() {
+      test.equal(log, [3, 1, 3, 2]);
+      setTimeout(next, 100);
+    }, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Triggers - group exit triggers', function (test, next) {
+  var rand = Random.id(), rand2 = Random.id();
+  var log = [];
+
+  var triggerFn = function (context) {
+    log.push(4);
+  };
+
+  var group = FlowRouter.group({
+    triggersExit: [triggerFn]
+  });
+
+  group.route('/' + rand, {
+    action: function(_params) {
+      log.push(1);
+    }
+  });
+
+  group.route('/' + rand2, {
+    action: function(_params) {
+      log.push(2);
+    }
+  });
+
+  FlowRouter.go('/' + rand);
+
+  setTimeout(function() {
+    FlowRouter.go('/' + rand2);
+
+    setTimeout(function() {
+      test.equal(log, [1, 4, 2]);
+      setTimeout(next, 100);
+    }, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Triggers - redirect from enter', function(test, next) {
+  var rand = Random.id(), rand2 = Random.id();
+  var log = [];
+
+  FlowRouter.route('/' + rand, {
+    triggersEnter: [function(context, redirect) {
+      redirect("/" + rand2);
+    }, function() {
+      throw new Error("should not execute this trigger");
+    }],
+    action: function(_params) {
+      log.push(1);
+    },
+    name: rand
+  });
+
+  FlowRouter.route('/' + rand2, {
+    action: function(_params) {
+      log.push(2);
+    },
+    name: rand2
+  });
+
+  FlowRouter.go('/');
+  FlowRouter.go('/' + rand);
+
+  setTimeout(function() {
+    test.equal(log, [2]);
+    next();
+  }, 300);
+});
+
+Tinytest.addAsync('Client - Triggers - redirect by routeName', function(test, next) {
+  var rand = Random.id(), rand2 = Random.id();
+  var log = [];
+
+  FlowRouter.route('/' + rand, {
+    name: rand,
+    triggersEnter: [function(context, redirect) {
+      redirect(rand2, null, {aa: "bb"});
+    }, function() {
+      throw new Error("should not execute this trigger");
+    }],
+    action: function(_params) {
+      log.push(1);
+    },
+    name: rand
+  });
+
+  FlowRouter.route('/' + rand2, {
+    name: rand2,
+    action: function(_params, queryParams) {
+      log.push(2);
+      test.equal(queryParams, {aa: "bb"});
+    },
+    name: rand2
+  });
+
+  FlowRouter.go('/');
+  FlowRouter.go('/' + rand);
+
+  setTimeout(function() {
+    test.equal(log, [2]);
+    next();
+  }, 300);
+});
+
+Tinytest.addAsync('Client - Triggers - redirect from exit', function(test, next) {
+  var rand = Random.id(), rand2 = Random.id(), rand3 = Random.id();
+  var log = [];
+
+  FlowRouter.route('/' + rand, {
+    action: function() {
+      log.push(1);
+    },
+    triggersExit: [
+      function(context, redirect) {
+        redirect('/' + rand3);
+      },
+      function() {
+        throw new Error("should not call this trigger");
+      }
+    ]
+  });
+
+  FlowRouter.route('/' + rand2, {
+    action: function() {
+      log.push(2);
+    }
+  });
+
+  FlowRouter.route('/' + rand3, {
+    action: function() {
+      log.push(3);
+    }
+  });
+
+  FlowRouter.go('/' + rand);
+
+  setTimeout(function() {
+    FlowRouter.go('/' + rand2);
+    
+    setTimeout(function() {
+      test.equal(log, [1, 3]);
+      next();
+    }, 100);
+  }, 100);
+});
+
+Tinytest.addAsync('Client - Triggers - redirect to external URL fails', function(test, next) {
+  var rand = Random.id(), rand2 = Random.id();
+  var log = [];
+
+  // testing "http://" URLs
+  FlowRouter.route('/' + rand, {
+    triggersEnter: [function(context, redirect) {
+      test.throws(function() {
+          redirect("http://example.com/")
+      }, "Redirects to URLs outside of the app are not supported")
+    }],
+    action: function(_params) {
+      log.push(1);
+    },
+    name: rand
+  });
+
+  // testing "https://" URLs
+  FlowRouter.route('/' + rand2, {
+    triggersEnter: [function(context, redirect) {
+      test.throws(function() {
+          redirect("https://example.com/")
+      })
+    }],
+    action: function(_params) {
+      log.push(2);
+    },
+    name: rand2
+  });
+
+  FlowRouter.go('/');
+  FlowRouter.go('/' + rand);
+  FlowRouter.go('/' + rand2);
+
+  setTimeout(function() {
+    test.equal(log, []);
+    next();
+  }, 300);
+});
+
+Tinytest.addAsync('Client - Triggers - stop callback from enter', function(test, next) {
+  var rand = Random.id();
+  var log = [];
+
+  FlowRouter.route('/' + rand, {
+    triggersEnter: [function(context, redirect, stop) {
+      log.push(10);
+      stop();
+    }, function() {
+      throw new Error("should not execute this trigger");
+    }],
+    action: function(_params) {
+      throw new Error("should not execute the action");
+    }
+  });
+
+  FlowRouter.go('/');
+  FlowRouter.go('/' + rand);
+
+  setTimeout(function() {
+    test.equal(log, [10]);
+    next();
+  }, 100);
+});
+
+Tinytest.addAsync(
+'Client - Triggers - invalidate inside an autorun', 
+function(test, next) {
+  var rand = Random.id(), rand2 = Random.id();
+  var log = [];
+  var paths = ['/' + rand2, '/' + rand];
+  var done = false;
+
+  FlowRouter.route('/' + rand, {
+    action: function(_params) {
+      log.push(1);
+    }
+  });
+
+  FlowRouter.route('/' + rand2, {
+    action: function(_params) {
+      log.push(2);
+    }
+  });
+
+  FlowRouter.triggers.enter([function(context) {
+    if(done) return;
+    test.equal(context.path, paths.pop());
+    log.push(0);
+  }]);
+
+  Tracker.autorun(function(c) {
+    FlowRouter.go('/' + rand);
+  });
+
+  setTimeout(function() {
+    FlowRouter.go('/' + rand2);
+
+    setTimeout(function() {
+      test.equal(log, [0, 1, 0, 2]);
+      done = true;
+      setTimeout(next, 100);
+    }, 100);
+  }, 100);
+});

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

@@ -0,0 +1,297 @@
+Tinytest.addAsync(
+'Triggers - runTriggers - run all and after',
+function(test, done) {
+  var store = [];
+  var triggers = MakeTriggers(2, store);
+  Triggers.runTriggers(triggers, null, null, function() {
+    test.equal(store, [0, 1]);
+    done();
+  });
+});
+
+Tinytest.addAsync(
+'Triggers - runTriggers - redirect with url',
+function(test, done) {
+  var store = [];
+  var url = "http://google.com";
+  var triggers = MakeTriggers(2, store);
+  triggers.splice(1, 0, function(context, redirect) {
+    redirect(url); 
+  });
+
+  Triggers.runTriggers(triggers, null, function(u) {
+    test.equal(store, [0]);
+    test.equal(u, url);
+    done();
+  }, null);
+});
+
+Tinytest.addAsync(
+'Triggers - runTriggers - redirect without url',
+function(test, done) {
+  var store = [];
+  var url = "http://google.com";
+  var triggers = MakeTriggers(2, store);
+  triggers.splice(1, 0, function(context, redirect) {
+    try {
+      redirect(); 
+    } catch(ex) {
+      test.isTrue(/requires an URL/.test(ex.message));
+      test.equal(store, [0]);
+      done();
+    }
+  });
+
+  Triggers.runTriggers(triggers, null, null, null);
+});
+
+Tinytest.addAsync(
+'Triggers - runTriggers - redirect in a different event loop',
+function(test, done) {
+  var store = [];
+  var url = "http://google.com";
+  var triggers = MakeTriggers(2, store);
+  var doneCalled = false;
+
+  triggers.splice(1, 0, function(context, redirect) {
+    setTimeout(function() {
+      try {
+        redirect(url); 
+      } catch(ex) {
+        test.isTrue(/sync/.test(ex.message));
+        test.equal(store, [0, 1]);
+        test.isTrue(doneCalled);
+        done();
+      }
+    }, 0);
+  });
+
+  Triggers.runTriggers(triggers, null, null, function() {
+    doneCalled = true;
+  });
+});
+
+Tinytest.addAsync(
+'Triggers - runTriggers - redirect called multiple times',
+function(test, done) {
+  var store = [];
+  var url = "http://google.com";
+  var triggers = MakeTriggers(2, store);
+  var redirectCalled = false;
+
+  triggers.splice(1, 0, function(context, redirect) {
+    redirect(url); 
+    try {
+      redirect(url);
+    } catch(ex) {
+      test.isTrue(/already redirected/.test(ex.message));
+      test.equal(store, [0]);
+      test.isTrue(redirectCalled);
+      done();
+    }
+  });
+
+  Triggers.runTriggers(triggers, null, function() {
+    redirectCalled = true;
+  }, null);
+});
+
+Tinytest.addAsync(
+'Triggers - runTriggers - stop callback',
+function(test, done) {
+  var store = [];
+  var triggers = MakeTriggers(2, store);
+  triggers.splice(1, 0, function(context, redirect, stop) {
+    stop();
+  });
+
+  Triggers.runTriggers(triggers, null, null, function() {
+    store.push(2);
+  });
+
+  test.equal(store, [0]);
+  done();
+});
+
+
+Tinytest.addAsync(
+'Triggers - runTriggers - get context',
+function(test, done) {
+  var context = {};
+  var trigger = function(c) {
+    test.equal(c, context);
+    done();
+  };
+
+  Triggers.runTriggers([trigger], context, function() {}, function() {});
+});
+
+Tinytest.addAsync(
+'Triggers - createRouteBoundTriggers - matching trigger',
+function(test, done) {
+  var context = {route: {name: "abc"}};
+  var redirect = function() {};
+
+  var trigger = function(c, r) {
+    test.equal(c, context);
+    test.equal(r, redirect);
+    done();
+  };
+
+  var triggers = Triggers.createRouteBoundTriggers([trigger], ["abc"]);
+  triggers[0](context, redirect);
+});
+
+Tinytest.addAsync(
+'Triggers - createRouteBoundTriggers - multiple matching triggers',
+function(test, done) {
+  var context = {route: {name: "abc"}};
+  var redirect = function() {};
+  var doneCount = 0;
+
+  var trigger = function(c, r) {
+    test.equal(c, context);
+    test.equal(r, redirect);
+    doneCount++;
+  };
+
+  var triggers = Triggers.createRouteBoundTriggers([trigger, trigger], ["abc"]);
+  triggers[0](context, redirect);
+  triggers[1](context, redirect);
+
+  test.equal(doneCount, 2);
+  done();
+});
+
+Tinytest.addAsync(
+'Triggers - createRouteBoundTriggers - no matching trigger',
+function(test, done) {
+  var context = {route: {name: "some-other-route"}};
+  var redirect = function() {};
+  var doneCount = 0;
+
+  var trigger = function(c, r) {
+    test.equal(c, context);
+    test.equal(r, redirect);
+    doneCount++;
+  };
+
+  var triggers = Triggers.createRouteBoundTriggers([trigger], ["abc"]);
+  triggers[0](context, redirect);
+
+  test.equal(doneCount, 0);
+  done();
+});
+
+Tinytest.addAsync(
+'Triggers - createRouteBoundTriggers - negate logic',
+function(test, done) {
+  var context = {route: {name: "some-other-route"}};
+  var redirect = function() {};
+  var doneCount = 0;
+
+  var trigger = function(c, r) {
+    test.equal(c, context);
+    test.equal(r, redirect);
+    doneCount++;
+  };
+
+  var triggers = Triggers.createRouteBoundTriggers([trigger], ["abc"], true);
+  triggers[0](context, redirect);
+
+  test.equal(doneCount, 1);
+  done();
+});
+
+Tinytest.addAsync(
+'Triggers - applyFilters - no filters',
+function(test, done) {
+  var original = [];
+  test.equal(Triggers.applyFilters(original), original);
+  done();
+});
+
+Tinytest.addAsync(
+'Triggers - applyFilters - single trigger to array',
+function(test, done) {
+  var original = function() {};
+  test.equal(Triggers.applyFilters(original)[0], original);
+  done();
+});
+
+Tinytest.addAsync(
+'Triggers - applyFilters - only and except both',
+function(test, done) {
+  var original = [];
+  try {
+    Triggers.applyFilters(original, {only: [], except: []});
+  } catch(ex) {
+    test.isTrue(/only and except/.test(ex.message));
+    done();
+  }
+});
+
+Tinytest.addAsync(
+'Triggers - applyFilters - only is not an array',
+function(test, done) {
+  var original = [];
+  try {
+    Triggers.applyFilters(original, {only: "name"});
+  } catch(ex) {
+    test.isTrue(/to be an array/.test(ex.message));
+    done();
+  }
+});
+
+Tinytest.addAsync(
+'Triggers - applyFilters - except is not an array',
+function(test, done) {
+  var original = [];
+  try {
+    Triggers.applyFilters(original, {except: "name"});
+  } catch(ex) {
+    test.isTrue(/to be an array/.test(ex.message));
+    done();
+  }
+});
+
+Tinytest.addAsync(
+'Triggers - applyFilters - unsupported filter',
+function(test, done) {
+  var original = [];
+  try {
+    Triggers.applyFilters(original, {wowFilter: []});
+  } catch(ex) {
+    test.isTrue(/not supported/.test(ex.message));
+    done();
+  }
+});
+
+Tinytest.addAsync(
+'Triggers - applyFilters - just only filter',
+function(test, done) {
+  var bounded = Triggers.applyFilters(done, {only: ["abc"]});
+  bounded[0]({route: {name: "abc"}});
+});
+
+Tinytest.addAsync(
+'Triggers - applyFilters - just except filter',
+function(test, done) {
+  var bounded = Triggers.applyFilters(done, {except: ["abc"]});
+  bounded[0]({route: {name: "some-other"}});
+});
+
+function MakeTriggers(count, store) {
+  var triggers = [];
+
+  function addTrigger(no) {
+    triggers.push(function() {
+      store.push(no);
+    });
+  }
+
+  for(var lc=0; lc<count; lc++) {
+    addTrigger(lc);
+  }
+  return triggers;
+}

+ 48 - 0
packages/kadira-flow-router/test/common/fast_render_route.js

@@ -0,0 +1,48 @@
+FastRenderColl = new Mongo.Collection('fast-render-coll');
+
+FlowRouter.route('/the-fast-render-route', {
+  subscriptions: function() {
+    this.register('data', Meteor.subscribe('fast-render-data'));
+  }
+});
+
+FlowRouter.route('/the-fast-render-route-params/:id', {
+  subscriptions: function(params, queryParams) {
+    this.register('data', Meteor.subscribe('fast-render-data-params', params, queryParams));
+  }
+});
+
+FlowRouter.route('/no-fast-render', {
+  subscriptions: function() {
+    if(Meteor.isClient) {
+      this.register('data', Meteor.subscribe('fast-render-data'));
+    }
+  }
+});
+
+var frGroup = FlowRouter.group({
+  prefix: "/fr"
+});
+
+frGroup.route("/have-fr", {
+  subscriptions: function() {
+    this.register('data', Meteor.subscribe('fast-render-data'));
+  }
+});
+
+if(Meteor.isServer) {
+  if(!FastRenderColl.findOne()) {
+    FastRenderColl.insert({_id: "one", aa: 10});
+    FastRenderColl.insert({_id: "two", aa: 20});
+  }
+
+  Meteor.publish('fast-render-data', function() {
+    return FastRenderColl.find({}, {sort: {aa: -1}});
+  });
+
+  Meteor.publish('fast-render-data-params', function(params, queryParams) {
+    var fields = {params: params, queryParams: queryParams};
+    this.added('fast-render-coll', 'one', fields);
+    this.ready();
+  });
+}

+ 16 - 0
packages/kadira-flow-router/test/common/group.spec.js

@@ -0,0 +1,16 @@
+Tinytest.add('Common - Group - expose group options', function (test) {
+  var pathDef = "/" + Random.id();
+  var name = Random.id();
+  var data = {aa: 10};
+  var layout = 'blah';
+
+  var group = FlowRouter.group({
+    name: name,
+    prefix: '/admin',
+    layout: layout,
+    someData: data
+  });
+
+  test.equal(group.options.someData, data);
+  test.equal(group.options.layout, layout);
+});

+ 15 - 0
packages/kadira-flow-router/test/common/route.spec.js

@@ -0,0 +1,15 @@
+Router = FlowRouter.Router;
+
+Tinytest.addAsync('Common - Route - expose route options', function (test, next) {
+  var pathDef = "/" + Random.id();
+  var name = Random.id();
+  var data = {aa: 10};
+  
+  FlowRouter.route(pathDef, {
+    name: name,
+    someData: data
+  });
+
+  test.equal(FlowRouter._routesMap[name].options.someData, data);
+  next();
+});

+ 30 - 0
packages/kadira-flow-router/test/common/router.addons.spec.js

@@ -0,0 +1,30 @@
+Router = FlowRouter.Router;
+
+Tinytest.addAsync('Common - Addons - onRouteRegister basic usage', function (test, done) {
+  var name = Random.id();
+  var customField = Random.id();
+  var pathDef = '/' + name;
+  
+  FlowRouter.onRouteRegister(function(route) {
+    test.equal(route, {
+      pathDef: pathDef,
+
+      // Route.path is deprecated and will be removed in 3.0
+      path: pathDef,
+
+      name: name,
+      options: {customField: customField}
+    });  
+    FlowRouter._onRouteCallbacks = [];
+    done();
+  });
+
+  FlowRouter.route(pathDef, {
+    name: name,
+    action: function() {},
+    subscriptions: function() {},
+    triggersEnter: function() {},
+    triggersExit: function() {},
+    customField: customField
+  });
+});

+ 135 - 0
packages/kadira-flow-router/test/common/router.path.spec.js

@@ -0,0 +1,135 @@
+Router = FlowRouter.Router;
+
+Tinytest.addAsync('Common - Router - validate path definition', function (test, next) {
+  // path must start with '/'
+  try {
+    FlowRouter.route(Random.id());
+  } catch(ex) {
+    next();
+  }
+});
+
+Tinytest.add('Common - Router - path - generic', function (test) {
+  var pathDef = "/blog/:blogId/some/:name";
+  var fields = {
+    blogId: "1001",
+    name: "superb"
+  };
+  var expectedPath = "/blog/1001/some/superb";
+
+  var path = FlowRouter.path(pathDef, fields);
+  test.equal(path, expectedPath);
+});
+
+Tinytest.add('Common - Router - path - queryParams', function (test) {
+  var pathDef = "/blog/:blogId/some/:name";
+  var fields = {
+    blogId: "1001",
+    name: "superb"
+  };
+
+  var queryParams = {
+    aa: "100",
+    bb: "200"
+  };
+
+  var expectedPath = "/blog/1001/some/superb?aa=100&bb=200";
+
+  var path = FlowRouter.path(pathDef, fields, queryParams);
+  test.equal(path, expectedPath);
+});
+
+Tinytest.add('Common - Router - path - just queryParams', function (test) {
+  var pathDef = "/blog/abc";
+  var queryParams = {
+    aa: "100",
+    bb: "200"
+  };
+
+  var expectedPath = "/blog/abc?aa=100&bb=200";
+
+  var path = FlowRouter.path(pathDef, null, queryParams);
+  test.equal(path, expectedPath);
+});
+
+
+Tinytest.add('Common - Router - path - missing fields', function (test) {
+  var pathDef = "/blog/:blogId/some/:name";
+  var fields = {
+    blogId: "1001",
+  };
+  var expectedPath = "/blog/1001/some";
+
+  var path = FlowRouter.path(pathDef, fields);
+  test.equal(path, expectedPath);
+});
+
+Tinytest.add('Common - Router - path - no fields', function (test) {
+  var pathDef = "/blog/blogId/some/name";
+  var path = FlowRouter.path(pathDef);
+  test.equal(path, pathDef);
+});
+
+Tinytest.add('Common - Router - path - complex route', function (test) {
+  var pathDef = "/blog/:blogId/some/:name(\\d*)+";
+  var fields = {
+    blogId: "1001",
+    name: 20
+  };
+  var expectedPath = "/blog/1001/some/20";
+
+  var path = FlowRouter.path(pathDef, fields);
+  test.equal(path, expectedPath);
+});
+
+Tinytest.add('Common - Router - path - optional last param missing', function (test) {
+  var pathDef = "/blog/:blogId/some/:name?";
+  var fields = {
+    blogId: "1001"
+  };
+  var expectedPath = "/blog/1001/some";
+
+  var path = FlowRouter.path(pathDef, fields);
+  test.equal(path, expectedPath);
+});
+
+Tinytest.add('Common - Router - path - optional last param exists', function (test) {
+  var pathDef = "/blog/:blogId/some/:name?";
+  var fields = {
+    blogId: "1001",
+    name: 20
+  };
+  var expectedPath = "/blog/1001/some/20";
+
+  var path = FlowRouter.path(pathDef, fields);
+  test.equal(path, expectedPath);
+});
+
+Tinytest.add('Common - Router - path - remove trailing slashes', function (test) {
+  var pathDef = "/blog/:blogId/some/:name//";
+  var fields = {
+    blogId: "1001",
+    name: "superb"
+  };
+  var expectedPath = "/blog/1001/some/superb";
+
+  var path = FlowRouter.path(pathDef, fields);
+  test.equal(path, expectedPath);
+});
+
+Tinytest.add('Common - Router - path - handle multiple slashes', function (test) {
+  var pathDef = "/blog///some/hi////";
+  var expectedPath = "/blog/some/hi";
+
+  var path = FlowRouter.path(pathDef);
+  test.equal(path, expectedPath);
+});
+
+Tinytest.add('Common - Router - path - keep the root slash', function (test) {
+  var pathDef = "/";
+  var fields = {};
+  var expectedPath = "/";
+
+  var path = FlowRouter.path(pathDef, fields);
+  test.equal(path, expectedPath);
+});

+ 11 - 0
packages/kadira-flow-router/test/common/router.url.spec.js

@@ -0,0 +1,11 @@
+Tinytest.add('Common - Router - url - generic', function (test) {
+  var pathDef = "/blog/:blogId/some/:name";
+  var fields = {
+    blogId: "1001",
+    name: "superb"
+  };
+  var expectedUrl = Meteor.absoluteUrl('blog/1001/some/superb');
+
+  var path = FlowRouter.url(pathDef, fields);
+  test.equal(path, expectedUrl);
+});

+ 38 - 0
packages/kadira-flow-router/test/server/_helpers.js

@@ -0,0 +1,38 @@
+Meteor.publish('foo', function () {
+  this.ready();
+});
+
+Meteor.publish('fooNotReady', function () {
+});
+
+Meteor.publish('bar', function () {
+  this.ready();
+});
+
+// use this only to test global subs
+Meteor.publish('baz', function () {
+  this.ready();
+});
+
+Meteor.publish('bazNotReady', function () {
+});
+
+Meteor.publish('readyness', function (doIt) {
+  if(doIt) {
+    this.ready();
+  }
+});
+
+InjectData = Package['meteorhacks:inject-data'].InjectData;
+var urlResolve = Npm.require('url').resolve;
+GetFRData = function GetFRData(path) {
+  var url = urlResolve(process.env.ROOT_URL, path);
+  // FastRender only servers if there is a accept header with html in it
+  var options  = {
+    headers: {'accept': 'html'}
+  };
+  var res = HTTP.get(url, options);
+
+  var encodedData = res.content.match(/data">(.*)<\/script/)[1];
+  return InjectData._decode(encodedData)['fast-render-data'];
+}

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

@@ -0,0 +1,35 @@
+Tinytest.add('Server - Fast Render - fast render supported route', function (test) {
+  var expectedFastRenderCollData = [
+    [{_id: "two", aa: 20}, {_id: "one", aa: 10}]
+  ];
+
+  var data = GetFRData('/the-fast-render-route');
+  test.equal(data.collectionData['fast-render-coll'], expectedFastRenderCollData);
+});
+
+Tinytest.add('Server - Fast Render - fast render supported route with params', function (test) {
+  var expectedFastRenderCollData = [
+    [{
+      _id: "one", 
+      params: {id: 'the-id'},
+      queryParams: {aa: "20"}
+    }]
+  ];
+
+  var data = GetFRData('/the-fast-render-route-params/the-id?aa=20');
+  test.equal(data.collectionData['fast-render-coll'], expectedFastRenderCollData);
+});
+
+Tinytest.add('Server - Fast Render - no fast render supported route', function (test) {
+  var data = GetFRData('/no-fast-render');
+  test.equal(data.collectionData, {});
+});
+
+Tinytest.add('Server - Fast Render - with group routes', function (test) {
+  var expectedFastRenderCollData = [
+    [{_id: "two", aa: 20}, {_id: "one", aa: 10}]
+  ];
+
+  var data = GetFRData('/fr/have-fr');
+  test.equal(data.collectionData['fast-render-coll'], expectedFastRenderCollData);
+});

+ 1 - 0
packages/markdown/.gitignore

@@ -0,0 +1 @@
+.build*

+ 40 - 0
packages/markdown/README.md

@@ -0,0 +1,40 @@
+markdown
+========
+
+GitHub flavored markdown parser for Meteor based on marked.js newest version, updated by xet7.
+
+GFM tables and linebreaks are enabled by default.
+
+
+Usage
+-----
+
+Anywhere inside your template add markdown block and write markdown inside.
+
+Example:
+
+```
+{{#markdown}}
+
+...markdown text here...
+
+{{/markdown}}
+```
+
+That's it!
+
+
+Thanks to:
+----------
+
+- Christopher Jeffrey for <a href="https://github.com/chjj/marked" target="_blank">marked.js</a>
+
+- Bozhao Yu for original <a href="https://github.com/yubozhao/meteor-markdown" target="_blank">meteor-markdown</a> package (I just made this package compatible with Meteor 0.9+)
+
+- Bernhard Millauer - for contributions to this package
+
+- <a href="https://github.com/xet7">xet7</a> for updating to newest GFM package.
+
+License
+-------
+MIT

+ 9 - 0
packages/markdown/markdown.js

@@ -0,0 +1,9 @@
+var mark = marked;
+
+mark.setOptions({
+  gfm: true,
+  tables: true,
+  breaks: true
+});
+
+Markdown = mark;

+ 16 - 0
packages/markdown/marked/.editorconfig

@@ -0,0 +1,16 @@
+root = true
+
+[*.{json,js}]
+charset = utf-8
+end_of_line = lf
+insert_final_newline = true
+indent_style = space
+indent_size = 2
+
+[*.md, !test/*.md]
+charset = utf-8
+end_of_line = lf
+insert_final_newline = true
+trim_trailing_whitespace = true
+indent_style = tab
+indent_size = 4

+ 1 - 0
packages/markdown/marked/.eslintignore

@@ -0,0 +1 @@
+*.min.js

+ 29 - 0
packages/markdown/marked/.eslintrc.json

@@ -0,0 +1,29 @@
+{
+  "extends": "standard",
+  "plugins": [
+    "standard"
+  ],
+  "parserOptions": { "ecmaVersion": 5 },
+  "rules": {
+    "semi": ["error", "always"],
+    "indent": ["warn", 2, {
+      "VariableDeclarator": { "var": 2 },
+      "SwitchCase": 1,
+      "outerIIFEBody": 0
+    }],
+    "space-before-function-paren": "off",
+    "object-curly-spacing": "off",
+    "operator-linebreak": ["error", "before", { "overrides": { "=": "after" } }],
+    "no-cond-assign": "off",
+    "no-useless-escape": "off",
+    "no-return-assign": "off",
+    "one-var": "off",
+    "no-control-regex": "off"
+  },
+  "env": {
+    "node": true,
+    "browser": true,
+    "amd": true,
+    "jasmine": true
+  }
+}

+ 2 - 0
packages/markdown/marked/.gitattributes

@@ -0,0 +1,2 @@
+test/* linguist-vendored
+

+ 42 - 0
packages/markdown/marked/.github/ISSUE_TEMPLATE.md

@@ -0,0 +1,42 @@
+**Marked version:**
+
+**Markdown flavor:** Markdown.pl|CommonMark|GitHub Flavored Markdown|n/a
+
+<!-- The NPM version or commit hash having the issue --> 
+
+<!-- 
+
+	If submitting something other than a defect with Marked itself, please use the following:
+
+**Proposal type:** new feature | project operations | other
+
+## What pain point are you perceiving?
+
+## What solution are you suggesting?
+
+-->
+
+## Expectation
+
+**CommonMark Demo:** [demo](https://spec.commonmark.org/dingus/)
+<!-- You can replace the link above with a permalink from: https://spec.commonmark.org/dingus/ -->
+
+<!-- Describe the output you are expecting from marked -->
+
+## Result
+
+**Marked Demo:** [demo](https://marked.js.org/demo/)
+<!-- You can replace the link above with a permalink from: https://marked.js.org/demo/ -->
+
+<!-- Describe the output you received from marked -->
+
+## What was attempted
+
+<!-- Describe what code combination got you there -->
+
+<!-- 
+	If error is thrown add the following:
+
+## Call stack & console log
+
+-->

+ 27 - 0
packages/markdown/marked/.github/ISSUE_TEMPLATE/Bug_report.md

@@ -0,0 +1,27 @@
+---
+name: Bug report
+about: Marked says it does this thing but does not
+
+---
+
+**Describe the bug**
+A clear and concise description of what the bug is.
+
+**To Reproduce**
+Steps to reproduce the behavior:
+
+<!-- If possible, use the Marked Demo permalink and compare to the CommonMark Dingus permalink to demonstrate the bug -->
+<!--
+1. [Marked Demo](https://marked.js.org/demo/)
+2. [CommonMark Demo](https://spec.commonmark.org/dingus/)
+-->
+
+<!-- If you need a specific version and options to reproduce the bug, use the following template -->
+<!--
+1. Install marked `npm install --save marked@0.3.19` with the version you are using
+2. Run marked with input string and options such as `marked('hello *world*', {gfm: true})`
+3. Actual output (or error) is...
+-->
+
+**Expected behavior**
+A clear and concise description of what you expected to happen.

+ 14 - 0
packages/markdown/marked/.github/ISSUE_TEMPLATE/Feature_request.md

@@ -0,0 +1,14 @@
+---
+name: Feature request
+about: Marked doesn't do this thing and I think it should
+
+---
+
+**Describe the feature**
+A clear and concise description of what you would like.
+
+**Why is this feature necessary?**
+A clear and concise description of why.
+
+**Describe alternatives you've considered**
+A clear and concise description of any alternative solutions or features you've considered.

+ 11 - 0
packages/markdown/marked/.github/ISSUE_TEMPLATE/Proposal.md

@@ -0,0 +1,11 @@
+---
+name: Proposal
+about: Marked doesn't do this thing and I think it should
+ 
+---
+ 
+**What pain point are you perceiving?.**
+A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
+ 
+**Describe the solution you'd like**
+A clear and concise description of what you want to happen.

+ 53 - 0
packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE.md

@@ -0,0 +1,53 @@
+
+<!--
+
+	If release PR, add ?template=release.md to the PR url to use the release PR template.
+
+	If badging PR, add ?template=badges.md to the PR url to use the badges PR template.
+
+	Otherwise, you are stating this PR fixes an issue that has been submitted; or,
+	describes the issue or proposal under consideration and contains the project-related code to implement.
+
+-->
+
+**Marked version:**
+
+<!-- The NPM version or commit hash having the issue -->
+
+**Markdown flavor:** Markdown.pl|CommonMark|GitHub Flavored Markdown|n/a
+
+## Description
+
+- Fixes #### (if fixing a known issue; otherwise, describe issue using the following format)
+
+<!--
+
+	If no issue exists that you're aware of. The maintainers should be able to figure out if it's a duplicate.
+
+## Expectation
+
+Describe the output you are expecting from marked
+
+## Result
+
+Describe the output you received from marked
+
+## What was attempted
+
+Describe what code combination got you there
+
+-->
+
+## Contributor
+
+- [ ] Test(s) exist to ensure functionality and minimize regression (if no tests added, list tests covering this PR); or,
+- [ ] no tests required for this PR.
+- [ ] If submitting new feature, it has been documented in the appropriate places.
+
+## Committer
+
+In most cases, this should be a different person than the contributor.
+
+- [ ] Draft GitHub release notes have been updated.
+- [ ] CI is green (no forced merge required).
+- [ ] Merge PR

+ 50 - 0
packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE/badges.md

@@ -0,0 +1,50 @@
+**@mention the contributor:**
+
+## Recommendation to:
+
+- [ ] Change user group
+- [ ] Add a badge
+- [ ] Remove a badge
+
+<!-- 
+
+	Explain your reasoning behind tagging that person. 
+
+	Preferably by citing objective examples, like PRs, Issues, and so on.
+
+-->
+
+## As the one mentioned, I would like to:
+
+- [ ] accept the recommendation; or,
+- [ ] graciously decline; or,
+- [ ] dispute the recommendation
+
+within 30 days, if you have not indicated which option you are taking one of the following will happen:
+
+1. If adding a badge, we will assume you are graciously declining.
+2. If removing a badge, we will assume you do not want to dispute the recommendation; therefore, the badge will be removed.
+
+<!--
+
+	Why would someone not accept a badge? Loads of reasons depending on the circumstances.
+
+	1. If you're a committer and someone puts a badge for you on having decision making authority in an area, do you really a) think you earned it and b) think you can do that *and* all the other stuff you got going as a committer, admin, or publisher (not to even mention your outside life)? Maybe not. And that's okay. Thank them for the recognition, explain you aren't able to take more on at the moment. It's cool to get recognized though.
+	2. Maybe you don't feel you actually earned it yet. I remember being in an interview once. The interviewer asked me to give an example of going above and beyond the call of duty. I said, "That's hard. Because what you consider going above and beyond may be what I consider to be 'just rising to'. If we're in battle and you get wounded and I pull you out of the frey before heading back into it, I don't consider that going above and beyond; I consider that rising to."
+
+	Why would someone remove their own badge? Loads of reasons...
+
+	1. Maybe you got a lot going on right now and want to broadcast to the Marked community that, "Hey, I don't want to say I'm going to do this unless I can really commit to it right now in a way that serves the project well." That's awesome! That takes courage! Because a) saying "no" is hard for most humans ("people pleasers") and b) the alternative, well, for those of us here since about October of 2017 (and prior), we know what the alternative can look like.
+	2. Maybe you just think you've done all you can to help and learned all you can from the experience. Again, very awesome and courageous. It takes courage to know when to walk away on your own accord.
+
+	Why would you want to remove someone's badge? Loads of reasons...
+
+	1. Maybe they have decision making authority on something. You asked for their advice. And, you ended up waiting almost a month before receiving a response.
+	2. Maybe it was relevant at the time (Master of Marked, for example) but you think they've lost their former level of skill (fell out of practice, for example). They could always get it back.
+	3. Maybe to signal to them that, "Hey, you seem to have forgotten about us. Are you still around (or alive)?"
+
+	Anyway, you get the idea. This isn't about good or bad...it's just about giving the community a simple game mechanic by which to publicly say, "Thank you" or "Here's what my status is" in the community or "Hey, I think something's wrong here" in a civil manner.
+
+-->
+
+Note: All committers must approve via review before merging, the disapproving committer can simply close the PR.

+ 25 - 0
packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE/release.md

@@ -0,0 +1,25 @@
+## Publisher
+
+- [ ] `$ npm version` has been run.
+- [ ] Release notes in [draft GitHub release](https://github.com/markedjs/marked/releases) are up to date
+- [ ] Release notes include which flavors and versions of Markdown are supported by this release
+- [ ] Committer checklist is complete.
+- [ ] Merge PR.
+- [ ] Publish GitHub release using `master` with correct version number.
+- [ ] `$ npm publish` has been run.
+- [ ] Create draft GitHub release to prepare next release.
+
+Note: If merges to `master` occur after submitting this PR and before running `$ npm pubish` you should be able to
+
+1. pull from `upstream/master` (`git pull upstream master`) into the branch holding this version,
+2. run `$ npm run build` to regenerate the `min` file, and
+3. commit and push the updated changes.
+
+## Committer
+
+In most cases, this should be someone different than the publisher.
+
+- [ ] Version in `package.json` has been updated (see [PUBLISHING.md](https://github.com/markedjs/marked/blob/master/docs/PUBLISHING.md)).
+- [ ] The `marked.min.js` has been updated; or,
+- [ ] release does not change library.
+- [ ] CI is green (no forced merge required).

+ 3 - 0
packages/markdown/marked/.gitignore

@@ -0,0 +1,3 @@
+.DS_Store
+node_modules/
+test/compiled_tests

+ 46 - 0
packages/markdown/marked/.travis.yml

@@ -0,0 +1,46 @@
+language: node_js
+
+jobs:
+  fast_finish: true
+  allow_failures:
+    - stage: security scan 🔐
+
+  include:
+    - stage: unit tests 👩🏽‍💻
+      script: npm run test:unit
+      node_js: lts/*
+
+    - stage: spec tests 👩🏽‍💻
+      script: npm run test:specs
+      node_js: v4
+    - node_js: lts/*
+    - node_js: node
+
+    - stage: lint ✨
+      script: npm run test:lint
+      node_js: lts/*
+
+    - stage: minify 🗜️
+      script: |
+        npm run build
+        if ! git diff --quiet; then
+          git config --global user.email "travis@travis-ci.org"
+          git config --global user.name "Travis-CI"
+          git config credential.helper "store --file=.git/credentials"
+          echo "https://${GITHUB_TOKEN}:@github.com" > .git/credentials
+          git commit -am '🗜️ minify [skip ci]'
+          git push origin HEAD:${TRAVIS_BRANCH}
+        fi
+      node_js: lts/*
+      if: branch = master AND type = push
+
+    - stage: security scan 🔐
+      script: npm run test:redos
+      node_js: lts/*
+
+cache:
+  directories:
+    - node_modules
+
+git:
+  depth: 3

+ 43 - 0
packages/markdown/marked/LICENSE.md

@@ -0,0 +1,43 @@
+# License information
+
+## Contribution License Agreement
+
+If you contribute code to this project, you are implicitly allowing your code
+to be distributed under the MIT license. You are also implicitly verifying that
+all code is your original work. `</legalese>`
+
+## Marked
+
+Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/)
+
+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.
+
+## Markdown
+
+Copyright © 2004, John Gruber 
+http://daringfireball.net/ 
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.

+ 15 - 0
packages/markdown/marked/Makefile

@@ -0,0 +1,15 @@
+all:
+	@cp lib/marked.js marked.js
+	@uglifyjs --comments '/\*[^\0]+?Copyright[^\0]+?\*/' -o marked.min.js lib/marked.js
+
+clean:
+	@rm marked.js
+	@rm marked.min.js
+
+bench:
+	@node test --bench
+
+man/marked.1.txt:
+	groff -man -Tascii man/marked.1 | col -b > man/marked.1.txt
+
+.PHONY: clean all

+ 76 - 0
packages/markdown/marked/README.md

@@ -0,0 +1,76 @@
+<a href="https://marked.js.org">
+  <img width="60px" height="60px" src="https://marked.js.org/img/logo-black.svg" align="right" />
+</a>
+
+# Marked
+
+[![npm](https://badgen.net/npm/v/marked)](https://www.npmjs.com/package/marked)
+[![gzip size](https://badgen.net/badgesize/gzip/https://cdn.jsdelivr.net/npm/marked/marked.min.js)](https://cdn.jsdelivr.net/npm/marked/marked.min.js)
+[![install size](https://badgen.net/packagephobia/install/marked)](https://packagephobia.now.sh/result?p=marked)
+[![downloads](https://badgen.net/npm/dt/marked)](https://www.npmjs.com/package/marked)
+[![dep](https://badgen.net/david/dep/markedjs/marked?label=deps)](https://david-dm.org/markedjs/marked)
+[![dev dep](https://badgen.net/david/dev/markedjs/marked?label=devDeps)](https://david-dm.org/markedjs/marked?type=dev)
+[![travis](https://badgen.net/travis/markedjs/marked)](https://travis-ci.org/markedjs/marked)
+[![snyk](https://snyk.io/test/npm/marked/badge.svg)](https://snyk.io/test/npm/marked)
+
+- ⚡ built for speed
+- ⬇️ low-level compiler for parsing markdown without caching or blocking for long periods of time
+- ⚖️ light-weight while implementing all markdown features from the supported flavors & specifications
+- 🌐 works in a browser, on a server, or from a command line interface (CLI)
+
+## Demo
+
+Checkout the [demo page](https://marked.js.org/demo/) to see marked in action ⛹️
+
+## Docs
+
+Our [documentation pages](https://marked.js.org) are also rendered using marked 💯
+
+Also read about:
+
+* [Options](https://marked.js.org/#/USING_ADVANCED.md)
+* [Extensibility](https://marked.js.org/#/USING_PRO.md)
+
+## Installation
+
+**CLI:** `npm install -g marked`
+
+**In-browser:** `npm install marked`
+
+## Usage
+
+### Warning: 🚨 Marked does not [sanitize](https://marked.js.org/#/USING_ADVANCED.md#options) the output HTML by default 🚨
+
+**CLI**
+
+``` bash
+$ marked -o hello.html
+hello world
+^D
+$ cat hello.html
+<p>hello world</p>
+```
+
+**Browser**
+
+```html
+<!doctype html>
+<html>
+<head>
+  <meta charset="utf-8"/>
+  <title>Marked in the browser</title>
+</head>
+<body>
+  <div id="content"></div>
+  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
+  <script>
+    document.getElementById('content').innerHTML =
+      marked('# Marked in the browser\n\nRendered by **marked**.');
+  </script>
+</body>
+</html>
+```
+
+## License
+
+Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License)

+ 215 - 0
packages/markdown/marked/bin/marked

@@ -0,0 +1,215 @@
+#!/usr/bin/env node
+
+/**
+ * Marked CLI
+ * Copyright (c) 2011-2013, Christopher Jeffrey (MIT License)
+ */
+
+var fs = require('fs'),
+    path = require('path'),
+    marked = require('../');
+
+/**
+ * Man Page
+ */
+
+function help() {
+  var spawn = require('child_process').spawn;
+
+  var options = {
+    cwd: process.cwd(),
+    env: process.env,
+    setsid: false,
+    stdio: 'inherit'
+  };
+
+  spawn('man', [path.resolve(__dirname, '/../man/marked.1')], options)
+    .on('error', function() {
+      fs.readFile(path.resolve(__dirname, '/../man/marked.1.txt'), 'utf8', function(err, data) {
+        if (err) throw err;
+        console.log(data);
+      });
+    });
+}
+
+function version() {
+  var pkg = require('../package.json');
+  console.log(pkg.version);
+}
+
+/**
+ * Main
+ */
+
+function main(argv, callback) {
+  var files = [],
+      options = {},
+      input,
+      output,
+      string,
+      arg,
+      tokens,
+      opt;
+
+  function getarg() {
+    var arg = argv.shift();
+
+    if (arg.indexOf('--') === 0) {
+      // e.g. --opt
+      arg = arg.split('=');
+      if (arg.length > 1) {
+        // e.g. --opt=val
+        argv.unshift(arg.slice(1).join('='));
+      }
+      arg = arg[0];
+    } else if (arg[0] === '-') {
+      if (arg.length > 2) {
+        // e.g. -abc
+        argv = arg.substring(1).split('').map(function(ch) {
+          return '-' + ch;
+        }).concat(argv);
+        arg = argv.shift();
+      } else {
+        // e.g. -a
+      }
+    } else {
+      // e.g. foo
+    }
+
+    return arg;
+  }
+
+  while (argv.length) {
+    arg = getarg();
+    switch (arg) {
+      case '--test':
+        return require('../test').main(process.argv.slice());
+      case '-o':
+      case '--output':
+        output = argv.shift();
+        break;
+      case '-i':
+      case '--input':
+        input = argv.shift();
+        break;
+      case '-s':
+      case '--string':
+        string = argv.shift();
+        break;
+      case '-t':
+      case '--tokens':
+        tokens = true;
+        break;
+      case '-h':
+      case '--help':
+        return help();
+      case '-v':
+      case '--version':
+        return version();
+      default:
+        if (arg.indexOf('--') === 0) {
+          opt = camelize(arg.replace(/^--(no-)?/, ''));
+          if (!marked.defaults.hasOwnProperty(opt)) {
+            continue;
+          }
+          if (arg.indexOf('--no-') === 0) {
+            options[opt] = typeof marked.defaults[opt] !== 'boolean'
+              ? null
+              : false;
+          } else {
+            options[opt] = typeof marked.defaults[opt] !== 'boolean'
+              ? argv.shift()
+              : true;
+          }
+        } else {
+          files.push(arg);
+        }
+        break;
+    }
+  }
+
+  function getData(callback) {
+    if (!input) {
+      if (files.length <= 2) {
+        if (string) {
+          return callback(null, string);
+        }
+        return getStdin(callback);
+      }
+      input = files.pop();
+    }
+    return fs.readFile(input, 'utf8', callback);
+  }
+
+  return getData(function(err, data) {
+    if (err) return callback(err);
+
+    data = tokens
+      ? JSON.stringify(marked.lexer(data, options), null, 2)
+      : marked(data, options);
+
+    if (!output) {
+      process.stdout.write(data + '\n');
+      return callback();
+    }
+
+    return fs.writeFile(output, data, callback);
+  });
+}
+
+/**
+ * Helpers
+ */
+
+function getStdin(callback) {
+  var stdin = process.stdin,
+      buff = '';
+
+  stdin.setEncoding('utf8');
+
+  stdin.on('data', function(data) {
+    buff += data;
+  });
+
+  stdin.on('error', function(err) {
+    return callback(err);
+  });
+
+  stdin.on('end', function() {
+    return callback(null, buff);
+  });
+
+  try {
+    stdin.resume();
+  } catch (e) {
+    callback(e);
+  }
+}
+
+function camelize(text) {
+  return text.replace(/(\w)-(\w)/g, function(_, a, b) {
+    return a + b.toUpperCase();
+  });
+}
+
+function handleError(err) {
+  if (err.code === 'ENOENT') {
+    console.error(`marked: output to ${err.path}: No such directory`);
+    return process.exit(1);
+  }
+  throw err;
+}
+
+/**
+ * Expose / Entry Point
+ */
+
+if (!module.parent) {
+  process.title = 'marked';
+  main(process.argv.slice(), function(err, code) {
+    if (err) return handleError(err);
+    return process.exit(code || 0);
+  });
+} else {
+  module.exports = main;
+}

+ 23 - 0
packages/markdown/marked/bower.json

@@ -0,0 +1,23 @@
+{
+  "name": "marked",
+  "homepage": "https://github.com/markedjs/marked",
+  "authors": [
+    "Christopher Jeffrey <chjjeffrey@gmail.com>"
+  ],
+  "description": "A markdown parser built for speed",
+  "keywords": [
+    "markdown",
+    "markup",
+    "html"
+  ],
+  "main": "lib/marked.js",
+  "license": "MIT",
+  "ignore": [
+    "**/.*",
+    "node_modules",
+    "bower_components",
+    "app/bower_components",
+    "test",
+    "tests"
+  ]
+}

+ 10 - 0
packages/markdown/marked/component.json

@@ -0,0 +1,10 @@
+{
+  "name": "marked",
+  "version": "0.3.4",
+  "repo": "markedjs/marked",
+  "description": "A markdown parser built for speed",
+  "keywords": ["markdown", "markup", "html"],
+  "scripts": ["lib/marked.js"],
+  "main": "lib/marked.js",
+  "license": "MIT"
+}

+ 269 - 0
packages/markdown/marked/docs/AUTHORS.md

@@ -0,0 +1,269 @@
+# Authors
+
+Marked takes an encompassing approach to its community. As such, you can think of these as [concentric circles](https://medium.com/the-node-js-collection/healthy-open-source-967fa8be7951), where each group encompases the following groups.
+
+<table>
+  <tbody>
+  	<tr>
+      <td align="center" valign="top" style="width:32%">
+        <a href="https://github.com/chjj">
+          <img width="100" height="100" src="https://github.com/chjj.png?s=150">
+        </a>
+        <br>
+        <a href="https://github.com/chjj">Christopher Jeffrey</a>
+        <div>Original Author</div>
+        <small>Started the fire</small>
+      </td>
+      <td align="center" valign="top" style="width:32%">
+        <a href="https://github.com/joshbruce">
+          <img width="100" height="100" src="https://github.com/joshbruce.png?s=150">
+        </a>
+        <br>
+        <a href="https://joshbruce.com">Josh Bruce</a>
+        <div>Publisher</div>
+        <small>Release Wrangler; Humaning Helper; Heckler of Hypertext</small>
+      </td>
+      <td align="center" valign="top" style="width:32%">
+        <a href="https://github.com/styfle">
+          <img width="100" height="100" src="https://github.com/styfle.png?s=150">
+        </a>
+        <br>
+        <a href="https://www.ceriously.com">Steven</a>
+        <div>Publisher</div>
+        <small>Release Wrangler; Dr. Docs; Open source, of course; GitHub Guru; Humaning Helper</small>
+      </td>
+    </tr>
+  	<tr>
+      <td align="center" valign="top">
+        <a href="https://github.com/davisjam">
+          <img width="100" height="100" src="https://github.com/davisjam.png?s=150">
+        </a>
+        <br>
+        <a href="https://github.com/davisjam">Jamie Davis</a>
+        <div>Committer</div>
+        <small>Seeker of Security</small>
+      </td>
+      <td align="center" valign="top">
+        <a href="https://github.com/UziTech">
+          <img width="100" height="100" src="https://github.com/UziTech.png?s=150">
+        </a>
+        <br>
+        <a href="https://tony.brix.ninja">Tony Brix</a>
+        <div>Publisher</div>
+        <small>Release Wrangler; Titan of the test harness; Dr. DevOps</small>
+      </td>
+      <td align="center" valign="top">
+        &nbsp;
+      </td>
+    </tr>
+  </tbody>
+</table>
+
+<table>
+  <tbody>
+    <tr>
+      <td align="center" valign="top">
+        <a href="https://github.com/intcreator">
+          <img width="100" height="100" src="https://github.com/intcreator.png?s=150">
+        </a>
+        <br>
+        <a href="https://github.com/intcreator">Brandon der Blätter</a>
+        <div>Contributor</div>
+        <small>Curious Contributor</small>
+      </td>
+      <td align="center" valign="top">
+        <a href="https://github.com/carlosvalle">
+          <img width="100" height="100" src="https://github.com/carlosvalle.png?s=150">
+        </a>
+        <br>
+        <a href="https://github.com/carlosvalle">Carlos Valle</a>
+        <div>Contributor</div>
+        <small>Maker of the Marked mark from 2018 to present</small>
+      </td>
+      <td align="center" width="20%" valign="top">
+        <a href="https://github.com/Feder1co5oave">
+          <img width="100" height="100" src="https://github.com/Feder1co5oave.png?s=150">
+        </a>
+        <br>
+        <a href="https://github.com/Feder1co5oave">Federico Soave</a>
+        <div>Contributor</div>
+        <small>Regent of the Regex; Master of Marked</small>
+      </td>
+      <td align="center" valign="top">
+        <a href="https://github.com/karenyavine">
+          <img width="100" height="100" src="https://github.com/karenyavine.png?s=150">
+        </a>
+        <br>
+        <a href="https://github.com/karenyavine">Karen Yavine</a>
+        <div>Contributor</div>
+        <small>Snyk's Security Saint</small>
+      </td>
+     </tr>
+     <tr>
+      <td align="center" valign="top">
+        <a href="https://github.com/KostyaTretyak">
+          <img width="100" height="100" src="https://github.com/KostyaTretyak.png?s=150">
+        </a>
+        <br>
+        <a href="https://github.com/KostyaTretyak">Костя Третяк</a>
+        <div>Contributor</div>
+        <small></small>
+      </td>
+      <td align="center" width="20%" valign="top">
+        <a href="https://github.com/tomtheisen">
+          <img width="100" height="100" src="https://github.com/tomtheisen.png?s=150">
+        </a>
+        <br>
+        <a href="https://github.com/tomtheisen">Tom Theisen</a>
+        <div>Contributor</div>
+        <small>Defibrillator</small>
+      </td>
+      <td align="center" width="20%" valign="top">
+        <a href="https://github.com/mccraveiro">
+          <img width="100" height="100" src="https://github.com/mccraveiro.png?s=150">
+        </a>
+        <br>
+        <a href="https://github.com/mccraveiro">Mateus Craveiro</a>
+        <div>Contributor</div>
+        <small>Defibrillator</small>
+      </td>
+      <td align="center" width="20%" valign="top">
+      </td>
+     </tr>
+  </tbody>
+</table>
+
+## Publishers
+
+Publishers are admins who also have the responsibility, privilege, and burden of publishing the new releases to NPM and performing outreach and external stakeholder communications. Further, when things go pear-shaped, they're the ones taking most of the heat. Finally, when things go well, they're the primary ones praising the contributors who made it possible.
+
+(In other words, while Admins are focused primarily on the internal workings of the project, Publishers are focused on internal *and* external concerns.)
+
+**Should not exceed 2:** Having more people with the authority to publish a release can quickly turn into a consensus seeking nightmare (design by committee). Having only one is preferred (Directly Responsible Individual); however, given the nature of the project and its history, having an immediate fallback, and a potential deep fallback (Original author) is probably a good idea.
+
+[Details on badges](#badges)
+
+## Admins
+
+Admins are committers who also have the responsibility, privilege, and burden of selecting committers and making sure the project itself runs smoothly, which includes community maintenance, governance, dispute resolution, and so on. (Letting the contributors easily enter into, and work within, the project to begin contributing, with as little friction as possible.)
+
+**Should not exceed 3:** When there are too many people with the ability to resolve disputes, the dispute itself can quickly turn into a dispute amongst the admins themselves; therefore, we want this group to be small enough to commit to action and large enough to not put too much burden on one person. (Should ensure faster resolution and responsiveness.)
+
+To be listed: Admins are usually selected from the pool of committers (or they volunteer, using the same process) who demonstrate good understanding of the marked culture, operations, and do their best to help new contributors get up to speed on how to contribute effectively to the project.
+
+To be removed: You can remove yourself through the [GitHub UI](https://help.github.com/articles/removing-yourself-from-a-collaborator-s-repository/).
+
+[Details on badges](#badges)
+
+## Committers
+
+Committers are contributors who also have the responsibility, privilege, some might even say burden of being able to review and merge contributions (just usually not their own).
+
+A note on "decision making authority". This is related to submitting PRs and the [advice process](http://www.reinventingorganizationswiki.com/Decision_Making). The person marked as having decision making authority over a certain area should be sought for advice in that area before committing to a course of action.
+
+**Should not exceed 5:** For larger PRs affecting more of the codebase and, most likely, review by more people, we try to keep this pool small and responsive and let those with decision making authority have final say without negative repercussions from the other committers.
+
+To be listed: Committers are usually selected (or they volunteer, using the same process) from contributors who enter the discussions regarding the future direction of Marked (maybe even doing informal reviews of contributions despite not being able to merge them yourself).
+
+To be removed: You can remove yourself through the [GitHub UI](https://help.github.com/articles/removing-yourself-from-a-collaborator-s-repository/).
+
+A note on volunteering:
+
+1. Please do not volunteer unless you believe you can demonstrate to your peers you can do the work required.
+2. Please do not overcommit yourself; we count on those committed to the project to be responsive. Really consider, with all you have going on, wehther you able to really commit to it.
+3. Don't let the previous frighten you away, it can always be changed later by you or your peers.
+
+[Details on badges](#badges)
+
+## Contributors
+
+Contributors are users who submit a [PR](https://github.com/markedjs/marked/pulls), [Issue](https://github.com/markedjs/marked/issues), or collaborate in making Marked a better product and experience for all the users.
+
+To be listed: make a contribution and, if it has significant impact, the committers may be able to add you here.
+
+To be removed: please let us know or submit a PR.
+
+[Details on badges](#badges)
+
+## Users
+
+Users are anyone using Marked in some fashion, without them, there's no reason for us to exist.
+
+|Individual or Organization |Website                 |Project                              |Submitted by                                        |
+|:--------------------------|:-----------------------|:------------------------------------|:---------------------------------------------------|
+|MarkedJS                   |https://marked.js.org   |https://github.com/markedjs/marked   |The marked committers                               |
+
+To be listed: All fields are optional. Contact any of the committers or, more timely, submit a pull request with the following (using the first row as an example):
+
+- **Individual or Organization:** The name you would like associated with the record.
+- **Website:** A URL to a standalone website for the project.
+- **Project:** A URL for the repository of the project using marked.
+- **Submitted by:** The name and optional honorifics for the person adding the listing.
+
+To be removed: Same as above. Only instead of requesting addition request deletion or delete the row yourself.
+
+<h2 id="badges">Badges</h2>
+
+Badges? You don't *need* no stinkin' badges.
+
+Movie references aside. (It was either that or, "Let's play a game", but that would have been creepy&hellip;that's why it will most likely come later.)
+
+Badges? If you *want* 'em, we got 'em, and here's how you get 'em (and&hellip;dramatic pause&hellip;why not two dramatic pauses for emphasis?&hellip; how they can be taken away).
+
+- [ ] Add the appropriate badge to the desired contributor in the desired column of this page, even if they're not listed here yet.
+- [ ] Submit a PR (we're big on PRs around here, if you haven't noticed, help us help you).
+- [ ] Follow the instructions for submitting a badge PR. (There are more details to find within. Come on. Everybody likes surprises, right? No? Actually, we just try to put documentation where it belongs, closer to the code and part of the sequence of events.)
+
+### Badges at play:
+
+<dl>
+	<dt>Curious Contributor</dt>
+	<dd>A contributor with less than one year on this page who is actively engaged in submitting PRs, Issues, making recommendations, sharing thoughts&hellip;without being too annoying about it (let's be clear, submitting 100 Issues recommending the Marked Committers send everyone candy is trying for the badge, not honestly earning it).</dd>
+	<dt>Dr. DevOps</dt>
+	<dd>
+		<p>Someone who understands and contributes to improving the developer experience and flow of Marked into the world.</p>
+		<blockquote>
+			"The main characteristic of the DevOps movement is to strongly advocate automation and monitoring at all steps of software construction, from integration, testing, releasing to deployment and infrastructure management. DevOps aims at shorter development cycles, increased deployment frequency, more dependable releases, in close alignment with business objectives." ~ <a href="https://www.wikipedia.org/wiki/DevOps">Wikipedia</a>
+		</blockquote>
+	</dd>
+  <dt>Dr. Docs</dt>
+  <dd>Someone who has contributed a great deal to the creation and maintainance of the non-code areas of marked.</dd>
+	<dt>Eye for the CLI</dt>
+	<dd>At this point? Pretty much anyone who can update that `man` file to the current Marked version without regression in the CLI tool itself.</dd>
+	<dt>GitHub Guru</dt>
+	<dd>Someone who always seems to be able to tell you easier ways to do things with GitHub.</dd>
+	<dt>Humaning Helper</dt>
+	<dd>Someone who goes out of their way to help contributors feel welcomed and valued. Further, someone who takes the extra steps(s) necessary to help new contributors get up to speed. Finally, they maintain composure even in times of disagreement and dispute resolution.</dd>
+	<dt>Heckler of Hypertext</dt>
+	<dd>Someone who demonstrates an esoteric level of knowledge when it comes to HTML. In other words, someone who says things like, "Did you know most Markdown flavors don't have a way to render a description list (`dl`)? All the more reason Markdown `!==` HTML."</dd>
+	<dt>Markdown Maestro</dt>
+	<dd>You know that person who knows about way too many different flavors of Markdown? The one who maybe seems a little too obsessed with the possibilities of Markdown beyond HTML? Come on. You know who they are. Or, at least you could, if you give them this badge.</dd>
+	<dt>Master of Marked</dt>
+	<dd>Someone who demonstrates they know the ins and outs of the codebase for Marked.</dd>
+	<dt>Open source, of course</dt>
+	<dd>Someone who advocates for and has a proven understanding of how to operate within open source communities.</dd>
+	<dt>Regent of the Regex</dt>
+	<dd><p>Can you demonstrate you understand the following without Google and Stackoverflow?</p>
+		<p><code>/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/</code></p>
+		<p>Because this author can't yet. That's who gets these.</p>
+	</dd>
+	<dt>Seeker of Security</dt>
+	<dd>Someone who has demonstrated a high degree of expertise or authority when it comes to software security.</dd>
+	<dt>Titan of the Test Harness</dt>
+	<dd>Someone who demonstrates high-levels of understanding regarding Marked's test harness.</dd>
+	<dt>Totally Tron</dt>
+	<dd>Someone who demonstrates they are willing and able to "fight for the users", both developers dependent on marked to do their jobs as well as end-users interacting with the output (particularly in the realm of those with the disabilities).</dd>
+</dl>
+
+### Special badges that come with the job:
+
+<dl>
+	<dt>Defibrillator</dt>
+	<dd>A contributor who stepped up to help bring Marked back to life by contriuting solutions to help Marked pass when compared against the CommonMark and GitHub Flavored Markdown specifications.</dd>
+	<dt>Maker of the Marked mark</dt>
+	<dd>This badge is given to the person or oganization credited with creating the logo (or logotype) used in Marked communications for a given period of time. **Maker of the Marked mark from 2017 to present**, for example.</dd>
+	<dt>Release Wrangler</dt>
+	<dd>This is a badge given to all Publishers.</dd>
+	<dt>Snyk's Security Saint</dt>
+	<dd>This is a badge given to whomever primarily reaches out from Snyk to let us know about security issues.</dd>
+</dl>

+ 1 - 0
packages/markdown/marked/docs/CNAME

@@ -0,0 +1 @@
+marked.js.org

+ 74 - 0
packages/markdown/marked/docs/CODE_OF_CONDUCT.md

@@ -0,0 +1,74 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as
+contributors and maintainers pledge to making participation in our project and
+our community a harassment-free experience for everyone, regardless of age, body
+size, disability, ethnicity, gender identity and expression, level of experience,
+nationality, personal appearance, race, religion, or sexual identity and
+orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment
+include:
+
+* Using welcoming and inclusive language
+* Being respectful of differing viewpoints and experiences
+* Gracefully accepting constructive criticism
+* Focusing on what is best for the community
+* Showing empathy towards other community members
+
+Examples of unacceptable behavior by participants include:
+
+* The use of sexualized language or imagery and unwelcome sexual attention or
+advances
+* Trolling, insulting/derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or electronic
+  address, without explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+  professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable
+behavior and are expected to take appropriate and fair corrective action in
+response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or
+reject comments, commits, code, wiki edits, issues, and other contributions
+that are not aligned to this Code of Conduct, or to block temporarily or
+permanently any contributor for other behaviors that they deem inappropriate,
+threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies both within project spaces and in public spaces
+when an individual is representing the project or its community. Examples of
+representing a project or community include using an official project e-mail
+address, posting via an official social media account, or acting as an appointed
+representative at an online or offline event. Representation of a project may be
+further defined and clarified by project maintainers.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported by contacting the project team by submitting a PR with changes to the [AUTHORS](#/AUTHORS.md) page (or emailing josh@8fold.com). All
+complaints will be reviewed and investigated and will result in a response that
+is deemed necessary and appropriate to the circumstances. The project team is
+obligated to maintain confidentiality with regard to the reporter of an incident.
+Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good
+faith may face temporary or permanent repercussions as determined by other
+members of the project's leadership.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage],
+version [1.4][version].
+
+[homepage]: https://www.contributor-covenant.org/
+[version]: https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

+ 92 - 0
packages/markdown/marked/docs/CONTRIBUTING.md

@@ -0,0 +1,92 @@
+# Contributing to Marked
+
+- [ ] Fork `markedjs/marked`.
+- [ ] Clone the library locally using GitHub Desktop or the command line.
+- [ ] Make sure you are on the `master` branch.
+- [ ] Be sure to run `npm install` or `npm update`.
+- [ ] Create a branch.
+- [ ] Make as small a change as possible.
+- [ ] Run `npm test`, fix any broken things (for linting, you can run `npm run lint` to have the linter fix them for you).
+- [ ] Submit a PR.
+
+## Design principles
+
+Marked tends to favor following the SOLID set of software design and development principles; mainly the [single responsibility](https://en.wikipedia.org/wiki/Single_responsibility_principle) and [open/closed principles](https://en.wikipedia.org/wiki/Open/closed_principle):
+
+- **Single responsibility:** Marked, and the components of Marked, have the single responsibility of converting Markdown strings into HTML.
+- **Open/closed:** Marked favors giving developers the means to easily extend the library and its components over changing Marked's behavior through configuration options.
+
+## Priorities
+
+We think we have our priorities sorted to build quality in.
+
+The following table lists the ticket type labels we use when there is work to be done on the code either through an Issue or a PR; in priority order.
+
+|Ticket type label                  |Description                                                                                                                                                                         |
+|:----------------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+|L0 - security                      |A security vulnerability within the Marked library is discovered.                                                                                                                   |
+|L1 - broken                        |Valid usage results in incorrect output compared to [supported specifications](#/README.md#specifications) OR causes marked to crash AND there is no known workaround for the issue. |
+|L2 - annoying                      |Similar to L1 - broken only there is a known workaround available for the issue.                                                                                                   |
+|RR - refactor and re-engineer      |Results in an improvement to developers using Marked (improved readability) or end-users (faster performance) or both.                                                              |
+|NFS - new feature (spec related)   |A capability Marked does not currently provide but is in one of the [supported specifications](#/README.md#specifications)                                                           |
+|NFU - new feature (user requested) |A capability Marked does not currently provide but has been requested by users of Marked.                                                                                           |
+
+## Test early, often, and everything
+
+We try to write test cases to validate output (writing tests based on the [supported specifications](#/README.md#specifications)) and minimize regression (writing tests for issues fixed). Therefore, if you would like to contribute, some things you should know regarding the test harness.
+
+|Location      |Description                                         |
+|:-------------|:---------------------------------------------------|
+|/test/browser |For testing Marked in a client-side implementation. |
+|/test/new     |Tests not related to the original `markdown.pl`.    |
+|/test/original|Tests validating against the original `markdown.pl`.|
+
+If your test uses features or options, assuming `gfm` is set to `false`, for example, you can add [front-matter](https://www.npmjs.com/package/front-matter) to the top of
+your `.md` file
+
+``` yml
+---
+gfm: false
+---
+```
+
+## Submitting PRs and Issues
+
+Marked provides templates for submitting both pull requests and issues. When you begin creating a new PR or issue, you will see instructions on using the template.
+
+The PR templates include checklists for both the submitter and the reviewer, which, in most cases, will not be the same person.
+
+## Scripts
+
+When it comes to NPM commands, we try to use the native scripts provided by the NPM framework.
+
+To run the tests:
+
+``` bash
+npm test
+```
+
+To test whether you are using the standard syntax rules for the project:
+
+```bash
+npm run test:lint
+```
+
+To see time comparisons between Marked and other popular Markdown libraries:
+
+```bash
+npm run bench
+```
+
+To check for (and fix) standardized syntax (lint):
+
+```bash
+npm run lint
+```
+
+To build your own minified version of Marked:
+
+```bash
+npm run build
+```
+

+ 24 - 0
packages/markdown/marked/docs/PUBLISHING.md

@@ -0,0 +1,24 @@
+# Releasing Marked
+
+- [ ] See [contributing](#/CONTRIBUTING.md)
+- [ ] Create release branch from `master` (`release-x.y.z`)
+- [ ] Submit PR with minimal name: Release x.y.z
+- [ ] Complete PR checklists
+
+## Overall strategy
+
+**Master is always shippable:** We try to merge PRs in such a way that `master` is the only branch to really be concerned about *and* `master` can always be released. This allows smoother flow between new fetures, bug fixes, and so on. (Almost a continuous deployment setup, without automation.)
+
+## Versioning
+
+We follow [semantic versioning](https://semver.org) where the following sequence is true `[major].[minor].[patch]`; therefore, consider the following implications of the release you are preparing:
+
+1. **Major:** There is at least one change not deemed backward compatible.
+2. **Minor:** There is at least one new feature added to the release.
+3. **Patch:** No breaking changes, no new features.
+
+What to expect while Marked is a zero-major (0.x.y):
+
+1. The major will remain at zero; thereby, alerting consumers to the potentially volatile nature of the package.
+2. The minor will tend to be more analagous to a `major` release. 
+3. The patch will tend to be more analagous to a `minor` release or a collection of bug fixes (patches).

+ 85 - 0
packages/markdown/marked/docs/README.md

@@ -0,0 +1,85 @@
+Marked is
+
+1. built for speed.<sup>*</sup>
+2. a low-level markdown compiler for parsing markdown without caching or blocking for long periods of time.<sup>**</sup>
+3. light-weight while implementing all markdown features from the supported flavors & specifications.<sup>***</sup>
+4. available as a command line interface (CLI) and running in client- or server-side JavaScript projects.
+
+<p><small><sup>*</sup> Still working on metrics for comparative analysis and definition.</small><br>
+<small><sup>**</sup> As few dependencies as possible.</small><br>
+<small><sup>***</sup> Strict compliance could result in slower processing when running comparative benchmarking.</small></p>
+
+
+<h2 id="demo">Demo</h2>
+
+Checkout the [demo page](./demo/) to see marked in action ⛹️
+
+These documentation pages are also rendered using marked 💯
+
+
+<h2 id="installation">Installation</h2>
+
+**CLI:** `npm install -g marked`
+
+**In-browser:** `npm install marked`
+
+<h2 id="usage">Usage</h2>
+
+### Warning: 🚨 Marked does not [sanitize](https://marked.js.org/#/USING_ADVANCED.md#options) the output HTML by default 🚨
+
+**CLI**
+
+``` bash
+$ marked -o hello.html
+hello world
+^D
+$ cat hello.html
+<p>hello world</p>
+```
+
+``` bash
+$ marked -s "*hello world*"
+<p><em>hello world</em></p>
+```
+
+**Browser**
+
+```html
+<!doctype html>
+<html>
+<head>
+  <meta charset="utf-8"/>
+  <title>Marked in the browser</title>
+</head>
+<body>
+  <div id="content"></div>
+  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
+  <script>
+    document.getElementById('content').innerHTML =
+      marked('# Marked in browser\n\nRendered by **marked**.');
+  </script>
+</body>
+</html>
+```
+
+
+Marked offers [advanced configurations](#/USING_ADVANCED.md) and [extensibility](#/USING_PRO.md) as well.
+
+<h2 id="specifications">Supported Markdown specifications</h2>
+
+We actively support the features of the following [Markdown flavors](https://github.com/commonmark/CommonMark/wiki/Markdown-Flavors).
+
+|Flavor                                                     |Version    |
+|:----------------------------------------------------------|:----------|
+|The original markdown.pl                                   |--         |
+|[CommonMark](http://spec.commonmark.org/0.28/)             |0.28       |
+|[GitHub Flavored Markdown](https://github.github.com/gfm/) |0.28       |
+
+By supporting the above Markdown flavors, it's possible that Marked can help you use other flavors as well; however, these are not actively supported by the community.
+
+<h2 id="security">Security</h2>
+
+The only completely secure system is the one that doesn't exist in the first place. Having said that, we take the security of Marked very seriously.
+
+Therefore, please disclose potential security issues by email to the project [committers](#/AUTHORS.md) as well as the [listed owners within NPM](https://docs.npmjs.com/cli/owner). We will provide an initial assessment of security reports within 48 hours and should apply patches within 2 weeks (also, feel free to contribute a fix for the issue).
+

+ 78 - 0
packages/markdown/marked/docs/USING_ADVANCED.md

@@ -0,0 +1,78 @@
+## The `marked` function
+
+```js
+marked(markdownString [,options] [,callback])
+```
+
+|Argument              |Type         |Notes                                                                                                |
+|:---------------------|:------------|:----------------------------------------------------------------------------------------------------|
+|markdownString        |`string`     |String of markdown source to be compiled.                                                            |
+|<a href="#options">options</a>|`object`|Hash of options. Can also use `marked.setOptions`.                                                |
+|callback              |`function`   |Called when `markdownString` has been parsed. Can be used as second argument if no `options` present.|
+
+### Alternative using reference
+
+```js
+// Create reference instance
+var myMarked = require('marked');
+
+// Set options
+// `highlight` example uses `highlight.js`
+myMarked.setOptions({
+  renderer: new myMarked.Renderer(),
+  highlight: function(code) {
+    return require('highlight.js').highlightAuto(code).value;
+  },
+  pedantic: false,
+  gfm: true,
+  tables: true,
+  breaks: false,
+  sanitize: false,
+  smartLists: true,
+  smartypants: false,
+  xhtml: false
+});
+
+// Compile
+console.log(myMarked('I am using __markdown__.'));
+```
+
+<h2 id="options">Options</h2>
+
+|Member      |Type      |Default  |Since    |Notes         |
+|:-----------|:---------|:--------|:--------|:-------------|
+|baseUrl     |`string`  |`null`   |0.3.9    |A prefix url for any relative link. |  
+|breaks      |`boolean` |`false`  |v0.2.7   |If true, add `<br>` on a single line break (copies GitHub). Requires `gfm` be `true`.|
+|gfm         |`boolean` |`true`   |v0.2.1   |If true, use approved [GitHub Flavored Markdown (GFM) specification](https://github.github.com/gfm/).|
+|headerIds   |`boolean` |`true`   |v0.4.0   |If true, include an `id` attribute when emitting headings (h1, h2, h3, etc).|
+|headerPrefix|`string`  |`''`     |v0.3.0   |A string to prefix the `id` attribute when emitting headings (h1, h2, h3, etc).|
+|highlight   |`function`|`null`   |v0.3.0   |A function to highlight code blocks, see <a href="#highlight">Asynchronous highlighting</a>.|
+|langPrefix  |`string`  |`'language-'`|v0.3.0|A string to prefix the className in a `<code>` block. Useful for syntax highlighting.|
+|mangle      |`boolean` |`true`   |v0.3.4   |If true, autolinked email address is escaped with HTML character references.|
+|pedantic    |`boolean` |`false`  |v0.2.1   |If true, conform to the original `markdown.pl` as much as possible. Don't fix original markdown bugs or behavior. Turns off and overrides `gfm`.|
+|renderer    |`object`  |`new Renderer()`|v0.3.0|An object containing functions to render tokens to HTML. See [extensibility](USING_PRO.md) for more details.|
+|sanitize    |`boolean` |`false`  |v0.2.1   |If true, sanitize the HTML passed into `markdownString` with the `sanitizer` function.|
+|sanitizer   |`function`|`null`   |v0.3.4   |A function to sanitize the HTML passed into `markdownString`.|
+|silent      |`boolean` |`false`  |v0.2.7   |If true, the parser does not throw any exception.|
+|smartLists  |`boolean` |`false`  |v0.2.8   |If true, use smarter list behavior than those found in `markdown.pl`.|
+|smartypants |`boolean` |`false`  |v0.2.9   |If true, use "smart" typographic punctuation for things like quotes and dashes.|
+|tables      |`boolean` |`true`   |v0.2.7   |If true and `gfm` is true, use [GFM Tables extension](https://github.github.com/gfm/#tables-extension-).|
+|xhtml       |`boolean` |`false`  |v0.3.2   |If true, emit self-closing HTML tags for void elements (&lt;br/&gt;, &lt;img/&gt;, etc.) with a "/" as required by XHTML.|
+
+<h2 id="highlight">Asynchronous highlighting</h2>
+
+Unlike `highlight.js` the `pygmentize.js` library uses asynchronous highlighting. This example demonstrates that marked is agnostic when it comes to the highlighter you use.
+
+```js
+myMarked.setOptions({
+  highlight: function(code, lang, callback) {
+    require('pygmentize-bundled') ({ lang: lang, format: 'html' }, code, function (err, result) {
+      callback(err, result.toString());
+    });
+  }
+});
+
+console.log(myMarked(markdownString));
+```
+
+In both examples, `code` is a `string` representing the section of code to pass to the highlighter. In this example, `lang` is a `string` informing the highlighter what programming lnaguage to use for the `code` and `callback` is the `function` the asynchronous highlighter will call once complete.

+ 163 - 0
packages/markdown/marked/docs/USING_PRO.md

@@ -0,0 +1,163 @@
+## Extending Marked
+
+To champion the single-responsibility and open/closed prinicples, we have tried to make it relatively painless to extend marked. If you are looking to add custom functionality, this is the place to start.
+
+<h2 id="renderer">The renderer</h2>
+
+The renderer is...
+
+**Example:** Overriding default heading token by adding an embedded anchor tag like on GitHub.
+
+```js
+// Create reference instance
+var myMarked = require('marked');
+
+// Get reference
+var renderer = new myMarked.Renderer();
+
+// Override function
+renderer.heading = function (text, level) {
+  var escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
+
+  return `
+          <h${level}>
+            <a name="${escapedText}" class="anchor" href="#${escapedText}">
+              <span class="header-link"></span>
+            </a>
+            ${text}
+          </h${level}>`;
+};
+
+// Run marked
+console.log(myMarked('# heading+', { renderer: renderer }));
+```
+
+**Output:**
+
+```html
+<h1>
+  <a name="heading-" class="anchor" href="#heading-">
+    <span class="header-link"></span>
+  </a>
+  heading+
+</h1>
+```
+
+### Block level renderer methods
+
+- code(*string* code, *string* infostring, *boolean* escaped)
+- blockquote(*string* quote)
+- html(*string* html)
+- heading(*string* text, *number* level, *string* raw, *Slugger* slugger)
+- hr()
+- list(*string* body, *boolean* ordered, *number* start)
+- listitem(*string* text, *boolean* task, *boolean* checked)
+- checkbox(*boolean* checked)
+- paragraph(*string* text)
+- table(*string* header, *string* body)
+- tablerow(*string* content)
+- tablecell(*string* content, *object* flags)
+
+`slugger` has the `slug` method to create an unique id from value:
+
+```js
+slugger.slug('foo')   // foo
+slugger.slug('foo')   // foo-1
+slugger.slug('foo')   // foo-2
+slugger.slug('foo 1') // foo-1-1
+slugger.slug('foo-1') // foo-1-2
+...
+```
+
+`flags` has the following properties:
+
+```js
+{
+    header: true || false,
+    align: 'center' || 'left' || 'right'
+}
+```
+
+### Inline level renderer methods
+
+- strong(*string* text)
+- em(*string* text)
+- codespan(*string* code)
+- br()
+- del(*string* text)
+- link(*string* href, *string* title, *string* text)
+- image(*string* href, *string* title, *string* text)
+- text(*string* text)
+
+<h2 id="lexer">The lexer</h2>
+
+The lexer is...
+
+
+<h2 id="parser">The parser</h2>
+
+The parser is...
+
+***
+
+<h2 id="extend">Access to lexer and parser</h2>
+
+You also have direct access to the lexer and parser if you so desire.
+
+``` js
+var tokens = marked.lexer(text, options);
+console.log(marked.parser(tokens));
+```
+
+``` js
+var lexer = new marked.Lexer(options);
+var tokens = lexer.lex(text);
+console.log(tokens);
+console.log(lexer.rules);
+```
+
+``` bash
+$ node
+> require('marked').lexer('> i am using marked.')
+[ { type: 'blockquote_start' },
+  { type: 'paragraph',
+    text: 'i am using marked.' },
+  { type: 'blockquote_end' },
+  links: {} ]
+```
+
+The Lexers build an array of tokens, which will be passed to their respective
+Parsers. The Parsers process each token in the token arrays,
+which are removed from the array of tokens:
+
+``` js
+const marked = require('marked');
+
+const md = `
+  # heading
+
+  [link][1]
+
+  [1]: #heading "heading"
+`;
+
+const tokens = marked.lexer(md);
+console.log(tokens);
+
+const html = marked.parser(tokens);
+console.log(html);
+
+console.log(tokens);
+```
+
+``` bash
+[ { type: 'heading', depth: 1, text: 'heading' },
+  { type: 'paragraph', text: '  [link][1]' },
+  { type: 'space' },
+  links: { '1': { href: '#heading', title: 'heading' } } ]
+
+<h1 id="heading">heading</h1>
+<p>  <a href="#heading" title="heading">link</a></p>
+
+[ links: { '1': { href: '#heading', title: 'heading' } } ]
+```

+ 426 - 0
packages/markdown/marked/docs/broken.md

@@ -0,0 +1,426 @@
+# Markdown is broken
+
+I have a lot of scraps of markdown engine oddities that I've collected over the
+years. What you see below is slightly messy, but it's what I've managed to
+cobble together to illustrate the differences between markdown engines, and
+why, if there ever is a markdown specification, it has to be absolutely
+thorough. There are a lot more of these little differences I have documented
+elsewhere. I know I will find them lingering on my disk one day, but until
+then, I'll continue to add whatever strange nonsensical things I find.
+
+Some of these examples may only mention a particular engine compared to marked.
+However, the examples with markdown.pl could easily be swapped out for
+discount, upskirt, or markdown.js, and you would very easily see even more
+inconsistencies.
+
+A lot of this was written when I was very unsatisfied with the inconsistencies
+between markdown engines. Please excuse the frustration noticeable in my
+writing.
+
+## Examples of markdown's "stupid" list parsing
+
+```
+$ markdown.pl
+
+  * item1
+
+    * item2
+
+  text
+^D
+<ul>
+<li><p>item1</p>
+
+<ul>
+<li>item2</li>
+</ul>
+
+<p><p>text</p></li>
+</ul></p>
+```
+
+
+```
+$ marked
+  * item1
+
+    * item2
+
+  text
+^D
+<ul>
+<li><p>item1</p>
+<ul>
+<li>item2</li>
+</ul>
+<p>text</p>
+</li>
+</ul>
+```
+
+Which looks correct to you?
+
+- - -
+
+```
+$ markdown.pl
+* hello
+  > world
+^D
+<p><ul>
+<li>hello</p>
+
+<blockquote>
+  <p>world</li>
+</ul></p>
+</blockquote>
+```
+
+```
+$ marked
+* hello
+  > world
+^D
+<ul>
+<li>hello<blockquote>
+<p>world</p>
+</blockquote>
+</li>
+</ul>
+```
+
+Again, which looks correct to you?
+
+- - -
+
+EXAMPLE:
+
+```
+$ markdown.pl
+* hello
+  * world
+    * hi
+          code
+^D
+<ul>
+<li>hello
+<ul>
+<li>world</li>
+<li>hi
+  code</li>
+</ul></li>
+</ul>
+```
+
+The code isn't a code block even though it's after the bullet margin. I know,
+lets give it two more spaces, effectively making it 8 spaces past the bullet.
+
+```
+$ markdown.pl
+* hello
+  * world
+    * hi
+            code
+^D
+<ul>
+<li>hello
+<ul>
+<li>world</li>
+<li>hi
+    code</li>
+</ul></li>
+</ul>
+```
+
+And, it's still not a code block. Did you also notice that the 3rd item isn't
+even its own list? Markdown screws that up too because of its indentation
+unaware parsing.
+
+- - -
+
+Let's look at some more examples of markdown's list parsing:
+
+```
+$ markdown.pl
+
+  * item1
+
+    * item2
+
+  text
+^D
+<ul>
+<li><p>item1</p>
+
+<ul>
+<li>item2</li>
+</ul>
+
+<p><p>text</p></li>
+</ul></p>
+```
+
+Misnested tags.
+
+
+```
+$ marked
+  * item1
+
+    * item2
+
+  text
+^D
+<ul>
+<li><p>item1</p>
+<ul>
+<li>item2</li>
+</ul>
+<p>text</p>
+</li>
+</ul>
+```
+
+Which looks correct to you?
+
+- - -
+
+```
+$ markdown.pl
+* hello
+  > world
+^D
+<p><ul>
+<li>hello</p>
+
+<blockquote>
+  <p>world</li>
+</ul></p>
+</blockquote>
+```
+
+More misnested tags.
+
+
+```
+$ marked
+* hello
+  > world
+^D
+<ul>
+<li>hello<blockquote>
+<p>world</p>
+</blockquote>
+</li>
+</ul>
+```
+
+Again, which looks correct to you?
+
+- - -
+
+# Why quality matters - Part 2
+
+``` bash
+$ markdown.pl
+* hello
+  > world
+^D
+<p><ul>
+<li>hello</p>
+
+<blockquote>
+  <p>world</li>
+</ul></p>
+</blockquote>
+```
+
+``` bash
+$ sundown # upskirt
+* hello
+  > world
+^D
+<ul>
+<li>hello
+&gt; world</li>
+</ul>
+```
+
+``` bash
+$ marked
+* hello
+  > world
+^D
+<ul><li>hello <blockquote><p>world</p></blockquote></li></ul>
+```
+
+Which looks correct to you?
+
+- - -
+
+See: https://github.com/evilstreak/markdown-js/issues/23
+
+``` bash
+$ markdown.pl # upskirt/markdown.js/discount
+* hello
+      var a = 1;
+* world
+^D
+<ul>
+<li>hello
+var a = 1;</li>
+<li>world</li>
+</ul>
+```
+
+``` bash
+$ marked
+* hello
+      var a = 1;
+* world
+^D
+<ul><li>hello
+<pre>code>var a = 1;</code></pre></li>
+<li>world</li></ul>
+```
+
+Which looks more reasonable? Why shouldn't code blocks be able to appear in
+list items in a sane way?
+
+- - -
+
+``` bash
+$ markdown.js
+<div>hello</div>
+
+<span>hello</span>
+^D
+<p>&lt;div&gt;hello&lt;/div&gt;</p>
+
+<p>&lt;span&gt;hello&lt;/span&gt;</p>
+```
+
+``` bash
+$ marked
+<div>hello</div>
+
+<span>hello</span>
+^D
+<div>hello</div>
+
+
+<p><span>hello</span>
+</p>
+```
+
+- - -
+
+See: https://github.com/evilstreak/markdown-js/issues/27
+
+``` bash
+$ markdown.js
+[![an image](/image)](/link)
+^D
+<p><a href="/image)](/link">![an image</a></p>
+```
+
+``` bash
+$ marked
+[![an image](/image)](/link)
+^D
+<p><a href="/link"><img src="/image" alt="an image"></a>
+</p>
+```
+
+- - -
+
+See: https://github.com/evilstreak/markdown-js/issues/24
+
+``` bash
+$ markdown.js
+> a
+
+> b
+
+> c
+^D
+<blockquote><p>a</p><p>bundefined&gt; c</p></blockquote>
+```
+
+``` bash
+$ marked
+> a
+
+> b
+
+> c
+^D
+<blockquote><p>a
+
+</p></blockquote>
+<blockquote><p>b
+
+</p></blockquote>
+<blockquote><p>c
+</p></blockquote>
+```
+
+- - -
+
+``` bash
+$ markdown.pl
+* hello
+  * world
+    how
+
+    are
+    you
+
+  * today
+* hi
+^D
+<ul>
+<li><p>hello</p>
+
+<ul>
+<li>world
+how</li>
+</ul>
+
+<p>are
+you</p>
+
+<ul>
+<li>today</li>
+</ul></li>
+<li>hi</li>
+</ul>
+```
+
+``` bash
+$ marked
+* hello
+  * world
+    how
+
+    are
+    you
+
+  * today
+* hi
+^D
+<ul>
+<li><p>hello</p>
+<ul>
+<li><p>world
+how</p>
+<p>are
+you</p>
+</li>
+<li><p>today</p>
+</li>
+</ul>
+</li>
+<li>hi</li>
+</ul>
+```

+ 72 - 0
packages/markdown/marked/docs/demo/demo.css

@@ -0,0 +1,72 @@
+html, body {
+	margin: 0;
+	padding: 0;
+	font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+	color: #333;
+	background-color: #fbfbfb;
+	height: 100%;
+}
+
+textarea {
+	font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
+	font-size: 12px;
+	resize: none;
+}
+
+header {
+	padding-top: 10px;
+	display: flex;
+	height: 58px;
+}
+
+header h1 {
+	margin: 0;
+}
+
+.github-ribbon {
+	position: absolute;
+	top: 0;
+	right: 0;
+	border: 0;
+	z-index: 1000;
+}
+
+.containers {
+	display: flex;
+	height: calc(100vh - 68px);
+}
+
+.container {
+	flex-basis: 50%;
+	padding: 5px;
+	display: flex;
+	flex-direction: column;
+	height: 100%;
+	box-sizing: border-box;
+}
+
+.pane, .inputPane {
+	margin-top: 5px;
+	padding: 0.6em;
+	border: 1px solid #ccc;
+	overflow: auto;
+	flex-grow: 1;
+	flex-shrink: 1;
+}
+
+#preview {
+	display: flex;
+}
+
+#preview iframe {
+	flex-grow: 1;
+}
+
+#main {
+	display: none;
+}
+
+.error {
+	border-color: red;
+	background-color: #FEE
+}

+ 534 - 0
packages/markdown/marked/docs/demo/demo.js

@@ -0,0 +1,534 @@
+/* globals marked, unfetch, ES6Promise */
+
+if (!window.Promise) {
+  window.Promise = ES6Promise;
+}
+if (!window.fetch) {
+  window.fetch = unfetch;
+}
+
+onunhandledrejection = function (e) {
+  throw e.reason;
+};
+
+var $loadingElem = document.querySelector('#loading');
+var $mainElem = document.querySelector('#main');
+var $markdownElem = document.querySelector('#markdown');
+var $markedVerElem = document.querySelector('#markedVersion');
+var $commitVerElem = document.querySelector('#commitVersion');
+var $markedVer = document.querySelector('#markedCdn');
+var $optionsElem = document.querySelector('#options');
+var $outputTypeElem = document.querySelector('#outputType');
+var $inputTypeElem = document.querySelector('#inputType');
+var $responseTimeElem = document.querySelector('#responseTime');
+var $previewElem = document.querySelector('#preview');
+var $previewIframe = document.querySelector('#preview iframe');
+var $permalinkElem = document.querySelector('#permalink');
+var $clearElem = document.querySelector('#clear');
+var $htmlElem = document.querySelector('#html');
+var $lexerElem = document.querySelector('#lexer');
+var $panes = document.querySelectorAll('.pane');
+var $inputPanes = document.querySelectorAll('.inputPane');
+var lastInput = '';
+var inputDirty = true;
+var $activeOutputElem = null;
+var search = searchToObject();
+var markedVersions = {
+  master: 'https://cdn.jsdelivr.net/gh/markedjs/marked/lib/marked.js'
+};
+var markedVersionCache = {};
+var delayTime = 1;
+var checkChangeTimeout = null;
+var markedWorker;
+
+$previewIframe.addEventListener('load', handleIframeLoad);
+
+$outputTypeElem.addEventListener('change', handleOutputChange, false);
+
+$inputTypeElem.addEventListener('change', handleInputChange, false);
+
+$markedVerElem.addEventListener('change', handleVersionChange, false);
+
+$markdownElem.addEventListener('change', handleInput, false);
+$markdownElem.addEventListener('keyup', handleInput, false);
+$markdownElem.addEventListener('keypress', handleInput, false);
+$markdownElem.addEventListener('keydown', handleInput, false);
+
+$optionsElem.addEventListener('change', handleInput, false);
+$optionsElem.addEventListener('keyup', handleInput, false);
+$optionsElem.addEventListener('keypress', handleInput, false);
+$optionsElem.addEventListener('keydown', handleInput, false);
+
+$commitVerElem.style.display = 'none';
+$commitVerElem.addEventListener('keypress', handleAddVersion, false);
+
+$clearElem.addEventListener('click', handleClearClick, false);
+
+Promise.all([
+  setInitialQuickref(),
+  setInitialOutputType(),
+  setInitialText(),
+  setInitialVersion()
+    .then(setInitialOptions)
+]).then(function () {
+  handleInputChange();
+  handleOutputChange();
+  checkForChanges();
+  setScrollPercent(0);
+  $loadingElem.style.display = 'none';
+  $mainElem.style.display = 'block';
+});
+
+function setInitialText() {
+  if ('text' in search) {
+    $markdownElem.value = search.text;
+  } else {
+    return fetch('./initial.md')
+      .then(function (res) { return res.text(); })
+      .then(function (text) {
+        if ($markdownElem.value === '') {
+          $markdownElem.value = text;
+        }
+      });
+  }
+}
+
+function setInitialQuickref() {
+  return fetch('./quickref.md')
+    .then(function (res) { return res.text(); })
+    .then(function (text) {
+      document.querySelector('#quickref').value = text;
+    });
+}
+
+function setInitialVersion() {
+  return fetch('https://data.jsdelivr.com/v1/package/npm/marked')
+    .then(function (res) {
+      return res.json();
+    })
+    .then(function (json) {
+      for (var i = 0; i < json.versions.length; i++) {
+        var ver = json.versions[i];
+        markedVersions[ver] = 'https://cdn.jsdelivr.net/npm/marked@' + ver + '/lib/marked.js';
+        var opt = document.createElement('option');
+        opt.textContent = ver;
+        opt.value = ver;
+        $markedVerElem.appendChild(opt);
+      }
+    })
+    .then(function () {
+      return fetch('https://api.github.com/repos/markedjs/marked/commits')
+        .then(function (res) {
+          return res.json();
+        })
+        .then(function (json) {
+          markedVersions['master'] = 'https://cdn.jsdelivr.net/gh/markedjs/marked@' + json[0].sha + '/lib/marked.js';
+        })
+        .catch(function () {
+          // do nothing
+          // uses url without commit
+        });
+    })
+    .then(function () {
+      if (search.version) {
+        if (markedVersions[search.version]) {
+          return search.version;
+        } else {
+          var match = search.version.match(/^(\w+):(.+)$/);
+          if (match) {
+            switch (match[1]) {
+              case 'commit':
+                addCommitVersion(search.version, match[2].substring(0, 7), match[2]);
+                return search.version;
+              case 'pr':
+                return getPrCommit(match[2])
+                  .then(function (commit) {
+                    if (!commit) {
+                      return 'master';
+                    }
+                    addCommitVersion(search.version, 'PR #' + match[2], commit);
+                    return search.version;
+                  });
+            }
+          }
+        }
+      }
+
+      return 'master';
+    })
+    .then(function (version) {
+      $markedVerElem.value = version;
+    })
+    .then(updateVersion);
+}
+
+function setInitialOptions() {
+  if ('options' in search) {
+    $optionsElem.value = search.options;
+  } else {
+    setDefaultOptions();
+  }
+}
+
+function setInitialOutputType() {
+  if (search.outputType) {
+    $outputTypeElem.value = search.outputType;
+  }
+}
+
+function handleIframeLoad() {
+  lastInput = '';
+  inputDirty = true;
+}
+
+function handleInput() {
+  inputDirty = true;
+};
+
+function handleVersionChange() {
+  if ($markedVerElem.value === 'commit' || $markedVerElem.value === 'pr') {
+    $commitVerElem.style.display = '';
+  } else {
+    $commitVerElem.style.display = 'none';
+    updateVersion();
+  }
+}
+
+function handleClearClick() {
+  $markdownElem.value = '';
+  $markedVerElem.value = 'master';
+  $commitVerElem.style.display = 'none';
+  updateVersion().then(setDefaultOptions);
+}
+
+function handleAddVersion(e) {
+  if (e.which === 13) {
+    switch ($markedVerElem.value) {
+      case 'commit':
+        var commit = $commitVerElem.value.toLowerCase();
+        if (!commit.match(/^[0-9a-f]{40}$/)) {
+          alert('That is not a valid commit');
+          return;
+        }
+        addCommitVersion('commit:' + commit, commit.substring(0, 7), commit);
+        $markedVerElem.value = 'commit:' + commit;
+        $commitVerElem.style.display = 'none';
+        $commitVerElem.value = '';
+        updateVersion();
+        break;
+      case 'pr':
+        $commitVerElem.disabled = true;
+        var pr = $commitVerElem.value.replace(/\D/g, '');
+        getPrCommit(pr)
+          .then(function (commit) {
+            $commitVerElem.disabled = false;
+            if (!commit) {
+              alert('That is not a valid PR');
+              return;
+            }
+            addCommitVersion('pr:' + pr, 'PR #' + pr, commit);
+            $markedVerElem.value = 'pr:' + pr;
+            $commitVerElem.style.display = 'none';
+            $commitVerElem.value = '';
+            updateVersion();
+          });
+    }
+  }
+}
+
+function handleInputChange() {
+  handleChange($inputPanes, $inputTypeElem.value);
+}
+
+function handleOutputChange() {
+  $activeOutputElem = handleChange($panes, $outputTypeElem.value);
+  updateLink();
+}
+
+function handleChange(panes, visiblePane) {
+  var active = null;
+  for (var i = 0; i < panes.length; i++) {
+    if (panes[i].id === visiblePane) {
+      panes[i].style.display = '';
+      active = panes[i];
+    } else {
+      panes[i].style.display = 'none';
+    }
+  }
+  return active;
+};
+
+function addCommitVersion(value, text, commit) {
+  if (markedVersions[value]) {
+    return;
+  }
+  markedVersions[value] = 'https://cdn.jsdelivr.net/gh/markedjs/marked@' + commit + '/lib/marked.js';
+  var opt = document.createElement('option');
+  opt.textContent = text;
+  opt.value = value;
+  $markedVerElem.insertBefore(opt, $markedVerElem.firstChild);
+}
+
+function getPrCommit(pr) {
+  return fetch('https://api.github.com/repos/markedjs/marked/pulls/' + pr + '/commits')
+    .then(function (res) {
+      return res.json();
+    })
+    .then(function (json) {
+      return json[json.length - 1].sha;
+    }).catch(function () {
+      // return undefined
+    });
+}
+
+function setDefaultOptions() {
+  if (window.Worker) {
+    messageWorker({
+      task: 'defaults',
+      version: markedVersions[$markedVerElem.value]
+    });
+  } else {
+    var defaults = marked.getDefaults();
+    setOptions(defaults);
+  }
+}
+
+function setOptions(opts) {
+  $optionsElem.value = JSON.stringify(
+    opts,
+    function (key, value) {
+      if (value && typeof value === 'object' && Object.getPrototypeOf(value) !== Object.prototype) {
+        return undefined;
+      }
+      return value;
+    }, ' ');
+}
+
+function searchToObject() {
+  // modified from https://stackoverflow.com/a/7090123/806777
+  var pairs = location.search.slice(1).split('&');
+  var obj = {};
+
+  for (var i = 0; i < pairs.length; i++) {
+    if (pairs[i] === '') {
+      continue;
+    }
+
+    var pair = pairs[i].split('=');
+
+    obj[decodeURIComponent(pair.shift())] = decodeURIComponent(pair.join('='));
+  }
+
+  return obj;
+}
+
+function jsonString(input) {
+  var output = (input + '')
+    .replace(/\n/g, '\\n')
+    .replace(/\r/g, '\\r')
+    .replace(/\t/g, '\\t')
+    .replace(/\f/g, '\\f')
+    .replace(/[\\"']/g, '\\$&')
+    .replace(/\u0000/g, '\\0');
+  return '"' + output + '"';
+};
+
+function getScrollSize() {
+  var e = $activeOutputElem;
+
+  return e.scrollHeight - e.clientHeight;
+};
+
+function getScrollPercent() {
+  var size = getScrollSize();
+
+  if (size <= 0) {
+    return 1;
+  }
+
+  return $activeOutputElem.scrollTop / size;
+};
+
+function setScrollPercent(percent) {
+  $activeOutputElem.scrollTop = percent * getScrollSize();
+};
+
+function updateLink() {
+  var outputType = '';
+  if ($outputTypeElem.value !== 'preview') {
+    outputType = 'outputType=' + $outputTypeElem.value + '&';
+  }
+
+  $permalinkElem.href = '?' + outputType + 'text=' + encodeURIComponent($markdownElem.value)
+      + '&options=' + encodeURIComponent($optionsElem.value)
+      + '&version=' + encodeURIComponent($markedVerElem.value);
+  history.replaceState('', document.title, $permalinkElem.href);
+}
+
+function updateVersion() {
+  if (window.Worker) {
+    handleInput();
+    return Promise.resolve();
+  }
+  var promise;
+  if (markedVersionCache[$markedVerElem.value]) {
+    promise = Promise.resolve(markedVersionCache[$markedVerElem.value]);
+  } else {
+    promise = fetch(markedVersions[$markedVerElem.value])
+      .then(function (res) { return res.text(); })
+      .then(function (text) {
+        markedVersionCache[$markedVerElem.value] = text;
+        return text;
+      });
+  }
+  return promise.then(function (text) {
+    var script = document.createElement('script');
+    script.textContent = text;
+
+    $markedVer.parentNode.replaceChild(script, $markedVer);
+    $markedVer = script;
+  }).then(handleInput);
+}
+
+function checkForChanges() {
+  if (inputDirty && $markedVerElem.value !== 'commit' && $markedVerElem.value !== 'pr' && (typeof marked !== 'undefined' || window.Worker)) {
+    inputDirty = false;
+
+    updateLink();
+
+    var options = {};
+    var optionsString = $optionsElem.value || '{}';
+    try {
+      var newOptions = JSON.parse(optionsString);
+      options = newOptions;
+      $optionsElem.classList.remove('error');
+    } catch (err) {
+      $optionsElem.classList.add('error');
+    }
+
+    var version = markedVersions[$markedVerElem.value];
+    var markdown = $markdownElem.value;
+    var hash = version + markdown + optionsString;
+    if (lastInput !== hash) {
+      lastInput = hash;
+      if (window.Worker) {
+        delayTime = 100;
+        messageWorker({
+          task: 'parse',
+          version: version,
+          markdown: markdown,
+          options: options
+        });
+      } else {
+        var startTime = new Date();
+        var lexed = marked.lexer(markdown, options);
+        var lexedList = [];
+        for (var i = 0; i < lexed.length; i++) {
+          var lexedLine = [];
+          for (var j in lexed[i]) {
+            lexedLine.push(j + ':' + jsonString(lexed[i][j]));
+          }
+          lexedList.push('{' + lexedLine.join(', ') + '}');
+        }
+        var parsed = marked.parser(lexed, options);
+        var scrollPercent = getScrollPercent();
+        setParsed(parsed, lexedList.join('\n'));
+        setScrollPercent(scrollPercent);
+        var endTime = new Date();
+        delayTime = endTime - startTime;
+        setResponseTime(delayTime);
+        if (delayTime < 50) {
+          delayTime = 50;
+        } else if (delayTime > 500) {
+          delayTime = 1000;
+        }
+      }
+    }
+  }
+  checkChangeTimeout = window.setTimeout(checkForChanges, delayTime);
+};
+
+function setResponseTime(ms) {
+  var amount = ms;
+  var suffix = 'ms';
+  if (ms > 1000 * 60 * 60) {
+    amount = 'Too Long';
+    suffix = '';
+  } else if (ms > 1000 * 60) {
+    amount = '>' + Math.floor(ms / (1000 * 60));
+    suffix = 'm';
+  } else if (ms > 1000) {
+    amount = '>' + Math.floor(ms / 1000);
+    suffix = 's';
+  }
+  $responseTimeElem.textContent = amount + suffix;
+}
+
+function setParsed(parsed, lexed) {
+  try {
+    $previewIframe.contentDocument.body.innerHTML = parsed;
+  } catch (ex) {}
+  $htmlElem.value = parsed;
+  $lexerElem.value = lexed;
+}
+
+function messageWorker(message) {
+  if (!markedWorker || markedWorker.working) {
+    if (markedWorker) {
+      clearTimeout(markedWorker.timeout);
+      markedWorker.terminate();
+    }
+    markedWorker = new Worker('worker.js');
+    markedWorker.onmessage = function (e) {
+      clearTimeout(markedWorker.timeout);
+      markedWorker.working = false;
+      switch (e.data.task) {
+        case 'defaults':
+          setOptions(e.data.defaults);
+          break;
+        case 'parse':
+          $previewElem.classList.remove('error');
+          $htmlElem.classList.remove('error');
+          $lexerElem.classList.remove('error');
+          var scrollPercent = getScrollPercent();
+          setParsed(e.data.parsed, e.data.lexed);
+          setScrollPercent(scrollPercent);
+          setResponseTime(e.data.time);
+          break;
+      }
+      clearTimeout(checkChangeTimeout);
+      delayTime = 10;
+      checkForChanges();
+    };
+    markedWorker.onerror = markedWorker.onmessageerror = function (err) {
+      clearTimeout(markedWorker.timeout);
+      var error = 'There was an error in the Worker';
+      if (err) {
+        if (err.message) {
+          error = err.message;
+        } else {
+          error = err;
+        }
+      }
+      error = error.replace(/^Uncaught Error: /, '');
+      $previewElem.classList.add('error');
+      $htmlElem.classList.add('error');
+      $lexerElem.classList.add('error');
+      setParsed(error, error);
+      setScrollPercent(0);
+    };
+  }
+  if (message.task !== 'defaults') {
+    markedWorker.working = true;
+    workerTimeout(0);
+  }
+  markedWorker.postMessage(message);
+}
+
+function workerTimeout(seconds) {
+  markedWorker.timeout = setTimeout(function () {
+    seconds++;
+    markedWorker.onerror('Marked has taken longer than ' + seconds + ' second' + (seconds > 1 ? 's' : '') + ' to respond...');
+    workerTimeout(seconds);
+  }, 1000);
+}

+ 78 - 0
packages/markdown/marked/docs/demo/index.html

@@ -0,0 +1,78 @@
+<!doctype html>
+<html lang="en">
+
+  <head>
+    <title>Marked Demo</title>
+    <link rel="stylesheet" href="./demo.css" type="text/css" />
+  </head>
+
+  <body>
+    <a href="https://github.com/markedjs/marked">
+    <img class="github-ribbon" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub">
+  </a>
+
+    <header>
+      <a href="../">
+      <img src="../img/logo-black.svg" height="64px" width="64px" />
+    </a>
+      <h1>Marked Demo</h1>
+    </header>
+
+    <div id="loading">Loading...</div>
+    <div id="main">
+      <div class="containers">
+        <div class="container">
+          <div class="label">
+            <span>Input</span> ·
+            <a id="permalink">Permalink</a> ·
+            <span>Version: </span>
+            <select id="markedVersion">
+              <option value="pr">Add PR:</option>
+              <option value="commit">Add Commit:</option>
+              <option value="master" selected>master</option>
+            </select>
+            <input type="text" id="commitVersion" title="Press ENTER to add commit" />·
+            <button id="clear">Clear</button>
+            <select id="inputType">
+              <option value="markdown">Markdown</option>
+              <option value="options">Options</option>
+            </select>
+          </div>
+          <textarea id="markdown" class="inputPane"></textarea>
+          <textarea id="options" class="inputPane" placeholder="Options (as JSON)"></textarea>
+        </div>
+
+        <div class="container">
+          <div class="label">
+            <select id="outputType">
+              <option value="preview">Preview</option>
+              <option value="html">HTML Source</option>
+              <option value="lexer">Lexer Data</option>
+              <option value="quickref">Quick Reference</option>
+            </select> ·
+            Response Time:
+            <span id="responseTime"></span>
+          </div>
+
+          <div id="preview" class="pane">
+            <noscript>
+              <h2>You'll need to enable Javascript to use this tool.</h2>
+            </noscript>
+            <iframe src="./preview.html" frameborder="0" sandbox="allow-same-origin allow-top-navigation-by-user-activation"></iframe>
+          </div>
+
+          <textarea id="html" class="pane" readonly="readonly"></textarea>
+
+          <textarea id="lexer" class="pane" readonly="readonly"></textarea>
+
+          <textarea id="quickref" class="pane" readonly="readonly"></textarea>
+        </div>
+      </div>
+    </div>
+    <script id="markedCdn"></script>
+    <script src="https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.js"></script>
+    <script src="https://cdn.jsdelivr.net/npm/unfetch/dist/unfetch.umd.js"></script>
+    <script src="./demo.js"></script>
+  </body>
+
+</html>

+ 36 - 0
packages/markdown/marked/docs/demo/initial.md

@@ -0,0 +1,36 @@
+Marked - Markdown Parser
+========================
+
+[Marked] lets you convert [Markdown] into HTML.  Markdown is a simple text format whose goal is to be very easy to read and write, even when not converted to HTML.  This demo page will let you type anything you like and see how it gets converted.  Live.  No more waiting around.
+
+How To Use The Demo
+-------------------
+
+1. Type in stuff on the left.
+2. See the live updates on the right.
+
+That's it.  Pretty simple.  There's also a drop-down option in the upper right to switch between various views:
+
+- **Preview:**  A live display of the generated HTML as it would render in a browser.
+- **HTML Source:**  The generated HTML before your browser makes it pretty.
+- **Lexer Data:**  What [marked] uses internally, in case you like gory stuff like this.
+- **Quick Reference:**  A brief run-down of how to format things using markdown.
+
+Why Markdown?
+-------------
+
+It's easy.  It's not overly bloated, unlike HTML.  Also, as the creator of [markdown] says,
+
+> The overriding design goal for Markdown's
+> formatting syntax is to make it as readable
+> as possible. The idea is that a
+> Markdown-formatted document should be
+> publishable as-is, as plain text, without
+> looking like it's been marked up with tags
+> or formatting instructions.
+
+Ready to start writing?  Either start changing stuff on the left or
+[clear everything](/demo/?text=) with a simple click.
+
+[Marked]: https://github.com/markedjs/marked/
+[Markdown]: http://daringfireball.net/projects/markdown/

+ 12 - 0
packages/markdown/marked/docs/demo/preview.html

@@ -0,0 +1,12 @@
+
+<!doctype html>
+<html lang="en">
+<head>
+  <meta charset="utf-8">
+  <title>marked.js preview</title>
+  <link rel="stylesheet" href="./demo.css" />
+  <base target="_parent">
+</head>
+<body>
+</body>
+</html>

+ 167 - 0
packages/markdown/marked/docs/demo/quickref.md

@@ -0,0 +1,167 @@
+Markdown Quick Reference
+========================
+
+This guide is a very brief overview, with examples, of the syntax that [Markdown] supports.  It is itself written in Markdown and you can copy the samples over to the left-hand pane for experimentation.  It's shown as *text* and not *rendered HTML*.
+
+[Markdown]: http://daringfireball.net/projects/markdown/
+
+
+Simple Text Formatting
+======================
+
+First thing is first.  You can use *stars* or _underscores_ for italics.  **Double stars** and __double underscores__ do bold.  ***Three together*** do ___both___.
+
+Paragraphs are pretty easy too.  Just have a blank line between chunks of text.
+
+> This chunk of text is in a block quote.  Its multiple lines will all be
+> indended a bit from the rest of the text.
+>
+> > Multiple levels of block quotes also work.
+
+Sometimes you want to include some code, such as when you are explaining how `<h1>` HTML tags work, or maybe you are a programmer and you are discussing `someMethod()`.
+
+If you want to include some code and have
+newlines preserved, indent the line with a tab
+or at least four spaces.
+    Extra spaces work here too.
+This is also called preformatted text and it is useful for showing examples.
+The text will stay as text, so any *markdown* or <u>HTML</u> you add will
+not show up formatted.  This way you can show markdown examples in a
+markdown document.
+
+>     You can also use preformatted text with your blockquotes
+>     as long as you add at least five spaces.
+
+
+Headings
+========
+
+There are a couple of ways to make headings.  Using three or more equals signs on a line under a heading makes it into an "h1" style.  Three or more hyphens under a line makes it "h2" (slightly smaller).  You can also use multiple pound symbols before and after a heading.  Pounds after the title are ignored.  Here's some examples:
+
+This is H1
+==========
+
+This is H2
+----------
+
+# This is H1
+## This is H2
+### This is H3 with some extra pounds ###
+#### You get the idea ####
+##### I don't need extra pounds at the end
+###### H6 is the max
+
+
+Links
+=====
+
+Let's link to a few sites.  First, let's use the bare URL, like <http://www.github.com>.  Great for text, but ugly for HTML.
+Next is an inline link to [Google](http://www.google.com).  A little nicer.
+This is a reference-style link to [Wikipedia] [1].
+Lastly, here's a pretty link to [Yahoo].  The reference-style and pretty links both automatically use the links defined below, but they could be defined *anywhere* in the markdown and are removed from the HTML.  The names are also case insensitive, so you can use [YaHoO] and have it link properly.
+
+[1]: http://www.wikipedia.org/
+[Yahoo]: http://www.yahoo.com/
+
+Title attributes may be added to links by adding text after a link.
+This is the [inline link](http://www.bing.com "Bing") with a "Bing" title.
+You can also go to [W3C] [2] and maybe visit a [friend].
+
+[2]: http://w3c.org (The W3C puts out specs for web-based things)
+[Friend]: http://facebook.com/ "Facebook!"
+
+Email addresses in plain text are not linked: test@example.com.
+Email addresses wrapped in angle brackets are linked: <test@example.com>.
+They are also obfuscated so that email harvesting spam robots hopefully won't get them.
+
+
+Lists
+=====
+
+* This is a bulleted list
+* Great for shopping lists
+- You can also use hyphens
++ Or plus symbols
+
+The above is an "unordered" list.  Now, on for a bit of order.
+
+1. Numbered lists are also easy
+2. Just start with a number
+3738762. However, the actual number doesn't matter when converted to HTML.
+1.  This will still show up as 4.
+
+You might want a few advanced lists:
+
+- This top-level list is wrapped in paragraph tags
+- This generates an extra space between each top-level item.
+
+- You do it by adding a blank line
+
+- This nested list also has blank lines between the list items.
+
+- How to create nested lists
+1.  Start your regular list
+2.  Indent nested lists with four spaces
+3.  Further nesting means you should indent with four more spaces
+    * This line is indented with eight spaces.
+
+- List items can be quite lengthy.  You can keep typing and either continue
+them on the next line with no indentation.
+
+- Alternately, if that looks ugly, you can also
+indent the next line a bit for a prettier look.
+
+- You can put large blocks of text in your list by just indenting with four spaces.
+
+This is formatted the same as code, but you can inspect the HTML
+and find that it's just wrapped in a `<p>` tag and *won't* be shown
+as preformatted text.
+
+You can keep adding more and more paragraphs to a single
+list item by adding the traditional blank line and then keep
+on indenting the paragraphs with four spaces.  You really need
+to only indent the first line, but that looks ugly.
+
+- Lists support blockquotes
+
+> Just like this example here.  By the way, you can
+> nest lists inside blockquotes!
+> - Fantastic!
+
+- Lists support preformatted text
+
+    You just need to indent eight spaces.
+
+
+Even More
+=========
+
+Horizontal Rule
+---------------
+
+If you need a horizontal rule you just need to put at least three hyphens, asterisks, or underscores on a line by themselves.  You can also even put spaces between the characters.
+
+---
+****************************
+_ _ _ _ _ _ _
+
+Those three all produced horizontal lines.  Keep in mind that three hyphens under any text turns that text into a heading, so add a blank like if you use hyphens.
+
+Images
+------
+
+Images work exactly like links, but they have exclamation points in front.  They work with references and titles too.
+
+![Google Logo](http://www.google.com/images/errors/logo_sm.gif) and ![Happy].
+
+[Happy]: http://www.wpclipart.com/smiley/simple_smiley/smiley_face_simple_green_small.png ("Smiley face")
+
+
+Inline HTML
+-----------
+
+If markdown is too limiting, you can just insert your own <strike>crazy</strike> HTML.  Span-level HTML <u>can *still* use markdown</u>.  Block level elements must be separated from text by a blank line and must not have any spaces before the opening and closing HTML.
+
+<div style='font-family: "Comic Sans", sans-serif;'>
+It is a pity, but markdown does **not** work in here for most markdown parsers.  [Marked] handles it pretty well.
+</div>

+ 105 - 0
packages/markdown/marked/docs/demo/worker.js

@@ -0,0 +1,105 @@
+/* globals marked, unfetch, ES6Promise */
+if (!self.Promise) {
+  self.importScripts('https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.js');
+  self.Promise = ES6Promise;
+}
+if (!self.fetch) {
+  self.importScripts('https://cdn.jsdelivr.net/npm/unfetch/dist/unfetch.umd.js');
+  self.fetch = unfetch;
+}
+
+var versionCache = {};
+var currentVersion;
+
+onunhandledrejection = function (e) {
+  throw e.reason;
+};
+
+onmessage = function (e) {
+  if (e.data.version === currentVersion) {
+    parse(e);
+  } else {
+    loadVersion(e.data.version).then(function () {
+      parse(e);
+    });
+  }
+};
+
+function parse(e) {
+  switch (e.data.task) {
+    case 'defaults':
+
+      var defaults = {};
+      if (typeof marked.getDefaults === 'function') {
+        defaults = marked.getDefaults();
+        delete defaults.renderer;
+      } else if ('defaults' in marked) {
+        for (var prop in marked.defaults) {
+          if (prop !== 'renderer') {
+            defaults[prop] = marked.defaults[prop];
+          }
+        }
+      }
+      postMessage({
+        task: e.data.task,
+        defaults: defaults
+      });
+      break;
+    case 'parse':
+      var startTime = new Date();
+      var lexed = marked.lexer(e.data.markdown, e.data.options);
+      var lexedList = [];
+      for (var i = 0; i < lexed.length; i++) {
+        var lexedLine = [];
+        for (var j in lexed[i]) {
+          lexedLine.push(j + ':' + jsonString(lexed[i][j]));
+        }
+        lexedList.push('{' + lexedLine.join(', ') + '}');
+      }
+      var parsed = marked.parser(lexed, e.data.options);
+      var endTime = new Date();
+      // setTimeout(function () {
+      postMessage({
+        task: e.data.task,
+        lexed: lexedList.join('\n'),
+        parsed: parsed,
+        time: endTime - startTime
+      });
+      // }, 10000);
+      break;
+  }
+}
+
+function jsonString(input) {
+  var output = (input + '')
+    .replace(/\n/g, '\\n')
+    .replace(/\r/g, '\\r')
+    .replace(/\t/g, '\\t')
+    .replace(/\f/g, '\\f')
+    .replace(/[\\"']/g, '\\$&')
+    .replace(/\u0000/g, '\\0');
+  return '"' + output + '"';
+};
+
+function loadVersion(ver) {
+  var promise;
+  if (versionCache[ver]) {
+    promise = Promise.resolve(versionCache[ver]);
+  } else {
+    promise = fetch(ver)
+      .then(function (res) { return res.text(); })
+      .then(function (text) {
+        versionCache[ver] = text;
+        return text;
+      });
+  }
+  return promise.then(function (text) {
+    try {
+      // eslint-disable-next-line no-new-func
+      Function(text)();
+    } catch (err) {
+      throw new Error('Cannot load that version of marked');
+    }
+    currentVersion = ver;
+  });
+}

+ 133 - 0
packages/markdown/marked/docs/img/logo-black-and-white.svg

@@ -0,0 +1,133 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 16.0.4, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+	 width="996px" height="439.589px" viewBox="0 0 996 439.589" enable-background="new 0 0 996 439.589" xml:space="preserve">
+<g>
+	<g id="Marked_Letters">
+		<path fill="#010101" d="M185.044,358.869h-9.961l-1.143-25.986l-14.092,25.986h-6.24l-6.709-26.807l-8.818,26.807h-10.225
+			l13.389-40.605h10.928l6.416,25.781l13.916-25.781h10.635L185.044,358.869z"/>
+		<path fill="#010101" d="M226.617,358.869h-10.811l-1.084-8.994H202.33l-4.102,8.994h-10.605l20.566-40.605h10.986L226.617,358.869
+			z M214.019,344.162l-1.934-15.527l-7.061,15.527H214.019z"/>
+		<path fill="#010101" d="M267.712,358.869h-11.338l-4.043-8.467c-1.191-2.559-2.227-4.478-3.105-5.757s-1.651-2.07-2.314-2.373
+			c-0.664-0.303-1.553-0.454-2.666-0.454h-1.553l-2.578,17.051h-10.283l5.889-40.605h15.85c5.761,0,9.672,1.27,11.733,3.809
+			c2.061,2.539,3.091,5.283,3.091,8.232c0,3.105-0.854,5.522-2.563,7.251c-1.709,1.729-4.097,2.798-7.163,3.208
+			c1.562,0.898,2.769,1.953,3.618,3.164s1.86,3.096,3.032,5.654L267.712,358.869z M255.525,330.012c0-1.562-0.571-2.925-1.714-4.087
+			s-3.453-1.743-6.929-1.743h-1.611l-1.699,11.719h4.102c2.89,0,4.922-0.61,6.094-1.831S255.525,331.496,255.525,330.012z"/>
+		<path fill="#010101" d="M313.705,318.264l-17.578,18.223l14.912,22.383h-11.807l-14.59-21.65l-3.282,21.65h-10.342l6.064-40.605
+			h10.401l-2.578,17.256l16.611-17.256H313.705z"/>
+		<path fill="#010101" d="M346.426,318.264L345.4,325.5h-16.436l-1.26,8.818h14.268l-1.025,7.266h-14.385l-1.377,10.02h19.98
+			l-1.025,7.266h-30.439l5.889-40.605H346.426z"/>
+		<path fill="#010101" d="M389.953,338.156c0,4.512-0.86,8.301-2.578,11.367c-1.719,3.066-4.273,5.391-7.662,6.973
+			s-7.583,2.373-12.582,2.373H348.41l5.83-40.605h14.941c3.534,0,6.625,0.527,9.271,1.582s4.82,2.51,6.52,4.365
+			s2.953,3.97,3.764,6.343S389.953,335.461,389.953,338.156z M379.377,338.303c0-2.031-0.387-4.004-1.158-5.918
+			s-2.192-3.54-4.262-4.878c-2.07-1.338-4.941-2.007-8.613-2.007h-1.67l-3.779,26.104h5.449c2.597,0,4.828-0.391,6.693-1.172
+			s3.33-1.821,4.395-3.12s1.821-2.71,2.271-4.233C379.152,341.555,379.377,339.963,379.377,338.303z"/>
+	</g>
+	<g>
+		<path fill="#010101" d="M406.922,307.149l-3.703,26.35c-0.609,4.324-2.72,6.486-6.33,6.486c-0.773,0-1.553-0.07-2.338-0.211
+			l-0.756-3.023c0.879,0.188,1.67,0.281,2.373,0.281c1.219,0,2.118-0.302,2.698-0.905s0.964-1.55,1.151-2.839l3.674-26.139H406.922z
+			"/>
+		<path fill="#010101" d="M423.027,307.8l-0.475,3.357c-1.312-0.867-2.748-1.301-4.307-1.301c-1.312,0-2.361,0.34-3.146,1.02
+			s-1.178,1.576-1.178,2.689c0,0.551,0.188,1.131,0.562,1.74s1.471,1.644,3.287,3.103s3.015,2.739,3.595,3.841
+			s0.87,2.203,0.87,3.305c0,1.758-0.662,3.275-1.986,4.553s-3.088,1.916-5.291,1.916c-1.957,0-3.938-0.586-5.941-1.758l0.51-3.604
+			c2.238,1.559,4.16,2.338,5.766,2.338c0.867,0,1.69-0.284,2.47-0.852c0.779-0.568,1.169-1.339,1.169-2.312
+			c0-0.62-0.197-1.265-0.59-1.933c-0.394-0.667-1.502-1.745-3.324-3.232c-1.824-1.486-3.014-2.778-3.568-3.874
+			c-0.555-1.097-0.832-2.185-0.832-3.263c0-1.899,0.785-3.491,2.355-4.775c1.57-1.283,3.422-1.926,5.555-1.926
+			C420.016,306.833,421.516,307.155,423.027,307.8z"/>
+	</g>
+	<g>
+		<g>
+			<path fill="#010101" d="M357,200v-92c0-8.284-6.716-15-15-15H172c-8.284,0-15,6.716-15,15v92H357z"/>
+			<path fill="#010101" d="M157,205v73c0,8.284,6.716,15,15,15h170c8.284,0,15-6.716,15-15v-73H157z"/>
+		</g>
+		<g>
+			<path fill="#FFFFFF" d="M208.737,180.15v-33.125l16.987,21.234l16.987-21.234v33.125h16.987v-57.756h-16.987l-16.987,21.234
+				l-16.987-21.234H191.75v57.756H208.737z"/>
+			<path fill="#FFFFFF" d="M322.55,151.272h-16.987v-28.878h-16.986v28.878h-16.987L297.069,181L322.55,151.272z"/>
+		</g>
+		<g>
+			<path fill="#FFFFFF" d="M217,241.154c0,2.124-1.722,3.846-3.845,3.846h-5.31c-2.124,0-3.845-1.722-3.845-3.846v-0.309
+				c0-2.124,1.722-3.846,3.845-3.846h5.31c2.124,0,3.845,1.722,3.845,3.846V241.154z"/>
+			<path fill="#FFFFFF" d="M207.859,256.5c0,1.933-1.1,3.5-2.457,3.5h-12.046c-1.357,0-2.457-1.567-2.457-3.5l0,0
+				c0-1.933,1.1-3.5,2.457-3.5h12.046C206.759,253,207.859,254.567,207.859,256.5L207.859,256.5z"/>
+			<path fill="#FFFFFF" d="M328.044,238.021c-1.058-3.094-2.692-5.85-4.907-8.269c-2.215-2.418-5.049-4.314-8.498-5.689
+				c-3.45-1.375-7.479-2.063-12.086-2.063h-19.477l-7.6,52.932h24.403c6.518,0,11.984-1.032,16.402-3.094
+				c4.416-2.062,7.746-5.092,9.986-9.09c2.24-3.996,3.361-8.936,3.361-14.817C329.629,244.418,329.1,241.115,328.044,238.021z
+				 M314.964,254.347c-0.586,1.986-1.573,3.826-2.96,5.519c-1.389,1.694-3.297,3.049-5.729,4.067s-5.34,1.528-8.727,1.528h-7.103
+				l4.927-34.027h2.176c4.787,0,8.529,0.872,11.229,2.616c2.698,1.744,4.55,3.863,5.557,6.358c1.005,2.494,1.508,5.066,1.508,7.713
+				C315.842,250.286,315.549,252.361,314.964,254.347z"/>
+			<path fill="#FFFFFF" d="M246.148,241.043l1.373-9.61h21.424l1.336-9.434h-10.601h-24.38h-1.256c-2.125,0-3.846,1.877-3.846,4
+				s1.721,4,3.846,4h0.096h3.793c1.928,0,3.491,1.563,3.491,3.491c0,1.928-1.563,3.491-3.491,3.491h-4.806L233.126,237h-8.983
+				c-1.299,0-2.353,1.786-2.353,3.988c0,2.203,1.053,3.989,2.353,3.989h7.826L231.966,245h3.189c2.124,0,3.845,1.722,3.845,3.846
+				v0.309c0,2.124-1.722,3.846-3.845,3.846h-4.349h-0.96H216.2c-1.933,0-3.5,1.567-3.5,3.5s1.567,3.5,3.5,3.5h8.645h4.945h0.364
+				c2.124,0,3.845,1.722,3.845,3.846v0.309c0,2.124-1.722,3.846-3.845,3.846h-1.524h-3.785h-1.8c-2.125,0-3.846,1.377-3.846,3.5
+				s1.721,3.5,3.846,3.5h25.636c0.273,0,0.538-0.024,0.795-0.068h17.828l1.336-9.471h-26.045l1.795-13.062h18.751l1.336-9.471
+				h-18.598l0.029-0.205C246.055,242.213,246.144,241.647,246.148,241.043z"/>
+		</g>
+	</g>
+</g>
+<g>
+	<g id="Marked_Letters_1_">
+		<path fill="#010101" d="M619.045,356.869h-9.961l-1.143-25.986l-14.092,25.986h-6.24l-6.709-26.807l-8.818,26.807h-10.225
+			l13.389-40.605h10.928l6.416,25.781l13.916-25.781h10.635L619.045,356.869z"/>
+		<path fill="#010101" d="M660.617,356.869h-10.811l-1.084-8.994H636.33l-4.102,8.994h-10.605l20.566-40.605h10.986L660.617,356.869
+			z M648.02,342.162l-1.934-15.527l-7.061,15.527H648.02z"/>
+		<path fill="#010101" d="M701.713,356.869h-11.338l-4.043-8.467c-1.191-2.559-2.227-4.478-3.105-5.757s-1.651-2.07-2.314-2.373
+			c-0.664-0.303-1.553-0.454-2.666-0.454h-1.553l-2.578,17.051h-10.283l5.889-40.605h15.85c5.761,0,9.672,1.27,11.732,3.809
+			s3.092,5.283,3.092,8.232c0,3.105-0.855,5.522-2.564,7.251s-4.097,2.798-7.162,3.208c1.562,0.898,2.768,1.953,3.617,3.164
+			s1.861,3.096,3.033,5.654L701.713,356.869z M689.525,328.012c0-1.562-0.572-2.925-1.715-4.087s-3.452-1.743-6.928-1.743h-1.611
+			l-1.699,11.719h4.102c2.89,0,4.922-0.61,6.094-1.831S689.525,329.496,689.525,328.012z"/>
+		<path fill="#010101" d="M747.705,316.264l-17.578,18.223l14.912,22.383h-11.807l-14.59-21.65l-3.281,21.65H705.02l6.064-40.605
+			h10.4l-2.578,17.256l16.611-17.256H747.705z"/>
+		<path fill="#010101" d="M780.426,316.264L779.4,323.5h-16.436l-1.26,8.818h14.268l-1.025,7.266h-14.385l-1.377,10.02h19.98
+			l-1.025,7.266h-30.439l5.889-40.605H780.426z"/>
+		<path fill="#010101" d="M823.953,336.156c0,4.512-0.86,8.301-2.578,11.367c-1.719,3.066-4.273,5.391-7.662,6.973
+			s-7.583,2.373-12.582,2.373H782.41l5.83-40.605h14.941c3.534,0,6.625,0.527,9.271,1.582s4.82,2.51,6.52,4.365
+			s2.953,3.97,3.764,6.343S823.953,333.461,823.953,336.156z M813.377,336.303c0-2.031-0.387-4.004-1.158-5.918
+			s-2.192-3.54-4.262-4.878c-2.07-1.338-4.941-2.007-8.613-2.007h-1.67l-3.779,26.104h5.449c2.597,0,4.828-0.391,6.693-1.172
+			s3.33-1.821,4.395-3.12s1.821-2.71,2.271-4.233C813.152,339.555,813.377,337.963,813.377,336.303z"/>
+	</g>
+	<g>
+		<path fill="#010101" d="M840.922,305.149l-3.703,26.35c-0.609,4.324-2.72,6.486-6.33,6.486c-0.773,0-1.553-0.07-2.338-0.211
+			l-0.756-3.023c0.879,0.188,1.67,0.281,2.373,0.281c1.219,0,2.118-0.302,2.698-0.905s0.964-1.55,1.151-2.839l3.674-26.139H840.922z
+			"/>
+		<path fill="#010101" d="M857.027,305.8l-0.475,3.357c-1.312-0.867-2.748-1.301-4.307-1.301c-1.312,0-2.361,0.34-3.146,1.02
+			s-1.178,1.576-1.178,2.689c0,0.551,0.188,1.131,0.562,1.74s1.471,1.644,3.287,3.103s3.015,2.739,3.595,3.841
+			s0.87,2.203,0.87,3.305c0,1.758-0.662,3.275-1.986,4.553s-3.088,1.916-5.291,1.916c-1.957,0-3.938-0.586-5.941-1.758l0.51-3.604
+			c2.238,1.559,4.16,2.338,5.766,2.338c0.867,0,1.69-0.284,2.47-0.852c0.779-0.568,1.169-1.339,1.169-2.312
+			c0-0.62-0.197-1.265-0.59-1.933c-0.394-0.667-1.502-1.745-3.324-3.232c-1.824-1.486-3.014-2.778-3.568-3.874
+			c-0.555-1.097-0.832-2.185-0.832-3.263c0-1.899,0.785-3.491,2.355-4.775c1.57-1.283,3.422-1.926,5.555-1.926
+			C854.016,304.833,855.516,305.155,857.027,305.8z"/>
+	</g>
+	<g>
+		<g>
+			<path d="M641,234.154c0,2.124-1.722,3.846-3.846,3.846h-5.309c-2.124,0-3.846-1.722-3.846-3.846v-0.309
+				c0-2.124,1.722-3.846,3.846-3.846h5.309c2.124,0,3.846,1.722,3.846,3.846V234.154z"/>
+			<path d="M631.859,249.5c0,1.933-1.1,3.5-2.457,3.5h-12.046c-1.356,0-2.456-1.567-2.456-3.5l0,0c0-1.933,1.1-3.5,2.456-3.5h12.046
+				C630.76,246,631.859,247.567,631.859,249.5L631.859,249.5z"/>
+			<path d="M752.044,231.021c-1.058-3.094-2.692-5.85-4.907-8.269c-2.215-2.418-5.049-4.314-8.498-5.689
+				c-3.45-1.375-7.479-2.063-12.086-2.063h-19.477l-7.6,52.932h24.402c6.518,0,11.984-1.032,16.402-3.094
+				c4.416-2.062,7.746-5.092,9.986-9.09c2.24-3.996,3.361-8.936,3.361-14.817C753.629,237.418,753.1,234.115,752.044,231.021z
+				 M738.964,247.347c-0.586,1.986-1.573,3.826-2.96,5.519c-1.389,1.694-3.297,3.049-5.729,4.067s-5.34,1.528-8.727,1.528h-7.103
+				l4.927-34.027h2.176c4.787,0,8.529,0.872,11.229,2.616c2.698,1.744,4.55,3.863,5.557,6.358c1.005,2.494,1.508,5.066,1.508,7.713
+				C739.842,243.286,739.549,245.361,738.964,247.347z"/>
+			<path d="M670.148,234.043l1.373-9.61h21.424l1.337-9.434h-10.601h-24.381h-1.256c-2.124,0-3.846,1.877-3.846,4s1.722,4,3.846,4
+				h0.096h3.793c1.929,0,3.492,1.563,3.492,3.491c0,1.928-1.563,3.491-3.492,3.491h-4.805L657.126,230h-8.983
+				c-1.299,0-2.352,1.786-2.352,3.988c0,2.203,1.053,3.989,2.352,3.989h7.826L655.966,238h3.188c2.124,0,3.846,1.722,3.846,3.846
+				v0.309c0,2.124-1.722,3.846-3.846,3.846h-4.349h-0.96H640.2c-1.933,0-3.5,1.567-3.5,3.5s1.567,3.5,3.5,3.5h8.646h4.945h0.363
+				c2.124,0,3.846,1.722,3.846,3.846v0.309c0,2.124-1.722,3.846-3.846,3.846h-1.523h-3.785h-1.801c-2.124,0-3.846,1.377-3.846,3.5
+				s1.722,3.5,3.846,3.5h25.637c0.272,0,0.537-0.024,0.795-0.068h17.827l1.337-9.471h-26.045l1.795-13.062h18.75l1.337-9.471
+				h-18.599l0.029-0.205C670.055,235.213,670.144,234.647,670.148,234.043z"/>
+		</g>
+		<g>
+			<path fill="#010101" d="M642.236,179.15v-33.125l16.988,21.234l16.986-21.234v33.125h16.987v-57.756h-16.987l-16.986,21.234
+				l-16.988-21.234H625.25v57.756H642.236z"/>
+			<path fill="#010101" d="M756.05,150.272h-16.987v-28.878h-16.986v28.878H705.09L730.569,180L756.05,150.272z"/>
+		</g>
+		<path fill="#010101" d="M776,90H606c-11.028,0-20,8.972-20,20v170c0,11.028,8.972,20,20,20h170c11.028,0,20-8.972,20-20V110
+			C796,98.972,787.028,90,776,90z M606,100h170c5.514,0,10,4.486,10,10v83H596v-83C596,104.486,600.486,100,606,100z M776,290H606
+			c-5.514,0-10-4.486-10-10v-82h190v82C786,285.514,781.514,290,776,290z"/>
+	</g>
+</g>
+</svg>

+ 32 - 0
packages/markdown/marked/docs/img/logo-black.svg

@@ -0,0 +1,32 @@
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" width="300px" height="439.589px" viewBox="100 100 400 400" xml:space="preserve">
+<g>
+	<g id="Marked_Letters">
+		<path fill="#010101" d="M185.044,358.869h-9.961l-1.143-25.986l-14.092,25.986h-6.24l-6.709-26.807l-8.818,26.807h-10.225    l13.389-40.605h10.928l6.416,25.781l13.916-25.781h10.635L185.044,358.869z"/>
+		<path fill="#010101" d="M226.617,358.869h-10.811l-1.084-8.994H202.33l-4.102,8.994h-10.605l20.566-40.605h10.986L226.617,358.869    z M214.019,344.162l-1.934-15.527l-7.061,15.527H214.019z"/>
+		<path fill="#010101" d="M267.712,358.869h-11.338l-4.043-8.467c-1.191-2.559-2.227-4.478-3.105-5.757s-1.651-2.07-2.314-2.373    c-0.664-0.303-1.553-0.454-2.666-0.454h-1.553l-2.578,17.051h-10.283l5.889-40.605h15.85c5.761,0,9.672,1.27,11.733,3.809    c2.061,2.539,3.091,5.283,3.091,8.232c0,3.105-0.854,5.522-2.563,7.251c-1.709,1.729-4.097,2.798-7.163,3.208    c1.562,0.898,2.769,1.953,3.618,3.164s1.86,3.096,3.032,5.654L267.712,358.869z M255.525,330.012c0-1.562-0.571-2.925-1.714-4.087    s-3.453-1.743-6.929-1.743h-1.611l-1.699,11.719h4.102c2.89,0,4.922-0.61,6.094-1.831S255.525,331.496,255.525,330.012z"/>
+		<path fill="#010101" d="M313.705,318.264l-17.578,18.223l14.912,22.383h-11.807l-14.59-21.65l-3.282,21.65h-10.342l6.064-40.605    h10.401l-2.578,17.256l16.611-17.256H313.705z"/>
+		<path fill="#010101" d="M346.426,318.264L345.4,325.5h-16.436l-1.26,8.818h14.268l-1.025,7.266h-14.385l-1.377,10.02h19.98    l-1.025,7.266h-30.439l5.889-40.605H346.426z"/>
+		<path fill="#010101" d="M389.953,338.156c0,4.512-0.86,8.301-2.578,11.367c-1.719,3.066-4.273,5.391-7.662,6.973    s-7.583,2.373-12.582,2.373H348.41l5.83-40.605h14.941c3.534,0,6.625,0.527,9.271,1.582s4.82,2.51,6.52,4.365    s2.953,3.97,3.764,6.343S389.953,335.461,389.953,338.156z M379.377,338.303c0-2.031-0.387-4.004-1.158-5.918    s-2.192-3.54-4.262-4.878c-2.07-1.338-4.941-2.007-8.613-2.007h-1.67l-3.779,26.104h5.449c2.597,0,4.828-0.391,6.693-1.172    s3.33-1.821,4.395-3.12s1.821-2.71,2.271-4.233C379.152,341.555,379.377,339.963,379.377,338.303z"/>
+	</g>
+	<g>
+		<path fill="#010101" d="M406.922,307.149l-3.703,26.35c-0.609,4.324-2.72,6.486-6.33,6.486c-0.773,0-1.553-0.07-2.338-0.211    l-0.756-3.023c0.879,0.188,1.67,0.281,2.373,0.281c1.219,0,2.118-0.302,2.698-0.905s0.964-1.55,1.151-2.839l3.674-26.139H406.922z    "/>
+		<path fill="#010101" d="M423.027,307.8l-0.475,3.357c-1.312-0.867-2.748-1.301-4.307-1.301c-1.312,0-2.361,0.34-3.146,1.02    s-1.178,1.576-1.178,2.689c0,0.551,0.188,1.131,0.562,1.74s1.471,1.644,3.287,3.103s3.015,2.739,3.595,3.841    s0.87,2.203,0.87,3.305c0,1.758-0.662,3.275-1.986,4.553s-3.088,1.916-5.291,1.916c-1.957,0-3.938-0.586-5.941-1.758l0.51-3.604    c2.238,1.559,4.16,2.338,5.766,2.338c0.867,0,1.69-0.284,2.47-0.852c0.779-0.568,1.169-1.339,1.169-2.312    c0-0.62-0.197-1.265-0.59-1.933c-0.394-0.667-1.502-1.745-3.324-3.232c-1.824-1.486-3.014-2.778-3.568-3.874    c-0.555-1.097-0.832-2.185-0.832-3.263c0-1.899,0.785-3.491,2.355-4.775c1.57-1.283,3.422-1.926,5.555-1.926    C420.016,306.833,421.516,307.155,423.027,307.8z"/>
+	</g>
+	<g>
+		<g>
+			<path fill="#010101" d="M357,200v-92c0-8.284-6.716-15-15-15H172c-8.284,0-15,6.716-15,15v92H357z"/>
+			<path fill="#010101" d="M157,205v73c0,8.284,6.716,15,15,15h170c8.284,0,15-6.716,15-15v-73H157z"/>
+		</g>
+		<g>
+			<path fill="#FFFFFF" d="M208.737,180.15v-33.125l16.987,21.234l16.987-21.234v33.125h16.987v-57.756h-16.987l-16.987,21.234     l-16.987-21.234H191.75v57.756H208.737z"/>
+			<path fill="#FFFFFF" d="M322.55,151.272h-16.987v-28.878h-16.986v28.878h-16.987L297.069,181L322.55,151.272z"/>
+		</g>
+		<g>
+			<path fill="#FFFFFF" d="M217,241.154c0,2.124-1.722,3.846-3.845,3.846h-5.31c-2.124,0-3.845-1.722-3.845-3.846v-0.309     c0-2.124,1.722-3.846,3.845-3.846h5.31c2.124,0,3.845,1.722,3.845,3.846V241.154z"/>
+			<path fill="#FFFFFF" d="M207.859,256.5c0,1.933-1.1,3.5-2.457,3.5h-12.046c-1.357,0-2.457-1.567-2.457-3.5l0,0     c0-1.933,1.1-3.5,2.457-3.5h12.046C206.759,253,207.859,254.567,207.859,256.5L207.859,256.5z"/>
+			<path fill="#FFFFFF" d="M328.044,238.021c-1.058-3.094-2.692-5.85-4.907-8.269c-2.215-2.418-5.049-4.314-8.498-5.689     c-3.45-1.375-7.479-2.063-12.086-2.063h-19.477l-7.6,52.932h24.403c6.518,0,11.984-1.032,16.402-3.094     c4.416-2.062,7.746-5.092,9.986-9.09c2.24-3.996,3.361-8.936,3.361-14.817C329.629,244.418,329.1,241.115,328.044,238.021z      M314.964,254.347c-0.586,1.986-1.573,3.826-2.96,5.519c-1.389,1.694-3.297,3.049-5.729,4.067s-5.34,1.528-8.727,1.528h-7.103     l4.927-34.027h2.176c4.787,0,8.529,0.872,11.229,2.616c2.698,1.744,4.55,3.863,5.557,6.358c1.005,2.494,1.508,5.066,1.508,7.713     C315.842,250.286,315.549,252.361,314.964,254.347z"/>
+			<path fill="#FFFFFF" d="M246.148,241.043l1.373-9.61h21.424l1.336-9.434h-10.601h-24.38h-1.256c-2.125,0-3.846,1.877-3.846,4     s1.721,4,3.846,4h0.096h3.793c1.928,0,3.491,1.563,3.491,3.491c0,1.928-1.563,3.491-3.491,3.491h-4.806L233.126,237h-8.983     c-1.299,0-2.353,1.786-2.353,3.988c0,2.203,1.053,3.989,2.353,3.989h7.826L231.966,245h3.189c2.124,0,3.845,1.722,3.845,3.846     v0.309c0,2.124-1.722,3.846-3.845,3.846h-4.349h-0.96H216.2c-1.933,0-3.5,1.567-3.5,3.5s1.567,3.5,3.5,3.5h8.645h4.945h0.364     c2.124,0,3.845,1.722,3.845,3.846v0.309c0,2.124-1.722,3.846-3.845,3.846h-1.524h-3.785h-1.8c-2.125,0-3.846,1.377-3.846,3.5     s1.721,3.5,3.846,3.5h25.636c0.273,0,0.538-0.024,0.795-0.068h17.828l1.336-9.471h-26.045l1.795-13.062h18.751l1.336-9.471     h-18.598l0.029-0.205C246.055,242.213,246.144,241.647,246.148,241.043z"/>
+		</g>
+	</g>
+</g>
+</svg>

+ 269 - 0
packages/markdown/marked/docs/index.html

@@ -0,0 +1,269 @@
+<!doctype html>
+<html>
+<head>
+    <meta charset="utf-8"/>
+    <title>Marked.js Documentation</title>
+    <style>
+        body {
+            font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";
+            font-size: 16px;
+            line-height: 1.5;
+            word-wrap: break-word;
+            background: #F9F9F9;
+        }
+
+        #container {
+            max-width: 900px;
+            margin: auto;
+        }
+
+        #content {
+            padding: 5px 10px;
+            border: 1px solid #ddd;
+            border-radius: 3px;
+            background: white;
+        }
+
+        #content h1:first-child {
+            margin-top: 0px;
+        }
+
+        nav {
+            border: 1px solid #ddd;
+            border-radius: 3px;
+            background: white;
+            margin-right: 10px;
+        }
+
+        nav > ul {
+            position: sticky;
+            top: 5px;
+            margin: 10px 0px;
+            padding: 0;
+            list-style-type: none;
+            font-size: 14px;
+        }
+
+        nav > ul > li {
+            min-width: 125px;
+            padding: 0px 15px;
+        }
+
+        nav > ul > li > ul {
+            padding-left: 25px;
+        }
+
+        nav > ul > li > ul > li {
+            font-size: 0.8em;
+        }
+
+        nav .selected {
+            color: #111;
+            font-weight: bold;
+        }
+
+        nav .selected:hover {
+            text-decoration: none;
+        }
+
+        header {
+            display: flex;
+            height: 50px;
+        }
+
+        header h1 { margin: 0; }
+
+        table {
+            border-spacing: 0;
+            border-collapse: collapse;
+            border: 1px solid #ddd;
+        }
+
+        td, th {
+            border: 1px solid #ddd;
+            padding: 5px;
+        }
+
+        a {
+            color: #0366d6;
+            text-decoration: none;
+        }
+
+        a:hover {
+            text-decoration: underline;
+        }
+
+        pre {
+            font-family: "SFMono-Regular",Consolas,"Liberation Mono",Menlo,Courier,monospace;
+            padding: 16px;
+            overflow: auto;
+            font-size: 85%;
+            line-height: 1.45;
+            background-color: #f6f8fa;
+            border-radius: 3px;
+        }
+
+        code:not([class]) {
+            padding: 0.2em 0.4em;
+            margin: 0;
+            font-size: 85%;
+            background-color: rgba(27,31,35,0.05);
+            border-radius: 3px;
+        }
+
+        .github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}
+
+    </style>
+</head>
+<body>
+    <a href="https://github.com/markedjs/marked" class="github-corner" aria-label="View source on Github">
+        <svg width="80" height="80" viewBox="0 0 250 250" style="fill:#202020; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true">
+            <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
+            <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
+            <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path>
+        </svg>
+    </a>
+    <div id="container">
+        <header>
+            <a href="#/README.md">
+                <img src="img/logo-black.svg" height="64px" width="64px" />
+            </a>
+            <h1>Marked.js Documentation</h1>
+        </header>
+        <div style="display: flex">
+            <nav>
+                <ul>
+                    <li>
+                        <a href="#/README.md">Getting Started</a>
+                        <ul>
+                            <li><a href="#/README.md#demo">Demo</a></li>
+                            <li><a href="#/README.md#installation">Installation</a></li>
+                            <li><a href="#/README.md#usage">Usage</a></li>
+                            <li><a href="#/README.md#specifications">Specs</a></li>
+                            <li><a href="#/README.md#security">Security</a></li>
+                        </ul>
+                    </li>
+                    <li>
+                        <a href="#/USING_ADVANCED.md">Advanced Usage</a>
+                        <ul>
+                            <li><a href="#/USING_ADVANCED.md#options">Options</a></li>
+                            <li><a href="#/USING_ADVANCED.md#highlight">Highlighting</a></li>
+                        </ul>
+                    </li>
+                    <li>
+                        <a href="#/USING_PRO.md">Extensibility</a>
+                        <ul>
+                            <li><a href="#/USING_PRO.md#renderer">Renderer</a></li>
+                            <li><a href="#/USING_PRO.md#lexer">Lexer</a></li>
+                            <li><a href="#/USING_PRO.md#parser">Parser</a></li>
+                        </ul>
+                    </li>
+                    <li>
+                        <a href="#/CONTRIBUTING.md">Contributing</a>
+                        <ul>
+                            <li><a href="#/CONTRIBUTING.md#design-principles">Design Principles</a></li>
+                            <li><a href="#/CONTRIBUTING.md#priorities">Priorities</a></li>
+                            <li><a href="#/CONTRIBUTING.md#test-early-often-and-everything">Testing</a></li>
+                        </ul>
+                    </li>
+                    <li><a href="#/CODE_OF_CONDUCT.md">Code of Conduct</a></li>
+                    <li><a href="#/AUTHORS.md">Authors</a></li>
+                    <li><a href="#/PUBLISHING.md">Publishing</a></li>
+                    <li><a href="https://github.com/markedjs/marked/blob/master/LICENSE.md">License</a></li>
+                </ul>
+            </nav>
+            <div id="content"></div>
+        </div>
+    </div>
+    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
+    <script src="https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.js"></script>
+    <script src="https://cdn.jsdelivr.net/npm/unfetch/dist/unfetch.umd.js"></script>
+    <script>
+        if (!window.Promise) {
+          window.Promise = ES6Promise;
+        }
+        if (!window.fetch) {
+          window.fetch = unfetch;
+        }
+
+        var content = document.querySelector('#content');
+        var body = document.querySelector('html');
+        var navLinks = document.querySelectorAll('nav a');
+        var currentPage = 'README.md';
+        var currentHash = '';
+        var renderedPage = '';
+
+        function hashChange() {
+            var hash = location.hash.slice(1);
+            if (!hash) {
+                hash = 'README.md';
+            }
+
+            var uri = hash.split('#');
+
+            if (uri[0].match(/^\//)) {
+                currentPage = uri[0].slice(1);
+                if (uri.length > 1) {
+                    currentHash = uri[1];
+                } else {
+                    currentHash = '';
+                }
+            } else {
+                currentHash = uri[0];
+            }
+
+            fetchPage(currentPage).then(function () {
+                fetchAnchor(currentHash)
+            });
+
+            var url = '#/' + currentPage + (currentHash ? '#' + currentHash : '');
+            var fullUrl = window.location.origin + '/' + url;
+
+            navLinks.forEach(function(link) {
+                link.className = link.href === fullUrl ? 'selected' : '';
+            });
+
+            history.replaceState('', document.title, url);
+        }
+
+        function fetchAnchor(anchor) {
+            if (!anchor) {
+                return;
+            }
+
+            var hashElement = document.getElementById(anchor);
+            if (hashElement) {
+                hashElement.scrollIntoView();
+            }
+        }
+
+        function fetchPage(page) {
+            if (page === renderedPage) {
+                return Promise.resolve();
+            }
+            return fetch(page)
+                .then(function (res) {
+                    if (!res.ok) {
+                        throw new Error('Error ' + res.status + ': ' + res.statusText);
+                    }
+                    return res.text();
+                })
+                .then(function (text) {
+                    renderedPage = page;
+                    content.innerHTML = marked(text);
+                    body.scrollTop = 0;
+                }).catch(function (e) {
+                    content.innerHTML = '<p>Oops! There was a problem rendering the page.</p>'
+                        + '<p>' + e.message + '</p>';
+                });
+        }
+
+        window.addEventListener('hashchange', function (e) {
+            e.preventDefault();
+            hashChange();
+        });
+
+        hashChange();
+    </script>
+</body>
+</html>

+ 1 - 0
packages/markdown/marked/index.js

@@ -0,0 +1 @@
+module.exports = require('./lib/marked');

+ 11 - 0
packages/markdown/marked/jasmine.json

@@ -0,0 +1,11 @@
+{
+  "spec_dir": "test",
+  "spec_files": [
+    "**/*-spec.js"
+  ],
+  "helpers": [
+    "helpers/helpers.js"
+  ],
+  "stopSpecOnExpectationFailure": false,
+  "random": true
+}

+ 1689 - 0
packages/markdown/marked/lib/marked.js

@@ -0,0 +1,1689 @@
+/**
+ * marked - a markdown parser
+ * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT Licensed)
+ * https://github.com/markedjs/marked
+ */
+
+;(function(root) {
+'use strict';
+
+/**
+ * Block-Level Grammar
+ */
+
+var block = {
+  newline: /^\n+/,
+  code: /^( {4}[^\n]+\n*)+/,
+  fences: noop,
+  hr: /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,
+  heading: /^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/,
+  nptable: noop,
+  blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,
+  list: /^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
+  html: '^ {0,3}(?:' // optional indentation
+    + '<(script|pre|style)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1)
+    + '|comment[^\\n]*(\\n+|$)' // (2)
+    + '|<\\?[\\s\\S]*?\\?>\\n*' // (3)
+    + '|<![A-Z][\\s\\S]*?>\\n*' // (4)
+    + '|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>\\n*' // (5)
+    + '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:\\n{2,}|$)' // (6)
+    + '|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) open tag
+    + '|</(?!script|pre|style)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) closing tag
+    + ')',
+  def: /^ {0,3}\[(label)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,
+  table: noop,
+  lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
+  paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading| {0,3}>|<\/?(?:tag)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)/,
+  text: /^[^\n]+/
+};
+
+block._label = /(?!\s*\])(?:\\[\[\]]|[^\[\]])+/;
+block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;
+block.def = edit(block.def)
+  .replace('label', block._label)
+  .replace('title', block._title)
+  .getRegex();
+
+block.bullet = /(?:[*+-]|\d{1,9}\.)/;
+block.item = /^( *)(bull) ?[^\n]*(?:\n(?!\1bull ?)[^\n]*)*/;
+block.item = edit(block.item, 'gm')
+  .replace(/bull/g, block.bullet)
+  .getRegex();
+
+block.list = edit(block.list)
+  .replace(/bull/g, block.bullet)
+  .replace('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))')
+  .replace('def', '\\n+(?=' + block.def.source + ')')
+  .getRegex();
+
+block._tag = 'address|article|aside|base|basefont|blockquote|body|caption'
+  + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'
+  + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'
+  + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'
+  + '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr'
+  + '|track|ul';
+block._comment = /<!--(?!-?>)[\s\S]*?-->/;
+block.html = edit(block.html, 'i')
+  .replace('comment', block._comment)
+  .replace('tag', block._tag)
+  .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/)
+  .getRegex();
+
+block.paragraph = edit(block.paragraph)
+  .replace('hr', block.hr)
+  .replace('heading', block.heading)
+  .replace('lheading', block.lheading)
+  .replace('tag', block._tag) // pars can be interrupted by type (6) html blocks
+  .getRegex();
+
+block.blockquote = edit(block.blockquote)
+  .replace('paragraph', block.paragraph)
+  .getRegex();
+
+/**
+ * Normal Block Grammar
+ */
+
+block.normal = merge({}, block);
+
+/**
+ * GFM Block Grammar
+ */
+
+block.gfm = merge({}, block.normal, {
+  fences: /^ {0,3}(`{3,}|~{3,})([^`\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/,
+  paragraph: /^/,
+  heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
+});
+
+block.gfm.paragraph = edit(block.paragraph)
+  .replace('(?!', '(?!'
+    + block.gfm.fences.source.replace('\\1', '\\2') + '|'
+    + block.list.source.replace('\\1', '\\3') + '|')
+  .getRegex();
+
+/**
+ * GFM + Tables Block Grammar
+ */
+
+block.tables = merge({}, block.gfm, {
+  nptable: /^ *([^|\n ].*\|.*)\n *([-:]+ *\|[-| :]*)(?:\n((?:.*[^>\n ].*(?:\n|$))*)\n*|$)/,
+  table: /^ *\|(.+)\n *\|?( *[-:]+[-| :]*)(?:\n((?: *[^>\n ].*(?:\n|$))*)\n*|$)/
+});
+
+/**
+ * Pedantic grammar
+ */
+
+block.pedantic = merge({}, block.normal, {
+  html: edit(
+    '^ *(?:comment *(?:\\n|\\s*$)'
+    + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag
+    + '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))')
+    .replace('comment', block._comment)
+    .replace(/tag/g, '(?!(?:'
+      + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'
+      + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'
+      + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b')
+    .getRegex(),
+  def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/
+});
+
+/**
+ * Block Lexer
+ */
+
+function Lexer(options) {
+  this.tokens = [];
+  this.tokens.links = Object.create(null);
+  this.options = options || marked.defaults;
+  this.rules = block.normal;
+
+  if (this.options.pedantic) {
+    this.rules = block.pedantic;
+  } else if (this.options.gfm) {
+    if (this.options.tables) {
+      this.rules = block.tables;
+    } else {
+      this.rules = block.gfm;
+    }
+  }
+}
+
+/**
+ * Expose Block Rules
+ */
+
+Lexer.rules = block;
+
+/**
+ * Static Lex Method
+ */
+
+Lexer.lex = function(src, options) {
+  var lexer = new Lexer(options);
+  return lexer.lex(src);
+};
+
+/**
+ * Preprocessing
+ */
+
+Lexer.prototype.lex = function(src) {
+  src = src
+    .replace(/\r\n|\r/g, '\n')
+    .replace(/\t/g, '    ')
+    .replace(/\u00a0/g, ' ')
+    .replace(/\u2424/g, '\n');
+
+  return this.token(src, true);
+};
+
+/**
+ * Lexing
+ */
+
+Lexer.prototype.token = function(src, top) {
+  src = src.replace(/^ +$/gm, '');
+  var next,
+      loose,
+      cap,
+      bull,
+      b,
+      item,
+      listStart,
+      listItems,
+      t,
+      space,
+      i,
+      tag,
+      l,
+      isordered,
+      istask,
+      ischecked;
+
+  while (src) {
+    // newline
+    if (cap = this.rules.newline.exec(src)) {
+      src = src.substring(cap[0].length);
+      if (cap[0].length > 1) {
+        this.tokens.push({
+          type: 'space'
+        });
+      }
+    }
+
+    // code
+    if (cap = this.rules.code.exec(src)) {
+      src = src.substring(cap[0].length);
+      cap = cap[0].replace(/^ {4}/gm, '');
+      this.tokens.push({
+        type: 'code',
+        text: !this.options.pedantic
+          ? rtrim(cap, '\n')
+          : cap
+      });
+      continue;
+    }
+
+    // fences (gfm)
+    if (cap = this.rules.fences.exec(src)) {
+      src = src.substring(cap[0].length);
+      this.tokens.push({
+        type: 'code',
+        lang: cap[2] ? cap[2].trim() : cap[2],
+        text: cap[3] || ''
+      });
+      continue;
+    }
+
+    // heading
+    if (cap = this.rules.heading.exec(src)) {
+      src = src.substring(cap[0].length);
+      this.tokens.push({
+        type: 'heading',
+        depth: cap[1].length,
+        text: cap[2]
+      });
+      continue;
+    }
+
+    // table no leading pipe (gfm)
+    if (cap = this.rules.nptable.exec(src)) {
+      item = {
+        type: 'table',
+        header: splitCells(cap[1].replace(/^ *| *\| *$/g, '')),
+        align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
+        cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : []
+      };
+
+      if (item.header.length === item.align.length) {
+        src = src.substring(cap[0].length);
+
+        for (i = 0; i < item.align.length; i++) {
+          if (/^ *-+: *$/.test(item.align[i])) {
+            item.align[i] = 'right';
+          } else if (/^ *:-+: *$/.test(item.align[i])) {
+            item.align[i] = 'center';
+          } else if (/^ *:-+ *$/.test(item.align[i])) {
+            item.align[i] = 'left';
+          } else {
+            item.align[i] = null;
+          }
+        }
+
+        for (i = 0; i < item.cells.length; i++) {
+          item.cells[i] = splitCells(item.cells[i], item.header.length);
+        }
+
+        this.tokens.push(item);
+
+        continue;
+      }
+    }
+
+    // hr
+    if (cap = this.rules.hr.exec(src)) {
+      src = src.substring(cap[0].length);
+      this.tokens.push({
+        type: 'hr'
+      });
+      continue;
+    }
+
+    // blockquote
+    if (cap = this.rules.blockquote.exec(src)) {
+      src = src.substring(cap[0].length);
+
+      this.tokens.push({
+        type: 'blockquote_start'
+      });
+
+      cap = cap[0].replace(/^ *> ?/gm, '');
+
+      // Pass `top` to keep the current
+      // "toplevel" state. This is exactly
+      // how markdown.pl works.
+      this.token(cap, top);
+
+      this.tokens.push({
+        type: 'blockquote_end'
+      });
+
+      continue;
+    }
+
+    // list
+    if (cap = this.rules.list.exec(src)) {
+      src = src.substring(cap[0].length);
+      bull = cap[2];
+      isordered = bull.length > 1;
+
+      listStart = {
+        type: 'list_start',
+        ordered: isordered,
+        start: isordered ? +bull : '',
+        loose: false
+      };
+
+      this.tokens.push(listStart);
+
+      // Get each top-level item.
+      cap = cap[0].match(this.rules.item);
+
+      listItems = [];
+      next = false;
+      l = cap.length;
+      i = 0;
+
+      for (; i < l; i++) {
+        item = cap[i];
+
+        // Remove the list item's bullet
+        // so it is seen as the next token.
+        space = item.length;
+        item = item.replace(/^ *([*+-]|\d+\.) */, '');
+
+        // Outdent whatever the
+        // list item contains. Hacky.
+        if (~item.indexOf('\n ')) {
+          space -= item.length;
+          item = !this.options.pedantic
+            ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
+            : item.replace(/^ {1,4}/gm, '');
+        }
+
+        // Determine whether the next list item belongs here.
+        // Backpedal if it does not belong in this list.
+        if (i !== l - 1) {
+          b = block.bullet.exec(cap[i + 1])[0];
+          if (bull.length > 1 ? b.length === 1
+            : (b.length > 1 || (this.options.smartLists && b !== bull))) {
+            src = cap.slice(i + 1).join('\n') + src;
+            i = l - 1;
+          }
+        }
+
+        // Determine whether item is loose or not.
+        // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
+        // for discount behavior.
+        loose = next || /\n\n(?!\s*$)/.test(item);
+        if (i !== l - 1) {
+          next = item.charAt(item.length - 1) === '\n';
+          if (!loose) loose = next;
+        }
+
+        if (loose) {
+          listStart.loose = true;
+        }
+
+        // Check for task list items
+        istask = /^\[[ xX]\] /.test(item);
+        ischecked = undefined;
+        if (istask) {
+          ischecked = item[1] !== ' ';
+          item = item.replace(/^\[[ xX]\] +/, '');
+        }
+
+        t = {
+          type: 'list_item_start',
+          task: istask,
+          checked: ischecked,
+          loose: loose
+        };
+
+        listItems.push(t);
+        this.tokens.push(t);
+
+        // Recurse.
+        this.token(item, false);
+
+        this.tokens.push({
+          type: 'list_item_end'
+        });
+      }
+
+      if (listStart.loose) {
+        l = listItems.length;
+        i = 0;
+        for (; i < l; i++) {
+          listItems[i].loose = true;
+        }
+      }
+
+      this.tokens.push({
+        type: 'list_end'
+      });
+
+      continue;
+    }
+
+    // html
+    if (cap = this.rules.html.exec(src)) {
+      src = src.substring(cap[0].length);
+      this.tokens.push({
+        type: this.options.sanitize
+          ? 'paragraph'
+          : 'html',
+        pre: !this.options.sanitizer
+          && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
+        text: cap[0]
+      });
+      continue;
+    }
+
+    // def
+    if (top && (cap = this.rules.def.exec(src))) {
+      src = src.substring(cap[0].length);
+      if (cap[3]) cap[3] = cap[3].substring(1, cap[3].length - 1);
+      tag = cap[1].toLowerCase().replace(/\s+/g, ' ');
+      if (!this.tokens.links[tag]) {
+        this.tokens.links[tag] = {
+          href: cap[2],
+          title: cap[3]
+        };
+      }
+      continue;
+    }
+
+    // table (gfm)
+    if (cap = this.rules.table.exec(src)) {
+      item = {
+        type: 'table',
+        header: splitCells(cap[1].replace(/^ *| *\| *$/g, '')),
+        align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
+        cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : []
+      };
+
+      if (item.header.length === item.align.length) {
+        src = src.substring(cap[0].length);
+
+        for (i = 0; i < item.align.length; i++) {
+          if (/^ *-+: *$/.test(item.align[i])) {
+            item.align[i] = 'right';
+          } else if (/^ *:-+: *$/.test(item.align[i])) {
+            item.align[i] = 'center';
+          } else if (/^ *:-+ *$/.test(item.align[i])) {
+            item.align[i] = 'left';
+          } else {
+            item.align[i] = null;
+          }
+        }
+
+        for (i = 0; i < item.cells.length; i++) {
+          item.cells[i] = splitCells(
+            item.cells[i].replace(/^ *\| *| *\| *$/g, ''),
+            item.header.length);
+        }
+
+        this.tokens.push(item);
+
+        continue;
+      }
+    }
+
+    // lheading
+    if (cap = this.rules.lheading.exec(src)) {
+      src = src.substring(cap[0].length);
+      this.tokens.push({
+        type: 'heading',
+        depth: cap[2] === '=' ? 1 : 2,
+        text: cap[1]
+      });
+      continue;
+    }
+
+    // top-level paragraph
+    if (top && (cap = this.rules.paragraph.exec(src))) {
+      src = src.substring(cap[0].length);
+      this.tokens.push({
+        type: 'paragraph',
+        text: cap[1].charAt(cap[1].length - 1) === '\n'
+          ? cap[1].slice(0, -1)
+          : cap[1]
+      });
+      continue;
+    }
+
+    // text
+    if (cap = this.rules.text.exec(src)) {
+      // Top-level should never reach here.
+      src = src.substring(cap[0].length);
+      this.tokens.push({
+        type: 'text',
+        text: cap[0]
+      });
+      continue;
+    }
+
+    if (src) {
+      throw new Error('Infinite loop on byte: ' + src.charCodeAt(0));
+    }
+  }
+
+  return this.tokens;
+};
+
+/**
+ * Inline-Level Grammar
+ */
+
+var inline = {
+  escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,
+  autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/,
+  url: noop,
+  tag: '^comment'
+    + '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag
+    + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag
+    + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?>
+    + '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html>
+    + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>', // CDATA section
+  link: /^!?\[(label)\]\(href(?:\s+(title))?\s*\)/,
+  reflink: /^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,
+  nolink: /^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,
+  strong: /^__([^\s_])__(?!_)|^\*\*([^\s*])\*\*(?!\*)|^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)/,
+  em: /^_([^\s_])_(?!_)|^\*([^\s*"<\[])\*(?!\*)|^_([^\s][\s\S]*?[^\s_])_(?!_|[^\spunctuation])|^_([^\s_][\s\S]*?[^\s])_(?!_|[^\spunctuation])|^\*([^\s"<\[][\s\S]*?[^\s*])\*(?!\*)|^\*([^\s*"<\[][\s\S]*?[^\s])\*(?!\*)/,
+  code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,
+  br: /^( {2,}|\\)\n(?!\s*$)/,
+  del: noop,
+  text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\<!\[`*]|\b_|$)|[^ ](?= {2,}\n))|(?= {2,}\n))/
+};
+
+// list of punctuation marks from common mark spec
+// without ` and ] to workaround Rule 17 (inline code blocks/links)
+inline._punctuation = '!"#$%&\'()*+,\\-./:;<=>?@\\[^_{|}~';
+inline.em = edit(inline.em).replace(/punctuation/g, inline._punctuation).getRegex();
+
+inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g;
+
+inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;
+inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/;
+inline.autolink = edit(inline.autolink)
+  .replace('scheme', inline._scheme)
+  .replace('email', inline._email)
+  .getRegex();
+
+inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;
+
+inline.tag = edit(inline.tag)
+  .replace('comment', block._comment)
+  .replace('attribute', inline._attribute)
+  .getRegex();
+
+inline._label = /(?:\[[^\[\]]*\]|\\[\[\]]?|`[^`]*`|`(?!`)|[^\[\]\\`])*?/;
+inline._href = /\s*(<(?:\\[<>]?|[^\s<>\\])*>|[^\s\x00-\x1f]*)/;
+inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;
+
+inline.link = edit(inline.link)
+  .replace('label', inline._label)
+  .replace('href', inline._href)
+  .replace('title', inline._title)
+  .getRegex();
+
+inline.reflink = edit(inline.reflink)
+  .replace('label', inline._label)
+  .getRegex();
+
+/**
+ * Normal Inline Grammar
+ */
+
+inline.normal = merge({}, inline);
+
+/**
+ * Pedantic Inline Grammar
+ */
+
+inline.pedantic = merge({}, inline.normal, {
+  strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
+  em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/,
+  link: edit(/^!?\[(label)\]\((.*?)\)/)
+    .replace('label', inline._label)
+    .getRegex(),
+  reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/)
+    .replace('label', inline._label)
+    .getRegex()
+});
+
+/**
+ * GFM Inline Grammar
+ */
+
+inline.gfm = merge({}, inline.normal, {
+  escape: edit(inline.escape).replace('])', '~|])').getRegex(),
+  _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,
+  url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,
+  _backpedal: /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,
+  del: /^~+(?=\S)([\s\S]*?\S)~+/,
+  text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\<!\[`*~]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))|(?= {2,}\n|[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))/
+});
+
+inline.gfm.url = edit(inline.gfm.url, 'i')
+  .replace('email', inline.gfm._extended_email)
+  .getRegex();
+/**
+ * GFM + Line Breaks Inline Grammar
+ */
+
+inline.breaks = merge({}, inline.gfm, {
+  br: edit(inline.br).replace('{2,}', '*').getRegex(),
+  text: edit(inline.gfm.text).replace(/\{2,\}/g, '*').getRegex()
+});
+
+/**
+ * Inline Lexer & Compiler
+ */
+
+function InlineLexer(links, options) {
+  this.options = options || marked.defaults;
+  this.links = links;
+  this.rules = inline.normal;
+  this.renderer = this.options.renderer || new Renderer();
+  this.renderer.options = this.options;
+
+  if (!this.links) {
+    throw new Error('Tokens array requires a `links` property.');
+  }
+
+  if (this.options.pedantic) {
+    this.rules = inline.pedantic;
+  } else if (this.options.gfm) {
+    if (this.options.breaks) {
+      this.rules = inline.breaks;
+    } else {
+      this.rules = inline.gfm;
+    }
+  }
+}
+
+/**
+ * Expose Inline Rules
+ */
+
+InlineLexer.rules = inline;
+
+/**
+ * Static Lexing/Compiling Method
+ */
+
+InlineLexer.output = function(src, links, options) {
+  var inline = new InlineLexer(links, options);
+  return inline.output(src);
+};
+
+/**
+ * Lexing/Compiling
+ */
+
+InlineLexer.prototype.output = function(src) {
+  var out = '',
+      link,
+      text,
+      href,
+      title,
+      cap,
+      prevCapZero;
+
+  while (src) {
+    // escape
+    if (cap = this.rules.escape.exec(src)) {
+      src = src.substring(cap[0].length);
+      out += escape(cap[1]);
+      continue;
+    }
+
+    // tag
+    if (cap = this.rules.tag.exec(src)) {
+      if (!this.inLink && /^<a /i.test(cap[0])) {
+        this.inLink = true;
+      } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
+        this.inLink = false;
+      }
+      if (!this.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
+        this.inRawBlock = true;
+      } else if (this.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
+        this.inRawBlock = false;
+      }
+
+      src = src.substring(cap[0].length);
+      out += this.options.sanitize
+        ? this.options.sanitizer
+          ? this.options.sanitizer(cap[0])
+          : escape(cap[0])
+        : cap[0];
+      continue;
+    }
+
+    // link
+    if (cap = this.rules.link.exec(src)) {
+      var lastParenIndex = findClosingBracket(cap[2], '()');
+      if (lastParenIndex > -1) {
+        var linkLen = cap[0].length - (cap[2].length - lastParenIndex) - (cap[3] || '').length;
+        cap[2] = cap[2].substring(0, lastParenIndex);
+        cap[0] = cap[0].substring(0, linkLen).trim();
+        cap[3] = '';
+      }
+      src = src.substring(cap[0].length);
+      this.inLink = true;
+      href = cap[2];
+      if (this.options.pedantic) {
+        link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
+
+        if (link) {
+          href = link[1];
+          title = link[3];
+        } else {
+          title = '';
+        }
+      } else {
+        title = cap[3] ? cap[3].slice(1, -1) : '';
+      }
+      href = href.trim().replace(/^<([\s\S]*)>$/, '$1');
+      out += this.outputLink(cap, {
+        href: InlineLexer.escapes(href),
+        title: InlineLexer.escapes(title)
+      });
+      this.inLink = false;
+      continue;
+    }
+
+    // reflink, nolink
+    if ((cap = this.rules.reflink.exec(src))
+        || (cap = this.rules.nolink.exec(src))) {
+      src = src.substring(cap[0].length);
+      link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
+      link = this.links[link.toLowerCase()];
+      if (!link || !link.href) {
+        out += cap[0].charAt(0);
+        src = cap[0].substring(1) + src;
+        continue;
+      }
+      this.inLink = true;
+      out += this.outputLink(cap, link);
+      this.inLink = false;
+      continue;
+    }
+
+    // strong
+    if (cap = this.rules.strong.exec(src)) {
+      src = src.substring(cap[0].length);
+      out += this.renderer.strong(this.output(cap[4] || cap[3] || cap[2] || cap[1]));
+      continue;
+    }
+
+    // em
+    if (cap = this.rules.em.exec(src)) {
+      src = src.substring(cap[0].length);
+      out += this.renderer.em(this.output(cap[6] || cap[5] || cap[4] || cap[3] || cap[2] || cap[1]));
+      continue;
+    }
+
+    // code
+    if (cap = this.rules.code.exec(src)) {
+      src = src.substring(cap[0].length);
+      out += this.renderer.codespan(escape(cap[2].trim(), true));
+      continue;
+    }
+
+    // br
+    if (cap = this.rules.br.exec(src)) {
+      src = src.substring(cap[0].length);
+      out += this.renderer.br();
+      continue;
+    }
+
+    // del (gfm)
+    if (cap = this.rules.del.exec(src)) {
+      src = src.substring(cap[0].length);
+      out += this.renderer.del(this.output(cap[1]));
+      continue;
+    }
+
+    // autolink
+    if (cap = this.rules.autolink.exec(src)) {
+      src = src.substring(cap[0].length);
+      if (cap[2] === '@') {
+        text = escape(this.mangle(cap[1]));
+        href = 'mailto:' + text;
+      } else {
+        text = escape(cap[1]);
+        href = text;
+      }
+      out += this.renderer.link(href, null, text);
+      continue;
+    }
+
+    // url (gfm)
+    if (!this.inLink && (cap = this.rules.url.exec(src))) {
+      if (cap[2] === '@') {
+        text = escape(cap[0]);
+        href = 'mailto:' + text;
+      } else {
+        // do extended autolink path validation
+        do {
+          prevCapZero = cap[0];
+          cap[0] = this.rules._backpedal.exec(cap[0])[0];
+        } while (prevCapZero !== cap[0]);
+        text = escape(cap[0]);
+        if (cap[1] === 'www.') {
+          href = 'http://' + text;
+        } else {
+          href = text;
+        }
+      }
+      src = src.substring(cap[0].length);
+      out += this.renderer.link(href, null, text);
+      continue;
+    }
+
+    // text
+    if (cap = this.rules.text.exec(src)) {
+      src = src.substring(cap[0].length);
+      if (this.inRawBlock) {
+        out += this.renderer.text(cap[0]);
+      } else {
+        out += this.renderer.text(escape(this.smartypants(cap[0])));
+      }
+      continue;
+    }
+
+    if (src) {
+      throw new Error('Infinite loop on byte: ' + src.charCodeAt(0));
+    }
+  }
+
+  return out;
+};
+
+InlineLexer.escapes = function(text) {
+  return text ? text.replace(InlineLexer.rules._escapes, '$1') : text;
+};
+
+/**
+ * Compile Link
+ */
+
+InlineLexer.prototype.outputLink = function(cap, link) {
+  var href = link.href,
+      title = link.title ? escape(link.title) : null;
+
+  return cap[0].charAt(0) !== '!'
+    ? this.renderer.link(href, title, this.output(cap[1]))
+    : this.renderer.image(href, title, escape(cap[1]));
+};
+
+/**
+ * Smartypants Transformations
+ */
+
+InlineLexer.prototype.smartypants = function(text) {
+  if (!this.options.smartypants) return text;
+  return text
+    // em-dashes
+    .replace(/---/g, '\u2014')
+    // en-dashes
+    .replace(/--/g, '\u2013')
+    // opening singles
+    .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
+    // closing singles & apostrophes
+    .replace(/'/g, '\u2019')
+    // opening doubles
+    .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
+    // closing doubles
+    .replace(/"/g, '\u201d')
+    // ellipses
+    .replace(/\.{3}/g, '\u2026');
+};
+
+/**
+ * Mangle Links
+ */
+
+InlineLexer.prototype.mangle = function(text) {
+  if (!this.options.mangle) return text;
+  var out = '',
+      l = text.length,
+      i = 0,
+      ch;
+
+  for (; i < l; i++) {
+    ch = text.charCodeAt(i);
+    if (Math.random() > 0.5) {
+      ch = 'x' + ch.toString(16);
+    }
+    out += '&#' + ch + ';';
+  }
+
+  return out;
+};
+
+/**
+ * Renderer
+ */
+
+function Renderer(options) {
+  this.options = options || marked.defaults;
+}
+
+Renderer.prototype.code = function(code, infostring, escaped) {
+  var lang = (infostring || '').match(/\S*/)[0];
+  if (this.options.highlight) {
+    var out = this.options.highlight(code, lang);
+    if (out != null && out !== code) {
+      escaped = true;
+      code = out;
+    }
+  }
+
+  if (!lang) {
+    return '<pre><code>'
+      + (escaped ? code : escape(code, true))
+      + '</code></pre>';
+  }
+
+  return '<pre><code class="'
+    + this.options.langPrefix
+    + escape(lang, true)
+    + '">'
+    + (escaped ? code : escape(code, true))
+    + '</code></pre>\n';
+};
+
+Renderer.prototype.blockquote = function(quote) {
+  return '<blockquote>\n' + quote + '</blockquote>\n';
+};
+
+Renderer.prototype.html = function(html) {
+  return html;
+};
+
+Renderer.prototype.heading = function(text, level, raw, slugger) {
+  if (this.options.headerIds) {
+    return '<h'
+      + level
+      + ' id="'
+      + this.options.headerPrefix
+      + slugger.slug(raw)
+      + '">'
+      + text
+      + '</h'
+      + level
+      + '>\n';
+  }
+  // ignore IDs
+  return '<h' + level + '>' + text + '</h' + level + '>\n';
+};
+
+Renderer.prototype.hr = function() {
+  return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
+};
+
+Renderer.prototype.list = function(body, ordered, start) {
+  var type = ordered ? 'ol' : 'ul',
+      startatt = (ordered && start !== 1) ? (' start="' + start + '"') : '';
+  return '<' + type + startatt + '>\n' + body + '</' + type + '>\n';
+};
+
+Renderer.prototype.listitem = function(text) {
+  return '<li>' + text + '</li>\n';
+};
+
+Renderer.prototype.checkbox = function(checked) {
+  return '<input '
+    + (checked ? 'checked="" ' : '')
+    + 'disabled="" type="checkbox"'
+    + (this.options.xhtml ? ' /' : '')
+    + '> ';
+};
+
+Renderer.prototype.paragraph = function(text) {
+  return '<p>' + text + '</p>\n';
+};
+
+Renderer.prototype.table = function(header, body) {
+  if (body) body = '<tbody>' + body + '</tbody>';
+
+  return '<table>\n'
+    + '<thead>\n'
+    + header
+    + '</thead>\n'
+    + body
+    + '</table>\n';
+};
+
+Renderer.prototype.tablerow = function(content) {
+  return '<tr>\n' + content + '</tr>\n';
+};
+
+Renderer.prototype.tablecell = function(content, flags) {
+  var type = flags.header ? 'th' : 'td';
+  var tag = flags.align
+    ? '<' + type + ' align="' + flags.align + '">'
+    : '<' + type + '>';
+  return tag + content + '</' + type + '>\n';
+};
+
+// span level renderer
+Renderer.prototype.strong = function(text) {
+  return '<strong>' + text + '</strong>';
+};
+
+Renderer.prototype.em = function(text) {
+  return '<em>' + text + '</em>';
+};
+
+Renderer.prototype.codespan = function(text) {
+  return '<code>' + text + '</code>';
+};
+
+Renderer.prototype.br = function() {
+  return this.options.xhtml ? '<br/>' : '<br>';
+};
+
+Renderer.prototype.del = function(text) {
+  return '<del>' + text + '</del>';
+};
+
+Renderer.prototype.link = function(href, title, text) {
+  href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);
+  if (href === null) {
+    return text;
+  }
+  var out = '<a href="' + escape(href) + '"';
+  if (title) {
+    out += ' title="' + title + '"';
+  }
+  out += '>' + text + '</a>';
+  return out;
+};
+
+Renderer.prototype.image = function(href, title, text) {
+  href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);
+  if (href === null) {
+    return text;
+  }
+
+  var out = '<img src="' + href + '" alt="' + text + '"';
+  if (title) {
+    out += ' title="' + title + '"';
+  }
+  out += this.options.xhtml ? '/>' : '>';
+  return out;
+};
+
+Renderer.prototype.text = function(text) {
+  return text;
+};
+
+/**
+ * TextRenderer
+ * returns only the textual part of the token
+ */
+
+function TextRenderer() {}
+
+// no need for block level renderers
+
+TextRenderer.prototype.strong =
+TextRenderer.prototype.em =
+TextRenderer.prototype.codespan =
+TextRenderer.prototype.del =
+TextRenderer.prototype.text = function (text) {
+  return text;
+};
+
+TextRenderer.prototype.link =
+TextRenderer.prototype.image = function(href, title, text) {
+  return '' + text;
+};
+
+TextRenderer.prototype.br = function() {
+  return '';
+};
+
+/**
+ * Parsing & Compiling
+ */
+
+function Parser(options) {
+  this.tokens = [];
+  this.token = null;
+  this.options = options || marked.defaults;
+  this.options.renderer = this.options.renderer || new Renderer();
+  this.renderer = this.options.renderer;
+  this.renderer.options = this.options;
+  this.slugger = new Slugger();
+}
+
+/**
+ * Static Parse Method
+ */
+
+Parser.parse = function(src, options) {
+  var parser = new Parser(options);
+  return parser.parse(src);
+};
+
+/**
+ * Parse Loop
+ */
+
+Parser.prototype.parse = function(src) {
+  this.inline = new InlineLexer(src.links, this.options);
+  // use an InlineLexer with a TextRenderer to extract pure text
+  this.inlineText = new InlineLexer(
+    src.links,
+    merge({}, this.options, {renderer: new TextRenderer()})
+  );
+  this.tokens = src.reverse();
+
+  var out = '';
+  while (this.next()) {
+    out += this.tok();
+  }
+
+  return out;
+};
+
+/**
+ * Next Token
+ */
+
+Parser.prototype.next = function() {
+  return this.token = this.tokens.pop();
+};
+
+/**
+ * Preview Next Token
+ */
+
+Parser.prototype.peek = function() {
+  return this.tokens[this.tokens.length - 1] || 0;
+};
+
+/**
+ * Parse Text Tokens
+ */
+
+Parser.prototype.parseText = function() {
+  var body = this.token.text;
+
+  while (this.peek().type === 'text') {
+    body += '\n' + this.next().text;
+  }
+
+  return this.inline.output(body);
+};
+
+/**
+ * Parse Current Token
+ */
+
+Parser.prototype.tok = function() {
+  switch (this.token.type) {
+    case 'space': {
+      return '';
+    }
+    case 'hr': {
+      return this.renderer.hr();
+    }
+    case 'heading': {
+      return this.renderer.heading(
+        this.inline.output(this.token.text),
+        this.token.depth,
+        unescape(this.inlineText.output(this.token.text)),
+        this.slugger);
+    }
+    case 'code': {
+      return this.renderer.code(this.token.text,
+        this.token.lang,
+        this.token.escaped);
+    }
+    case 'table': {
+      var header = '',
+          body = '',
+          i,
+          row,
+          cell,
+          j;
+
+      // header
+      cell = '';
+      for (i = 0; i < this.token.header.length; i++) {
+        cell += this.renderer.tablecell(
+          this.inline.output(this.token.header[i]),
+          { header: true, align: this.token.align[i] }
+        );
+      }
+      header += this.renderer.tablerow(cell);
+
+      for (i = 0; i < this.token.cells.length; i++) {
+        row = this.token.cells[i];
+
+        cell = '';
+        for (j = 0; j < row.length; j++) {
+          cell += this.renderer.tablecell(
+            this.inline.output(row[j]),
+            { header: false, align: this.token.align[j] }
+          );
+        }
+
+        body += this.renderer.tablerow(cell);
+      }
+      return this.renderer.table(header, body);
+    }
+    case 'blockquote_start': {
+      body = '';
+
+      while (this.next().type !== 'blockquote_end') {
+        body += this.tok();
+      }
+
+      return this.renderer.blockquote(body);
+    }
+    case 'list_start': {
+      body = '';
+      var ordered = this.token.ordered,
+          start = this.token.start;
+
+      while (this.next().type !== 'list_end') {
+        body += this.tok();
+      }
+
+      return this.renderer.list(body, ordered, start);
+    }
+    case 'list_item_start': {
+      body = '';
+      var loose = this.token.loose;
+      var checked = this.token.checked;
+      var task = this.token.task;
+
+      if (this.token.task) {
+        body += this.renderer.checkbox(checked);
+      }
+
+      while (this.next().type !== 'list_item_end') {
+        body += !loose && this.token.type === 'text'
+          ? this.parseText()
+          : this.tok();
+      }
+      return this.renderer.listitem(body, task, checked);
+    }
+    case 'html': {
+      // TODO parse inline content if parameter markdown=1
+      return this.renderer.html(this.token.text);
+    }
+    case 'paragraph': {
+      return this.renderer.paragraph(this.inline.output(this.token.text));
+    }
+    case 'text': {
+      return this.renderer.paragraph(this.parseText());
+    }
+    default: {
+      var errMsg = 'Token with "' + this.token.type + '" type was not found.';
+      if (this.options.silent) {
+        console.log(errMsg);
+      } else {
+        throw new Error(errMsg);
+      }
+    }
+  }
+};
+
+/**
+ * Slugger generates header id
+ */
+
+function Slugger () {
+  this.seen = {};
+}
+
+/**
+ * Convert string to unique id
+ */
+
+Slugger.prototype.slug = function (value) {
+  var slug = value
+    .toLowerCase()
+    .trim()
+    .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '')
+    .replace(/\s/g, '-');
+
+  if (this.seen.hasOwnProperty(slug)) {
+    var originalSlug = slug;
+    do {
+      this.seen[originalSlug]++;
+      slug = originalSlug + '-' + this.seen[originalSlug];
+    } while (this.seen.hasOwnProperty(slug));
+  }
+  this.seen[slug] = 0;
+
+  return slug;
+};
+
+/**
+ * Helpers
+ */
+
+function escape(html, encode) {
+  if (encode) {
+    if (escape.escapeTest.test(html)) {
+      return html.replace(escape.escapeReplace, function (ch) { return escape.replacements[ch]; });
+    }
+  } else {
+    if (escape.escapeTestNoEncode.test(html)) {
+      return html.replace(escape.escapeReplaceNoEncode, function (ch) { return escape.replacements[ch]; });
+    }
+  }
+
+  return html;
+}
+
+escape.escapeTest = /[&<>"']/;
+escape.escapeReplace = /[&<>"']/g;
+escape.replacements = {
+  '&': '&amp;',
+  '<': '&lt;',
+  '>': '&gt;',
+  '"': '&quot;',
+  "'": '&#39;'
+};
+
+escape.escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/;
+escape.escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g;
+
+function unescape(html) {
+  // explicitly match decimal, hex, and named HTML entities
+  return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, function(_, n) {
+    n = n.toLowerCase();
+    if (n === 'colon') return ':';
+    if (n.charAt(0) === '#') {
+      return n.charAt(1) === 'x'
+        ? String.fromCharCode(parseInt(n.substring(2), 16))
+        : String.fromCharCode(+n.substring(1));
+    }
+    return '';
+  });
+}
+
+function edit(regex, opt) {
+  regex = regex.source || regex;
+  opt = opt || '';
+  return {
+    replace: function(name, val) {
+      val = val.source || val;
+      val = val.replace(/(^|[^\[])\^/g, '$1');
+      regex = regex.replace(name, val);
+      return this;
+    },
+    getRegex: function() {
+      return new RegExp(regex, opt);
+    }
+  };
+}
+
+function cleanUrl(sanitize, base, href) {
+  if (sanitize) {
+    try {
+      var prot = decodeURIComponent(unescape(href))
+        .replace(/[^\w:]/g, '')
+        .toLowerCase();
+    } catch (e) {
+      return null;
+    }
+    if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
+      return null;
+    }
+  }
+  if (base && !originIndependentUrl.test(href)) {
+    href = resolveUrl(base, href);
+  }
+  try {
+    href = encodeURI(href).replace(/%25/g, '%');
+  } catch (e) {
+    return null;
+  }
+  return href;
+}
+
+function resolveUrl(base, href) {
+  if (!baseUrls[' ' + base]) {
+    // we can ignore everything in base after the last slash of its path component,
+    // but we might need to add _that_
+    // https://tools.ietf.org/html/rfc3986#section-3
+    if (/^[^:]+:\/*[^/]*$/.test(base)) {
+      baseUrls[' ' + base] = base + '/';
+    } else {
+      baseUrls[' ' + base] = rtrim(base, '/', true);
+    }
+  }
+  base = baseUrls[' ' + base];
+
+  if (href.slice(0, 2) === '//') {
+    return base.replace(/:[\s\S]*/, ':') + href;
+  } else if (href.charAt(0) === '/') {
+    return base.replace(/(:\/*[^/]*)[\s\S]*/, '$1') + href;
+  } else {
+    return base + href;
+  }
+}
+var baseUrls = {};
+var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;
+
+function noop() {}
+noop.exec = noop;
+
+function merge(obj) {
+  var i = 1,
+      target,
+      key;
+
+  for (; i < arguments.length; i++) {
+    target = arguments[i];
+    for (key in target) {
+      if (Object.prototype.hasOwnProperty.call(target, key)) {
+        obj[key] = target[key];
+      }
+    }
+  }
+
+  return obj;
+}
+
+function splitCells(tableRow, count) {
+  // ensure that every cell-delimiting pipe has a space
+  // before it to distinguish it from an escaped pipe
+  var row = tableRow.replace(/\|/g, function (match, offset, str) {
+        var escaped = false,
+            curr = offset;
+        while (--curr >= 0 && str[curr] === '\\') escaped = !escaped;
+        if (escaped) {
+          // odd number of slashes means | is escaped
+          // so we leave it alone
+          return '|';
+        } else {
+          // add space before unescaped |
+          return ' |';
+        }
+      }),
+      cells = row.split(/ \|/),
+      i = 0;
+
+  if (cells.length > count) {
+    cells.splice(count);
+  } else {
+    while (cells.length < count) cells.push('');
+  }
+
+  for (; i < cells.length; i++) {
+    // leading or trailing whitespace is ignored per the gfm spec
+    cells[i] = cells[i].trim().replace(/\\\|/g, '|');
+  }
+  return cells;
+}
+
+// Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').
+// /c*$/ is vulnerable to REDOS.
+// invert: Remove suffix of non-c chars instead. Default falsey.
+function rtrim(str, c, invert) {
+  if (str.length === 0) {
+    return '';
+  }
+
+  // Length of suffix matching the invert condition.
+  var suffLen = 0;
+
+  // Step left until we fail to match the invert condition.
+  while (suffLen < str.length) {
+    var currChar = str.charAt(str.length - suffLen - 1);
+    if (currChar === c && !invert) {
+      suffLen++;
+    } else if (currChar !== c && invert) {
+      suffLen++;
+    } else {
+      break;
+    }
+  }
+
+  return str.substr(0, str.length - suffLen);
+}
+
+function findClosingBracket(str, b) {
+  if (str.indexOf(b[1]) === -1) {
+    return -1;
+  }
+  var level = 0;
+  for (var i = 0; i < str.length; i++) {
+    if (str[i] === '\\') {
+      i++;
+    } else if (str[i] === b[0]) {
+      level++;
+    } else if (str[i] === b[1]) {
+      level--;
+      if (level < 0) {
+        return i;
+      }
+    }
+  }
+  return -1;
+}
+
+/**
+ * Marked
+ */
+
+function marked(src, opt, callback) {
+  // throw error in case of non string input
+  if (typeof src === 'undefined' || src === null) {
+    throw new Error('marked(): input parameter is undefined or null');
+  }
+  if (typeof src !== 'string') {
+    throw new Error('marked(): input parameter is of type '
+      + Object.prototype.toString.call(src) + ', string expected');
+  }
+
+  if (callback || typeof opt === 'function') {
+    if (!callback) {
+      callback = opt;
+      opt = null;
+    }
+
+    opt = merge({}, marked.defaults, opt || {});
+
+    var highlight = opt.highlight,
+        tokens,
+        pending,
+        i = 0;
+
+    try {
+      tokens = Lexer.lex(src, opt);
+    } catch (e) {
+      return callback(e);
+    }
+
+    pending = tokens.length;
+
+    var done = function(err) {
+      if (err) {
+        opt.highlight = highlight;
+        return callback(err);
+      }
+
+      var out;
+
+      try {
+        out = Parser.parse(tokens, opt);
+      } catch (e) {
+        err = e;
+      }
+
+      opt.highlight = highlight;
+
+      return err
+        ? callback(err)
+        : callback(null, out);
+    };
+
+    if (!highlight || highlight.length < 3) {
+      return done();
+    }
+
+    delete opt.highlight;
+
+    if (!pending) return done();
+
+    for (; i < tokens.length; i++) {
+      (function(token) {
+        if (token.type !== 'code') {
+          return --pending || done();
+        }
+        return highlight(token.text, token.lang, function(err, code) {
+          if (err) return done(err);
+          if (code == null || code === token.text) {
+            return --pending || done();
+          }
+          token.text = code;
+          token.escaped = true;
+          --pending || done();
+        });
+      })(tokens[i]);
+    }
+
+    return;
+  }
+  try {
+    if (opt) opt = merge({}, marked.defaults, opt);
+    return Parser.parse(Lexer.lex(src, opt), opt);
+  } catch (e) {
+    e.message += '\nPlease report this to https://github.com/markedjs/marked.';
+    if ((opt || marked.defaults).silent) {
+      return '<p>An error occurred:</p><pre>'
+        + escape(e.message + '', true)
+        + '</pre>';
+    }
+    throw e;
+  }
+}
+
+/**
+ * Options
+ */
+
+marked.options =
+marked.setOptions = function(opt) {
+  merge(marked.defaults, opt);
+  return marked;
+};
+
+marked.getDefaults = function () {
+  return {
+    baseUrl: null,
+    breaks: false,
+    gfm: true,
+    headerIds: true,
+    headerPrefix: '',
+    highlight: null,
+    langPrefix: 'language-',
+    mangle: true,
+    pedantic: false,
+    renderer: new Renderer(),
+    sanitize: false,
+    sanitizer: null,
+    silent: false,
+    smartLists: false,
+    smartypants: false,
+    tables: true,
+    xhtml: false
+  };
+};
+
+marked.defaults = marked.getDefaults();
+
+/**
+ * Expose
+ */
+
+marked.Parser = Parser;
+marked.parser = Parser.parse;
+
+marked.Renderer = Renderer;
+marked.TextRenderer = TextRenderer;
+
+marked.Lexer = Lexer;
+marked.lexer = Lexer.lex;
+
+marked.InlineLexer = InlineLexer;
+marked.inlineLexer = InlineLexer.output;
+
+marked.Slugger = Slugger;
+
+marked.parse = marked;
+
+if (typeof module !== 'undefined' && typeof exports === 'object') {
+  module.exports = marked;
+} else if (typeof define === 'function' && define.amd) {
+  define(function() { return marked; });
+} else {
+  root.marked = marked;
+}
+})(this || (typeof window !== 'undefined' ? window : global));

+ 114 - 0
packages/markdown/marked/man/marked.1

@@ -0,0 +1,114 @@
+.ds q \N'34'
+.TH marked 1
+
+.SH NAME
+marked \- a javascript markdown parser
+
+.SH SYNOPSIS
+.B marked
+[\-o \fI<output>\fP] [\-i \fI<input>\fP] [\-\-help]
+[\-\-tokens] [\-\-pedantic] [\-\-gfm]
+[\-\-breaks] [\-\-tables] [\-\-sanitize]
+[\-\-smart\-lists] [\-\-lang\-prefix \fI<prefix>\fP]
+[\-\-no\-etc...] [\-\-silent] [\fIfilename\fP]
+
+.SH DESCRIPTION
+.B marked
+is a full-featured javascript markdown parser, built for speed.
+It also includes multiple GFM features.
+
+.SH EXAMPLES
+.TP
+cat in.md | marked > out.html
+.TP
+echo "hello *world*" | marked
+.TP
+marked \-o out.html \-i in.md \-\-gfm
+.TP
+marked \-\-output="hello world.html" \-i in.md \-\-no-breaks
+
+.SH OPTIONS
+.TP
+.BI \-o,\ \-\-output\ [\fIoutput\fP]
+Specify file output. If none is specified, write to stdout.
+.TP
+.BI \-i,\ \-\-input\ [\fIinput\fP]
+Specify file input, otherwise use last argument as input file.
+If no input file is specified, read from stdin.
+.TP
+.BI \-\-test
+Makes sure the test(s) pass.
+.RS
+.PP
+.B \-\-glob [\fIfile\fP]
+Specify which test to use.
+.PP
+.B \-\-fix
+Fixes tests.
+.PP
+.B \-\-bench
+Benchmarks the test(s).
+.PP
+.B \-\-time
+Times The test(s).
+.PP
+.B \-\-minified
+Runs test file(s) as minified.
+.PP
+.B \-\-stop
+Stop process if a test fails.
+.RE
+.TP
+.BI \-t,\ \-\-tokens
+Output a token stream instead of html.
+.TP
+.BI \-\-pedantic
+Conform to obscure parts of markdown.pl as much as possible.
+Don't fix original markdown bugs.
+.TP
+.BI \-\-gfm
+Enable github flavored markdown.
+.TP
+.BI \-\-breaks
+Enable GFM line breaks. Only works with the gfm option.
+.TP
+.BI \-\-tables
+Enable GFM tables. Only works with the gfm option.
+.TP
+.BI \-\-sanitize
+Sanitize output. Ignore any HTML input.
+.TP
+.BI \-\-smart\-lists
+Use smarter list behavior than the original markdown.
+.TP
+.BI \-\-lang\-prefix\ [\fIprefix\fP]
+Set the prefix for code block classes.
+.TP
+.BI \-\-mangle
+Mangle email addresses.
+.TP
+.BI \-\-no\-sanitize,\ \-no-etc...
+The inverse of any of the marked options above.
+.TP
+.BI \-\-silent
+Silence error output.
+.TP
+.BI \-h,\ \-\-help
+Display help information.
+
+.SH CONFIGURATION
+For configuring and running programmatically.
+
+.B Example
+
+    require('marked')('*foo*', { gfm: true });
+
+.SH BUGS
+Please report any bugs to https://github.com/markedjs/marked.
+
+.SH LICENSE
+Copyright (c) 2011-2014, Christopher Jeffrey (MIT License).
+
+.SH "SEE ALSO"
+.BR markdown(1),
+.BR node.js(1)

+ 99 - 0
packages/markdown/marked/man/marked.1.txt

@@ -0,0 +1,99 @@
+marked(1)		    General Commands Manual		     marked(1)
+
+NAME
+       marked - a javascript markdown parser
+
+SYNOPSIS
+       marked  [-o  <output>]  [-i  <input>]  [--help]  [--tokens]
+       [--pedantic]  [--gfm]  [--breaks]  [--tables]  [--sanitize]
+       [--smart-lists]  [--lang-prefix <prefix>]  [--no-etc...]  [--silent]
+       [filename]
+
+DESCRIPTION
+       marked is a full-featured javascript markdown parser, built for speed.
+       It also includes multiple GFM features.
+
+EXAMPLES
+       cat in.md | marked > out.html
+
+       echo "hello *world*" | marked
+
+       marked -o out.html -i in.md --gfm
+
+       marked --output="hello world.html" -i in.md --no-breaks
+
+OPTIONS
+       -o, --output [output]
+              Specify file output. If none is specified, write to stdout.
+
+       -i, --input [input]
+              Specify file input, otherwise use last argument as input file.
+              If no input file is specified, read from stdin.
+
+       --test Makes sure the test(s) pass.
+
+              --glob [file] Specify which test to use.
+
+              --fix Fixes tests.
+
+              --bench Benchmarks the test(s).
+
+              --time Times The test(s).
+
+              --minified Runs test file(s) as minified.
+
+              --stop Stop process if a test fails.
+
+       -t, --tokens
+              Output a token stream instead of html.
+
+       --pedantic
+              Conform to obscure parts of markdown.pl as much as possible.
+              Don't fix original markdown bugs.
+
+       --gfm  Enable github flavored markdown.
+
+       --breaks
+              Enable GFM line breaks. Only works with the gfm option.
+
+       --tables
+              Enable GFM tables. Only works with the gfm option.
+
+       --sanitize
+              Sanitize output. Ignore any HTML input.
+
+       --smart-lists
+              Use smarter list behavior than the original markdown.
+
+       --lang-prefix [prefix]
+              Set the prefix for code block classes.
+
+       --mangle
+              Mangle email addresses.
+
+       --no-sanitize, -no-etc...
+              The inverse of any of the marked options above.
+
+       --silent
+              Silence error output.
+
+       -h, --help
+              Display help information.
+
+CONFIGURATION
+       For configuring and running programmatically.
+
+       Example
+
+           require('marked')('*foo*', { gfm: true });
+
+BUGS
+       Please report any bugs to https://github.com/markedjs/marked.
+
+LICENSE
+       Copyright (c) 2011-2014, Christopher Jeffrey (MIT License).
+
+SEE ALSO
+       markdown(1), node.js(1)
+
+								     marked(1)

Diff do ficheiro suprimidas por serem muito extensas
+ 5 - 0
packages/markdown/marked/marked.min.js


+ 69 - 0
packages/markdown/marked/package.json

@@ -0,0 +1,69 @@
+{
+  "name": "marked",
+  "description": "A markdown parser built for speed",
+  "author": "Christopher Jeffrey",
+  "version": "0.6.2",
+  "main": "./lib/marked.js",
+  "bin": "./bin/marked",
+  "man": "./man/marked.1",
+  "files": [
+    "bin/",
+    "lib/",
+    "man/",
+    "marked.min.js"
+  ],
+  "repository": "git://github.com/markedjs/marked.git",
+  "homepage": "https://marked.js.org",
+  "bugs": {
+    "url": "http://github.com/markedjs/marked/issues"
+  },
+  "license": "MIT",
+  "keywords": [
+    "markdown",
+    "markup",
+    "html"
+  ],
+  "tags": [
+    "markdown",
+    "markup",
+    "html"
+  ],
+  "devDependencies": {
+    "@markedjs/html-differ": "^2.0.1",
+    "cheerio": "^1.0.0-rc.3",
+    "commonmark": "0.x",
+    "eslint": "^5.15.1",
+    "eslint-config-standard": "^12.0.0",
+    "eslint-plugin-import": "^2.16.0",
+    "eslint-plugin-node": "^8.0.1",
+    "eslint-plugin-promise": "^4.0.1",
+    "eslint-plugin-standard": "^4.0.0",
+    "eslint-plugin-vuln-regex-detector": "^1.0.4",
+    "front-matter": "^3.0.1",
+    "glob-to-regexp": "^0.4.0",
+    "jasmine": "^3.3.1",
+    "markdown": "0.x",
+    "markdown-it": "8.x",
+    "node-fetch": "^2.3.0",
+    "uglify-js": "^3.4.9"
+  },
+  "scripts": {
+    "test": "jasmine --config=jasmine.json",
+    "test:unit": "npm test -- test/unit/**/*-spec.js",
+    "test:specs": "npm test -- test/specs/**/*-spec.js",
+    "test:cm": "npm test -- test/specs/commonmark/**/*-spec.js",
+    "test:gfm": "npm test -- test/specs/gfm/**/*-spec.js",
+    "test:marked": "npm test -- test/specs/marked/**/*-spec.js",
+    "test:old": "node test",
+    "test:lint": "eslint bin/marked .",
+    "test:redos": "eslint --plugin vuln-regex-detector --rule '\"vuln-regex-detector/no-vuln-regex\": 2' lib/marked.js",
+    "test:node4": "npx node@4 ./node_modules/jasmine/bin/jasmine.js --config=jasmine.json",
+    "bench": "node test --bench",
+    "lint": "eslint --fix bin/marked .",
+    "build": "uglifyjs lib/marked.js -cm  --comments /Copyright/ -o marked.min.js",
+    "preversion": "npm run build && (git diff --quiet || git commit -am 'minify')"
+  },
+  "engines": {
+    "node": ">=0.10.0"
+  }
+}

+ 10 - 0
packages/markdown/marked/test/README

@@ -0,0 +1,10 @@
+In this directory:
+
+#
+# MarkdownTester -- Run tests for Markdown implementations
+#
+# Copyright (c) 2004-2005 John Gruber
+# <http://daringfireball.net/projects/markdown/>
+#
+
+Partially modified for testing purposes.

+ 5 - 0
packages/markdown/marked/test/browser/index.html

@@ -0,0 +1,5 @@
+<!doctype html>
+<title>marked tests</title>
+<p>testing...</p>
+<script src="marked.js"></script>
+<script src="test.js"></script>

+ 39 - 0
packages/markdown/marked/test/browser/index.js

@@ -0,0 +1,39 @@
+var fs = require('fs'),
+    path = require('path');
+
+var testMod = require('../'),
+    load = testMod.load;
+
+var express = require('express'),
+    app = express();
+
+var files = load();
+
+app.use(function(req, res, next) {
+  var setHeader = res.setHeader;
+  res.setHeader = function(name) {
+    switch (name) {
+      case 'Cache-Control':
+      case 'Last-Modified':
+      case 'ETag':
+        return;
+    }
+    return setHeader.apply(res, arguments);
+  };
+  next();
+});
+
+app.get('/test.js', function(req, res, next) {
+  var test = fs.readFileSync(path.join(__dirname, 'test.js'), 'utf8');
+  var testScript = test.replace('__TESTS__', JSON.stringify(files))
+    .replace('__MAIN__', testMod.runTests + '')
+    .replace('__LIBS__', testMod.testFile + '');
+
+  res.contentType('.js');
+  res.send(testScript);
+});
+
+app.use(express.static(path.join(__dirname, '/../../lib')));
+app.use(express.static(__dirname));
+
+app.listen(8080);

+ 66 - 0
packages/markdown/marked/test/browser/test.js

@@ -0,0 +1,66 @@
+
+;(function() {
+  var console = {},
+      files = __TESTS__; // eslint-disable-line no-undef
+
+  console.log = function(text) {
+    var args = Array.prototype.slice.call(arguments, 1),
+        i = 0;
+
+    text = text.replace(/%\w/g, function() {
+      return args[i++] || '';
+    });
+
+    if (window.console) window.console.log(text);
+    document.body.innerHTML += '<pre>' + escape(text) + '</pre>';
+  };
+
+  if (!Object.keys) {
+    Object.keys = function(obj) {
+      var out = [],
+          key;
+
+      for (key in obj) {
+        if (Object.prototype.hasOwnProperty.call(obj, key)) {
+          out.push(key);
+        }
+      }
+
+      return out;
+    };
+  }
+
+  if (!Array.prototype.forEach) {
+    // eslint-disable-next-line no-extend-native
+    Array.prototype.forEach = function(callback, context) {
+      for (var i = 0; i < this.length; i++) {
+        callback.call(context || null, this[i], i, this);
+      }
+    };
+  }
+
+  if (!String.prototype.trim) {
+    // eslint-disable-next-line no-extend-native
+    String.prototype.trim = function() {
+      return this.replace(/^\s+|\s+$/g, '');
+    };
+  }
+
+  // eslint-disable-next-line no-unused-vars
+  function load() {
+    return files;
+  }
+
+  function escape(html, encode) {
+    return html
+      .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
+      .replace(/</g, '&lt;')
+      .replace(/>/g, '&gt;')
+      .replace(/"/g, '&quot;')
+      .replace(/'/g, '&#39;');
+  }
+
+  __LIBS__; // eslint-disable-line no-undef, no-unused-expressions
+
+  (__MAIN__)(); // eslint-disable-line no-undef
+}).call(this);

+ 26 - 0
packages/markdown/marked/test/helpers/helpers.js

@@ -0,0 +1,26 @@
+const marked = require('../../');
+const htmlDiffer = require('./html-differ.js');
+
+beforeEach(() => {
+  marked.setOptions(marked.getDefaults());
+
+  jasmine.addMatchers({
+    toRender: () => {
+      return {
+        compare: (spec, expected) => {
+          const result = {};
+          const actual = marked(spec.markdown, spec.options);
+          result.pass = htmlDiffer.isEqual(expected, actual);
+
+          if (result.pass) {
+            result.message = `${spec.markdown}\n------\n\nExpected: Should Fail`;
+          } else {
+            const diff = htmlDiffer.firstDiff(actual, expected);
+            result.message = `Expected: ${diff.expected}\n  Actual: ${diff.actual}`;
+          }
+          return result;
+        }
+      };
+    }
+  });
+});

+ 38 - 0
packages/markdown/marked/test/helpers/html-differ.js

@@ -0,0 +1,38 @@
+const HtmlDiffer = require('@markedjs/html-differ').HtmlDiffer;
+const htmlDiffer = new HtmlDiffer({ignoreSelfClosingSlash: true});
+
+module.exports = {
+  isEqual: htmlDiffer.isEqual.bind(htmlDiffer),
+  firstDiff: (actual, expected, padding) => {
+    padding = padding || 30;
+    const result = htmlDiffer
+      .diffHtml(actual, expected)
+      .reduce((obj, diff) => {
+        if (diff.added) {
+          if (obj.firstIndex === null) {
+            obj.firstIndex = obj.expected.length;
+          }
+          obj.expected += diff.value;
+        } else if (diff.removed) {
+          if (obj.firstIndex === null) {
+            obj.firstIndex = obj.actual.length;
+          }
+          obj.actual += diff.value;
+        } else {
+          obj.actual += diff.value;
+          obj.expected += diff.value;
+        }
+
+        return obj;
+      }, {
+        firstIndex: null,
+        actual: '',
+        expected: ''
+      });
+
+    return {
+      actual: result.actual.substring(result.firstIndex - padding, result.firstIndex + padding),
+      expected: result.expected.substring(result.firstIndex - padding, result.firstIndex + padding)
+    };
+  }
+};

+ 551 - 0
packages/markdown/marked/test/index.js

@@ -0,0 +1,551 @@
+#!/usr/bin/env node
+'use strict';
+// 'use strict' is here so we can use let and const in node 4
+
+/**
+ * marked tests
+ * Copyright (c) 2011-2013, Christopher Jeffrey. (MIT Licensed)
+ * https://github.com/markedjs/marked
+ */
+
+/**
+ * Modules
+ */
+
+const fs = require('fs');
+const path = require('path');
+const fm = require('front-matter');
+const g2r = require('glob-to-regexp');
+let marked = require('../');
+const htmlDiffer = require('./helpers/html-differ.js');
+
+/**
+ * Load Tests
+ */
+
+function load(options) {
+  options = options || {};
+  const dir = path.join(__dirname, 'compiled_tests');
+  const glob = g2r(options.glob || '*', { extended: true });
+
+  const list = fs
+    .readdirSync(dir)
+    .filter(file => {
+      return path.extname(file) === '.md';
+    })
+    .sort();
+
+  const files = list.reduce((obj, item) => {
+    const name = path.basename(item, '.md');
+    if (glob.test(name)) {
+      const file = path.join(dir, item);
+      const content = fm(fs.readFileSync(file, 'utf8'));
+
+      obj[name] = {
+        options: content.attributes,
+        text: content.body,
+        html: fs.readFileSync(file.replace(/[^.]+$/, 'html'), 'utf8')
+      };
+    }
+    return obj;
+  }, {});
+
+  if (options.bench || options.time) {
+    if (!options.glob) {
+      // Change certain tests to allow
+      // comparison to older benchmark times.
+      fs.readdirSync(path.join(__dirname, 'new')).forEach(name => {
+        if (path.extname(name) === '.html') return;
+        if (name === 'main.md') return;
+        delete files[name];
+      });
+    }
+
+    if (files['backslash_escapes.md']) {
+      files['backslash_escapes.md'] = {
+        text: 'hello world \\[how](are you) today'
+      };
+    }
+
+    if (files['main.md']) {
+      files['main.md'].text = files['main.md'].text.replace('* * *\n\n', '');
+    }
+  }
+
+  return files;
+}
+
+/**
+ * Test Runner
+ */
+
+function runTests(engine, options) {
+  if (typeof engine !== 'function') {
+    options = engine;
+    engine = null;
+  }
+
+  engine = engine || marked;
+  options = options || {};
+
+  let succeeded = 0;
+  let failed = 0;
+  const files = options.files || load(options);
+  const filenames = Object.keys(files);
+
+  if (options.marked) {
+    marked.setOptions(options.marked);
+  }
+
+  for (let i = 0; i < filenames.length; i++) {
+    const filename = filenames[i];
+    const file = files[filename];
+
+    const success = testFile(engine, file, filename, i + 1);
+
+    if (success) {
+      succeeded++;
+    } else {
+      failed++;
+      if (options.stop) {
+        break;
+      }
+    }
+  }
+
+  console.log('\n%d/%d tests completed successfully.', succeeded, filenames.length);
+  if (failed) console.log('%d/%d tests failed.', failed, filenames.length);
+
+  return !failed;
+}
+
+/**
+ * Test a file
+ */
+
+function testFile(engine, file, filename, index) {
+  const opts = Object.keys(file.options);
+
+  if (marked._original) {
+    marked.defaults = marked._original;
+    delete marked._original;
+  }
+
+  console.log('#%d. Test %s', index, filename);
+
+  if (opts.length) {
+    marked._original = marked.defaults;
+    marked.defaults = {};
+    Object.keys(marked._original).forEach(key => {
+      marked.defaults[key] = marked._original[key];
+    });
+    opts.forEach(key => {
+      if (marked.defaults.hasOwnProperty(key)) {
+        marked.defaults[key] = file.options[key];
+      }
+    });
+  }
+
+  const before = process.hrtime();
+
+  let text, html, elapsed;
+  try {
+    text = engine(file.text);
+    html = file.html;
+  } catch (e) {
+    elapsed = process.hrtime(before);
+    console.log('\n    failed in %dms\n', prettyElapsedTime(elapsed));
+    throw e;
+  }
+
+  elapsed = process.hrtime(before);
+
+  if (htmlDiffer.isEqual(text, html)) {
+    if (elapsed[0] > 0) {
+      console.log('\n    failed because it took too long.\n\n    passed in %dms\n', prettyElapsedTime(elapsed));
+      return false;
+    }
+    console.log('    passed in %dms', prettyElapsedTime(elapsed));
+    return true;
+  }
+
+  const diff = htmlDiffer.firstDiff(text, html);
+
+  console.log('\n    failed in %dms', prettyElapsedTime(elapsed));
+  console.log('    Expected: %s', diff.expected);
+  console.log('      Actual: %s\n', diff.actual);
+  return false;
+}
+
+/**
+ * Benchmark a function
+ */
+
+function bench(name, files, engine) {
+  const start = Date.now();
+
+  for (let i = 0; i < 1000; i++) {
+    for (const filename in files) {
+      engine(files[filename].text);
+    }
+  }
+
+  const end = Date.now();
+
+  console.log('%s completed in %dms.', name, end - start);
+}
+
+/**
+ * Benchmark all engines
+ */
+
+function runBench(options) {
+  options = options || {};
+  const files = load(options);
+
+  // Non-GFM, Non-pedantic
+  marked.setOptions({
+    gfm: false,
+    tables: false,
+    breaks: false,
+    pedantic: false,
+    sanitize: false,
+    smartLists: false
+  });
+  if (options.marked) {
+    marked.setOptions(options.marked);
+  }
+  bench('marked', files, marked);
+
+  // GFM
+  marked.setOptions({
+    gfm: true,
+    tables: false,
+    breaks: false,
+    pedantic: false,
+    sanitize: false,
+    smartLists: false
+  });
+  if (options.marked) {
+    marked.setOptions(options.marked);
+  }
+  bench('marked (gfm)', files, marked);
+
+  // Pedantic
+  marked.setOptions({
+    gfm: false,
+    tables: false,
+    breaks: false,
+    pedantic: true,
+    sanitize: false,
+    smartLists: false
+  });
+  if (options.marked) {
+    marked.setOptions(options.marked);
+  }
+  bench('marked (pedantic)', files, marked);
+
+  try {
+    bench('commonmark', files, (() => {
+      const commonmark = require('commonmark');
+      const parser = new commonmark.Parser();
+      const writer = new commonmark.HtmlRenderer();
+      return function (text) {
+        return writer.render(parser.parse(text));
+      };
+    })());
+  } catch (e) {
+    console.log('Could not bench commonmark. (Error: %s)', e.message);
+  }
+
+  try {
+    bench('markdown-it', files, (() => {
+      const MarkdownIt = require('markdown-it');
+      const md = new MarkdownIt();
+      return md.render.bind(md);
+    })());
+  } catch (e) {
+    console.log('Could not bench markdown-it. (Error: %s)', e.message);
+  }
+
+  try {
+    bench('markdown.js', files, (() => {
+      const markdown = require('markdown').markdown;
+      return markdown.toHTML.bind(markdown);
+    })());
+  } catch (e) {
+    console.log('Could not bench markdown.js. (Error: %s)', e.message);
+  }
+
+  return true;
+}
+
+/**
+ * A simple one-time benchmark
+ */
+
+function time(options) {
+  options = options || {};
+  const files = load(options);
+  if (options.marked) {
+    marked.setOptions(options.marked);
+  }
+  bench('marked', files, marked);
+
+  return true;
+}
+
+/**
+ * Markdown Test Suite Fixer
+ *   This function is responsible for "fixing"
+ *   the markdown test suite. There are
+ *   certain aspects of the suite that
+ *   are strange or might make tests
+ *   fail for reasons unrelated to
+ *   conformance.
+ */
+
+function fix() {
+  ['compiled_tests', 'original', 'new', 'redos'].forEach(dir => {
+    try {
+      fs.mkdirSync(path.resolve(__dirname, dir));
+    } catch (e) {
+      // directory already exists
+    }
+  });
+
+  // rm -rf tests
+  fs.readdirSync(path.resolve(__dirname, 'compiled_tests')).forEach(file => {
+    fs.unlinkSync(path.resolve(__dirname, 'compiled_tests', file));
+  });
+
+  // cp -r original tests
+  fs.readdirSync(path.resolve(__dirname, 'original')).forEach(file => {
+    let text = fs.readFileSync(path.resolve(__dirname, 'original', file), 'utf8');
+
+    if (path.extname(file) === '.md') {
+      if (fm.test(text)) {
+        text = fm(text);
+        text = `---\n${text.frontmatter}\ngfm: false\n---\n${text.body}`;
+      } else {
+        text = `---\ngfm: false\n---\n${text}`;
+      }
+    }
+
+    fs.writeFileSync(path.resolve(__dirname, 'compiled_tests', file), text);
+  });
+
+  // node fix.js
+  const dir = path.join(__dirname, 'compiled_tests');
+
+  fs.readdirSync(dir).filter(file => {
+    return path.extname(file) === '.html';
+  }).forEach(file => {
+    file = path.join(dir, file);
+    let html = fs.readFileSync(file, 'utf8');
+
+    // fix unencoded quotes
+    html = html
+      .replace(/='([^\n']*)'(?=[^<>\n]*>)/g, '=&__APOS__;$1&__APOS__;')
+      .replace(/="([^\n"]*)"(?=[^<>\n]*>)/g, '=&__QUOT__;$1&__QUOT__;')
+      .replace(/"/g, '&quot;')
+      .replace(/'/g, '&#39;')
+      .replace(/&__QUOT__;/g, '"')
+      .replace(/&__APOS__;/g, '\'');
+
+    fs.writeFileSync(file, html);
+  });
+
+  // turn <hr /> into <hr>
+  fs.readdirSync(dir).forEach(file => {
+    file = path.join(dir, file);
+    let text = fs.readFileSync(file, 'utf8');
+
+    text = text.replace(/(<|&lt;)hr\s*\/(>|&gt;)/g, '$1hr$2');
+
+    fs.writeFileSync(file, text);
+  });
+
+  // markdown does some strange things.
+  // it does not encode naked `>`, marked does.
+  {
+    const file = `${dir}/amps_and_angles_encoding.html`;
+    const html = fs.readFileSync(file, 'utf8')
+      .replace('6 > 5.', '6 &gt; 5.');
+
+    fs.writeFileSync(file, html);
+  }
+
+  // cp new/* tests/
+  fs.readdirSync(path.resolve(__dirname, 'new')).forEach(file => {
+    fs.writeFileSync(path.resolve(__dirname, 'compiled_tests', file),
+      fs.readFileSync(path.resolve(__dirname, 'new', file)));
+  });
+
+  // cp redos/* tests/
+  fs.readdirSync(path.resolve(__dirname, 'redos')).forEach(file => {
+    fs.writeFileSync(path.resolve(__dirname, 'compiled_tests', file),
+      fs.readFileSync(path.resolve(__dirname, 'redos', file)));
+  });
+}
+
+/**
+ * Argument Parsing
+ */
+
+function parseArg(argv) {
+  argv = argv.slice(2);
+
+  const options = {};
+  const orphans = [];
+
+  function getarg() {
+    let arg = argv.shift();
+
+    if (arg.indexOf('--') === 0) {
+      // e.g. --opt
+      arg = arg.split('=');
+      if (arg.length > 1) {
+        // e.g. --opt=val
+        argv.unshift(arg.slice(1).join('='));
+      }
+      arg = arg[0];
+    } else if (arg[0] === '-') {
+      if (arg.length > 2) {
+        // e.g. -abc
+        argv = arg.substring(1).split('').map(ch => {
+          return `-${ch}`;
+        }).concat(argv);
+        arg = argv.shift();
+      } else {
+        // e.g. -a
+      }
+    } else {
+      // e.g. foo
+    }
+
+    return arg;
+  }
+
+  while (argv.length) {
+    let arg = getarg();
+    switch (arg) {
+      case '-f':
+      case '--fix':
+      case 'fix':
+        if (options.fix !== false) {
+          options.fix = true;
+        }
+        break;
+      case '--no-fix':
+      case 'no-fix':
+        options.fix = false;
+        break;
+      case '-b':
+      case '--bench':
+        options.bench = true;
+        break;
+      case '-s':
+      case '--stop':
+        options.stop = true;
+        break;
+      case '-t':
+      case '--time':
+        options.time = true;
+        break;
+      case '-m':
+      case '--minified':
+        options.minified = true;
+        break;
+      case '--glob':
+        arg = argv.shift();
+        options.glob = arg.replace(/^=/, '');
+        break;
+      default:
+        if (arg.indexOf('--') === 0) {
+          const opt = camelize(arg.replace(/^--(no-)?/, ''));
+          if (!marked.defaults.hasOwnProperty(opt)) {
+            continue;
+          }
+          options.marked = options.marked || {};
+          if (arg.indexOf('--no-') === 0) {
+            options.marked[opt] = typeof marked.defaults[opt] !== 'boolean'
+              ? null
+              : false;
+          } else {
+            options.marked[opt] = typeof marked.defaults[opt] !== 'boolean'
+              ? argv.shift()
+              : true;
+          }
+        } else {
+          orphans.push(arg);
+        }
+        break;
+    }
+  }
+
+  return options;
+}
+
+/**
+ * Helpers
+ */
+
+function camelize(text) {
+  return text.replace(/(\w)-(\w)/g, (_, a, b) => a + b.toUpperCase());
+}
+
+/**
+ * Main
+ */
+
+function main(argv) {
+  const opt = parseArg(argv);
+
+  if (opt.fix !== false) {
+    fix();
+  }
+
+  if (opt.fix) {
+    // only run fix
+    return;
+  }
+
+  if (opt.bench) {
+    return runBench(opt);
+  }
+
+  if (opt.time) {
+    return time(opt);
+  }
+
+  if (opt.minified) {
+    marked = require('../marked.min.js');
+  }
+  return runTests(opt);
+}
+
+/**
+ * Execute
+ */
+
+if (!module.parent) {
+  process.title = 'marked';
+  process.exit(main(process.argv.slice()) ? 0 : 1);
+} else {
+  exports = main;
+  exports.main = main;
+  exports.runTests = runTests;
+  exports.testFile = testFile;
+  exports.runBench = runBench;
+  exports.load = load;
+  exports.bench = bench;
+  module.exports = exports;
+}
+
+// returns time to millisecond granularity
+function prettyElapsedTime(hrtimeElapsed) {
+  const seconds = hrtimeElapsed[0];
+  const frac = Math.round(hrtimeElapsed[1] / 1e3) / 1e3;
+  return seconds * 1e3 + frac;
+}

+ 62 - 0
packages/markdown/marked/test/json-to-files.js

@@ -0,0 +1,62 @@
+const path = require('path');
+const fs = require('fs');
+
+const folder = process.argv[2];
+const jsonFile = process.argv[3];
+
+if (!folder || !jsonFile) {
+  console.log('node ./json-to-files.js {path to folder} {path to json file}');
+  process.exit(1);
+}
+
+const specs = require(jsonFile);
+
+const files = specs.reduce((obj, spec) => {
+  if (!obj[spec.section]) {
+    obj[spec.section] = {
+      md: [],
+      html: [],
+      options: {}
+    };
+  }
+
+  obj[spec.section].md.push(spec.markdown);
+  obj[spec.section].html.push(spec.html);
+  Object.assign(obj[spec.section].options, spec.options);
+
+  return obj;
+}, {});
+
+try {
+  fs.mkdirSync(folder, {recursive: true});
+} catch (ex) {
+  // already exists
+}
+
+for (const section in files) {
+  const file = files[section];
+  const name = section.toLowerCase().replace(' ', '_');
+  const frontMatter = Object.keys(file.options).map(opt => {
+    let value = file.options[opt];
+    if (typeof value !== 'string') {
+      value = JSON.stringify(value);
+    }
+    return `${opt}: ${value}`;
+  }).join('\n');
+
+  let markdown = file.md.join('\n\n');
+  if (frontMatter) {
+    markdown = `---\n${frontMatter}\n---\n\n${markdown}`;
+  }
+  const html = file.html.join('\n\n');
+
+  const mdFile = path.resolve(folder, `${name}.md`);
+  const htmlFile = path.resolve(folder, `${name}.html`);
+
+  if (fs.existsSync(mdFile) || fs.existsSync(htmlFile)) {
+    throw new Error(`${name} already exists.`);
+  }
+
+  fs.writeFileSync(mdFile, markdown);
+  fs.writeFileSync(htmlFile, html);
+}

+ 9 - 0
packages/markdown/marked/test/new/adjacent_lists.html

@@ -0,0 +1,9 @@
+<ul>
+<li>This should be</li>
+<li>An unordered list</li>
+</ul>
+
+<ol>
+<li>This should be</li>
+<li>An unordered list</li>
+</ol>

+ 5 - 0
packages/markdown/marked/test/new/adjacent_lists.md

@@ -0,0 +1,5 @@
+* This should be
+* An unordered list
+
+1. This should be
+2. An unordered list

+ 3 - 0
packages/markdown/marked/test/new/autolink_lines.html

@@ -0,0 +1,3 @@
+<p>hello world
+<a href="http://example.com">http://example.com</a>
+</p>

+ 2 - 0
packages/markdown/marked/test/new/autolink_lines.md

@@ -0,0 +1,2 @@
+hello world
+<http://example.com>

+ 15 - 0
packages/markdown/marked/test/new/autolinks.html

@@ -0,0 +1,15 @@
+<p>(See <a href="https://www.example.com/fhqwhgads">https://www.example.com/fhqwhgads</a>.)</p>
+
+<p>((<a href="http://foo.com">http://foo.com</a>))</p>
+
+<p>((<a href="http://foo.com">http://foo.com</a>.))</p>
+
+<p><a href="HTTP://FOO.COM">HTTP://FOO.COM</a></p>
+
+<p><a href="hTtP://fOo.CoM">hTtP://fOo.CoM</a></p>
+
+<p><del><a href="mailto:hello@email.com">hello@email.com</a></del></p>
+
+<p><strong><a href="mailto:me@example.com">me@example.com</a></strong></p>
+
+<p><strong><a href="mailto:test@test.com">test@test.com</a></strong></p>

+ 15 - 0
packages/markdown/marked/test/new/autolinks.md

@@ -0,0 +1,15 @@
+(See https://www.example.com/fhqwhgads.)
+
+((http://foo.com))
+
+((http://foo.com.))
+
+HTTP://FOO.COM
+
+hTtP://fOo.CoM
+
+~~hello@email.com~~
+
+**me@example.com**
+
+__test@test.com__

Alguns ficheiros não foram mostrados porque muitos ficheiros mudaram neste diff