Exemplo n.º 1
0
  const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
  return '<h' + level + ' id="' + escapedText +
    '" class="www-heading pb4 mb2 relative h3">' + text + '</h' + level +
    '>';
};
renderer.paragraph = function (text) {
  return '<p class="mb2 px1">' + text + '</p>';
};

const encodedTemplateRegexp = /\[\[\s*<.*?>([A-Za-z]*?)\s*(<.*?>)?(\.[A-Za-z]*)?\s*<\/span>\s*\]\]/g

marked.setOptions({
  highlight: function(code, lang) {
    if (lang) {
      return highlight(lang, code).value;
    } else {
      return S(code).escapeHTML().s;
    }
  }
});
const COMMENT_START = '<!--';
const COMMENT_END = '-->';
const HIDDEN_LINE_COUNT_THRESHOLD = 1;

module.exports = class CodeSection {

  constructor(doc, code, preview) {
    if (!arguments.length) {
      doc = '';
      code = '';
      preview = '';
Exemplo n.º 2
0
    headingId[id] = 1;
  }
  // add headerlink
  return '<h' + level + ' id="' + id + '"><a href="#' + id + '" class="headerlink" title="' + stripHTML(text) + '"></a>' + text + '</h' + level + '>';
};

function anchorId(str) {
  // Add support for Chinese
  return escape(str
    .replace(/\s+/g, '_')
    .replace(/\./g, '-')
    .replace(/-{2,}/g, '-')).replace(/%/g, '_').replace(/^[\-_]+|[\-_]+$/g, '');
}

marked.setOptions({
  langPrefix: '',
  highlight: function(code, lang) {
    return highlight(stripIndent(code), {
      lang: lang,
      gutter: false,
      wrap: false
    });
  }
});

module.exports = function(data, options) {
  return marked(data.text, assign({
    renderer: new Renderer()
  }, this.config.marked, options));
};
Exemplo n.º 3
0
"use strict"

var express = require('express');
var router = express.Router();
var assert = require('assert');
var marked = require('marked');
marked.setOptions({
	renderer: new marked.Renderer(),
	gfm: true,
	tables: true,
	breaks: false,
	pedantic: false,
	sanitize: true,
	smartLists: true,
	smartypants: false
});
var Article = require('../model/article');
var User = require('../model/user');
var Goingon = require('../model/goingon');
var tokenHandler = require('../tokenHandler');
var ossHelper = require('../helper/aliOss.js')
var dateFormat = require('../helper/dateExtension').format

// 
router.use(function (req, res, next) {
	let headers = req.headers;
    if (req._authorizationTokenInfo) {
    	next();	
    }else {
    	res.status(403).send()
Exemplo n.º 4
0
(function () {
    "use strict";

    var fs = require("fs"),
        mkdirp = require("mkdirp"),
        path = require("path"),
        glob = require("glob"),
        marked = require("marked"),
        split = require("split"),
        stream = require("stream"),
        nomnoml = require('nomnoml'),
        Canvas = require('canvas'),
        options = require("minimist")(process.argv.slice(2));

    // Convert from nomnoml source to a target PNG file.
    function renderNomnoml(source, target) {
        var canvas =
            new Canvas(CONSTANTS.DIAGRAM_WIDTH, CONSTANTS.DIAGRAM_HEIGHT);
        nomnoml.draw(canvas, source, 1.0);
        canvas.pngStream().pipe(fs.createWriteStream(target));
    }

    // Stream transform.
    // Pulls out nomnoml diagrams from fenced code blocks and renders them
    // as PNG files in the output directory, prefixed with a provided name.
    // The fenced code blocks will be replaced with Markdown in the
    // output of this stream.
    function nomnomlifier(outputDirectory, prefix) {
        var transform = new stream.Transform({ objectMode: true }),
            isBuilding = false,
            counter = 1,
            outputPath,
            source = "";

        transform._transform = function (chunk, encoding, done) {
            if (!isBuilding) {
                if (chunk.trim().indexOf("```nomnoml") === 0) {
                    var outputFilename = prefix + '-' + counter + '.png';
                    outputPath = path.join(outputDirectory, outputFilename);
                    this.push([
                        "\n![Diagram ",
                        counter,
                        "](",
                        outputFilename,
                        ")\n\n"
                    ].join(""));
                    isBuilding = true;
                    source = "";
                    counter += 1;
                } else {
                    // Otherwise, pass through
                    this.push(chunk + '\n');
                }
            } else {
                if (chunk.trim() === "```") {
                    // End nomnoml
                    renderNomnoml(source, outputPath);
                    isBuilding = false;
                } else {
                    source += chunk + '\n';
                }
            }
            done();
        };

        return transform;
    }

    // Convert from Github-flavored Markdown to HTML
    function gfmifier() {
        var transform = new stream.Transform({ objectMode: true }),
            markdown = "";
        transform._transform = function (chunk, encoding, done) {
            markdown += chunk;
            done();
        };
        transform._flush = function (done) {
            this.push("<html><body>\n");
            this.push(marked(markdown));
            this.push("\n</body></html>\n");
            done();
        };
        return transform;
    }

    // Custom renderer for marked; converts relative links from md to html,
    // and makes headings linkable.
    function CustomRenderer() {
        var renderer = new marked.Renderer(),
            customRenderer = Object.create(renderer);
        customRenderer.heading = function (text, level) {
            var escapedText = (text || "").trim().toLowerCase().replace(/\W/g, "-"),
                aOpen = "<a name=\"" + escapedText + "\" href=\"#" + escapedText + "\">",
                aClose = "</a>";
            return aOpen + renderer.heading.apply(renderer, arguments) + aClose;
        };
        // Change links to .md files to .html
        customRenderer.link = function (href, title, text) {
            // ...but only if they look like relative paths
            return (href || "").indexOf(":") === -1 && href[0] !== "/" ?
                renderer.link(href.replace(/\.md/, ".html"), title, text) :
                renderer.link.apply(renderer, arguments);
        };
        return customRenderer;
    }

    options['in'] = options['in'] || options.i;
    options.out = options.out || options.o;

    marked.setOptions({
        renderer: new CustomRenderer(),
        gfm: true,
        tables: true,
        breaks: false,
        pedantic: false,
        sanitize: true,
        smartLists: true,
        smartypants: false
    });

    // Convert all markdown files.
    // First, pull out nomnoml diagrams.
    // Then, convert remaining Markdown to HTML.
    glob(options['in'] + "/**/*.md", {}, function (err, files) {
        files.forEach(function (file) {
            var destination = file.replace(options['in'], options.out)
                .replace(/md$/, "html"),
                destPath = path.dirname(destination),
                prefix = path.basename(destination).replace(/\.html$/, "");

            mkdirp(destPath, function (err) {
                fs.createReadStream(file, { encoding: 'utf8' })
                    .pipe(split())
                    .pipe(nomnomlifier(destPath, prefix))
                    .pipe(gfmifier())
                    .pipe(fs.createWriteStream(destination, {
                        encoding: 'utf8'
                    }));
            });
        });
    });

    // Also copy over all HTML, CSS, or PNG files
    glob(options['in'] + "/**/*.@(html|css|png)", {}, function (err, files) {
        files.forEach(function (file) {
            var destination = file.replace(options['in'], options.out),
                destPath = path.dirname(destination);

            mkdirp(destPath, function (err) {
                fs.createReadStream(file, { encoding: 'utf8' })
                    .pipe(fs.createWriteStream(destination, {
                        encoding: 'utf8'
                    }));
            });
        });
    });

}());
Exemplo n.º 5
0
"use strict";
var marked = require('marked');
var Crypto = require('crypto');
var Nsh = require('node-syntaxhighlighter');

marked.setOptions({
  gfm: true,
  tables: true,
  breaks: true,
  smartLists: true,
  pedantic: false,
  sanitize: false, // To be able to add iframes 
  highlight: function (code, lang) {
    return Nsh.highlight(code, Nsh.getLanguage(lang || 'text'), {gutter: !!lang});
  }
});

var tagmap = {};

// Yields the content with the rendered [[bracket tags]]
// The rules are the same for Gollum https://github.com/github/gollum
function extractTags(text) {

  tagmap = {};

  var matches = text.match(/(.?)\[\[(.+?)\]\]([^\[]?)/g);
  var tag;
  var id;

  if (matches) {
    matches.forEach(function (match) {
Exemplo n.º 6
0
  Handlebars.registerHelper('compose', function(context, options) {
    options = _.extend(context, options);
    var hash = options.hash || {};

    // Default options
    options = _.extend({glob: {}, sep: '\n'}, options, opts.compose, hash);
    var i = 0;
    var result = '';
    var data;
    var ctx = _.extend(grunt.config.data, opts, this);

    // Define marked.js options
    marked.setOptions(markedOpts);

    // Add some src variables to the context
    ctx.dir = path.dirname(ctx.page.src || '');
    ctx.base = file.basename(ctx.page.src);

    var patterns = grunt.config.process(options.src);
    if(!Array.isArray(patterns)) {
       patterns = [patterns];
    }

    options.cwd = grunt.task.current.files[0].orig.cwd || options.cwd;
    var cwd = path.join.bind(null, options.cwd || '');
    // Recalculate cwd after ctx.dir has been added to context
    if(options.hash.cwd) {
      cwd = path.join.bind(null, grunt.config.process(options.hash.cwd));
    }

    /**
     * Accepts two objects (a, b),
     * @param  {Object} a
     * @param  {Object} b
     * @return {Number} returns 1 if (a >= b), otherwise -1
     */
    var compareFn = function (a, b) {
      var opts = _.extend({sortOrder: 'asc', sortBy: 'index'}, options);

      a = a.data[opts.sortBy];
      b = b.data[opts.sortBy];

      var result = 0;
      result = a > b ? 1 : a < b ? -1 : 0;
      if(opts.sortOrder.toLowerCase() === 'desc') {
        return result * -1;
      }
      return result;
    };

    patterns.forEach(function (pattern) {
      var files = glob.find(cwd(pattern), options.glob);

      if(options.filter) {
        files = options.filter(files);
      }

      var src = files.map(function (filepath) {

        i += 1;

        var content = yfm(filepath).content || '';
        var metadata = yfm(filepath).context || {};

        /**
         * Process context from last to first, with #1 winning over other contexts.
         * 1. `context`          : The given context (second parameter)
         * 2. `metadata`         : YAML front matter of the partial
         * 3. `opts.data[name]`  : JSON/YAML data file defined in Assemble options.data
         *                         with a basename matching the name of the partial, e.g
         *                         {{include 'foo'}} => foo.json
         * 4. `this`             : Typically either YAML front matter of the "inheriting" page,
         *                         layout, block expression, or "parent" helper wrapping this helper
         * 5. `opts`             : Custom properties defined in Assemble options
         * 6. `grunt.config.data`: Data from grunt.config.data
         *                         (e.g. pkg: grunt.file.readJSON('package.json'))
         */
        var basename = file.basename(filepath);
        ctx = _.extend(ctx, opts.data[ctx.base], opts.data[basename], metadata, context);

        // Process config (Lo-Dash) templates
        ctx = processContext(grunt, ctx);
        // Also process metadata separately so we can use it to extend the `data` object
        metadata = processContext(grunt, metadata);

        // Inject private variables into block, so that variables on `data`
        // are only available in the block helper's child template and
        // not in the original context
        data = Handlebars.createFrame(ctx.data);
        data = _.extend(data, opts.compose, _.omit(metadata, ['assemble', 'pages', 'plugins', '_plugins']));

        // Best guess at some useful properties to add to the data context
        data.filepath  = filepath;
        data.basename  = basename;
        data.filename  = file.filename(filepath);
        data.pagename  = file.filename(filepath);
        data.slug      = data.slug || _str.slugify(data.basename);
        data.id        = data.slug;
        data.title     = data.title || ctx.title || _str.titleize(data.basename);

        // Some of these might come in handy for ordering/sorting
        // or identifying posts, chapters, etc.
        data.index  = i;
        data.number = i + 1;
        data.first  = (i === 0);
        data.prev   = i - 1;
        data.next   = i + 1;
        data.last   = (i === (files.length - 1));

        // Content from src files
        var glob_fn = Handlebars.compile(content);
        data.content = glob_fn(ctx).replace(/^\s+/, '');

        if((opts.marked && opts.marked.process === true) || hash.markdown) {
          data.content = marked(data.content);
        }

        // Content from inside the block
        var output = options.fn(ctx, {data: data});

        // Prepend output with the filepath to the original partial
        if (options.origin && options.origin === true) {
          output = '<!-- ' + filepath + ' -->\n' + output;
        }

        return {
          data: data,
          content: output
        };
      }).sort(options.compare || compareFn).map(function (obj) {
        if(options.debug) {file.writeDataSync(options.debug, obj);}

        // Return content from src files
        return obj.content;
      }).join(options.sep);

      result += src;
    });
    return new Handlebars.SafeString(result);
  });
Exemplo n.º 7
0
  html += sanitize(text);
  html += '<a href="#' + name + '" class="anchor">';
  html += '<i class="fa fa-link"></i>';
  html += '</a>';
  html += '</h' + level + '>';
  return html;
};

// Set the options to use for rendering markdown
marked.setOptions({
  highlight: function (code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(lang, code).value;
    } else {
      return hljs.highlightAuto(code).value;
    }
  },
  renderer: renderer,
  gfm: true,
  tables: true,
  breaks: true,
  pedantic: false,
  sanitize: false, // we use sanitize-html to sanitize HTML
  smartLists: true,
  smartypants: false
});

exports.renderMd = function (text) {
  return marked(text);
};
Exemplo n.º 8
0
  exports.markdown = function(src, options, template) {

    var html = null;
    var templateContext = null;
    var codeLines = options.codeLines;
    var shouldWrap = codeLines && codeLines.before && codeLines.after;

    function wrapLines(code) {
      var out = [];
      var before = codeLines.before;
      var after = codeLines.after;
      code = code.split('\n');
      code.forEach(function(line) {
        out.push(before+line+after);
        });
      return out.join('\n');
    }

    if(typeof options.markdownOptions.highlight === 'string') {
      if(options.markdownOptions.highlight === 'auto') {
        options.highlight = function(code) {
          var out = hljs.highlightAuto(code).value;
          if(shouldWrap) {
            out = wrapLines(out);
          }
          return out;
        };
      } else if (options.markdownOptions.highlight === 'manual') {
        options.markdownOptions.highlight = function(code, lang) {
          var out = code;
          try {
            out = hljs.highlight(lang, code).value;
          } catch(e) {
            out = hljs.highlightAuto(code).value;
          }
          if(shouldWrap) {
            out = wrapLines(out);
          }
          return out;
        };
      }

    }

    markdown.setOptions(options.markdownOptions);

    grunt.verbose.write('Marking down...');

    if(_.isFunction(options.templateContext)) {
      templateContext = options.templateContext();
    } else {
      templateContext = options.templateContext;
    }

    src = options.preCompile(src, templateContext) || src;
    html = markdown(src);
    html = options.postCompile(html, templateContext) || html;

    templateContext.content = html;

    src = _.template(template, templateContext);
    return src;

  };
Exemplo n.º 9
0
const acquit = require('acquit');
const fs = require('fs');
const jade = require('jade');
const pkg = require('./package');
const linktype = require('./docs/helpers/linktype');
const href = require('./docs/helpers/href');
const klass = require('./docs/helpers/klass');
const transform = require('acquit-require');

require('acquit-ignore')();

const markdown = require('marked');
const highlight = require('highlight.js');
markdown.setOptions({
  highlight: function(code) {
    return highlight.highlight('JavaScript', code).value;
  }
});

jade.filters.markdown = markdown;

const tests = [
  ...acquit.parse(fs.readFileSync('./test/webpack.test.js').toString()),
  ...acquit.parse(fs.readFileSync('./test/geojson.test.js').toString()),
  ...acquit.parse(fs.readFileSync('./test/docs/transactions.test.js').toString()),
  ...acquit.parse(fs.readFileSync('./test/schema.alias.test.js').toString()),
  ...acquit.parse(fs.readFileSync('./test/model.middleware.test.js').toString()),
  ...acquit.parse(fs.readFileSync('./test/docs/date.test.js').toString()),
  ...acquit.parse(fs.readFileSync('./test/es-next/lean.test.es6.js').toString())
];
Exemplo n.º 10
0
import {Actions} from 'flummox';
import marked from 'marked';
import {highlightAuto} from 'highlight.js';

marked.setOptions({
  highlight: (code) => highlightAuto(code).value
});

class DirectoryActions extends Actions {

  /**
   * Fetches the directory structure and meta
   * data and applies the filter.
   * @param searchTerm
   * @returns {Promise}
   */
  fetchDirectory(searchTerm = '') {
    return new Promise((resolve) => {
      resolve(window.gon.directory, searchTerm);
    });
  }

  /**
   * Fetches the markdown from the md file and
   * and returns a promise with the rendered HTML.
   * @param route
   * @returns {Promise}
   */
  fetchDocument(route) {
    return window.fetch(route, {credentials: 'include'})
      .then((response) => {
Exemplo n.º 11
0
var cheerio = require('cheerio'),
	fs = require('fs'),
	path = require('path'),
	marked = require('marked');

marked.setOptions({

});

var idRegex = /[^\w]/g;

var setExtHeader1Regex = /^(.+)[ \t]*\r?\n=+[ \t]*(?:\r?\n)+/gm;
var setExtHeader2Regex = /^(.+)[ \t]*\r?\n-+[ \t]*(?:\r?\n)+/gm;

/*    /
	^(\#{1,6})      // $1 = string of #'s
		[ \t]*
	(.+?)           // $2 = Header text
	[ \t]*
	\#*             // optional closing #'s (not counted)
	\n+
	/gm */
var atxHeaderRegex = /^(\#{1,6})[ \t]*(.+?)[ \t]*\#*(?:\r?\n)+/gm;
var markdownHeaders = [
	'',
	"#",
	"##",
	"###",
	"####",
	"#####",
	"######"
Exemplo n.º 12
0
/* Markdown converter opts
 * Wrap each <code> into a <pre class=language-related>
 * Generate an example if language is not CSS or JS
 * Replace '<' and '>' html entities
 * Allow user to add options */

var hljs = require('highlight.js');
var mdConvert = require('marked');
var renderer = new mdConvert.Renderer();

mdConvert.setOptions({
	renderer: renderer,
	gfm: true,
	tables: true,
	smartLists: true
});

renderer.code = function (code, language) {
	var codeExample = '';
	var codeWrapped = '';

	if (language !== 'css' && language !== 'js')
		codeExample = code + '\n';

	code = hljs.highlightAuto(code).value;

	if (language !== 'esc')
		codeWrapped = '<pre class="code">' + '<code class="' + (language ? language : "") + '">' + code + '</code>' + '</pre>';

	return codeExample + codeWrapped;
};
Exemplo n.º 13
0
  constructor() {
    super();
    this.state = { markdown: `
# H1
## H2
### H3
#### H4
##### H5
###### H6

Alternatively, for H1 and H2, an underline-ish style:

Alt-H1
======

Alt-H2
------


Emphasis, aka italics, with *asterisks* or _underscores_.

Strong emphasis, aka bold, with **asterisks** or __underscores__.

Combined emphasis with **asterisks and _underscores_**.

Strikethrough uses two tildes. ~~Scratch this.~~


1. First ordered list item
2. Another item
  * Unordered sub-list.
1. Actual numbers don't matter, just that it's a number
  1. Ordered sub-list
4. And another item.

      You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown).

      To have a line break without a paragraph, you will need to use two trailing spaces.⋅⋅
      Note that this line is separate, but within the same paragraph.⋅⋅
      (This is contrary to the typical GFM line break behaviour, where trailing spaces are not required.)

* Unordered list can use asterisks
- Or minuses
+ Or pluses

[I'm an inline-style link](https://www.google.com)

[I'm an inline-style link with title](https://www.google.com "Google's Homepage")

[I'm a reference-style link][Arbitrary case-insensitive reference text]

[I'm a relative reference to a repository file](../blob/master/LICENSE)

[You can use numbers for reference-style link definitions][1]

Or leave it empty and use the [link text itself].

URLs and URLs in angle brackets will automatically get turned into links.
http://www.example.com or <http://www.example.com> and sometimes
example.com (but not on Github, for example).

Some text to show that the reference links can follow later.

[arbitrary case-insensitive reference text]: https://www.mozilla.org
[1]: http://slashdot.org
[link text itself]: http://www.reddit.com

Here's our logo (hover to see the title text):

Inline-style:
![alt text](https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png "Logo Title Text 1")

Reference-style:
![alt text][logo]

[logo]: https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png "Logo Title Text 2"


Inline \`code\` has \`back-ticks around\` it.


\`\`\`javascript
var s = "JavaScript syntax highlighting";
alert(s);
\`\`\`


Colons can be used to align columns.

| Tables        | Are           | Cool  |
| ------------- |:-------------:| -----:|
| col 3 is      | right-aligned | $1600 |
| col 2 is      | centered      |   $12 |
| zebra stripes | are neat      |    $1 |

There must be at least 3 dashes separating each header cell.
The outer pipes (|) are optional, and you don't need to make the
raw Markdown line up prettily. You can also use inline Markdown.

Markdown | Less | Pretty
--- | --- | ---
*Still* | \`renders\` | **nicely**
1 | 2 | 3



> Blockquotes are very handy in email to emulate reply text.
> This line is part of the same quote.

Quote break.

> This is a very long line that will still be quoted properly when it wraps. Oh boy let's keep writing to make sure this is long enough to actually wrap for everyone. Oh, you can *put* **Markdown** into a blockquote.


<dl>
  <dt>Definition list</dt>
  <dd>Is something people use sometimes.</dd>

  <dt>Markdown in HTML</dt>
  <dd>Does *not* work **very** well. Use HTML <em>tags</em>.</dd>
</dl>


Three or more...

---

Hyphens

***

Asterisks

___

Underscores


[![IMAGE ALT TEXT HERE](http://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg)](http://www.youtube.com/watch?v=YOUTUBE_VIDEO_ID_HERE)
      `};
    Marked.setOptions({
      gfm: true
    });
  }
Exemplo n.º 14
0
var Path = require('path'),
    Url = require('url'),
    Fs = require('fs'),
    Crypto = require('crypto'),
    Glob = require('glob'),
    Promise = require('lie'),
    FrontMatter = require('yaml-front-matter'),
    marked = require('marked'),
    assign = require('object-assign'),
    join = require('../../utils/join-results');

marked.setOptions({
  gfm: true,
  tables: true,
  breaks: true,
  pedantic: false,
  sanitize: true,
  smartLists: true,
  smartypants: true
});

function loadPage(path, options) {
    var filePath = Path.resolve(options.pagesPath, path);
    var $ = new Promise(function(resolve, reject) {
        Fs.readFile(filePath, 'utf8', function(err, data) {
            if (err) throw err;
            var md5 = Crypto.createHash('md5').update(data).digest('hex');
            var doc = FrontMatter.loadFront(data);
            var docPath = path.replace(Path.extname(path), '');
            doc.content = marked(doc.__content);
            doc.path = Url.resolve('/', docPath);
Exemplo n.º 15
0
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

var fs = require('fs')
  , md = require('marked')
  , hljs = require('highlight.js');

var BRANCH = 'v0.11';

md.setOptions({
  gfm: true
, pedantic: false
, highlight: function (code, lang) {
    return hljs.highlightAuto(code).value;
  }
});

var Main = function () {

  this.index = function (req, resp, params) {
    this.respond(params, {
      format: 'html'
    , template: 'app/views/main/index'
    });
  };

  this.documentation = function (req, resp, params) {
    this.respond(params, {
Exemplo n.º 16
0
module.exports = function(app, config, storage) {
	search.configureStorage(storage)

	Handlebars.registerPartial('entry', fs.readFileSync(require.resolve('./GUI/entry.hbs'), 'utf8'));
	var template = Handlebars.compile(fs.readFileSync(require.resolve('./GUI/index.hbs'), 'utf8'));

	app.get('/', function(req, res, next) {
		res.setHeader('Content-Type', 'text/html');

		storage.get_local(function(err, packages) {
			res.send(template({
				name:       config.web.title || "Sinopia",
				packages:   packages,
				baseUrl:    config.url_prefix || req.protocol + '://' + req.get('host') + '/'
			}));
		});
	});

	// Static
	app.get('/-/static/:filename', function(req, res, next) {
		var file = __dirname + '/static/' + req.params.filename
		fs.exists(file, function(exists) {
			if (exists) {
				res.sendfile(file)
			} else {
				res.status(404);
				res.send("File Not Found")
			}
		})
	})

	app.get('/-/logo', function(req, res, next) {
		res.sendfile(config.web.logo ? config.web.logo : __dirname + "/static/logo.png")
	})

	app.get('/-/logo-sm', function(req, res, next) {
		res.sendfile(config.web.logosm ? config.web.logosm : __dirname + "/static/logo-sm.png")
	})

	// Search
	app.get('/-/search/:anything', function(req, res, next) {
		var results = search.query(req.params.anything),
			packages = []

		var getData = function(i) {
			storage.get_package(results[i].ref, function(err, entry) {
				if (entry) {
					packages.push(entry.versions[entry['dist-tags'].latest])
				}

				if (i >= results.length - 1) {
					res.send(packages)
				} else {
					getData(i + 1)
				}
			})
		}

		if (results.length) {
			getData(0);
		} else {
			res.send([])
		}
	})

	// Readme
	marked.setOptions({
		highlight: function (code) {
			return require('highlight.js').highlightAuto(code).value
		}
	})

	app.get('/-/readme/:package/:version?', function(req, res, next) {
		storage.get_package(req.params.package, {req: req}, function(err, info) {
			if (err) return next(err)
			res.send(marked(info.readme || 'ERROR: No README data found!'))
		})
	})
}
Exemplo n.º 17
0
/**
 * Created by MihaiCotizo on 5/10/2014.
 */

var Article = require('../Article');
var marked = require('marked');
marked.setOptions({
    sanitize: true
});

function home(db) {
    return function (req, res) {
        var LIMIT = 10;
        var page = req.query.page ? req.query.page : 1;
        var toSkip = (page - 1) * LIMIT;
        Article.count(function (err, count) {
            if (err) { console.error(err); res.send(400); return; }
            Article.find().sort('-date').skip(toSkip).limit(LIMIT).exec(function (err, articles) {
                if (err) {
                    console.error(err);
                    res.send(404);
                    return;
                }

                articles = articles.map(function (x) {
                    x.content = marked(x.content);
                    return x;
                });
                var isFirst = page == 1;
                var prev = !isFirst ? page - 1 : "#";
                var isLast = toSkip + LIMIT >= count;
Exemplo n.º 18
0
  grunt.registerTask('blog', 'Compile Grunt Blog', function () {
    grunt.log.ok('Generating blog...');

    // Set default marked options
    marked.setOptions({
      gfm:true,
      anchors:true,
      base:'/',
      pedantic:false,
      sanitize:true,
      // callback for code highlighter
      highlight:function (code) {
        return highlighter.highlight('javascript', code).value;
      }
    });

    var names,
      shortList = [],
      articleList = [],
      base = 'tmp/wiki/',
      files = grunt.file.expand({cwd:base}, ['Blog-*.md']);

    names = files.map(function (name) {
      return name.substring(5, name.length - 3);
    }).reverse();

    // REVERSE the list, generate short article list
    files.reverse().forEach(function (file, i) {
      var name = names[i],
        postTitle = name.substring(10, name.length).replace(/-/g, ' '),
        postDate = name.substring(0, 10),
        destName = name.toLowerCase();

      articleList.push({
        url:destName,
        title:postTitle,
        postDate:blog.formatDate(postDate)
      });
    });

    files.forEach(function (file, i) {

      var name = names[i],
        postTitle = name.substring(10, name.length).replace(/-/g, ' '),
        postDate = name.substring(0, 10),
        destName = name.toLowerCase(),
        src = base + file,
        dest = 'build/blog/' + destName + '.html';

      grunt.file.copy(src, dest, {
        process:function (src) {
          var file = 'src/tmpl/blog.jade',
            templateData = {
              page:'news',
              singlePost:true,
              url:destName,
              title:postTitle,
              postDate:blog.formatDate(postDate),
              postRawDate:postDate,
              articleList:articleList,
              content:marked(src),
              rawSrc:src
            };
          shortList.push(templateData);

          return jade.compile(grunt.file.read(file), {filename:file})(templateData);
        }
      });
    });

    /**
     * Generate the blog page with a list of posts
     */
    grunt.log.ok('Generating blog front page..');
    var blogTpl = 'src/tmpl/blog.jade';
    var blogOut = jade.compile(grunt.file.read(blogTpl), {filename:blogTpl})({
      page:'blog',
      title:'The Grunt Blog',
      content:shortList,
      articleList:articleList
    });
    grunt.file.write('build/blog.html', blogOut);

    /**
     * Generate the RSS feed
     */
    grunt.log.ok('Generating rss feed...');
    // remove anchors from RSS setting
    marked.setOptions({
      anchors:false
    });
    // generate the feed items with different 'marked' settings
    shortList.forEach(function (item) {
      item.rssSrc = marked(item.rawSrc);
      item.atomId = blog.atomIDnTimeStampChurner(item.url, item.postRawDate);
    });
    var rssTpl = 'src/tmpl/rss.jade';
    var rssOut = jade.compile(grunt.file.read(rssTpl), {filename:rssTpl})({
      page:'rss',
      posts:shortList
    });
    grunt.file.write('build/atom.xml', rssOut);

    /**
     * Generate the front page
     */
    grunt.log.ok('Generating the front page...');
    var indexTpl = 'src/tmpl/index.jade';
    var indexOut = jade.compile(grunt.file.read(indexTpl), {filename:indexTpl})({
      page:'index',
      news:shortList.splice(0, 5)
    });
    grunt.file.write('build/index.html', indexOut);
  });
Exemplo n.º 19
0
module.exports = function(config_hash) {
	var config = new Config(config_hash)
	  , storage = new Storage(config);

	search.configureStorage(storage);

	var can = function(action) {
		return function(req, res, next) {
			if (config['allow_'+action](req.params.package, req.remoteUser)) {
				next()
			} else {
				if (!req.remoteUser) {
					if (req.remoteUserError) {
						var message = "can't "+action+' restricted package, ' + req.remoteUserError
					} else {
						var message = "can't "+action+" restricted package without auth, did you forget 'npm set always-auth true'?"
					}
					next(new UError({
						status: 403,
						message: message,
					}))
				} else {
					next(new UError({
						status: 403,
						message: 'user '+req.remoteUser+' not allowed to '+action+' it'
					}))
				}
			}
		}
	}

	var app = express()

	// run in production mode by default, just in case
	// it shouldn't make any difference anyway
	app.set('env', process.env.NODE_ENV || 'production')

	function error_reporting_middleware(req, res, next) {
		var calls = 0
		res.report_error = res.report_error || function(err) {
			calls++
			if (err.status && err.status >= 400 && err.status < 600) {
				if (calls == 1) {
					res.status(err.status)
					res.send({error: err.message || 'unknown error'})
				}
			} else {
				Logger.logger.error({err: err}, 'unexpected error: @{!err.message}\n@{err.stack}')
				if (!res.status || !res.send) {
					Logger.logger.error('this is an error in express.js, please report this')
					res.destroy()
				} else if (calls == 1) {
					res.status(500)
					res.send({error: 'internal server error'})
				} else {
					// socket should be already closed
				}
			}
		}
		next()
	}

	app.use(error_reporting_middleware)
	app.use(Middleware.log_and_etagify)
	app.use(function(req, res, next) {
		res.setHeader('X-Powered-By', config.user_agent)
		next()
	})
	app.use(Cats.middleware)
	app.use(basic_auth(function(user, pass, cb) {
		config.authenticate(user, pass, cb)
	}))
	app.use(express.json({strict: false, limit: config.max_body_size || '10mb'}))
	app.use(express.compress())
	app.use(Middleware.anti_loop(config))

	// validate all of these params as a package name
	// this might be too harsh, so ask if it causes trouble
	app.param('package', validate_name)
	app.param('filename', validate_name)
	app.param('tag', validate_name)
	app.param('version', validate_name)
	app.param('revision', validate_name)

	// these can't be safely put into express url for some reason
	app.param('_rev', match(/^-rev$/))
	app.param('org_couchdb_user', match(/^org\.couchdb\.user:/))
	app.param('anything', match(/.*/))

/*  app.get('/-/all', function(req, res) {
		var https = require('https')
		var JSONStream = require('JSONStream')
		var request = require('request')({
			url: 'https://registry.npmjs.org/-/all',
		})
		.pipe(JSONStream.parse('*'))
		.on('data', function(d) {
			console.log(d)
		})
	})*/
	
	Handlebars.registerPartial('entry', fs.readFileSync(require.resolve('./GUI/entry.hbs'), 'utf8'));
	var template = Handlebars.compile(fs.readFileSync(require.resolve('./GUI/index.hbs'), 'utf8'));

	app.get('/', can('access'), function(req, res, next) {
		res.setHeader('Content-Type', 'text/html');

		storage.get_local(function(err, packages) {
			res.send(template({
				name:       config.title || "Sinopia",
				packages:   packages,
				baseUrl:    config.url_prefix || req.protocol + '://' + req.get('host') + '/'
			}));
		});
	});

	// TODO: anonymous user?
	app.get('/:package/:version?', can('access'), function(req, res, next) {
		storage.get_package(req.params.package, {req: req}, function(err, info) {
			if (err) return next(err)
			info = utils.filter_tarball_urls(info, req, config)

			var version = req.params.version
			  , t
			if (!version) {
				return res.send(info)
			}

			if ((t = utils.get_version(info, version)) != null) {
				return res.send(t)
			}

			if (info['dist-tags'] != null) {
				if (info['dist-tags'][version] != null) {
					version = info['dist-tags'][version]
					if ((t = utils.get_version(info, version)) != null) {
						return res.send(t)
					}
				}
			}

			return next(new UError({
				status: 404,
				message: 'version not found: ' + req.params.version
			}))
		})
	})

	app.get('/:package/-/:filename', can('access'), function(req, res, next) {
		var stream = storage.get_tarball(req.params.package, req.params.filename)
		stream.on('content-length', function(v) {
			res.header('Content-Length', v)
		})
		stream.on('error', function(err) {
			return res.report_error(err)
		})
		res.header('Content-Type', 'application/octet-stream')
		stream.pipe(res)
	})

	// searching packages
	app.get('/-/all/:anything?', function(req, res, next) {
		storage.search(req.param.startkey || 0, {req: req}, function(err, result) {
			if (err) return next(err)
			for (var pkg in result) {
				if (!config.allow_access(pkg, req.remoteUser)) {
					delete result[pkg]
				}
			}
			return res.send(result)
		})
	})

	//app.get('/*', function(req, res) {
	//  proxy.request(req, res)
	//})

	// placeholder 'cause npm require to be authenticated to publish
	// we do not do any real authentication yet
	app.post('/_session', cookies.express(), function(req, res) {
		res.cookies.set('AuthSession', String(Math.random()), {
			// npmjs.org sets 10h expire
			expires: new Date(Date.now() + 10*60*60*1000)
		})
		res.send({'ok':true,'name':'somebody','roles':[]})
	})

	app.get('/-/user/:org_couchdb_user', function(req, res, next) {
		res.status(200)
		return res.send({
			ok: 'you are authenticated as "' + req.remoteUser + '"',
		})
	})

	app.put('/-/user/:org_couchdb_user/:_rev?/:revision?', function(req, res, next) {
		if (req.remoteUser != null) {
			res.status(201)
			return res.send({
				ok: 'you are authenticated as "' + req.remoteUser + '"',
			})
		} else {
			if (typeof(req.body.name) !== 'string' || typeof(req.body.password) !== 'string') {
				return next(new UError({
					status: 400,
					message: 'user/password is not found in request (npm issue?)',
				}))
			}
			config.add_user(req.body.name, req.body.password, function(err) {
				if (err) {
					if (err.status < 500 && err.message === 'this user already exists') {
						// with npm registering is the same as logging in
						// so we replace message in case of conflict
						return next(new UError({
							status: 409,
							message: 'bad username/password, access denied'
						}))
					}
					return next(err)
				}

				res.status(201)
				return res.send({
					ok: 'user "' + req.body.name + '" created',
				})
			})
		}
	})

	// Static
	app.get('/-/static/:file', function(req, res, next) {
		var file = __dirname + '/static/' + req.params.file;
		fs.exists(file, function(exists) {
			if(exists) {
				res.sendfile(file);
			}
			else {
				res.status(404);
				res.send("File Not Found");
			}
		});
	});

	app.get('/-/logo', function(req, res, next) {
		res.sendfile(config.logo ? config.logo : __dirname + "/static/logo.png");
	});

	// Search
	app.get('/-/search/:query', function(req, res, next) {
		var results = search.query(req.params.query),
			packages = [];

		var getData = function(i) {
			storage.get_package(results[i].ref, function(err, entry) {
				if(entry) {
					packages.push(entry.versions[entry['dist-tags'].latest]);
				}

				if(i >= results.length - 1) {
					res.send(packages);
				}
				else {
					getData(i + 1);
				}
			});
		};

		if(results.length) {
			getData(0);
		}
		else {
			res.send([]);
		}
	});

	// Readme
	marked.setOptions({
	  highlight: function (code) {
		return require('highlight.js').highlightAuto(code).value;
	  }
	});

	app.get('/-/readme/:name/:version', function(req, res, next) {
		storage.get_readme(req.params.name, req.params.version, function(readme) {
			res.send(marked(readme));
		});
	});

	// tagging a package
	app.put('/:package/:tag', can('publish'), media('application/json'), function(req, res, next) {
		if (typeof(req.body) !== 'string') return next('route')

		var tags = {}
		tags[req.params.tag] = req.body
		storage.add_tags(req.params.package, tags, function(err) {
			if (err) return next(err)
			res.status(201)
			return res.send({
				ok: 'package tagged'
			})
		})
	})

	// publishing a package
	app.put('/:package/:_rev?/:revision?', can('publish'), media('application/json'), expect_json, function(req, res, next) {
		var name = req.params.package

		if (Object.keys(req.body).length == 1 && utils.is_object(req.body.users)) {
			return next(new UError({
				// 501 status is more meaningful, but npm doesn't show error message for 5xx
				status: 404,
				message: 'npm star|unstar calls are not implemented',
			}))
		}

		try {
			var metadata = utils.validate_metadata(req.body, name)
		} catch(err) {
			return next(new UError({
				status: 422,
				message: 'bad incoming package data',
			}))
		}

		if (req.params._rev) {
			storage.change_package(name, metadata, req.params.revision, function(err) {
				after_change(err, 'package changed')
			})
		} else {
			storage.add_package(name, metadata, function(err) {
				after_change(err, 'created new package')
			})
		}

		function after_change(err, ok_message) {
			// old npm behaviour
			if (metadata._attachments == null) {
				if (err) return next(err)
				res.status(201)
				return res.send({
					ok: ok_message
				})
			}

			// npm-registry-client 0.3+ embeds tarball into the json upload
			// https://github.com/isaacs/npm-registry-client/commit/e9fbeb8b67f249394f735c74ef11fe4720d46ca0
			// issue #31, dealing with it here:

			if (typeof(metadata._attachments) != 'object'
			||  Object.keys(metadata._attachments).length != 1
			||  typeof(metadata.versions) != 'object'
			||  Object.keys(metadata.versions).length != 1) {

				// npm is doing something strange again
				// if this happens in normal circumstances, report it as a bug
				return next(new UError({
					status: 400,
					message: 'unsupported registry call',
				}))
			}

			if (err && err.status != 409) return next(err)

			// at this point document is either created or existed before
			var t1 = Object.keys(metadata._attachments)[0]
			create_tarball(t1, metadata._attachments[t1], function(err) {
				if (err) return next(err)

				var t2 = Object.keys(metadata.versions)[0]
				create_version(t2, metadata.versions[t2], function(err) {
					if (err) return next(err)

					add_tags(metadata['dist-tags'], function(err) {
						if (err) return next(err)

						res.status(201)
						return res.send({
							ok: ok_message
						})
					})
				})
			})
		}

		function create_tarball(filename, data, cb) {
			var stream = storage.add_tarball(name, filename)
			stream.on('error', function(err) {
				cb(err)
			})
			stream.on('success', function() {
				cb()
			})

			// this is dumb and memory-consuming, but what choices do we have?
			stream.end(new Buffer(data.data, 'base64'))
			stream.done()
		}

		function create_version(version, data, cb) {
			storage.add_version(name, version, data, null, cb)
		}

		function add_tags(tags, cb) {
			storage.add_tags(name, tags, cb)
		}
	})

	// unpublishing an entire package
	app.delete('/:package/-rev/*', can('publish'), function(req, res, next) {
		storage.remove_package(req.params.package, function(err) {
			if (err) return next(err)
			res.status(201)
			return res.send({
				ok: 'package removed'
			})
		})
	})

	// removing a tarball
	app.delete('/:package/-/:filename/-rev/:revision', can('publish'), function(req, res, next) {
		storage.remove_tarball(req.params.package, req.params.filename, req.params.revision, function(err) {
			if (err) return next(err)
			res.status(201)
			return res.send({
				ok: 'tarball removed'
			})
		})
	})

	// uploading package tarball
	app.put('/:package/-/:filename/*', can('publish'), media('application/octet-stream'), function(req, res, next) {
		var name = req.params.package

		var stream = storage.add_tarball(name, req.params.filename)
		req.pipe(stream)

		// checking if end event came before closing
		var complete = false
		req.on('end', function() {
			complete = true
			stream.done()
		})
		req.on('close', function() {
			if (!complete) {
				stream.abort()
			}
		})

		stream.on('error', function(err) {
			return res.report_error(err)
		})
		stream.on('success', function() {
			res.status(201)
			return res.send({
				ok: 'tarball uploaded successfully'
			})
		})
	})

	// adding a version
	app.put('/:package/:version/-tag/:tag', can('publish'), media('application/json'), expect_json, function(req, res, next) {
		var name = req.params.package
		  , version = req.params.version
		  , tag = req.params.tag

		storage.add_version(name, version, req.body, tag, function(err) {
			if (err) return next(err)
			res.status(201)
			return res.send({
				ok: 'package published'
			})
		})
	})

	app.use(app.router)
	app.use(function(err, req, res, next) {
		if (typeof(res.report_error) !== 'function') {
			// in case of very early error this middleware may not be loaded before error is generated
			// fixing that
			error_reporting_middleware(req, res, function(){})
		}
		res.report_error(err)
	})

	return app
}
Exemplo n.º 20
0
var Backbone = require('backbone')
var _ = require('underscore')
var React = require('react')
var Flasher = require('./flash.js')
var marked = require('marked')

window.$ = Backbone.$ = $;

// Set up marker

var renderer = new marked.Renderer()
renderer.codespan = function (html) { // Don't consider codespans in markdown (they're actually 'latex')
	return '`'+html+'`';
}
marked.setOptions({ renderer: renderer })

/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
// Cookies util

function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = '; expires='+date.toGMTString();
	}
	else var expires = '';
	document.cookie = name+'='+value+expires+'; path=/';
}
Exemplo n.º 21
0
    /**
     * generate the docs based on the github wiki
     */
    function generateDocs() {
      // marked markdown parser
      var marked = require('marked');
      // Set default marked options
      marked.setOptions({
        gfm:true,
        anchors: true,
        base: "/",
        pedantic:false,
        sanitize:true,
        // callback for code highlighter
        highlight:function (code) {
          return highlighter.highlight('javascript', code).value;
        }
      });

      // grunt guides - wiki articles that are not part of the grunt api
      generateGuides();

      // grunt api docs - wiki articles that start with 'grunt.*'
      generateAPI();

      done(true);


      /**
       *
       * Helper Functions
       *
       */

      /**
       * Generate grunt guides documentation
       */
      function generateGuides() {
        grunt.log.ok('Generating Guides...');

        // API Docs
        var sidebars = [],
          base = 'tmp/wiki/',
          names = grunt.file.expand({cwd:base}, ['*', '!Blog-*', '!grunt*.md', '!*.js']);

          sidebars[0] = getSidebarSection('## Documentation', 'icon-document-alt-stroke');
          sidebars[1] = getSidebarSection('### Advanced');
          sidebars[2] = getSidebarSection('### Community');
          sidebars[3] = getSidebarSection('### Migration guides');

        names.forEach(function (name) {

          var title = name.replace(/-/g,' ').replace('.md', ''),
            segment = name.replace(/ /g,'-').replace('.md', '').toLowerCase(),
            src = base + name,
            dest = 'build/docs/' + name.replace('.md', '').toLowerCase() + '.html';

          grunt.file.copy(src, dest, {
            process:function (src) {
              try {
                var file = 'src/tmpl/docs.jade',
                  templateData = {
                    page:'docs',
                    rootSidebar: true,
                    pageSegment: segment,
                    title:title,
                    content: docs.anchorFilter( marked( docs.wikiAnchors(src) ) ),
                    sidebars: sidebars
                  };
                return jade.compile(grunt.file.read(file), {filename:file})(templateData);
              } catch (e) {
                grunt.log.error(e);
                grunt.fail.warn('Jade failed to compile.');
              }
            }
          });
        });
        grunt.log.ok('Created ' + names.length + ' files.');
      }


      /**
       * Generate grunt API documentation
       */
      function generateAPI() {
        grunt.log.ok('Generating API Docs...');
        // API Docs
        var sidebars = [],
          base = 'tmp/wiki/',
          names = grunt.file.expand({cwd:base}, ['grunt.*.md', '!*utils*']);

        names = names.map(function (name) {
          return name.substring(0, name.length - 3);
        });

        // the default api page is special
        names.push('grunt');
        // TODO: temporary store for these
        names.push('Inside-Tasks');
        names.push('Exit-Codes');

        // get docs sidebars
        sidebars[0] = getSidebarSection('## API', 'icon-cog');
        sidebars[1] = getSidebarSection('### Other');

        names.forEach(function (name) {
          var src = base + name + '.md',
            dest = 'build/api/' + name.toLowerCase() + '.html';
          grunt.file.copy(src, dest, {
            process:function (src) {
              try {
                var file = 'src/tmpl/docs.jade',
                  templateData = {
                    page:'api',
                    pageSegment: name.toLowerCase(),
                    title:name.replace(/-/g,' '),
                    content: docs.anchorFilter( marked( docs.wikiAnchors(src) ) ),
                    sidebars: sidebars
                  };

                return jade.compile(grunt.file.read(file), {filename:file})(templateData);
              } catch (e) {
                grunt.log.error(e);
                grunt.fail.warn('Jade failed to compile.');
              }
            }
          });
        });
        grunt.log.ok('Created ' + names.length + ' files.');
      }


      /**
       * Get sidebar list for section from Home.md
       */
      function getSidebarSection(section, iconClass) {
        var rMode = false,
          l,
          items = [];

        // read the Home.md of the wiki, extract the section links
        var lines = fs.readFileSync('tmp/wiki/Home.md').toString().split('\n');
        for(l in lines) {
          var line = lines[l];

          // choose a section of the file
          if (line === section) { rMode = true; }
          // end of section
          else if (line.substring(0,2) === '##') { rMode = false; }

          if (rMode && line.length > 0) {
            var item = line.replace(/#/g,'').replace(']]', '').replace('* [[', ''),
              url = item;

            if (item[0] === " ") {
              // TODO: clean this up...
              if (iconClass) {
                items.push({name: item.substring(1,item.length), icon: iconClass});
              } else {
                items.push({name: item.substring(1,item.length)});
              }
            } else {
              items.push({name: item, url: url.replace(/ /g,'-').toLowerCase()});
            }
          }
        }
        return items;
      }

    }
Exemplo n.º 22
0
  grunt.registerTask('site-meta', 'Build metadata files describing example usages', function (tag) {
    var done = this.async();
    var glob = require('glob');
    var fs = require('fs');
    var path = require('path');
    var util = require('util');
    var marked = require('marked');
    var meta = {};
    var tasks = [];

    marked.setOptions({
      renderer: new marked.Renderer(),
      gfm: true,
      tables: true,
      breaks: false,
      pedantic: false,
      sanitize: true,
      smartLists: true,
      smartypants: false
    });

    tasks.push(function buildCoverage() {
      // Parse Lcov report and generate `coverage.json` file for site.
      var parse = require('lcov-parse');
      parse('.coverage/lcov.info', function (err, data) {
        if (err) {
          grunt.log.ok('skipping code coverage because lcov.info is missing');
          return next();
        }
        // Obj has "found" and "hit"
        function percent(obj) {
          if (obj.found === 0) {
            return 100;
          }
          return parseFloat((obj.hit / obj.found * 100.0).toPrecision(2), 10);
        }

        var outMeta = data.map(function (d) {
          delete d.lines.details;
          delete d.functions.details;
          delete d.branches.details;
          delete d.title;
          d.lines.percent = percent(d.lines);
          d.functions.percent = percent(d.functions);
          d.branches.percent = percent(d.branches);
          return d;
        });
        writeJson('public/coverage.json', outMeta);
        next();
      });
    });

    tasks.push(function buildReadmeFiles() {
      glob("examples/components/**/readme.md", function (err, files) {
        files.forEach(function parseDemo(readmeFile) {
          var component = readableString(path.basename(path.dirname(readmeFile)));
          meta[component] = meta[component] || {};
          meta[component].readme = marked(fs.readFileSync(readmeFile).toString());
        });
        next();
      });
    });

    tasks.push(function buildProjectReadme() {
      var rendered = marked(fs.readFileSync(path.join(__dirname, 'README.md')).toString());
      var pkg = require('./package.json');
      writeJson('public/version.json', {
        version: pkg.version,
        readme: rendered,
        angular2: pkg.dependencies.angular2
      });
      next();
    });

    tasks.push(function buildExamples() {
      glob("examples/components/**/*.html", function (err, files) {
        files.forEach(function parseDemo(templateFile) {
          var name = path.basename(templateFile, '.html');
          var result = {
            template: templateFile
          };
          var readmeFile = path.join(path.dirname(templateFile), name + '.md');
          var sourceFile = path.join(path.dirname(templateFile), name + '.ts');
          var stylesFile = path.join(path.dirname(templateFile), name + '.scss');
          if (fileExists(stylesFile)) {
            result.styles = stylesFile;
          }
          if (fileExists(sourceFile)) {
            result.source = sourceFile;
          }
          if (fileExists(readmeFile)) {
            result.readme = marked(fs.readFileSync(readmeFile).toString());
          }

          var component = readableString(path.basename(path.dirname(templateFile)));
          result.component = selectorString(component + ' ' + readableString(name));
          meta[component] = meta[component] || {};
          meta[component].files = [];
          meta[component][readableString(name)] = result;
          lintDemo(result);
        });


        glob("ng2-material/components/**/*.ts", function (err, files) {
          files.forEach(function linkComponentsToExamples(sourceFile) {
            var component = readableString(path.basename(path.dirname(sourceFile)));
            if (!meta[component]) {
              return;
            }
            meta[component].files.push(sourceFile);
          });
          writeJson('public/meta.json', prepareMeta());
          next();
        });
      });
    });

    function next() {
      if (tasks.length === 0) {
        return done();
      }
      var current = tasks.shift();
      current();
    }

    return next();

    // ------------------------------------------------------------------------
    // Helpers and such
    // ------------------------------------------------------------------------

    function writeJson(to, data) {
      try {
        fs.writeFileSync(to, JSON.stringify(data, null, 2));
      }
      catch (e) {
        grunt.log.fatal('failed to write (' + to + ') with error: ' + e);

      }
    }


    // Make the metadata easier to access in angular by using arrays rather than key/value pairs.
    // Store as an object internally to group examples by component.
    function prepareMeta() {
      var keys = Object.keys(meta);

      return keys.map(function (key) {
        var demos = meta[key];
        var sources = demos.files.slice();
        var readme = demos.readme;
        delete demos.files;
        delete demos.readme;
        var demoKeys = Object.keys(demos);
        var result = {
          name: key,
          sources: sources,
          id: selectorString(key),
          examples: demoKeys.map(function (key) {
            demos[key].name = key;
            return demos[key];
          })
        };
        if (readme) {
          result.readme = readme;
        }
        return result;
      });
    }

    // Convert readable string of component + demo to a valid element name that
    // can be inserted into the dom to produce the demo.
    // e.g. "Card Basic Usage" -> "card-basic-usage"
    function selectorString(readableString) {
      return readableString
        .split(' ')
        .map(function (c) {
          return c.toLowerCase();
        })
        .join('-');
    }

    function readableString(snakeCaseString) {
      return snakeCaseString
        .split('_')
        .map(function (c) {
          return c[0].toUpperCase() + c.slice(1);
        })
        .join(' ');
    }

    function lintDemo(outputMeta) {
      grunt.log.ok('checking ' + outputMeta.source + ' no lint present');
    }

    function fileExists(filePath) {
      try {
        return fs.statSync(filePath).isFile();
      }
      catch (err) {
        return false;
      }
    }
  });
Exemplo n.º 23
0
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, calc(5vw));
    font-size: 3em;
    font-family: "Open Sans", sans-serif;
    font-weight: 600;
  }
`;

const HeaderWrapper = styled.div`
  transition: opacity 0.3s;
  opacity: ${p => p.visible ? 1 : 0};
`
marked.setOptions({
  gfm: true,
  breaks: true,
});
const innerHtml = { __html: marked(profile) }

export default class App extends React.Component {
  state = {
    isHeaderVisible: false,
  }

  onChangeHero = isVisible => {
    this.setState({ isHeaderVisible: !isVisible });
  }

  render() {
    return (
      <AppWrapper>
Exemplo n.º 24
0
Arquivo: tool.js Projeto: kveen/agroup
var settings = config.settings;
var getParams = config.getParams;
var _ = require('lodash');
var marked = require('marked');
var fs = require('fs');
var os = require('os');
var path = require('path');
var Stream = require('stream');

marked.setOptions({
  renderer: new marked.Renderer(),
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: true,
  smartLists: true,
  smartypants: false,
  highlight: function(code) {
    return require('highlight.js').highlightAuto(code).value;
  }
});


// Apply template to the current document
function md2html(filename, content) {
  try {
    var template = settings.pdfTemplate;
    return _.template(template, {
      documentTitle: filename,
      documentHTML: marked(content)
Exemplo n.º 25
0
var marked = require('marked');
var hljs = require('highlight.js');
var mime = require('mime');

var indexpath = path.join(__dirname, '..', 'public', 'index.html');
var index = fs.readFileSync(indexpath, 'utf8');
var content = [], toc = [];

marked.setOptions({
  gfm: true,
  pedantic: false,
  sanitize: true,
  highlight: function(code, lang) {
  	var value;
  	if (code && lang) {
			return hljs.highlight(lang, code).value;
  	}
  	else {
  		return code;
  	}
  }
});

var datapath = path.join(__dirname, '..', 'data');
var filenames = fs.readdirSync(datapath);

for (var i = 0, l = filenames.length; i<l; i++) {
  filenames[i] = path.basename(filenames[i], '.md');
}

filenames
Exemplo n.º 26
0
web.set('view engine', 'jade');
web.use(compress());
web.use(favicon(config.rootDir + config.publicPath + '/favicon.ico'));
server.use(morgan('dev'));
server.use(bodyParser());
server.use(methodOverride());
web.use(require('stylus').middleware(config.rootDir + config.publicPath));
web.use(express.static(config.rootDir + config.publicPath));
api.use(middleware.defaultContentType); // Forces application/json
api.use(middleware.attachApiKey);
web.use(middleware.addDate); // Adds date to every template render

// Synchronous highlighting with highlight.js
marked.setOptions({
  highlight: function (code) {
    return require('highlight.js').highlightAuto(code).value;
  }
});


if (process.env.ENVIRONMENT === 'production') {
  require('newrelic');
} else {
  server.use(errorHandler());
}

// Web routes
web.get('/', function (req, res) {
  res.render('home');
});
Exemplo n.º 27
0
  return "<code class=\"md-code "
    + this.options.langPrefix
    + escape(lang, true)
    + "\">"
    + (escaped ? code : escape(code, true))
    + "\n</code>\n";
};

Marked.setOptions({
  gfm: true,
  renderer: mdRenderer,
  // pedantic: this is set on the render method
  // breaks: this is set on the render method
  tables: true,
  smartLists: true,
  sanitize: false, // To be able to add iframes
  highlight: function (code, lang) {
    lang = lang || "text";
    return Nsh.highlight(code, Nsh.getLanguage(lang) || Nsh.getLanguage("text"), {gutter: lang !== "text"});
  }
});

var tagmap = {};

// Yields the content with the rendered [[bracket tags]]
// The rules are the same for Gollum https://github.com/github/gollum
function extractTags(text) {

  tagmap = {};
Exemplo n.º 28
0
	if (title) {
		result += ' title="' + title + '"';
	}

	result += ` target="_blank">${text}</a>`;

	return result;
};

marked.setOptions({
	renderer: renderer,
	gfm: true,
	tables: true,
	breaks: false,
	pedantic: false,
	sanitize: false,
	smartLists: false,
	smartypants: false,
	langPrefix: 'hljs lang-',
    highlight: require('../code-block').highlight,
	anchorTarget: '_blank'
});

exports.renderer = function(input, out) {
    var body = out.captureString(function () {
        input.renderBody(out);
    });

	body = removeIndentation(body);

    out.write(marked(body));
Exemplo n.º 29
0
renderer.br = function () {
  return '<br />';
};

var markedOptions = {
  renderer: renderer
, gfm: true
, tables: true
, breaks: true
, pedantic: false
, sanitize: false
, smartLists: true
, smartypants: false
};

markdown.setOptions(markedOptions);

/**
 * Expose api.
 */

exports.api = require('./api');

/**
 * Parse comments in the given string of `js`.
 *
 * @param {String} js
 * @param {Object} options
 * @return {Array}
 * @see exports.parseComment
 * @api public
Exemplo n.º 30
0
	liens_defaillance = require('./routes/liens_defaillance'),
	admin = require('./routes/admin'),
	webmention = require('./routes/webmention'),
	utils = require('./utils'),
	db = require('./database');

var mongoose = require('mongoose'),
	express = require('express'),
	marked = require('marked');

console.log('Server launched');


marked.setOptions({
	highlight : function (code, lang) {
		return '<pre class="line-numbers"><code class="language-javascript">' + code + '</code></pre>'; //' + lang === '' ? 'js' : lang + '
	}
});

db.init(utils, mongoose);

var app = express();

app
.use(express.favicon('public/images/favicon.ico'))
.use(express.bodyParser())
.use(express.cookieParser())
.use(express.cookieSession({
	key : 'exppad.session',
	secret : 'key#exppad'
}))