Based on handy compile function in https://github.com/gruntjs/grunt-contrib-compass/blob/master/tasks/compass.js#
348776
function(args, options, cb) {

                args = !_.isArray(args) ? [args] : args;
                args = options && args.concat(helper.optsToArgs(options)) || args;

                var child = grunt.util.spawn({
                    cmd:"node",
                    args:args
                }, function (error, result, code) {
                    cb(error);
                });

                child.stdout.pipe(process.stdout);
                child.stderr.pipe(process.stderr);

            }
1337399
function compile() {
        debug('read %s', cssPath);
        fs.readFile(stylusPath, 'utf8', function(err, str){
          if (err) return error(err);
          var style = options.compile(str, stylusPath);
          var paths = style.options._imports = [];
          imports[stylusPath] = null;
          style.render(function(err, css){
            if (err) return next(err);
            debug('render %s', stylusPath);
            imports[stylusPath] = paths;
            mkdir(dirname(cssPath), { mode: parseInt('0700', 8), recursive: true }, function(err){
              if (err) return error(err);
              fs.writeFile(cssPath, css, 'utf8', next);
            });
          });
        });
      }
125055
function compile(src) {
   var cached;

   if (typeof src !== "string") {
      throw new TypeError("src must be a string, instead saw '" + typeof src + "'");
   }

   if (!compile.cache) {
      return parser.parse(src);
   }

   cached = compile.cache[src];

   if (!cached) {
      cached = compile.cache[src] = parser.parse(src);
   }

   return cached;
}
383253
function ( taskName ) {
			var task = grunt.config.get( "bundles" )[taskName];

			var retVal = {};
			if ( task && task.aliases ) {
				var aliases = task.aliases;
				if ( !sys.isEmpty( aliases ) ) {
					grunt.verbose.writeln( "Adding aliases for " + taskName );
					if ( sys.isArray( aliases ) ) {
						sys.each( aliases, function ( map ) {
							map = map || {};

							if ( !sys.isString( map.dest ) ) {map.dest = map.cwd;}
							if ( !sys.isString( map.dest ) ) {return grunt.util.error( "dest or cwd is required" );}

							map.cwd = map.cwd || "";
							map.expand = map.expand !== false;
							var files = grunt.file.expand( map, map.src );
							sys.each( files, function ( item ) {
								var thisPath;
								if ( sys.isEmpty( map.dest ) ) {
									thisPath = item;
								} else {
									thisPath = path.join( map.dest, item );
								}

								var thisAlias = thisPath.replace( /\.[^/.]+$/, "" ).replace( /\\/g, "/" );

								retVal[thisAlias] = resolvePath( path.join( map.cwd, item ) );

							} );
						} );
					} else {
						sys.each( aliases, function ( item, key ) {
							retVal[key] = resolvePath( item );
						} );

					}
				}
			}
			return retVal;
		}
442658
function finalizeCompile() {
  if (fs.existsSync(path.join(__dirname, './lib'))) {
    // Build package.json version to lib/version/index.js
    // prevent json-loader needing in user-side
    const versionFilePath = path.join(process.cwd(), 'lib', 'version', 'index.js');
    const versionFileContent = fs.readFileSync(versionFilePath).toString();
    fs.writeFileSync(
      versionFilePath,
      versionFileContent.replace(
        /require\(('|")\.\.\/\.\.\/package\.json('|")\)/,
        `{ version: '${packageInfo.version}' }`,
      ),
    );
    // eslint-disable-next-line
    console.log('Wrote version into lib/version/index.js');

    // Build package.json version to lib/version/index.d.ts
    // prevent https://github.com/ant-design/ant-design/issues/4935
    const versionDefPath = path.join(process.cwd(), 'lib', 'version', 'index.d.ts');
    fs.writeFileSync(
      versionDefPath,
      `declare var _default: "${packageInfo.version}";\nexport default _default;\n`,
    );
    // eslint-disable-next-line
    console.log('Wrote version into lib/version/index.d.ts');

    // Build a entry less file to dist/antd.less
    const componentsPath = path.join(process.cwd(), 'components');
    let componentsLessContent = '';
    // Build components in one file: lib/style/components.less
    fs.readdir(componentsPath, (err, files) => {
      files.forEach(file => {
        if (fs.existsSync(path.join(componentsPath, file, 'style', 'index.less'))) {
          componentsLessContent += `@import "../${path.join(file, 'style', 'index.less')}";\n`;
        }
      });
      fs.writeFileSync(
        path.join(process.cwd(), 'lib', 'style', 'components.less'),
        componentsLessContent,
      );
    });
  }
}
414213
function(deps) {

    deps = deps || {};

    var grunt = dependency(deps, 'grunt');
    var task = dependency(deps, 'task');
    var done = task.async();

    task.files.forEach(function(subTask) {

      // make sure an editing function has been provided

      if (typeof subTask.editor !== 'function') {
        return grunt.fatal(task.current.nameArgs + ' needs a ".editor" method');
      }

      // replace contents of each file with the return value
      // of the editor when given the file's contents and path.

      subTask.src.forEach(function(filePath) {

        if (!grunt.file.isFile(filePath)) {
          return grunt.log.write('skipped "' + filePath + '" as is not a file');
        }

        var original = grunt.file.read(filePath);
        var rewritten = subTask.editor(original, filePath);

        if (typeof rewritten === 'undefined') {
          return grunt.fatal(task.current.nameArgs + ' ".editor" method did not return a value');
        }

        grunt.file.write(filePath, rewritten);

      });

    });

    done();

  }
126053
def compile_command(context, backend, config):
    
    logger = logging.getLogger("boussole")
    logger.info(u"Building project")

    # Discover settings file
    try:
        discovering = Discover(backends=[SettingsBackendJson,
                                         SettingsBackendYaml])
        config_filepath, config_engine = discovering.search(
            filepath=config,
            basedir=os.getcwd(),
            kind=backend
        )

        project = ProjectBase(backend_name=config_engine._kind_name)
        settings = project.backend_engine.load(filepath=config_filepath)
    except BoussoleBaseException as e:
        logger.critical(six.text_type(e))
        raise click.Abort()

    logger.debug(u"Settings file: {} ({})".format(
                 config_filepath, config_engine._kind_name))
    logger.debug(u"Project sources directory: {}".format(
                 settings.SOURCES_PATH))
    logger.debug(u"Project destination directory: {}".format(
                 settings.TARGET_PATH))
    logger.debug(u"Exclude patterns: {}".format(
                 settings.EXCLUDES))

    # Find all sources with their destination path
    try:
        compilable_files = ScssFinder().mirror_sources(
            settings.SOURCES_PATH,
            targetdir=settings.TARGET_PATH,
            excludes=settings.EXCLUDES
        )
    except BoussoleBaseException as e:
        logger.error(six.text_type(e))
        raise click.Abort()

    # Build all compilable stylesheets
    compiler = SassCompileHelper()
    errors = 0
    for src, dst in compilable_files:
        logger.debug(u"Compile: {}".format(src))

        output_opts = {}
        success, message = compiler.safe_compile(settings, src, dst)

        if success:
            logger.info(u"Output: {}".format(message), **output_opts)
        else:
            errors += 1
            logger.error(message)

    # Ensure correct exit code if error has occured
    if errors:
        raise click.Abort()
338849
function generateFunctionsFiles ({ suffix, factories, entryFolder }) {
  const braceOpen = '{' // a hack to be able to create a single brace open character in handlebars

  const sortedFactories = sortFactories(values(factories))

  // sort the factories, and split them in three groups:
  // - transform: the transform functions
  // - impure: the functions that depend on `math` or `mathWithTransform` (directly or indirectly),
  // - pure: the rest
  const pureFactories = []
  const impureFactories = []
  const transformFactories = []
  sortedFactories
    .filter(factory => !DEPRECATED_FACTORIES[factory.fn])
    .forEach(factory => {
      if (isTransform(factory)) {
        transformFactories.push(factory)
      } else if (
        contains(factory.dependencies, 'math') ||
        contains(factory.dependencies, 'mathWithTransform') ||
        contains(factory.dependencies, 'classes') ||
        isTransform(factory) ||
        factory.dependencies.some(dependency => {
          return impureFactories.find(f => f.fn === stripOptionalNotation(dependency))
        })
      ) {
        impureFactories.push(factory)
      } else {
        pureFactories.push(factory)
      }
    })

  // a map containing:
  // {
  //   'sqrt': true,
  //   'subset': true,
  //   ...
  // }
  const pureExists = {
    config: true
  }
  pureFactories.forEach(factory => {
    pureExists[factory.fn] = true
  })

  const impureExists = {
    ...pureExists
  }
  impureFactories.forEach(factory => {
    impureExists[factory.fn] = true
  })

  const math = sortedFactories
    .filter(factory => !isClass(factory))
    .filter(factory => !isTransform(factory))
    .map(factory => {
      return {
        name: factory.fn,
        renamed: DEPRECATED_FACTORIES[factory.fn],
        mappedName: FACTORY_NAMES_ES6_MAPPING[factory.fn]
      }
    })

  const classes = sortedFactories
    .filter(factory => isClass(factory))
    .map(factory => ({ name: factory.fn }))

  const data = {
    suffix,
    pureFactories: pureFactories.map(factory => {
      const name = FACTORY_NAMES_ES6_MAPPING[factory.fn] || factory.fn

      return {
        braceOpen,
        factoryName: findKey(factories, factory), // TODO: find a better way to match the factory names
        eslintComment: name === 'SQRT1_2'
          ? ' // eslint-disable-line camelcase'
          : undefined,
        name,
        dependencies: factory.dependencies
          .map(stripOptionalNotation)
          .filter(dependency => !IGNORED_DEPENDENCIES_ES6[dependency])
          .filter(dependency => {
            // TODO: this code is duplicated. extract it in a separate function
            if (!pureExists[dependency]) {
              if (factory.dependencies.indexOf(dependency) !== -1) {
                throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}"`)
              }

              return false
            }

            return true
          })
          .map(dependency => ({ name: dependency }))
      }
    }),

    impureFactories: impureFactories.map(factory => {
      const name = FACTORY_NAMES_ES6_MAPPING[factory.fn] || factory.fn

      return {
        braceOpen,
        factoryName: findKey(factories, factory), // TODO: find a better way to match the factory names
        eslintComment: name === 'SQRT1_2'
          ? ' // eslint-disable-line camelcase'
          : undefined,
        name,
        dependencies: factory.dependencies
          .map(stripOptionalNotation)
          .filter(dependency => !IGNORED_DEPENDENCIES_ES6[dependency])
          .filter(dependency => {
            if (dependency === 'math' || dependency === 'mathWithTransform' || dependency === 'classes') {
              return true
            }

            // TODO: this code is duplicated. extract it in a separate function
            if (!impureExists[dependency]) {
              // if (factory.dependencies.indexOf(dependency) !== -1) {
              //   throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}"`)
              // }

              return false
            }

            return true
          })
          .map(dependency => ({ name: dependency }))
      }
    }),

    transformFactories: transformFactories.map(factory => {
      const name = FACTORY_NAMES_ES6_MAPPING[factory.fn] || factory.fn

      return {
        braceOpen,
        factoryName: findKey(factories, factory), // TODO: find a better way to match the factory names
        eslintComment: name === 'SQRT1_2'
          ? ' // eslint-disable-line camelcase'
          : undefined,
        name,
        dependencies: factory.dependencies
          .map(stripOptionalNotation)
          .filter(dependency => !IGNORED_DEPENDENCIES_ES6[dependency])
          .filter(dependency => {
            if (dependency === 'math' || dependency === 'mathWithTransform' || dependency === 'classes') {
              return true
            }

            // TODO: this code is duplicated. extract it in a separate function
            if (!impureExists[dependency]) {
              // if (factory.dependencies.indexOf(dependency) !== -1) {
              //   throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}"`)
              // }

              return false
            }

            return true
          })
          .map(dependency => ({ name: dependency }))
      }
    }),

    math,
    classes
  }

  // create file with all functions: functionsAny.generated.js, functionsNumber.generated.js
  fs.writeFileSync(path.join(entryFolder, 'pureFunctions' + suffix + '.generated.js'), pureFunctionsTemplate(data))

  // create file with all functions: impureFunctions.generated.js, impureFunctions.generated.js
  fs.writeFileSync(path.join(entryFolder, 'impureFunctions' + suffix + '.generated.js'), impureFunctionsTemplate(data))
}
305681
function buildJs() {
	// Construct a stream for the JS sources of our plugin, don't read file contents when compiling TypeScript.
	var sourceStream = gulp.src( config.Sources.Scripts, {
		cwd  : config.WorkingDirectory,
		read : true
	} );

	return sourceStream
		.pipe( jscs() )
		.pipe( jscs.reporter() )
		.pipe( jsValidate() )
		.pipe( order() )
		// Only pass through files that have changed since the last build iteration (relevant during "watch").
		.pipe( cached( path.join( config.Output.Production, config.Output.DirectoryNames.Scripts ) ) )
		// Generate sourcemaps
		.pipe( sourcemaps.init() )
		.pipe( wrapper( {
			header : "(function() {\n\"use strict\";\n",
			footer : "}());"
		} ) )
		.pipe( jsValidate() )
		.pipe( jshint() )
		.pipe( jshint.reporter( stylish ) )
		// Put Angular dependency injection annotation where needed.
		.pipe( ngAnnotate() )
		// Pull out files which haven't changed since our last build iteration and put them back into the stream.
		.pipe( remember() )
		// Place the results in the development output directory.
		.pipe( gulp.dest( path.join( config.Output.Development, config.Output.DirectoryNames.Scripts ) ) )
		// Concatenate all files into a single one.
		.pipe( concat( slug( application.name ) + ".concat.js", {
			newLine : ";"
		} ) )
		// Put that file into the development output as well.
		.pipe( gulp.dest( path.join( config.Output.Development, config.Output.DirectoryNames.Scripts ) ) )
		// Minify the file.
		.pipe( uglify() )
		// Rename it to indicate minification.
		.pipe( rename( {
			extname : ".min.js"
		} ) )
		// Write out sourcemaps
		.pipe( sourcemaps.write( "maps" ) )
		// Write the file to the production output directory.
		.pipe( gulp.dest( path.join( config.Output.Production, config.Output.DirectoryNames.Scripts ) ) );
}
860891
function(files, callback) {
            if (files.dest) {
                options['output'] = files.dest;
            }

			var commandLine = compcOptions.toCommandLine(options);

            if (files.src && files.src.length > 0) {                
                commandLine.push('-include-sources');
                commandLine.push.apply(commandLine, files.src);
                commandLine.push('--');
            }
            
			grunt.verbose.writeln('compc path: ' + binary);
			grunt.verbose.writeln('options: ' + commandLine);
		
			childProcess.execFile(binary, commandLine, function(error, stdout, stderr) {
                grunt.verbose.writeln('output: ' + stdout);
                
				if (error) {
					grunt.log.error(error.toString());
                    
                    if (options.force !== true) {
                        grunt.fail.warn('Compc task has failed.');
                    }                    
				}
                else if (files.dest) {
                    grunt.log.writeln('Build complete: ' + files.dest);
                }
                
                callback(error);
			});
		}
1361302
function compile() {
    swig.log.info('', 'Compiling module list...');

    const modulesPath = path.join(swig.temp, '/**/node_modules/@gilt-tech');
    const modPaths = glob.sync(modulesPath);
    let dirs;

    swig.log.verbose(`[compile] searching: ${modulesPath}`);
    swig.log.verbose(`[compile] found module directories: ${modPaths.length}`);

    modPaths.forEach((modPath) => {
      swig.log.verbose(`[compile] compiling: ${modPath}`);

      dirs = fs.readdirSync(modPath);

      _.each(dirs, (dir) => {
        const dirPath = path.join(modPath, dir);
        if (fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory()) {
          azModules.push({ name: dir, path: dirPath });
        }
      });
    });

    // group by basename, and take the 'topmost' module in the hierarchy
    azModules = _.groupBy(azModules, module => path.basename(module.path));

    // pull out the 'winning' module path, for each module
    azModules = _.map(azModules, (modulesList) => {
      // the modules arg will be [{ name:, path: }, ...]

      if (modulesList.length === 1) {
        return modulesList[0];
      }

      // glob will almost always return the right order,
      // but let's assert this to be safe. we can spare the cycles.
      return _.sortBy(modulesList, module => module.path.length)[0];
    });

    // and now we pretty sort a-z for various output
    // we dont reset azModules to the sorted array because we need it dirty for deps.less
    _.sortBy(azModules, mod => mod.name).forEach((mod) => {
      modules[mod.name] = mod.path;
    });

    swig.log.verbose('[compile] sorted modules: ');
    swig.log.verbose(modules);
  }
1322602
function FunctionCompiler() {
    var _this;

    _classCallCheck(this, FunctionCompiler);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(FunctionCompiler).call(this));
    /**
     * Compile sequence.
     * @type {Array<function>}
     */

    _this._sequence = [_this._uncomment, _this._validate, _this._extract, _this._direct, _this._compile, _this._definehead, _this._injecthead, _this._macromize];
    /**
     * Options from Grunt.
     * @type {Map}
     */

    _this._options = null;
    /**
     * Hm.
     */

    _this._macros = null;
    /**
     * Mapping script tag attributes.
     * This may be put to future use.
     * @type {Map<string,string>}
     */

    _this._directives = null;
    /**
     * Processing intstructions.
     * @type {Array<Instruction>}
     */

    _this._instructions = null;
    /**
     * Compiled arguments list.
     * @type {Array<string>}
     */

    _this._params = null;
    /**
     * Tracking imported functions.
     * @type {Map<string,string>}
     */

    _this._functions = {};
    /**
     * Did compilation fail just yet?
     * @type {boolean}
     */

    _this._failed = false;
    return _this;
  }
700093
function compile(srcPath, outPath) {
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

  if (options.debug) {
    console.log('\nBegin compile...', srcPath, outPath, options);
  }

  var files = getFiles(srcPath, true);

  var changedFiles = [];

  if (options.debug) {
    console.log('all files:', files);
  }

  files.forEach(function (file) {
    var srcFullPath = path.join(srcPath, file);
    var saveOutFullPathpath = path.join(outPath, file);
    var extname = path.extname(file);

    if (options.debug) {
      console.log('[' + extname + '] ' + srcFullPath + ' => ' + saveOutFullPathpath);
    }

    //if is not js file, only copy
    if (allowFileExt.indexOf(extname) === -1) {
      compileFile(srcFullPath, saveOutFullPathpath, true, options);
      return;
    }

    var mTime = fs.statSync(srcFullPath).mtime.getTime();

    if (fileUtil.isFile(saveOutFullPathpath)) {
      var outmTime = fs.statSync(saveOutFullPathpath).mtime.getTime();

      // if compiled file mtime is later than source file,
      // it means source file not modified, so there is no necessary to compile.
      if (outmTime >= mTime) {
        return;
      }
    }

    if (!compiledMtime[file] || mTime > compiledMtime[file]) {
      var ret = compileFile(srcFullPath, saveOutFullPathpath, false, options);

      if (ret) {
        changedFiles.push(saveOutFullPathpath);
      }

      compiledMtime[file] = mTime;

      var index = compiledErrorFiles.indexOf(file);

      if (ret) {
        if (index > -1) {
          compiledErrorFiles.splice(index, 1);
        }
      } else if (ret === false) {
        if (index === -1) {
          compiledErrorFiles.push(file);
        }
      }
    }
  });

  // console.error(compiledErrorFiles)
}
885408
function gruntYakTask(grunt) {
    'use strict';

    /**
     * @type {!Array<string>}
     */
    let filesToUpload = [];

    /**
     * @type {RequestSender}
     */
    let requestSender;

    /**
     * Register task for grunt.
     */
    grunt.registerMultiTask('yakjs', 'A grunt task to update the YAKjs via rest API.', function task() {
        /**
         * This tasks sends several http request asynchronous.
         * So let's get the done callback from the task runner.
         */
        let done = this.async();

        /**
         * @type {!TaskOptions}
         */
        let options = this.options(new TaskOptions());

        filesToUpload = [];

        this.files.forEach(file => {
            filesToUpload = filesToUpload.concat(file.src);
        });

        let logger = {
            log: grunt.log.writeln,
            error: grunt.log.error
        };

        uploadFiles(filesToUpload, options, logger)
            .then(() => {
                grunt.log.writeln('');
                grunt.log.ok('All files uploaded.');
            })
            .then(() => {
                return clearModuleCache(options, logger);
            })
            .then(() => {
                return startInstances(options, logger);
            })
            .then(done)
            .catch((message, error) => {
                grunt.log.writeln('');
                grunt.log.error(JSON.stringify(message, null, 4));
                grunt.fatal('One or more files could not be uploaded.');
                done();
            });
    });
}
299051
function(tasksConfig) {
  /* JS linting  */
  gulp.task('lint', extendDeps([], tasksConfig.lint), function() {
    return gulp.src(extendSrcs([
      paths.src.js,
      paths.src.es6
    ], tasksConfig.lint))
    .pipe($.jshint({
      lookup: true
    }))
    .pipe($.jshint.reporter('jshint-stylish'));
  });
  gulp.task('lint:blocker', extendDeps([], tasksConfig.lint), function() {
    return gulp.src(extendSrcs([
      paths.src.js,
      paths.src.es6
    ], tasksConfig.lint))
    .pipe($.jshint({
      lookup: true
    }))
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jshint.reporter('fail'));
  });

  /* JS validation  */
  gulp.task('jsvalidate:blocker', ['babelify'], function () {
    return gulp.src(extendSrcs([
      paths.src.tmp + '**/*.js',
      paths.src.tmp + '**/*' + paths.src.esnextExt,
      '!' + paths.src.tmp + '**/*.test.js',
      '!' + paths.src.tmp + '**/*.test' + paths.src.esnextExt
    ], tasksConfig.lint))
    .pipe($.jsvalidate());
  });
  gulp.task('jsvalidate:blocker:clean', ['jsvalidate:blocker'], cleanTmp);

  /* JS unit tests runner  */
  gulp.task('karma', function() {
    return gulp.src([
      'tricky/freaky/trick/**/*.js'
    ])
    .pipe($.karma({
      configFile: 'karma.conf.js',
      action: 'run'
    }))
    .on('error', function(/*err*/) {
      // throw err;
    });
  });
  gulp.task('karma:dev', function() {
    return gulp.src([
      'tricky/freaky/trick/**/*.js'
    ])
    .pipe($.karma({
      configFile: 'karma.conf.js',
      action: 'watch'
    }))
    .on('error', function(/*err*/) {
      // throw err;
    });
  });
}
467446
function taskFontmin() {
    // prase options
    let opts    = this.options()
    let data    = this.data
    let destdir = opts.dest    || './'
    let basedir = opts.basedir || './'
    let src     = grunt.file.expand(data.src)
    let fonts   = grunt.file.expand(join(basedir, this.target))
    let getText = opts.getText!==undefined ? opts.getText : (content)=>html2text.fromString(content)
    let type='woff', typeOpts=true

    // check if more than one output option is specified
    if ( !atMostDefined(data, 1, 'woff', 'css') )
        throw new Error('Multiple output type defined!')

    // set type, typeOpts
    if (data.woff!==undefined) { type='woff' }
    if (data.css!==undefined)  { type='css'; typeOpts=data.css }

    // string of unique characters(glyphs) to be included in minimized font
    let uniqGlyphs =
        src.map( path => grunt.file.read(path) )
           .map( getText )
           .join()
           .split('')
           .sort().reduce( nodup(), [] )   // remove duplicate characters
           .join('')


    fonts.forEach( path => {
        // create output ArrayBuffer
        let ttf = readToTTF(path)
        let stripped = glyphStrip(ttf, uniqGlyphs)
        let output = ttfToOutput(stripped, type, typeOpts)

        // solve dest path, write output
        let destPath = join(destdir, getOutputFilename(path,type))
        grunt.file.write(destPath, toBuffer(output))

        // output information
        grunt.log.writeln(basename(path)+' => '+type+' '
            +chalk.green(stripped.glyf.length)+' glyphs, '
            +chalk.green(output.byteLength)+' bytes')
    } )

}
1101670
function compile (format) {
  if (typeof format !== 'string') {
    throw new TypeError('argument format must be a string')
  }

  var fmt = String(JSON.stringify(format))
  var js = '  "use strict"\n  return ' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function (_, name, arg) {
    var tokenArguments = 'req, res'
    var tokenFunction = 'tokens[' + String(JSON.stringify(name)) + ']'

    if (arg !== undefined) {
      tokenArguments += ', ' + String(JSON.stringify(arg))
    }

    return '" +\n    (' + tokenFunction + '(' + tokenArguments + ') || "-") + "'
  })

  // eslint-disable-next-line no-new-func
  return new Function('tokens, req, res', js)
}