cdp-lib
Version:
Contains npm modules used primarily by cdp boilerplate generator.
1,257 lines (1,221 loc) • 86 kB
JavaScript
/*!
* cdp-lib.js 0.1.7
*
* Date: 2018-02-23T10:48:14.987Z
*/
module.exports =
/******/ (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 = 14);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = require("path");
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(32));
__export(__webpack_require__(33));
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(3));
__export(__webpack_require__(29));
__export(__webpack_require__(5));
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __webpack_require__(16);
exports.fs = fs;
const glob = __webpack_require__(17);
exports.glob = glob;
const hogan = __webpack_require__(18);
exports.hogan = hogan;
const _l = __webpack_require__(19);
const _s = __webpack_require__(20);
const which = __webpack_require__(21);
exports.which = which;
const uuid = __webpack_require__(22);
exports.uuid = uuid;
const chalk_1 = __webpack_require__(23);
exports.chalk = chalk_1.default;
const semverRegex = __webpack_require__(24);
exports.semverRegex = semverRegex;
const cli_spinner_1 = __webpack_require__(25);
exports.Spinner = cli_spinner_1.Spinner;
const $ = (() => {
const _window = (() => {
const jsdom = __webpack_require__(26);
if ("function" === typeof jsdom.JSDOM) {
return new jsdom.JSDOM().window;
}
else {
return jsdom.jsdom().defaultView;
}
})();
// patch scope:
((root) => {
/*
* jsdom 9.4.0 - 9.12.0 に実装されている DOMParser は XML の serialize ができないため,
* xmldom に置き換える
* jsdom 10.1.0 まで動かないことを確認
*/
const xmldom = __webpack_require__(27);
root.DOMParser = xmldom.DOMParser;
// xmldom には dom.toString() が実装されているが、global にも export する
global.XMLSerializer = root.XMLSerializer = xmldom.XMLSerializer;
})(_window);
return __webpack_require__(28)(_window);
})();
exports.$ = $;
const _m = _l.mixin(_s.exports());
exports._ = _m;
/***/ }),
/* 4 */
/***/ (function(module, exports) {
module.exports = require("os");
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const path = __webpack_require__(0);
const libs_1 = __webpack_require__(3);
let _settings = {
force: false,
verbose: false,
silent: false,
lang: "en-US",
};
let _libPath; // cdp-lib の存在している path
///////////////////////////////////////////////////////////////////////
// exports methods:
/**
* 設定取得
*
* @returns options ログに使用するオプション
*/
function getSettings() {
return libs_1.$.extend({}, _settings);
}
exports.getSettings = getSettings;
/**
* 設定指定
*
* @param options ログに使用するオプション
*/
function setSettings(settings) {
if (settings) {
_settings.force = settings.force || _settings.force;
_settings.verbose = settings.verbose || _settings.verbose;
_settings.silent = settings.silent || _settings.silent;
_settings.targetDir = settings.targetDir || _settings.targetDir;
_settings.lang = settings.lang || _settings.lang;
}
else {
_settings = {
force: false,
verbose: false,
silent: false,
lang: "en-US",
};
}
}
exports.setSettings = setSettings;
/**
* "cdp-lib" が存在するパスを取得
*
* @returns cdp-lib への path
*/
function getLibPath() {
if (null == _libPath) {
const TRY_COUNT = 3;
let tried = 0;
_libPath = __dirname;
while (true) {
if (TRY_COUNT <= tried) {
throw Error("lib path is not resolved.");
}
_libPath = path.join(_libPath, "..");
const check = path.join(_libPath, "cdp-lib");
if (libs_1.fs.pathExistsSync(check)) {
_libPath = check;
break;
}
tried++;
}
}
return _libPath;
}
exports.getLibPath = getLibPath;
/**
* 指定された targetDir を取得
*
* @returns targetDir への path
*/
function getTargetDir() {
return _settings.targetDir;
}
exports.getTargetDir = getTargetDir;
/**
* ログ出力
* console.log() と同等
*
* @param message 出力メッセージ
* @param optionalParams 付加情報
*/
function log(message, ...optionalParams) {
if (!_settings.silent) {
if (0 < optionalParams.length) {
console.log(message, optionalParams);
}
else {
console.log(message);
}
}
}
exports.log = log;
/**
* 詳細ログ出力
* console.debug() と同等
*
* @param message 出力メッセージ
* @param optionalParams 付加情報
*/
function debug(message, ...optionalParams) {
if (!_settings.silent && _settings.verbose) {
if (0 < optionalParams.length) {
console.error("DEBUG: " + message, optionalParams);
}
else {
console.error("DEBUG: " + message);
}
}
}
exports.debug = debug;
/**
* 検証
* console.assert() と同等
*
* @param test 検証する式
* @param message 出力メッセージ
* @param optionalParams 付加情報
*/
function assert(test, message, ...optionalParams) {
if (!test) {
if (_settings.force) {
if (0 < optionalParams.length) {
console.warn(message, optionalParams);
}
else {
console.warn(message);
}
}
else {
if (0 < optionalParams.length) {
console.error(message, optionalParams);
}
else {
console.error(message);
}
process.exit(1);
}
}
}
exports.assert = assert;
let _lang;
/**
* ローカライズ
*
* @param key キー文字列
* @returns 翻訳された文字列
*/
function translate(key) {
if (!_lang) {
try {
_lang = JSON.parse(libs_1.fs.readFileSync(path.join(getLibPath(), "res/locales", "messages." + _settings.lang + ".json"), "utf8").toString());
}
catch (error) {
throw Error("Language resource JSON parse error: " + error.message);
}
}
let resouce = libs_1.$.extend({}, _lang);
const props = key.split(".");
while (0 < props.length) {
const prop = props.shift();
if (resouce[prop]) {
resouce = resouce[prop];
}
else {
assert(false, "resouce not found. key: " + key);
return null;
}
}
return resouce;
}
exports.translate = translate;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const generator_module_1 = __webpack_require__(7);
__export(__webpack_require__(7));
/**
* generator 生成関数
*/
function newGeneratorLibrary(config) {
return new generator_module_1.GeneratorModule(config);
}
exports.newGeneratorLibrary = newGeneratorLibrary;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = __webpack_require__(0);
const os = __webpack_require__(4);
const base_1 = __webpack_require__(1);
const fs = base_1.Utils.fs;
const glob = base_1.Utils.glob;
const $ = base_1.Utils.$;
const _ = base_1.Utils._;
const debug = base_1.Utils.debug;
const templatePath = base_1.Utils.templatePath;
const copyTpl = base_1.Utils.copyTpl;
/**
* @class GeneratorModule
* @brief Library Module 用 Generator クラス
*/
class GeneratorModule extends base_1.GeneratorBase {
///////////////////////////////////////////////////////////////////////
// imprementes: GeneratorBase
/**
* 既定の directory 構造を返却
*/
defaultBaseStructure() {
return {
src: "src",
pkg: "dist",
built: "built",
doc: "docs",
task: "tasks",
test: "tests",
types: "@types",
temp: ".temp",
};
}
/**
* create action entry
* @param {ILibraryConfigration} config コンフィグ設定
*/
create() {
return __awaiter(this, void 0, void 0, function* () {
yield this.ensureModuleProps();
yield this.createDirectoryStructure();
yield this.createProjectSettings();
yield this.createSourceTemplate();
yield this.createVisualStudioSolution();
});
}
/**
* 必要とする task script 一覧を返却. action: create のときに呼ばれる
*/
get taskList() {
return [
"banner.js",
"clean.js",
"srcmap.js",
"bundle-finalizer.js",
"remap-coverage.js",
];
}
///////////////////////////////////////////////////////////////////////
// protected methods:
/**
* 開発時の依存モジュールリストの取得
* 必要に応じてオーバーライド
*
* @return {IDependency}
*/
get defaultDevDependencies() {
const depends = super.defaultDevDependencies.concat([
{ name: "@types/jasmine", version: undefined, },
{ name: "dts-bundle", version: undefined, },
{ name: "typescript-formatter", version: undefined, },
]);
const extra = [];
if (this.config.nodejs) {
extra.push({ name: "jasmine-node", version: "^2.0.0", });
}
else {
extra.push({ name: "requirejs", version: undefined, });
}
return _.sortBy(depends.concat(extra), (depend) => depend.name);
}
///////////////////////////////////////////////////////////////////////
// private methods:
/**
* configration にアクセス
*/
get config() {
return this._config;
}
/**
* module 名, main ファイル名の保証
* - 1: moduleName が指定されている場合は使用する
* - 2: projectName が使用可能な場合はそれを使用する
* - 3: projectName が使用不可の場合は、"-" つなぎ文字列を生成する
*/
ensureModuleProps() {
// module name
if (null == this.config.moduleName) {
if (!/^.*[(\\|\s|/|:|*|?|"|<|>||)].*$/.test(this.config.projectName)) {
this.config.moduleName = this.config.projectName;
}
else {
this.config.moduleName = _.trim(_.dasherize(this.config.projectName), "-");
}
}
debug("moduleName: " + this.config.moduleName);
// main file name
if (null == this.config.mainBaseName) {
this.config.mainBaseName = this.config.moduleName;
}
debug("mainBaseName: " + this.config.mainBaseName);
}
/**
* ディレクトリ構成情報のコピー
*/
createDirectoryStructure() {
this.copyTplDir("library/structure");
}
/**
* プロジェクト設定ファイルの作成
*/
createProjectSettings() {
return __awaiter(this, void 0, void 0, function* () {
// project.config.js
copyTpl(path.join(templatePath("library"), "_project.config.js"), path.join(this.rootDir, "project.config.js"), this._config, { delimiters: "<% %>" });
// tsconfig
if (!this.config.outputSameDir) {
// main tsconfig.json
copyTpl(path.join(templatePath("library"), "_tsconfig.json"), path.join(this.rootDir, "tsconfig.json"), this._config, { delimiters: "<% %>", bom: false, });
// test tsconfig.json
copyTpl(path.join(templatePath("library"), "_tsconfig.test.json"), path.join(this.rootDir, this._config.structureConfig.test, "unit", "tsconfig.json"), this._config, { delimiters: "<% %>", bom: false, });
}
else {
// main tsconfig.json
copyTpl(path.join(templatePath("library"), "_tsconfig.output-same-dir.json"), path.join(this.rootDir, "tsconfig.json"), this._config, { delimiters: "<% %>", bom: false, });
}
// eslintrc.json
copyTpl(path.join(templatePath("library"), "_eslintrc.json"), path.join(this.rootDir, this._config.structureConfig.test, "eslint", "eslintrc.json"), this.queryEsLintEnvParam(), { delimiters: "<% %>", bom: false, });
// testem
if (!this.config.nodejs) {
copyTpl(path.join(templatePath("library/tools/testem"), "_testem.json"), path.join(this.rootDir, this._config.structureConfig.test, "runner", "testem.json"), this._config, { delimiters: "<% %>", bom: false, });
const testemStuffPath = templatePath("library/tools/testem/runner");
glob.sync("**", {
cwd: testemStuffPath,
nodir: true,
})
.forEach((file) => {
fs.copySync(path.join(testemStuffPath, file), path.join(this.rootDir, this._config.structureConfig.test, "runner", file));
});
}
// .gitignore
copyTpl(path.join(templatePath("library"), "_gitignore"), path.join(this.rootDir, ".gitignore"), this._config, { bom: false, });
// README.md
copyTpl(path.join(templatePath("library"), "_README.md"), path.join(this.rootDir, "README.md"), this._config, { delimiters: "<% %>" });
// package.json
this.config.devDependencies = yield this.queryDependenciesParam(this.config.devDependencies || this.defaultDevDependencies);
copyTpl(path.join(templatePath("library"), "_package.json"), path.join(this.rootDir, "package.json"), this._config, { delimiters: "<% %>", bom: false, });
});
}
/**
* ソースの雛形作成
*/
createSourceTemplate() {
return __awaiter(this, void 0, void 0, function* () {
const _module = path.basename(this._config.moduleName, ".js");
const param = {
sampleClass: _.classify(_module),
sampleModule: _module,
built: this._config.structureConfig.built,
};
const script = (() => {
if (this._config.structureConfig.srcConfig) {
return this._config.structureConfig.srcConfig.script || "";
}
return "";
})();
// index.ts
copyTpl(path.join(templatePath("library"), "src", "_index.ts"), path.join(this.rootDir, this._config.structureConfig.src, script, _module + ".ts"), param, { delimiters: "<% %>" });
// index.spec.ts
copyTpl(path.join(templatePath("library"), "src", "_index.spec.ts"), path.join(this.rootDir, this._config.structureConfig.test, "unit", _module + ".spec.ts"), param, { delimiters: "<% %>" });
});
}
/**
* Visual Studio のソリューションファイル作成
*/
createVisualStudioSolution() {
return __awaiter(this, void 0, void 0, function* () {
const vsParam = (() => {
const createGUID = base_1.Utils.createGUID;
const param = $.extend({}, this._config.structureConfig);
param.projectName = this._config.projectName;
param.projectGUID = createGUID();
param.types = param.types.replace("@", "%40"); // escape "@" to "%40"
param.mainBaseName = this._config.mainBaseName;
param.license = !this._config.private;
// tools
param.webpack = this.isEnableTool("webpack");
param.testem = !this.config.nodejs;
param.outputSameDir = this.config.outputSameDir;
// setup built js group
param.jsGroup = [];
if (!param.outputSameDir) {
param.jsGroup.push({
relativePath: param.built + "\\",
fileName: param.mainBaseName,
dependee: true,
d_ts: true,
map: true,
min_map: false,
});
}
if (this.config.minify) {
// setup pkg group
param.jsGroup.push({
relativePath: param.pkg + "\\",
fileName: param.mainBaseName,
dependee: false,
d_ts: false,
map: false,
min_map: true,
});
}
// setup test js group
param.tsGroup = [
{
relativePath: param.test + "\\unit\\",
fileName: param.mainBaseName + ".spec",
dependee: true,
map: this.config.outputSameDir,
},
];
if (param.outputSameDir) {
param.tsGroup.push({
relativePath: param.built + "\\",
fileName: param.mainBaseName,
dependee: false,
map: true,
});
}
return param;
})();
// .sln
copyTpl(path.join(templatePath("base/visual.studio"), "_solution.sln.tpl"), path.join(this.rootDir, vsParam.projectName + ".sln"), vsParam, { delimiters: "<% %>" });
// .csproj
(() => {
const toXmlString = (file) => {
const hogan = base_1.Utils.hogan;
const normalizeText = base_1.Utils.normalizeText;
const options = {
eol: os.EOL,
bom: true,
delimiters: "{{ }}",
};
const tpl = path.join(templatePath("base/visual.studio"), file);
const jst = hogan.compile(normalizeText(fs.readFileSync(tpl).toString(), { eol: "\n", bom: false }), options);
return jst.render(vsParam);
};
const toXmlDOM = (file) => {
return $($.parseXML(toXmlString(file)));
};
const toXmlNode = (file) => {
return base_1.Utils.str2XmlNode(toXmlString(file));
};
const $proj = toXmlDOM("_project.csproj.tpl");
const $gpTS = toXmlNode("_ts.item.group.tpl");
const $gpJS = toXmlNode("_js.item.group.tpl");
$proj
.find("ItemGroup")
.last()
.after($gpTS)
.after($gpJS);
const formatXML = base_1.Utils.formatXML;
const dstPath = path.join(this.rootDir, vsParam.projectName + ".csproj");
debug(base_1.Utils.xmlNode2Str($proj));
fs.writeFileSync(dstPath, formatXML(base_1.Utils.xmlNode2Str($proj)));
})();
});
}
}
exports.GeneratorModule = GeneratorModule;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const generator_cordova_1 = __webpack_require__(9);
__export(__webpack_require__(9));
/**
* generator 生成関数
*/
function newGeneratorMobile(config) {
return new generator_cordova_1.GeneratorCordova(config);
}
exports.newGeneratorMobile = newGeneratorMobile;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = __webpack_require__(0);
const os = __webpack_require__(4);
const utils_1 = __webpack_require__(2);
const base_1 = __webpack_require__(1);
/**
* @class GeneratorCordova
* @brief Mobile Cordova 用 Generator クラス
*/
class GeneratorCordova extends base_1.GeneratorBase {
///////////////////////////////////////////////////////////////////////
// imprementes: GeneratorBase
/**
* 既定の directory 構造を返却
*/
defaultBaseStructure() {
return {
src: "app",
pkg: "www",
built: "app",
doc: "docs",
task: "tasks",
test: "tests",
types: "@types",
temp: ".temp",
lib: "lib",
external: "external",
porting: "porting",
res: "res",
srcConfig: {
script: "scripts",
stylesheet: "stylesheets",
template: "templates",
},
};
}
/**
* create action entry
* @param {ILibraryConfigration} config コンフィグ設定
*/
create() {
return __awaiter(this, void 0, void 0, function* () {
utils_1.debug(JSON.stringify(this.config, null, 4));
if (this.isEnableCordova()) {
yield this.chdir(this.rootDir);
yield this.createCordovaScaffold();
yield this.updateConfigXML();
yield this.addCordovaPlatforms();
yield this.addCordovaPlugins();
yield this.addCordovaExtentionFiles();
yield this.cacheCordovaPackageJSON();
yield this.chdir("..");
}
yield this.createDirectoryStructure();
yield this.createProjectSettings();
yield this.createSourceTemplate();
yield this.createVisualStudioSolution();
});
}
/**
* 必要とする task script 一覧を返却. action: create のときに呼ばれる
*/
get taskList() {
return [
"banner.js",
"clean.js",
"command.js",
"external-rearrange.js",
"minify.js",
"srcmap.js",
"bundle-finalizer.js",
"remap-coverage.js",
];
}
///////////////////////////////////////////////////////////////////////
// protected methods:
/**
* 開発時の依存モジュールリストの取得
* 必要に応じてオーバーライド
*
* @return {IDependency}
*/
get defaultDevDependencies() {
const depends = super.defaultDevDependencies.concat([
{ name: "@types/jasmine", version: undefined, },
{ name: "@types/requirejs", version: undefined, },
{ name: "autoprefixer", version: undefined, },
{ name: "clean-css", version: undefined, },
{ name: "fs-extra", version: undefined, },
{ name: "html-minifier", version: undefined, },
{ name: "node-sass", version: undefined, },
{ name: "postcss-cli", version: undefined, },
{ name: "smartwatch", version: undefined, },
]);
const extra = [];
this.config.devDependencies.forEach((depend) => {
extra.push({ name: depend.name, version: depend.version, });
});
if (this.isEnableCordova()) {
extra.push({ name: "@types/cordova", version: undefined, });
}
return utils_1._.sortBy(depends.concat(extra), (depend) => depend.name);
}
/**
* eslintrc に指定する template paramaeter を取得
*
* @return {Object} テンプレートパラメータオブジェクト
*/
queryEsLintEnvParam() {
const base = super.queryEsLintEnvParam();
return Object.assign({}, base, {
cordova: this.isEnableCordova(),
hammerjs: this.isInstallationTarget("hammerjs"),
iscroll: this.isInstallationTarget("iscroll"),
flipsnap: this.isInstallationTarget("flipsnap"),
});
}
/**
* tsconfig.base に指定する template paramaeter を取得
*
* @return {Object} テンプレートパラメータオブジェクト
*/
queryTsConfigBaseParam() {
return Object.assign({}, this._config, {
cordova: this.isEnableCordova(),
});
}
///////////////////////////////////////////////////////////////////////
// private methods:
/**
* 開発時の依存モジュールリストの取得
* 必要に応じてオーバーライド
*
* @return {IDependency}
*/
get defaultDependencies() {
const depends = [
{ name: "@cdp/mobile", version: undefined, },
{ name: "backbone", version: undefined, },
{ name: "jquery", version: undefined, },
{ name: "requirejs", version: undefined, },
{ name: "underscore", version: undefined, },
];
const extra = [];
this.config.dependencies.forEach((depend) => {
extra.push({ name: depend.name, version: depend.version, });
});
return utils_1._.sortBy(depends.concat(extra), (depend) => depend.name);
}
/**
* configration にアクセス
*/
get config() {
return this._config;
}
/**
* cordova の有効/無効チェック
*
* @returns true: 有効 / false: 無効
*/
isEnableCordova() {
return (0 < this.config.platforms.length);
}
/**
* lib/porting の設定状況のチェック
*
* @param target
* @returns true: 設定 / false: 未設定
*/
hasStructureOf(target) {
return (this.config.projectStructure && 0 <= this.config.projectStructure.indexOf(target));
}
/**
* インストール対象/非対象チェック
*
* @param name [in] モジュール名
* @param depends [in] 検索対象 (既定 this.config.dependencies)
* @returns true: 対象 / false: 非対象
*/
isInstallationTarget(name, depends = this.config.dependencies) {
return !!depends.find((depend) => name === depend.name);
}
//___________________________________________________________________________________________________________________//
/**
* cordova を用いたプロジェクト作成
*/
createCordovaScaffold() {
return __awaiter(this, void 0, void 0, function* () {
this.progress("mobile.create.cordova.createCordovaScaffold");
utils_1.debug("createCordovaScaffold");
// `$ cordova create cool-mobile com.sony.cdp.coolmobile "Cool Mobile"`
yield utils_1.execCommand("cordova", ["create", this.config.projectName, this.config.appId, this.config.appName]);
// remove files
utils_1.glob.sync("www/**/*", {
cwd: this.config.projectName,
}).forEach((file) => {
utils_1.fs.removeSync(path.join(this.config.projectName, file));
});
utils_1.fs.removeSync(path.join(this.config.projectName, "res"));
utils_1.fs.removeSync(path.join(this.config.projectName, ".npmignore"));
// move root directory
utils_1.fs.copySync(this.config.projectName, "./");
utils_1.fs.removeSync(this.config.projectName);
});
}
/**
* config.xml の修正
*/
updateConfigXML() {
return __awaiter(this, void 0, void 0, function* () {
this.progress("mobile.create.cordova.updateConfigXml");
utils_1.debug("updateConfigXML");
const configXmlPath = path.join(process.cwd(), "config.xml");
const $configXmlDom = utils_1.$(utils_1.str2XmlNode(utils_1.fs.readFileSync(configXmlPath).toString()));
$configXmlDom
.find("widget")
.attr("version", this.config.version)
.attr("ios-CFBundleIdentifier", this.config.appId)
.prepend(utils_1.str2XmlNode(`
<preference name="DisallowOverscroll" value="true"/>
<preference name="KeyboardDisplayRequiresUserAction" value="false"/>
<preference name="BackgroundColor" value="0xff000000" />
`));
// remove cordova team information
$configXmlDom
.find("description")
.remove();
$configXmlDom
.find("author")
.remove();
utils_1.fs.writeFileSync(configXmlPath, utils_1.formatXML(utils_1.xmlNode2Str($configXmlDom)));
});
}
/**
* platform 追加
*/
addCordovaPlatforms() {
return __awaiter(this, void 0, void 0, function* () {
utils_1.debug("addCordovaPlatforms");
const targets = this.config.platforms.slice();
const index = targets.indexOf("ios");
if (0 <= index && "darwin" !== process.platform) {
this.warn("mobile.create.cordova.iOSWarning");
targets.splice(index, 1);
if (targets.length <= 0) {
return Promise.resolve();
}
}
this.progress("mobile.create.cordova.addPlatforms");
// `$ cordova platform add android ios`
yield utils_1.execCommand("cordova", ["platform", "add"].concat(targets));
});
}
/**
* plugin 追加
*/
addCordovaPlugins() {
return __awaiter(this, void 0, void 0, function* () {
this.progress("mobile.create.cordova.addPlugins");
utils_1.debug("addCordovaPlugins");
/*
* I/F は複数のプラグインを一括で追加することが可能だが、
* cordova version を判定しているプラグインは誤判定することがあるため、
* 1つずつ追加する
*
* 以下の不具合に類似する現象
* https://issues.apache.org/jira/browse/CB-12663
*/
for (let i = 0, n = this.config.cordova_plugin.length; i < n; i++) {
// `$ cordova plugin add cordova-plugin-inappbrowser`
yield utils_1.execCommand("cordova", ["plugin", "add", this.config.cordova_plugin[i].name]);
}
});
}
/**
* cordova project に追加するリソースをコピー
*/
addCordovaExtentionFiles() {
return __awaiter(this, void 0, void 0, function* () {
this.progress("mobile.create.cordova.addExtensions");
utils_1.debug("addCordovaExtentionFiles");
this.copyTplDir("mobile/cordova");
});
}
/**
* cordova が生成した package.json をキャッシュ
*/
cacheCordovaPackageJSON() {
return __awaiter(this, void 0, void 0, function* () {
if (utils_1.fs.existsSync("./package.json")) {
this.config.cordovaPackageJson = JSON.parse(utils_1.fs.readFileSync("./package.json").toString());
// remove cordova team information
delete this.config.cordovaPackageJson.name;
delete this.config.cordovaPackageJson.version;
delete this.config.cordovaPackageJson.displayName;
delete this.config.cordovaPackageJson.main;
delete this.config.cordovaPackageJson.scripts;
delete this.config.cordovaPackageJson.author;
delete this.config.cordovaPackageJson.description;
delete this.config.cordovaPackageJson.license;
// ファイルはいったん削除
utils_1.fs.removeSync("./package.json");
}
});
}
//___________________________________________________________________________________________________________________//
/**
* ディレクトリ構成情報のコピー
*/
createDirectoryStructure() {
this.progress("mobile.create.app.createDirectoryStructure");
utils_1.debug("createDirectoryStructure");
// app base structure
this.copyTplDir("mobile/structure/base");
// lib
if (this.hasStructureOf("lib")) {
this.copyTplDir("mobile/structure/lib", path.join(this.rootDir, this.config.structureConfig.src, this.config.structureConfig.lib));
}
// porting
if (this.hasStructureOf("porting")) {
this.copyTplDir("mobile/structure/porting", path.join(this.rootDir, this.config.structureConfig.src, this.config.structureConfig.porting));
// create: dev/porting/@types
utils_1.fs.copySync(utils_1.templatePath("base/.gitkeep"), path.join(this.rootDir, this.config.structureConfig.src, this.config.structureConfig.porting, this.config.structureConfig.types, ".gitkeep"));
const PLATFORMS_ROOT = path.join(this.rootDir, "platforms");
utils_1.fs.readdirSync(PLATFORMS_ROOT)
.forEach((platform) => {
if (utils_1.fs.statSync(path.join(PLATFORMS_ROOT, platform)).isDirectory()) {
this.copyTplDir("mobile/structure/porting", path.join(PLATFORMS_ROOT, platform, this.config.structureConfig.porting));
}
});
}
// www
const WWW = path.join(this.rootDir, this.config.structureConfig.pkg);
if (!utils_1.fs.existsSync(WWW)) {
utils_1.fs.mkdir(WWW);
}
utils_1.fs.copySync(utils_1.templatePath("base/.gitkeep"), path.join(WWW, ".gitkeep"));
// task
utils_1.glob.sync("**/*", {
cwd: utils_1.templatePath("mobile/task"),
}).forEach((file) => {
utils_1.fs.copySync(path.join(utils_1.templatePath("mobile/task"), file), path.join(this.rootDir, this.config.structureConfig.task, file));
});
}
/**
* プロジェクト設定ファイルの作成
*/
createProjectSettings() {
return __awaiter(this, void 0, void 0, function* () {
this.progress("mobile.create.app.createProjectSettings");
utils_1.debug("createProjectSettings");
// project.config.js
utils_1.copyTpl(path.join(utils_1.templatePath("mobile"), "_project.config.js"), path.join(this.rootDir, "project.config.js"), utils_1.$.extend({}, this._config, {
hogan: this.isInstallationTarget("hogan.js"),
hammerjs: this.isInstallationTarget("hammerjs"),
iscroll: this.isInstallationTarget("iscroll"),
}), { delimiters: "<% %>" });
// tsconfig
// tsconfig.base.json
utils_1.copyTpl(path.join(utils_1.templatePath("mobile"), "_tsconfig.base.json"), path.join(this.rootDir, "tsconfig.base.json"), this.queryTsConfigBaseParam(), { delimiters: "<% %>", bom: false, });
// main tsconfig.json
utils_1.copyTpl(path.join(utils_1.templatePath("mobile"), "_tsconfig.json"), path.join(this.rootDir, "tsconfig.json"), this._config, { delimiters: "<% %>", bom: false, });
// eslintrc.json
utils_1.copyTpl(path.join(utils_1.templatePath("mobile"), "_eslintrc.json"), path.join(this.rootDir, this._config.structureConfig.test, "eslint", "eslintrc.json"), this.queryEsLintEnvParam(), { delimiters: "<% %>", bom: false, });
// testem
utils_1.copyTpl(path.join(utils_1.templatePath("mobile/tools/testem"), "_testem.json"), path.join(this.rootDir, this._config.structureConfig.test, "runner", "testem.json"), this._config, { delimiters: "<% %>", bom: false, });
const testemStuffPath = utils_1.templatePath("mobile/tools/testem/runner");
utils_1.glob.sync("**", {
cwd: testemStuffPath,
nodir: true,
})
.forEach((file) => {
utils_1.fs.copySync(path.join(testemStuffPath, file), path.join(this.rootDir, this._config.structureConfig.test, "runner", file));
});
// .gitignore
utils_1.copyTpl(path.join(utils_1.templatePath("mobile"), "_gitignore"), path.join(this.rootDir, ".gitignore"), this._config, { bom: false, });
// README.md
utils_1.copyTpl(path.join(utils_1.templatePath("mobile"), "_README.md"), path.join(this.rootDir, "README.md"), utils_1.$.extend({}, this._config, {
cordova: this.isEnableCordova(),
lib: this.hasStructureOf("lib"),
porting: this.hasStructureOf("porting"),
}), { delimiters: "<% %>" });
// TODO: templates/mobile/addon からコピーする場合はここで対応
// package.json
const resolvedConfig = utils_1.$.extend(true, {}, this.config);
resolvedConfig.dependencies = yield this.queryDependenciesParam(this.defaultDependencies);
resolvedConfig.devDependencies = yield this.queryDependenciesParam(this.defaultDevDependencies);
utils_1.copyTpl(path.join(utils_1.templatePath("mobile"), "_package.json"), path.join(this.rootDir, "package.json"), resolvedConfig, { delimiters: "<% %>", bom: false, });
// cordovaPackageJSON とマージ
if (this.config.cordovaPackageJson) {
const PKG_PATH = path.join(this.rootDir, "package.json");
const pkg = JSON.parse(utils_1.fs.readFileSync(PKG_PATH).toString());
utils_1.$.extend(true, pkg, this.config.cordovaPackageJson);
const sortKeys = (target) => {
const sorted = {};
Object.keys(target).sort().forEach((key) => {
sorted[key] = target[key];
});
return sorted;
};
pkg.dependencies = sortKeys(pkg.dependencies);
pkg.devDependencies = sortKeys(pkg.devDependencies);
utils_1.fs.writeFileSync(PKG_PATH, JSON.stringify(pkg, null, 2));
}
});
}
/**
* ソースの雛形作成
*/
createSourceTemplate() {
return __awaiter(this, void 0, void 0, function* () {
this.progress("mobile.create.app.createSourceTemplate");
utils_1.debug("createSourceTemplate");
// copy sources
this.copyTplDir("mobile/src/structure", path.join(this.rootDir));
{
const additional = (() => {
if (this.config.dependencies.length < 0) {
return null;
}
const param = {
additional: {
list: [],
listWithCustomName: [],
},
};
const targets = [...this.config.dependencies, ...this.config.resource_addon];
targets.forEach((info) => {
if (info.fileName || info.venderName) {
param.additional.listWithCustomName.push({
moduleName: info.alias || info.name,
venderName: info.venderName || info.alias || info.name,
fileName: info.fileName || info.alias || info.name,
});
}
else {
param.additional.list.push({
moduleName: info.alias || info.name,
});
}
});
return param;
})();
utils_1.copyTpl(path.join(utils_1.templatePath("mobile/src"), "_config.ts"), path.join(this.rootDir, this.config.structureConfig.src, this.config.structureConfig.srcConfig.script, "config.ts"), utils_1.$.extend({}, this._config, additional), { delimiters: "<% %>" });
}
{
const globals = (() => {
if (this.config.dependencies.length < 0) {
return null;
}
const param = {
globals: {
importsList: [],
exportsList: [],
hasExports: false,
},
};
const targets = [...this.config.dependencies, ...this.config.resource_addon];
targets.forEach((info) => {
if (info.globalExport) {
param.globals.exportsList.push({
globalExport: info.globalExport,
moduleName: info.alias || info.name,
});
}
else {
param.globals.importsList.push({
moduleName: info.alias || info.name,
});
}
});
param.globals.hasExports = (0 < param.globals.exportsList.length);
return param;
})();
utils_1.copyTpl(path.join(utils_1.templatePath("mobile/src"), "_app.ts"), path.join(this.rootDir, this.config.structureConfig.src, this.config.structureConfig.srcConfig.script, "app.ts"), globals, { delimiters: "<% %>" });
}
{
utils_1.copyTpl(path.join(utils_1.templatePath("mobile/src/_locales"), "_messages.en-US.json"), path.join(this.rootDir, this.config.structureConfig.src, this.config.structureConfig.res, "locales", "messages.en-US.json"), this.config, { delimiters: "<% %>", bom: false, });
utils_1.copyTpl(path.join(utils_1.templatePath("mobile/src/_locales"), "_messages.ja-JP.json"), path.join(this.rootDir, this.config.structureConfig.src, this.config.structureConfig.res, "locales", "messages.ja-JP.json"), this.config, { delimiters: "<% %>", bom: false, });
// remove .gitkeep
utils_1.fs.unlinkSync(path.join(this.rootDir, this.config.structureConfig.src, this.config.structureConfig.res, ".gitkeep"));
}
{
utils_1.copyTpl(path.join(utils_1.templatePath("mobile/src/_patch.dependencies"), "_index.d.ts"), path.join(this.rootDir, this.config.structureConfig.src, this.config.structureConfig.external, this.config.structureConfig.types, "patch.dependencies", "index.d.ts"), {
hammerjs: this.isInstallationTarget("hammerjs"),
flipsnap: this.isInstallationTarget("flipsnap"),
iscroll: this.isInstallationTarget("iscroll"),
});
// copy patch d.ts
if (this.isInstallationTarget("hammerjs")) {
utils_1.fs.copySync(utils_1.templatePath("mobile/src/_patch.dependencies/jquery.hammer.d.ts"), path.join(this.rootDir, this.config.structureConfig.src, this.config.structureConfig.external, this.config.structureConfig.types, "patch.dependencies", "jquery.hammer.d.ts"));
}
if (this.isInstallationTarget("flipsnap")) {
utils_1.fs.copySync(utils_1.templatePath("mobile/src/_patch.dependencies/flipsnap.d.ts"), path.join(this.rootDir, this.config.structureConfig.src, this.config.structureConfig.external, this.config.structureConfig.types, "patch.dependencies", "flipsnap.d.ts"));
}
if (this.isInstallationTarget("iscroll")) {
utils_1.fs.copySync(utils_1.templatePath("mobile/src/_patch.dependencies/iscroll.d.ts"), path.join(this.rootDir, this.config.structureConfig.src, this.config.structureConfig.external, this.config.structureConfig.types, "patch.dependencies", "iscroll.d.ts"));
}
// remove .gitkeep
utils_1.fs.unlinkSync(path.join(this.rootDir, this.config.structureConfig.src, this.config.structureConfig.external, this.config.structureConfig.types, ".gitkeep"));
}
{
utils_1.copyTpl(path.join(utils_1.templatePath("mobile/src"), "_index.html"), path.join(this.rootDir, this.config.structureConfig.src, "index.html"), this.config);
}
});
}
/**
* Visual Studio のソリューションファイル作成
*/
createVisualStudioSolution() {
return __awaiter(this, void 0, void 0, function* () {
const vsParam = (() => {
const param = utils_1.$.extend({}, this._config.structureConfig);
param.projectName = this._config.projectName;
param.projectGUID = utils_1.createGUID();
param.types = param.types.replace("@", "%40"); // escape "@" to "%40"
param.license = !this._config.private;
// external
param.cordova = this.isEnableCordova();
param.hogan = this.isInstallationTarget("hogan.js");
param.hammerjs = this.isInstallationTarget("hammerjs");
param.iscroll = this.isInstallationTarget("iscroll");
param.flipsnap = this.isInstallationTarget("flipsnap");
// project structure
param.enableLib = this.hasStructureOf("lib");
param.enablePorting = this.hasStructureOf("porting");
// platforms
param.platforms = [...this.config.platforms];
// setup built ts group
param.tsGroup = [];
utils_1.glob.sync("**/*.ts", {
cwd: path.join(this.rootDir, param.src, param.srcConfig.script),
}).forEach((file) => {
const relativePath = path.join(param.src, param.srcConfig.script, path.dirname(file)).replace(/\//g, "\\") + "\\";
const fileName = path.basename(file, ".ts");
param.tsGroup.push({
relativePath: relativePath,
fileName: fileName,
dependee: true,
map: false,
});
});
// setup test ts group
utils_1.glob.sync("**/*.ts", {
cwd: path.join(this.rootDir, this.config.structureConfig.test, "unit"),
}).forEach((file) => {
const relativePath = param.test + "\\unit\\";
const fileName = path.basename(file, ".ts");
param.tsGroup.push({
relativePath: relativePath,
fileName: fileName,
dependee: true,
map: false,