Precompiles linked files, generating a .meta file with all the meta data

@param {Object<String, String[]>} { code, files }
@return {Promise}
558279
function precompile({ code, files }) {
    return resolve(files)
        .then(filter(test(/^locales(\/|\\)[a-z]{2,3}(_[A-Z]{2})?\.json$/)))
        .then(localesToPairs)
        .then(runInAllLocales(code))
        .then(createMetaFile)
        .return(['.meta', ...files]);
}
1328594
function(sourceOrProgram, filename) {
        
        if (!(this instanceof MetaScript)) {
            __version = Array.prototype.join.call(arguments, '.');
            return;
        }
        
        // Whether constructing from a meta program or, otherwise, a source
        var isProgram = (sourceOrProgram+="").substring(0, 11) === 'MetaScript(';
        
        /**
         * Original source.
         * @type {?string}
         */
        this.source = isProgram ? null : sourceOrProgram;

        /**
         * Original source file name.
         * @type {string}
         */
        this.filename = filename || "main";

        /**
         * The compiled meta program's source.
         * @type {string}
         */
        this.program = isProgram ? sourceOrProgram : MetaScript.compile(sourceOrProgram);
    }
639717
function processFile() {
  return (file, callback) => {
    let parsed;
    if (file.meta !== undefined && file.meta.layout !== undefined) {
      const ext = path.extname(file.meta.layout);
      parsed = path.parse(`${trimExtension(file.path)}${ext}`);
    } else {
      parsed = path.parse(file.path);
    }

    const filePath = {
      dir: parsed.dir,
      name: parsed.name,
      ext: parsed.ext,
    };
    const meta = Object.assign({}, file.meta, { filePath });
    async.nextTick(callback, null, Object.assign({}, file, { meta }));
  };
}
562753
function (files, callback) {
		//loop on all files and write them
		async.each(files, function (fileObj, mCb) {
			var data = swagger.cloneObj(fileObj.data);
			
			//if tokens, replace all occurences with corresponding values
			if (fileObj.tokens) {
				for (var i in fileObj.tokens) {
					var regexp = new RegExp("%" + i + "%", "g");
					data = data.replace(regexp, fileObj.tokens[i]);
				}
			}
			if (fileObj.purify) {
				data = data.replace(/\\"/g, '"').replace(/["]+/g, '"').replace(/"__dirname/g, '__dirname');
				data = data.replace(/("group": "__empty__")/g, '"group": ""');
				data = data.replace(/("prefix": "(\s?|\s+),)/g, '"prefix": "",');
				data = data.replace(/("l": "__empty__")/g, '"l": ""');
				//"__dirname + \"/lib/mw/_get.js\""
				//"__dirname + "/lib/mw/_get.js""
				//"__dirname + "/lib/mw/_get.js"
				//__dirname + "/lib/mw/_get.js"
			}
			console.log("creating file:", fileObj.file);
			fs.writeFile(fileObj.file, data, "utf8", mCb);
		}, function (error) {
			if (error) {
				return callback({"code": 854, "msg": error.message});
			}
			return callback(null, true);
		});
	}
742926
function compileFile(srcFullPath, saveOutFullPath, onlyCopy) {
  var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};

  var content = fs.readFileSync(srcFullPath, 'utf8');

  //when get file content empty, maybe file is locked
  if (!content) {
    return;
  }

  // only copy file content
  if (onlyCopy) {
    fse.copySync(srcFullPath, saveOutFullPath);
    return;
  }

  try {
    var startTime = Date.now();

    var data = compileByBabel(content, {
      filename: srcFullPath
      // sourceMaps: true,
      // sourceFileName: relativePath
    });

    var endTime = Date.now();

    if (options.debug) {
      console.log('Compile file ' + srcFullPath, 'Babel cost ' + (endTime - startTime) + ' ms');
    }

    // save file
    fse.outputFileSync(saveOutFullPath, data.code);

    return true;
  } catch (e) {
    console.error('compile file ' + srcFullPath + ' error', e);
  }

  return false;
}
1297280
function() {
        return new Promise(function(resolve, reject) {
            try {
                let files;
                if(fileUtils.fileExists(resourceDir)) {
                    files = fs.readdirSync(resourceDir);
                    files = _.uniqBy(files, function (f) {
                        return path.basename(f, '.' + rc.tools.spec.file_ext);
                    }).map(function(f) { return path.join(resourceDir, f);});
                }
                if(!files) files = [];
                resolve(files);
            } catch (err) {
                reject(err);
            }
        }).then(function(files) {
            return promiseUtils.chain(rc.tools.inspect, function(err) {
                console.error(err);
                return false;
            })(files);
        });
    }
508248
async function build(file) {
  const { code, map, assets } = await ncc(file, options);

  if (Object.keys(assets).length)
    console.error("New unexpected assets are being emitted for", file);

  const name = basename(file, ".js");
  await mkdirp(resolve(DIST_DIR, name));
  write(resolve(DIST_DIR, name, "index.js"), code);
  write(resolve(DIST_DIR, name, "index.map.js"), map);
}
50111
function() {
        var self = this;

        self._modules = [];

        return new Promise(function(resolve, reject) {
            var base;
            var processors = [];

            if (self._options.base) {
                base = fs.readFileSync(path.resolve(self._options.base), 'utf8');
            }

            // For every file or folder, create a promise,
            // parse the file, extract the config and store it
            // to the global modules array.
            // Once all files are being processed, store the generated config.
            for (var i = 0; i < self._options.args.length; i++) {
                var file = self._options.args[i];

                var fileStats = fs.statSync(file);

                if (fileStats.isDirectory(file)) {
                    var walker = walk.walk(file, {
                        followLinks: false
                    });

                    walker.on('file', self._onWalkerFile.bind(self));

                    processors.push(self._onWalkerEnd(walker));
                } else if (fileStats.isFile()) {
                    processors.push(self._processFile(file));
                }
            }

            Promise.all(processors)
                .then(function(uselessPromises) {
                    return self._generateConfig();
                })
                .then(function(config) {
                    var content;

                    if (self._options.config) {
                        if (base) {
                            content = base + self._options.config + '.modules = ' + JSON.stringify(config) + ';';
                        } else {
                            content = 'var ' + self._options.config + ' = {modules: ' + JSON.stringify(config) + '};';
                        }
                    } else {
                        content = JSON.stringify(config);
                    }

                    return self._saveConfig(beautify(content));
                })
                .then(function(config) {
                    resolve(config);
                })
                .catch(function(error) {
                    reject(error);
                });
        });
    }
422780
function docsBuild(file, info) {
  console.log(`Processing file: ${file}\n`)
  const vueObj = vueDocgen.parse(file)

  let compDataObj = {
    "api": {},
    "version": '',
  }

  // calculate associated component names and paths
  const vueCompName = path.basename(file,'.vue')
  const vueCompDir = path.dirname(file)
  const vueCompFilePath = vueCompDir + path.sep + vueCompName
  const BASE_VERSION = '0.0.0'
  let latestMdDoc = null, latestMdVer = BASE_VERSION

  // Determine version of current raw vue component based on its associated package.json file
  const currentDir = path.dirname(file) + path.sep
  const readmeFilePath = `${currentDir}README.md`
  const examplesFilePath = `${currentDir}EXAMPLES.md`
  const compDataHistoryFilePath = `${currentDir}build${path.sep}component-data.json`
  let compDataHistory = {"name": `${vueCompName}`, "versions": []}
  const currentVer = info.version
  compDataObj.version = currentVer

  // create data objects for component properties, events, methods, and slots
  const apiProm = new Promise((resolve, reject) => { resolve(buildAPIs(vueObj)) })
  .then( api => { 
    console.log(`Completed API data object for ${vueCompName}\n`)
    console.log(`${util.inspect(api)}`)
    Object.assign(compDataObj.api, api) 
  })
  .catch( err => { console.log(`Error while trying to create API objects:\n${err}`) })

  // After all promises complete, add new component data object to history of component
  // If current version is in history array, replace that element with current 
  Promise.all([apiProm])
  .then(() => {
    let currVersionIdx = -1
    currVersionIdx = compDataHistory.versions.findIndex((element) => {
      return element.version === compDataObj.version
    })
    currVersionIdx == -1 ? 
      compDataHistory.versions.unshift(compDataObj) :
      compDataHistory.versions[currVersionIdx] = compDataObj

    return fs.outputJSON(compDataHistoryFilePath, compDataHistory, {spaces: '\t'})
  })
  .catch( err => {
    console.log(`Problem saving component history for ${vueCompName}:\n${err}`)
    process.exit(1)
  })
}
88328
function compile(patch) {
  var code = "";
  patch.forEach(function(op) {
    var o = "";
    switch (op.op) {
      case "remove":
        o += "delete " + pathToStatement(op.path);
        break;
      case "add":
        o += pathToStatement(op.path) + " = " + JSON.stringify(op.value);
        break;
      case "replace":
        o += pathToStatement(op.path) + " = " + JSON.stringify(op.value);
        break;
      case "move":
        var from = pathToStatement(op.from);
        o += pathToStatement(op.path) + " = " + from + ";\n";
        o += "delete " + from;
        break;
      case "copy":
        o += pathToStatement(op.path) + " = " + from;
        break;
      case "test":
        o +=
          "if (!oo.equal(" +
          pathToStatement(op.path) +
          ", " +
          JSON.stringify(op.value) +
          ") throw new Error()";
        break;
    }
    code += o + ";\n";
  });
  return code;
}
328090
function(searchParams, generateMatches, generateMeta) {
			try {
				return this.getFileClient().search(searchParams).then(function(jsonData) {
					var searchResult = this.convert(jsonData, searchParams);
					return this._generateMatches(searchParams, searchResult, generateMatches).then(function() {
						return this._generateMeta(searchResult, generateMeta).then(function() {
							return searchResult;
						});
					}.bind(this));
				}.bind(this));
			}
			catch(err){
				var error = err.message || err;
				if(typeof error === "string" && error.toLowerCase().indexOf("search") > -1){ //$NON-NLS-1$ //$NON-NLS-0$
					if(!this._crawler) {
						this._crawler = this._createCrawler(searchParams);
					}
					if(searchParams.nameSearch) {
						return this._crawler.searchName(searchParams).then(function(jsonData) {
							return this.convert(jsonData, searchParams);
						}.bind(this));
					}
					var result;
					return result = this._crawler.search(function() {
						result.progress(arguments[0], arguments[1]);
					}).then(function(jsonData) {
						return this.convert(jsonData, searchParams);
					}.bind(this));
				}
				throw error;
			}
		}
1267687
function compile(fileNames, options, verbose) {
  const program = ts.createProgram(fileNames, options)
  const emitResult = program.emit()

  /* istanbul ignore next */
  if (verbose) {
    const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics)

    allDiagnostics.forEach((diagnostic) => {
      if (diagnostic.file) {
        const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(
          diagnostic.start
        )
        const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")
        console.log(
          `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`
        )
      } else {
        console.log(`${ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")}`)
      }
    })
  }
}
1225310
async function build() {
  console.time('Packager');

  let requires = [];
  let esmExportString = '';
  let cjsExportString = '';

  try {
    if (!fs.existsSync(DIST_PATH)) fs.mkdirSync(DIST_PATH);
    fs.writeFileSync(ROLLUP_INPUT_FILE, '');
    fs.writeFileSync(TEST_MODULE_FILE, '');

    // All the snippets that are Node.js-based and will break in a browser
    // environment
    const nodeSnippets = fs
      .readFileSync('tag_database', 'utf8')
      .split('\n')
      .filter(v => v.search(/:.*node/g) !== -1)
      .map(v => v.slice(0, v.indexOf(':')));

    const snippets = fs.readdirSync(SNIPPETS_PATH);
    const archivedSnippets = fs
      .readdirSync(SNIPPETS_ARCHIVE_PATH)
      .filter(v => v !== 'README.md');

    snippets.forEach(snippet => {
      const rawSnippetString = getRawSnippetString(SNIPPETS_PATH, snippet);
      const snippetName = snippet.replace('.md', '');
      let code = getCode(rawSnippetString);
      if (nodeSnippets.includes(snippetName)) {
        requires.push(code.match(/const.*=.*require\(([^\)]*)\);/g));
        code = code.replace(/const.*=.*require\(([^\)]*)\);/g, '');
      }
      esmExportString += `export ${code}`;
      cjsExportString += code;
    });
    archivedSnippets.forEach(snippet => {
      const rawSnippetString = getRawSnippetString(
        SNIPPETS_ARCHIVE_PATH,
        snippet
      );
      cjsExportString += getCode(rawSnippetString);
    });

    requires = [
      ...new Set(
        requires
          .filter(Boolean)
          .map(v =>
            v[0].replace(
              'require(',
              'typeof require !== "undefined" && require('
            )
          )
      )
    ].join('\n');

    fs.writeFileSync(ROLLUP_INPUT_FILE, `${requires}\n\n${esmExportString}`);

    const testExports = `module.exports = {${[...snippets, ...archivedSnippets]
      .map(v => v.replace('.md', ''))
      .join(',')}}`;

    fs.writeFileSync(
      TEST_MODULE_FILE,
      `${requires}\n\n${cjsExportString}\n\n${testExports}`
    );

    // Check Travis builds - Will skip builds on Travis if not CRON/API
    if (util.isTravisCI() && util.isNotTravisCronOrAPI()) {
      fs.unlink(ROLLUP_INPUT_FILE);
      console.log(
        `${chalk.green(
          'NOBUILD'
        )} Module build terminated, not a cron job or a custom build!`
      );
      console.timeEnd('Packager');
      process.exit(0);
    }

    await doRollup();

    // Clean up the temporary input file Rollup used for building the module
    fs.unlink(ROLLUP_INPUT_FILE);

    console.log(`${chalk.green('SUCCESS!')} Snippet module built!`);
    console.timeEnd('Packager');
  } catch (err) {
    console.log(`${chalk.red('ERROR!')} During module creation: ${err}`);
    process.exit(1);
  }
}
123529
function initCustomPointerTypemaps(typemapsdir) {
  return fs.readdirAsync(typemapsdir).then(function(dirs) {
    return Promise.all(_.map(dirs, function(dir) {
      // get all js*.i directives from class-specific subdirectories, to be parsed below for %typemaps directives
      return fs.readdirAsync(typemapsdir + '/' + dir).then(function(files) {
        var directive = _.find(files, function(fn) {
          return ((path.extname(fn) == '.i') && (path.basename(fn).search(/^js/) != -1));
        });
        var data = {};
        if (directive) {
          data[dir] = typemapsdir + '/' + dir + '/' + directive;
        }
        return data;
      }).catch(function(e) {
        // get all .i directives from top level directory, and parse for %array_class directives
        if (e.code == 'ENOTDIR') {
          var fn = dir;
          if (path.extname(fn) == '.i') {
            return fs.readFileAsync(typemapsdir + '/' + fn, 'utf8').then(function(directives) {
              var arraytypes = _.filter(directives.split(/\n/), function(line) {
                return (line.search(/^%array_class/) != -1);
              });
              _.each(arraytypes, function(arraytype) {
                var parsed = arraytype.match(/%array_class\(([A-Za-z0-9_]+)[\s]*,[\s]*([A-Za-z0-9_]+)\)/);
                if (parsed) {
                  var from = parsed[1];
                  var to = parsed[2];
                  xml2js.ARRAY_TYPEMAPS[from] = { arrayType: to, classes: [] };
                } else {
                  console.log('Incorrectly parsed array_class from ' + fn + ': ' + arraytype);
                }
              });
            });
          }
        } else {
          throw e;
        }
      });
    }));
  }).then(function(__directivesFiles) {
    // parse for %typemaps & %pointer_functions directives
    var _directivesFiles = _.filter(__directivesFiles, function(data) { return !_.isEmpty(data); });
    var directivesFiles = _.object(_.map(_directivesFiles, _.keys), _.flatten(_.map(_directivesFiles, _.values)));
    return Promise.all(_.map(directivesFiles, function(directivesFn, className) {
      return fs.readFileAsync(directivesFn, 'utf8').then(function(directives) {
        var typemaps = _.filter(directives.split(/\n/), function(line) {
          return (line.search(/^%typemap/) != -1);
        });
        _.each(typemaps, function(typemap) {
          var parsed = typemap.match(/%typemap\((in|out)\)[\s]+([A-Za-z0-9_]+[\s]*[\*])/);
          if (parsed) {
            var dir = parsed[1]; // TODO: ignored for now
            var type = normalizePointer(parsed[2]);
            var datatype = getPointerDataType(type);
            if (_.has(xml2js.ARRAY_TYPEMAPS, datatype)) {
              xml2js.ARRAY_TYPEMAPS[datatype].classes.push(className);
            } else {
              console.log('Ignored typemap from ' + directivesFn + ': ' + typemap.replace('{', '') + ' (no %array_class directive found for ' + datatype + ')');
            }
          } else {
            console.log('Ignored typemap from ' + directivesFn + ': ' + typemap.replace('{', '') + ' (only considering in/out typemaps of pointer types)');
          }
        });
        var ptrfns = _.filter(directives.split(/\n/), function(line) {
          return (line.search(/^%pointer_functions/) != -1);
        });
        _.each(ptrfns, function(ptrfn) {
          var parsed = ptrfn.match(/%pointer_functions\(([A-Za-z0-9_]+)[\s]*,[\s]*([A-Za-z0-9_]+)\)/);
          if (parsed) {
            var from = parsed[1];
            var to = parsed[2];
            if (!_.has(xml2js.POINTER_TYPEMAPS, className)) {
              xml2js.POINTER_TYPEMAPS[className] = {};
            }
            xml2js.POINTER_TYPEMAPS[className][from] = to;
          }
        });
      });
    }));
  });
}
343489
function compile(code, options) {
        var output;
        options = options || {};
        options.requireModule = options.requireModule || requireModule;
        var ast = parse(code, options.modules || [], options);
        if (options.readableNames) {
            ast = optimizeHygiene(ast);
        }
        if (options.ast) {
            return ast;
        }
        if (options.sourceMap) {
            output = codegen.generate(ast, _.extend({
                comment: true,
                sourceMap: options.filename,
                sourceMapWithCode: true
            }, options.escodegen));
            return {
                code: output.code,
                sourceMap: output.map.toString()
            };
        }
        return { code: codegen.generate(ast, _.extend({ comment: true }, options.escodegen)) };
    }
821490
async function _uploadFiles(dir, presignedPosts) {
  const promises = [];
  const limit = pLimit(5);
  let uploaded = false;

  Object.keys(presignedPosts).forEach(async (path) => {
    const { post } = presignedPosts[path];

    if (!post) {
      Logger.tagged('exists', path, 'blue');
    } else {
      const filePath = resolve(dir, path);
      const form = new FormData();

      Utils.forEach(post.fields, (value, key) => { form.append(key, value); });
      form.append('file', fs.createReadStream(filePath));

      const promise = limit(() => got.post(post.url, { body: form }).then(() => {
        Logger.tagged('upload', path);
      }));

      promises.push(promise);
      uploaded = true;
    }
  });

  await Promise.all(promises);
  return uploaded;
}
159352
function jslintFile(file, extraArgs) {
    return readConf(homeDir, {})
        .then(function (homeConf) {
            if (Array.isArray(file)) {
                return file.reduce(function (prom, file) {
                    return prom.then(function (oldReport) {
                        return jslintFile(file, extraArgs)
                            .then(function (newReport) {
                                return oldReport.concat(newReport);
                            });
                    });
                }, Promise.resolve([]));
            }
            return readFile(file, "utf8")
                .then(function (data) {
                    const opts = (
                        typeof extraArgs === "object" && extraArgs !== null
                    )
                        ? extraArgs
                        : {};
                    const projectDir = opts.projectDir || process.cwd();
                    return readConf(projectDir, path.dirname(file), homeConf)
                        .then(function (conf) {
                            const newConf = Object.assign(
                                {},
                                conf,
                                opts.options
                            );
                            const lines = Array.isArray(data)
                                ? data
                                : data.split(/\n|\r\n?/);
                            const sb = opts.shaBang
                                ? lines[0].startsWith("#!")
                                    ? [""].concat(lines.slice(1))
                                    : lines
                                : lines;
                            const report = {
                                pathname: file,
                                report: jslint(sb, newConf, opts.globals)
                            };

                            return typeof opts.callback === "function"
                                ? opts.callback(report)
                                : report;
                        });
                });
        });
}