| 1 |
'use strict'; |
| 2 |
|
| 3 |
var fs = require('fs'); |
| 4 |
var templateSTR = fs.readFileSync(__dirname + '/template.min.js', 'utf8'); |
| 5 |
|
| 6 |
function template(moduleName, options) { |
| 7 |
if (typeof options === 'boolean') { |
| 8 |
options = {commonJS: options}; |
| 9 |
} else if (!options) { |
| 10 |
options = {}; |
| 11 |
} |
| 12 |
var str = templateSTR.replace(/defineNamespace\(\)/g, compileNamespace(moduleName)) |
| 13 |
.split('source()') |
| 14 |
str[0] = str[0].trim(); |
| 15 |
|
| 16 |
str[0] += 'var define,module,exports;'; |
| 17 |
if (options.commonJS) str[0] += 'module={exports:(exports={})};'; |
| 18 |
str[0] += '\n'; |
| 19 |
if (options.commonJS) str[1] = 'return module.exports;' + str[1]; |
| 20 |
str[1] = '\n' + str[1]; |
| 21 |
return str; |
| 22 |
} |
| 23 |
|
| 24 |
exports = module.exports = function (name, src, options) { |
| 25 |
if (typeof options === 'string' && typeof src === 'object') { |
| 26 |
var tmp = options; |
| 27 |
options = src; |
| 28 |
src = tmp; |
| 29 |
} |
| 30 |
return exports.prelude(name, options) + src + exports.postlude(name, options); |
| 31 |
}; |
| 32 |
|
| 33 |
exports.prelude = function (moduleName, options) { |
| 34 |
return template(moduleName, options)[0]; |
| 35 |
}; |
| 36 |
exports.postlude = function (moduleName, options) { |
| 37 |
return template(moduleName, options)[1]; |
| 38 |
}; |
| 39 |
|
| 40 |
|
| 41 |
function camelCase(name) { |
| 42 |
name = name.replace(/\-([a-z])/g, function (_, char) { return char.toUpperCase(); }); |
| 43 |
if (!/^[a-zA-Z_$]$/.test(name[0])) { |
| 44 |
name = name.substr(1); |
| 45 |
} |
| 46 |
var result = name.replace(/[^\w$]+/g, '') |
| 47 |
if (!result) { |
| 48 |
throw new Error('Invalid JavaScript identifier resulted from camel-casing'); |
| 49 |
} |
| 50 |
return result |
| 51 |
} |
| 52 |
|
| 53 |
|
| 54 |
function compileNamespace(name) { |
| 55 |
var names = name.split('.') |
| 56 |
|
| 57 |
|
| 58 |
if (names.length === 1) { |
| 59 |
return 'g.' + camelCase(name) + ' = f()'; |
| 60 |
|
| 61 |
|
| 62 |
} else if (names.length === 2) { |
| 63 |
names = names.map(camelCase); |
| 64 |
return '(g.' + names[0] + ' || (g.' + names[0] + ' = {})).' + names[1] + ' = f()'; |
| 65 |
|
| 66 |
|
| 67 |
} else { |
| 68 |
var valueContainer = names.pop() |
| 69 |
return names.map(compileNamespaceStep) |
| 70 |
.concat(['g.' + camelCase(valueContainer) + ' = f()']) |
| 71 |
.join(';'); |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
function compileNamespaceStep(name) { |
| 76 |
name = camelCase(name); |
| 77 |
return 'g=(g.' + name + '||(g.' + name + ' = {}))'; |
| 78 |
} |