enigma-bbs/core/asset.js

129 lines
2.3 KiB
JavaScript
Raw Normal View History

/* jslint node: true */
'use strict';
2016-06-26 04:36:40 +00:00
// ENiGMA½
const Config = require('./config.js').get;
const StatLog = require('./stat_log.js');
2016-06-26 04:36:40 +00:00
// deps
const _ = require('lodash');
const assert = require('assert');
exports.parseAsset = parseAsset;
exports.getAssetWithShorthand = getAssetWithShorthand;
exports.getArtAsset = getArtAsset;
exports.getModuleAsset = getModuleAsset;
exports.resolveConfigAsset = resolveConfigAsset;
exports.resolveSystemStatAsset = resolveSystemStatAsset;
exports.getViewPropertyAsset = getViewPropertyAsset;
const ALL_ASSETS = [
'art',
'menu',
'method',
'userModule',
2015-04-21 05:24:15 +00:00
'systemMethod',
'systemModule',
'prompt',
'config',
'sysStat',
];
2016-06-26 04:36:40 +00:00
const ASSET_RE = new RegExp('\\@(' + ALL_ASSETS.join('|') + ')\\:([\\w\\d\\.]*)(?:\\/([\\w\\d\\_]+))*');
function parseAsset(s) {
2016-06-26 04:36:40 +00:00
const m = ASSET_RE.exec(s);
if(m) {
2016-06-26 04:36:40 +00:00
let result = { type : m[1] };
if(m[3]) {
result.location = m[2];
result.asset = m[3];
} else {
result.asset = m[2];
}
return result;
}
}
function getAssetWithShorthand(spec, defaultType) {
if(!_.isString(spec)) {
return null;
}
if('@' === spec[0]) {
2016-06-26 04:36:40 +00:00
const asset = parseAsset(spec);
assert(_.isString(asset.type));
return asset;
}
return {
type : defaultType,
asset : spec,
};
}
2016-06-26 04:36:40 +00:00
function getArtAsset(spec) {
const asset = getAssetWithShorthand(spec, 'art');
2016-06-26 04:36:40 +00:00
if(!asset) {
return null;
}
2016-06-26 04:36:40 +00:00
assert( ['art', 'method' ].indexOf(asset.type) > -1);
return asset;
}
2016-06-26 04:36:40 +00:00
function getModuleAsset(spec) {
const asset = getAssetWithShorthand(spec, 'systemModule');
2016-06-26 04:36:40 +00:00
if(!asset) {
return null;
}
assert( ['userModule', 'systemModule' ].includes(asset.type) );
2016-06-26 04:36:40 +00:00
return asset;
}
2016-06-26 04:36:40 +00:00
function resolveConfigAsset(spec) {
const asset = parseAsset(spec);
if(asset) {
assert('config' === asset.type);
2016-06-26 04:36:40 +00:00
const path = asset.asset.split('.');
let conf = Config();
2016-06-26 04:36:40 +00:00
for(let i = 0; i < path.length; ++i) {
if(_.isUndefined(conf[path[i]])) {
2016-06-26 04:36:40 +00:00
return spec;
}
conf = conf[path[i]];
}
return conf;
} else {
2016-06-26 04:36:40 +00:00
return spec;
}
}
function resolveSystemStatAsset(spec) {
const asset = parseAsset(spec);
if(!asset) {
return spec;
}
assert('sysStat' === asset.type);
return StatLog.getSystemStat(asset.asset) || spec;
}
function getViewPropertyAsset(src) {
if(!_.isString(src) || '@' !== src.charAt(0)) {
return null;
}
return parseAsset(src);
2016-06-26 04:36:40 +00:00
}