1// Copyright 2016 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5'use strict';
6
7/**
8 * @fileoverview Lets node import catapult HTML-imports-authored modules.
9 *
10 */
11var isNode = global.process && global.process.versions.node;
12if (!isNode)
13  throw new Error('Only works inside node');
14
15var fs = require('fs');
16var path = require('path');
17var process = require('process');
18var child_process = require('child_process');
19
20var catapultPath = fs.realpathSync(path.join(__dirname, '..'));
21var catapultBuildPath = path.join(catapultPath, 'catapult_build');
22
23var vinnPath = path.join(catapultPath, 'third_party', 'vinn');
24
25function loadAndEval(fileName) {
26  var contents = fs.readFileSync(fileName, 'utf8');
27  (function() {
28    eval(contents);
29  }).call(global);
30}
31
32function initialize() {
33  loadAndEval(path.join(vinnPath, 'vinn', 'base64_compat.js'));
34
35  // First, we need to hand-load the HTML imports loader from Vinn,
36  // plus a few of its supporting files. These all assume that 'this' is the
37  // global object, so eval them with 'this' redirected.
38  loadAndEval(path.join(vinnPath, 'third_party', 'parse5', 'parse5.js'));
39  loadAndEval(path.join(vinnPath, 'vinn', 'html_to_js_generator.js'));
40  loadAndEval(path.join(vinnPath, 'vinn', 'html_imports_loader.js'));
41  loadAndEval(path.join(vinnPath, 'vinn', 'path_utils.js'));
42
43  // Now that everything is loaded, we need to set up the loader.
44  var pathUtils = new global.PathUtils(
45      {
46        currentWorkingDirectory: process.cwd(),
47        exists: function(fileName) {
48          return fs.existsSync(fileName);
49        }
50      });
51  global.HTMLImportsLoader.setPathUtils(pathUtils);
52}
53
54
55/**
56 * Gets the source search paths for a catapult project module.
57 *
58 * @param {String} projectName The project in question.
59 * @return {Array} A list of search paths.
60 */
61module.exports.getSourcePathsForProject = function(projectName) {
62  var sourcePathsString = child_process.execFileSync(
63      path.join(catapultBuildPath, 'print_project_info'),
64      ['--source-paths', projectName]);
65  return JSON.parse(sourcePathsString);
66};
67
68
69/**
70 * Gets the headless test module filenames for a catapult project module.
71 *
72 * @param {String} projectName The project in question.
73 * @return {Array} A list of module filenames.
74 */
75module.exports.getHeadlessTestModuleFilenamesForProject =
76    function(projectName) {
77  var sourcePathsString = child_process.execFileSync(
78      path.join(catapultBuildPath, 'print_project_info'),
79      ['--headless-test-module-filenames', projectName]);
80  return JSON.parse(sourcePathsString);
81};
82
83initialize();
84