윤준현

Merge branch 'default'

Showing 219 changed files with 69 additions and 4699 deletions
......@@ -26,42 +26,43 @@ http.createServer(app).listen(8080, () => {
// http://서버주소/message
app.post('/message', function (req, res) {
app.post('/message', function(req,res){
//유저가 입력한 데이터
var msg = req.body.content;
console.log('전달받은 메시지 : ' + msg);
var send = {};
switch (msg) {
case '일본':
switch(msg){
case '일본' :
send = {
'message': {
'text': '등록된 가수 목록입니다.'
},
keyboard: {
'type': 'buttons',
'buttons': ['Reol', '米津玄師', 'yanaginagi', 'ヨルシカ', 'ダズビ', 'Polkadot Stingray', 'Aimyong']
'message' : {
'text' : '등록된 가수 목록입니다.'
},
keyboard : {
'type' : 'buttons',
'buttons' : ['Reol', '米津玄師', 'yanaginagi', 'ヨルシカ', 'ダズビ', 'Polkadot Stingray', 'Aimyong']
}
};
break;
case '한국':
case '한국' :
send = {
'message': {
'text': '등록된 가수 목록입니다.'
},
keyboard: {
'type': 'buttons',
'buttons': ['볼빨간 사춘기', 'MOT', 'Gukkasten', 'ZICO', 'DEAN', 'IU', 'Heize']
'message' : {
'text' : '등록된 가수 목록입니다.'
},
keyboard : {
'type' : 'buttons',
'buttons' : ['볼빨간 사춘기', 'MOT', 'Gukkasten', 'ZICO', 'DEAN', 'IU', 'Heize']
}
};
break;
default:
send = singer.jpSinger(msg)
if (send == '')
send = singer.jpSinger(msg);
if(send == '')
send = singer.krSinger(msg);
break;
}
console.log(send);
res.json(hell_send);
res.json(send);
})
\ No newline at end of file
......
This diff is collapsed. Click to expand it.
//Reol 나무위키 앨범 발매년도 트랙 크롤링
var request = require('request');
var cheerio = require('cheerio');
function crawl_Reol(url, callBack){
request(url, function(err, res, body){
const $ = cheerio.load(body);
function crawl_Reol(url){
return new Promise(function(resolve, reject){
request(url, function (err, res, body) {
const $ = cheerio.load(body);
var Reol = new Array();
var album, year
var album_track = new Array();
var json_album = new Array(), json_year = new Array(), json_track = new Array();
var Reol = new Array();
var album, year
var album_track = new Array();
var json_album = new Array(), json_year = new Array(), json_track = new Array();
$('body > div.content-wrapper > article > div.wiki-content.clearfix > div').each(function (index, ele) {
for (var i = 1; i <= $('.toc-item').length; i++) {
album = $(this).find('#toc > div > div:nth-child(2) > span:nth-child(' + i + ')').text() //앨범 정보 가져오기
if (album != '') {
json_album.push(album.substr(2));
}
$('body > div.content-wrapper > article > div.wiki-content.clearfix > div').each(function(index, ele){
for(var i = 1; i <= $('.toc-item').length; i++){
album = $(this).find('#toc > div > div:nth-child(2) > span:nth-child('+i+')').text() //앨범 정보 가져오기
if(album != ''){
json_album.push(album.substr(2));
}
var index = 7 + (i*2); //트랙, 연도 가져오기 인덱스 변수
var index = 7 + (i * 2); //트랙, 연도 가져오기 인덱스 변수
if(index != 25){ //규칙성이 어긋나는 부분을 예외처리를 위해 if문
//year 가져오기
year = $('body > div.content-wrapper > article > div.wiki-content.clearfix > div > div:nth-child('+index+') > div:nth-child(3) > table > tbody > tr:nth-child(1) > td:nth-child(2)').text();
//track 가져오기
$('body > div.content-wrapper > article > div.wiki-content.clearfix > div > div:nth-child('+index+') > div:nth-child(3) > table > tbody').find('tr').each(function(index, ele){
var track = $(this).children().eq(1).text();
if(track != '1' && track != '곡명' && track[4] != '년')
album_track.push(track)
});
}
else{
year = $('body > div.content-wrapper > article > div.wiki-content.clearfix > div > div:nth-child('+index+') > div:nth-child(4) > table > tbody > tr:nth-child(1) > td:nth-child(2)').text();
$('body > div.content-wrapper > article > div.wiki-content.clearfix > div > div:nth-child('+index+') > div:nth-child(4) > table > tbody').find('tr').each(function(index, ele){
var track = $(this).children().eq(1).text();
if(track != '1' && track != '곡명' && track[4] != '년')
album_track.push(track)
});
}
if(year != ''){
json_year.push(year);
json_track.push(album_track);
if (index != 25) { //규칙성이 어긋나는 부분을 예외처리를 위해 if문
//year 가져오기
year = $('body > div.content-wrapper > article > div.wiki-content.clearfix > div > div:nth-child(' + index + ') > div:nth-child(3) > table > tbody > tr:nth-child(1) > td:nth-child(2)').text();
//track 가져오기
$('body > div.content-wrapper > article > div.wiki-content.clearfix > div > div:nth-child(' + index + ') > div:nth-child(3) > table > tbody').find('tr').each(function (index, ele) {
var track = $(this).children().eq(1).text();
if (track != '1' && track != '곡명' && track[4] != '년')
album_track.push(track)
});
}
else {
year = $('body > div.content-wrapper > article > div.wiki-content.clearfix > div > div:nth-child(' + index + ') > div:nth-child(4) > table > tbody > tr:nth-child(1) > td:nth-child(2)').text();
$('body > div.content-wrapper > article > div.wiki-content.clearfix > div > div:nth-child(' + index + ') > div:nth-child(4) > table > tbody').find('tr').each(function (index, ele) {
var track = $(this).children().eq(1).text();
if (track != '1' && track != '곡명' && track[4] != '년')
album_track.push(track)
});
}
if (year != '') {
json_year.push(year);
json_track.push(album_track);
}
album_track = [];
}
album_track = [];
});
Reol.push({ json_album, json_year, json_track });
if (Reol) {
resolve(Reol);
}
reject(new Error("Request is failed"));
});
Reol.push({json_album,json_year,json_track});
callBack(Reol);
});
}
......
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../require/bin/require-command.js" "$@"
ret=$?
else
node "$basedir/../require/bin/require-command.js" "$@"
ret=$?
fi
exit $ret
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\require\bin\require-command.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\require\bin\require-command.js" %*
)
\ No newline at end of file
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../uglify-js/bin/uglifyjs" "$@"
ret=$?
else
node "$basedir/../uglify-js/bin/uglifyjs" "$@"
ret=$?
fi
exit $ret
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\uglify-js\bin\uglifyjs" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\uglify-js\bin\uglifyjs" %*
)
\ No newline at end of file
amdefine is released under two licenses: new BSD, and MIT. You may pick the
license that best suits your development needs. The text of both licenses are
provided below.
The "New" BSD License:
----------------------
Copyright (c) 2011-2016, The Dojo Foundation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Dojo Foundation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
MIT License
-----------
Copyright (c) 2011-2016, The Dojo Foundation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# amdefine
A module that can be used to implement AMD's define() in Node. This allows you
to code to the AMD API and have the module work in node programs without
requiring those other programs to use AMD.
## Usage
**1)** Update your package.json to indicate amdefine as a dependency:
```javascript
"dependencies": {
"amdefine": ">=0.1.0"
}
```
Then run `npm install` to get amdefine into your project.
**2)** At the top of each module that uses define(), place this code:
```javascript
if (typeof define !== 'function') { var define = require('amdefine')(module) }
```
**Only use these snippets** when loading amdefine. If you preserve the basic structure,
with the braces, it will be stripped out when using the [RequireJS optimizer](#optimizer).
You can add spaces, line breaks and even require amdefine with a local path, but
keep the rest of the structure to get the stripping behavior.
As you may know, because `if` statements in JavaScript don't have their own scope, the var
declaration in the above snippet is made whether the `if` expression is truthy or not. If
RequireJS is loaded then the declaration is superfluous because `define` is already already
declared in the same scope in RequireJS. Fortunately JavaScript handles multiple `var`
declarations of the same variable in the same scope gracefully.
If you want to deliver amdefine.js with your code rather than specifying it as a dependency
with npm, then just download the latest release and refer to it using a relative path:
[Latest Version](https://github.com/jrburke/amdefine/raw/latest/amdefine.js)
### amdefine/intercept
Consider this very experimental.
Instead of pasting the piece of text for the amdefine setup of a `define`
variable in each module you create or consume, you can use `amdefine/intercept`
instead. It will automatically insert the above snippet in each .js file loaded
by Node.
**Warning**: you should only use this if you are creating an application that
is consuming AMD style defined()'d modules that are distributed via npm and want
to run that code in Node.
For library code where you are not sure if it will be used by others in Node or
in the browser, then explicitly depending on amdefine and placing the code
snippet above is suggested path, instead of using `amdefine/intercept`. The
intercept module affects all .js files loaded in the Node app, and it is
inconsiderate to modify global state like that unless you are also controlling
the top level app.
#### Why distribute AMD-style modules via npm?
npm has a lot of weaknesses for front-end use (installed layout is not great,
should have better support for the `baseUrl + moduleID + '.js' style of loading,
single file JS installs), but some people want a JS package manager and are
willing to live with those constraints. If that is you, but still want to author
in AMD style modules to get dynamic require([]), better direct source usage and
powerful loader plugin support in the browser, then this tool can help.
#### amdefine/intercept usage
Just require it in your top level app module (for example index.js, server.js):
```javascript
require('amdefine/intercept');
```
The module does not return a value, so no need to assign the result to a local
variable.
Then just require() code as you normally would with Node's require(). Any .js
loaded after the intercept require will have the amdefine check injected in
the .js source as it is loaded. It does not modify the source on disk, just
prepends some content to the text of the module as it is loaded by Node.
#### How amdefine/intercept works
It overrides the `Module._extensions['.js']` in Node to automatically prepend
the amdefine snippet above. So, it will affect any .js file loaded by your
app.
## define() usage
It is best if you use the anonymous forms of define() in your module:
```javascript
define(function (require) {
var dependency = require('dependency');
});
```
or
```javascript
define(['dependency'], function (dependency) {
});
```
## RequireJS optimizer integration. <a name="optimizer"></name>
Version 1.0.3 of the [RequireJS optimizer](http://requirejs.org/docs/optimization.html)
will have support for stripping the `if (typeof define !== 'function')` check
mentioned above, so you can include this snippet for code that runs in the
browser, but avoid taking the cost of the if() statement once the code is
optimized for deployment.
## Node 0.4 Support
If you want to support Node 0.4, then add `require` as the second parameter to amdefine:
```javascript
//Only if you want Node 0.4. If using 0.5 or later, use the above snippet.
if (typeof define !== 'function') { var define = require('amdefine')(module, require) }
```
## Limitations
### Synchronous vs Asynchronous
amdefine creates a define() function that is callable by your code. It will
execute and trace dependencies and call the factory function *synchronously*,
to keep the behavior in line with Node's synchronous dependency tracing.
The exception: calling AMD's callback-style require() from inside a factory
function. The require callback is called on process.nextTick():
```javascript
define(function (require) {
require(['a'], function(a) {
//'a' is loaded synchronously, but
//this callback is called on process.nextTick().
});
});
```
### Loader Plugins
Loader plugins are supported as long as they call their load() callbacks
synchronously. So ones that do network requests will not work. However plugins
like [text](http://requirejs.org/docs/api.html#text) can load text files locally.
The plugin API's `load.fromText()` is **not supported** in amdefine, so this means
transpiler plugins like the [CoffeeScript loader plugin](https://github.com/jrburke/require-cs)
will not work. This may be fixable, but it is a bit complex, and I do not have
enough node-fu to figure it out yet. See the source for amdefine.js if you want
to get an idea of the issues involved.
## Tests
To run the tests, cd to **tests** and run:
```
node all.js
node all-intercept.js
```
## License
New BSD and MIT. Check the LICENSE file for all the details.
/** vim: et:ts=4:sw=4:sts=4
* @license amdefine 1.0.1 Copyright (c) 2011-2016, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/amdefine for details
*/
/*jslint node: true */
/*global module, process */
'use strict';
/**
* Creates a define for node.
* @param {Object} module the "module" object that is defined by Node for the
* current module.
* @param {Function} [requireFn]. Node's require function for the current module.
* It only needs to be passed in Node versions before 0.5, when module.require
* did not exist.
* @returns {Function} a define function that is usable for the current node
* module.
*/
function amdefine(module, requireFn) {
'use strict';
var defineCache = {},
loaderCache = {},
alreadyCalled = false,
path = require('path'),
makeRequire, stringRequire;
/**
* Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments.
*/
function trimDots(ary) {
var i, part;
for (i = 0; ary[i]; i+= 1) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
function normalize(name, baseName) {
var baseParts;
//Adjust any relative paths.
if (name && name.charAt(0) === '.') {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
baseParts = baseName.split('/');
baseParts = baseParts.slice(0, baseParts.length - 1);
baseParts = baseParts.concat(name.split('/'));
trimDots(baseParts);
name = baseParts.join('/');
}
}
return name;
}
/**
* Create the normalize() function passed to a loader plugin's
* normalize method.
*/
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName);
};
}
function makeLoad(id) {
function load(value) {
loaderCache[id] = value;
}
load.fromText = function (id, text) {
//This one is difficult because the text can/probably uses
//define, and any relative paths and requires should be relative
//to that id was it would be found on disk. But this would require
//bootstrapping a module/require fairly deeply from node core.
//Not sure how best to go about that yet.
throw new Error('amdefine does not implement load.fromText');
};
return load;
}
makeRequire = function (systemRequire, exports, module, relId) {
function amdRequire(deps, callback) {
if (typeof deps === 'string') {
//Synchronous, single module require('')
return stringRequire(systemRequire, exports, module, deps, relId);
} else {
//Array of dependencies with a callback.
//Convert the dependencies to modules.
deps = deps.map(function (depName) {
return stringRequire(systemRequire, exports, module, depName, relId);
});
//Wait for next tick to call back the require call.
if (callback) {
process.nextTick(function () {
callback.apply(null, deps);
});
}
}
}
amdRequire.toUrl = function (filePath) {
if (filePath.indexOf('.') === 0) {
return normalize(filePath, path.dirname(module.filename));
} else {
return filePath;
}
};
return amdRequire;
};
//Favor explicit value, passed in if the module wants to support Node 0.4.
requireFn = requireFn || function req() {
return module.require.apply(module, arguments);
};
function runFactory(id, deps, factory) {
var r, e, m, result;
if (id) {
e = loaderCache[id] = {};
m = {
id: id,
uri: __filename,
exports: e
};
r = makeRequire(requireFn, e, m, id);
} else {
//Only support one define call per file
if (alreadyCalled) {
throw new Error('amdefine with no module ID cannot be called more than once per file.');
}
alreadyCalled = true;
//Use the real variables from node
//Use module.exports for exports, since
//the exports in here is amdefine exports.
e = module.exports;
m = module;
r = makeRequire(requireFn, e, m, module.id);
}
//If there are dependencies, they are strings, so need
//to convert them to dependency values.
if (deps) {
deps = deps.map(function (depName) {
return r(depName);
});
}
//Call the factory with the right dependencies.
if (typeof factory === 'function') {
result = factory.apply(m.exports, deps);
} else {
result = factory;
}
if (result !== undefined) {
m.exports = result;
if (id) {
loaderCache[id] = m.exports;
}
}
}
stringRequire = function (systemRequire, exports, module, id, relId) {
//Split the ID by a ! so that
var index = id.indexOf('!'),
originalId = id,
prefix, plugin;
if (index === -1) {
id = normalize(id, relId);
//Straight module lookup. If it is one of the special dependencies,
//deal with it, otherwise, delegate to node.
if (id === 'require') {
return makeRequire(systemRequire, exports, module, relId);
} else if (id === 'exports') {
return exports;
} else if (id === 'module') {
return module;
} else if (loaderCache.hasOwnProperty(id)) {
return loaderCache[id];
} else if (defineCache[id]) {
runFactory.apply(null, defineCache[id]);
return loaderCache[id];
} else {
if(systemRequire) {
return systemRequire(originalId);
} else {
throw new Error('No module with ID: ' + id);
}
}
} else {
//There is a plugin in play.
prefix = id.substring(0, index);
id = id.substring(index + 1, id.length);
plugin = stringRequire(systemRequire, exports, module, prefix, relId);
if (plugin.normalize) {
id = plugin.normalize(id, makeNormalize(relId));
} else {
//Normalize the ID normally.
id = normalize(id, relId);
}
if (loaderCache[id]) {
return loaderCache[id];
} else {
plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
return loaderCache[id];
}
}
};
//Create a define function specific to the module asking for amdefine.
function define(id, deps, factory) {
if (Array.isArray(id)) {
factory = deps;
deps = id;
id = undefined;
} else if (typeof id !== 'string') {
factory = id;
id = deps = undefined;
}
if (deps && !Array.isArray(deps)) {
factory = deps;
deps = undefined;
}
if (!deps) {
deps = ['require', 'exports', 'module'];
}
//Set up properties for this module. If an ID, then use
//internal cache. If no ID, then use the external variables
//for this node module.
if (id) {
//Put the module in deep freeze until there is a
//require call for it.
defineCache[id] = [id, deps, factory];
} else {
runFactory(id, deps, factory);
}
}
//define.require, which has access to all the values in the
//cache. Useful for AMD modules that all have IDs in the file,
//but need to finally export a value to node based on one of those
//IDs.
define.require = function (id) {
if (loaderCache[id]) {
return loaderCache[id];
}
if (defineCache[id]) {
runFactory.apply(null, defineCache[id]);
return loaderCache[id];
}
};
define.amd = {};
return define;
}
module.exports = amdefine;
/*jshint node: true */
var inserted,
Module = require('module'),
fs = require('fs'),
existingExtFn = Module._extensions['.js'],
amdefineRegExp = /amdefine\.js/;
inserted = "if (typeof define !== 'function') {var define = require('amdefine')(module)}";
//From the node/lib/module.js source:
function stripBOM(content) {
// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
// because the buffer-to-string conversion in `fs.readFileSync()`
// translates it to FEFF, the UTF-16 BOM.
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
}
//Also adapted from the node/lib/module.js source:
function intercept(module, filename) {
var content = stripBOM(fs.readFileSync(filename, 'utf8'));
if (!amdefineRegExp.test(module.id)) {
content = inserted + content;
}
module._compile(content, filename);
}
intercept._id = 'amdefine/intercept';
if (!existingExtFn._id || existingExtFn._id !== intercept._id) {
Module._extensions['.js'] = intercept;
}
{
"_from": "amdefine@>=0.0.4",
"_id": "amdefine@1.0.1",
"_inBundle": false,
"_integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=",
"_location": "/amdefine",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "amdefine@>=0.0.4",
"name": "amdefine",
"escapedName": "amdefine",
"rawSpec": ">=0.0.4",
"saveSpec": null,
"fetchSpec": ">=0.0.4"
},
"_requiredBy": [
"/source-map"
],
"_resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.1.tgz",
"_shasum": "4a5282ac164729e93619bcfd3ad151f817ce91f5",
"_spec": "amdefine@>=0.0.4",
"_where": "D:\\OneDrive\\University Life\\2018\\2nd semester\\OpenSourceSoftware\\KaKao_ChatBot\\node_modules\\source-map",
"author": {
"name": "James Burke",
"email": "jrburke@gmail.com",
"url": "http://github.com/jrburke"
},
"bugs": {
"url": "https://github.com/jrburke/amdefine/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Provide AMD's define() API for declaring modules in the AMD format",
"engines": {
"node": ">=0.4.2"
},
"homepage": "http://github.com/jrburke/amdefine",
"license": "BSD-3-Clause OR MIT",
"main": "./amdefine.js",
"name": "amdefine",
"repository": {
"type": "git",
"url": "git+https://github.com/jrburke/amdefine.git"
},
"version": "1.0.1"
}
Copyright (c) 2010 Caolan McMahon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
This diff is collapsed. Click to expand it.
{
"name": "async",
"repo": "caolan/async",
"description": "Higher-order functions and common patterns for asynchronous code",
"version": "0.1.23",
"keywords": [],
"dependencies": {},
"development": {},
"main": "lib/async.js",
"scripts": [ "lib/async.js" ]
}
This diff is collapsed. Click to expand it.
{
"_from": "async@~0.2.6",
"_id": "async@0.2.10",
"_inBundle": false,
"_integrity": "sha1-trvgsGdLnXGXCMo43owjfLUmw9E=",
"_location": "/async",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "async@~0.2.6",
"name": "async",
"escapedName": "async",
"rawSpec": "~0.2.6",
"saveSpec": null,
"fetchSpec": "~0.2.6"
},
"_requiredBy": [
"/uglify-js"
],
"_resolved": "http://registry.npmjs.org/async/-/async-0.2.10.tgz",
"_shasum": "b6bbe0b0674b9d719708ca38de8c237cb526c3d1",
"_spec": "async@~0.2.6",
"_where": "D:\\OneDrive\\University Life\\2018\\2nd semester\\OpenSourceSoftware\\KaKao_ChatBot\\node_modules\\uglify-js",
"author": {
"name": "Caolan McMahon"
},
"bugs": {
"url": "https://github.com/caolan/async/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Higher-order functions and common patterns for asynchronous code",
"devDependencies": {
"nodelint": ">0.0.0",
"nodeunit": ">0.0.0",
"uglify-js": "1.2.x"
},
"homepage": "https://github.com/caolan/async#readme",
"jam": {
"main": "lib/async.js",
"include": [
"lib/async.js",
"README.md",
"LICENSE"
]
},
"licenses": [
{
"type": "MIT",
"url": "https://github.com/caolan/async/raw/master/LICENSE"
}
],
"main": "./lib/async",
"name": "async",
"repository": {
"type": "git",
"url": "git+https://github.com/caolan/async.git"
},
"scripts": {
"test": "nodeunit test/test-async.js"
},
"version": "0.2.10"
}
{
"_from": "cheerio@^1.0.0-rc.2",
"_from": "cheerio",
"_id": "cheerio@1.0.0-rc.2",
"_inBundle": false,
"_integrity": "sha1-S59TqBsn5NXawxwP/Qz6A8xoMNs=",
"_location": "/cheerio",
"_phantomChildren": {},
"_requested": {
"type": "range",
"type": "tag",
"registry": true,
"raw": "cheerio@^1.0.0-rc.2",
"raw": "cheerio",
"name": "cheerio",
"escapedName": "cheerio",
"rawSpec": "^1.0.0-rc.2",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "^1.0.0-rc.2"
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
......@@ -21,7 +21,7 @@
],
"_resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.2.tgz",
"_shasum": "4b9f53a81b27e4d5dac31c0ffd0cfa03cc6830db",
"_spec": "cheerio@^1.0.0-rc.2",
"_spec": "cheerio",
"_where": "D:\\OneDrive\\University Life\\2018\\2nd semester\\OpenSourceSoftware\\KaKao_ChatBot",
"author": {
"name": "Matt Mueller",
......
language: node_js
node_js:
- "0.8"
- "0.10"
Copyright 2010 James Halliday (mail@substack.net)
This project is free software released under the MIT/X11 license:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
#!/usr/bin/env node
var util = require('util');
var argv = require('optimist').argv;
if (argv.s) {
util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: ');
}
console.log(
(argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '')
);
#!/usr/bin/env node
var argv = require('optimist')
.boolean(['x','y','z'])
.argv
;
console.dir([ argv.x, argv.y, argv.z ]);
console.dir(argv._);
#!/usr/bin/env node
var argv = require('optimist')
.boolean('v')
.argv
;
console.dir(argv.v);
console.dir(argv._);
#!/usr/bin/env node
var argv = require('optimist')
.default({ x : 10, y : 10 })
.argv
;
console.log(argv.x + argv.y);
#!/usr/bin/env node
var argv = require('optimist')
.default('x', 10)
.default('y', 10)
.argv
;
console.log(argv.x + argv.y);
#!/usr/bin/env node
var argv = require('optimist')
.usage('Usage: $0 -x [num] -y [num]')
.demand(['x','y'])
.argv;
console.log(argv.x / argv.y);
#!/usr/bin/env node
var argv = require('optimist')
.usage('Count the lines in a file.\nUsage: $0')
.demand('f')
.alias('f', 'file')
.describe('f', 'Load a file')
.argv
;
var fs = require('fs');
var s = fs.createReadStream(argv.file);
var lines = 0;
s.on('data', function (buf) {
lines += buf.toString().match(/\n/g).length;
});
s.on('end', function () {
console.log(lines);
});
#!/usr/bin/env node
var argv = require('optimist')
.usage('Count the lines in a file.\nUsage: $0')
.options({
file : {
demand : true,
alias : 'f',
description : 'Load a file'
},
base : {
alias : 'b',
description : 'Numeric base to use for output',
default : 10,
},
})
.argv
;
var fs = require('fs');
var s = fs.createReadStream(argv.file);
var lines = 0;
s.on('data', function (buf) {
lines += buf.toString().match(/\n/g).length;
});
s.on('end', function () {
console.log(lines.toString(argv.base));
});
#!/usr/bin/env node
var argv = require('optimist')
.usage('Count the lines in a file.\nUsage: $0')
.wrap(80)
.demand('f')
.alias('f', [ 'file', 'filename' ])
.describe('f',
"Load a file. It's pretty important."
+ " Required even. So you'd better specify it."
)
.alias('b', 'base')
.describe('b', 'Numeric base to display the number of lines in')
.default('b', 10)
.describe('x', 'Super-secret optional parameter which is secret')
.default('x', '')
.argv
;
var fs = require('fs');
var s = fs.createReadStream(argv.file);
var lines = 0;
s.on('data', function (buf) {
lines += buf.toString().match(/\n/g).length;
});
s.on('end', function () {
console.log(lines.toString(argv.base));
});
#!/usr/bin/env node
var argv = require('optimist').argv;
console.log('(%d,%d)', argv.x, argv.y);
console.log(argv._);
#!/usr/bin/env node
console.dir(require('optimist').argv);
#!/usr/bin/env node
var argv = require('optimist').argv;
console.log('(%d,%d)', argv.x, argv.y);
#!/usr/bin/env node
var argv = require('optimist')
.string('x', 'y')
.argv
;
console.dir([ argv.x, argv.y ]);
/* Turns off numeric coercion:
./node string.js -x 000123 -y 9876
[ '000123', '9876' ]
*/
var optimist = require('./../index');
var argv = optimist.usage('This is my awesome program', {
'about': {
description: 'Provide some details about the author of this program',
required: true,
short: 'a',
},
'info': {
description: 'Provide some information about the node.js agains!!!!!!',
boolean: true,
short: 'i'
}
}).argv;
optimist.showHelp();
console.log('\n\nInspecting options');
console.dir(argv);
\ No newline at end of file
#!/usr/bin/env node
var argv = require('optimist').argv;
if (argv.rif - 5 * argv.xup > 7.138) {
console.log('Buy more riffiwobbles');
}
else {
console.log('Sell the xupptumblers');
}
This diff is collapsed. Click to expand it.
{
"_from": "optimist@~0.3.5",
"_id": "optimist@0.3.7",
"_inBundle": false,
"_integrity": "sha1-yQlBrVnkJzMokjB00s8ufLxuwNk=",
"_location": "/optimist",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "optimist@~0.3.5",
"name": "optimist",
"escapedName": "optimist",
"rawSpec": "~0.3.5",
"saveSpec": null,
"fetchSpec": "~0.3.5"
},
"_requiredBy": [
"/uglify-js"
],
"_resolved": "https://registry.npmjs.org/optimist/-/optimist-0.3.7.tgz",
"_shasum": "c90941ad59e4273328923074d2cf2e7cbc6ec0d9",
"_spec": "optimist@~0.3.5",
"_where": "D:\\OneDrive\\University Life\\2018\\2nd semester\\OpenSourceSoftware\\KaKao_ChatBot\\node_modules\\uglify-js",
"author": {
"name": "James Halliday",
"email": "mail@substack.net",
"url": "http://substack.net"
},
"bugs": {
"url": "https://github.com/substack/node-optimist/issues"
},
"bundleDependencies": false,
"dependencies": {
"wordwrap": "~0.0.2"
},
"deprecated": false,
"description": "Light-weight option parsing with an argv hash. No optstrings attached.",
"devDependencies": {
"hashish": "~0.0.4",
"tap": "~0.4.0"
},
"engine": {
"node": ">=0.4"
},
"homepage": "https://github.com/substack/node-optimist#readme",
"keywords": [
"argument",
"args",
"option",
"parser",
"parsing",
"cli",
"command"
],
"license": "MIT/X11",
"main": "./index.js",
"name": "optimist",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/substack/node-optimist.git"
},
"scripts": {
"test": "tap ./test/*.js"
},
"version": "0.3.7"
}
optimist
========
Optimist is a node.js library for option parsing for people who hate option
parsing. More specifically, this module is for people who like all the --bells
and -whistlz of program usage but think optstrings are a waste of time.
With optimist, option parsing doesn't have to suck (as much).
[![build status](https://secure.travis-ci.org/substack/node-optimist.png)](http://travis-ci.org/substack/node-optimist)
examples
========
With Optimist, the options are just a hash! No optstrings attached.
-------------------------------------------------------------------
xup.js:
````javascript
#!/usr/bin/env node
var argv = require('optimist').argv;
if (argv.rif - 5 * argv.xup > 7.138) {
console.log('Buy more riffiwobbles');
}
else {
console.log('Sell the xupptumblers');
}
````
***
$ ./xup.js --rif=55 --xup=9.52
Buy more riffiwobbles
$ ./xup.js --rif 12 --xup 8.1
Sell the xupptumblers
![This one's optimistic.](http://substack.net/images/optimistic.png)
But wait! There's more! You can do short options:
-------------------------------------------------
short.js:
````javascript
#!/usr/bin/env node
var argv = require('optimist').argv;
console.log('(%d,%d)', argv.x, argv.y);
````
***
$ ./short.js -x 10 -y 21
(10,21)
And booleans, both long and short (and grouped):
----------------------------------
bool.js:
````javascript
#!/usr/bin/env node
var util = require('util');
var argv = require('optimist').argv;
if (argv.s) {
util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: ');
}
console.log(
(argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '')
);
````
***
$ ./bool.js -s
The cat says: meow
$ ./bool.js -sp
The cat says: meow.
$ ./bool.js -sp --fr
Le chat dit: miaou.
And non-hypenated options too! Just use `argv._`!
-------------------------------------------------
nonopt.js:
````javascript
#!/usr/bin/env node
var argv = require('optimist').argv;
console.log('(%d,%d)', argv.x, argv.y);
console.log(argv._);
````
***
$ ./nonopt.js -x 6.82 -y 3.35 moo
(6.82,3.35)
[ 'moo' ]
$ ./nonopt.js foo -x 0.54 bar -y 1.12 baz
(0.54,1.12)
[ 'foo', 'bar', 'baz' ]
Plus, Optimist comes with .usage() and .demand()!
-------------------------------------------------
divide.js:
````javascript
#!/usr/bin/env node
var argv = require('optimist')
.usage('Usage: $0 -x [num] -y [num]')
.demand(['x','y'])
.argv;
console.log(argv.x / argv.y);
````
***
$ ./divide.js -x 55 -y 11
5
$ node ./divide.js -x 4.91 -z 2.51
Usage: node ./divide.js -x [num] -y [num]
Options:
-x [required]
-y [required]
Missing required arguments: y
EVEN MORE HOLY COW
------------------
default_singles.js:
````javascript
#!/usr/bin/env node
var argv = require('optimist')
.default('x', 10)
.default('y', 10)
.argv
;
console.log(argv.x + argv.y);
````
***
$ ./default_singles.js -x 5
15
default_hash.js:
````javascript
#!/usr/bin/env node
var argv = require('optimist')
.default({ x : 10, y : 10 })
.argv
;
console.log(argv.x + argv.y);
````
***
$ ./default_hash.js -y 7
17
And if you really want to get all descriptive about it...
---------------------------------------------------------
boolean_single.js
````javascript
#!/usr/bin/env node
var argv = require('optimist')
.boolean('v')
.argv
;
console.dir(argv);
````
***
$ ./boolean_single.js -v foo bar baz
true
[ 'bar', 'baz', 'foo' ]
boolean_double.js
````javascript
#!/usr/bin/env node
var argv = require('optimist')
.boolean(['x','y','z'])
.argv
;
console.dir([ argv.x, argv.y, argv.z ]);
console.dir(argv._);
````
***
$ ./boolean_double.js -x -z one two three
[ true, false, true ]
[ 'one', 'two', 'three' ]
Optimist is here to help...
---------------------------
You can describe parameters for help messages and set aliases. Optimist figures
out how to format a handy help string automatically.
line_count.js
````javascript
#!/usr/bin/env node
var argv = require('optimist')
.usage('Count the lines in a file.\nUsage: $0')
.demand('f')
.alias('f', 'file')
.describe('f', 'Load a file')
.argv
;
var fs = require('fs');
var s = fs.createReadStream(argv.file);
var lines = 0;
s.on('data', function (buf) {
lines += buf.toString().match(/\n/g).length;
});
s.on('end', function () {
console.log(lines);
});
````
***
$ node line_count.js
Count the lines in a file.
Usage: node ./line_count.js
Options:
-f, --file Load a file [required]
Missing required arguments: f
$ node line_count.js --file line_count.js
20
$ node line_count.js -f line_count.js
20
methods
=======
By itself,
````javascript
require('optimist').argv
`````
will use `process.argv` array to construct the `argv` object.
You can pass in the `process.argv` yourself:
````javascript
require('optimist')([ '-x', '1', '-y', '2' ]).argv
````
or use .parse() to do the same thing:
````javascript
require('optimist').parse([ '-x', '1', '-y', '2' ])
````
The rest of these methods below come in just before the terminating `.argv`.
.alias(key, alias)
------------------
Set key names as equivalent such that updates to a key will propagate to aliases
and vice-versa.
Optionally `.alias()` can take an object that maps keys to aliases.
.default(key, value)
--------------------
Set `argv[key]` to `value` if no option was specified on `process.argv`.
Optionally `.default()` can take an object that maps keys to default values.
.demand(key)
------------
If `key` is a string, show the usage information and exit if `key` wasn't
specified in `process.argv`.
If `key` is a number, demand at least as many non-option arguments, which show
up in `argv._`.
If `key` is an Array, demand each element.
.describe(key, desc)
--------------------
Describe a `key` for the generated usage information.
Optionally `.describe()` can take an object that maps keys to descriptions.
.options(key, opt)
------------------
Instead of chaining together `.alias().demand().default()`, you can specify
keys in `opt` for each of the chainable methods.
For example:
````javascript
var argv = require('optimist')
.options('f', {
alias : 'file',
default : '/etc/passwd',
})
.argv
;
````
is the same as
````javascript
var argv = require('optimist')
.alias('f', 'file')
.default('f', '/etc/passwd')
.argv
;
````
Optionally `.options()` can take an object that maps keys to `opt` parameters.
.usage(message)
---------------
Set a usage message to show which commands to use. Inside `message`, the string
`$0` will get interpolated to the current script name or node command for the
present script similar to how `$0` works in bash or perl.
.check(fn)
----------
Check that certain conditions are met in the provided arguments.
If `fn` throws or returns `false`, show the thrown error, usage information, and
exit.
.boolean(key)
-------------
Interpret `key` as a boolean. If a non-flag option follows `key` in
`process.argv`, that string won't get set as the value of `key`.
If `key` never shows up as a flag in `process.arguments`, `argv[key]` will be
`false`.
If `key` is an Array, interpret all the elements as booleans.
.string(key)
------------
Tell the parser logic not to interpret `key` as a number or boolean.
This can be useful if you need to preserve leading zeros in an input.
If `key` is an Array, interpret all the elements as strings.
.wrap(columns)
--------------
Format usage output to wrap at `columns` many columns.
.help()
-------
Return the generated usage string.
.showHelp(fn=console.error)
---------------------------
Print the usage data using `fn` for printing.
.parse(args)
------------
Parse `args` instead of `process.argv`. Returns the `argv` object.
.argv
-----
Get the arguments as a plain old object.
Arguments without a corresponding flag show up in the `argv._` array.
The script name or node command is available at `argv.$0` similarly to how `$0`
works in bash or perl.
parsing tricks
==============
stop parsing
------------
Use `--` to stop parsing flags and stuff the remainder into `argv._`.
$ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4
{ _: [ '-c', '3', '-d', '4' ],
'$0': 'node ./examples/reflect.js',
a: 1,
b: 2 }
negate fields
-------------
If you want to explicity set a field to false instead of just leaving it
undefined or to override a default you can do `--no-key`.
$ node examples/reflect.js -a --no-b
{ _: [],
'$0': 'node ./examples/reflect.js',
a: true,
b: false }
numbers
-------
Every argument that looks like a number (`!isNaN(Number(arg))`) is converted to
one. This way you can just `net.createConnection(argv.port)` and you can add
numbers out of `argv` with `+` without having that mean concatenation,
which is super frustrating.
duplicates
----------
If you specify a flag multiple times it will get turned into an array containing
all the values in order.
$ node examples/reflect.js -x 5 -x 8 -x 0
{ _: [],
'$0': 'node ./examples/reflect.js',
x: [ 5, 8, 0 ] }
dot notation
------------
When you use dots (`.`s) in argument names, an implicit object path is assumed.
This lets you organize arguments into nested objects.
$ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5
{ _: [],
'$0': 'node ./examples/reflect.js',
foo: { bar: { baz: 33 }, quux: 5 } }
installation
============
With [npm](http://github.com/isaacs/npm), just do:
npm install optimist
or clone this project on github:
git clone http://github.com/substack/node-optimist.git
To run the tests with [expresso](http://github.com/visionmedia/expresso),
just do:
expresso
inspired By
===========
This module is loosely inspired by Perl's
[Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm).
var spawn = require('child_process').spawn;
var test = require('tap').test;
test('dotSlashEmpty', testCmd('./bin.js', []));
test('dotSlashArgs', testCmd('./bin.js', [ 'a', 'b', 'c' ]));
test('nodeEmpty', testCmd('node bin.js', []));
test('nodeArgs', testCmd('node bin.js', [ 'x', 'y', 'z' ]));
test('whichNodeEmpty', function (t) {
var which = spawn('which', ['node']);
which.stdout.on('data', function (buf) {
t.test(
testCmd(buf.toString().trim() + ' bin.js', [])
);
t.end();
});
which.stderr.on('data', function (err) {
assert.error(err);
t.end();
});
});
test('whichNodeArgs', function (t) {
var which = spawn('which', ['node']);
which.stdout.on('data', function (buf) {
t.test(
testCmd(buf.toString().trim() + ' bin.js', [ 'q', 'r' ])
);
t.end();
});
which.stderr.on('data', function (err) {
t.error(err);
t.end();
});
});
function testCmd (cmd, args) {
return function (t) {
var to = setTimeout(function () {
assert.fail('Never got stdout data.')
}, 5000);
var oldDir = process.cwd();
process.chdir(__dirname + '/_');
var cmds = cmd.split(' ');
var bin = spawn(cmds[0], cmds.slice(1).concat(args.map(String)));
process.chdir(oldDir);
bin.stderr.on('data', function (err) {
t.error(err);
t.end();
});
bin.stdout.on('data', function (buf) {
clearTimeout(to);
var _ = JSON.parse(buf.toString());
t.same(_.map(String), args.map(String));
t.end();
});
};
}
#!/usr/bin/env node
console.log(JSON.stringify(process.argv));
#!/usr/bin/env node
var argv = require('../../index').argv
console.log(JSON.stringify(argv._));
This diff is collapsed. Click to expand it.
var Hash = require('hashish');
var optimist = require('../index');
var test = require('tap').test;
test('usageFail', function (t) {
var r = checkUsage(function () {
return optimist('-x 10 -z 20'.split(' '))
.usage('Usage: $0 -x NUM -y NUM')
.demand(['x','y'])
.argv;
});
t.same(
r.result,
{ x : 10, z : 20, _ : [], $0 : './usage' }
);
t.same(
r.errors.join('\n').split(/\n+/),
[
'Usage: ./usage -x NUM -y NUM',
'Options:',
' -x [required]',
' -y [required]',
'Missing required arguments: y',
]
);
t.same(r.logs, []);
t.ok(r.exit);
t.end();
});
test('usagePass', function (t) {
var r = checkUsage(function () {
return optimist('-x 10 -y 20'.split(' '))
.usage('Usage: $0 -x NUM -y NUM')
.demand(['x','y'])
.argv;
});
t.same(r, {
result : { x : 10, y : 20, _ : [], $0 : './usage' },
errors : [],
logs : [],
exit : false,
});
t.end();
});
test('checkPass', function (t) {
var r = checkUsage(function () {
return optimist('-x 10 -y 20'.split(' '))
.usage('Usage: $0 -x NUM -y NUM')
.check(function (argv) {
if (!('x' in argv)) throw 'You forgot about -x';
if (!('y' in argv)) throw 'You forgot about -y';
})
.argv;
});
t.same(r, {
result : { x : 10, y : 20, _ : [], $0 : './usage' },
errors : [],
logs : [],
exit : false,
});
t.end();
});
test('checkFail', function (t) {
var r = checkUsage(function () {
return optimist('-x 10 -z 20'.split(' '))
.usage('Usage: $0 -x NUM -y NUM')
.check(function (argv) {
if (!('x' in argv)) throw 'You forgot about -x';
if (!('y' in argv)) throw 'You forgot about -y';
})
.argv;
});
t.same(
r.result,
{ x : 10, z : 20, _ : [], $0 : './usage' }
);
t.same(
r.errors.join('\n').split(/\n+/),
[
'Usage: ./usage -x NUM -y NUM',
'You forgot about -y'
]
);
t.same(r.logs, []);
t.ok(r.exit);
t.end();
});
test('checkCondPass', function (t) {
function checker (argv) {
return 'x' in argv && 'y' in argv;
}
var r = checkUsage(function () {
return optimist('-x 10 -y 20'.split(' '))
.usage('Usage: $0 -x NUM -y NUM')
.check(checker)
.argv;
});
t.same(r, {
result : { x : 10, y : 20, _ : [], $0 : './usage' },
errors : [],
logs : [],
exit : false,
});
t.end();
});
test('checkCondFail', function (t) {
function checker (argv) {
return 'x' in argv && 'y' in argv;
}
var r = checkUsage(function () {
return optimist('-x 10 -z 20'.split(' '))
.usage('Usage: $0 -x NUM -y NUM')
.check(checker)
.argv;
});
t.same(
r.result,
{ x : 10, z : 20, _ : [], $0 : './usage' }
);
t.same(
r.errors.join('\n').split(/\n+/).join('\n'),
'Usage: ./usage -x NUM -y NUM\n'
+ 'Argument check failed: ' + checker.toString()
);
t.same(r.logs, []);
t.ok(r.exit);
t.end();
});
test('countPass', function (t) {
var r = checkUsage(function () {
return optimist('1 2 3 --moo'.split(' '))
.usage('Usage: $0 [x] [y] [z] {OPTIONS}')
.demand(3)
.argv;
});
t.same(r, {
result : { _ : [ '1', '2', '3' ], moo : true, $0 : './usage' },
errors : [],
logs : [],
exit : false,
});
t.end();
});
test('countFail', function (t) {
var r = checkUsage(function () {
return optimist('1 2 --moo'.split(' '))
.usage('Usage: $0 [x] [y] [z] {OPTIONS}')
.demand(3)
.argv;
});
t.same(
r.result,
{ _ : [ '1', '2' ], moo : true, $0 : './usage' }
);
t.same(
r.errors.join('\n').split(/\n+/),
[
'Usage: ./usage [x] [y] [z] {OPTIONS}',
'Not enough non-option arguments: got 2, need at least 3',
]
);
t.same(r.logs, []);
t.ok(r.exit);
t.end();
});
test('defaultSingles', function (t) {
var r = checkUsage(function () {
return optimist('--foo 50 --baz 70 --powsy'.split(' '))
.default('foo', 5)
.default('bar', 6)
.default('baz', 7)
.argv
;
});
t.same(r.result, {
foo : '50',
bar : 6,
baz : '70',
powsy : true,
_ : [],
$0 : './usage',
});
t.end();
});
test('defaultAliases', function (t) {
var r = checkUsage(function () {
return optimist('')
.alias('f', 'foo')
.default('f', 5)
.argv
;
});
t.same(r.result, {
f : '5',
foo : '5',
_ : [],
$0 : './usage',
});
t.end();
});
test('defaultHash', function (t) {
var r = checkUsage(function () {
return optimist('--foo 50 --baz 70'.split(' '))
.default({ foo : 10, bar : 20, quux : 30 })
.argv
;
});
t.same(r.result, {
_ : [],
$0 : './usage',
foo : 50,
baz : 70,
bar : 20,
quux : 30,
});
t.end();
});
test('rebase', function (t) {
t.equal(
optimist.rebase('/home/substack', '/home/substack/foo/bar/baz'),
'./foo/bar/baz'
);
t.equal(
optimist.rebase('/home/substack/foo/bar/baz', '/home/substack'),
'../../..'
);
t.equal(
optimist.rebase('/home/substack/foo', '/home/substack/pow/zoom.txt'),
'../pow/zoom.txt'
);
t.end();
});
function checkUsage (f) {
var exit = false;
process._exit = process.exit;
process._env = process.env;
process._argv = process.argv;
process.exit = function (t) { exit = true };
process.env = Hash.merge(process.env, { _ : 'node' });
process.argv = [ './usage' ];
var errors = [];
var logs = [];
console._error = console.error;
console.error = function (msg) { errors.push(msg) };
console._log = console.log;
console.log = function (msg) { logs.push(msg) };
var result = f();
process.exit = process._exit;
process.env = process._env;
process.argv = process._argv;
console.error = console._error;
console.log = console._log;
return {
errors : errors,
logs : logs,
exit : exit,
result : result,
};
};
TODO
v0.5.0
+ Major cleanup
+ Remove old unused functionality
+ Load modules in parallel (faster dev mode)
v0.4.9
+ Make the max length of lines an option and make it quite short by default for easier debugging
v0.4.7
+ Remove default port and host - just use what the current page uses by default
+ Treat Android devices as mobile, with regards to loading resources in one big response rather than individual requests
+ Now works if script include put in head
v0.4.6
+ Add server.setOpts and server.handleRequest
v0.4.5
+ Set the mimetype of script files correctly
+ Remove node_modules directory - use dependencies in package.json instead
+ Implement addPath and addFile for specifying custom path resolutions
+ Implement addReplacement for replacing code during dev serving or compilation
+ Implement dontAddClosureForModule and dontIncludeModule for compiler
+ Remove dependency on std.js
+ Add usePagePort option to make module requests go to the host/port of the page it's served on, rather than the host/port passed in to listen(port, ...)
v0.4.4
+ Import js files directly under node_modules correctly, e.g. ./node_modules/foo.js
v0.4.3
+ Fix import of socket.io browser npm module
+ Enable nested npm module imports by reimplementing node's require.resolve algorithm
v0.4.2
+ Use uglifyjs to compress JS
+ Synchronous compilation API
+ Remove --paths option. Search for modules exactly like require.resolve does
+ Greatle simplify Readme instructions
+ Use util.resolve in compiler, minimizing repeated code
+ Implement require.mount(server, opts) - mounts itself onto an existing http server
+ Implement require.connect(opts) - connect middleware
+ Implement require.isRequireRequest - checks if an http request is for the require server
v0.4.1
+ Consult package.json's "main" field when resolving modules in the compiler
+ Fix bug where modules starting with (function() { ... }) would throw in their compiled form
+ Clearer compiler usage example in example/compile.js
+ Better error messages when a module cannot be found during compilation
v0.4.0
+ New API
+ New command line utility
+ New documentation
v0.3.2
+ Improved command line tool
+ new API: single method require('require/compiler').compile(<code | file path>, <compilation level 0 | 1 | 2 | 3>, <callback>)
+ allow chaining of methods on the require server
+ alert an error message client-side when a module is not found (rather than crash the process :)
v0.3.1
+ Fix context bug in delay
+ Change compiled instances of require._[PATH] to require[PATH]. require is simply a hash of module paths.
+ Add setRoot API
+ Improved docs in README
+ Binary request-dev --port 1234 --host localhost ./path
v0.3.0
+ Make a standalone server for dev mode
v0.2.8
+ Don't leave require.paths modified after require.resolve. Add paths right before they're needed, and remove paths after.
v0.2.7
+ Improve path resolution
v0.2.6
+ Improve the order in which we try to load modules
v0.2.5
+ Fix compilation order for __main__
v0.2.1
+ A development server that serves requires files in dev mode
v0.2.0
+ latest version published on npm
v0.1.13
+ better file layout - bin/ lib/
+ created bin/compile to compile files
+ created bin/compress to compile and compress files
+ improved readability of compiled files by flattening the require hierarchy
+ replace module names with short names, e.g. "_1", "_2", etc
v0.1.12
+ Support module path names in the compiler, e.g. require('require/compiler')
v0.1.11
+ Fix: compiler now resolves module/index.js paths correctly
v0.1.10
+ Allow for a node server to server require using require('require').toString()
v0.1.9
+ It's no longer required to add id="browser-require" to a script tag in order to load the main module automatically
v0.1.8
+ Rename to require
v0.1.7
+ Publish with npm
v0.1.6
+ Fix: Variables declared inside of require.js are no longer visible to imported modules
+ Remove the "root" configuration parameter added in v0.1.1. You cannot modify the root in node.
v0.1.5
+ Allow for a file inside of a folder to import the folder's index file with require('./')
v0.1.4
+ Allow modules with circular dependencies to reference each other
v0.1.3
+ Don't get stuck loading circular dependencies
v0.1.2
+ Support index.js - if a module is not found at location, look for it at location/index.js
v0.1.1
+ Support the "root" configuration parameter
+ Fix: consecutive slashes get replaced with a single slash as opposed to no slash
v0.1.0
First version, implements node's require() statement for the browser
Copyright (c) 2011 Marcus Westin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\ No newline at end of file
require brings `require` to the browser
=======================================
Node's `require()` is the de facto javascript dependency statement.
`npm` is the de facto javascript module manager.
require brings both of them to the browser.
tl;dr
=====
"Just give me some code that runs"
mkdir app; cd app
echo '{ "name":"app" }' > package.json
sudo npm install require
sudo npm install raphael
curl -O https://raw.github.com/gist/975866/little_server.js
curl -O https://raw.github.com/gist/975868/little_client.js
node little_server.js
Now go to http://localhost:8080
Install
=======
sudo npm install -g require
Run
===
Start dev server
require serve ./example --port 1234 --host localhost
In your HTML:
<script src="//localhost:1234/require/client"></script>
This is like calling require('client') from inside ./example.
[Read more on node's require path resolution](http://nodejs.org/api/modules.html)
Compile
=======
(You'll want to do this before you deploy to production)
require compile ./example/client.js > client.min.js
Use programmatically
====================
In node:
require('require/server').listen(1234)
or mount it on an http server you're already running
var server = http.createServer(function(req, res) { })
require('require/server').mount(server)
server.listen(8080, 'localhost')
or, as connect middleware
connect.createServer(
connect.static(__dirname + '/example'),
require('require/server').connect()
)
Compile programmatically:
var compiler = require('require/compiler')
console.log(compiler.compile('./example/client.js'))
console.log(compiler.compileCode('require("./example/client")'))
The compiler supports all the options of https://github.com/mishoo/UglifyJS, e.g.
compiler.compile('./example/client.js', { beautify:true, ascii_only:true })
#!/usr/bin/env node
var path = require('path'),
server = require('../server'),
compiler = require('../compiler')
var opts = {
port: 1234,
host: 'localhost',
command: null,
path: null
}
var args = [].slice.call(process.argv, 2)
opts.command = args.shift()
opts.path = path.resolve(args.shift())
while (args.length) {
var arg = args.shift()
switch(arg) {
case '--port':
opts.port = args.shift()
break
case '--host':
opts.host = args.shift()
break
case '--root':
opts.root = args.shift()
break
case '--usePagePort':
if (args[0] && args[0][0] != '-') {
console.log('Unexpected value for --usePagePort flag', args[0])
process.exit(1)
}
opts.usePagePort = true
break
default:
console.log('Unknown option', arg)
process.exit(1)
break
}
}
switch (opts.command) {
case 'serve':
if (!opts.path) {
console.log('Specify a path to serve from, e.g. require serve ./example')
process.exit(1)
}
server.listen(opts)
console.log('serving from', opts.path, 'on', 'http://'+opts.host+':'+opts.port)
break
case 'compile':
if (!opts.path) {
console.log('Specify a single file to compile, e.g. require compile ./path/to/file.js')
process.exit(1)
}
console.log(compiler.compile(opts.path))
break
default:
if (opts.command) {
console.log('Unknown command', '"' + opts.command + '".', 'Try "require serve" or "require compile"')
} else {
console.log('You need to give a command, e.g. "require serve" or "require compile"')
}
process.exit(1)
}
var fs = require('fs')
var path = require('path')
var extend = require('std/extend')
var each = require('std/each')
var getCode = require('./lib/getCode')
var resolve = require('./lib/resolve')
var getRequireStatements = require('./lib/getRequireStatements')
module.exports = {
compile: compileFile,
compileHTML: compileHTMLFile,
compileCode: compileCode
}
/* api
*****/
function compileFile(filePath, opts) {
filePath = path.resolve(filePath)
opts = extend(opts, { basePath:path.dirname(filePath), toplevel:true })
var code = getCode(filePath)
return _compile(code, opts, filePath)
}
function compileCode(code, opts) {
opts = extend(opts, { basePath:process.cwd(), toplevel:true })
return _compile(code, opts, '<code passed into compiler.compile()>')
}
function compileHTMLFile(filePath, opts) {
var html = fs.readFileSync(filePath).toString()
while (match = html.match(/<script src="\/require\/([\/\w\.]+)"><\/script>/)) {
var js = compileFile(match[1].toString(), opts)
var BACKREFERENCE_WORKAROUND = '____________backreference_workaround________'
js = js.replace('\$\&', BACKREFERENCE_WORKAROUND)
html = html.replace(match[0], '<script>'+js+'</script>')
html = html.replace(BACKREFERENCE_WORKAROUND, '\$\&')
}
return html
}
var _compile = function(code, opts, mainModule) {
var code = 'var __require__ = {}, require=function(){}\n' + _compileModule(code, opts.basePath, mainModule)
if (opts.minify === false) { return code } // TODO use uglifyjs' beautifier?
var UglifyJS = require('uglify-js')
var result = UglifyJS.minify(code, {
fromString:true,
mangle:true,
output: {
// http://lisperator.net/uglifyjs/codegen
indent_start : 0, // start indentation on every line (only when `beautify`)
indent_level : 4, // indentation level (only when `beautify`)
quote_keys : false, // quote all keys in object literals?
space_colon : true, // add a space after colon signs?
ascii_only : false, // output ASCII-safe? (encodes Unicode characters as ASCII)
inline_script : false, // escape "</script"?
width : 80, // informative maximum line width (for beautified output)
max_line_len : 200, // maximum line length (for non-beautified output)
ie_proof : true, // output IE-safe code?
beautify : false, // beautify output?
source_map : null, // output a source map
bracketize : false, // use brackets every time?
comments : false, // output comments?
semicolons : true // use semicolons to separate statements? (otherwise, newlines)
},
compress: {
// http://lisperator.net/uglifyjs/compress
sequences : true, // join consecutive statemets with the “comma operator”
properties : true, // optimize property access: a["foo"] → a.foo
dead_code : true, // discard unreachable code
drop_debugger : true, // discard “debugger” statements
unsafe : false, // some unsafe optimizations (see below)
conditionals : true, // optimize if-s and conditional expressions
comparisons : true, // optimize comparisons
evaluate : true, // evaluate constant expressions
booleans : true, // optimize boolean expressions
loops : true, // optimize loops
unused : true, // drop unused variables/functions
hoist_funs : true, // hoist function declarations
hoist_vars : false, // hoist variable declarations
if_return : true, // optimize if-s followed by return/continue
join_vars : true, // join var declarations
cascade : true, // try to cascade `right` into `left` in sequences
side_effects : true, // drop side-effect-free statements
warnings : false, // warn about potentially dangerous optimizations/code
global_defs : {} // global definitions
}
})
// also see result.map
return result.code
}
/* util
******/
var _compileModule = function(code, pathBase, mainModule) {
var modules = [mainModule]
_replaceRequireStatements(mainModule, code, modules, pathBase)
code = _concatModules(modules)
code = _minifyRequireStatements(code, modules)
return code
}
var _minifyRequireStatements = function(code, modules) {
each(modules, function(modulePath, i) {
var escapedPath = modulePath.replace(/\//g, '\\/').replace('(','\\(').replace(')','\\)')
var regex = new RegExp('__require__\\["'+ escapedPath +'"\\]', 'g')
code = code.replace(regex, '__require__["_'+ i +'"]')
})
return code
}
var _replaceRequireStatements = function(modulePath, code, modules, pathBase) {
var requireStatements = getRequireStatements(code)
if (!requireStatements.length) {
modules[modulePath] = code
return
}
each(requireStatements, function(requireStatement) {
var subModulePath = resolve.requireStatement(requireStatement, modulePath)
if (!subModulePath) {
throw new Error("Require Compiler Error: Cannot find module '"+ rawModulePath +"' (in '"+ modulePath +"')")
}
code = code.replace(requireStatement, '__require__["' + subModulePath + '"].exports')
if (!modules[subModulePath]) {
modules[subModulePath] = true
var newPathBase = path.dirname(subModulePath)
var newModuleCode = getCode(subModulePath)
_replaceRequireStatements(subModulePath, newModuleCode, modules, newPathBase)
modules.push(subModulePath)
}
})
modules[modulePath] = code
}
var _concatModules = function(modules) {
var getClosuredModule = function(modulePath) {
return [
';(function() {',
' // ' + modulePath,
' var module = __require__["'+modulePath+'"] = {exports:{}}, exports = module.exports;',
modules[modulePath],
'})()'
].join('\n')
}
var moduleDefinitions = []
for (var i=1, modulePath; modulePath = modules[i]; i++) {
moduleDefinitions.push(getClosuredModule(modulePath))
}
moduleDefinitions.push(getClosuredModule(modules[0])) // __main__
return moduleDefinitions.join('\n\n')
}
var dependency = require('./shared/dependency')
var el = document.body.appendChild(document.createElement('div'))
el.innerHTML = 'shared dependency:' + JSON.stringify(dependency)
var fs = require('fs'),
compiler = require('../compiler')
var file = __dirname + '/client.js',
basePath = __dirname,
code = fs.readFileSync(file).toString()
console.log(compiler.compileCode(code, { basePath:__dirname }))
var connect = require('connect'),
requireServer = require('require/server')
connect.createServer(
connect.static(__dirname),
requireServer.connect(__dirname)
).listen(8080)
<!doctype html>
<html>
<head>
<title>test</title>
</head>
<body>
<script src="/require/client"></script>
</body>
{
"author": "",
"name": "testApp",
"version": "0.0.0",
"repository": {
"url": ""
},
"directories": {
"lib": "."
},
"engines": {
"node": "*"
},
"dependencies": {},
"devDependencies": {}
}
\ No newline at end of file
<body>
<script src="//localhost:1234/raphael_circle"></script>
</body>
var raphael = require('raphael'),
canvas = document.body.appendChild(document.createElement('div')),
paper = raphael(canvas)
paper.circle(50, 50, 40)
var http = require('http'),
fs = require('fs'),
dependency = require('./shared/dependency'),
requireServer = require('../server') // this would be require('require/server') in most applications
var base = __dirname + '/',
root = 'require'
var server = http.createServer(function(req, res) {
if (requireServer.isRequireRequest(req)) { return }
fs.readFile(base + (req.url.substr(1) || 'index.html'), function(err, content) {
if (err) { return res.end(err.stack) }
res.end(content)
})
})
requireServer.mount(server, __dirname)
server.listen(8080)
console.log('shared dependency:', dependency)
module.exports = {
foo: 'bar',
cat: 'qwe'
}
var fs = require('fs')
module.exports = function readCode(filePath) {
if (!filePath.match(/\.js$/)) { filePath += '.js' }
return fs.readFileSync(filePath).toString()
}
\ No newline at end of file
var each = require('std/each')
var getCode = require('./getCode')
var getRequireStatements = require('./getRequireStatements')
var resolve = require('./resolve')
module.exports = getDependencyLevels
function getDependencyLevels(mainModulePath) {
var leaves = []
var root = []
root.isRoot = true
root.path = mainModulePath
_buildDependencyTreeOf(root)
var levels = []
var seenPaths = {}
_buildLevel(leaves)
return levels
// builds full dependency tree, noting every dependency of every node
function _buildDependencyTreeOf(node) {
var requireStatements = getRequireStatements(getCode(node.path))
if (requireStatements.length == 0) {
return leaves.push(node)
}
each(requireStatements, function(requireStatement) {
var childNode = []
childNode.path = resolve.requireStatement(requireStatement, node.path)
childNode.parent = node
node.push(childNode)
_buildDependencyTreeOf(childNode)
})
node.waitingForNumChildren = node.length
}
// builds a list of dependency levels, where nodes in each level is dependent only on nodes in levels below it
// the dependency levels allow for parallel loading of every file in any given level
function _buildLevel(nodes) {
var level = []
levels.push(level)
var parents = []
each(nodes, function(node) {
if (!seenPaths[node.path]) {
seenPaths[node.path] = true
level.push(node.path)
}
if (node.isRoot) { return }
node.parent.waitingForNumChildren -= 1
if (node.parent.waitingForNumChildren == 0) {
parents.push(node.parent)
}
})
if (!parents.length) { return }
_buildLevel(parents)
}
}
module.exports = getRequireStatements
var _globalRequireRegex = /require\s*\(['"][\w\/\.-]*['"]\)/g
function getRequireStatements(code) {
return code.match(_globalRequireRegex) || []
}
var path = require('path')
var fs = require('fs')
var existsSync = fs.existsSync || path.existsSync
var _nodePaths = (process.env.NODE_PATH ? process.env.NODE_PATH.split(':') : [])
_nodePaths.push(process.cwd())
module.exports = {
path: resolvePath,
_nodePaths:_nodePaths,
requireStatement: resolveRequireStatement
}
function resolvePath(searchPath, pathBase) {
if (searchPath[0] == '.') {
// relative path, e.g. require("./foo")
return _findModuleMain(path.resolve(pathBase, searchPath))
}
var searchParts = searchPath.split('/')
var componentName = searchParts[searchParts.length - 1]
var name = searchParts.shift()
var rest = searchParts.join('/')
// npm-style path, e.g. require("npm").
// Climb parent directories in search for "node_modules"
var modulePath = _findModuleMain(path.resolve(pathBase, 'node_modules', searchPath))
if (modulePath) { return modulePath }
if (pathBase != '/') {
// not yet at the root - keep climbing!
return resolvePath(searchPath, path.resolve(pathBase, '..'))
}
return ''
}
var _pathnameGroupingRegex = /require\s*\(['"]([\w\/\.-]*)['"]\)/
function resolveRequireStatement(requireStmnt, currentPath) {
var rawPath = requireStmnt.match(_pathnameGroupingRegex)[1]
var resolvedPath = resolvePath(rawPath, path.dirname(currentPath))
if (!resolvedPath && rawPath[0] != '.' && rawPath[0] != '/') {
for (var i=0; i<_nodePaths.length; i++) {
resolvedPath = _findModuleMain(path.resolve(_nodePaths[i], rawPath))
if (resolvedPath) { break }
}
}
if (!resolvedPath) { throw 'Could not resolve "'+rawPath+'" in "'+currentPath+'"' }
return resolvedPath
}
function _findModuleMain(absModulePath, tryFileName) {
var foundPath = ''
function attempt(aPath) {
if (foundPath) { return }
if (existsSync(aPath)) { foundPath = aPath }
}
attempt(absModulePath + '.js')
try {
var package = JSON.parse(fs.readFileSync(absModulePath + '/package.json').toString())
attempt(path.resolve(absModulePath, package.main+'.js'))
attempt(path.resolve(absModulePath, package.main))
} catch(e) {}
attempt(absModulePath + '/index.js')
if (tryFileName) { attempt(absModulePath + '/' + tryFileName + '.js') }
return foundPath
}
{
"_from": "require",
"_id": "require@2.4.20",
"_inBundle": false,
"_integrity": "sha1-Zstrqqu2XeinHXk/XGX9GE83mLY=",
"_location": "/require",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "require",
"name": "require",
"escapedName": "require",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/require/-/require-2.4.20.tgz",
"_shasum": "66cb6baaabb65de8a71d793f5c65fd184f3798b6",
"_spec": "require",
"_where": "D:\\OneDrive\\University Life\\2018\\2nd semester\\OpenSourceSoftware\\KaKao_ChatBot",
"author": {
"name": "Marcus Westin",
"email": "narcvs@gmail.com",
"url": "http://marcuswest.in"
},
"bin": {
"require": "./bin/require-command.js"
},
"bugs": {
"url": "https://github.com/marcuswestin/require/issues"
},
"bundleDependencies": false,
"dependencies": {
"std": "0.1.40",
"uglify-js": "2.3.0"
},
"deprecated": false,
"description": "javascript module management! brings node's require statement to the browser",
"devDependencies": {},
"directories": {},
"engines": {
"browsers": "*",
"node": "*"
},
"homepage": "https://github.com/marcuswestin/require",
"main": "./require",
"name": "require",
"repository": {
"type": "git",
"url": "git://github.com/marcuswestin/require.git"
},
"scripts": {
"start": "node server.js"
},
"version": "2.4.20"
}
var http = require('http')
var fs = require('fs')
var path = require('path')
var extend = require('std/extend')
var isObject = require('std/isObject')
var map = require('std/map')
var each = require('std/each')
var getDependencyLevels = require('./lib/getDependencyLevels')
var getRequireStatements = require('./lib/getRequireStatements')
var getCode = require('./lib/getCode')
var resolve = require('./lib/resolve')
module.exports = {
listen: listen,
mount: mount,
connect: connect,
isRequireRequest: isRequireRequest,
handleRequest: handleRequest
}
function listen(portOrOpts) {
var _opts = (isObject(portOrOpts) ? portOrOpts : { port:portOrOpts || 1234 })
opts.handleAllRequests = true
mount(http.createServer(), _opts).listen(opts.port, opts.host)
}
function mount(server, _opts) {
setOpts(_opts)
return server.on('request', _checkRequest)
}
function connect(opts) {
setOpts(opts)
return _checkRequest
}
function _checkRequest(req, res, next) {
if (isRequireRequest(req) || opts.handleAllRequests) {
handleRequest(req, res)
} else {
next && next()
}
}
function isRequireRequest(req) {
return req.url.substr(1, opts.root.length) == opts.root
}
/* options
*********/
var opts = {
path: process.cwd(),
root: 'require',
port: null,
host: null
}
function setOpts(_opts) {
opts = extend(_opts, opts)
if (opts.path) {
resolve._nodePaths.push(opts.path)
}
}
function getUrlBase() {
var basePort = (!opts.usePagePort && opts.port)
if (opts.host && basePort) {
return '//' + opts.host + ':' + basePort + '/' + opts.root + '/'
} else {
return '/' + opts.root + '/'
}
}
/* request handlers
******************/
function handleRequest(req, res) {
var reqPath = _normalizeURL(req.url).substr(opts.root.length + 2)
if (reqPath.match(/\.js$/)) {
_handleModuleRequest(reqPath, res)
} else {
_handleMainModuleRequest(reqPath, req, res)
}
function _normalizeURL(url) {
return url.replace(/\?.*/g, '').replace(/\/js$/, '.js')
}
}
function _handleMainModuleRequest(reqPath, req, res) {
var mainModulePath = resolve.path('./' + reqPath, opts.path)
if (!mainModulePath) { return _sendError(res, 'Could not find module "'+reqPath+'" from "'+opts.path+'"') }
try { var dependencyTree = getDependencyLevels(mainModulePath) }
catch(err) { return _sendError(res, 'in getDependencyLevels: ' + (err.message || err)) }
var userAgent = req.headers['user-agent']
var isMobile = userAgent.match('iPad') || userAgent.match('iPod') || userAgent.match('iPhone') || userAgent.match('Android')
var response = isMobile ? _getMobilePayload() : _getNormalPayload()
res.writeHead(200, { 'Cache-Control':'no-cache', 'Expires':'Fri, 31 Dec 1998 12:00:00 GMT', 'Content-Length':response.length, 'Content-Type':'text/javascript' })
res.end(response)
function _getMobilePayload() {
var result = ['__require__={loadNextModule:function(){},onModuleLoaded:function(){}}']
each(dependencyTree, function(level) {
each(level, function(dependency) {
result.push(';(function(){ '+_getModuleCode(res, dependency)+' }());')
})
})
return new Buffer(result.join('\n'))
}
function _getNormalPayload() {
var paramsString = map([getUrlBase(), dependencyTree], JSON.stringify).join(',\n\t\t')
return new Buffer('\t('+clientBootstrapFn.toString()+')(\n\t\t'+paramsString+'\n\t)')
function clientBootstrapFn(urlBase, levels) {
// This function gets sent to the client as toString
__require__ = {
loadNextLevel: loadNextLevel,
onModuleLoaded: onModuleLoaded
}
var currentLevel = null
loadNextLevel()
function loadNextLevel() {
if (!levels.length) { return } // all done!
currentLevel = levels.shift()
var head = document.getElementsByTagName('head')[0]
for (var i=0; i<currentLevel.length; i++) {
// var url = location.protocol + '//' + location.host + urlBase + currentLevel[i]
var url = urlBase + currentLevel[i]
head.appendChild(document.createElement('script')).src = url
}
}
function onModuleLoaded() {
currentLevel.pop()
if (currentLevel.length == 0) {
loadNextLevel()
}
}
}
}
}
function _asString(fn) { return fn.toString() }
function _handleModuleRequest(reqPath, res) {
try { var code = _getModuleCode(res, reqPath) }
catch(err) { return _sendError(res, err.stack || err) }
code += '\n\n'
var buf = new Buffer(code)
res.writeHead(200, { 'Cache-Control':'no-cache', 'Expires':'Fri, 31 Dec 1998 12:00:00 GMT', 'Content-Length':buf.length, 'Content-Type':'text/javascript' })
res.end(buf)
}
function _getModuleCode(res, reqPath) {
var code = getCode(reqPath)
var requireStatements = getRequireStatements(code)
try {
each(requireStatements, function(requireStmnt) {
var depPath = resolve.requireStatement(requireStmnt, reqPath)
if (!depPath) { throw 'Could not resolve module' }
code = code.replace(requireStmnt, '__require__["'+depPath+'"]')
})
} catch(e) {
_sendError(res, e.message || e)
}
var _closureStart = ';(function(){'
var _moduleDef = 'var module={exports:{}},exports=module.exports;/*FILE BEGIN*/ '
var _closureEnd = '/*FILE END*/__require__["'+reqPath+'"]=module.exports; __require__.onModuleLoaded()\n})()'
return _closureStart + _moduleDef + code + // all on the first line to make error line number reports correct
'\n' + _closureEnd
}
function _sendError(res, msg) {
if (msg) { msg = msg.replace(/\n/g, '\\n').replace(/"/g, '\\"') }
res.writeHead(200)
res.end('alert("error: ' + msg + '")')
}
language: node_js
node_js:
- 0.8
- "0.10"
\ No newline at end of file
# Change Log
## 0.1.43
* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue
#148 for some discussion and issues #150, #151, and #152 for implementations.
## 0.1.42
* Fix an issue where `SourceNode`s from different versions of the source-map
library couldn't be used in conjunction with each other. See issue #142.
## 0.1.41
* Fix a bug with getting the source content of relative sources with a "./"
prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768).
* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the
column span of each mapping.
* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find
all generated positions associated with a given original source and line.
## 0.1.40
* Performance improvements for parsing source maps in SourceMapConsumer.
## 0.1.39
* Fix a bug where setting a source's contents to null before any source content
had been set before threw a TypeError. See issue #131.
## 0.1.38
* Fix a bug where finding relative paths from an empty path were creating
absolute paths. See issue #129.
## 0.1.37
* Fix a bug where if the source root was an empty string, relative source paths
would turn into absolute source paths. Issue #124.
## 0.1.36
* Allow the `names` mapping property to be an empty string. Issue #121.
## 0.1.35
* A third optional parameter was added to `SourceNode.fromStringWithSourceMap`
to specify a path that relative sources in the second parameter should be
relative to. Issue #105.
* If no file property is given to a `SourceMapGenerator`, then the resulting
source map will no longer have a `null` file property. The property will
simply not exist. Issue #104.
* Fixed a bug where consecutive newlines were ignored in `SourceNode`s.
Issue #116.
## 0.1.34
* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103.
* Fix bug involving source contents and the
`SourceMapGenerator.prototype.applySourceMap`. Issue #100.
## 0.1.33
* Fix some edge cases surrounding path joining and URL resolution.
* Add a third parameter for relative path to
`SourceMapGenerator.prototype.applySourceMap`.
* Fix issues with mappings and EOLs.
## 0.1.32
* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns
(issue 92).
* Fixed test runner to actually report number of failed tests as its process
exit code.
* Fixed a typo when reporting bad mappings (issue 87).
## 0.1.31
* Delay parsing the mappings in SourceMapConsumer until queried for a source
location.
* Support Sass source maps (which at the time of writing deviate from the spec
in small ways) in SourceMapConsumer.
## 0.1.30
* Do not join source root with a source, when the source is a data URI.
* Extend the test runner to allow running single specific test files at a time.
* Performance improvements in `SourceNode.prototype.walk` and
`SourceMapConsumer.prototype.eachMapping`.
* Source map browser builds will now work inside Workers.
* Better error messages when attempting to add an invalid mapping to a
`SourceMapGenerator`.
## 0.1.29
* Allow duplicate entries in the `names` and `sources` arrays of source maps
(usually from TypeScript) we are parsing. Fixes github issue 72.
## 0.1.28
* Skip duplicate mappings when creating source maps from SourceNode; github
issue 75.
## 0.1.27
* Don't throw an error when the `file` property is missing in SourceMapConsumer,
we don't use it anyway.
## 0.1.26
* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70.
## 0.1.25
* Make compatible with browserify
## 0.1.24
* Fix issue with absolute paths and `file://` URIs. See
https://bugzilla.mozilla.org/show_bug.cgi?id=885597
## 0.1.23
* Fix issue with absolute paths and sourcesContent, github issue 64.
## 0.1.22
* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21.
## 0.1.21
* Fixed handling of sources that start with a slash so that they are relative to
the source root's host.
## 0.1.20
* Fixed github issue #43: absolute URLs aren't joined with the source root
anymore.
## 0.1.19
* Using Travis CI to run tests.
## 0.1.18
* Fixed a bug in the handling of sourceRoot.
## 0.1.17
* Added SourceNode.fromStringWithSourceMap.
## 0.1.16
* Added missing documentation.
* Fixed the generating of empty mappings in SourceNode.
## 0.1.15
* Added SourceMapGenerator.applySourceMap.
## 0.1.14
* The sourceRoot is now handled consistently.
## 0.1.13
* Added SourceMapGenerator.fromSourceMap.
## 0.1.12
* SourceNode now generates empty mappings too.
## 0.1.11
* Added name support to SourceNode.
## 0.1.10
* Added sourcesContent support to the customer and generator.
Copyright (c) 2009-2011, Mozilla Foundation and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of the Mozilla Foundation nor the names of project
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var path = require('path');
var fs = require('fs');
var copy = require('dryice').copy;
function removeAmdefine(src) {
src = String(src).replace(
/if\s*\(typeof\s*define\s*!==\s*'function'\)\s*{\s*var\s*define\s*=\s*require\('amdefine'\)\(module,\s*require\);\s*}\s*/g,
'');
src = src.replace(
/\b(define\(.*)('amdefine',?)/gm,
'$1');
return src;
}
removeAmdefine.onRead = true;
function makeNonRelative(src) {
return src
.replace(/require\('.\//g, 'require(\'source-map/')
.replace(/\.\.\/\.\.\/lib\//g, '');
}
makeNonRelative.onRead = true;
function buildBrowser() {
console.log('\nCreating dist/source-map.js');
var project = copy.createCommonJsProject({
roots: [ path.join(__dirname, 'lib') ]
});
copy({
source: [
'build/mini-require.js',
{
project: project,
require: [ 'source-map/source-map-generator',
'source-map/source-map-consumer',
'source-map/source-node']
},
'build/suffix-browser.js'
],
filter: [
copy.filter.moduleDefines,
removeAmdefine
],
dest: 'dist/source-map.js'
});
}
function buildBrowserMin() {
console.log('\nCreating dist/source-map.min.js');
copy({
source: 'dist/source-map.js',
filter: copy.filter.uglifyjs,
dest: 'dist/source-map.min.js'
});
}
function buildFirefox() {
console.log('\nCreating dist/SourceMap.jsm');
var project = copy.createCommonJsProject({
roots: [ path.join(__dirname, 'lib') ]
});
copy({
source: [
'build/prefix-source-map.jsm',
{
project: project,
require: [ 'source-map/source-map-consumer',
'source-map/source-map-generator',
'source-map/source-node' ]
},
'build/suffix-source-map.jsm'
],
filter: [
copy.filter.moduleDefines,
removeAmdefine,
makeNonRelative
],
dest: 'dist/SourceMap.jsm'
});
// Create dist/test/Utils.jsm
console.log('\nCreating dist/test/Utils.jsm');
project = copy.createCommonJsProject({
roots: [ __dirname, path.join(__dirname, 'lib') ]
});
copy({
source: [
'build/prefix-utils.jsm',
'build/assert-shim.js',
{
project: project,
require: [ 'test/source-map/util' ]
},
'build/suffix-utils.jsm'
],
filter: [
copy.filter.moduleDefines,
removeAmdefine,
makeNonRelative
],
dest: 'dist/test/Utils.jsm'
});
function isTestFile(f) {
return /^test\-.*?\.js/.test(f);
}
var testFiles = fs.readdirSync(path.join(__dirname, 'test', 'source-map')).filter(isTestFile);
testFiles.forEach(function (testFile) {
console.log('\nCreating', path.join('dist', 'test', testFile.replace(/\-/g, '_')));
copy({
source: [
'build/test-prefix.js',
path.join('test', 'source-map', testFile),
'build/test-suffix.js'
],
filter: [
removeAmdefine,
makeNonRelative,
function (input, source) {
return input.replace('define(',
'define("'
+ path.join('test', 'source-map', testFile.replace(/\.js$/, ''))
+ '", ["require", "exports", "module"], ');
},
function (input, source) {
return input.replace('{THIS_MODULE}', function () {
return "test/source-map/" + testFile.replace(/\.js$/, '');
});
}
],
dest: path.join('dist', 'test', testFile.replace(/\-/g, '_'))
});
});
}
function ensureDir(name) {
var dirExists = false;
try {
dirExists = fs.statSync(name).isDirectory();
} catch (err) {}
if (!dirExists) {
fs.mkdirSync(name, 0777);
}
}
ensureDir("dist");
ensureDir("dist/test");
buildFirefox();
buildBrowser();
buildBrowserMin();
This diff is collapsed. Click to expand it.
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
define('test/source-map/assert', ['exports'], function (exports) {
let do_throw = function (msg) {
throw new Error(msg);
};
exports.init = function (throw_fn) {
do_throw = throw_fn;
};
exports.doesNotThrow = function (fn) {
try {
fn();
}
catch (e) {
do_throw(e.message);
}
};
exports.equal = function (actual, expected, msg) {
msg = msg || String(actual) + ' != ' + String(expected);
if (actual != expected) {
do_throw(msg);
}
};
exports.ok = function (val, msg) {
msg = msg || String(val) + ' is falsey';
if (!Boolean(val)) {
do_throw(msg);
}
};
exports.strictEqual = function (actual, expected, msg) {
msg = msg || String(actual) + ' !== ' + String(expected);
if (actual !== expected) {
do_throw(msg);
}
};
exports.throws = function (fn) {
try {
fn();
do_throw('Expected an error to be thrown, but it wasn\'t.');
}
catch (e) {
}
};
});
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/**
* Define a module along with a payload.
* @param {string} moduleName Name for the payload
* @param {ignored} deps Ignored. For compatibility with CommonJS AMD Spec
* @param {function} payload Function with (require, exports, module) params
*/
function define(moduleName, deps, payload) {
if (typeof moduleName != "string") {
throw new TypeError('Expected string, got: ' + moduleName);
}
if (arguments.length == 2) {
payload = deps;
}
if (moduleName in define.modules) {
throw new Error("Module already defined: " + moduleName);
}
define.modules[moduleName] = payload;
};
/**
* The global store of un-instantiated modules
*/
define.modules = {};
/**
* We invoke require() in the context of a Domain so we can have multiple
* sets of modules running separate from each other.
* This contrasts with JSMs which are singletons, Domains allows us to
* optionally load a CommonJS module twice with separate data each time.
* Perhaps you want 2 command lines with a different set of commands in each,
* for example.
*/
function Domain() {
this.modules = {};
this._currentModule = null;
}
(function () {
/**
* Lookup module names and resolve them by calling the definition function if
* needed.
* There are 2 ways to call this, either with an array of dependencies and a
* callback to call when the dependencies are found (which can happen
* asynchronously in an in-page context) or with a single string an no callback
* where the dependency is resolved synchronously and returned.
* The API is designed to be compatible with the CommonJS AMD spec and
* RequireJS.
* @param {string[]|string} deps A name, or names for the payload
* @param {function|undefined} callback Function to call when the dependencies
* are resolved
* @return {undefined|object} The module required or undefined for
* array/callback method
*/
Domain.prototype.require = function(deps, callback) {
if (Array.isArray(deps)) {
var params = deps.map(function(dep) {
return this.lookup(dep);
}, this);
if (callback) {
callback.apply(null, params);
}
return undefined;
}
else {
return this.lookup(deps);
}
};
function normalize(path) {
var bits = path.split('/');
var i = 1;
while (i < bits.length) {
if (bits[i] === '..') {
bits.splice(i-1, 1);
} else if (bits[i] === '.') {
bits.splice(i, 1);
} else {
i++;
}
}
return bits.join('/');
}
function join(a, b) {
a = a.trim();
b = b.trim();
if (/^\//.test(b)) {
return b;
} else {
return a.replace(/\/*$/, '/') + b;
}
}
function dirname(path) {
var bits = path.split('/');
bits.pop();
return bits.join('/');
}
/**
* Lookup module names and resolve them by calling the definition function if
* needed.
* @param {string} moduleName A name for the payload to lookup
* @return {object} The module specified by aModuleName or null if not found.
*/
Domain.prototype.lookup = function(moduleName) {
if (/^\./.test(moduleName)) {
moduleName = normalize(join(dirname(this._currentModule), moduleName));
}
if (moduleName in this.modules) {
var module = this.modules[moduleName];
return module;
}
if (!(moduleName in define.modules)) {
throw new Error("Module not defined: " + moduleName);
}
var module = define.modules[moduleName];
if (typeof module == "function") {
var exports = {};
var previousModule = this._currentModule;
this._currentModule = moduleName;
module(this.require.bind(this), exports, { id: moduleName, uri: "" });
this._currentModule = previousModule;
module = exports;
}
// cache the resulting module object for next time
this.modules[moduleName] = module;
return module;
};
}());
define.Domain = Domain;
define.globalDomain = new Domain();
var require = define.globalDomain.require.bind(define.globalDomain);
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/*
* WARNING!
*
* Do not edit this file directly, it is built from the sources at
* https://github.com/mozilla/source-map/
*/
///////////////////////////////////////////////////////////////////////////////
this.EXPORTED_SYMBOLS = [ "SourceMapConsumer", "SourceMapGenerator", "SourceNode" ];
Components.utils.import('resource://gre/modules/devtools/Require.jsm');
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/*
* WARNING!
*
* Do not edit this file directly, it is built from the sources at
* https://github.com/mozilla/source-map/
*/
Components.utils.import('resource://gre/modules/devtools/Require.jsm');
Components.utils.import('resource://gre/modules/devtools/SourceMap.jsm');
this.EXPORTED_SYMBOLS = [ "define", "runSourceMapTests" ];
/* -*- Mode: js; js-indent-level: 2; -*- */
///////////////////////////////////////////////////////////////////////////////
this.sourceMap = {
SourceMapConsumer: require('source-map/source-map-consumer').SourceMapConsumer,
SourceMapGenerator: require('source-map/source-map-generator').SourceMapGenerator,
SourceNode: require('source-map/source-node').SourceNode
};
/* -*- Mode: js; js-indent-level: 2; -*- */
///////////////////////////////////////////////////////////////////////////////
this.SourceMapConsumer = require('source-map/source-map-consumer').SourceMapConsumer;
this.SourceMapGenerator = require('source-map/source-map-generator').SourceMapGenerator;
this.SourceNode = require('source-map/source-node').SourceNode;
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
function runSourceMapTests(modName, do_throw) {
let mod = require(modName);
let assert = require('test/source-map/assert');
let util = require('test/source-map/util');
assert.init(do_throw);
for (let k in mod) {
if (/^test/.test(k)) {
mod[k](assert, util);
}
}
}
this.runSourceMapTests = runSourceMapTests;
/*
* WARNING!
*
* Do not edit this file directly, it is built from the sources at
* https://github.com/mozilla/source-map/
*/
Components.utils.import('resource://test/Utils.jsm');
function run_test() {
runSourceMapTests('{THIS_MODULE}', do_throw);
}
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer;
exports.SourceNode = require('./source-map/source-node').SourceNode;
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var util = require('./util');
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
function ArraySet() {
this._array = [];
this._set = {};
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
};
/**
* Add the given string to this set.
*
* @param String aStr
*/
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var isDuplicate = this.has(aStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
this._set[util.toSetString(aStr)] = idx;
}
};
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
return Object.prototype.hasOwnProperty.call(this._set,
util.toSetString(aStr));
};
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (this.has(aStr)) {
return this._set[util.toSetString(aStr)];
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;
});
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var base64 = require('./base64');
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
var VLQ_BASE_SHIFT = 5;
// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
var VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0
? ((-aValue) << 1) + 1
: (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
/**
* Decodes the next base 64 VLQ value from the given string and returns the
* value and the rest of the string via the out parameter.
*/
exports.decode = function base64VLQ_decode(aStr, aOutParam) {
var i = 0;
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (i >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charAt(i++));
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
aOutParam.value = fromVLQSigned(result);
aOutParam.rest = aStr.slice(i);
};
});
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var charToIntMap = {};
var intToCharMap = {};
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
.split('')
.forEach(function (ch, index) {
charToIntMap[ch] = index;
intToCharMap[index] = ch;
});
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function base64_encode(aNumber) {
if (aNumber in intToCharMap) {
return intToCharMap[aNumber];
}
throw new TypeError("Must be between 0 and 63: " + aNumber);
};
/**
* Decode a single base 64 digit to an integer.
*/
exports.decode = function base64_decode(aChar) {
if (aChar in charToIntMap) {
return charToIntMap[aChar];
}
throw new TypeError("Not a valid base 64 digit: " + aChar);
};
});
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the index of
// the next closest element that is less than that element.
//
// 3. We did not find the exact element, and there is no next-closest
// element which is less than the one we are searching for, so we
// return -1.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return mid;
}
else if (cmp > 0) {
// aHaystack[mid] is greater than our needle.
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
}
// We did not find an exact match, return the next closest one
// (termination case 2).
return mid;
}
else {
// aHaystack[mid] is less than our needle.
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (2) or (3) and return the appropriate thing.
return aLow < 0 ? -1 : aLow;
}
}
/**
* This is an implementation of binary search which will always try and return
* the index of next lowest value checked if there is no exact hit. This is
* because mappings between original and generated line/col pairs are single
* points, and there is an implicit region between each of them, so a miss
* just means that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
*/
exports.search = function search(aNeedle, aHaystack, aCompare) {
if (aHaystack.length === 0) {
return -1;
}
return recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
};
});
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2014 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var util = require('./util');
/**
* Determine whether mappingB is after mappingA with respect to generated
* position.
*/
function generatedPositionAfter(mappingA, mappingB) {
// Optimized for most common case
var lineA = mappingA.generatedLine;
var lineB = mappingB.generatedLine;
var columnA = mappingA.generatedColumn;
var columnB = mappingB.generatedColumn;
return lineB > lineA || lineB == lineA && columnB >= columnA ||
util.compareByGeneratedPositions(mappingA, mappingB) <= 0;
}
/**
* A data structure to provide a sorted view of accumulated mappings in a
* performance conscious manner. It trades a neglibable overhead in general
* case for a large speedup in case of mappings being added in order.
*/
function MappingList() {
this._array = [];
this._sorted = true;
// Serves as infimum
this._last = {generatedLine: -1, generatedColumn: 0};
}
/**
* Iterate through internal items. This method takes the same arguments that
* `Array.prototype.forEach` takes.
*
* NOTE: The order of the mappings is NOT guaranteed.
*/
MappingList.prototype.unsortedForEach =
function MappingList_forEach(aCallback, aThisArg) {
this._array.forEach(aCallback, aThisArg);
};
/**
* Add the given source mapping.
*
* @param Object aMapping
*/
MappingList.prototype.add = function MappingList_add(aMapping) {
var mapping;
if (generatedPositionAfter(this._last, aMapping)) {
this._last = aMapping;
this._array.push(aMapping);
} else {
this._sorted = false;
this._array.push(aMapping);
}
};
/**
* Returns the flat, sorted array of mappings. The mappings are sorted by
* generated position.
*
* WARNING: This method returns internal data without copying, for
* performance. The return value must NOT be mutated, and should be treated as
* an immutable borrow. If you want to take ownership, you must make your own
* copy.
*/
MappingList.prototype.toArray = function MappingList_toArray() {
if (!this._sorted) {
this._array.sort(util.compareByGeneratedPositions);
this._sorted = true;
}
return this._array;
};
exports.MappingList = MappingList;
});
This diff is collapsed. Click to expand it.
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
var dataUrlRegexp = /^data:.+\,.+$/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[2],
host: match[3],
port: match[4],
path: match[5]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = '';
if (aParsedUrl.scheme) {
url += aParsedUrl.scheme + ':';
}
url += '//';
if (aParsedUrl.auth) {
url += aParsedUrl.auth + '@';
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
/**
* Normalizes a path, or the path portion of a URL:
*
* - Replaces consequtive slashes with one slash.
* - Removes unnecessary '.' parts.
* - Removes unnecessary '<dir>/..' parts.
*
* Based on code in the Node.js 'path' core module.
*
* @param aPath The path or url to normalize.
*/
function normalize(aPath) {
var path = aPath;
var url = urlParse(aPath);
if (url) {
if (!url.path) {
return aPath;
}
path = url.path;
}
var isAbsolute = (path.charAt(0) === '/');
var parts = path.split(/\/+/);
for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
part = parts[i];
if (part === '.') {
parts.splice(i, 1);
} else if (part === '..') {
up++;
} else if (up > 0) {
if (part === '') {
// The first part is blank if the path is absolute. Trying to go
// above the root is a no-op. Therefore we can remove all '..' parts
// directly after the root.
parts.splice(i + 1, up);
up = 0;
} else {
parts.splice(i, 2);
up--;
}
}
}
path = parts.join('/');
if (path === '') {
path = isAbsolute ? '/' : '.';
}
if (url) {
url.path = path;
return urlGenerate(url);
}
return path;
}
exports.normalize = normalize;
/**
* Joins two paths/URLs.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be joined with the root.
*
* - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
* scheme-relative URL: Then the scheme of aRoot, if any, is prepended
* first.
* - Otherwise aPath is a path. If aRoot is a URL, then its path portion
* is updated with the result and aRoot is returned. Otherwise the result
* is returned.
* - If aPath is absolute, the result is aPath.
* - Otherwise the two paths are joined with a slash.
* - Joining for example 'http://' and 'www.example.com' is also supported.
*/
function join(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
if (aPath === "") {
aPath = ".";
}
var aPathUrl = urlParse(aPath);
var aRootUrl = urlParse(aRoot);
if (aRootUrl) {
aRoot = aRootUrl.path || '/';
}
// `join(foo, '//www.example.org')`
if (aPathUrl && !aPathUrl.scheme) {
if (aRootUrl) {
aPathUrl.scheme = aRootUrl.scheme;
}
return urlGenerate(aPathUrl);
}
if (aPathUrl || aPath.match(dataUrlRegexp)) {
return aPath;
}
// `join('http://', 'www.example.com')`
if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
aRootUrl.host = aPath;
return urlGenerate(aRootUrl);
}
var joined = aPath.charAt(0) === '/'
? aPath
: normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
if (aRootUrl) {
aRootUrl.path = joined;
return urlGenerate(aRootUrl);
}
return joined;
}
exports.join = join;
/**
* Make a path relative to a URL or another path.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be made relative to aRoot.
*/
function relative(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
aRoot = aRoot.replace(/\/$/, '');
// XXX: It is possible to remove this block, and the tests still pass!
var url = urlParse(aRoot);
if (aPath.charAt(0) == "/" && url && url.path == "/") {
return aPath.slice(1);
}
return aPath.indexOf(aRoot + '/') === 0
? aPath.substr(aRoot.length + 1)
: aPath;
}
exports.relative = relative;
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
return '$' + aStr;
}
exports.toSetString = toSetString;
function fromSetString(aStr) {
return aStr.substr(1);
}
exports.fromSetString = fromSetString;
function strcmp(aStr1, aStr2) {
var s1 = aStr1 || "";
var s2 = aStr2 || "";
return (s1 > s2) - (s1 < s2);
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp;
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp || onlyCompareOriginal) {
return cmp;
}
cmp = strcmp(mappingA.name, mappingB.name);
if (cmp) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
return mappingA.generatedColumn - mappingB.generatedColumn;
};
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings where the generated positions are
* compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
var cmp;
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp || onlyCompareGenerated) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
};
exports.compareByGeneratedPositions = compareByGeneratedPositions;
});
{
"_from": "source-map@~0.1.7",
"_id": "source-map@0.1.43",
"_inBundle": false,
"_integrity": "sha1-wkvBRspRfBRx9drL4lcbK3+eM0Y=",
"_location": "/source-map",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "source-map@~0.1.7",
"name": "source-map",
"escapedName": "source-map",
"rawSpec": "~0.1.7",
"saveSpec": null,
"fetchSpec": "~0.1.7"
},
"_requiredBy": [
"/uglify-js"
],
"_resolved": "http://registry.npmjs.org/source-map/-/source-map-0.1.43.tgz",
"_shasum": "c24bc146ca517c1471f5dacbe2571b2b7f9e3346",
"_spec": "source-map@~0.1.7",
"_where": "D:\\OneDrive\\University Life\\2018\\2nd semester\\OpenSourceSoftware\\KaKao_ChatBot\\node_modules\\uglify-js",
"author": {
"name": "Nick Fitzgerald",
"email": "nfitzgerald@mozilla.com"
},
"bugs": {
"url": "https://github.com/mozilla/source-map/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Tobias Koppers",
"email": "tobias.koppers@googlemail.com"
},
{
"name": "Duncan Beevers",
"email": "duncan@dweebd.com"
},
{
"name": "Stephen Crane",
"email": "scrane@mozilla.com"
},
{
"name": "Ryan Seddon",
"email": "seddon.ryan@gmail.com"
},
{
"name": "Miles Elam",
"email": "miles.elam@deem.com"
},
{
"name": "Mihai Bazon",
"email": "mihai.bazon@gmail.com"
},
{
"name": "Michael Ficarra",
"email": "github.public.email@michael.ficarra.me"
},
{
"name": "Todd Wolfson",
"email": "todd@twolfson.com"
},
{
"name": "Alexander Solovyov",
"email": "alexander@solovyov.net"
},
{
"name": "Felix Gnass",
"email": "fgnass@gmail.com"
},
{
"name": "Conrad Irwin",
"email": "conrad.irwin@gmail.com"
},
{
"name": "usrbincc",
"email": "usrbincc@yahoo.com"
},
{
"name": "David Glasser",
"email": "glasser@davidglasser.net"
},
{
"name": "Chase Douglas",
"email": "chase@newrelic.com"
},
{
"name": "Evan Wallace",
"email": "evan.exe@gmail.com"
},
{
"name": "Heather Arthur",
"email": "fayearthur@gmail.com"
},
{
"name": "Hugh Kennedy",
"email": "hughskennedy@gmail.com"
},
{
"name": "David Glasser",
"email": "glasser@davidglasser.net"
},
{
"name": "Simon Lydell",
"email": "simon.lydell@gmail.com"
},
{
"name": "Jmeas Smith",
"email": "jellyes2@gmail.com"
},
{
"name": "Michael Z Goddard",
"email": "mzgoddard@gmail.com"
},
{
"name": "azu",
"email": "azu@users.noreply.github.com"
},
{
"name": "John Gozde",
"email": "john@gozde.ca"
},
{
"name": "Adam Kirkton",
"email": "akirkton@truefitinnovation.com"
},
{
"name": "Chris Montgomery",
"email": "christopher.montgomery@dowjones.com"
},
{
"name": "J. Ryan Stinnett",
"email": "jryans@gmail.com"
},
{
"name": "Jack Herrington",
"email": "jherrington@walmartlabs.com"
},
{
"name": "Chris Truter",
"email": "jeffpalentine@gmail.com"
},
{
"name": "Daniel Espeset",
"email": "daniel@danielespeset.com"
}
],
"dependencies": {
"amdefine": ">=0.0.4"
},
"deprecated": false,
"description": "Generates and consumes source maps",
"devDependencies": {
"dryice": ">=0.4.8"
},
"directories": {
"lib": "./lib"
},
"engines": {
"node": ">=0.8.0"
},
"homepage": "https://github.com/mozilla/source-map",
"licenses": [
{
"type": "BSD",
"url": "http://opensource.org/licenses/BSD-3-Clause"
}
],
"main": "./lib/source-map.js",
"name": "source-map",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/mozilla/source-map.git"
},
"scripts": {
"build": "node Makefile.dryice.js",
"test": "node test/run-tests.js"
},
"version": "0.1.43"
}
#!/usr/bin/env node
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var assert = require('assert');
var fs = require('fs');
var path = require('path');
var util = require('./source-map/util');
function run(tests) {
var total = 0;
var passed = 0;
for (var i = 0; i < tests.length; i++) {
for (var k in tests[i].testCase) {
if (/^test/.test(k)) {
total++;
try {
tests[i].testCase[k](assert, util);
passed++;
}
catch (e) {
console.log('FAILED ' + tests[i].name + ': ' + k + '!');
console.log(e.stack);
}
}
}
}
console.log('');
console.log(passed + ' / ' + total + ' tests passed.');
console.log('');
return total - passed;
}
function isTestFile(f) {
var testToRun = process.argv[2];
return testToRun
? path.basename(testToRun) === f
: /^test\-.*?\.js/.test(f);
}
function toModule(f) {
return './source-map/' + f.replace(/\.js$/, '');
}
var requires = fs.readdirSync(path.join(__dirname, 'source-map'))
.filter(isTestFile)
.map(toModule);
var code = run(requires.map(require).map(function (mod, i) {
return {
name: requires[i],
testCase: mod
};
}));
process.exit(code);
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2012 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var sourceMap;
try {
sourceMap = require('../../lib/source-map');
} catch (e) {
sourceMap = {};
Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap);
}
exports['test that the api is properly exposed in the top level'] = function (assert, util) {
assert.equal(typeof sourceMap.SourceMapGenerator, "function");
assert.equal(typeof sourceMap.SourceMapConsumer, "function");
assert.equal(typeof sourceMap.SourceNode, "function");
};
});
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var ArraySet = require('../../lib/source-map/array-set').ArraySet;
function makeTestSet() {
var set = new ArraySet();
for (var i = 0; i < 100; i++) {
set.add(String(i));
}
return set;
}
exports['test .has() membership'] = function (assert, util) {
var set = makeTestSet();
for (var i = 0; i < 100; i++) {
assert.ok(set.has(String(i)));
}
};
exports['test .indexOf() elements'] = function (assert, util) {
var set = makeTestSet();
for (var i = 0; i < 100; i++) {
assert.strictEqual(set.indexOf(String(i)), i);
}
};
exports['test .at() indexing'] = function (assert, util) {
var set = makeTestSet();
for (var i = 0; i < 100; i++) {
assert.strictEqual(set.at(i), String(i));
}
};
exports['test creating from an array'] = function (assert, util) {
var set = ArraySet.fromArray(['foo', 'bar', 'baz', 'quux', 'hasOwnProperty']);
assert.ok(set.has('foo'));
assert.ok(set.has('bar'));
assert.ok(set.has('baz'));
assert.ok(set.has('quux'));
assert.ok(set.has('hasOwnProperty'));
assert.strictEqual(set.indexOf('foo'), 0);
assert.strictEqual(set.indexOf('bar'), 1);
assert.strictEqual(set.indexOf('baz'), 2);
assert.strictEqual(set.indexOf('quux'), 3);
assert.strictEqual(set.at(0), 'foo');
assert.strictEqual(set.at(1), 'bar');
assert.strictEqual(set.at(2), 'baz');
assert.strictEqual(set.at(3), 'quux');
};
exports['test that you can add __proto__; see github issue #30'] = function (assert, util) {
var set = new ArraySet();
set.add('__proto__');
assert.ok(set.has('__proto__'));
assert.strictEqual(set.at(0), '__proto__');
assert.strictEqual(set.indexOf('__proto__'), 0);
};
exports['test .fromArray() with duplicates'] = function (assert, util) {
var set = ArraySet.fromArray(['foo', 'foo']);
assert.ok(set.has('foo'));
assert.strictEqual(set.at(0), 'foo');
assert.strictEqual(set.indexOf('foo'), 0);
assert.strictEqual(set.toArray().length, 1);
set = ArraySet.fromArray(['foo', 'foo'], true);
assert.ok(set.has('foo'));
assert.strictEqual(set.at(0), 'foo');
assert.strictEqual(set.at(1), 'foo');
assert.strictEqual(set.indexOf('foo'), 0);
assert.strictEqual(set.toArray().length, 2);
};
exports['test .add() with duplicates'] = function (assert, util) {
var set = new ArraySet();
set.add('foo');
set.add('foo');
assert.ok(set.has('foo'));
assert.strictEqual(set.at(0), 'foo');
assert.strictEqual(set.indexOf('foo'), 0);
assert.strictEqual(set.toArray().length, 1);
set.add('foo', true);
assert.ok(set.has('foo'));
assert.strictEqual(set.at(0), 'foo');
assert.strictEqual(set.at(1), 'foo');
assert.strictEqual(set.indexOf('foo'), 0);
assert.strictEqual(set.toArray().length, 2);
};
});
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.