nunjucks
Version:
A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
1,653 lines (1,614 loc) • 220 kB
JavaScript
/*! Browser bundle of nunjucks 3.2.4 */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["nunjucks"] = factory();
else
root["nunjucks"] = factory();
})(typeof self !== 'undefined' ? self : this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 11);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ArrayProto = Array.prototype;
var ObjProto = Object.prototype;
var escapeMap = {
'&': '&',
'"': '"',
'\'': ''',
'<': '<',
'>': '>',
'\\': '\'
};
var escapeRegex = /[&"'<>\\]/g;
var exports = module.exports = {};
function hasOwnProp(obj, k) {
return ObjProto.hasOwnProperty.call(obj, k);
}
exports.hasOwnProp = hasOwnProp;
function lookupEscape(ch) {
return escapeMap[ch];
}
function _prettifyError(path, withInternals, err) {
if (!err.Update) {
// not one of ours, cast it
err = new exports.TemplateError(err);
}
err.Update(path);
// Unless they marked the dev flag, show them a trace from here
if (!withInternals) {
var old = err;
err = new Error(old.message);
err.name = old.name;
}
return err;
}
exports._prettifyError = _prettifyError;
function TemplateError(message, lineno, colno) {
var err;
var cause;
if (message instanceof Error) {
cause = message;
message = cause.name + ": " + cause.message;
}
if (Object.setPrototypeOf) {
err = new Error(message);
Object.setPrototypeOf(err, TemplateError.prototype);
} else {
err = this;
Object.defineProperty(err, 'message', {
enumerable: false,
writable: true,
value: message
});
}
Object.defineProperty(err, 'name', {
value: 'Template render error'
});
if (Error.captureStackTrace) {
Error.captureStackTrace(err, this.constructor);
}
var getStack;
if (cause) {
var stackDescriptor = Object.getOwnPropertyDescriptor(cause, 'stack');
getStack = stackDescriptor && (stackDescriptor.get || function () {
return stackDescriptor.value;
});
if (!getStack) {
getStack = function getStack() {
return cause.stack;
};
}
} else {
var stack = new Error(message).stack;
getStack = function getStack() {
return stack;
};
}
Object.defineProperty(err, 'stack', {
get: function get() {
return getStack.call(err);
}
});
Object.defineProperty(err, 'cause', {
value: cause
});
err.lineno = lineno;
err.colno = colno;
err.firstUpdate = true;
err.Update = function Update(path) {
var msg = '(' + (path || 'unknown path') + ')';
// only show lineno + colno next to path of template
// where error occurred
if (this.firstUpdate) {
if (this.lineno && this.colno) {
msg += " [Line " + this.lineno + ", Column " + this.colno + "]";
} else if (this.lineno) {
msg += " [Line " + this.lineno + "]";
}
}
msg += '\n ';
if (this.firstUpdate) {
msg += ' ';
}
this.message = msg + (this.message || '');
this.firstUpdate = false;
return this;
};
return err;
}
if (Object.setPrototypeOf) {
Object.setPrototypeOf(TemplateError.prototype, Error.prototype);
} else {
TemplateError.prototype = Object.create(Error.prototype, {
constructor: {
value: TemplateError
}
});
}
exports.TemplateError = TemplateError;
function escape(val) {
return val.replace(escapeRegex, lookupEscape);
}
exports.escape = escape;
function isFunction(obj) {
return ObjProto.toString.call(obj) === '[object Function]';
}
exports.isFunction = isFunction;
function isArray(obj) {
return ObjProto.toString.call(obj) === '[object Array]';
}
exports.isArray = isArray;
function isString(obj) {
return ObjProto.toString.call(obj) === '[object String]';
}
exports.isString = isString;
function isObject(obj) {
return ObjProto.toString.call(obj) === '[object Object]';
}
exports.isObject = isObject;
/**
* @param {string|number} attr
* @returns {(string|number)[]}
* @private
*/
function _prepareAttributeParts(attr) {
if (!attr) {
return [];
}
if (typeof attr === 'string') {
return attr.split('.');
}
return [attr];
}
/**
* @param {string} attribute Attribute value. Dots allowed.
* @returns {function(Object): *}
*/
function getAttrGetter(attribute) {
var parts = _prepareAttributeParts(attribute);
return function attrGetter(item) {
var _item = item;
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
// If item is not an object, and we still got parts to handle, it means
// that something goes wrong. Just roll out to undefined in that case.
if (hasOwnProp(_item, part)) {
_item = _item[part];
} else {
return undefined;
}
}
return _item;
};
}
exports.getAttrGetter = getAttrGetter;
function groupBy(obj, val, throwOnUndefined) {
var result = {};
var iterator = isFunction(val) ? val : getAttrGetter(val);
for (var i = 0; i < obj.length; i++) {
var value = obj[i];
var key = iterator(value, i);
if (key === undefined && throwOnUndefined === true) {
throw new TypeError("groupby: attribute \"" + val + "\" resolved to undefined");
}
(result[key] || (result[key] = [])).push(value);
}
return result;
}
exports.groupBy = groupBy;
function toArray(obj) {
return Array.prototype.slice.call(obj);
}
exports.toArray = toArray;
function without(array) {
var result = [];
if (!array) {
return result;
}
var length = array.length;
var contains = toArray(arguments).slice(1);
var index = -1;
while (++index < length) {
if (indexOf(contains, array[index]) === -1) {
result.push(array[index]);
}
}
return result;
}
exports.without = without;
function repeat(char_, n) {
var str = '';
for (var i = 0; i < n; i++) {
str += char_;
}
return str;
}
exports.repeat = repeat;
function each(obj, func, context) {
if (obj == null) {
return;
}
if (ArrayProto.forEach && obj.forEach === ArrayProto.forEach) {
obj.forEach(func, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
func.call(context, obj[i], i, obj);
}
}
}
exports.each = each;
function map(obj, func) {
var results = [];
if (obj == null) {
return results;
}
if (ArrayProto.map && obj.map === ArrayProto.map) {
return obj.map(func);
}
for (var i = 0; i < obj.length; i++) {
results[results.length] = func(obj[i], i);
}
if (obj.length === +obj.length) {
results.length = obj.length;
}
return results;
}
exports.map = map;
function asyncIter(arr, iter, cb) {
var i = -1;
function next() {
i++;
if (i < arr.length) {
iter(arr[i], i, next, cb);
} else {
cb();
}
}
next();
}
exports.asyncIter = asyncIter;
function asyncFor(obj, iter, cb) {
var keys = keys_(obj || {});
var len = keys.length;
var i = -1;
function next() {
i++;
var k = keys[i];
if (i < len) {
iter(k, obj[k], i, len, next);
} else {
cb();
}
}
next();
}
exports.asyncFor = asyncFor;
function indexOf(arr, searchElement, fromIndex) {
return Array.prototype.indexOf.call(arr || [], searchElement, fromIndex);
}
exports.indexOf = indexOf;
function keys_(obj) {
/* eslint-disable no-restricted-syntax */
var arr = [];
for (var k in obj) {
if (hasOwnProp(obj, k)) {
arr.push(k);
}
}
return arr;
}
exports.keys = keys_;
function _entries(obj) {
return keys_(obj).map(function (k) {
return [k, obj[k]];
});
}
exports._entries = _entries;
function _values(obj) {
return keys_(obj).map(function (k) {
return obj[k];
});
}
exports._values = _values;
function extend(obj1, obj2) {
obj1 = obj1 || {};
keys_(obj2).forEach(function (k) {
obj1[k] = obj2[k];
});
return obj1;
}
exports._assign = exports.extend = extend;
function inOperator(key, val) {
if (isArray(val) || isString(val)) {
return val.indexOf(key) !== -1;
} else if (isObject(val)) {
return key in val;
}
throw new Error('Cannot use "in" operator to search for "' + key + '" in unexpected types.');
}
exports.inOperator = inOperator;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// A simple class system, more documentation to come
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var EventEmitter = __webpack_require__(16);
var lib = __webpack_require__(0);
function parentWrap(parent, prop) {
if (typeof parent !== 'function' || typeof prop !== 'function') {
return prop;
}
return function wrap() {
// Save the current parent method
var tmp = this.parent;
// Set parent to the previous method, call, and restore
this.parent = parent;
var res = prop.apply(this, arguments);
this.parent = tmp;
return res;
};
}
function extendClass(cls, name, props) {
props = props || {};
lib.keys(props).forEach(function (k) {
props[k] = parentWrap(cls.prototype[k], props[k]);
});
var subclass = /*#__PURE__*/function (_cls) {
_inheritsLoose(subclass, _cls);
function subclass() {
return _cls.apply(this, arguments) || this;
}
_createClass(subclass, [{
key: "typename",
get: function get() {
return name;
}
}]);
return subclass;
}(cls);
lib._assign(subclass.prototype, props);
return subclass;
}
var Obj = /*#__PURE__*/function () {
function Obj() {
// Unfortunately necessary for backwards compatibility
this.init.apply(this, arguments);
}
var _proto = Obj.prototype;
_proto.init = function init() {};
Obj.extend = function extend(name, props) {
if (typeof name === 'object') {
props = name;
name = 'anonymous';
}
return extendClass(this, name, props);
};
_createClass(Obj, [{
key: "typename",
get: function get() {
return this.constructor.name;
}
}]);
return Obj;
}();
var EmitterObj = /*#__PURE__*/function (_EventEmitter) {
_inheritsLoose(EmitterObj, _EventEmitter);
function EmitterObj() {
var _this2;
var _this;
_this = _EventEmitter.call(this) || this;
// Unfortunately necessary for backwards compatibility
(_this2 = _this).init.apply(_this2, arguments);
return _this;
}
var _proto2 = EmitterObj.prototype;
_proto2.init = function init() {};
EmitterObj.extend = function extend(name, props) {
if (typeof name === 'object') {
props = name;
name = 'anonymous';
}
return extendClass(this, name, props);
};
_createClass(EmitterObj, [{
key: "typename",
get: function get() {
return this.constructor.name;
}
}]);
return EmitterObj;
}(EventEmitter);
module.exports = {
Obj: Obj,
EmitterObj: EmitterObj
};
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var lib = __webpack_require__(0);
var arrayFrom = Array.from;
var supportsIterators = typeof Symbol === 'function' && Symbol.iterator && typeof arrayFrom === 'function';
// Frames keep track of scoping both at compile-time and run-time so
// we know how to access variables. Block tags can introduce special
// variables, for example.
var Frame = /*#__PURE__*/function () {
function Frame(parent, isolateWrites) {
this.variables = Object.create(null);
this.parent = parent;
this.topLevel = false;
// if this is true, writes (set) should never propagate upwards past
// this frame to its parent (though reads may).
this.isolateWrites = isolateWrites;
}
var _proto = Frame.prototype;
_proto.set = function set(name, val, resolveUp) {
// Allow variables with dots by automatically creating the
// nested structure
var parts = name.split('.');
var obj = this.variables;
var frame = this;
if (resolveUp) {
if (frame = this.resolve(parts[0], true)) {
frame.set(name, val);
return;
}
}
for (var i = 0; i < parts.length - 1; i++) {
var id = parts[i];
if (!obj[id]) {
obj[id] = {};
}
obj = obj[id];
}
obj[parts[parts.length - 1]] = val;
};
_proto.get = function get(name) {
var val = this.variables[name];
if (val !== undefined) {
return val;
}
return null;
};
_proto.lookup = function lookup(name) {
var p = this.parent;
var val = this.variables[name];
if (val !== undefined) {
return val;
}
return p && p.lookup(name);
};
_proto.resolve = function resolve(name, forWrite) {
var p = forWrite && this.isolateWrites ? undefined : this.parent;
var val = this.variables[name];
if (val !== undefined) {
return this;
}
return p && p.resolve(name);
};
_proto.push = function push(isolateWrites) {
return new Frame(this, isolateWrites);
};
_proto.pop = function pop() {
return this.parent;
};
return Frame;
}();
function makeMacro(argNames, kwargNames, func) {
return function macro() {
for (var _len = arguments.length, macroArgs = new Array(_len), _key = 0; _key < _len; _key++) {
macroArgs[_key] = arguments[_key];
}
var argCount = numArgs(macroArgs);
var args;
var kwargs = getKeywordArgs(macroArgs);
if (argCount > argNames.length) {
args = macroArgs.slice(0, argNames.length);
// Positional arguments that should be passed in as
// keyword arguments (essentially default values)
macroArgs.slice(args.length, argCount).forEach(function (val, i) {
if (i < kwargNames.length) {
kwargs[kwargNames[i]] = val;
}
});
args.push(kwargs);
} else if (argCount < argNames.length) {
args = macroArgs.slice(0, argCount);
for (var i = argCount; i < argNames.length; i++) {
var arg = argNames[i];
// Keyword arguments that should be passed as
// positional arguments, i.e. the caller explicitly
// used the name of a positional arg
args.push(kwargs[arg]);
delete kwargs[arg];
}
args.push(kwargs);
} else {
args = macroArgs;
}
return func.apply(this, args);
};
}
function makeKeywordArgs(obj) {
obj.__keywords = true;
return obj;
}
function isKeywordArgs(obj) {
return obj && Object.prototype.hasOwnProperty.call(obj, '__keywords');
}
function getKeywordArgs(args) {
var len = args.length;
if (len) {
var lastArg = args[len - 1];
if (isKeywordArgs(lastArg)) {
return lastArg;
}
}
return {};
}
function numArgs(args) {
var len = args.length;
if (len === 0) {
return 0;
}
var lastArg = args[len - 1];
if (isKeywordArgs(lastArg)) {
return len - 1;
} else {
return len;
}
}
// A SafeString object indicates that the string should not be
// autoescaped. This happens magically because autoescaping only
// occurs on primitive string objects.
function SafeString(val) {
if (typeof val !== 'string') {
return val;
}
this.val = val;
this.length = val.length;
}
SafeString.prototype = Object.create(String.prototype, {
length: {
writable: true,
configurable: true,
value: 0
}
});
SafeString.prototype.valueOf = function valueOf() {
return this.val;
};
SafeString.prototype.toString = function toString() {
return this.val;
};
function copySafeness(dest, target) {
if (dest instanceof SafeString) {
return new SafeString(target);
}
return target.toString();
}
function markSafe(val) {
var type = typeof val;
if (type === 'string') {
return new SafeString(val);
} else if (type !== 'function') {
return val;
} else {
return function wrapSafe(args) {
var ret = val.apply(this, arguments);
if (typeof ret === 'string') {
return new SafeString(ret);
}
return ret;
};
}
}
function suppressValue(val, autoescape) {
val = val !== undefined && val !== null ? val : '';
if (autoescape && !(val instanceof SafeString)) {
val = lib.escape(val.toString());
}
return val;
}
function ensureDefined(val, lineno, colno) {
if (val === null || val === undefined) {
throw new lib.TemplateError('attempted to output null or undefined value', lineno + 1, colno + 1);
}
return val;
}
function memberLookup(obj, val) {
if (obj === undefined || obj === null) {
return undefined;
}
if (typeof obj[val] === 'function') {
return function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return obj[val].apply(obj, args);
};
}
return obj[val];
}
function callWrap(obj, name, context, args) {
if (!obj) {
throw new Error('Unable to call `' + name + '`, which is undefined or falsey');
} else if (typeof obj !== 'function') {
throw new Error('Unable to call `' + name + '`, which is not a function');
}
return obj.apply(context, args);
}
function contextOrFrameLookup(context, frame, name) {
var val = frame.lookup(name);
return val !== undefined ? val : context.lookup(name);
}
function handleError(error, lineno, colno) {
if (error.lineno) {
return error;
} else {
return new lib.TemplateError(error, lineno, colno);
}
}
function asyncEach(arr, dimen, iter, cb) {
if (lib.isArray(arr)) {
var len = arr.length;
lib.asyncIter(arr, function iterCallback(item, i, next) {
switch (dimen) {
case 1:
iter(item, i, len, next);
break;
case 2:
iter(item[0], item[1], i, len, next);
break;
case 3:
iter(item[0], item[1], item[2], i, len, next);
break;
default:
item.push(i, len, next);
iter.apply(this, item);
}
}, cb);
} else {
lib.asyncFor(arr, function iterCallback(key, val, i, len, next) {
iter(key, val, i, len, next);
}, cb);
}
}
function asyncAll(arr, dimen, func, cb) {
var finished = 0;
var len;
var outputArr;
function done(i, output) {
finished++;
outputArr[i] = output;
if (finished === len) {
cb(null, outputArr.join(''));
}
}
if (lib.isArray(arr)) {
len = arr.length;
outputArr = new Array(len);
if (len === 0) {
cb(null, '');
} else {
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
switch (dimen) {
case 1:
func(item, i, len, done);
break;
case 2:
func(item[0], item[1], i, len, done);
break;
case 3:
func(item[0], item[1], item[2], i, len, done);
break;
default:
item.push(i, len, done);
func.apply(this, item);
}
}
}
} else {
var keys = lib.keys(arr || {});
len = keys.length;
outputArr = new Array(len);
if (len === 0) {
cb(null, '');
} else {
for (var _i = 0; _i < keys.length; _i++) {
var k = keys[_i];
func(k, arr[k], _i, len, done);
}
}
}
}
function fromIterator(arr) {
if (typeof arr !== 'object' || arr === null || lib.isArray(arr)) {
return arr;
} else if (supportsIterators && Symbol.iterator in arr) {
return arrayFrom(arr);
} else {
return arr;
}
}
module.exports = {
Frame: Frame,
makeMacro: makeMacro,
makeKeywordArgs: makeKeywordArgs,
numArgs: numArgs,
suppressValue: suppressValue,
ensureDefined: ensureDefined,
memberLookup: memberLookup,
contextOrFrameLookup: contextOrFrameLookup,
callWrap: callWrap,
handleError: handleError,
isArray: lib.isArray,
keys: lib.keys,
SafeString: SafeString,
copySafeness: copySafeness,
markSafe: markSafe,
asyncEach: asyncEach,
asyncAll: asyncAll,
inOperator: lib.inOperator,
fromIterator: fromIterator
};
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var _require = __webpack_require__(1),
Obj = _require.Obj;
function traverseAndCheck(obj, type, results) {
if (obj instanceof type) {
results.push(obj);
}
if (obj instanceof Node) {
obj.findAll(type, results);
}
}
var Node = /*#__PURE__*/function (_Obj) {
_inheritsLoose(Node, _Obj);
function Node() {
return _Obj.apply(this, arguments) || this;
}
var _proto = Node.prototype;
_proto.init = function init(lineno, colno) {
var _arguments = arguments,
_this = this;
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
this.lineno = lineno;
this.colno = colno;
this.fields.forEach(function (field, i) {
// The first two args are line/col numbers, so offset by 2
var val = _arguments[i + 2];
// Fields should never be undefined, but null. It makes
// testing easier to normalize values.
if (val === undefined) {
val = null;
}
_this[field] = val;
});
};
_proto.findAll = function findAll(type, results) {
var _this2 = this;
results = results || [];
if (this instanceof NodeList) {
this.children.forEach(function (child) {
return traverseAndCheck(child, type, results);
});
} else {
this.fields.forEach(function (field) {
return traverseAndCheck(_this2[field], type, results);
});
}
return results;
};
_proto.iterFields = function iterFields(func) {
var _this3 = this;
this.fields.forEach(function (field) {
func(_this3[field], field);
});
};
return Node;
}(Obj); // Abstract nodes
var Value = /*#__PURE__*/function (_Node) {
_inheritsLoose(Value, _Node);
function Value() {
return _Node.apply(this, arguments) || this;
}
_createClass(Value, [{
key: "typename",
get: function get() {
return 'Value';
}
}, {
key: "fields",
get: function get() {
return ['value'];
}
}]);
return Value;
}(Node); // Concrete nodes
var NodeList = /*#__PURE__*/function (_Node2) {
_inheritsLoose(NodeList, _Node2);
function NodeList() {
return _Node2.apply(this, arguments) || this;
}
var _proto2 = NodeList.prototype;
_proto2.init = function init(lineno, colno, nodes) {
_Node2.prototype.init.call(this, lineno, colno, nodes || []);
};
_proto2.addChild = function addChild(node) {
this.children.push(node);
};
_createClass(NodeList, [{
key: "typename",
get: function get() {
return 'NodeList';
}
}, {
key: "fields",
get: function get() {
return ['children'];
}
}]);
return NodeList;
}(Node);
var Root = NodeList.extend('Root');
var Literal = Value.extend('Literal');
var _Symbol = Value.extend('Symbol');
var Group = NodeList.extend('Group');
var ArrayNode = NodeList.extend('Array');
var Pair = Node.extend('Pair', {
fields: ['key', 'value']
});
var Dict = NodeList.extend('Dict');
var LookupVal = Node.extend('LookupVal', {
fields: ['target', 'val']
});
var If = Node.extend('If', {
fields: ['cond', 'body', 'else_']
});
var IfAsync = If.extend('IfAsync');
var InlineIf = Node.extend('InlineIf', {
fields: ['cond', 'body', 'else_']
});
var For = Node.extend('For', {
fields: ['arr', 'name', 'body', 'else_']
});
var AsyncEach = For.extend('AsyncEach');
var AsyncAll = For.extend('AsyncAll');
var Macro = Node.extend('Macro', {
fields: ['name', 'args', 'body']
});
var Caller = Macro.extend('Caller');
var Import = Node.extend('Import', {
fields: ['template', 'target', 'withContext']
});
var FromImport = /*#__PURE__*/function (_Node3) {
_inheritsLoose(FromImport, _Node3);
function FromImport() {
return _Node3.apply(this, arguments) || this;
}
var _proto3 = FromImport.prototype;
_proto3.init = function init(lineno, colno, template, names, withContext) {
_Node3.prototype.init.call(this, lineno, colno, template, names || new NodeList(), withContext);
};
_createClass(FromImport, [{
key: "typename",
get: function get() {
return 'FromImport';
}
}, {
key: "fields",
get: function get() {
return ['template', 'names', 'withContext'];
}
}]);
return FromImport;
}(Node);
var FunCall = Node.extend('FunCall', {
fields: ['name', 'args']
});
var Filter = FunCall.extend('Filter');
var FilterAsync = Filter.extend('FilterAsync', {
fields: ['name', 'args', 'symbol']
});
var KeywordArgs = Dict.extend('KeywordArgs');
var Block = Node.extend('Block', {
fields: ['name', 'body']
});
var Super = Node.extend('Super', {
fields: ['blockName', 'symbol']
});
var TemplateRef = Node.extend('TemplateRef', {
fields: ['template']
});
var Extends = TemplateRef.extend('Extends');
var Include = Node.extend('Include', {
fields: ['template', 'ignoreMissing']
});
var Set = Node.extend('Set', {
fields: ['targets', 'value']
});
var Switch = Node.extend('Switch', {
fields: ['expr', 'cases', 'default']
});
var Case = Node.extend('Case', {
fields: ['cond', 'body']
});
var Output = NodeList.extend('Output');
var Capture = Node.extend('Capture', {
fields: ['body']
});
var TemplateData = Literal.extend('TemplateData');
var UnaryOp = Node.extend('UnaryOp', {
fields: ['target']
});
var BinOp = Node.extend('BinOp', {
fields: ['left', 'right']
});
var In = BinOp.extend('In');
var Is = BinOp.extend('Is');
var Or = BinOp.extend('Or');
var And = BinOp.extend('And');
var Not = UnaryOp.extend('Not');
var Add = BinOp.extend('Add');
var Concat = BinOp.extend('Concat');
var Sub = BinOp.extend('Sub');
var Mul = BinOp.extend('Mul');
var Div = BinOp.extend('Div');
var FloorDiv = BinOp.extend('FloorDiv');
var Mod = BinOp.extend('Mod');
var Pow = BinOp.extend('Pow');
var Neg = UnaryOp.extend('Neg');
var Pos = UnaryOp.extend('Pos');
var Compare = Node.extend('Compare', {
fields: ['expr', 'ops']
});
var CompareOperand = Node.extend('CompareOperand', {
fields: ['expr', 'type']
});
var CallExtension = Node.extend('CallExtension', {
init: function init(ext, prop, args, contentArgs) {
this.parent();
this.extName = ext.__name || ext;
this.prop = prop;
this.args = args || new NodeList();
this.contentArgs = contentArgs || [];
this.autoescape = ext.autoescape;
},
fields: ['extName', 'prop', 'args', 'contentArgs']
});
var CallExtensionAsync = CallExtension.extend('CallExtensionAsync');
// This is hacky, but this is just a debugging function anyway
function print(str, indent, inline) {
var lines = str.split('\n');
lines.forEach(function (line, i) {
if (line && (inline && i > 0 || !inline)) {
process.stdout.write(' '.repeat(indent));
}
var nl = i === lines.length - 1 ? '' : '\n';
process.stdout.write("" + line + nl);
});
}
// Print the AST in a nicely formatted tree format for debuggin
function printNodes(node, indent) {
indent = indent || 0;
print(node.typename + ': ', indent);
if (node instanceof NodeList) {
print('\n');
node.children.forEach(function (n) {
printNodes(n, indent + 2);
});
} else if (node instanceof CallExtension) {
print(node.extName + "." + node.prop + "\n");
if (node.args) {
printNodes(node.args, indent + 2);
}
if (node.contentArgs) {
node.contentArgs.forEach(function (n) {
printNodes(n, indent + 2);
});
}
} else {
var nodes = [];
var props = null;
node.iterFields(function (val, fieldName) {
if (val instanceof Node) {
nodes.push([fieldName, val]);
} else {
props = props || {};
props[fieldName] = val;
}
});
if (props) {
print(JSON.stringify(props, null, 2) + '\n', null, true);
} else {
print('\n');
}
nodes.forEach(function (_ref) {
var fieldName = _ref[0],
n = _ref[1];
print("[" + fieldName + "] =>", indent + 2);
printNodes(n, indent + 4);
});
}
}
module.exports = {
Node: Node,
Root: Root,
NodeList: NodeList,
Value: Value,
Literal: Literal,
Symbol: _Symbol,
Group: Group,
Array: ArrayNode,
Pair: Pair,
Dict: Dict,
Output: Output,
Capture: Capture,
TemplateData: TemplateData,
If: If,
IfAsync: IfAsync,
InlineIf: InlineIf,
For: For,
AsyncEach: AsyncEach,
AsyncAll: AsyncAll,
Macro: Macro,
Caller: Caller,
Import: Import,
FromImport: FromImport,
FunCall: FunCall,
Filter: Filter,
FilterAsync: FilterAsync,
KeywordArgs: KeywordArgs,
Block: Block,
Super: Super,
Extends: Extends,
Include: Include,
Set: Set,
Switch: Switch,
Case: Case,
LookupVal: LookupVal,
BinOp: BinOp,
In: In,
Is: Is,
Or: Or,
And: And,
Not: Not,
Add: Add,
Concat: Concat,
Sub: Sub,
Mul: Mul,
Div: Div,
FloorDiv: FloorDiv,
Mod: Mod,
Pow: Pow,
Neg: Neg,
Pos: Pos,
Compare: Compare,
CompareOperand: CompareOperand,
CallExtension: CallExtension,
CallExtensionAsync: CallExtensionAsync,
printNodes: printNodes
};
/***/ }),
/* 4 */
/***/ (function(module, exports) {
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var parser = __webpack_require__(8);
var transformer = __webpack_require__(17);
var nodes = __webpack_require__(3);
var _require = __webpack_require__(0),
TemplateError = _require.TemplateError;
var _require2 = __webpack_require__(2),
Frame = _require2.Frame;
var _require3 = __webpack_require__(1),
Obj = _require3.Obj;
// These are all the same for now, but shouldn't be passed straight
// through
var compareOps = {
'==': '==',
'===': '===',
'!=': '!=',
'!==': '!==',
'<': '<',
'>': '>',
'<=': '<=',
'>=': '>='
};
var Compiler = /*#__PURE__*/function (_Obj) {
_inheritsLoose(Compiler, _Obj);
function Compiler() {
return _Obj.apply(this, arguments) || this;
}
var _proto = Compiler.prototype;
_proto.init = function init(templateName, throwOnUndefined) {
this.templateName = templateName;
this.codebuf = [];
this.lastId = 0;
this.buffer = null;
this.bufferStack = [];
this._scopeClosers = '';
this.inBlock = false;
this.throwOnUndefined = throwOnUndefined;
};
_proto.fail = function fail(msg, lineno, colno) {
if (lineno !== undefined) {
lineno += 1;
}
if (colno !== undefined) {
colno += 1;
}
throw new TemplateError(msg, lineno, colno);
};
_proto._pushBuffer = function _pushBuffer() {
var id = this._tmpid();
this.bufferStack.push(this.buffer);
this.buffer = id;
this._emit("var " + this.buffer + " = \"\";");
return id;
};
_proto._popBuffer = function _popBuffer() {
this.buffer = this.bufferStack.pop();
};
_proto._emit = function _emit(code) {
this.codebuf.push(code);
};
_proto._emitLine = function _emitLine(code) {
this._emit(code + '\n');
};
_proto._emitLines = function _emitLines() {
var _this = this;
for (var _len = arguments.length, lines = new Array(_len), _key = 0; _key < _len; _key++) {
lines[_key] = arguments[_key];
}
lines.forEach(function (line) {
return _this._emitLine(line);
});
};
_proto._emitFuncBegin = function _emitFuncBegin(node, name) {
this.buffer = 'output';
this._scopeClosers = '';
this._emitLine("function " + name + "(env, context, frame, runtime, cb) {");
this._emitLine("var lineno = " + node.lineno + ";");
this._emitLine("var colno = " + node.colno + ";");
this._emitLine("var " + this.buffer + " = \"\";");
this._emitLine('try {');
};
_proto._emitFuncEnd = function _emitFuncEnd(noReturn) {
if (!noReturn) {
this._emitLine('cb(null, ' + this.buffer + ');');
}
this._closeScopeLevels();
this._emitLine('} catch (e) {');
this._emitLine(' cb(runtime.handleError(e, lineno, colno));');
this._emitLine('}');
this._emitLine('}');
this.buffer = null;
};
_proto._addScopeLevel = function _addScopeLevel() {
this._scopeClosers += '})';
};
_proto._closeScopeLevels = function _closeScopeLevels() {
this._emitLine(this._scopeClosers + ';');
this._scopeClosers = '';
};
_proto._withScopedSyntax = function _withScopedSyntax(func) {
var _scopeClosers = this._scopeClosers;
this._scopeClosers = '';
func.call(this);
this._closeScopeLevels();
this._scopeClosers = _scopeClosers;
};
_proto._makeCallback = function _makeCallback(res) {
var err = this._tmpid();
return 'function(' + err + (res ? ',' + res : '') + ') {\n' + 'if(' + err + ') { cb(' + err + '); return; }';
};
_proto._tmpid = function _tmpid() {
this.lastId++;
return 't_' + this.lastId;
};
_proto._templateName = function _templateName() {
return this.templateName == null ? 'undefined' : JSON.stringify(this.templateName);
};
_proto._compileChildren = function _compileChildren(node, frame) {
var _this2 = this;
node.children.forEach(function (child) {
_this2.compile(child, frame);
});
};
_proto._compileAggregate = function _compileAggregate(node, frame, startChar, endChar) {
var _this3 = this;
if (startChar) {
this._emit(startChar);
}
node.children.forEach(function (child, i) {
if (i > 0) {
_this3._emit(',');
}
_this3.compile(child, frame);
});
if (endChar) {
this._emit(endChar);
}
};
_proto._compileExpression = function _compileExpression(node, frame) {
// TODO: I'm not really sure if this type check is worth it or
// not.
this.assertType(node, nodes.Literal, nodes.Symbol, nodes.Group, nodes.Array, nodes.Dict, nodes.FunCall, nodes.Caller, nodes.Filter, nodes.LookupVal, nodes.Compare, nodes.InlineIf, nodes.In, nodes.Is, nodes.And, nodes.Or, nodes.Not, nodes.Add, nodes.Concat, nodes.Sub, nodes.Mul, nodes.Div, nodes.FloorDiv, nodes.Mod, nodes.Pow, nodes.Neg, nodes.Pos, nodes.Compare, nodes.NodeList);
this.compile(node, frame);
};
_proto.assertType = function assertType(node) {
for (var _len2 = arguments.length, types = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
types[_key2 - 1] = arguments[_key2];
}
if (!types.some(function (t) {
return node instanceof t;
})) {
this.fail("assertType: invalid type: " + node.typename, node.lineno, node.colno);
}
};
_proto.compileCallExtension = function compileCallExtension(node, frame, async) {
var _this4 = this;
var args = node.args;
var contentArgs = node.contentArgs;
var autoescape = typeof node.autoescape === 'boolean' ? node.autoescape : true;
if (!async) {
this._emit(this.buffer + " += runtime.suppressValue(");
}
this._emit("env.getExtension(\"" + node.extName + "\")[\"" + node.prop + "\"](");
this._emit('context');
if (args || contentArgs) {
this._emit(',');
}
if (args) {
if (!(args instanceof nodes.NodeList)) {
this.fail('compileCallExtension: arguments must be a NodeList, ' + 'use `parser.parseSignature`');
}
args.children.forEach(function (arg, i) {
// Tag arguments are passed normally to the call. Note
// that keyword arguments are turned into a single js
// object as the last argument, if they exist.
_this4._compileExpression(arg, frame);
if (i !== args.children.length - 1 || contentArgs.length) {
_this4._emit(',');
}
});
}
if (contentArgs.length) {
contentArgs.forEach(function (arg, i) {
if (i > 0) {
_this4._emit(',');
}
if (arg) {
_this4._emitLine('function(cb) {');
_this4._emitLine('if(!cb) { cb = function(err) { if(err) { throw err; }}}');
var id = _this4._pushBuffer();
_this4._withScopedSyntax(function () {
_this4.compile(arg, frame);
_this4._emitLine("cb(null, " + id + ");");
});
_this4._popBuffer();
_this4._emitLine("return " + id + ";");
_this4._emitLine('}');
} else {
_this4._emit('null');
}
});
}
if (async) {
var res = this._tmpid();
this._emitLine(', ' + this._makeCallback(res));
this._emitLine(this.buffer + " += runtime.suppressValue(" + res + ", " + autoescape + " && env.opts.autoescape);");
this._addScopeLevel();
} else {
this._emit(')');
this._emit(", " + autoescape + " && env.opts.autoescape);\n");
}
};
_proto.compileCallExtensionAsync = function compileCallExtensionAsync(node, frame) {
this.compileCallExtension(node, frame, true);
};
_proto.compileNodeList = function compileNodeList(node, frame) {
this._compileChildren(node, frame);
};
_proto.compileLiteral = function compileLiteral(node) {
if (typeof node.value === 'string') {
var val = node.value.replace(/\\/g, '\\\\');
val = val.replace(/"/g, '\\"');
val = val.replace(/\n/g, '\\n');
val = val.replace(/\r/g, '\\r');
val = val.replace(/\t/g, '\\t');
val = val.replace(/\u2028/g, "\\u2028");
this._emit("\"" + val + "\"");
} else if (node.value === null) {
this._emit('null');
} else {
this._emit(node.value.toString());
}
};
_proto.compileSymbol = function compileSymbol(node, frame) {
var name = node.value;
var v = frame.lookup(name);
if (v) {
this._emit(v);
} else {
this._emit('runtime.contextOrFrameLookup(' + 'context, frame, "' + name + '")');
}
};
_proto.compileGroup = function compileGroup(node, frame) {
this._compileAggregate(node, frame, '(', ')');
};
_proto.compileArray = function compileArray(node, frame) {
this._compileAggregate(node, frame, '[', ']');
};
_proto.compileDict = function compileDict(node, frame) {
this._compileAggregate(node, frame, '{', '}');
};
_proto.compilePair = function compilePair(node, frame) {
var key = node.key;
var val = node.value;
if (key instanceof nodes.Symbol) {
key = new nodes.Literal(key.lineno, key.colno, key.value);
} else if (!(key instanceof nodes.Literal && typeof key.value === 'string')) {
this.fail('compilePair: Dict keys must be strings or names', key.lineno, key.colno);
}
this.compile(key, frame);
this._emit(': ');
this._compileExpression(val, frame);
};
_proto.compileInlineIf = function compileInlineIf(node, frame) {
this._emit('(');
this.compile(node.cond, frame);
this._emit('?');
this.compile(node.body, frame);
this._emit(':');
if (node.else_ !== null) {
this.compile(node.else_, frame);
} else {
this._emit('""');
}
this._emit(')');
};
_proto.compileIn = function compileIn(node, frame) {
this._emit('runtime.inOperator(');
this.compile(node.left, frame);
this._emit(',');
this.compile(node.right, frame);
this._emit(')');
};
_proto.compileIs = function compileIs(node, frame) {
// first, we need to try to get the name of the test function, if it's a
// callable (i.e., has args) and not a symbol.
var right = node.right.name ? node.right.name.value
// otherwise go with the symbol value
: node.right.value;
this._emit('env.getTest("' + right + '").call(context, ');
this.compile(node.left, frame);
// compile the arguments for the callable if they exist
if (node.right.args) {
this._emit(',');
this.compile(node.right.args, frame);
}
this._emit(') === true');
};
_proto._binOpEmitter = function _binOpEmitter(node, frame, str) {
this.compile(node.left, frame);
this._emit(str);
this.compile(node.right, frame);
}
// ensure concatenation instead of addition
// by adding empty string in between
;
_proto.compileOr = function compileOr(node, frame) {
return this._binOpEmitter(node, frame, ' || ');
};
_proto.compileAnd = function compileAnd(node, frame) {
return this._binOpEmitter(node, frame, ' && ');
};
_proto.compileAdd = function compileAdd(node, frame) {
return this._binOpEmitter(node, frame, ' + ');
};
_proto.compileConcat = function compileConcat(node, frame) {
return this._binOpEmitter(node, frame, ' + "" + ');
};
_proto.compileSub = function compileSub(node, frame) {
return this._binOpEmitter(node, frame, ' - ');
};
_proto.compileMul = function compileMul(node, frame) {
return this._binOpEmitter(node, frame, ' * ');
};
_proto.compileDiv = function compileDiv(node, frame) {
return this._binOpEmitter(node, frame, ' / ');
};
_proto.compileMod = function compileMod(node, frame) {
return this._binOpEmitter(node, frame, ' % ');
};
_proto.compileNot = function compileNot(node, frame) {
this._emit('!');
this.compile(node.target, frame);
};
_proto.compileFloorDiv = function compileFloorDiv(node, frame) {
this._emit('Math.floor(');
this.compile(node.left, frame);
this._emit(' / ');
this.compile(node.right, frame);
this._emit(')');
};
_proto.compilePow = function compilePow(node, frame) {
this._emit('Math.pow(');
this.compile(node.left, frame);
this._emit(', ');
this.compile(node.right, frame);
this._emit(')');
};
_proto.compileNeg = function compileNeg(node, frame) {
this._emit('-');
this.compile(node.target, frame);
};
_proto.compilePos = function compilePos(node, frame) {
this._emit('+');
this.compile(node.target, frame);
};
_proto.compileCompare = function compileCompare(node, frame) {
var _this5 = this;
this.compile(node.expr, frame);
node.ops.forEach(function (op) {
_this5._emit(" " + compareOps[op.type] + " ");
_this5.compile(op.expr, frame);
});
};
_proto.compileLookupVal = function compileLookupVal(node, frame) {
this._emit('runtime.memberLookup((');
this._compileExpression(node.target, frame);
this._emit('),');
this._compileExpression(node.val, frame);
this._emit(')');
};
_proto._getNodeName = function _getNodeName(node) {
switch (node.typename) {
case 'Symbol':
return node.value;
case 'FunCall':
return 'the return value of (' + this._getNodeName(node.name) + ')';
case 'LookupVal':
return this._getNodeName(node.target) + '["' + this._getNodeName(node.val) + '"]';
case 'Literal':
return node.value.toString();
default:
return '--expression--';
}
};
_proto.compileFunCall = function compileFunCall(node, frame) {
// Keep track of line/col info at runtime by settings
// variables within an expression. An expression in javascript
// like (x, y, z) returns the last value, and x and y can be
// anything
this._emit('(lineno = ' + node.lineno + ', colno = ' + node.colno + ', ');
this._emit('runtime.callWrap(');
// Compile it as normal.
this._compileExpression(node.name, frame);
// Output the name of what we're calling so we can get friendly errors
// if the lookup fails.
this._emit(', "' + this._getNodeName(node.name).replace(/"/g, '\\"') + '", context, ');
this._compileAggregate(node.args, frame, '[', '])');
this._emit(')');
};
_proto.compileFilter = function compileFilter(node, frame) {
var name = node.name;
this.assertType(name, nodes.Symbol);
this._emit('env.getFilter("' + name.value + '").call(context, ');
this._compileAggregate(node.args, frame);
this._emit(')');
};
_proto.compileFilterAsync = function compileFilterAsync(node, frame) {
var name = node.name;
var symbol = node.symbol.value;
this.assertType(name, nodes.Symbol);
frame.set(symbol, symbol);
this._emit('env.getFilter("' + name.value + '").call(context, ');
this._compileAggregate(node.args, frame);
this._emitLine(', ' + this._makeCallback(symbol));
this._addScopeLevel();
};
_proto.compileKeywordArgs = function compileKeywordArgs(node, frame) {
this._emit('runtime.makeKeywordArgs(');
this.compileDict(node, frame);
this._emit(')');
};
_proto.compileSet = function compileSet(node, frame) {
var _this6 = this;
var ids = [];
// Lookup the variable names for each identifier and create
// new ones if necessar