From 410037d4a2a9278e62880689ed5bc45c241b9d35 Mon Sep 17 00:00:00 2001 From: Raul Ochoa Date: Tue, 9 Dec 2014 17:53:06 +0100 Subject: [PATCH] Adds carto in examples vendor directory --- examples/vendor/carto.js | 8625 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 8625 insertions(+) create mode 100644 examples/vendor/carto.js diff --git a/examples/vendor/carto.js b/examples/vendor/carto.js new file mode 100644 index 0000000..1f377cc --- /dev/null +++ b/examples/vendor/carto.js @@ -0,0 +1,8625 @@ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.carto=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 1) color = arguments[1]; + if (arguments.length > 2) mode = arguments[2]; + + return { + is: 'tag', + val: val, + color: color, + mode: mode, + toString: function(env) { + return '\n\t'; + } + }; + }, + hsl: function (h, s, l) { + return this.hsla(h, s, l, 1.0); + }, + hsla: function (h, s, l, a) { + h = (number(h) % 360) / 360; + s = number(s); l = number(l); a = number(a); + if ([h, s, l, a].some(isNaN)) return null; + + var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s, + m1 = l * 2 - m2; + + return this.rgba(hue(h + 1/3) * 255, + hue(h) * 255, + hue(h - 1/3) * 255, + a); + + function hue(h) { + h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h); + if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; + else if (h * 2 < 1) return m2; + else if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6; + else return m1; + } + }, + hue: function (color) { + if (!('toHSL' in color)) return null; + return new tree.Dimension(Math.round(color.toHSL().h)); + }, + saturation: function (color) { + if (!('toHSL' in color)) return null; + return new tree.Dimension(Math.round(color.toHSL().s * 100), '%'); + }, + lightness: function (color) { + if (!('toHSL' in color)) return null; + return new tree.Dimension(Math.round(color.toHSL().l * 100), '%'); + }, + alpha: function (color) { + if (!('toHSL' in color)) return null; + return new tree.Dimension(color.toHSL().a); + }, + saturate: function (color, amount) { + if (!('toHSL' in color)) return null; + var hsl = color.toHSL(); + + hsl.s += amount.value / 100; + hsl.s = clamp(hsl.s); + return hsla(hsl); + }, + desaturate: function (color, amount) { + if (!('toHSL' in color)) return null; + var hsl = color.toHSL(); + + hsl.s -= amount.value / 100; + hsl.s = clamp(hsl.s); + return hsla(hsl); + }, + lighten: function (color, amount) { + if (!('toHSL' in color)) return null; + var hsl = color.toHSL(); + + hsl.l += amount.value / 100; + hsl.l = clamp(hsl.l); + return hsla(hsl); + }, + darken: function (color, amount) { + if (!('toHSL' in color)) return null; + var hsl = color.toHSL(); + + hsl.l -= amount.value / 100; + hsl.l = clamp(hsl.l); + return hsla(hsl); + }, + fadein: function (color, amount) { + if (!('toHSL' in color)) return null; + var hsl = color.toHSL(); + + hsl.a += amount.value / 100; + hsl.a = clamp(hsl.a); + return hsla(hsl); + }, + fadeout: function (color, amount) { + if (!('toHSL' in color)) return null; + var hsl = color.toHSL(); + + hsl.a -= amount.value / 100; + hsl.a = clamp(hsl.a); + return hsla(hsl); + }, + spin: function (color, amount) { + if (!('toHSL' in color)) return null; + var hsl = color.toHSL(); + var hue = (hsl.h + amount.value) % 360; + + hsl.h = hue < 0 ? 360 + hue : hue; + + return hsla(hsl); + }, + replace: function (entity, a, b) { + if (entity.is === 'field') { + return entity.toString + '.replace(' + a.toString() + ', ' + b.toString() + ')'; + } else { + return entity.replace(a, b); + } + }, + // + // Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein + // http://sass-lang.com + // + mix: function (color1, color2, weight) { + var p = weight.value / 100.0; + var w = p * 2 - 1; + var a = color1.toHSL().a - color2.toHSL().a; + + var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; + var w2 = 1 - w1; + + var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2, + color1.rgb[1] * w1 + color2.rgb[1] * w2, + color1.rgb[2] * w1 + color2.rgb[2] * w2]; + + var alpha = color1.alpha * p + color2.alpha * (1 - p); + + return new tree.Color(rgb, alpha); + }, + greyscale: function (color) { + return this.desaturate(color, new tree.Dimension(100)); + }, + '%': function (quoted /* arg, arg, ...*/) { + var args = Array.prototype.slice.call(arguments, 1), + str = quoted.value; + + for (var i = 0; i < args.length; i++) { + str = str.replace(/%s/, args[i].value) + .replace(/%[da]/, args[i].toString()); + } + str = str.replace(/%%/g, '%'); + return new tree.Quoted(str); + } +}; + +var image_filter_functors = [ + 'emboss', 'blur', 'gray', 'sobel', 'edge-detect', + 'x-gradient', 'y-gradient', 'sharpen']; + +for (var i = 0; i < image_filter_functors.length; i++) { + var f = image_filter_functors[i]; + tree.functions[f] = (function(f) { + return function() { + return new tree.ImageFilter(f); + }; + })(f); +} + +tree.functions['agg-stack-blur'] = function(x, y) { + return new tree.ImageFilter('agg-stack-blur', [x, y]); +}; + +tree.functions['scale-hsla'] = function(h0,h1,s0,s1,l0,l1,a0,a1) { + return new tree.ImageFilter('scale-hsla', [h0,h1,s0,s1,l0,l1,a0,a1]); +}; + +function hsla(h) { + return tree.functions.hsla(h.h, h.s, h.l, h.a); +} + +function number(n) { + if (n instanceof tree.Dimension) { + return parseFloat(n.unit == '%' ? n.value / 100 : n.value); + } else if (typeof(n) === 'number') { + return n; + } else { + return NaN; + } +} + +function clamp(val) { + return Math.min(1, Math.max(0, val)); +} + +})(require('./tree')); + +},{"./tree":7}],2:[function(require,module,exports){ +(function (process,__dirname){ +var util = require('util'), + fs = require('fs'), + path = require('path'); + + +function getVersion() { + if (process.browser) { + return require('../../package.json').version.split('.'); + } else if (parseInt(process.version.split('.')[1], 10) > 4) { + return require('../../package.json').version.split('.'); + } else { + // older node + var package_json = JSON.parse(fs.readFileSync(path.join(__dirname,'../../package.json'))); + return package_json.version.split('.'); + } +} + +var carto = { + version: getVersion(), + Parser: require('./parser').Parser, + Renderer: require('./renderer').Renderer, + tree: require('./tree'), + RendererJS: require('./renderer_js'), + + // @TODO + writeError: function(ctx, options) { + var message = ''; + var extract = ctx.extract; + var error = []; + + options = options || {}; + + if (options.silent) { return; } + + options.indent = options.indent || ''; + + if (!('index' in ctx) || !extract) { + return util.error(options.indent + (ctx.stack || ctx.message)); + } + + if (typeof(extract[0]) === 'string') { + error.push(stylize((ctx.line - 1) + ' ' + extract[0], 'grey')); + } + + if (extract[1] === '' && typeof extract[2] === 'undefined') { + extract[1] = '¶'; + } + error.push(ctx.line + ' ' + extract[1].slice(0, ctx.column) + + stylize(stylize(extract[1][ctx.column], 'bold') + + extract[1].slice(ctx.column + 1), 'yellow')); + + if (typeof(extract[2]) === 'string') { + error.push(stylize((ctx.line + 1) + ' ' + extract[2], 'grey')); + } + error = options.indent + error.join('\n' + options.indent) + '\033[0m\n'; + + message = options.indent + message + stylize(ctx.message, 'red'); + if (ctx.filename) (message += stylize(' in ', 'red') + ctx.filename); + + util.error(message, error); + + if (ctx.callLine) { + util.error(stylize('from ', 'red') + (ctx.filename || '')); + util.error(stylize(ctx.callLine, 'grey') + ' ' + ctx.callExtract); + } + if (ctx.stack) { util.error(stylize(ctx.stack, 'red')); } + } +}; + +require('./tree/call'); +require('./tree/color'); +require('./tree/comment'); +require('./tree/definition'); +require('./tree/dimension'); +require('./tree/element'); +require('./tree/expression'); +require('./tree/filterset'); +require('./tree/filter'); +require('./tree/field'); +require('./tree/keyword'); +require('./tree/layer'); +require('./tree/literal'); +require('./tree/operation'); +require('./tree/quoted'); +require('./tree/imagefilter'); +require('./tree/reference'); +require('./tree/rule'); +require('./tree/ruleset'); +require('./tree/selector'); +require('./tree/style'); +require('./tree/url'); +require('./tree/value'); +require('./tree/variable'); +require('./tree/zoom'); +require('./tree/invalid'); +require('./tree/fontset'); +require('./tree/frame_offset'); +require('./functions'); + +for (var k in carto) { exports[k] = carto[k]; } + +// Stylize a string +function stylize(str, style) { + var styles = { + 'bold' : [1, 22], + 'inverse' : [7, 27], + 'underline' : [4, 24], + 'yellow' : [33, 39], + 'green' : [32, 39], + 'red' : [31, 39], + 'grey' : [90, 39] + }; + return '\033[' + styles[style][0] + 'm' + str + + '\033[' + styles[style][1] + 'm'; +} + +}).call(this,require('_process'),"/lib/carto") +},{"../../package.json":38,"./functions":1,"./parser":3,"./renderer":4,"./renderer_js":5,"./tree":7,"./tree/call":8,"./tree/color":9,"./tree/comment":10,"./tree/definition":11,"./tree/dimension":12,"./tree/element":13,"./tree/expression":14,"./tree/field":15,"./tree/filter":16,"./tree/filterset":17,"./tree/fontset":18,"./tree/frame_offset":19,"./tree/imagefilter":20,"./tree/invalid":21,"./tree/keyword":22,"./tree/layer":23,"./tree/literal":24,"./tree/operation":25,"./tree/quoted":26,"./tree/reference":27,"./tree/rule":28,"./tree/ruleset":29,"./tree/selector":30,"./tree/style":31,"./tree/url":32,"./tree/value":33,"./tree/variable":34,"./tree/zoom":35,"_process":43,"fs":39,"path":42,"util":45}],3:[function(require,module,exports){ +var carto = exports, + tree = require('./tree'), + _ = require('underscore'); + +// Token matching is done with the `$` function, which either takes +// a terminal string or regexp, or a non-terminal function to call. +// It also takes care of moving all the indices forwards. +carto.Parser = function Parser(env) { + var input, // LeSS input string + i, // current index in `input` + j, // current chunk + temp, // temporarily holds a chunk's state, for backtracking + memo, // temporarily holds `i`, when backtracking + furthest, // furthest index the parser has gone to + chunks, // chunkified input + current, // index of current chunk, in `input` + parser; + + var that = this; + + // This function is called after all files + // have been imported through `@import`. + var finish = function() {}; + + function save() { + temp = chunks[j]; + memo = i; + current = i; + } + function restore() { + chunks[j] = temp; + i = memo; + current = i; + } + + function sync() { + if (i > current) { + chunks[j] = chunks[j].slice(i - current); + current = i; + } + } + // + // Parse from a token, regexp or string, and move forward if match + // + function $(tok) { + var match, args, length, c, index, endIndex, k; + + // Non-terminal + if (tok instanceof Function) { + return tok.call(parser.parsers); + // Terminal + // Either match a single character in the input, + // or match a regexp in the current chunk (chunk[j]). + } else if (typeof(tok) === 'string') { + match = input.charAt(i) === tok ? tok : null; + length = 1; + sync(); + } else { + sync(); + + match = tok.exec(chunks[j]); + if (match) { + length = match[0].length; + } else { + return null; + } + } + + // The match is confirmed, add the match length to `i`, + // and consume any extra white-space characters (' ' || '\n') + // which come after that. The reason for this is that LeSS's + // grammar is mostly white-space insensitive. + if (match) { + var mem = i += length; + endIndex = i + chunks[j].length - length; + + while (i < endIndex) { + c = input.charCodeAt(i); + if (! (c === 32 || c === 10 || c === 9)) { break; } + i++; + } + chunks[j] = chunks[j].slice(length + (i - mem)); + current = i; + + if (chunks[j].length === 0 && j < chunks.length - 1) { j++; } + + if (typeof(match) === 'string') { + return match; + } else { + return match.length === 1 ? match[0] : match; + } + } + } + + // Same as $(), but don't change the state of the parser, + // just return the match. + function peek(tok) { + if (typeof(tok) === 'string') { + return input.charAt(i) === tok; + } else { + return !!tok.test(chunks[j]); + } + } + + function extractErrorLine(style, errorIndex) { + return (style.slice(0, errorIndex).match(/\n/g) || '').length + 1; + } + + + // Make an error object from a passed set of properties. + // Accepted properties: + // - `message`: Text of the error message. + // - `filename`: Filename where the error occurred. + // - `index`: Char. index where the error occurred. + function makeError(err) { + var einput; + + _(err).defaults({ + index: furthest, + filename: env.filename, + message: 'Parse error.', + line: 0, + column: -1 + }); + + if (err.filename && that.env.inputs && that.env.inputs[err.filename]) { + einput = that.env.inputs[err.filename]; + } else { + einput = input; + } + + err.line = extractErrorLine(einput, err.index); + for (var n = err.index; n >= 0 && einput.charAt(n) !== '\n'; n--) { + err.column++; + } + + return new Error(_('<%=filename%>:<%=line%>:<%=column%> <%=message%>').template(err)); + } + + this.env = env = env || {}; + this.env.filename = this.env.filename || null; + this.env.inputs = this.env.inputs || {}; + + // The Parser + parser = { + + extractErrorLine: extractErrorLine, + // + // Parse an input string into an abstract syntax tree. + // Throws an error on parse errors. + parse: function(str) { + var root, start, end, zone, line, lines, buff = [], c, error = null; + + i = j = current = furthest = 0; + chunks = []; + input = str.replace(/\r\n/g, '\n'); + if (env.filename) { + that.env.inputs[env.filename] = input; + } + + var early_exit = false; + + // Split the input into chunks. + chunks = (function (chunks) { + var j = 0, + skip = /(?:@\{[\w-]+\}|[^"'`\{\}\/\(\)\\])+/g, + comment = /\/\*(?:[^*]|\*+[^\/*])*\*+\/|\/\/.*/g, + string = /"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'|`((?:[^`]|\\.)*)`/g, + level = 0, + match, + chunk = chunks[0], + inParam; + + for (var i = 0, c, cc; i < input.length;) { + skip.lastIndex = i; + if (match = skip.exec(input)) { + if (match.index === i) { + i += match[0].length; + chunk.push(match[0]); + } + } + c = input.charAt(i); + comment.lastIndex = string.lastIndex = i; + + if (match = string.exec(input)) { + if (match.index === i) { + i += match[0].length; + chunk.push(match[0]); + continue; + } + } + + if (!inParam && c === '/') { + cc = input.charAt(i + 1); + if (cc === '/' || cc === '*') { + if (match = comment.exec(input)) { + if (match.index === i) { + i += match[0].length; + chunk.push(match[0]); + continue; + } + } + } + } + + switch (c) { + case '{': if (! inParam) { level ++; chunk.push(c); break; } + case '}': if (! inParam) { level --; chunk.push(c); chunks[++j] = chunk = []; break; } + case '(': if (! inParam) { inParam = true; chunk.push(c); break; } + case ')': if ( inParam) { inParam = false; chunk.push(c); break; } + default: chunk.push(c); + } + + i++; + } + if (level !== 0) { + error = { + index: i - 1, + type: 'Parse', + message: (level > 0) ? "missing closing `}`" : "missing opening `{`" + }; + } + + return chunks.map(function (c) { return c.join(''); }); + })([[]]); + + if (error) { + throw makeError(error); + } + + // Start with the primary rule. + // The whole syntax tree is held under a Ruleset node, + // with the `root` property set to true, so no `{}` are + // output. + root = new tree.Ruleset([], $(this.parsers.primary)); + root.root = true; + + // Get an array of Ruleset objects, flattened + // and sorted according to specificitySort + root.toList = (function() { + var line, lines, column; + return function(env) { + env.error = function(e) { + if (!env.errors) env.errors = new Error(''); + if (env.errors.message) { + env.errors.message += '\n' + makeError(e).message; + } else { + env.errors.message = makeError(e).message; + } + }; + env.frames = env.frames || []; + + + // call populates Invalid-caused errors + var definitions = this.flatten([], [], env); + definitions.sort(specificitySort); + return definitions; + }; + })(); + + // Sort rules by specificity: this function expects selectors to be + // split already. + // + // Written to be used as a .sort(Function); + // argument. + // + // [1, 0, 0, 467] > [0, 0, 1, 520] + var specificitySort = function(a, b) { + var as = a.specificity; + var bs = b.specificity; + + if (as[0] != bs[0]) return bs[0] - as[0]; + if (as[1] != bs[1]) return bs[1] - as[1]; + if (as[2] != bs[2]) return bs[2] - as[2]; + return bs[3] - as[3]; + }; + + return root; + }, + + // Here in, the parsing rules/functions + // + // The basic structure of the syntax tree generated is as follows: + // + // Ruleset -> Rule -> Value -> Expression -> Entity + // + // In general, most rules will try to parse a token with the `$()` function, and if the return + // value is truly, will return a new node, of the relevant type. Sometimes, we need to check + // first, before parsing, that's when we use `peek()`. + parsers: { + // The `primary` rule is the *entry* and *exit* point of the parser. + // The rules here can appear at any level of the parse tree. + // + // The recursive nature of the grammar is an interplay between the `block` + // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule, + // as represented by this simplified grammar: + // + // primary → (ruleset | rule)+ + // ruleset → selector+ block + // block → '{' primary '}' + // + // Only at one point is the primary rule not called from the + // block rule: at the root level. + primary: function() { + var node, root = []; + + while ((node = $(this.rule) || $(this.ruleset) || + $(this.comment)) || + $(/^[\s\n]+/) || (node = $(this.invalid))) { + if (node) root.push(node); + } + return root; + }, + + invalid: function () { + var chunk = $(/^[^;\n]*[;\n]/); + + // To fail gracefully, match everything until a semicolon or linebreak. + if (chunk) { + return new tree.Invalid(chunk, memo); + } + }, + + // We create a Comment node for CSS comments `/* */`, + // but keep the LeSS comments `//` silent, by just skipping + // over them. + comment: function() { + var comment; + + if (input.charAt(i) !== '/') return; + + if (input.charAt(i + 1) === '/') { + return new tree.Comment($(/^\/\/.*/), true); + } else if (comment = $(/^\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/)) { + return new tree.Comment(comment); + } + }, + + // Entities are tokens which can be found inside an Expression + entities: { + + // A string, which supports escaping " and ' "milky way" 'he\'s the one!' + quoted: function() { + if (input.charAt(i) !== '"' && input.charAt(i) !== "'") return; + var str = $(/^"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'/); + if (str) { + return new tree.Quoted(str[1] || str[2]); + } + }, + + // A reference to a Mapnik field, like [NAME] + // Behind the scenes, this has the same representation, but Carto + // needs to be careful to warn when unsupported operations are used. + field: function() { + if (! $('[')) return; + var field_name = $(/(^[^\]]+)/); + if (! $(']')) return; + if (field_name) return new tree.Field(field_name[1]); + }, + + // This is a comparison operator + comparison: function() { + var str = $(/^=~|=|!=|<=|>=|<|>/); + if (str) { + return str; + } + }, + + // A catch-all word, such as: hard-light + // These can start with either a letter or a dash (-), + // and then contain numbers, underscores, and letters. + keyword: function() { + var k = $(/^[A-Za-z-]+[A-Za-z-0-9_]*/); + if (k) { return new tree.Keyword(k); } + }, + + // A function call like rgb(255, 0, 255) + // The arguments are parsed with the `entities.arguments` parser. + call: function() { + var name, args; + + if (!(name = /^([\w\-]+|%)\(/.exec(chunks[j]))) return; + + name = name[1]; + + if (name === 'url') { + // url() is handled by the url parser instead + return null; + } else { + i += name.length; + } + + $('('); // Parse the '(' and consume whitespace. + + args = $(this.entities['arguments']); + + if (!$(')')) return; + + if (name) { + return new tree.Call(name, args, i); + } + }, + // Arguments are comma-separated expressions + 'arguments': function() { + var args = [], arg; + + while (arg = $(this.expression)) { + args.push(arg); + if (! $(',')) { break; } + } + + return args; + }, + literal: function() { + return $(this.entities.dimension) || + $(this.entities.keywordcolor) || + $(this.entities.hexcolor) || + $(this.entities.quoted); + }, + + // Parse url() tokens + // + // We use a specific rule for urls, because they don't really behave like + // standard function calls. The difference is that the argument doesn't have + // to be enclosed within a string, so it can't be parsed as an Expression. + url: function() { + var value; + + if (input.charAt(i) !== 'u' || !$(/^url\(/)) return; + value = $(this.entities.quoted) || $(this.entities.variable) || + $(/^[\-\w%@$\/.&=:;#+?~]+/) || ''; + if (! $(')')) { + return new tree.Invalid(value, memo, 'Missing closing ) in URL.'); + } else { + return new tree.URL((typeof value.value !== 'undefined' || + value instanceof tree.Variable) ? + value : new tree.Quoted(value)); + } + }, + + // A Variable entity, such as `@fink`, in + // + // width: @fink + 2px + // + // We use a different parser for variable definitions, + // see `parsers.variable`. + variable: function() { + var name, index = i; + + if (input.charAt(i) === '@' && (name = $(/^@[\w-]+/))) { + return new tree.Variable(name, index, env.filename); + } + }, + + hexcolor: function() { + var rgb; + if (input.charAt(i) === '#' && (rgb = $(/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})/))) { + return new tree.Color(rgb[1]); + } + }, + + keywordcolor: function() { + var rgb = chunks[j].match(/^[a-z]+/); + if (rgb && rgb[0] in tree.Reference.data.colors) { + return new tree.Color(tree.Reference.data.colors[$(/^[a-z]+/)]); + } + }, + + // A Dimension, that is, a number and a unit. The only + // unit that has an effect is % + dimension: function() { + var c = input.charCodeAt(i); + if ((c > 57 || c < 45) || c === 47) return; + var value = $(/^(-?\d*\.?\d+(?:[eE][-+]?\d+)?)(\%|\w+)?/); + if (value) { + return new tree.Dimension(value[1], value[2], memo); + } + } + }, + + // The variable part of a variable definition. + // Used in the `rule` parser. Like @fink: + variable: function() { + var name; + + if (input.charAt(i) === '@' && (name = $(/^(@[\w-]+)\s*:/))) { + return name[1]; + } + }, + + // Entities are the smallest recognized token, + // and can be found inside a rule's value. + entity: function() { + return $(this.entities.call) || + $(this.entities.literal) || + $(this.entities.field) || + $(this.entities.variable) || + $(this.entities.url) || + $(this.entities.keyword); + }, + + // A Rule terminator. Note that we use `peek()` to check for '}', + // because the `block` rule will be expecting it, but we still need to make sure + // it's there, if ';' was ommitted. + end: function() { + return $(';') || peek('}'); + }, + + // Elements are the building blocks for Selectors. They consist of + // an element name, such as a tag a class, or `*`. + element: function() { + var e = $(/^(?:[.#][\w\-]+|\*|Map)/); + if (e) return new tree.Element(e); + }, + + // Attachments allow adding multiple lines, polygons etc. to an + // object. There can only be one attachment per selector. + attachment: function() { + var s = $(/^::([\w\-]+(?:\/[\w\-]+)*)/); + if (s) return s[1]; + }, + + // Selectors are made out of one or more Elements, see above. + selector: function() { + var a, attachment, + e, elements = [], + f, filters = new tree.Filterset(), + z, zooms = [], + frame_offset = tree.FrameOffset.none; + segments = 0, conditions = 0; + + while ( + (e = $(this.element)) || + (z = $(this.zoom)) || + (fo = $(this.frame_offset)) || + (f = $(this.filter)) || + (a = $(this.attachment)) + ) { + segments++; + if (e) { + elements.push(e); + } else if (z) { + zooms.push(z); + conditions++; + } else if (fo) { + frame_offset = fo; + conditions++; + } else if (f) { + var err = filters.add(f); + if (err) { + throw makeError({ + message: err, + index: i - 1 + }); + } + conditions++; + } else if (attachment) { + throw makeError({ + message: 'Encountered second attachment name.', + index: i - 1 + }); + } else { + attachment = a; + } + + var c = input.charAt(i); + if (c === '{' || c === '}' || c === ';' || c === ',') { break; } + } + + if (segments) { + return new tree.Selector(filters, zooms, frame_offset, elements, attachment, conditions, memo); + } + }, + + filter: function() { + save(); + var key, op, val; + if (! $('[')) return; + if (key = $(/^[a-zA-Z0-9\-_]+/) || + $(this.entities.quoted) || + $(this.entities.variable) || + $(this.entities.keyword) || + $(this.entities.field)) { + // TODO: remove at 1.0.0 + if (key instanceof tree.Quoted) { + key = new tree.Field(key.toString()); + } + if ((op = $(this.entities.comparison)) && + (val = $(this.entities.quoted) || + $(this.entities.variable) || + $(this.entities.dimension) || + $(this.entities.keyword) || + $(this.entities.field))) { + if (! $(']')) { + throw makeError({ + message: 'Missing closing ] of filter.', + index: memo - 1 + }); + } + if (!key.is) key = new tree.Field(key); + return new tree.Filter(key, op, val, memo, env.filename); + } + } + }, + + frame_offset: function() { + save(); + var op, val; + if ($(/^\[\s*frame-offset/g) && + (op = $(this.entities.comparison)) && + (val = $(/^\d+/)) && + $(']')) { + return tree.FrameOffset(op, val, memo); + } + }, + + zoom: function() { + save(); + var op, val; + if ($(/^\[\s*zoom/g) && + (op = $(this.entities.comparison)) && + (val = $(this.entities.variable) || $(this.entities.dimension)) && $(']')) { + return new tree.Zoom(op, val, memo); + } else { + // backtrack + restore(); + } + }, + + // The `block` rule is used by `ruleset` + // It's a wrapper around the `primary` rule, with added `{}`. + block: function() { + var content; + + if ($('{') && (content = $(this.primary)) && $('}')) { + return content; + } + }, + + // div, .class, body > p {...} + ruleset: function() { + var selectors = [], s, f, l, rules, filters = []; + save(); + + while (s = $(this.selector)) { + selectors.push(s); + while ($(this.comment)) {} + if (! $(',')) { break; } + while ($(this.comment)) {} + } + if (s) { + while ($(this.comment)) {} + } + + if (selectors.length > 0 && (rules = $(this.block))) { + if (selectors.length === 1 && + selectors[0].elements.length && + selectors[0].elements[0].value === 'Map') { + var rs = new tree.Ruleset(selectors, rules); + rs.isMap = true; + return rs; + } + return new tree.Ruleset(selectors, rules); + } else { + // Backtrack + restore(); + } + }, + + rule: function() { + var name, value, c = input.charAt(i); + save(); + + if (c === '.' || c === '#') { return; } + + if (name = $(this.variable) || $(this.property)) { + value = $(this.value); + + if (value && $(this.end)) { + return new tree.Rule(name, value, memo, env.filename); + } else { + furthest = i; + restore(); + } + } + }, + + font: function() { + var value = [], expression = [], weight, font, e; + + while (e = $(this.entity)) { + expression.push(e); + } + + value.push(new tree.Expression(expression)); + + if ($(',')) { + while (e = $(this.expression)) { + value.push(e); + if (! $(',')) { break; } + } + } + return new tree.Value(value); + }, + + // A Value is a comma-delimited list of Expressions + // In a Rule, a Value represents everything after the `:`, + // and before the `;`. + value: function() { + var e, expressions = []; + + while (e = $(this.expression)) { + expressions.push(e); + if (! $(',')) { break; } + } + + if (expressions.length > 1) { + return new tree.Value(expressions.map(function(e) { + return e.value[0]; + })); + } else if (expressions.length === 1) { + return new tree.Value(expressions); + } + }, + // A sub-expression, contained by parenthensis + sub: function() { + var e; + + if ($('(') && (e = $(this.expression)) && $(')')) { + return e; + } + }, + // This is a misnomer because it actually handles multiplication + // and division. + multiplication: function() { + var m, a, op, operation; + if (m = $(this.operand)) { + while ((op = ($('/') || $('*') || $('%'))) && (a = $(this.operand))) { + operation = new tree.Operation(op, [operation || m, a], memo); + } + return operation || m; + } + }, + addition: function() { + var m, a, op, operation; + if (m = $(this.multiplication)) { + while ((op = $(/^[-+]\s+/) || (input.charAt(i - 1) != ' ' && ($('+') || $('-')))) && + (a = $(this.multiplication))) { + operation = new tree.Operation(op, [operation || m, a], memo); + } + return operation || m; + } + }, + + // An operand is anything that can be part of an operation, + // such as a Color, or a Variable + operand: function() { + return $(this.sub) || $(this.entity); + }, + + // Expressions either represent mathematical operations, + // or white-space delimited Entities. @var * 2 + expression: function() { + var e, delim, entities = [], d; + + while (e = $(this.addition) || $(this.entity)) { + entities.push(e); + } + + if (entities.length > 0) { + return new tree.Expression(entities); + } + }, + property: function() { + var name = $(/^(([a-z][-a-z_0-9]*\/)?\*?-?[-a-z_0-9]+)\s*:/); + if (name) return name[1]; + } + } + }; + return parser; +}; + +},{"./tree":7,"underscore":37}],4:[function(require,module,exports){ +var _ = require('underscore'); +var carto = require('./index'); + +carto.Renderer = function Renderer(env, options) { + this.env = env || {}; + this.options = options || {}; + this.options.mapnik_version = this.options.mapnik_version || '3.0.0'; +}; + +/** + * Prepare a MSS document (given as an string) into a + * XML Style fragment (mostly useful for debugging) + * + * @param {String} data the mss contents as a string. + */ +carto.Renderer.prototype.renderMSS = function render(data) { + // effects is a container for side-effects, which currently + // are limited to FontSets. + var env = _(this.env).defaults({ + benchmark: false, + validation_data: false, + effects: [] + }); + + if (!carto.tree.Reference.setVersion(this.options.mapnik_version)) { + throw new Error("Could not set mapnik version to " + this.options.mapnik_version); + } + + var output = []; + var styles = []; + + if (env.benchmark) console.time('Parsing MSS'); + var parser = (carto.Parser(env)).parse(data); + if (env.benchmark) console.timeEnd('Parsing MSS'); + + if (env.benchmark) console.time('Rule generation'); + var rule_list = parser.toList(env); + if (env.benchmark) console.timeEnd('Rule generation'); + + if (env.benchmark) console.time('Rule inheritance'); + var rules = inheritDefinitions(rule_list, env); + if (env.benchmark) console.timeEnd('Rule inheritance'); + + if (env.benchmark) console.time('Style sort'); + var sorted = sortStyles(rules,env); + if (env.benchmark) console.timeEnd('Style sort'); + + if (env.benchmark) console.time('Total Style generation'); + for (var k = 0, rule, style_name; k < sorted.length; k++) { + rule = sorted[k]; + style_name = 'style' + (rule.attachment !== '__default__' ? '-' + rule.attachment : ''); + styles.push(style_name); + var bench_name = '\tStyle "'+style_name+'" (#'+k+') toXML'; + if (env.benchmark) console.time(bench_name); + // env.effects can be modified by this call + output.push(carto.tree.StyleXML(style_name, rule.attachment, rule, env)); + if (env.benchmark) console.timeEnd(bench_name); + } + if (env.benchmark) console.timeEnd('Total Style generation'); + if (env.errors) throw env.errors; + return output.join('\n'); +}; + +/** + * Prepare a MML document (given as an object) into a + * fully-localized XML file ready for Mapnik2 consumption + * + * @param {String} m - the JSON file as a string. + */ +carto.Renderer.prototype.render = function render(m) { + // effects is a container for side-effects, which currently + // are limited to FontSets. + var env = _(this.env).defaults({ + benchmark: false, + validation_data: false, + effects: [], + ppi: 90.714 + }); + + if (!carto.tree.Reference.setVersion(this.options.mapnik_version)) { + throw new Error("Could not set mapnik version to " + this.options.mapnik_version); + } + + var output = []; + + // Transform stylesheets into definitions. + var definitions = _(m.Stylesheet).chain() + .map(function(s) { + if (typeof s == 'string') { + throw new Error("Stylesheet object is expected not a string: '" + s + "'"); + } + // Passing the environment from stylesheet to stylesheet, + // allows frames and effects to be maintained. + env = _(env).extend({filename:s.id}); + + var time = +new Date(), + root = (carto.Parser(env)).parse(s.data); + if (env.benchmark) + console.warn('Parsing time: ' + (new Date() - time) + 'ms'); + return root.toList(env); + }) + .flatten() + .value(); + + function appliesTo(name, classIndex) { + return function(definition) { + return definition.appliesTo(l.name, classIndex); + }; + } + + // Iterate through layers and create styles custom-built + // for each of them, and apply those styles to the layers. + var styles, l, classIndex, rules, sorted, matching; + for (var i = 0; i < m.Layer.length; i++) { + l = m.Layer[i]; + styles = []; + classIndex = {}; + + if (env.benchmark) console.warn('processing layer: ' + l.id); + // Classes are given as space-separated alphanumeric strings. + var classes = (l['class'] || '').split(/\s+/g); + for (var j = 0; j < classes.length; j++) { + classIndex[classes[j]] = true; + } + matching = definitions.filter(appliesTo(l.name, classIndex)); + rules = inheritDefinitions(matching, env); + sorted = sortStyles(rules, env); + + for (var k = 0, rule, style_name; k < sorted.length; k++) { + rule = sorted[k]; + style_name = l.name + (rule.attachment !== '__default__' ? '-' + rule.attachment : ''); + + // env.effects can be modified by this call + var styleXML = carto.tree.StyleXML(style_name, rule.attachment, rule, env); + + if (styleXML) { + output.push(styleXML); + styles.push(style_name); + } + } + + output.push(carto.tree.LayerXML(l, styles)); + } + + output.unshift(env.effects.map(function(e) { + return e.toXML(env); + }).join('\n')); + + var map_properties = getMapProperties(m, definitions, env); + + // Exit on errors. + if (env.errors) throw env.errors; + + // Pass TileJSON and other custom parameters through to Mapnik XML. + var parameters = _(m).reduce(function(memo, v, k) { + if (!v && v !== 0) return memo; + + switch (k) { + // Known skippable properties. + case 'srs': + case 'Layer': + case 'Stylesheet': + break; + // Non URL-bound TileJSON properties. + case 'bounds': + case 'center': + case 'minzoom': + case 'maxzoom': + case 'version': + memo.push(' ' + v + ''); + break; + // Properties that require CDATA. + case 'name': + case 'description': + case 'legend': + case 'attribution': + case 'template': + memo.push(' '); + break; + // Mapnik image format. + case 'format': + memo.push(' ' + v + ''); + break; + // Mapnik interactivity settings. + case 'interactivity': + memo.push(' ' + v.layer + ''); + memo.push(' ' + v.fields + ''); + break; + // Support any additional scalar properties. + default: + if ('string' === typeof v) { + memo.push(' '); + } else if ('number' === typeof v) { + memo.push(' ' + v + ''); + } else if ('boolean' === typeof v) { + memo.push(' ' + v + ''); + } + break; + } + return memo; + }, []); + if (parameters.length) output.unshift( + '\n' + + parameters.join('\n') + + '\n\n' + ); + + var properties = _(map_properties).map(function(v) { return ' ' + v; }).join(''); + + output.unshift( + '\n' + + '\n' + + '\n'); + output.push(''); + return output.join('\n'); +}; + +/** + * This function currently modifies 'current' + * @param {Array} current current list of rules + * @param {Object} definition a Definition object to add to the rules + * @param {Object} byFilter an object/dictionary of existing filters. This is + * actually keyed `attachment->filter` + * @param {Object} env the current environment +*/ +function addRules(current, definition, byFilter, env) { + var newFilters = definition.filters, + newRules = definition.rules, + updatedFilters, clone, previous; + + // The current definition might have been split up into + // multiple definitions already. + for (var k = 0; k < current.length; k++) { + updatedFilters = current[k].filters.cloneWith(newFilters); + if (updatedFilters) { + previous = byFilter[updatedFilters]; + if (previous) { + // There's already a definition with those exact + // filters. Add the current definitions' rules + // and stop processing it as the existing rule + // has already gone down the inheritance chain. + previous.addRules(newRules); + } else { + clone = current[k].clone(updatedFilters); + // Make sure that we're only maintaining the clone + // when we did actually add rules. If not, there's + // no need to keep the clone around. + if (clone.addRules(newRules)) { + // We inserted an element before this one, so we need + // to make sure that in the next loop iteration, we're + // not performing the same task for this element again, + // hence the k++. + byFilter[updatedFilters] = clone; + current.splice(k, 0, clone); + k++; + } + } + } else if (updatedFilters === null) { + // if updatedFilters is null, then adding the filters doesn't + // invalidate or split the selector, so we addRules to the + // combined selector + + // Filters can be added, but they don't change the + // filters. This means we don't have to split the + // definition. + // + // this is cloned here because of shared classes, see + // sharedclass.mss + current[k] = current[k].clone(); + current[k].addRules(newRules); + } + // if updatedFeatures is false, then the filters split the rule, + // so they aren't the same inheritance chain + } + return current; +} + +/** + * Apply inherited styles from their ancestors to them. + * + * called either once per render (in the case of mss) or per layer + * (for mml) + * + * @param {Object} definitions - a list of definitions objects + * that contain .rules + * @param {Object} env - the environment + * @return {Array} an array of arrays is returned, + * in which each array refers to a specific attachment + */ +function inheritDefinitions(definitions, env) { + var inheritTime = +new Date(); + // definitions are ordered by specificity, + // high (index 0) to low + var byAttachment = {}, + byFilter = {}; + var result = []; + var current, previous, attachment; + + // Evaluate the filters specified by each definition with the given + // environment to correctly resolve variable references + definitions.forEach(function(d) { + d.filters.ev(env); + }); + + for (var i = 0; i < definitions.length; i++) { + + attachment = definitions[i].attachment; + current = [definitions[i]]; + + if (!byAttachment[attachment]) { + byAttachment[attachment] = []; + byAttachment[attachment].attachment = attachment; + byFilter[attachment] = {}; + result.push(byAttachment[attachment]); + } + + // Iterate over all subsequent rules. + for (var j = i + 1; j < definitions.length; j++) { + if (definitions[j].attachment === attachment) { + // Only inherit rules from the same attachment. + current = addRules(current, definitions[j], byFilter[attachment], env); + } + } + + for (var k = 0; k < current.length; k++) { + byFilter[attachment][current[k].filters] = current[k]; + byAttachment[attachment].push(current[k]); + } + } + + if (env.benchmark) console.warn('Inheritance time: ' + ((new Date() - inheritTime)) + 'ms'); + + return result; + +} + +// Sort styles by the minimum index of their rules. +// This sorts a slice of the styles, so it returns a sorted +// array but does not change the input. +function sortStylesIndex(a, b) { return b.index - a.index; } +function sortStyles(styles, env) { + for (var i = 0; i < styles.length; i++) { + var style = styles[i]; + style.index = Infinity; + for (var b = 0; b < style.length; b++) { + var rules = style[b].rules; + for (var r = 0; r < rules.length; r++) { + var rule = rules[r]; + if (rule.index < style.index) { + style.index = rule.index; + } + } + } + } + + var result = styles.slice(); + result.sort(sortStylesIndex); + return result; +} + +/** + * Find a rule like Map { background-color: #fff; }, + * if any, and return a list of properties to be inserted + * into the = minzoom - 1e-6 and scale < maxzoom + 1e-6" + }, + "maxzoom": { + "default-value": "1.79769e+308", + "type":"float", + "default-meaning": "The layer will be visible at the maximum possible scale", + "doc": "The maximum scale denominator that this layer will be visible at. The default is the numeric limit of the C++ double type, which may vary slightly by system, but is likely a massive number like 1.79769e+308 and ensures that this layer will always be visible unless the value is reduced. A layer's visibility is determined by whether its status is true and if the Map scale >= minzoom - 1e-6 and scale < maxzoom + 1e-6" + }, + "queryable": { + "default-value": false, + "type":"boolean", + "default-meaning": "The layer will not be available for the direct querying of data values", + "doc": "This property was added for GetFeatureInfo/WMS compatibility and is rarely used. It is off by default meaning that in a WMS context the layer will not be able to be queried unless the property is explicitly set to true" + }, + "clear-label-cache": { + "default-value": false, + "type":"boolean", + "default-meaning": "The renderer's collision detector cache (used for avoiding duplicate labels and overlapping markers) will not be cleared immediately before processing this layer", + "doc": "This property, by default off, can be enabled to allow a user to clear the collision detector cache before a given layer is processed. This may be desirable to ensure that a given layers data shows up on the map even if it normally would not because of collisions with previously rendered labels or markers" + }, + "group-by": { + "default-value": "", + "type":"string", + "default-meaning": "No special layer grouping will be used during rendering", + "doc": "https://github.com/mapnik/mapnik/wiki/Grouped-rendering" + }, + "buffer-size": { + "default-value": "0", + "type":"float", + "default-meaning": "No buffer will be used", + "doc": "Extra tolerance around the Layer extent (in pixels) used to when querying and (potentially) clipping the layer data during rendering" + }, + "maximum-extent": { + "default-value": "none", + "type":"bbox", + "default-meaning": "No clipping extent will be used", + "doc": "An extent to be used to limit the bounds used to query this specific layer data during rendering. Should be minx, miny, maxx, maxy in the coordinates of the Layer." + } + }, + "symbolizers" : { + "*": { + "image-filters": { + "css": "image-filters", + "default-value": "none", + "default-meaning": "no filters", + "type": "functions", + "functions": [ + ["agg-stack-blur", 2], + ["emboss", 0], + ["blur", 0], + ["gray", 0], + ["sobel", 0], + ["edge-detect", 0], + ["x-gradient", 0], + ["y-gradient", 0], + ["invert", 0], + ["sharpen", 0] + ], + "doc": "A list of image filters." + }, + "comp-op": { + "css": "comp-op", + "default-value": "src-over", + "default-meaning": "add the current layer on top of other layers", + "doc": "Composite operation. This defines how this layer should behave relative to layers atop or below it.", + "type": ["clear", + "src", + "dst", + "src-over", + "source-over", // added for torque + "dst-over", + "src-in", + "dst-in", + "src-out", + "dst-out", + "src-atop", + "dst-atop", + "xor", + "plus", + "minus", + "multiply", + "screen", + "overlay", + "darken", + "lighten", + "lighter", // added for torque + "color-dodge", + "color-burn", + "hard-light", + "soft-light", + "difference", + "exclusion", + "contrast", + "invert", + "invert-rgb", + "grain-merge", + "grain-extract", + "hue", + "saturation", + "color", + "value" + ] + }, + "opacity": { + "css": "opacity", + "type": "float", + "doc": "An alpha value for the style (which means an alpha applied to all features in separate buffer and then composited back to main buffer)", + "default-value": 1, + "default-meaning": "no separate buffer will be used and no alpha will be applied to the style after rendering" + } + }, + "map": { + "background-color": { + "css": "background-color", + "default-value": "none", + "default-meaning": "transparent", + "type": "color", + "doc": "Map Background color" + }, + "background-image": { + "css": "background-image", + "type": "uri", + "default-value": "", + "default-meaning": "transparent", + "doc": "An image that is repeated below all features on a map as a background.", + "description": "Map Background image" + }, + "srs": { + "css": "srs", + "type": "string", + "default-value": "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs", + "default-meaning": "The proj4 literal of EPSG:4326 is assumed to be the Map's spatial reference and all data from layers within this map will be plotted using this coordinate system. If any layers do not declare an srs value then they will be assumed to be in the same srs as the Map and not transformations will be needed to plot them in the Map's coordinate space", + "doc": "Map spatial reference (proj4 string)" + }, + "buffer-size": { + "css": "buffer-size", + "default-value": "0", + "type":"float", + "default-meaning": "No buffer will be used", + "doc": "Extra tolerance around the map (in pixels) used to ensure labels crossing tile boundaries are equally rendered in each tile (e.g. cut in each tile). Not intended to be used in combination with \"avoid-edges\"." + }, + "maximum-extent": { + "css": "", + "default-value": "none", + "type":"bbox", + "default-meaning": "No clipping extent will be used", + "doc": "An extent to be used to limit the bounds used to query all layers during rendering. Should be minx, miny, maxx, maxy in the coordinates of the Map." + }, + "base": { + "css": "base", + "default-value": "", + "default-meaning": "This base path defaults to an empty string meaning that any relative paths to files referenced in styles or layers will be interpreted relative to the application process.", + "type": "string", + "doc": "Any relative paths used to reference files will be understood as relative to this directory path if the map is loaded from an in memory object rather than from the filesystem. If the map is loaded from the filesystem and this option is not provided it will be set to the directory of the stylesheet." + }, + "paths-from-xml": { + "css": "", + "default-value": true, + "default-meaning": "Paths read from XML will be interpreted from the location of the XML", + "type": "boolean", + "doc": "value to control whether paths in the XML will be interpreted from the location of the XML or from the working directory of the program that calls load_map()" + }, + "minimum-version": { + "css": "", + "default-value": "none", + "default-meaning": "Mapnik version will not be detected and no error will be thrown about compatibility", + "type": "string", + "doc": "The minumum Mapnik version (e.g. 0.7.2) needed to use certain functionality in the stylesheet" + }, + "font-directory": { + "css": "font-directory", + "type": "uri", + "default-value": "none", + "default-meaning": "No map-specific fonts will be registered", + "doc": "Path to a directory which holds fonts which should be registered when the Map is loaded (in addition to any fonts that may be automatically registered)." + } + }, + "polygon": { + "fill": { + "css": "polygon-fill", + "type": "color", + "default-value": "rgba(128,128,128,1)", + "default-meaning": "gray and fully opaque (alpha = 1), same as rgb(128,128,128)", + "doc": "Fill color to assign to a polygon" + }, + "fill-opacity": { + "css": "polygon-opacity", + "type": "float", + "doc": "The opacity of the polygon", + "default-value": 1, + "default-meaning": "opaque" + }, + "gamma": { + "css": "polygon-gamma", + "type": "float", + "default-value": 1, + "default-meaning": "fully antialiased", + "range": "0-1", + "doc": "Level of antialiasing of polygon edges" + }, + "gamma-method": { + "css": "polygon-gamma-method", + "type": [ + "power", + "linear", + "none", + "threshold", + "multiply" + ], + "default-value": "power", + "default-meaning": "pow(x,gamma) is used to calculate pixel gamma, which produces slightly smoother line and polygon antialiasing than the 'linear' method, while other methods are usually only used to disable AA", + "doc": "An Antigrain Geometry specific rendering hint to control the quality of antialiasing. Under the hood in Mapnik this method is used in combination with the 'gamma' value (which defaults to 1). The methods are in the AGG source at https://github.com/mapnik/mapnik/blob/master/deps/agg/include/agg_gamma_functions.h" + }, + "clip": { + "css": "polygon-clip", + "type": "boolean", + "default-value": true, + "default-meaning": "geometry will be clipped to map bounds before rendering", + "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." + }, + "smooth": { + "css": "polygon-smooth", + "type": "float", + "default-value": 0, + "default-meaning": "no smoothing", + "range": "0-1", + "doc": "Smooths out geometry angles. 0 is no smoothing, 1 is fully smoothed. Values greater than 1 will produce wild, looping geometries." + }, + "geometry-transform": { + "css": "polygon-geometry-transform", + "type": "functions", + "default-value": "none", + "default-meaning": "geometry will not be transformed", + "doc": "Allows transformation functions to be applied to the geometry.", + "functions": [ + ["matrix", 6], + ["translate", 2], + ["scale", 2], + ["rotate", 3], + ["skewX", 1], + ["skewY", 1] + ] + }, + "comp-op": { + "css": "polygon-comp-op", + "default-value": "src-over", + "default-meaning": "add the current symbolizer on top of other symbolizer", + "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", + "type": ["clear", + "src", + "dst", + "src-over", + "dst-over", + "src-in", + "dst-in", + "src-out", + "dst-out", + "src-atop", + "dst-atop", + "xor", + "plus", + "minus", + "multiply", + "screen", + "overlay", + "darken", + "lighten", + "color-dodge", + "color-burn", + "hard-light", + "soft-light", + "difference", + "exclusion", + "contrast", + "invert", + "invert-rgb", + "grain-merge", + "grain-extract", + "hue", + "saturation", + "color", + "value" + ] + } + }, + "line": { + "stroke": { + "css": "line-color", + "default-value": "rgba(0,0,0,1)", + "type": "color", + "default-meaning": "black and fully opaque (alpha = 1), same as rgb(0,0,0)", + "doc": "The color of a drawn line" + }, + "stroke-width": { + "css": "line-width", + "default-value": 1, + "type": "float", + "doc": "The width of a line in pixels" + }, + "stroke-opacity": { + "css": "line-opacity", + "default-value": 1, + "type": "float", + "default-meaning": "opaque", + "doc": "The opacity of a line" + }, + "stroke-linejoin": { + "css": "line-join", + "default-value": "miter", + "type": [ + "miter", + "round", + "bevel" + ], + "doc": "The behavior of lines when joining" + }, + "stroke-linecap": { + "css": "line-cap", + "default-value": "butt", + "type": [ + "butt", + "round", + "square" + ], + "doc": "The display of line endings" + }, + "stroke-gamma": { + "css": "line-gamma", + "type": "float", + "default-value": 1, + "default-meaning": "fully antialiased", + "range": "0-1", + "doc": "Level of antialiasing of stroke line" + }, + "stroke-gamma-method": { + "css": "line-gamma-method", + "type": [ + "power", + "linear", + "none", + "threshold", + "multiply" + ], + "default-value": "power", + "default-meaning": "pow(x,gamma) is used to calculate pixel gamma, which produces slightly smoother line and polygon antialiasing than the 'linear' method, while other methods are usually only used to disable AA", + "doc": "An Antigrain Geometry specific rendering hint to control the quality of antialiasing. Under the hood in Mapnik this method is used in combination with the 'gamma' value (which defaults to 1). The methods are in the AGG source at https://github.com/mapnik/mapnik/blob/master/deps/agg/include/agg_gamma_functions.h" + }, + "stroke-dasharray": { + "css": "line-dasharray", + "type": "numbers", + "doc": "A pair of length values [a,b], where (a) is the dash length and (b) is the gap length respectively. More than two values are supported for more complex patterns.", + "default-value": "none", + "default-meaning": "solid line" + }, + "stroke-dashoffset": { + "css": "line-dash-offset", + "type": "numbers", + "doc": "valid parameter but not currently used in renderers (only exists for experimental svg support in Mapnik which is not yet enabled)", + "default-value": "none", + "default-meaning": "solid line" + }, + "stroke-miterlimit": { + "css": "line-miterlimit", + "type": "float", + "doc": "The limit on the ratio of the miter length to the stroke-width. Used to automatically convert miter joins to bevel joins for sharp angles to avoid the miter extending beyond the thickness of the stroking path. Normally will not need to be set, but a larger value can sometimes help avoid jaggy artifacts.", + "default-value": 4.0, + "default-meaning": "Will auto-convert miters to bevel line joins when theta is less than 29 degrees as per the SVG spec: 'miterLength / stroke-width = 1 / sin ( theta / 2 )'" + }, + "clip": { + "css": "line-clip", + "type": "boolean", + "default-value": true, + "default-meaning": "geometry will be clipped to map bounds before rendering", + "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." + }, + "smooth": { + "css": "line-smooth", + "type": "float", + "default-value": 0, + "default-meaning": "no smoothing", + "range": "0-1", + "doc": "Smooths out geometry angles. 0 is no smoothing, 1 is fully smoothed. Values greater than 1 will produce wild, looping geometries." + }, + "offset": { + "css": "line-offset", + "type": "float", + "default-value": 0, + "default-meaning": "no offset", + "doc": "Offsets a line a number of pixels parallel to its actual path. Postive values move the line left, negative values move it right (relative to the directionality of the line)." + }, + "rasterizer": { + "css": "line-rasterizer", + "type": [ + "full", + "fast" + ], + "default-value": "full", + "doc": "Exposes an alternate AGG rendering method that sacrifices some accuracy for speed." + }, + "geometry-transform": { + "css": "line-geometry-transform", + "type": "functions", + "default-value": "none", + "default-meaning": "geometry will not be transformed", + "doc": "Allows transformation functions to be applied to the geometry.", + "functions": [ + ["matrix", 6], + ["translate", 2], + ["scale", 2], + ["rotate", 3], + ["skewX", 1], + ["skewY", 1] + ] + }, + "comp-op": { + "css": "line-comp-op", + "default-value": "src-over", + "default-meaning": "add the current symbolizer on top of other symbolizer", + "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", + "type": ["clear", + "src", + "dst", + "src-over", + "dst-over", + "src-in", + "dst-in", + "src-out", + "dst-out", + "src-atop", + "dst-atop", + "xor", + "plus", + "minus", + "multiply", + "screen", + "overlay", + "darken", + "lighten", + "color-dodge", + "color-burn", + "hard-light", + "soft-light", + "difference", + "exclusion", + "contrast", + "invert", + "invert-rgb", + "grain-merge", + "grain-extract", + "hue", + "saturation", + "color", + "value" + ] + } + }, + "markers": { + "file": { + "css": "marker-file", + "doc": "An SVG file that this marker shows at each placement. If no file is given, the marker will show an ellipse.", + "default-value": "", + "default-meaning": "An ellipse or circle, if width equals height", + "type": "uri" + }, + "opacity": { + "css": "marker-opacity", + "doc": "The overall opacity of the marker, if set, overrides both the opacity of both the fill and stroke", + "default-value": 1, + "default-meaning": "The stroke-opacity and fill-opacity will be used", + "type": "float" + }, + "fill-opacity": { + "css": "marker-fill-opacity", + "doc": "The fill opacity of the marker", + "default-value": 1, + "default-meaning": "opaque", + "type": "float" + }, + "stroke": { + "css": "marker-line-color", + "doc": "The color of the stroke around a marker shape.", + "default-value": "black", + "type": "color" + }, + "stroke-width": { + "css": "marker-line-width", + "doc": "The width of the stroke around a marker shape, in pixels. This is positioned on the boundary, so high values can cover the area itself.", + "type": "float" + }, + "stroke-opacity": { + "css": "marker-line-opacity", + "default-value": 1, + "default-meaning": "opaque", + "doc": "The opacity of a line", + "type": "float" + }, + "placement": { + "css": "marker-placement", + "type": [ + "point", + "line", + "interior" + ], + "default-value": "point", + "default-meaning": "Place markers at the center point (centroid) of the geometry", + "doc": "Attempt to place markers on a point, in the center of a polygon, or if markers-placement:line, then multiple times along a line. 'interior' placement can be used to ensure that points placed on polygons are forced to be inside the polygon interior" + }, + "multi-policy": { + "css": "marker-multi-policy", + "type": [ + "each", + "whole", + "largest" + ], + "default-value": "each", + "default-meaning": "If a feature contains multiple geometries and the placement type is either point or interior then a marker will be rendered for each", + "doc": "A special setting to allow the user to control rendering behavior for 'multi-geometries' (when a feature contains multiple geometries). This setting does not apply to markers placed along lines. The 'each' policy is default and means all geometries will get a marker. The 'whole' policy means that the aggregate centroid between all geometries will be used. The 'largest' policy means that only the largest (by bounding box areas) feature will get a rendered marker (this is how text labeling behaves by default)." + }, + "marker-type": { + "css": "marker-type", + "type": [ + "arrow", + "ellipse", + "rectangle" + ], + "default-value": "ellipse", + "doc": "The default marker-type. If a SVG file is not given as the marker-file parameter, the renderer provides either an arrow or an ellipse (a circle if height is equal to width)" + }, + "width": { + "css": "marker-width", + "default-value": 10, + "doc": "The width of the marker, if using one of the default types.", + "type": "expression" + }, + "height": { + "css": "marker-height", + "default-value": 10, + "doc": "The height of the marker, if using one of the default types.", + "type": "expression" + }, + "fill": { + "css": "marker-fill", + "default-value": "blue", + "doc": "The color of the area of the marker.", + "type": "color" + }, + "allow-overlap": { + "css": "marker-allow-overlap", + "type": "boolean", + "default-value": false, + "doc": "Control whether overlapping markers are shown or hidden.", + "default-meaning": "Do not allow makers to overlap with each other - overlapping markers will not be shown." + }, + "ignore-placement": { + "css": "marker-ignore-placement", + "type": "boolean", + "default-value": false, + "default-meaning": "do not store the bbox of this geometry in the collision detector cache", + "doc": "value to control whether the placement of the feature will prevent the placement of other features" + }, + "spacing": { + "css": "marker-spacing", + "doc": "Space between repeated labels", + "default-value": 100, + "type": "float" + }, + "max-error": { + "css": "marker-max-error", + "type": "float", + "default-value": 0.2, + "doc": "The maximum difference between actual marker placement and the marker-spacing parameter. Setting a high value can allow the renderer to try to resolve placement conflicts with other symbolizers." + }, + "transform": { + "css": "marker-transform", + "type": "functions", + "functions": [ + ["matrix", 6], + ["translate", 2], + ["scale", 2], + ["rotate", 3], + ["skewX", 1], + ["skewY", 1] + ], + "default-value": "", + "default-meaning": "No transformation", + "doc": "SVG transformation definition" + }, + "clip": { + "css": "marker-clip", + "type": "boolean", + "default-value": true, + "default-meaning": "geometry will be clipped to map bounds before rendering", + "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." + }, + "smooth": { + "css": "marker-smooth", + "type": "float", + "default-value": 0, + "default-meaning": "no smoothing", + "range": "0-1", + "doc": "Smooths out geometry angles. 0 is no smoothing, 1 is fully smoothed. Values greater than 1 will produce wild, looping geometries." + }, + "geometry-transform": { + "css": "marker-geometry-transform", + "type": "functions", + "default-value": "none", + "default-meaning": "geometry will not be transformed", + "doc": "Allows transformation functions to be applied to the geometry.", + "functions": [ + ["matrix", 6], + ["translate", 2], + ["scale", 2], + ["rotate", 3], + ["skewX", 1], + ["skewY", 1] + ] + }, + "comp-op": { + "css": "marker-comp-op", + "default-value": "src-over", + "default-meaning": "add the current symbolizer on top of other symbolizer", + "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", + "type": ["clear", + "src", + "dst", + "src-over", + "dst-over", + "src-in", + "dst-in", + "src-out", + "dst-out", + "src-atop", + "dst-atop", + "xor", + "plus", + "minus", + "multiply", + "screen", + "overlay", + "darken", + "lighten", + "color-dodge", + "color-burn", + "hard-light", + "soft-light", + "difference", + "exclusion", + "contrast", + "invert", + "invert-rgb", + "grain-merge", + "grain-extract", + "hue", + "saturation", + "color", + "value" + ] + } + }, + "shield": { + "name": { + "css": "shield-name", + "type": "expression", + "serialization": "content", + "doc": "Value to use for a shield\"s text label. Data columns are specified using brackets like [column_name]" + }, + "file": { + "css": "shield-file", + "required": true, + "type": "uri", + "default-value": "none", + "doc": "Image file to render behind the shield text" + }, + "face-name": { + "css": "shield-face-name", + "type": "string", + "validate": "font", + "doc": "Font name and style to use for the shield text", + "default-value": "", + "required": true + }, + "unlock-image": { + "css": "shield-unlock-image", + "type": "boolean", + "doc": "This parameter should be set to true if you are trying to position text beside rather than on top of the shield image", + "default-value": false, + "default-meaning": "text alignment relative to the shield image uses the center of the image as the anchor for text positioning." + }, + "size": { + "css": "shield-size", + "type": "float", + "doc": "The size of the shield text in pixels" + }, + "fill": { + "css": "shield-fill", + "type": "color", + "doc": "The color of the shield text" + }, + "placement": { + "css": "shield-placement", + "type": [ + "point", + "line", + "vertex", + "interior" + ], + "default-value": "point", + "doc": "How this shield should be placed. Point placement attempts to place it on top of points, line places along lines multiple times per feature, vertex places on the vertexes of polygons, and interior attempts to place inside of polygons." + }, + "avoid-edges": { + "css": "shield-avoid-edges", + "doc": "Tell positioning algorithm to avoid labeling near intersection edges.", + "type": "boolean", + "default-value": false + }, + "allow-overlap": { + "css": "shield-allow-overlap", + "type": "boolean", + "default-value": false, + "doc": "Control whether overlapping shields are shown or hidden.", + "default-meaning": "Do not allow shields to overlap with other map elements already placed." + }, + "minimum-distance": { + "css": "shield-min-distance", + "type": "float", + "default-value": 0, + "doc": "Minimum distance to the next shield symbol, not necessarily the same shield." + }, + "spacing": { + "css": "shield-spacing", + "type": "float", + "default-value": 0, + "doc": "The spacing between repeated occurrences of the same shield on a line" + }, + "minimum-padding": { + "css": "shield-min-padding", + "default-value": 0, + "doc": "Determines the minimum amount of padding that a shield gets relative to other shields", + "type": "float" + }, + "wrap-width": { + "css": "shield-wrap-width", + "type": "unsigned", + "default-value": 0, + "doc": "Length of a chunk of text in characters before wrapping text" + }, + "wrap-before": { + "css": "shield-wrap-before", + "type": "boolean", + "default-value": false, + "doc": "Wrap text before wrap-width is reached. If false, wrapped lines will be a bit longer than wrap-width." + }, + "wrap-character": { + "css": "shield-wrap-character", + "type": "string", + "default-value": " ", + "doc": "Use this character instead of a space to wrap long names." + }, + "halo-fill": { + "css": "shield-halo-fill", + "type": "color", + "default-value": "#FFFFFF", + "default-meaning": "white", + "doc": "Specifies the color of the halo around the text." + }, + "halo-radius": { + "css": "shield-halo-radius", + "doc": "Specify the radius of the halo in pixels", + "default-value": 0, + "default-meaning": "no halo", + "type": "float" + }, + "character-spacing": { + "css": "shield-character-spacing", + "type": "unsigned", + "default-value": 0, + "doc": "Horizontal spacing between characters (in pixels). Currently works for point placement only, not line placement." + }, + "line-spacing": { + "css": "shield-line-spacing", + "doc": "Vertical spacing between lines of multiline labels (in pixels)", + "type": "unsigned" + }, + "dx": { + "css": "shield-text-dx", + "type": "float", + "doc": "Displace text within shield by fixed amount, in pixels, +/- along the X axis. A positive value will shift the text right", + "default-value": 0 + }, + "dy": { + "css": "shield-text-dy", + "type": "float", + "doc": "Displace text within shield by fixed amount, in pixels, +/- along the Y axis. A positive value will shift the text down", + "default-value": 0 + }, + "shield-dx": { + "css": "shield-dx", + "type": "float", + "doc": "Displace shield by fixed amount, in pixels, +/- along the X axis. A positive value will shift the text right", + "default-value": 0 + }, + "shield-dy": { + "css": "shield-dy", + "type": "float", + "doc": "Displace shield by fixed amount, in pixels, +/- along the Y axis. A positive value will shift the text down", + "default-value": 0 + }, + "opacity": { + "css": "shield-opacity", + "type": "float", + "doc": "(Default 1.0) - opacity of the image used for the shield", + "default-value": 1 + }, + "text-opacity": { + "css": "shield-text-opacity", + "type": "float", + "doc": "(Default 1.0) - opacity of the text placed on top of the shield", + "default-value": 1 + }, + "horizontal-alignment": { + "css": "shield-horizontal-alignment", + "type": [ + "left", + "middle", + "right", + "auto" + ], + "doc": "The shield's horizontal alignment from its centerpoint", + "default-value": "auto" + }, + "vertical-alignment": { + "css": "shield-vertical-alignment", + "type": [ + "top", + "middle", + "bottom", + "auto" + ], + "doc": "The shield's vertical alignment from its centerpoint", + "default-value": "middle" + }, + "text-transform": { + "css": "shield-text-transform", + "type": [ + "none", + "uppercase", + "lowercase", + "capitalize" + ], + "doc": "Transform the case of the characters", + "default-value": "none" + }, + "justify-alignment": { + "css": "shield-justify-alignment", + "type": [ + "left", + "center", + "right", + "auto" + ], + "doc": "Define how text in a shield's label is justified", + "default-value": "auto" + }, + "clip": { + "css": "shield-clip", + "type": "boolean", + "default-value": true, + "default-meaning": "geometry will be clipped to map bounds before rendering", + "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." + }, + "comp-op": { + "css": "shield-comp-op", + "default-value": "src-over", + "default-meaning": "add the current symbolizer on top of other symbolizer", + "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", + "type": ["clear", + "src", + "dst", + "src-over", + "dst-over", + "src-in", + "dst-in", + "src-out", + "dst-out", + "src-atop", + "dst-atop", + "xor", + "plus", + "minus", + "multiply", + "screen", + "overlay", + "darken", + "lighten", + "color-dodge", + "color-burn", + "hard-light", + "soft-light", + "difference", + "exclusion", + "contrast", + "invert", + "invert-rgb", + "grain-merge", + "grain-extract", + "hue", + "saturation", + "color", + "value" + ] + } + }, + "line-pattern": { + "file": { + "css": "line-pattern-file", + "type": "uri", + "default-value": "none", + "required": true, + "doc": "An image file to be repeated and warped along a line" + }, + "clip": { + "css": "line-pattern-clip", + "type": "boolean", + "default-value": true, + "default-meaning": "geometry will be clipped to map bounds before rendering", + "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." + }, + "smooth": { + "css": "line-pattern-smooth", + "type": "float", + "default-value": 0, + "default-meaning": "no smoothing", + "range": "0-1", + "doc": "Smooths out geometry angles. 0 is no smoothing, 1 is fully smoothed. Values greater than 1 will produce wild, looping geometries." + }, + "geometry-transform": { + "css": "line-pattern-geometry-transform", + "type": "functions", + "default-value": "none", + "default-meaning": "geometry will not be transformed", + "doc": "Allows transformation functions to be applied to the geometry.", + "functions": [ + ["matrix", 6], + ["translate", 2], + ["scale", 2], + ["rotate", 3], + ["skewX", 1], + ["skewY", 1] + ] + }, + "comp-op": { + "css": "line-pattern-comp-op", + "default-value": "src-over", + "default-meaning": "add the current symbolizer on top of other symbolizer", + "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", + "type": ["clear", + "src", + "dst", + "src-over", + "dst-over", + "src-in", + "dst-in", + "src-out", + "dst-out", + "src-atop", + "dst-atop", + "xor", + "plus", + "minus", + "multiply", + "screen", + "overlay", + "darken", + "lighten", + "color-dodge", + "color-burn", + "hard-light", + "soft-light", + "difference", + "exclusion", + "contrast", + "invert", + "invert-rgb", + "grain-merge", + "grain-extract", + "hue", + "saturation", + "color", + "value" + ] + } + }, + "polygon-pattern": { + "file": { + "css": "polygon-pattern-file", + "type": "uri", + "default-value": "none", + "required": true, + "doc": "Image to use as a repeated pattern fill within a polygon" + }, + "alignment": { + "css": "polygon-pattern-alignment", + "type": [ + "local", + "global" + ], + "default-value": "local", + "doc": "Specify whether to align pattern fills to the layer or to the map." + }, + "gamma": { + "css": "polygon-pattern-gamma", + "type": "float", + "default-value": 1, + "default-meaning": "fully antialiased", + "range": "0-1", + "doc": "Level of antialiasing of polygon pattern edges" + }, + "opacity": { + "css": "polygon-pattern-opacity", + "type": "float", + "doc": "(Default 1.0) - Apply an opacity level to the image used for the pattern", + "default-value": 1, + "default-meaning": "The image is rendered without modifications" + }, + "clip": { + "css": "polygon-pattern-clip", + "type": "boolean", + "default-value": true, + "default-meaning": "geometry will be clipped to map bounds before rendering", + "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." + }, + "smooth": { + "css": "polygon-pattern-smooth", + "type": "float", + "default-value": 0, + "default-meaning": "no smoothing", + "range": "0-1", + "doc": "Smooths out geometry angles. 0 is no smoothing, 1 is fully smoothed. Values greater than 1 will produce wild, looping geometries." + }, + "geometry-transform": { + "css": "polygon-pattern-geometry-transform", + "type": "functions", + "default-value": "none", + "default-meaning": "geometry will not be transformed", + "doc": "Allows transformation functions to be applied to the geometry.", + "functions": [ + ["matrix", 6], + ["translate", 2], + ["scale", 2], + ["rotate", 3], + ["skewX", 1], + ["skewY", 1] + ] + }, + "comp-op": { + "css": "polygon-pattern-comp-op", + "default-value": "src-over", + "default-meaning": "add the current symbolizer on top of other symbolizer", + "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", + "type": ["clear", + "src", + "dst", + "src-over", + "dst-over", + "src-in", + "dst-in", + "src-out", + "dst-out", + "src-atop", + "dst-atop", + "xor", + "plus", + "minus", + "multiply", + "screen", + "overlay", + "darken", + "lighten", + "color-dodge", + "color-burn", + "hard-light", + "soft-light", + "difference", + "exclusion", + "contrast", + "invert", + "invert-rgb", + "grain-merge", + "grain-extract", + "hue", + "saturation", + "color", + "value" + ] + } + }, + "raster": { + "opacity": { + "css": "raster-opacity", + "default-value": 1, + "default-meaning": "opaque", + "type": "float", + "doc": "The opacity of the raster symbolizer on top of other symbolizers." + }, + "filter-factor": { + "css": "raster-filter-factor", + "default-value": -1, + "default-meaning": "Allow the datasource to choose appropriate downscaling.", + "type": "float", + "doc": "This is used by the Raster or Gdal datasources to pre-downscale images using overviews. Higher numbers can sometimes cause much better scaled image output, at the cost of speed." + }, + "scaling": { + "css": "raster-scaling", + "type": [ + "near", + "fast", + "bilinear", + "bilinear8", + "bicubic", + "spline16", + "spline36", + "hanning", + "hamming", + "hermite", + "kaiser", + "quadric", + "catrom", + "gaussian", + "bessel", + "mitchell", + "sinc", + "lanczos", + "blackman" + ], + "default-value": "near", + "doc": "The scaling algorithm used to making different resolution versions of this raster layer. Bilinear is a good compromise between speed and accuracy, while lanczos gives the highest quality." + }, + "mesh-size": { + "css": "raster-mesh-size", + "default-value": 16, + "default-meaning": "Reprojection mesh will be 1/16 of the resolution of the source image", + "type": "unsigned", + "doc": "A reduced resolution mesh is used for raster reprojection, and the total image size is divided by the mesh-size to determine the quality of that mesh. Values for mesh-size larger than the default will result in faster reprojection but might lead to distortion." + }, + "comp-op": { + "css": "raster-comp-op", + "default-value": "src-over", + "default-meaning": "add the current symbolizer on top of other symbolizer", + "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", + "type": ["clear", + "src", + "dst", + "src-over", + "dst-over", + "src-in", + "dst-in", + "src-out", + "dst-out", + "src-atop", + "dst-atop", + "xor", + "plus", + "minus", + "multiply", + "screen", + "overlay", + "darken", + "lighten", + "color-dodge", + "color-burn", + "hard-light", + "soft-light", + "difference", + "exclusion", + "contrast", + "invert", + "invert-rgb", + "grain-merge", + "grain-extract", + "hue", + "saturation", + "color", + "value" + ] + } + }, + "point": { + "file": { + "css": "point-file", + "type": "uri", + "required": false, + "default-value": "none", + "doc": "Image file to represent a point" + }, + "allow-overlap": { + "css": "point-allow-overlap", + "type": "boolean", + "default-value": false, + "doc": "Control whether overlapping points are shown or hidden.", + "default-meaning": "Do not allow points to overlap with each other - overlapping markers will not be shown." + }, + "ignore-placement": { + "css": "point-ignore-placement", + "type": "boolean", + "default-value": false, + "default-meaning": "do not store the bbox of this geometry in the collision detector cache", + "doc": "value to control whether the placement of the feature will prevent the placement of other features" + }, + "opacity": { + "css": "point-opacity", + "type": "float", + "default-value": 1.0, + "default-meaning": "Fully opaque", + "doc": "A value from 0 to 1 to control the opacity of the point" + }, + "placement": { + "css": "point-placement", + "type": [ + "centroid", + "interior" + ], + "doc": "How this point should be placed. Centroid calculates the geometric center of a polygon, which can be outside of it, while interior always places inside of a polygon.", + "default-value": "centroid" + }, + "transform": { + "css": "point-transform", + "type": "functions", + "functions": [ + ["matrix", 6], + ["translate", 2], + ["scale", 2], + ["rotate", 3], + ["skewX", 1], + ["skewY", 1] + ], + "default-value": "", + "default-meaning": "No transformation", + "doc": "SVG transformation definition" + }, + "comp-op": { + "css": "point-comp-op", + "default-value": "src-over", + "default-meaning": "add the current symbolizer on top of other symbolizer", + "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", + "type": ["clear", + "src", + "dst", + "src-over", + "dst-over", + "src-in", + "dst-in", + "src-out", + "dst-out", + "src-atop", + "dst-atop", + "xor", + "plus", + "minus", + "multiply", + "screen", + "overlay", + "darken", + "lighten", + "color-dodge", + "color-burn", + "hard-light", + "soft-light", + "difference", + "exclusion", + "contrast", + "invert", + "invert-rgb", + "grain-merge", + "grain-extract", + "hue", + "saturation", + "color", + "value" + ] + } + }, + "text": { + "name": { + "css": "text-name", + "type": "expression", + "required": true, + "default-value": "", + "serialization": "content", + "doc": "Value to use for a text label. Data columns are specified using brackets like [column_name]" + }, + "face-name": { + "css": "text-face-name", + "type": "string", + "validate": "font", + "doc": "Font name and style to render a label in", + "required": true + }, + "size": { + "css": "text-size", + "type": "float", + "default-value": 10, + "doc": "Text size in pixels" + }, + "text-ratio": { + "css": "text-ratio", + "doc": "Define the amount of text (of the total) present on successive lines when wrapping occurs", + "default-value": 0, + "type": "unsigned" + }, + "wrap-width": { + "css": "text-wrap-width", + "doc": "Length of a chunk of text in characters before wrapping text", + "default-value": 0, + "type": "unsigned" + }, + "wrap-before": { + "css": "text-wrap-before", + "type": "boolean", + "default-value": false, + "doc": "Wrap text before wrap-width is reached. If false, wrapped lines will be a bit longer than wrap-width." + }, + "wrap-character": { + "css": "text-wrap-character", + "type": "string", + "default-value": " ", + "doc": "Use this character instead of a space to wrap long text." + }, + "spacing": { + "css": "text-spacing", + "type": "unsigned", + "doc": "Distance between repeated text labels on a line (aka. label-spacing)" + }, + "character-spacing": { + "css": "text-character-spacing", + "type": "float", + "default-value": 0, + "doc": "Horizontal spacing adjustment between characters in pixels" + }, + "line-spacing": { + "css": "text-line-spacing", + "default-value": 0, + "type": "unsigned", + "doc": "Vertical spacing adjustment between lines in pixels" + }, + "label-position-tolerance": { + "css": "text-label-position-tolerance", + "default-value": 0, + "type": "unsigned", + "doc": "Allows the label to be displaced from its ideal position by a number of pixels (only works with placement:line)" + }, + "max-char-angle-delta": { + "css": "text-max-char-angle-delta", + "type": "float", + "default-value": "22.5", + "doc": "The maximum angle change, in degrees, allowed between adjacent characters in a label. This value internally is converted to radians to the default is 22.5*math.pi/180.0. The higher the value the fewer labels will be placed around around sharp corners." + }, + "fill": { + "css": "text-fill", + "doc": "Specifies the color for the text", + "default-value": "#000000", + "type": "color" + }, + "opacity": { + "css": "text-opacity", + "doc": "A number from 0 to 1 specifying the opacity for the text", + "default-value": 1.0, + "default-meaning": "Fully opaque", + "type": "float" + }, + "halo-fill": { + "css": "text-halo-fill", + "type": "color", + "default-value": "#FFFFFF", + "default-meaning": "white", + "doc": "Specifies the color of the halo around the text." + }, + "halo-radius": { + "css": "text-halo-radius", + "doc": "Specify the radius of the halo in pixels", + "default-value": 0, + "default-meaning": "no halo", + "type": "float" + }, + "dx": { + "css": "text-dx", + "type": "float", + "doc": "Displace text by fixed amount, in pixels, +/- along the X axis. A positive value will shift the text right", + "default-value": 0 + }, + "dy": { + "css": "text-dy", + "type": "float", + "doc": "Displace text by fixed amount, in pixels, +/- along the Y axis. A positive value will shift the text down", + "default-value": 0 + }, + "vertical-alignment": { + "css": "text-vertical-alignment", + "type": [ + "top", + "middle", + "bottom", + "auto" + ], + "doc": "Position of label relative to point position.", + "default-value": "auto", + "default-meaning": "Default affected by value of dy; \"bottom\" for dy>0, \"top\" for dy<0." + }, + "avoid-edges": { + "css": "text-avoid-edges", + "doc": "Tell positioning algorithm to avoid labeling near intersection edges.", + "default-value": false, + "type": "boolean" + }, + "minimum-distance": { + "css": "text-min-distance", + "doc": "Minimum permitted distance to the next text symbolizer.", + "type": "float" + }, + "minimum-padding": { + "css": "text-min-padding", + "doc": "Determines the minimum amount of padding that a text symbolizer gets relative to other text", + "type": "float" + }, + "minimum-path-length": { + "css": "text-min-path-length", + "type": "float", + "default-value": 0, + "default-meaning": "place labels on all paths", + "doc": "Place labels only on paths longer than this value." + }, + "allow-overlap": { + "css": "text-allow-overlap", + "type": "boolean", + "default-value": false, + "doc": "Control whether overlapping text is shown or hidden.", + "default-meaning": "Do not allow text to overlap with other text - overlapping markers will not be shown." + }, + "orientation": { + "css": "text-orientation", + "type": "expression", + "doc": "Rotate the text." + }, + "placement": { + "css": "text-placement", + "type": [ + "point", + "line", + "vertex", + "interior" + ], + "default-value": "point", + "doc": "Control the style of placement of a point versus the geometry it is attached to." + }, + "placement-type": { + "css": "text-placement-type", + "doc": "Re-position and/or re-size text to avoid overlaps. \"simple\" for basic algorithm (using text-placements string,) \"dummy\" to turn this feature off.", + "type": [ + "dummy", + "simple" + ], + "default-value": "dummy" + }, + "placements": { + "css": "text-placements", + "type": "string", + "default-value": "", + "doc": "If \"placement-type\" is set to \"simple\", use this \"POSITIONS,[SIZES]\" string. An example is `text-placements: \"E,NE,SE,W,NW,SW\";` " + }, + "text-transform": { + "css": "text-transform", + "type": [ + "none", + "uppercase", + "lowercase", + "capitalize" + ], + "doc": "Transform the case of the characters", + "default-value": "none" + }, + "horizontal-alignment": { + "css": "text-horizontal-alignment", + "type": [ + "left", + "middle", + "right", + "auto" + ], + "doc": "The text's horizontal alignment from its centerpoint", + "default-value": "auto" + }, + "justify-alignment": { + "css": "text-align", + "type": [ + "left", + "right", + "center", + "auto" + ], + "doc": "Define how text is justified", + "default-value": "auto", + "default-meaning": "Auto alignment means that text will be centered by default except when using the `placement-type` parameter - in that case either right or left justification will be used automatically depending on where the text could be fit given the `text-placements` directives" + }, + "clip": { + "css": "text-clip", + "type": "boolean", + "default-value": true, + "default-meaning": "geometry will be clipped to map bounds before rendering", + "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." + }, + "comp-op": { + "css": "text-comp-op", + "default-value": "src-over", + "default-meaning": "add the current symbolizer on top of other symbolizer", + "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", + "type": ["clear", + "src", + "dst", + "src-over", + "dst-over", + "src-in", + "dst-in", + "src-out", + "dst-out", + "src-atop", + "dst-atop", + "xor", + "plus", + "minus", + "multiply", + "screen", + "overlay", + "darken", + "lighten", + "color-dodge", + "color-burn", + "hard-light", + "soft-light", + "difference", + "exclusion", + "contrast", + "invert", + "invert-rgb", + "grain-merge", + "grain-extract", + "hue", + "saturation", + "color", + "value" + ] + } + }, + "building": { + "fill": { + "css": "building-fill", + "default-value": "#FFFFFF", + "doc": "The color of the buildings walls.", + "type": "color" + }, + "fill-opacity": { + "css": "building-fill-opacity", + "type": "float", + "doc": "The opacity of the building as a whole, including all walls.", + "default-value": 1 + }, + "height": { + "css": "building-height", + "doc": "The height of the building in pixels.", + "type": "expression", + "default-value": "0" + } + }, + "torque": { + "-torque-frame-count": { + "css": "-torque-frame-count", + "default-value": "128", + "type":"float", + "default-meaning": "the data is broken into 128 time frames", + "doc": "Number of animation steps/frames used in the animation. If the data contains a fewere number of total frames, the lesser value will be used." + }, + "-torque-resolution": { + "css": "-torque-resolution", + "default-value": "2", + "type":"float", + "default-meaning": "", + "doc": "Spatial resolution in pixels. A resolution of 1 means no spatial aggregation of the data. Any other resolution of N results in spatial aggregation into cells of NxN pixels. The value N must be power of 2" + }, + "-torque-animation-duration": { + "css": "-torque-animation-duration", + "default-value": "30", + "type":"float", + "default-meaning": "the animation lasts 30 seconds", + "doc": "Animation duration in seconds" + }, + "-torque-aggregation-function": { + "css": "-torque-aggregation-function", + "default-value": "count(cartodb_id)", + "type": "string", + "default-meaning": "the value for each cell is the count of points in that cell", + "doc": "A function used to calculate a value from the aggregate data for each cell. See -torque-resolution" + }, + "-torque-time-attribute": { + "css": "-torque-time-attribute", + "default-value": "time", + "type": "string", + "default-meaning": "the data column in your table that is of a time based type", + "doc": "The table column that contains the time information used create the animation" + }, + "-torque-data-aggregation": { + "css": "-torque-data-aggregation", + "default-value": "linear", + "type": [ + "linear", + "cumulative" + ], + "default-meaning": "previous values are discarded", + "doc": "A linear animation will discard previous values while a cumulative animation will accumulate them until it restarts" + } + } + }, + "colors": { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255,235,205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "grey": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50], + "transparent": [0, 0, 0, 0] + }, + "filter": { + "value": [ + "true", + "false", + "null", + "point", + "linestring", + "polygon", + "collection" + ] + } +} + +module.exports = { + version: { + latest: _mapnik_reference_latest, + '2.1.1': _mapnik_reference_latest + } +}; + +},{}],7:[function(require,module,exports){ +/** + * TODO: document this. What does this do? + */ +if(typeof(module) !== "undefined") { + module.exports.find = function (obj, fun) { + for (var i = 0, r; i < obj.length; i++) { + if (r = fun.call(obj, obj[i])) { return r; } + } + return null; + }; +} + +},{}],8:[function(require,module,exports){ +(function(tree) { +var _ = require('underscore'); +tree.Call = function Call(name, args, index) { + this.name = name; + this.args = args; + this.index = index; +}; + +tree.Call.prototype = { + is: 'call', + // When evuating a function call, + // we either find the function in `tree.functions` [1], + // in which case we call it, passing the evaluated arguments, + // or we simply print it out as it appeared originally [2]. + // The *functions.js* file contains the built-in functions. + // The reason why we evaluate the arguments, is in the case where + // we try to pass a variable to a function, like: `saturate(@color)`. + // The function should receive the value, not the variable. + 'ev': function(env) { + var args = this.args.map(function(a) { return a.ev(env); }); + + for (var i = 0; i < args.length; i++) { + if (args[i].is === 'undefined') { + return { + is: 'undefined', + value: 'undefined' + }; + } + } + + if (this.name in tree.functions) { + if (tree.functions[this.name].length <= args.length) { + var val = tree.functions[this.name].apply(tree.functions, args); + if (val === null) { + env.error({ + message: 'incorrect arguments given to ' + this.name + '()', + index: this.index, + type: 'runtime', + filename: this.filename + }); + return { is: 'undefined', value: 'undefined' }; + } + return val; + } else { + env.error({ + message: 'incorrect number of arguments for ' + this.name + + '(). ' + tree.functions[this.name].length + ' expected.', + index: this.index, + type: 'runtime', + filename: this.filename + }); + return { + is: 'undefined', + value: 'undefined' + }; + } + } else { + var fn = tree.Reference.mapnikFunctions[this.name]; + if (fn === undefined) { + var functions = _.pairs(tree.Reference.mapnikFunctions); + // cheap closest, needs improvement. + var name = this.name; + var mean = functions.map(function(f) { + return [f[0], tree.Reference.editDistance(name, f[0]), f[1]]; + }).sort(function(a, b) { + return a[1] - b[1]; + }); + env.error({ + message: 'unknown function ' + this.name + '(), did you mean ' + + mean[0][0] + '(' + mean[0][2] + ')', + index: this.index, + type: 'runtime', + filename: this.filename + }); + return { + is: 'undefined', + value: 'undefined' + }; + } + if (fn !== args.length && + !(Array.isArray(fn) && _.include(fn, args.length)) && + // support variable-arg functions like `colorize-alpha` + fn !== -1) { + env.error({ + message: 'function ' + this.name + '() takes ' + + fn + ' arguments and was given ' + args.length, + index: this.index, + type: 'runtime', + filename: this.filename + }); + return { + is: 'undefined', + value: 'undefined' + }; + } else { + // Save the evaluated versions of arguments + this.args = args; + return this; + } + } + }, + + toString: function(env, format) { + if (this.args.length) { + return this.name + '(' + this.args.join(',') + ')'; + } else { + return this.name; + } + } +}; + +})(require('../tree')); + +},{"../tree":7,"underscore":37}],9:[function(require,module,exports){ +(function(tree) { +// RGB Colors - #ff0014, #eee +// can be initialized with a 3 or 6 char string or a 3 or 4 element +// numerical array +tree.Color = function Color(rgb, a) { + // The end goal here, is to parse the arguments + // into an integer triplet, such as `128, 255, 0` + // + // This facilitates operations and conversions. + if (Array.isArray(rgb)) { + this.rgb = rgb.slice(0, 3); + } else if (rgb.length == 6) { + this.rgb = rgb.match(/.{2}/g).map(function(c) { + return parseInt(c, 16); + }); + } else { + this.rgb = rgb.split('').map(function(c) { + return parseInt(c + c, 16); + }); + } + + if (typeof(a) === 'number') { + this.alpha = a; + } else if (rgb.length === 4) { + this.alpha = rgb[3]; + } else { + this.alpha = 1; + } +}; + +tree.Color.prototype = { + is: 'color', + 'ev': function() { return this; }, + + // If we have some transparency, the only way to represent it + // is via `rgba`. Otherwise, we use the hex representation, + // which has better compatibility with older browsers. + // Values are capped between `0` and `255`, rounded and zero-padded. + toString: function() { + if (this.alpha < 1.0) { + return 'rgba(' + this.rgb.map(function(c) { + return Math.round(c); + }).concat(this.alpha).join(', ') + ')'; + } else { + return '#' + this.rgb.map(function(i) { + i = Math.round(i); + i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16); + return i.length === 1 ? '0' + i : i; + }).join(''); + } + }, + + // Operations have to be done per-channel, if not, + // channels will spill onto each other. Once we have + // our result, in the form of an integer triplet, + // we create a new Color node to hold the result. + operate: function(env, op, other) { + var result = []; + + if (! (other instanceof tree.Color)) { + other = other.toColor(); + } + + for (var c = 0; c < 3; c++) { + result[c] = tree.operate(op, this.rgb[c], other.rgb[c]); + } + return new tree.Color(result); + }, + + toHSL: function() { + var r = this.rgb[0] / 255, + g = this.rgb[1] / 255, + b = this.rgb[2] / 255, + a = this.alpha; + + var max = Math.max(r, g, b), min = Math.min(r, g, b); + var h, s, l = (max + min) / 2, d = max - min; + + if (max === min) { + h = s = 0; + } else { + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + + switch (max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + h /= 6; + } + return { h: h * 360, s: s, l: l, a: a }; + } +}; + +})(require('../tree')); + +},{"../tree":7}],10:[function(require,module,exports){ +(function(tree) { + +tree.Comment = function Comment(value, silent) { + this.value = value; + this.silent = !!silent; +}; + +tree.Comment.prototype = { + toString: function(env) { + return ''; + }, + 'ev': function() { return this; } +}; + +})(require('../tree')); + +},{"../tree":7}],11:[function(require,module,exports){ +(function(tree) { +var assert = require('assert'), + _ = require('underscore'); + +// A definition is the combination of a selector and rules, like +// #foo { +// polygon-opacity:1.0; +// } +// +// The selector can have filters +tree.Definition = function Definition(selector, rules) { + this.elements = selector.elements; + assert.ok(selector.filters instanceof tree.Filterset); + this.rules = rules; + this.ruleIndex = {}; + for (var i = 0; i < this.rules.length; i++) { + if ('zoom' in this.rules[i]) this.rules[i] = this.rules[i].clone(); + this.rules[i].zoom = selector.zoom; + this.ruleIndex[this.rules[i].updateID()] = true; + } + this.filters = selector.filters; + this.zoom = selector.zoom; + this.frame_offset = selector.frame_offset; + this.attachment = selector.attachment || '__default__'; + this.specificity = selector.specificity(); +}; + +tree.Definition.prototype.toString = function() { + var str = this.filters.toString(); + for (var i = 0; i < this.rules.length; i++) { + str += '\n ' + this.rules[i]; + } + return str; +}; + +tree.Definition.prototype.clone = function(filters) { + if (filters) assert.ok(filters instanceof tree.Filterset); + var clone = Object.create(tree.Definition.prototype); + clone.rules = this.rules.slice(); + clone.ruleIndex = _.clone(this.ruleIndex); + clone.filters = filters ? filters : this.filters.clone(); + clone.attachment = this.attachment; + return clone; +}; + +tree.Definition.prototype.addRules = function(rules) { + var added = 0; + + // Add only unique rules. + for (var i = 0; i < rules.length; i++) { + if (!this.ruleIndex[rules[i].id]) { + this.rules.push(rules[i]); + this.ruleIndex[rules[i].id] = true; + added++; + } + } + + return added; +}; + +// Determine whether this selector matches a given id +// and array of classes, by determining whether +// all elements it contains match. +tree.Definition.prototype.appliesTo = function(id, classes) { + for (var i = 0, l = this.elements.length; i < l; i++) { + var elem = this.elements[i]; + if (!(elem.wildcard || + (elem.type === 'class' && classes[elem.clean]) || + (elem.type === 'id' && id === elem.clean))) return false; + } + return true; +}; + +function symbolizerName(symbolizer) { + function capitalize(str) { return str[1].toUpperCase(); } + return symbolizer.charAt(0).toUpperCase() + + symbolizer.slice(1).replace(/\-./, capitalize) + 'Symbolizer'; +} + +// Get a simple list of the symbolizers, in order +function symbolizerList(sym_order) { + return sym_order.sort(function(a, b) { return a[1] - b[1]; }) + .map(function(v) { return v[0]; }); +} + +tree.Definition.prototype.symbolizersToXML = function(env, symbolizers, zoom) { + var xml = zoom.toXML(env).join('') + this.filters.toXML(env); + + // Sort symbolizers by the index of their first property definition + var sym_order = [], indexes = []; + for (var key in symbolizers) { + indexes = []; + for (var prop in symbolizers[key]) { + indexes.push(symbolizers[key][prop].index); + } + var min_idx = Math.min.apply(Math, indexes); + sym_order.push([key, min_idx]); + } + + sym_order = symbolizerList(sym_order); + var sym_count = 0; + + for (var i = 0; i < sym_order.length; i++) { + var attributes = symbolizers[sym_order[i]]; + var symbolizer = sym_order[i].split('/').pop(); + + // Skip the magical * symbolizer which is used for universal properties + // which are bubbled up to Style elements intead of Symbolizer elements. + if (symbolizer === '*') continue; + sym_count++; + + var fail = tree.Reference.requiredProperties(symbolizer, attributes); + if (fail) { + var rule = attributes[Object.keys(attributes).shift()]; + env.error({ + message: fail, + index: rule.index, + filename: rule.filename + }); + } + + var name = symbolizerName(symbolizer); + + var selfclosing = true, tagcontent; + xml += ' <' + name + ' '; + for (var j in attributes) { + if (symbolizer === 'map') env.error({ + message: 'Map properties are not permitted in other rules', + index: attributes[j].index, + filename: attributes[j].filename + }); + var x = tree.Reference.selector(attributes[j].name); + if (x && x.serialization && x.serialization === 'content') { + selfclosing = false; + tagcontent = attributes[j].ev(env).toXML(env, true); + } else if (x && x.serialization && x.serialization === 'tag') { + selfclosing = false; + tagcontent = attributes[j].ev(env).toXML(env, true); + } else { + xml += attributes[j].ev(env).toXML(env) + ' '; + } + } + if (selfclosing) { + xml += '/>\n'; + } else if (typeof tagcontent !== "undefined") { + if (tagcontent.indexOf('<') != -1) { + xml += '>' + tagcontent + '\n'; + } else { + xml += '>\n'; + } + } + } + if (!sym_count || !xml) return ''; + return ' \n' + xml + ' \n'; +}; + +// Take a zoom range of zooms and 'i', the index of a rule in this.rules, +// and finds all applicable symbolizers +tree.Definition.prototype.collectSymbolizers = function(zooms, i) { + var symbolizers = {}, child; + + for (var j = i; j < this.rules.length; j++) { + child = this.rules[j]; + var key = child.instance + '/' + child.symbolizer; + if (zooms.current & child.zoom && + (!(key in symbolizers) || + (!(child.name in symbolizers[key])))) { + zooms.current &= child.zoom; + if (!(key in symbolizers)) { + symbolizers[key] = {}; + } + symbolizers[key][child.name] = child; + } + } + + if (Object.keys(symbolizers).length) { + zooms.rule &= (zooms.available &= ~zooms.current); + return symbolizers; + } +}; + +// The tree.Zoom.toString function ignores the holes in zoom ranges and outputs +// scaledenominators that cover the whole range from the first to last bit set. +// This algorithm can produces zoom ranges that may have holes. However, +// when using the filter-mode="first", more specific zoom filters will always +// end up before broader ranges. The filter-mode will pick those first before +// resorting to the zoom range with the hole and stop processing further rules. +tree.Definition.prototype.toXML = function(env, existing) { + var filter = this.filters.toString(); + if (!(filter in existing)) existing[filter] = tree.Zoom.all; + + var available = tree.Zoom.all, xml = '', zoom, symbolizers, + zooms = { available: tree.Zoom.all }; + for (var i = 0; i < this.rules.length && available; i++) { + zooms.rule = this.rules[i].zoom; + if (!(existing[filter] & zooms.rule)) continue; + + while (zooms.current = zooms.rule & available) { + if (symbolizers = this.collectSymbolizers(zooms, i)) { + if (!(existing[filter] & zooms.current)) continue; + xml += this.symbolizersToXML(env, symbolizers, + (new tree.Zoom()).setZoom(existing[filter] & zooms.current)); + existing[filter] &= ~zooms.current; + } + } + } + + return xml; +}; + +tree.Definition.prototype.toJS = function(env) { + var shaderAttrs = {}; + + // merge conditions from filters with zoom condition of the + // definition + var zoom = "(" + this.zoom + " & (1 << ctx.zoom))"; + var frame_offset = this.frame_offset; + var _if = this.filters.toJS(env); + var filters = [zoom]; + if(_if) filters.push(_if); + if(frame_offset) filters.push('ctx["frame-offset"] === ' + frame_offset); + _if = filters.join(" && "); + _.each(this.rules, function(rule) { + if(rule instanceof tree.Rule) { + shaderAttrs[rule.name] = shaderAttrs[rule.name] || []; + + var r = { + index: rule.index, + symbolizer: rule.symbolizer + }; + + if (_if) { + r.js = "if(" + _if + "){" + rule.value.toJS(env) + "}" + } else { + r.js = rule.value.toJS(env); + } + + r.constant = rule.value.ev(env).is !== 'field'; + r.filtered = !!_if; + + shaderAttrs[rule.name].push(r); + } else { + throw new Error("Ruleset not supported"); + //if (rule instanceof tree.Ruleset) { + //var sh = rule.toJS(env); + //for(var v in sh) { + //shaderAttrs[v] = shaderAttrs[v] || []; + //for(var attr in sh[v]) { + //shaderAttrs[v].push(sh[v][attr]); + //} + //} + //} + } + }); + return shaderAttrs; +}; + + +})(require('../tree')); + +},{"../tree":7,"assert":40,"underscore":37}],12:[function(require,module,exports){ +(function(tree) { +var _ = require('underscore'); +// +// A number with a unit +// +tree.Dimension = function Dimension(value, unit, index) { + this.value = parseFloat(value); + this.unit = unit || null; + this.index = index; +}; + +tree.Dimension.prototype = { + is: 'float', + physical_units: ['m', 'cm', 'in', 'mm', 'pt', 'pc'], + screen_units: ['px', '%'], + all_units: ['m', 'cm', 'in', 'mm', 'pt', 'pc', 'px', '%'], + densities: { + m: 0.0254, + mm: 25.4, + cm: 2.54, + pt: 72, + pc: 6 + }, + ev: function (env) { + if (this.unit && !_.contains(this.all_units, this.unit)) { + env.error({ + message: "Invalid unit: '" + this.unit + "'", + index: this.index + }); + return { is: 'undefined', value: 'undefined' }; + } + + // normalize units which are not px or % + if (this.unit && _.contains(this.physical_units, this.unit)) { + if (!env.ppi) { + env.error({ + message: "ppi is not set, so metric units can't be used", + index: this.index + }); + return { is: 'undefined', value: 'undefined' }; + } + // convert all units to inch + // convert inch to px using ppi + this.value = (this.value / this.densities[this.unit]) * env.ppi; + this.unit = 'px'; + } + + return this; + }, + round: function() { + this.value = Math.round(this.value); + return this; + }, + toColor: function() { + return new tree.Color([this.value, this.value, this.value]); + }, + round: function() { + this.value = Math.round(this.value); + return this; + }, + toString: function() { + return this.value.toString(); + }, + operate: function(env, op, other) { + if (this.unit === '%' && other.unit !== '%') { + env.error({ + message: 'If two operands differ, the first must not be %', + index: this.index + }); + return { + is: 'undefined', + value: 'undefined' + }; + } + + if (this.unit !== '%' && other.unit === '%') { + if (op === '*' || op === '/' || op === '%') { + env.error({ + message: 'Percent values can only be added or subtracted from other values', + index: this.index + }); + return { + is: 'undefined', + value: 'undefined' + }; + } + + return new tree.Dimension(tree.operate(op, + this.value, this.value * other.value * 0.01), + this.unit); + } + + //here the operands are either the same (% or undefined or px), or one is undefined and the other is px + return new tree.Dimension(tree.operate(op, this.value, other.value), + this.unit || other.unit); + } +}; + +})(require('../tree')); + +},{"../tree":7,"underscore":37}],13:[function(require,module,exports){ +(function(tree) { + +// An element is an id or class selector +tree.Element = function Element(value) { + this.value = value.trim(); + if (this.value[0] === '#') { + this.type = 'id'; + this.clean = this.value.replace(/^#/, ''); + } + if (this.value[0] === '.') { + this.type = 'class'; + this.clean = this.value.replace(/^\./, ''); + } + if (this.value.indexOf('*') !== -1) { + this.type = 'wildcard'; + } +}; + +// Determine the 'specificity matrix' of this +// specific selector +tree.Element.prototype.specificity = function() { + return [ + (this.type === 'id') ? 1 : 0, // a + (this.type === 'class') ? 1 : 0 // b + ]; +}; + +tree.Element.prototype.toString = function() { return this.value; }; + +})(require('../tree')); + +},{"../tree":7}],14:[function(require,module,exports){ +(function(tree) { + +tree.Expression = function Expression(value) { + this.value = value; +}; + +tree.Expression.prototype = { + is: 'expression', + ev: function(env) { + if (this.value.length > 1) { + return new tree.Expression(this.value.map(function(e) { + return e.ev(env); + })); + } else { + return this.value[0].ev(env); + } + }, + + toString: function(env) { + return this.value.map(function(e) { + return e.toString(env); + }).join(' '); + } +}; + +})(require('../tree')); + +},{"../tree":7}],15:[function(require,module,exports){ +(function(tree) { + +tree.Field = function Field(content) { + this.value = content || ''; +}; + +tree.Field.prototype = { + is: 'field', + toString: function() { + return '[' + this.value + ']'; + }, + 'ev': function() { + return this; + } +}; + +})(require('../tree')); + +},{"../tree":7}],16:[function(require,module,exports){ +(function(tree) { + +tree.Filter = function Filter(key, op, val, index, filename) { + this.key = key; + this.op = op; + this.val = val; + this.index = index; + this.filename = filename; + + this.id = this.key + this.op + this.val; +}; + +// xmlsafe, numeric, suffix +var ops = { + '<': [' < ', 'numeric'], + '>': [' > ', 'numeric'], + '=': [' = ', 'both'], + '!=': [' != ', 'both'], + '<=': [' <= ', 'numeric'], + '>=': [' >= ', 'numeric'], + '=~': ['.match(', 'string', ')'] +}; + +tree.Filter.prototype.ev = function(env) { + this.key = this.key.ev(env); + this.val = this.val.ev(env); + return this; +}; + +tree.Filter.prototype.toXML = function(env) { + if (tree.Reference.data.filter) { + if (this.key.is === 'keyword' && -1 === tree.Reference.data.filter.value.indexOf(this.key.toString())) { + env.error({ + message: this.key.toString() + ' is not a valid keyword in a filter expression', + index: this.index, + filename: this.filename + }); + } + if (this.val.is === 'keyword' && -1 === tree.Reference.data.filter.value.indexOf(this.val.toString())) { + env.error({ + message: this.val.toString() + ' is not a valid keyword in a filter expression', + index: this.index, + filename: this.filename + }); + } + } + var key = this.key.toString(false); + var val = this.val.toString(this.val.is == 'string'); + + if ( + (ops[this.op][1] == 'numeric' && isNaN(val) && this.val.is !== 'field') || + (ops[this.op][1] == 'string' && (val)[0] != "'") + ) { + env.error({ + message: 'Cannot use operator "' + this.op + '" with value ' + this.val, + index: this.index, + filename: this.filename + }); + } + + return key + ops[this.op][0] + val + (ops[this.op][2] || ''); +}; + +tree.Filter.prototype.toString = function() { + return '[' + this.id + ']'; +}; + +})(require('../tree')); + +},{"../tree":7}],17:[function(require,module,exports){ +var tree = require('../tree'); +var _ = require('underscore'); + +tree.Filterset = function Filterset() { + this.filters = {}; +}; + +tree.Filterset.prototype.toXML = function(env) { + var filters = []; + for (var id in this.filters) { + filters.push('(' + this.filters[id].toXML(env).trim() + ')'); + } + if (filters.length) { + return ' ' + filters.join(' and ') + '\n'; + } else { + return ''; + } +}; + +tree.Filterset.prototype.toString = function() { + var arr = []; + for (var id in this.filters) arr.push(this.filters[id].id); + return arr.sort().join('\t'); +}; + +tree.Filterset.prototype.ev = function(env) { + for (var i in this.filters) { + this.filters[i].ev(env); + } + return this; +}; + +tree.Filterset.prototype.clone = function() { + var clone = new tree.Filterset(); + for (var id in this.filters) { + clone.filters[id] = this.filters[id]; + } + return clone; +}; + +// Note: other has to be a tree.Filterset. +tree.Filterset.prototype.cloneWith = function(other) { + var additions = []; + for (var id in other.filters) { + var status = this.addable(other.filters[id]); + // status is true, false or null. if it's null we don't fail this + // clone nor do we add the filter. + if (status === false) { + return false; + } + if (status === true) { + // Adding the filter will override another value. + additions.push(other.filters[id]); + } + } + + // Adding the other filters doesn't make this filterset invalid, but it + // doesn't add anything to it either. + if (!additions.length) { + return null; + } + + // We can successfully add all filters. Now clone the filterset and add the + // new rules. + var clone = new tree.Filterset(); + + // We can add the rules that are already present without going through the + // add function as a Filterset is always in it's simplest canonical form. + for (id in this.filters) { + clone.filters[id] = this.filters[id]; + } + + // Only add new filters that actually change the filter. + while (id = additions.shift()) { + clone.add(id); + } + + return clone; +}; + +tree.Filterset.prototype.toJS = function(env) { + var opMap = { + '=': '===' + }; + return _.map(this.filters, function(filter) { + var op = filter.op; + if(op in opMap) { + op = opMap[op]; + } + var val = filter.val; + if(filter._val !== undefined) { + val = filter._val.toString(true); + } + var attrs = "data"; + return attrs + "." + filter.key.value + " " + op + " " + (val.is === 'string' ? "'"+ val +"'" : val); + }).join(' && '); +}; + +// Returns true when the new filter can be added, false otherwise. +// It can also return null, and on the other side we test for === true or +// false +tree.Filterset.prototype.addable = function(filter) { + var key = filter.key.toString(), + value = filter.val.toString(); + + if (value.match(/^[0-9]+(\.[0-9]*)?$/)) value = parseFloat(value); + + switch (filter.op) { + case '=': + // if there is already foo= and we're adding foo= + if (this.filters[key + '='] !== undefined) { + if (this.filters[key + '='].val.toString() != value) { + return false; + } else { + return null; + } + } + if (this.filters[key + '!=' + value] !== undefined) return false; + if (this.filters[key + '>'] !== undefined && this.filters[key + '>'].val >= value) return false; + if (this.filters[key + '<'] !== undefined && this.filters[key + '<'].val <= value) return false; + if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val > value) return false; + if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val < value) return false; + return true; + + case '=~': + return true; + + case '!=': + if (this.filters[key + '='] !== undefined) return (this.filters[key + '='].val == value) ? false : null; + if (this.filters[key + '!=' + value] !== undefined) return null; + if (this.filters[key + '>'] !== undefined && this.filters[key + '>'].val >= value) return null; + if (this.filters[key + '<'] !== undefined && this.filters[key + '<'].val <= value) return null; + if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val > value) return null; + if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val < value) return null; + return true; + + case '>': + if (key + '=' in this.filters) { + if (this.filters[key + '='].val <= value) { + return false; + } else { + return null; + } + } + if (this.filters[key + '<'] !== undefined && this.filters[key + '<'].val <= value) return false; + if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val <= value) return false; + if (this.filters[key + '>'] !== undefined && this.filters[key + '>'].val >= value) return null; + if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val > value) return null; + return true; + + case '>=': + if (this.filters[key + '=' ] !== undefined) return (this.filters[key + '='].val < value) ? false : null; + if (this.filters[key + '<' ] !== undefined && this.filters[key + '<'].val <= value) return false; + if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val < value) return false; + if (this.filters[key + '>' ] !== undefined && this.filters[key + '>'].val >= value) return null; + if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val >= value) return null; + return true; + + case '<': + if (this.filters[key + '=' ] !== undefined) return (this.filters[key + '='].val >= value) ? false : null; + if (this.filters[key + '>' ] !== undefined && this.filters[key + '>'].val >= value) return false; + if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val >= value) return false; + if (this.filters[key + '<' ] !== undefined && this.filters[key + '<'].val <= value) return null; + if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val < value) return null; + return true; + + case '<=': + if (this.filters[key + '=' ] !== undefined) return (this.filters[key + '='].val > value) ? false : null; + if (this.filters[key + '>' ] !== undefined && this.filters[key + '>'].val >= value) return false; + if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val > value) return false; + if (this.filters[key + '<' ] !== undefined && this.filters[key + '<'].val <= value) return null; + if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val <= value) return null; + return true; + } +}; + +// Does the new filter constitute a conflict? +tree.Filterset.prototype.conflict = function(filter) { + var key = filter.key.toString(), + value = filter.val.toString(); + + if (!isNaN(parseFloat(value))) value = parseFloat(value); + + // if (a=b) && (a=c) + // if (a=b) && (a!=b) + // or (a!=b) && (a=b) + if ((filter.op === '=' && this.filters[key + '='] !== undefined && + value != this.filters[key + '='].val.toString()) || + (filter.op === '!=' && this.filters[key + '='] !== undefined && + value == this.filters[key + '='].val.toString()) || + (filter.op === '=' && this.filters[key + '!='] !== undefined && + value == this.filters[key + '!='].val.toString())) { + return filter.toString() + ' added to ' + this.toString() + ' produces an invalid filter'; + } + + return false; +}; + +// Only call this function for filters that have been cleared by .addable(). +tree.Filterset.prototype.add = function(filter, env) { + var key = filter.key.toString(), + id, + op = filter.op, + conflict = this.conflict(filter), + numval; + + if (conflict) return conflict; + + if (op === '=') { + for (var i in this.filters) { + if (this.filters[i].key == key) delete this.filters[i]; + } + this.filters[key + '='] = filter; + } else if (op === '!=') { + this.filters[key + '!=' + filter.val] = filter; + } else if (op === '=~') { + this.filters[key + '=~' + filter.val] = filter; + } else if (op === '>') { + // If there are other filters that are also > + // but are less than this one, they don't matter, so + // remove them. + for (var j in this.filters) { + if (this.filters[j].key == key && this.filters[j].val <= filter.val) { + delete this.filters[j]; + } + } + this.filters[key + '>'] = filter; + } else if (op === '>=') { + for (var k in this.filters) { + numval = (+this.filters[k].val.toString()); + if (this.filters[k].key == key && numval < filter.val) { + delete this.filters[k]; + } + } + if (this.filters[key + '!=' + filter.val] !== undefined) { + delete this.filters[key + '!=' + filter.val]; + filter.op = '>'; + this.filters[key + '>'] = filter; + } + else { + this.filters[key + '>='] = filter; + } + } else if (op === '<') { + for (var l in this.filters) { + numval = (+this.filters[l].val.toString()); + if (this.filters[l].key == key && numval >= filter.val) { + delete this.filters[l]; + } + } + this.filters[key + '<'] = filter; + } else if (op === '<=') { + for (var m in this.filters) { + numval = (+this.filters[m].val.toString()); + if (this.filters[m].key == key && numval > filter.val) { + delete this.filters[m]; + } + } + if (this.filters[key + '!=' + filter.val] !== undefined) { + delete this.filters[key + '!=' + filter.val]; + filter.op = '<'; + this.filters[key + '<'] = filter; + } + else { + this.filters[key + '<='] = filter; + } + } +}; + +},{"../tree":7,"underscore":37}],18:[function(require,module,exports){ +(function(tree) { + +tree._getFontSet = function(env, fonts) { + var fontKey = fonts.join(''); + if (env._fontMap && env._fontMap[fontKey]) { + return env._fontMap[fontKey]; + } + + var new_fontset = new tree.FontSet(env, fonts); + env.effects.push(new_fontset); + if (!env._fontMap) env._fontMap = {}; + env._fontMap[fontKey] = new_fontset; + return new_fontset; +}; + +tree.FontSet = function FontSet(env, fonts) { + this.fonts = fonts; + this.name = 'fontset-' + env.effects.length; +}; + +tree.FontSet.prototype.toXML = function(env) { + return '\n' + + this.fonts.map(function(f) { + return ' '; + }).join('\n') + + '\n'; +}; + +})(require('../tree')); + +},{"../tree":7}],19:[function(require,module,exports){ +var tree = require('../tree'); + +// Storage for Frame offset value +// and stores them as bit-sequences so that they can be combined, +// inverted, and compared quickly. +tree.FrameOffset = function(op, value, index) { + value = parseInt(value, 10); + if (value > tree.FrameOffset.max || value <= 0) { + throw { + message: 'Only frame-offset levels between 1 and ' + + tree.FrameOffset.max + ' supported.', + index: index + }; + } + + if (op !== '=') { + throw { + message: 'only = operator is supported for frame-offset', + index: index + }; + } + return value; +}; + +tree.FrameOffset.max = 32; +tree.FrameOffset.none = 0; + + +},{"../tree":7}],20:[function(require,module,exports){ +(function(tree) { + +tree.ImageFilter = function ImageFilter(filter, args) { + this.filter = filter; + this.args = args || null; +}; + +tree.ImageFilter.prototype = { + is: 'imagefilter', + ev: function() { return this; }, + + toString: function() { + if (this.args) { + return this.filter + '(' + this.args.join(',') + ')'; + } else { + return this.filter; + } + } +}; + + +})(require('../tree')); + +},{"../tree":7}],21:[function(require,module,exports){ +(function (tree) { +tree.Invalid = function Invalid(chunk, index, message) { + this.chunk = chunk; + this.index = index; + this.type = 'syntax'; + this.message = message || "Invalid code: " + this.chunk; +}; + +tree.Invalid.prototype.is = 'invalid'; + +tree.Invalid.prototype.ev = function(env) { + env.error({ + chunk: this.chunk, + index: this.index, + type: 'syntax', + message: this.message || "Invalid code: " + this.chunk + }); + return { + is: 'undefined' + }; +}; +})(require('../tree')); + +},{"../tree":7}],22:[function(require,module,exports){ +(function(tree) { + +tree.Keyword = function Keyword(value) { + this.value = value; + var special = { + 'transparent': 'color', + 'true': 'boolean', + 'false': 'boolean' + }; + this.is = special[value] ? special[value] : 'keyword'; +}; +tree.Keyword.prototype = { + ev: function() { return this; }, + toString: function() { return this.value; } +}; + +})(require('../tree')); + +},{"../tree":7}],23:[function(require,module,exports){ +(function(tree) { + +tree.LayerXML = function(obj, styles) { + var dsoptions = []; + for (var i in obj.Datasource) { + dsoptions.push(''); + } + + var prop_string = ''; + for (var prop in obj.properties) { + if (prop === 'minzoom') { + prop_string += ' maxzoom="' + tree.Zoom.ranges[obj.properties[prop]] + '"\n'; + } else if (prop === 'maxzoom') { + prop_string += ' minzoom="' + tree.Zoom.ranges[obj.properties[prop]+1] + '"\n'; + } else { + prop_string += ' ' + prop + '="' + obj.properties[prop] + '"\n'; + } + } + + return '\n ' + + styles.reverse().map(function(s) { + return '' + s + ''; + }).join('\n ') + + (dsoptions.length ? + '\n \n ' + + dsoptions.join('\n ') + + '\n \n' + : '') + + ' \n'; +}; + +})(require('../tree')); + +},{"../tree":7}],24:[function(require,module,exports){ +// A literal is a literal string for Mapnik - the +// result of the combination of a `tree.Field` with any +// other type. +(function(tree) { + +tree.Literal = function Field(content) { + this.value = content || ''; + this.is = 'field'; +}; + +tree.Literal.prototype = { + toString: function() { + return this.value; + }, + 'ev': function() { + return this; + } +}; + +})(require('../tree')); + +},{"../tree":7}],25:[function(require,module,exports){ +// An operation is an expression with an op in between two operands, +// like 2 + 1. +(function(tree) { + +tree.Operation = function Operation(op, operands, index) { + this.op = op.trim(); + this.operands = operands; + this.index = index; +}; + +tree.Operation.prototype.is = 'operation'; + +tree.Operation.prototype.ev = function(env) { + var a = this.operands[0].ev(env), + b = this.operands[1].ev(env), + temp; + + if (a.is === 'undefined' || b.is === 'undefined') { + return { + is: 'undefined', + value: 'undefined' + }; + } + + if (a instanceof tree.Dimension && b instanceof tree.Color) { + if (this.op === '*' || this.op === '+') { + temp = b, b = a, a = temp; + } else { + env.error({ + name: "OperationError", + message: "Can't substract or divide a color from a number", + index: this.index + }); + } + } + + // Only concatenate plain strings, because this is easily + // pre-processed + if (a instanceof tree.Quoted && b instanceof tree.Quoted && this.op !== '+') { + env.error({ + message: "Can't subtract, divide, or multiply strings.", + index: this.index, + type: 'runtime', + filename: this.filename + }); + return { + is: 'undefined', + value: 'undefined' + }; + } + + // Fields, literals, dimensions, and quoted strings can be combined. + if (a instanceof tree.Field || b instanceof tree.Field || + a instanceof tree.Literal || b instanceof tree.Literal) { + if (a.is === 'color' || b.is === 'color') { + env.error({ + message: "Can't subtract, divide, or multiply colors in expressions.", + index: this.index, + type: 'runtime', + filename: this.filename + }); + return { + is: 'undefined', + value: 'undefined' + }; + } else { + return new tree.Literal(a.ev(env).toString(true) + this.op + b.ev(env).toString(true)); + } + } + + if (a.operate === undefined) { + env.error({ + message: 'Cannot do math with type ' + a.is + '.', + index: this.index, + type: 'runtime', + filename: this.filename + }); + return { + is: 'undefined', + value: 'undefined' + }; + } + + return a.operate(env, this.op, b); +}; + +tree.operate = function(op, a, b) { + switch (op) { + case '+': return a + b; + case '-': return a - b; + case '*': return a * b; + case '%': return a % b; + case '/': return a / b; + } +}; + +})(require('../tree')); + +},{"../tree":7}],26:[function(require,module,exports){ +(function(tree) { + +tree.Quoted = function Quoted(content) { + this.value = content || ''; +}; + +tree.Quoted.prototype = { + is: 'string', + + toString: function(quotes) { + var escapedValue = this.value + .replace(/&/g, '&') + var xmlvalue = escapedValue + .replace(/\'/g, '\\\'') + .replace(/\"/g, '"') + .replace(//g, '>'); + return (quotes === true) ? "'" + xmlvalue + "'" : escapedValue; + }, + + 'ev': function() { + return this; + }, + + operate: function(env, op, other) { + return new tree.Quoted(tree.operate(op, this.toString(), other.toString(this.contains_field))); + } +}; + +})(require('../tree')); + +},{"../tree":7}],27:[function(require,module,exports){ +// Carto pulls in a reference from the `mapnik-reference` +// module. This file builds indexes from that file for its various +// options, and provides validation methods for property: value +// combinations. +(function(tree) { + +var _ = require('underscore'), + ref = {}; + +ref.setData = function(data) { + ref.data = data; + ref.selector_cache = generateSelectorCache(data); + ref.mapnikFunctions = generateMapnikFunctions(data); + + ref.mapnikFunctions.matrix = [6]; + ref.mapnikFunctions.translate = [1, 2]; + ref.mapnikFunctions.scale = [1, 2]; + ref.mapnikFunctions.rotate = [1, 3]; + ref.mapnikFunctions.skewX = [1]; + ref.mapnikFunctions.skewY = [1]; + + ref.required_cache = generateRequiredProperties(data); +}; + +ref.setVersion = function(version) { + var mapnik_reference = require('mapnik-reference'); + if (mapnik_reference.version.hasOwnProperty(version)) { + ref.setData(mapnik_reference.version[version]); + return true; + } else { + return false; + } +}; + +ref.selectorData = function(selector, i) { + if (ref.selector_cache[selector]) return ref.selector_cache[selector][i]; +}; + +ref.validSelector = function(selector) { return !!ref.selector_cache[selector]; }; +ref.selectorName = function(selector) { return ref.selectorData(selector, 2); }; +ref.selector = function(selector) { return ref.selectorData(selector, 0); }; +ref.symbolizer = function(selector) { return ref.selectorData(selector, 1); }; + +function generateSelectorCache(data) { + var index = {}; + for (var i in data.symbolizers) { + for (var j in data.symbolizers[i]) { + if (data.symbolizers[i][j].hasOwnProperty('css')) { + index[data.symbolizers[i][j].css] = [data.symbolizers[i][j], i, j]; + } + } + } + return index; +} + +function generateMapnikFunctions(data) { + var functions = {}; + for (var i in data.symbolizers) { + for (var j in data.symbolizers[i]) { + if (data.symbolizers[i][j].type === 'functions') { + for (var k = 0; k < data.symbolizers[i][j].functions.length; k++) { + var fn = data.symbolizers[i][j].functions[k]; + functions[fn[0]] = fn[1]; + } + } + } + } + return functions; +} + +function generateRequiredProperties(data) { + var cache = {}; + for (var symbolizer_name in data.symbolizers) { + cache[symbolizer_name] = []; + for (var j in data.symbolizers[symbolizer_name]) { + if (data.symbolizers[symbolizer_name][j].required) { + cache[symbolizer_name].push(data.symbolizers[symbolizer_name][j].css); + } + } + } + return cache; +} + +ref.requiredProperties = function(symbolizer_name, rules) { + var req = ref.required_cache[symbolizer_name]; + for (var i in req) { + if (!(req[i] in rules)) { + return 'Property ' + req[i] + ' required for defining ' + + symbolizer_name + ' styles.'; + } + } +}; + +// TODO: finish implementation - this is dead code +ref._validateValue = { + 'font': function(env, value) { + if (env.validation_data && env.validation_data.fonts) { + return env.validation_data.fonts.indexOf(value) != -1; + } else { + return true; + } + } +}; + +ref.isFont = function(selector) { + return ref.selector(selector).validate == 'font'; +}; + +// https://gist.github.com/982927 +ref.editDistance = function(a, b){ + if (a.length === 0) return b.length; + if (b.length === 0) return a.length; + var matrix = []; + for (var i = 0; i <= b.length; i++) { matrix[i] = [i]; } + for (var j = 0; j <= a.length; j++) { matrix[0][j] = j; } + for (i = 1; i <= b.length; i++) { + for (j = 1; j <= a.length; j++) { + if (b.charAt(i-1) == a.charAt(j-1)) { + matrix[i][j] = matrix[i-1][j-1]; + } else { + matrix[i][j] = Math.min(matrix[i-1][j-1] + 1, // substitution + Math.min(matrix[i][j-1] + 1, // insertion + matrix[i-1][j] + 1)); // deletion + } + } + } + return matrix[b.length][a.length]; +}; + +function validateFunctions(value, selector) { + if (value.value[0].is === 'string') return true; + for (var i in value.value) { + for (var j in value.value[i].value) { + if (value.value[i].value[j].is !== 'call') return false; + var f = _.find(ref + .selector(selector).functions, function(x) { + return x[0] == value.value[i].value[j].name; + }); + if (!(f && f[1] == -1)) { + // This filter is unknown or given an incorrect number of arguments + if (!f || f[1] !== value.value[i].value[j].args.length) return false; + } + } + } + return true; +} + +function validateKeyword(value, selector) { + if (typeof ref.selector(selector).type === 'object') { + return ref.selector(selector).type + .indexOf(value.value[0].value) !== -1; + } else { + // allow unquoted keywords as strings + return ref.selector(selector).type === 'string'; + } +} + +ref.validValue = function(env, selector, value) { + var i, j; + // TODO: handle in reusable way + if (!ref.selector(selector)) { + return false; + } else if (value.value[0].is == 'keyword') { + return validateKeyword(value, selector); + } else if (value.value[0].is == 'undefined') { + // caught earlier in the chain - ignore here so that + // error is not overridden + return true; + } else if (ref.selector(selector).type == 'numbers') { + for (i in value.value) { + if (value.value[i].is !== 'float') { + return false; + } + } + return true; + } else if (ref.selector(selector).type == 'tags') { + if (!value.value) return false; + if (!value.value[0].value) { + return value.value[0].is === 'tag'; + } + for (i = 0; i < value.value[0].value.length; i++) { + if (value.value[0].value[i].is !== 'tag') return false; + } + return true; + } else if (ref.selector(selector).type == 'functions') { + // For backwards compatibility, you can specify a string for `functions`-compatible + // values, though they will not be validated. + return validateFunctions(value, selector); + } else if (ref.selector(selector).type === 'unsigned') { + if (value.value[0].is === 'float') { + value.value[0].round(); + return true; + } else { + return false; + } + } else if ((ref.selector(selector).expression)) { + return true; + } else { + if (ref.selector(selector).validate) { + var valid = false; + for (i = 0; i < value.value.length; i++) { + if (ref.selector(selector).type == value.value[i].is && + ref + ._validateValue + [ref.selector(selector).validate] + (env, value.value[i].value)) { + return true; + } + } + return valid; + } else { + return ref.selector(selector).type == value.value[0].is; + } + } +}; + +tree.Reference = ref; + +})(require('../tree')); + +},{"../tree":7,"mapnik-reference":36,"underscore":37}],28:[function(require,module,exports){ +(function(tree) { +// a rule is a single property and value combination, or variable +// name and value combination, like +// polygon-opacity: 1.0; or @opacity: 1.0; +tree.Rule = function Rule(name, value, index, filename) { + var parts = name.split('/'); + this.name = parts.pop(); + this.instance = parts.length ? parts[0] : '__default__'; + this.value = (value instanceof tree.Value) ? + value : new tree.Value([value]); + this.index = index; + this.symbolizer = tree.Reference.symbolizer(this.name); + this.filename = filename; + this.variable = (name.charAt(0) === '@'); +}; + +tree.Rule.prototype.is = 'rule'; + +tree.Rule.prototype.clone = function() { + var clone = Object.create(tree.Rule.prototype); + clone.name = this.name; + clone.value = this.value; + clone.index = this.index; + clone.instance = this.instance; + clone.symbolizer = this.symbolizer; + clone.filename = this.filename; + clone.variable = this.variable; + return clone; +}; + +tree.Rule.prototype.updateID = function() { + return this.id = this.zoom + '#' + this.instance + '#' + this.name; +}; + +tree.Rule.prototype.toString = function() { + return '[' + tree.Zoom.toString(this.zoom) + '] ' + this.name + ': ' + this.value; +}; + +function getMean(name) { + return Object.keys(tree.Reference.selector_cache).map(function(f) { + return [f, tree.Reference.editDistance(name, f)]; + }).sort(function(a, b) { return a[1] - b[1]; }); +} + +// second argument, if true, outputs the value of this +// rule without the usual attribute="content" wrapping. Right +// now this is just for the TextSymbolizer, but applies to other +// properties in reference.json which specify serialization=content +tree.Rule.prototype.toXML = function(env, content, sep, format) { + if (!tree.Reference.validSelector(this.name)) { + var mean = getMean(this.name); + var mean_message = ''; + if (mean[0][1] < 3) { + mean_message = '. Did you mean ' + mean[0][0] + '?'; + } + return env.error({ + message: "Unrecognized rule: " + this.name + mean_message, + index: this.index, + type: 'syntax', + filename: this.filename + }); + } + + if ((this.value instanceof tree.Value) && + !tree.Reference.validValue(env, this.name, this.value)) { + if (!tree.Reference.selector(this.name)) { + return env.error({ + message: 'Unrecognized property: ' + + this.name, + index: this.index, + type: 'syntax', + filename: this.filename + }); + } else { + var typename; + if (tree.Reference.selector(this.name).validate) { + typename = tree.Reference.selector(this.name).validate; + } else if (typeof tree.Reference.selector(this.name).type === 'object') { + typename = 'keyword (options: ' + tree.Reference.selector(this.name).type.join(', ') + ')'; + } else { + typename = tree.Reference.selector(this.name).type; + } + return env.error({ + message: 'Invalid value for ' + + this.name + + ', the type ' + typename + + ' is expected. ' + this.value + + ' (of type ' + this.value.value[0].is + ') ' + + ' was given.', + index: this.index, + type: 'syntax', + filename: this.filename + }); + } + } + + if (this.variable) { + return ''; + } else if (tree.Reference.isFont(this.name) && this.value.value.length > 1) { + var f = tree._getFontSet(env, this.value.value); + return 'fontset-name="' + f.name + '"'; + } else if (content) { + return this.value.toString(env, this.name, sep); + } else { + return tree.Reference.selectorName(this.name) + + '="' + + this.value.toString(env, this.name) + + '"'; + } +}; + +// TODO: Rule ev chain should add fontsets to env.frames +tree.Rule.prototype.ev = function(context) { + return new tree.Rule(this.name, + this.value.ev(context), + this.index, + this.filename); +}; + +})(require('../tree')); + +},{"../tree":7}],29:[function(require,module,exports){ +(function(tree) { + +tree.Ruleset = function Ruleset(selectors, rules) { + this.selectors = selectors; + this.rules = rules; + // static cache of find() function + this._lookups = {}; +}; +tree.Ruleset.prototype = { + is: 'ruleset', + 'ev': function(env) { + var i, + ruleset = new tree.Ruleset(this.selectors, this.rules.slice(0)); + ruleset.root = this.root; + + // push the current ruleset to the frames stack + env.frames.unshift(ruleset); + + // Evaluate everything else + for (i = 0, rule; i < ruleset.rules.length; i++) { + rule = ruleset.rules[i]; + ruleset.rules[i] = rule.ev ? rule.ev(env) : rule; + } + + // Pop the stack + env.frames.shift(); + + return ruleset; + }, + match: function(args) { + return !args || args.length === 0; + }, + variables: function() { + if (this._variables) { return this._variables; } + else { + return this._variables = this.rules.reduce(function(hash, r) { + if (r instanceof tree.Rule && r.variable === true) { + hash[r.name] = r; + } + return hash; + }, {}); + } + }, + variable: function(name) { + return this.variables()[name]; + }, + rulesets: function() { + if (this._rulesets) { return this._rulesets; } + else { + return this._rulesets = this.rules.filter(function(r) { + return (r instanceof tree.Ruleset); + }); + } + }, + find: function(selector, self) { + self = self || this; + var rules = [], rule, match, + key = selector.toString(); + + if (key in this._lookups) { return this._lookups[key]; } + + this.rulesets().forEach(function(rule) { + if (rule !== self) { + for (var j = 0; j < rule.selectors.length; j++) { + match = selector.match(rule.selectors[j]); + if (match) { + if (selector.elements.length > 1) { + Array.prototype.push.apply(rules, rule.find( + new tree.Selector(null, null, null, selector.elements.slice(1)), self)); + } else { + rules.push(rule); + } + break; + } + } + } + }); + return this._lookups[key] = rules; + }, + // Zooms can use variables. This replaces tree.Zoom objects on selectors + // with simple bit-arrays that we can compare easily. + evZooms: function(env) { + for (var i = 0; i < this.selectors.length; i++) { + var zval = tree.Zoom.all; + for (var z = 0; z < this.selectors[i].zoom.length; z++) { + zval = zval & this.selectors[i].zoom[z].ev(env).zoom; + } + this.selectors[i].zoom = zval; + } + }, + flatten: function(result, parents, env) { + var selectors = [], i, j; + if (this.selectors.length === 0) { + env.frames = env.frames.concat(this.rules); + } + // evaluate zoom variables on this object. + this.evZooms(env); + for (i = 0; i < this.selectors.length; i++) { + var child = this.selectors[i]; + + if (!child.filters) { + // TODO: is this internal inconsistency? + // This is an invalid filterset. + continue; + } + + if (parents.length) { + for (j = 0; j < parents.length; j++) { + var parent = parents[j]; + + var mergedFilters = parent.filters.cloneWith(child.filters); + if (mergedFilters === null) { + // Filters could be added, but they didn't change the + // filters. This means that we only have to clone when + // the zoom levels or the attachment is different too. + if (parent.zoom === (parent.zoom & child.zoom) && + parent.frame_offset === child.frame_offset && + parent.attachment === child.attachment && + parent.elements.join() === child.elements.join()) { + selectors.push(parent); + continue; + } else { + mergedFilters = parent.filters; + } + } else if (!mergedFilters) { + // The merged filters are invalid, that means we don't + // have to clone. + continue; + } + + var clone = Object.create(tree.Selector.prototype); + clone.filters = mergedFilters; + clone.zoom = parent.zoom & child.zoom; + clone.frame_offset = child.frame_offset; + clone.elements = parent.elements.concat(child.elements); + if (parent.attachment && child.attachment) { + clone.attachment = parent.attachment + '/' + child.attachment; + } + else clone.attachment = child.attachment || parent.attachment; + clone.conditions = parent.conditions + child.conditions; + clone.index = child.index; + selectors.push(clone); + } + } else { + selectors.push(child); + } + } + + var rules = []; + for (i = 0; i < this.rules.length; i++) { + var rule = this.rules[i]; + + // Recursively flatten any nested rulesets + if (rule instanceof tree.Ruleset) { + rule.flatten(result, selectors, env); + } else if (rule instanceof tree.Rule) { + rules.push(rule); + } else if (rule instanceof tree.Invalid) { + env.error(rule); + } + } + + var index = rules.length ? rules[0].index : false; + for (i = 0; i < selectors.length; i++) { + // For specificity sort, use the position of the first rule to allow + // defining attachments that are under current element as a descendant + // selector. + if (index !== false) { + selectors[i].index = index; + } + result.push(new tree.Definition(selectors[i], rules.slice())); + } + + return result; + } +}; +})(require('../tree')); + +},{"../tree":7}],30:[function(require,module,exports){ +(function(tree) { + +tree.Selector = function Selector(filters, zoom, frame_offset, elements, attachment, conditions, index) { + this.elements = elements || []; + this.attachment = attachment; + this.filters = filters || {}; + this.frame_offset = frame_offset; + this.zoom = typeof zoom !== 'undefined' ? zoom : tree.Zoom.all; + this.conditions = conditions; + this.index = index; +}; + +// Determine the specificity of this selector +// based on the specificity of its elements - calling +// Element.specificity() in order to do so +// +// [ID, Class, Filters, Position in document] +tree.Selector.prototype.specificity = function() { + return this.elements.reduce(function(memo, e) { + var spec = e.specificity(); + memo[0] += spec[0]; + memo[1] += spec[1]; + return memo; + }, [0, 0, this.conditions, this.index]); +}; + +})(require('../tree')); + +},{"../tree":7}],31:[function(require,module,exports){ +(function(tree) { +var _ = require('underscore'); + +// Given a style's name, attachment, definitions, and an environment object, +// return a stringified style for Mapnik +tree.StyleXML = function(name, attachment, definitions, env) { + var existing = {}; + var image_filters = [], image_filters_inflate = [], direct_image_filters = [], comp_op = [], opacity = []; + + for (var i = 0; i < definitions.length; i++) { + for (var j = 0; j < definitions[i].rules.length; j++) { + if (definitions[i].rules[j].name === 'image-filters') { + image_filters.push(definitions[i].rules[j]); + } + if (definitions[i].rules[j].name === 'image-filters-inflate') { + image_filters_inflate.push(definitions[i].rules[j]); + } + if (definitions[i].rules[j].name === 'direct-image-filters') { + direct_image_filters.push(definitions[i].rules[j]); + } + if (definitions[i].rules[j].name === 'comp-op') { + comp_op.push(definitions[i].rules[j]); + } + if (definitions[i].rules[j].name === 'opacity') { + opacity.push(definitions[i].rules[j]); + } + } + } + + var rules = definitions.map(function(definition) { + return definition.toXML(env, existing); + }); + + var attrs_xml = ''; + + if (image_filters.length) { + attrs_xml += ' image-filters="' + _.chain(image_filters) + // prevent identical filters from being duplicated in the style + .uniq(function(i) { return i.id; }).map(function(f) { + return f.ev(env).toXML(env, true, ',', 'image-filter'); + }).value().join(',') + '"'; + } + + if (image_filters_inflate.length) { + attrs_xml += ' image-filters-inflate="' + image_filters_inflate[0].value.ev(env).toString() + '"'; + } + + if (direct_image_filters.length) { + attrs_xml += ' direct-image-filters="' + _.chain(direct_image_filters) + // prevent identical filters from being duplicated in the style + .uniq(function(i) { return i.id; }).map(function(f) { + return f.ev(env).toXML(env, true, ',', 'direct-image-filter'); + }).value().join(',') + '"'; + } + + if (comp_op.length && comp_op[0].value.ev(env).value != 'src-over') { + attrs_xml += ' comp-op="' + comp_op[0].value.ev(env).toString() + '"'; + } + + if (opacity.length && opacity[0].value.ev(env).value != 1) { + attrs_xml += ' opacity="' + opacity[0].value.ev(env).toString() + '"'; + } + var rule_string = rules.join(''); + if (!attrs_xml && !rule_string) return ''; + return ''; +}; + +})(require('../tree')); + +},{"../tree":7,"underscore":37}],32:[function(require,module,exports){ +(function(tree) { + +tree.URL = function URL(val, paths) { + this.value = val; + this.paths = paths; +}; + +tree.URL.prototype = { + is: 'uri', + toString: function() { + return this.value.toString(); + }, + ev: function(ctx) { + return new tree.URL(this.value.ev(ctx), this.paths); + } +}; + +})(require('../tree')); + +},{"../tree":7}],33:[function(require,module,exports){ +(function(tree) { + +tree.Value = function Value(value) { + this.value = value; +}; + +tree.Value.prototype = { + is: 'value', + ev: function(env) { + if (this.value.length === 1) { + return this.value[0].ev(env); + } else { + return new tree.Value(this.value.map(function(v) { + return v.ev(env); + })); + } + }, + toString: function(env, selector, sep, format) { + return this.value.map(function(e) { + return e.toString(env, format); + }).join(sep || ', '); + }, + clone: function() { + var obj = Object.create(tree.Value.prototype); + if (Array.isArray(obj)) obj.value = this.value.slice(); + else obj.value = this.value; + obj.is = this.is; + return obj; + }, + + toJS: function(env) { + //var v = this.value[0].value[0]; + var val = this.ev(env); + var v = val.toString(); + if(val.is === "color" || val.is === 'uri' || val.is === 'string' || val.is === 'keyword') { + v = "'" + v + "'"; + } else if (val.is === 'field') { + // replace [variable] by ctx['variable'] + v = v.replace(/\[(.*)\]/g, "data['$1']"); + } + return "_value = " + v + ";"; + } + +}; + +})(require('../tree')); + +},{"../tree":7}],34:[function(require,module,exports){ +(function(tree) { + +tree.Variable = function Variable(name, index, filename) { + this.name = name; + this.index = index; + this.filename = filename; +}; + +tree.Variable.prototype = { + is: 'variable', + toString: function() { + return this.name; + }, + ev: function(env) { + var variable, + v, + name = this.name; + + if (this._css) return this._css; + + var thisframe = env.frames.filter(function(f) { + return f.name == this.name; + }.bind(this)); + if (thisframe.length) { + return thisframe[0].value.ev(env); + } else { + env.error({ + message: 'variable ' + this.name + ' is undefined', + index: this.index, + type: 'runtime', + filename: this.filename + }); + return { + is: 'undefined', + value: 'undefined' + }; + } + } +}; + +})(require('../tree')); + +},{"../tree":7}],35:[function(require,module,exports){ +var tree = require('../tree'); + +// Storage for zoom ranges. Only supports continuous ranges, +// and stores them as bit-sequences so that they can be combined, +// inverted, and compared quickly. +tree.Zoom = function(op, value, index) { + this.op = op; + this.value = value; + this.index = index; +}; + +tree.Zoom.prototype.setZoom = function(zoom) { + this.zoom = zoom; + return this; +}; + +tree.Zoom.prototype.ev = function(env) { + var start = 0, + end = Infinity, + value = parseInt(this.value.ev(env).toString(), 10), + zoom = 0; + + if (value > tree.Zoom.maxZoom || value < 0) { + env.error({ + message: 'Only zoom levels between 0 and ' + + tree.Zoom.maxZoom + ' supported.', + index: this.index + }); + } + + switch (this.op) { + case '=': + this.zoom = 1 << value; + return this; + case '>': + start = value + 1; + break; + case '>=': + start = value; + break; + case '<': + end = value - 1; + break; + case '<=': + end = value; + break; + } + for (var i = 0; i <= tree.Zoom.maxZoom; i++) { + if (i >= start && i <= end) { + zoom |= (1 << i); + } + } + this.zoom = zoom; + return this; +}; + +tree.Zoom.prototype.toString = function() { + return this.zoom; +}; + +// Covers all zoomlevels from 0 to 22 +tree.Zoom.all = 0x7FFFFF; + +tree.Zoom.maxZoom = 22; + +tree.Zoom.ranges = { + 0: 1000000000, + 1: 500000000, + 2: 200000000, + 3: 100000000, + 4: 50000000, + 5: 25000000, + 6: 12500000, + 7: 6500000, + 8: 3000000, + 9: 1500000, + 10: 750000, + 11: 400000, + 12: 200000, + 13: 100000, + 14: 50000, + 15: 25000, + 16: 12500, + 17: 5000, + 18: 2500, + 19: 1500, + 20: 750, + 21: 500, + 22: 250, + 23: 100 +}; + +// Only works for single range zooms. `[XXX....XXXXX.........]` is invalid. +tree.Zoom.prototype.toXML = function() { + var conditions = []; + if (this.zoom != tree.Zoom.all) { + var start = null, end = null; + for (var i = 0; i <= tree.Zoom.maxZoom; i++) { + if (this.zoom & (1 << i)) { + if (start === null) start = i; + end = i; + } + } + if (start > 0) conditions.push(' ' + + tree.Zoom.ranges[start] + '\n'); + if (end < 22) conditions.push(' ' + + tree.Zoom.ranges[end + 1] + '\n'); + } + return conditions; +}; + +tree.Zoom.prototype.toString = function() { + var str = ''; + for (var i = 0; i <= tree.Zoom.maxZoom; i++) { + str += (this.zoom & (1 << i)) ? 'X' : '.'; + } + return str; +}; + +},{"../tree":7}],36:[function(require,module,exports){ +(function (__dirname){ +var fs = require('fs'), + path = require('path'), + existsSync = require('fs').existsSync || require('path').existsSync; + +// Load all stated versions into the module exports +module.exports.version = {}; + +var refs = [ + '2.0.0', + '2.0.1', + '2.0.2', + '2.1.0', + '2.1.1', + '2.2.0', + '2.3.0', + '3.0.0' +]; + +refs.map(function(version) { + module.exports.version[version] = require(path.join(__dirname, version, 'reference.json')); + var ds_path = path.join(__dirname, version, 'datasources.json'); + if (existsSync(ds_path)) { + module.exports.version[version].datasources = require(ds_path).datasources; + } +}); + +}).call(this,"/node_modules/mapnik-reference") +},{"fs":39,"path":42}],37:[function(require,module,exports){ +// Underscore.js 1.6.0 +// http://underscorejs.org +// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// Underscore may be freely distributed under the MIT license. + +(function() { + + // Baseline setup + // -------------- + + // Establish the root object, `window` in the browser, or `exports` on the server. + var root = this; + + // Save the previous value of the `_` variable. + var previousUnderscore = root._; + + // Establish the object that gets returned to break out of a loop iteration. + var breaker = {}; + + // Save bytes in the minified (but not gzipped) version: + var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; + + // Create quick reference variables for speed access to core prototypes. + var + push = ArrayProto.push, + slice = ArrayProto.slice, + concat = ArrayProto.concat, + toString = ObjProto.toString, + hasOwnProperty = ObjProto.hasOwnProperty; + + // All **ECMAScript 5** native function implementations that we hope to use + // are declared here. + var + nativeForEach = ArrayProto.forEach, + nativeMap = ArrayProto.map, + nativeReduce = ArrayProto.reduce, + nativeReduceRight = ArrayProto.reduceRight, + nativeFilter = ArrayProto.filter, + nativeEvery = ArrayProto.every, + nativeSome = ArrayProto.some, + nativeIndexOf = ArrayProto.indexOf, + nativeLastIndexOf = ArrayProto.lastIndexOf, + nativeIsArray = Array.isArray, + nativeKeys = Object.keys, + nativeBind = FuncProto.bind; + + // Create a safe reference to the Underscore object for use below. + var _ = function(obj) { + if (obj instanceof _) return obj; + if (!(this instanceof _)) return new _(obj); + this._wrapped = obj; + }; + + // Export the Underscore object for **Node.js**, with + // backwards-compatibility for the old `require()` API. If we're in + // the browser, add `_` as a global object via a string identifier, + // for Closure Compiler "advanced" mode. + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = _; + } + exports._ = _; + } else { + root._ = _; + } + + // Current version. + _.VERSION = '1.6.0'; + + // Collection Functions + // -------------------- + + // The cornerstone, an `each` implementation, aka `forEach`. + // Handles objects with the built-in `forEach`, arrays, and raw objects. + // Delegates to **ECMAScript 5**'s native `forEach` if available. + var each = _.each = _.forEach = function(obj, iterator, context) { + if (obj == null) return obj; + if (nativeForEach && obj.forEach === nativeForEach) { + obj.forEach(iterator, context); + } else if (obj.length === +obj.length) { + for (var i = 0, length = obj.length; i < length; i++) { + if (iterator.call(context, obj[i], i, obj) === breaker) return; + } + } else { + var keys = _.keys(obj); + for (var i = 0, length = keys.length; i < length; i++) { + if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return; + } + } + return obj; + }; + + // Return the results of applying the iterator to each element. + // Delegates to **ECMAScript 5**'s native `map` if available. + _.map = _.collect = function(obj, iterator, context) { + var results = []; + if (obj == null) return results; + if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); + each(obj, function(value, index, list) { + results.push(iterator.call(context, value, index, list)); + }); + return results; + }; + + var reduceError = 'Reduce of empty array with no initial value'; + + // **Reduce** builds up a single result from a list of values, aka `inject`, + // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. + _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { + var initial = arguments.length > 2; + if (obj == null) obj = []; + if (nativeReduce && obj.reduce === nativeReduce) { + if (context) iterator = _.bind(iterator, context); + return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); + } + each(obj, function(value, index, list) { + if (!initial) { + memo = value; + initial = true; + } else { + memo = iterator.call(context, memo, value, index, list); + } + }); + if (!initial) throw new TypeError(reduceError); + return memo; + }; + + // The right-associative version of reduce, also known as `foldr`. + // Delegates to **ECMAScript 5**'s native `reduceRight` if available. + _.reduceRight = _.foldr = function(obj, iterator, memo, context) { + var initial = arguments.length > 2; + if (obj == null) obj = []; + if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { + if (context) iterator = _.bind(iterator, context); + return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); + } + var length = obj.length; + if (length !== +length) { + var keys = _.keys(obj); + length = keys.length; + } + each(obj, function(value, index, list) { + index = keys ? keys[--length] : --length; + if (!initial) { + memo = obj[index]; + initial = true; + } else { + memo = iterator.call(context, memo, obj[index], index, list); + } + }); + if (!initial) throw new TypeError(reduceError); + return memo; + }; + + // Return the first value which passes a truth test. Aliased as `detect`. + _.find = _.detect = function(obj, predicate, context) { + var result; + any(obj, function(value, index, list) { + if (predicate.call(context, value, index, list)) { + result = value; + return true; + } + }); + return result; + }; + + // Return all the elements that pass a truth test. + // Delegates to **ECMAScript 5**'s native `filter` if available. + // Aliased as `select`. + _.filter = _.select = function(obj, predicate, context) { + var results = []; + if (obj == null) return results; + if (nativeFilter && obj.filter === nativeFilter) return obj.filter(predicate, context); + each(obj, function(value, index, list) { + if (predicate.call(context, value, index, list)) results.push(value); + }); + return results; + }; + + // Return all the elements for which a truth test fails. + _.reject = function(obj, predicate, context) { + return _.filter(obj, function(value, index, list) { + return !predicate.call(context, value, index, list); + }, context); + }; + + // Determine whether all of the elements match a truth test. + // Delegates to **ECMAScript 5**'s native `every` if available. + // Aliased as `all`. + _.every = _.all = function(obj, predicate, context) { + predicate || (predicate = _.identity); + var result = true; + if (obj == null) return result; + if (nativeEvery && obj.every === nativeEvery) return obj.every(predicate, context); + each(obj, function(value, index, list) { + if (!(result = result && predicate.call(context, value, index, list))) return breaker; + }); + return !!result; + }; + + // Determine if at least one element in the object matches a truth test. + // Delegates to **ECMAScript 5**'s native `some` if available. + // Aliased as `any`. + var any = _.some = _.any = function(obj, predicate, context) { + predicate || (predicate = _.identity); + var result = false; + if (obj == null) return result; + if (nativeSome && obj.some === nativeSome) return obj.some(predicate, context); + each(obj, function(value, index, list) { + if (result || (result = predicate.call(context, value, index, list))) return breaker; + }); + return !!result; + }; + + // Determine if the array or object contains a given value (using `===`). + // Aliased as `include`. + _.contains = _.include = function(obj, target) { + if (obj == null) return false; + if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; + return any(obj, function(value) { + return value === target; + }); + }; + + // Invoke a method (with arguments) on every item in a collection. + _.invoke = function(obj, method) { + var args = slice.call(arguments, 2); + var isFunc = _.isFunction(method); + return _.map(obj, function(value) { + return (isFunc ? method : value[method]).apply(value, args); + }); + }; + + // Convenience version of a common use case of `map`: fetching a property. + _.pluck = function(obj, key) { + return _.map(obj, _.property(key)); + }; + + // Convenience version of a common use case of `filter`: selecting only objects + // containing specific `key:value` pairs. + _.where = function(obj, attrs) { + return _.filter(obj, _.matches(attrs)); + }; + + // Convenience version of a common use case of `find`: getting the first object + // containing specific `key:value` pairs. + _.findWhere = function(obj, attrs) { + return _.find(obj, _.matches(attrs)); + }; + + // Return the maximum element or (element-based computation). + // Can't optimize arrays of integers longer than 65,535 elements. + // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797) + _.max = function(obj, iterator, context) { + if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { + return Math.max.apply(Math, obj); + } + var result = -Infinity, lastComputed = -Infinity; + each(obj, function(value, index, list) { + var computed = iterator ? iterator.call(context, value, index, list) : value; + if (computed > lastComputed) { + result = value; + lastComputed = computed; + } + }); + return result; + }; + + // Return the minimum element (or element-based computation). + _.min = function(obj, iterator, context) { + if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { + return Math.min.apply(Math, obj); + } + var result = Infinity, lastComputed = Infinity; + each(obj, function(value, index, list) { + var computed = iterator ? iterator.call(context, value, index, list) : value; + if (computed < lastComputed) { + result = value; + lastComputed = computed; + } + }); + return result; + }; + + // Shuffle an array, using the modern version of the + // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). + _.shuffle = function(obj) { + var rand; + var index = 0; + var shuffled = []; + each(obj, function(value) { + rand = _.random(index++); + shuffled[index - 1] = shuffled[rand]; + shuffled[rand] = value; + }); + return shuffled; + }; + + // Sample **n** random values from a collection. + // If **n** is not specified, returns a single random element. + // The internal `guard` argument allows it to work with `map`. + _.sample = function(obj, n, guard) { + if (n == null || guard) { + if (obj.length !== +obj.length) obj = _.values(obj); + return obj[_.random(obj.length - 1)]; + } + return _.shuffle(obj).slice(0, Math.max(0, n)); + }; + + // An internal function to generate lookup iterators. + var lookupIterator = function(value) { + if (value == null) return _.identity; + if (_.isFunction(value)) return value; + return _.property(value); + }; + + // Sort the object's values by a criterion produced by an iterator. + _.sortBy = function(obj, iterator, context) { + iterator = lookupIterator(iterator); + return _.pluck(_.map(obj, function(value, index, list) { + return { + value: value, + index: index, + criteria: iterator.call(context, value, index, list) + }; + }).sort(function(left, right) { + var a = left.criteria; + var b = right.criteria; + if (a !== b) { + if (a > b || a === void 0) return 1; + if (a < b || b === void 0) return -1; + } + return left.index - right.index; + }), 'value'); + }; + + // An internal function used for aggregate "group by" operations. + var group = function(behavior) { + return function(obj, iterator, context) { + var result = {}; + iterator = lookupIterator(iterator); + each(obj, function(value, index) { + var key = iterator.call(context, value, index, obj); + behavior(result, key, value); + }); + return result; + }; + }; + + // Groups the object's values by a criterion. Pass either a string attribute + // to group by, or a function that returns the criterion. + _.groupBy = group(function(result, key, value) { + _.has(result, key) ? result[key].push(value) : result[key] = [value]; + }); + + // Indexes the object's values by a criterion, similar to `groupBy`, but for + // when you know that your index values will be unique. + _.indexBy = group(function(result, key, value) { + result[key] = value; + }); + + // Counts instances of an object that group by a certain criterion. Pass + // either a string attribute to count by, or a function that returns the + // criterion. + _.countBy = group(function(result, key) { + _.has(result, key) ? result[key]++ : result[key] = 1; + }); + + // Use a comparator function to figure out the smallest index at which + // an object should be inserted so as to maintain order. Uses binary search. + _.sortedIndex = function(array, obj, iterator, context) { + iterator = lookupIterator(iterator); + var value = iterator.call(context, obj); + var low = 0, high = array.length; + while (low < high) { + var mid = (low + high) >>> 1; + iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; + } + return low; + }; + + // Safely create a real, live array from anything iterable. + _.toArray = function(obj) { + if (!obj) return []; + if (_.isArray(obj)) return slice.call(obj); + if (obj.length === +obj.length) return _.map(obj, _.identity); + return _.values(obj); + }; + + // Return the number of elements in an object. + _.size = function(obj) { + if (obj == null) return 0; + return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; + }; + + // Array Functions + // --------------- + + // Get the first element of an array. Passing **n** will return the first N + // values in the array. Aliased as `head` and `take`. The **guard** check + // allows it to work with `_.map`. + _.first = _.head = _.take = function(array, n, guard) { + if (array == null) return void 0; + if ((n == null) || guard) return array[0]; + if (n < 0) return []; + return slice.call(array, 0, n); + }; + + // Returns everything but the last entry of the array. Especially useful on + // the arguments object. Passing **n** will return all the values in + // the array, excluding the last N. The **guard** check allows it to work with + // `_.map`. + _.initial = function(array, n, guard) { + return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); + }; + + // Get the last element of an array. Passing **n** will return the last N + // values in the array. The **guard** check allows it to work with `_.map`. + _.last = function(array, n, guard) { + if (array == null) return void 0; + if ((n == null) || guard) return array[array.length - 1]; + return slice.call(array, Math.max(array.length - n, 0)); + }; + + // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. + // Especially useful on the arguments object. Passing an **n** will return + // the rest N values in the array. The **guard** + // check allows it to work with `_.map`. + _.rest = _.tail = _.drop = function(array, n, guard) { + return slice.call(array, (n == null) || guard ? 1 : n); + }; + + // Trim out all falsy values from an array. + _.compact = function(array) { + return _.filter(array, _.identity); + }; + + // Internal implementation of a recursive `flatten` function. + var flatten = function(input, shallow, output) { + if (shallow && _.every(input, _.isArray)) { + return concat.apply(output, input); + } + each(input, function(value) { + if (_.isArray(value) || _.isArguments(value)) { + shallow ? push.apply(output, value) : flatten(value, shallow, output); + } else { + output.push(value); + } + }); + return output; + }; + + // Flatten out an array, either recursively (by default), or just one level. + _.flatten = function(array, shallow) { + return flatten(array, shallow, []); + }; + + // Return a version of the array that does not contain the specified value(s). + _.without = function(array) { + return _.difference(array, slice.call(arguments, 1)); + }; + + // Split an array into two arrays: one whose elements all satisfy the given + // predicate, and one whose elements all do not satisfy the predicate. + _.partition = function(array, predicate) { + var pass = [], fail = []; + each(array, function(elem) { + (predicate(elem) ? pass : fail).push(elem); + }); + return [pass, fail]; + }; + + // Produce a duplicate-free version of the array. If the array has already + // been sorted, you have the option of using a faster algorithm. + // Aliased as `unique`. + _.uniq = _.unique = function(array, isSorted, iterator, context) { + if (_.isFunction(isSorted)) { + context = iterator; + iterator = isSorted; + isSorted = false; + } + var initial = iterator ? _.map(array, iterator, context) : array; + var results = []; + var seen = []; + each(initial, function(value, index) { + if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { + seen.push(value); + results.push(array[index]); + } + }); + return results; + }; + + // Produce an array that contains the union: each distinct element from all of + // the passed-in arrays. + _.union = function() { + return _.uniq(_.flatten(arguments, true)); + }; + + // Produce an array that contains every item shared between all the + // passed-in arrays. + _.intersection = function(array) { + var rest = slice.call(arguments, 1); + return _.filter(_.uniq(array), function(item) { + return _.every(rest, function(other) { + return _.contains(other, item); + }); + }); + }; + + // Take the difference between one array and a number of other arrays. + // Only the elements present in just the first array will remain. + _.difference = function(array) { + var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); + return _.filter(array, function(value){ return !_.contains(rest, value); }); + }; + + // Zip together multiple lists into a single array -- elements that share + // an index go together. + _.zip = function() { + var length = _.max(_.pluck(arguments, 'length').concat(0)); + var results = new Array(length); + for (var i = 0; i < length; i++) { + results[i] = _.pluck(arguments, '' + i); + } + return results; + }; + + // Converts lists into objects. Pass either a single array of `[key, value]` + // pairs, or two parallel arrays of the same length -- one of keys, and one of + // the corresponding values. + _.object = function(list, values) { + if (list == null) return {}; + var result = {}; + for (var i = 0, length = list.length; i < length; i++) { + if (values) { + result[list[i]] = values[i]; + } else { + result[list[i][0]] = list[i][1]; + } + } + return result; + }; + + // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), + // we need this function. Return the position of the first occurrence of an + // item in an array, or -1 if the item is not included in the array. + // Delegates to **ECMAScript 5**'s native `indexOf` if available. + // If the array is large and already in sort order, pass `true` + // for **isSorted** to use binary search. + _.indexOf = function(array, item, isSorted) { + if (array == null) return -1; + var i = 0, length = array.length; + if (isSorted) { + if (typeof isSorted == 'number') { + i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted); + } else { + i = _.sortedIndex(array, item); + return array[i] === item ? i : -1; + } + } + if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); + for (; i < length; i++) if (array[i] === item) return i; + return -1; + }; + + // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. + _.lastIndexOf = function(array, item, from) { + if (array == null) return -1; + var hasIndex = from != null; + if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { + return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); + } + var i = (hasIndex ? from : array.length); + while (i--) if (array[i] === item) return i; + return -1; + }; + + // Generate an integer Array containing an arithmetic progression. A port of + // the native Python `range()` function. See + // [the Python documentation](http://docs.python.org/library/functions.html#range). + _.range = function(start, stop, step) { + if (arguments.length <= 1) { + stop = start || 0; + start = 0; + } + step = arguments[2] || 1; + + var length = Math.max(Math.ceil((stop - start) / step), 0); + var idx = 0; + var range = new Array(length); + + while(idx < length) { + range[idx++] = start; + start += step; + } + + return range; + }; + + // Function (ahem) Functions + // ------------------ + + // Reusable constructor function for prototype setting. + var ctor = function(){}; + + // Create a function bound to a given object (assigning `this`, and arguments, + // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if + // available. + _.bind = function(func, context) { + var args, bound; + if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); + if (!_.isFunction(func)) throw new TypeError; + args = slice.call(arguments, 2); + return bound = function() { + if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); + ctor.prototype = func.prototype; + var self = new ctor; + ctor.prototype = null; + var result = func.apply(self, args.concat(slice.call(arguments))); + if (Object(result) === result) return result; + return self; + }; + }; + + // Partially apply a function by creating a version that has had some of its + // arguments pre-filled, without changing its dynamic `this` context. _ acts + // as a placeholder, allowing any combination of arguments to be pre-filled. + _.partial = function(func) { + var boundArgs = slice.call(arguments, 1); + return function() { + var position = 0; + var args = boundArgs.slice(); + for (var i = 0, length = args.length; i < length; i++) { + if (args[i] === _) args[i] = arguments[position++]; + } + while (position < arguments.length) args.push(arguments[position++]); + return func.apply(this, args); + }; + }; + + // Bind a number of an object's methods to that object. Remaining arguments + // are the method names to be bound. Useful for ensuring that all callbacks + // defined on an object belong to it. + _.bindAll = function(obj) { + var funcs = slice.call(arguments, 1); + if (funcs.length === 0) throw new Error('bindAll must be passed function names'); + each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); + return obj; + }; + + // Memoize an expensive function by storing its results. + _.memoize = function(func, hasher) { + var memo = {}; + hasher || (hasher = _.identity); + return function() { + var key = hasher.apply(this, arguments); + return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); + }; + }; + + // Delays a function for the given number of milliseconds, and then calls + // it with the arguments supplied. + _.delay = function(func, wait) { + var args = slice.call(arguments, 2); + return setTimeout(function(){ return func.apply(null, args); }, wait); + }; + + // Defers a function, scheduling it to run after the current call stack has + // cleared. + _.defer = function(func) { + return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); + }; + + // Returns a function, that, when invoked, will only be triggered at most once + // during a given window of time. Normally, the throttled function will run + // as much as it can, without ever going more than once per `wait` duration; + // but if you'd like to disable the execution on the leading edge, pass + // `{leading: false}`. To disable execution on the trailing edge, ditto. + _.throttle = function(func, wait, options) { + var context, args, result; + var timeout = null; + var previous = 0; + options || (options = {}); + var later = function() { + previous = options.leading === false ? 0 : _.now(); + timeout = null; + result = func.apply(context, args); + context = args = null; + }; + return function() { + var now = _.now(); + if (!previous && options.leading === false) previous = now; + var remaining = wait - (now - previous); + context = this; + args = arguments; + if (remaining <= 0) { + clearTimeout(timeout); + timeout = null; + previous = now; + result = func.apply(context, args); + context = args = null; + } else if (!timeout && options.trailing !== false) { + timeout = setTimeout(later, remaining); + } + return result; + }; + }; + + // Returns a function, that, as long as it continues to be invoked, will not + // be triggered. The function will be called after it stops being called for + // N milliseconds. If `immediate` is passed, trigger the function on the + // leading edge, instead of the trailing. + _.debounce = function(func, wait, immediate) { + var timeout, args, context, timestamp, result; + + var later = function() { + var last = _.now() - timestamp; + if (last < wait) { + timeout = setTimeout(later, wait - last); + } else { + timeout = null; + if (!immediate) { + result = func.apply(context, args); + context = args = null; + } + } + }; + + return function() { + context = this; + args = arguments; + timestamp = _.now(); + var callNow = immediate && !timeout; + if (!timeout) { + timeout = setTimeout(later, wait); + } + if (callNow) { + result = func.apply(context, args); + context = args = null; + } + + return result; + }; + }; + + // Returns a function that will be executed at most one time, no matter how + // often you call it. Useful for lazy initialization. + _.once = function(func) { + var ran = false, memo; + return function() { + if (ran) return memo; + ran = true; + memo = func.apply(this, arguments); + func = null; + return memo; + }; + }; + + // Returns the first function passed as an argument to the second, + // allowing you to adjust arguments, run code before and after, and + // conditionally execute the original function. + _.wrap = function(func, wrapper) { + return _.partial(wrapper, func); + }; + + // Returns a function that is the composition of a list of functions, each + // consuming the return value of the function that follows. + _.compose = function() { + var funcs = arguments; + return function() { + var args = arguments; + for (var i = funcs.length - 1; i >= 0; i--) { + args = [funcs[i].apply(this, args)]; + } + return args[0]; + }; + }; + + // Returns a function that will only be executed after being called N times. + _.after = function(times, func) { + return function() { + if (--times < 1) { + return func.apply(this, arguments); + } + }; + }; + + // Object Functions + // ---------------- + + // Retrieve the names of an object's properties. + // Delegates to **ECMAScript 5**'s native `Object.keys` + _.keys = function(obj) { + if (!_.isObject(obj)) return []; + if (nativeKeys) return nativeKeys(obj); + var keys = []; + for (var key in obj) if (_.has(obj, key)) keys.push(key); + return keys; + }; + + // Retrieve the values of an object's properties. + _.values = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var values = new Array(length); + for (var i = 0; i < length; i++) { + values[i] = obj[keys[i]]; + } + return values; + }; + + // Convert an object into a list of `[key, value]` pairs. + _.pairs = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var pairs = new Array(length); + for (var i = 0; i < length; i++) { + pairs[i] = [keys[i], obj[keys[i]]]; + } + return pairs; + }; + + // Invert the keys and values of an object. The values must be serializable. + _.invert = function(obj) { + var result = {}; + var keys = _.keys(obj); + for (var i = 0, length = keys.length; i < length; i++) { + result[obj[keys[i]]] = keys[i]; + } + return result; + }; + + // Return a sorted list of the function names available on the object. + // Aliased as `methods` + _.functions = _.methods = function(obj) { + var names = []; + for (var key in obj) { + if (_.isFunction(obj[key])) names.push(key); + } + return names.sort(); + }; + + // Extend a given object with all the properties in passed-in object(s). + _.extend = function(obj) { + each(slice.call(arguments, 1), function(source) { + if (source) { + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }); + return obj; + }; + + // Return a copy of the object only containing the whitelisted properties. + _.pick = function(obj) { + var copy = {}; + var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); + each(keys, function(key) { + if (key in obj) copy[key] = obj[key]; + }); + return copy; + }; + + // Return a copy of the object without the blacklisted properties. + _.omit = function(obj) { + var copy = {}; + var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); + for (var key in obj) { + if (!_.contains(keys, key)) copy[key] = obj[key]; + } + return copy; + }; + + // Fill in a given object with default properties. + _.defaults = function(obj) { + each(slice.call(arguments, 1), function(source) { + if (source) { + for (var prop in source) { + if (obj[prop] === void 0) obj[prop] = source[prop]; + } + } + }); + return obj; + }; + + // Create a (shallow-cloned) duplicate of an object. + _.clone = function(obj) { + if (!_.isObject(obj)) return obj; + return _.isArray(obj) ? obj.slice() : _.extend({}, obj); + }; + + // Invokes interceptor with the obj, and then returns obj. + // The primary purpose of this method is to "tap into" a method chain, in + // order to perform operations on intermediate results within the chain. + _.tap = function(obj, interceptor) { + interceptor(obj); + return obj; + }; + + // Internal recursive comparison function for `isEqual`. + var eq = function(a, b, aStack, bStack) { + // Identical objects are equal. `0 === -0`, but they aren't identical. + // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). + if (a === b) return a !== 0 || 1 / a == 1 / b; + // A strict comparison is necessary because `null == undefined`. + if (a == null || b == null) return a === b; + // Unwrap any wrapped objects. + if (a instanceof _) a = a._wrapped; + if (b instanceof _) b = b._wrapped; + // Compare `[[Class]]` names. + var className = toString.call(a); + if (className != toString.call(b)) return false; + switch (className) { + // Strings, numbers, dates, and booleans are compared by value. + case '[object String]': + // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is + // equivalent to `new String("5")`. + return a == String(b); + case '[object Number]': + // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for + // other numeric values. + return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); + case '[object Date]': + case '[object Boolean]': + // Coerce dates and booleans to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // of `NaN` are not equivalent. + return +a == +b; + // RegExps are compared by their source patterns and flags. + case '[object RegExp]': + return a.source == b.source && + a.global == b.global && + a.multiline == b.multiline && + a.ignoreCase == b.ignoreCase; + } + if (typeof a != 'object' || typeof b != 'object') return false; + // Assume equality for cyclic structures. The algorithm for detecting cyclic + // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. + var length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + if (aStack[length] == a) return bStack[length] == b; + } + // Objects with different constructors are not equivalent, but `Object`s + // from different frames are. + var aCtor = a.constructor, bCtor = b.constructor; + if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && + _.isFunction(bCtor) && (bCtor instanceof bCtor)) + && ('constructor' in a && 'constructor' in b)) { + return false; + } + // Add the first object to the stack of traversed objects. + aStack.push(a); + bStack.push(b); + var size = 0, result = true; + // Recursively compare objects and arrays. + if (className == '[object Array]') { + // Compare array lengths to determine if a deep comparison is necessary. + size = a.length; + result = size == b.length; + if (result) { + // Deep compare the contents, ignoring non-numeric properties. + while (size--) { + if (!(result = eq(a[size], b[size], aStack, bStack))) break; + } + } + } else { + // Deep compare objects. + for (var key in a) { + if (_.has(a, key)) { + // Count the expected number of properties. + size++; + // Deep compare each member. + if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; + } + } + // Ensure that both objects contain the same number of properties. + if (result) { + for (key in b) { + if (_.has(b, key) && !(size--)) break; + } + result = !size; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + bStack.pop(); + return result; + }; + + // Perform a deep comparison to check if two objects are equal. + _.isEqual = function(a, b) { + return eq(a, b, [], []); + }; + + // Is a given array, string, or object empty? + // An "empty" object has no enumerable own-properties. + _.isEmpty = function(obj) { + if (obj == null) return true; + if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; + for (var key in obj) if (_.has(obj, key)) return false; + return true; + }; + + // Is a given value a DOM element? + _.isElement = function(obj) { + return !!(obj && obj.nodeType === 1); + }; + + // Is a given value an array? + // Delegates to ECMA5's native Array.isArray + _.isArray = nativeIsArray || function(obj) { + return toString.call(obj) == '[object Array]'; + }; + + // Is a given variable an object? + _.isObject = function(obj) { + return obj === Object(obj); + }; + + // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. + each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { + _['is' + name] = function(obj) { + return toString.call(obj) == '[object ' + name + ']'; + }; + }); + + // Define a fallback version of the method in browsers (ahem, IE), where + // there isn't any inspectable "Arguments" type. + if (!_.isArguments(arguments)) { + _.isArguments = function(obj) { + return !!(obj && _.has(obj, 'callee')); + }; + } + + // Optimize `isFunction` if appropriate. + if (typeof (/./) !== 'function') { + _.isFunction = function(obj) { + return typeof obj === 'function'; + }; + } + + // Is a given object a finite number? + _.isFinite = function(obj) { + return isFinite(obj) && !isNaN(parseFloat(obj)); + }; + + // Is the given value `NaN`? (NaN is the only number which does not equal itself). + _.isNaN = function(obj) { + return _.isNumber(obj) && obj != +obj; + }; + + // Is a given value a boolean? + _.isBoolean = function(obj) { + return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; + }; + + // Is a given value equal to null? + _.isNull = function(obj) { + return obj === null; + }; + + // Is a given variable undefined? + _.isUndefined = function(obj) { + return obj === void 0; + }; + + // Shortcut function for checking if an object has a given property directly + // on itself (in other words, not on a prototype). + _.has = function(obj, key) { + return hasOwnProperty.call(obj, key); + }; + + // Utility Functions + // ----------------- + + // Run Underscore.js in *noConflict* mode, returning the `_` variable to its + // previous owner. Returns a reference to the Underscore object. + _.noConflict = function() { + root._ = previousUnderscore; + return this; + }; + + // Keep the identity function around for default iterators. + _.identity = function(value) { + return value; + }; + + _.constant = function(value) { + return function () { + return value; + }; + }; + + _.property = function(key) { + return function(obj) { + return obj[key]; + }; + }; + + // Returns a predicate for checking whether an object has a given set of `key:value` pairs. + _.matches = function(attrs) { + return function(obj) { + if (obj === attrs) return true; //avoid comparing an object to itself. + for (var key in attrs) { + if (attrs[key] !== obj[key]) + return false; + } + return true; + } + }; + + // Run a function **n** times. + _.times = function(n, iterator, context) { + var accum = Array(Math.max(0, n)); + for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i); + return accum; + }; + + // Return a random integer between min and max (inclusive). + _.random = function(min, max) { + if (max == null) { + max = min; + min = 0; + } + return min + Math.floor(Math.random() * (max - min + 1)); + }; + + // A (possibly faster) way to get the current timestamp as an integer. + _.now = Date.now || function() { return new Date().getTime(); }; + + // List of HTML entities for escaping. + var entityMap = { + escape: { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + } + }; + entityMap.unescape = _.invert(entityMap.escape); + + // Regexes containing the keys and values listed immediately above. + var entityRegexes = { + escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), + unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') + }; + + // Functions for escaping and unescaping strings to/from HTML interpolation. + _.each(['escape', 'unescape'], function(method) { + _[method] = function(string) { + if (string == null) return ''; + return ('' + string).replace(entityRegexes[method], function(match) { + return entityMap[method][match]; + }); + }; + }); + + // If the value of the named `property` is a function then invoke it with the + // `object` as context; otherwise, return it. + _.result = function(object, property) { + if (object == null) return void 0; + var value = object[property]; + return _.isFunction(value) ? value.call(object) : value; + }; + + // Add your own custom functions to the Underscore object. + _.mixin = function(obj) { + each(_.functions(obj), function(name) { + var func = _[name] = obj[name]; + _.prototype[name] = function() { + var args = [this._wrapped]; + push.apply(args, arguments); + return result.call(this, func.apply(_, args)); + }; + }); + }; + + // Generate a unique integer id (unique within the entire client session). + // Useful for temporary DOM ids. + var idCounter = 0; + _.uniqueId = function(prefix) { + var id = ++idCounter + ''; + return prefix ? prefix + id : id; + }; + + // By default, Underscore uses ERB-style template delimiters, change the + // following template settings to use alternative delimiters. + _.templateSettings = { + evaluate : /<%([\s\S]+?)%>/g, + interpolate : /<%=([\s\S]+?)%>/g, + escape : /<%-([\s\S]+?)%>/g + }; + + // When customizing `templateSettings`, if you don't want to define an + // interpolation, evaluation or escaping regex, we need one that is + // guaranteed not to match. + var noMatch = /(.)^/; + + // Certain characters need to be escaped so that they can be put into a + // string literal. + var escapes = { + "'": "'", + '\\': '\\', + '\r': 'r', + '\n': 'n', + '\t': 't', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; + + // JavaScript micro-templating, similar to John Resig's implementation. + // Underscore templating handles arbitrary delimiters, preserves whitespace, + // and correctly escapes quotes within interpolated code. + _.template = function(text, data, settings) { + var render; + settings = _.defaults({}, settings, _.templateSettings); + + // Combine delimiters into one regular expression via alternation. + var matcher = new RegExp([ + (settings.escape || noMatch).source, + (settings.interpolate || noMatch).source, + (settings.evaluate || noMatch).source + ].join('|') + '|$', 'g'); + + // Compile the template source, escaping string literals appropriately. + var index = 0; + var source = "__p+='"; + text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { + source += text.slice(index, offset) + .replace(escaper, function(match) { return '\\' + escapes[match]; }); + + if (escape) { + source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; + } + if (interpolate) { + source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; + } + if (evaluate) { + source += "';\n" + evaluate + "\n__p+='"; + } + index = offset + match.length; + return match; + }); + source += "';\n"; + + // If a variable is not specified, place data values in local scope. + if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; + + source = "var __t,__p='',__j=Array.prototype.join," + + "print=function(){__p+=__j.call(arguments,'');};\n" + + source + "return __p;\n"; + + try { + render = new Function(settings.variable || 'obj', '_', source); + } catch (e) { + e.source = source; + throw e; + } + + if (data) return render(data, _); + var template = function(data) { + return render.call(this, data, _); + }; + + // Provide the compiled function source as a convenience for precompilation. + template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; + + return template; + }; + + // Add a "chain" function, which will delegate to the wrapper. + _.chain = function(obj) { + return _(obj).chain(); + }; + + // OOP + // --------------- + // If Underscore is called as a function, it returns a wrapped object that + // can be used OO-style. This wrapper holds altered versions of all the + // underscore functions. Wrapped objects may be chained. + + // Helper function to continue chaining intermediate results. + var result = function(obj) { + return this._chain ? _(obj).chain() : obj; + }; + + // Add all of the Underscore functions to the wrapper object. + _.mixin(_); + + // Add all mutator Array functions to the wrapper. + each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + var obj = this._wrapped; + method.apply(obj, arguments); + if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; + return result.call(this, obj); + }; + }); + + // Add all accessor Array functions to the wrapper. + each(['concat', 'join', 'slice'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + return result.call(this, method.apply(this._wrapped, arguments)); + }; + }); + + _.extend(_.prototype, { + + // Start chaining a wrapped Underscore object. + chain: function() { + this._chain = true; + return this; + }, + + // Extracts the result from a wrapped and chained object. + value: function() { + return this._wrapped; + } + + }); + + // AMD registration happens at the end for compatibility with AMD loaders + // that may not enforce next-turn semantics on modules. Even though general + // practice for AMD registration is to be anonymous, underscore registers + // as a named module because, like jQuery, it is a base library that is + // popular enough to be bundled in a third party lib, but not be part of + // an AMD load request. Those cases could generate an error when an + // anonymous define() is called outside of a loader request. + if (typeof define === 'function' && define.amd) { + define('underscore', [], function() { + return _; + }); + } +}).call(this); + +},{}],38:[function(require,module,exports){ +module.exports={ + "name": "carto", + "version": "0.14.0", + "description": "Mapnik Stylesheet Compiler", + "url": "https://github.com/mapbox/carto", + "repository": { + "type": "git", + "url": "http://github.com/mapbox/carto.git" + }, + "author": { + "name": "Mapbox", + "url": "http://mapbox.com/", + "email": "info@mapbox.com" + }, + "keywords": [ + "mapnik", + "maps", + "css", + "stylesheets" + ], + "contributors": [ + "Tom MacWright ", + "Konstantin Käfer", + "Alexis Sellier " + ], + "licenses": [ + { + "type": "Apache" + } + ], + "bin": { + "carto": "./bin/carto" + }, + "man": "./man/carto.1", + "main": "./lib/carto/index", + "engines": { + "node": ">=0.4.x" + }, + "dependencies": { + "underscore": "~1.6.0", + "mapnik-reference": "~6.0.2", + "optimist": "~0.6.0" + }, + "devDependencies": { + "mocha": "1.12.x", + "jshint": "0.2.x", + "sax": "0.1.x", + "istanbul": "~0.2.14", + "coveralls": "~2.10.1", + "browserify": "~7.0.0" + }, + "scripts": { + "pretest": "npm install", + "test": "mocha -R spec", + "coverage": "istanbul cover ./node_modules/.bin/_mocha && coveralls < ./coverage/lcov.info" + } +} + +},{}],39:[function(require,module,exports){ + +},{}],40:[function(require,module,exports){ +// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 +// +// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! +// +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.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 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. + +// when used in node, this will actually load the util module we depend on +// versus loading the builtin util module as happens otherwise +// this is a bug in node module loading as far as I am concerned +var util = require('util/'); + +var pSlice = Array.prototype.slice; +var hasOwn = Object.prototype.hasOwnProperty; + +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = module.exports = ok; + +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) + +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } + else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = stackStartFunction.name; + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } +}; + +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); + +function replacer(key, value) { + if (util.isUndefined(value)) { + return '' + value; + } + if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { + return value.toString(); + } + if (util.isFunction(value) || util.isRegExp(value)) { + return value.toString(); + } + return value; +} + +function truncate(s, n) { + if (util.isString(s)) { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} + +function getMessage(self) { + return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + + self.operator + ' ' + + truncate(JSON.stringify(self.expected, replacer), 128); +} + +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. + +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} + +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; + +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. + +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; + +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); + +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; + +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); + +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } +}; + +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); + +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } +}; + +function _deepEqual(actual, expected) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + + } else if (util.isBuffer(actual) && util.isBuffer(expected)) { + if (actual.length != expected.length) return false; + + for (var i = 0; i < actual.length; i++) { + if (actual[i] !== expected[i]) return false; + } + + return true; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if (!util.isObject(actual) && !util.isObject(expected)) { + return actual == expected; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else { + return objEquiv(actual, expected); + } +} + +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function objEquiv(a, b) { + if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) + return false; + // an identical 'prototype' property. + if (a.prototype !== b.prototype) return false; + //~~~I've managed to break Object.keys through screwy arguments passing. + // Converting to array solves the problem. + if (isArguments(a)) { + if (!isArguments(b)) { + return false; + } + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b); + } + try { + var ka = objectKeys(a), + kb = objectKeys(b), + key, i; + } catch (e) {//happens when one is a string literal and the other isn't + return false; + } + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length != kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] != kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key])) return false; + } + return true; +} + +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); + +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } +}; + +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); + +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } +}; + +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; + +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } else if (actual instanceof expected) { + return true; + } else if (expected.call({}, actual) === true) { + return true; + } + + return false; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (util.isString(expected)) { + message = expected; + expected = null; + } + + try { + block(); + } catch (e) { + actual = e; + } + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + if (!shouldThrow && expectedException(actual, expected)) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); + +assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws.apply(this, [true].concat(pSlice.call(arguments))); +}; + +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function(block, /*optional*/message) { + _throws.apply(this, [false].concat(pSlice.call(arguments))); +}; + +assert.ifError = function(err) { if (err) {throw err;}}; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; + +},{"util/":45}],41:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],42:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) +},{"_process":43}],43:[function(require,module,exports){ +// shim for using process in browser + +var process = module.exports = {}; + +process.nextTick = (function () { + var canSetImmediate = typeof window !== 'undefined' + && window.setImmediate; + var canMutationObserver = typeof window !== 'undefined' + && window.MutationObserver; + var canPost = typeof window !== 'undefined' + && window.postMessage && window.addEventListener + ; + + if (canSetImmediate) { + return function (f) { return window.setImmediate(f) }; + } + + var queue = []; + + if (canMutationObserver) { + var hiddenDiv = document.createElement("div"); + var observer = new MutationObserver(function () { + var queueList = queue.slice(); + queue.length = 0; + queueList.forEach(function (fn) { + fn(); + }); + }); + + observer.observe(hiddenDiv, { attributes: true }); + + return function nextTick(fn) { + if (!queue.length) { + hiddenDiv.setAttribute('yes', 'no'); + } + queue.push(fn); + }; + } + + if (canPost) { + window.addEventListener('message', function (ev) { + var source = ev.source; + if ((source === window || source === null) && ev.data === 'process-tick') { + ev.stopPropagation(); + if (queue.length > 0) { + var fn = queue.shift(); + fn(); + } + } + }, true); + + return function nextTick(fn) { + queue.push(fn); + window.postMessage('process-tick', '*'); + }; + } + + return function nextTick(fn) { + setTimeout(fn, 0); + }; +})(); + +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +// TODO(shtylman) +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; + +},{}],44:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +},{}],45:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":44,"_process":43,"inherits":41}]},{},[2])(2) +}); \ No newline at end of file