SIGN IN SIGN UP

A modern JavaScript utility library delivering modularity, performance, & extras.

0 0 9 JavaScript
2016-12-19 17:17:56 -06:00
define(['./assignInWith', './attempt', './_baseValues', './_customDefaultsAssignIn', './_escapeStringChar', './isError', './_isIterateeCall', './keys', './_reInterpolate', './templateSettings', './toString'], function(assignInWith, attempt, baseValues, customDefaultsAssignIn, escapeStringChar, isError, isIterateeCall, keys, reInterpolate, templateSettings, toString) {
2015-01-08 00:37:01 -08:00
/** Used as a safe reference for `undefined` in pre-ES5 environments. */
var undefined;
Update lodash-amd to v4.17.21 + edadd45 (#6064) * Fix prototype pollution in _.set and related functions Prevents setting dangerous properties (__proto__, constructor, prototype) that could lead to prototype pollution vulnerabilities. * Fix command injection vulnerability in _.template - Add validation for the variable option to prevent injection attacks - Improve sourceURL whitespace normalization to prevent code injection * Fix cyclic value comparison in _.isEqual Properly checks both directions when comparing cyclic values to ensure correct equality comparisons for circular references. * Improve _.sortBy and _.orderBy performance and array handling - Add early return for empty arrays in sorted index operations - Improve array iteratee handling to support nested property paths - Add missing keysIn import in baseClone * Refactor _.trim, _.trimEnd, and _.trimStart implementations Extract shared trim logic into reusable utilities (_baseTrim, _trimmedEndIndex) for better code organization and consistency. Update related functions (toNumber, parseInt) to use new utilities. Improve comment accuracy. * Add documentation for predicate composition with _.overEvery and _.overSome Enhance documentation to show how _.matches and _.matchesProperty can be combined using _.overEvery and _.overSome for more powerful filtering. Add examples demonstrating shorthand predicate syntax. * Bump to v4.17.21 * Fix prototype pollution in _.unset and _.omit Prevent prototype pollution on baseUnset function by: - Blocking "__proto__" if not an own property - Blocking "constructor.prototype" chains (except when starting at primitive root) - Skipping non-string keys See: https://github.com/lodash/lodash/security/advisories/GHSA-xxjr-mmjv-4gpg * Update JSDoc documentation to align with main branch - Fix sortBy example ages (40 -> 30) for correct sort order demonstration - Fix _setCacheHas return type (number -> boolean)
2025-12-10 17:03:07 -05:00
/** Error message constants. */
var INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';
2015-01-08 00:37:01 -08:00
/** Used to match empty string literals in compiled template source. */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
Update lodash-amd to v4.17.21 + edadd45 (#6064) * Fix prototype pollution in _.set and related functions Prevents setting dangerous properties (__proto__, constructor, prototype) that could lead to prototype pollution vulnerabilities. * Fix command injection vulnerability in _.template - Add validation for the variable option to prevent injection attacks - Improve sourceURL whitespace normalization to prevent code injection * Fix cyclic value comparison in _.isEqual Properly checks both directions when comparing cyclic values to ensure correct equality comparisons for circular references. * Improve _.sortBy and _.orderBy performance and array handling - Add early return for empty arrays in sorted index operations - Improve array iteratee handling to support nested property paths - Add missing keysIn import in baseClone * Refactor _.trim, _.trimEnd, and _.trimStart implementations Extract shared trim logic into reusable utilities (_baseTrim, _trimmedEndIndex) for better code organization and consistency. Update related functions (toNumber, parseInt) to use new utilities. Improve comment accuracy. * Add documentation for predicate composition with _.overEvery and _.overSome Enhance documentation to show how _.matches and _.matchesProperty can be combined using _.overEvery and _.overSome for more powerful filtering. Add examples demonstrating shorthand predicate syntax. * Bump to v4.17.21 * Fix prototype pollution in _.unset and _.omit Prevent prototype pollution on baseUnset function by: - Blocking "__proto__" if not an own property - Blocking "constructor.prototype" chains (except when starting at primitive root) - Skipping non-string keys See: https://github.com/lodash/lodash/security/advisories/GHSA-xxjr-mmjv-4gpg * Update JSDoc documentation to align with main branch - Fix sortBy example ages (40 -> 30) for correct sort order demonstration - Fix _setCacheHas return type (number -> boolean)
2025-12-10 17:03:07 -05:00
/**
* Used to validate the `validate` option in `_.template` variable.
*
* Forbids characters which could potentially change the meaning of the function argument definition:
* - "()," (modification of function parameters)
* - "=" (default value)
* - "[]{}" (destructuring of function parameters)
* - "/" (beginning of a comment)
* - whitespace
*/
var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/;
2016-04-01 23:28:48 -07:00
/**
* Used to match
2016-08-07 21:21:03 -07:00
* [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
2016-04-01 23:28:48 -07:00
*/
2015-01-08 00:37:01 -08:00
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
/** Used to ensure capturing order of template delimiters. */
var reNoMatch = /($^)/;
/** Used to match unescaped characters in compiled string literals. */
var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
2019-07-09 13:47:57 -07:00
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
2015-01-08 00:37:01 -08:00
/**
* Creates a compiled template function that can interpolate data properties
* in "interpolate" delimiters, HTML-escape interpolated data properties in
* "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
* properties may be accessed as free variables in the template. If a setting
2016-04-07 21:35:23 -07:00
* object is given, it takes precedence over `_.templateSettings` values.
2015-01-08 00:37:01 -08:00
*
2015-12-16 17:49:07 -08:00
* **Note:** In the development build `_.template` utilizes
* [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
* for easier debugging.
2015-01-08 00:37:01 -08:00
*
* For more information on precompiling templates see
* [lodash's custom builds documentation](https://lodash.com/custom-builds).
*
* For more information on Chrome extension sandboxes see
* [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
*
* @static
2016-03-26 00:00:01 -07:00
* @since 0.1.0
2015-01-08 00:37:01 -08:00
* @memberOf _
* @category String
* @param {string} [string=''] The template string.
2016-03-26 00:00:01 -07:00
* @param {Object} [options={}] The options object.
* @param {RegExp} [options.escape=_.templateSettings.escape]
* The HTML "escape" delimiter.
* @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
* The "evaluate" delimiter.
* @param {Object} [options.imports=_.templateSettings.imports]
* An object to import into the template as free variables.
* @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
* The "interpolate" delimiter.
* @param {string} [options.sourceURL='templateSources[n]']
* The sourceURL of the compiled template.
* @param {string} [options.variable='obj']
* The data object variable name.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
2015-01-08 00:37:01 -08:00
* @returns {Function} Returns the compiled template function.
* @example
*
2016-02-01 23:13:04 -08:00
* // Use the "interpolate" delimiter to create a compiled template.
2015-01-08 00:37:01 -08:00
* var compiled = _.template('hello <%= user %>!');
* compiled({ 'user': 'fred' });
* // => 'hello fred!'
*
2016-02-01 23:13:04 -08:00
* // Use the HTML "escape" delimiter to escape data property values.
2015-01-08 00:37:01 -08:00
* var compiled = _.template('<b><%- value %></b>');
* compiled({ 'value': '<script>' });
* // => '<b>&lt;script&gt;</b>'
*
2016-02-01 23:13:04 -08:00
* // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
2015-01-08 00:37:01 -08:00
* var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
2016-02-01 23:13:04 -08:00
* // Use the internal `print` function in "evaluate" delimiters.
2015-01-08 00:37:01 -08:00
* var compiled = _.template('<% print("hello " + user); %>!');
* compiled({ 'user': 'barney' });
* // => 'hello barney!'
*
2016-09-17 22:24:52 -07:00
* // Use the ES template literal delimiter as an "interpolate" delimiter.
* // Disable support by replacing the "interpolate" delimiter.
2015-01-08 00:37:01 -08:00
* var compiled = _.template('hello ${ user }!');
* compiled({ 'user': 'pebbles' });
* // => 'hello pebbles!'
*
2016-02-01 23:13:04 -08:00
* // Use backslashes to treat delimiters as plain text.
2015-01-08 00:37:01 -08:00
* var compiled = _.template('<%= "\\<%- value %\\>" %>');
* compiled({ 'value': 'ignored' });
* // => '<%- value %>'
*
2016-02-01 23:13:04 -08:00
* // Use the `imports` option to import `jQuery` as `jq`.
2015-01-08 00:37:01 -08:00
* var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
* var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
2016-02-01 23:13:04 -08:00
* // Use the `sourceURL` option to specify a custom sourceURL for the template.
2015-01-08 00:37:01 -08:00
* var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
* compiled(data);
2016-03-26 00:00:01 -07:00
* // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
2015-01-08 00:37:01 -08:00
*
2016-02-01 23:13:04 -08:00
* // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
2015-01-08 00:37:01 -08:00
* var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
* compiled.source;
* // => function(data) {
2015-12-16 17:47:30 -08:00
* // var __t, __p = '';
* // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
* // return __p;
* // }
2015-01-08 00:37:01 -08:00
*
2016-05-07 11:49:46 -07:00
* // Use custom template delimiters.
* _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
* var compiled = _.template('hello {{ user }}!');
* compiled({ 'user': 'mustache' });
* // => 'hello mustache!'
*
2016-02-01 23:13:04 -08:00
* // Use the `source` property to inline compiled templates for meaningful
* // line numbers in error messages and stack traces.
2016-05-07 11:49:46 -07:00
* fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
2015-01-08 00:37:01 -08:00
* var JST = {\
* "main": ' + _.template(mainText).source + '\
* };\
* ');
*/
2015-12-16 17:53:20 -08:00
function template(string, options, guard) {
2016-03-26 00:00:01 -07:00
// Based on John Resig's `tmpl` implementation
// (http://ejohn.org/blog/javascript-micro-templating/)
2015-01-08 00:37:01 -08:00
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
var settings = templateSettings.imports._.templateSettings || templateSettings;
2015-12-16 17:53:20 -08:00
if (guard && isIterateeCall(string, options, guard)) {
options = undefined;
2015-01-08 00:37:01 -08:00
}
2015-12-16 17:53:20 -08:00
string = toString(string);
2016-12-19 17:17:56 -06:00
options = assignInWith({}, options, settings, customDefaultsAssignIn);
2015-01-08 00:37:01 -08:00
2016-12-19 17:17:56 -06:00
var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
2015-01-08 00:37:01 -08:00
importsKeys = keys(imports),
importsValues = baseValues(imports, importsKeys);
var isEscaping,
isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// Compile the regexp to match each delimiter.
var reDelimiters = RegExp(
(options.escape || reNoMatch).source + '|' +
interpolate.source + '|' +
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
(options.evaluate || reNoMatch).source + '|$'
, 'g');
// Use a sourceURL for easier debugging.
2019-07-09 13:47:57 -07:00
// The sourceURL gets injected into the source that's eval-ed, so be careful
Update lodash-amd to v4.17.21 + edadd45 (#6064) * Fix prototype pollution in _.set and related functions Prevents setting dangerous properties (__proto__, constructor, prototype) that could lead to prototype pollution vulnerabilities. * Fix command injection vulnerability in _.template - Add validation for the variable option to prevent injection attacks - Improve sourceURL whitespace normalization to prevent code injection * Fix cyclic value comparison in _.isEqual Properly checks both directions when comparing cyclic values to ensure correct equality comparisons for circular references. * Improve _.sortBy and _.orderBy performance and array handling - Add early return for empty arrays in sorted index operations - Improve array iteratee handling to support nested property paths - Add missing keysIn import in baseClone * Refactor _.trim, _.trimEnd, and _.trimStart implementations Extract shared trim logic into reusable utilities (_baseTrim, _trimmedEndIndex) for better code organization and consistency. Update related functions (toNumber, parseInt) to use new utilities. Improve comment accuracy. * Add documentation for predicate composition with _.overEvery and _.overSome Enhance documentation to show how _.matches and _.matchesProperty can be combined using _.overEvery and _.overSome for more powerful filtering. Add examples demonstrating shorthand predicate syntax. * Bump to v4.17.21 * Fix prototype pollution in _.unset and _.omit Prevent prototype pollution on baseUnset function by: - Blocking "__proto__" if not an own property - Blocking "constructor.prototype" chains (except when starting at primitive root) - Skipping non-string keys See: https://github.com/lodash/lodash/security/advisories/GHSA-xxjr-mmjv-4gpg * Update JSDoc documentation to align with main branch - Fix sortBy example ages (40 -> 30) for correct sort order demonstration - Fix _setCacheHas return type (number -> boolean)
2025-12-10 17:03:07 -05:00
// to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in
// and escape the comment, thus injecting code that gets evaled.
2019-07-09 13:47:57 -07:00
var sourceURL = hasOwnProperty.call(options, 'sourceURL')
? ('//# sourceURL=' +
Update lodash-amd to v4.17.21 + edadd45 (#6064) * Fix prototype pollution in _.set and related functions Prevents setting dangerous properties (__proto__, constructor, prototype) that could lead to prototype pollution vulnerabilities. * Fix command injection vulnerability in _.template - Add validation for the variable option to prevent injection attacks - Improve sourceURL whitespace normalization to prevent code injection * Fix cyclic value comparison in _.isEqual Properly checks both directions when comparing cyclic values to ensure correct equality comparisons for circular references. * Improve _.sortBy and _.orderBy performance and array handling - Add early return for empty arrays in sorted index operations - Improve array iteratee handling to support nested property paths - Add missing keysIn import in baseClone * Refactor _.trim, _.trimEnd, and _.trimStart implementations Extract shared trim logic into reusable utilities (_baseTrim, _trimmedEndIndex) for better code organization and consistency. Update related functions (toNumber, parseInt) to use new utilities. Improve comment accuracy. * Add documentation for predicate composition with _.overEvery and _.overSome Enhance documentation to show how _.matches and _.matchesProperty can be combined using _.overEvery and _.overSome for more powerful filtering. Add examples demonstrating shorthand predicate syntax. * Bump to v4.17.21 * Fix prototype pollution in _.unset and _.omit Prevent prototype pollution on baseUnset function by: - Blocking "__proto__" if not an own property - Blocking "constructor.prototype" chains (except when starting at primitive root) - Skipping non-string keys See: https://github.com/lodash/lodash/security/advisories/GHSA-xxjr-mmjv-4gpg * Update JSDoc documentation to align with main branch - Fix sortBy example ages (40 -> 30) for correct sort order demonstration - Fix _setCacheHas return type (number -> boolean)
2025-12-10 17:03:07 -05:00
(options.sourceURL + '').replace(/\s/g, ' ') +
2019-07-09 13:47:57 -07:00
'\n')
: '';
2015-01-08 00:37:01 -08:00
string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// Escape characters that can't be included in string literals.
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// Replace delimiters with snippets.
if (escapeValue) {
isEscaping = true;
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
2015-12-16 17:53:20 -08:00
// The JS engine embedded in Adobe products needs `match` returned in
// order to produce the correct `offset` value.
2015-01-08 00:37:01 -08:00
return match;
});
source += "';\n";
// If `variable` is not specified wrap a with-statement around the generated
// code to add the data object to the top of the scope chain.
2019-07-09 13:47:57 -07:00
var variable = hasOwnProperty.call(options, 'variable') && options.variable;
2015-01-08 00:37:01 -08:00
if (!variable) {
source = 'with (obj) {\n' + source + '\n}\n';
}
Update lodash-amd to v4.17.21 + edadd45 (#6064) * Fix prototype pollution in _.set and related functions Prevents setting dangerous properties (__proto__, constructor, prototype) that could lead to prototype pollution vulnerabilities. * Fix command injection vulnerability in _.template - Add validation for the variable option to prevent injection attacks - Improve sourceURL whitespace normalization to prevent code injection * Fix cyclic value comparison in _.isEqual Properly checks both directions when comparing cyclic values to ensure correct equality comparisons for circular references. * Improve _.sortBy and _.orderBy performance and array handling - Add early return for empty arrays in sorted index operations - Improve array iteratee handling to support nested property paths - Add missing keysIn import in baseClone * Refactor _.trim, _.trimEnd, and _.trimStart implementations Extract shared trim logic into reusable utilities (_baseTrim, _trimmedEndIndex) for better code organization and consistency. Update related functions (toNumber, parseInt) to use new utilities. Improve comment accuracy. * Add documentation for predicate composition with _.overEvery and _.overSome Enhance documentation to show how _.matches and _.matchesProperty can be combined using _.overEvery and _.overSome for more powerful filtering. Add examples demonstrating shorthand predicate syntax. * Bump to v4.17.21 * Fix prototype pollution in _.unset and _.omit Prevent prototype pollution on baseUnset function by: - Blocking "__proto__" if not an own property - Blocking "constructor.prototype" chains (except when starting at primitive root) - Skipping non-string keys See: https://github.com/lodash/lodash/security/advisories/GHSA-xxjr-mmjv-4gpg * Update JSDoc documentation to align with main branch - Fix sortBy example ages (40 -> 30) for correct sort order demonstration - Fix _setCacheHas return type (number -> boolean)
2025-12-10 17:03:07 -05:00
// Throw an error if a forbidden character was found in `variable`, to prevent
// potential command injection attacks.
else if (reForbiddenIdentifierChars.test(variable)) {
throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT);
}
2015-01-08 00:37:01 -08:00
// Cleanup code by stripping empty strings.
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// Frame code as the function body.
source = 'function(' + (variable || 'obj') + ') {\n' +
(variable
? ''
: 'obj || (obj = {});\n'
) +
"var __t, __p = ''" +
(isEscaping
? ', __e = _.escape'
: ''
) +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
"function print() { __p += __j.call(arguments, '') }\n"
: ';\n'
) +
source +
'return __p\n}';
var result = attempt(function() {
2016-02-15 20:20:54 -08:00
return Function(importsKeys, sourceURL + 'return ' + source)
.apply(undefined, importsValues);
2015-01-08 00:37:01 -08:00
});
// Provide the compiled function's source by its `toString` method or
// the `source` property as a convenience for inlining compiled templates.
result.source = source;
if (isError(result)) {
throw result;
}
return result;
}
return template;
});