better free var filling, node.js test
This commit is contained in:
parent
97ed773cb1
commit
ebd6488752
|
@ -1,4 +1,5 @@
|
|||
/node_modules
|
||||
/test/js
|
||||
/test/browsertest/js
|
||||
/examples/*/js
|
||||
/test/browsertest/node_modules/vm-browserify
|
||||
/examples/*/js
|
||||
|
|
15
README.md
15
README.md
|
@ -88,7 +88,9 @@ Initially only `web.js` is included (and loaded) by your application.
|
|||
`1.web.js` is loaded when the call to `require.ensure` happens.
|
||||
After the second bundle (`1.web.js`) is loaded, the callback function will be invoked.
|
||||
|
||||
See [details](modules-webpack/tree/master/examples/code-splitting) for exact output.
|
||||
See [details](/sokra/modules-webpack/tree/master/examples/code-splitting) for exact output.
|
||||
|
||||
See [more examples](/sokra/modules-webpack/tree/master/examples).
|
||||
|
||||
## Reusing node.js code
|
||||
|
||||
|
@ -250,9 +252,16 @@ Some credit goes to the browserify contributors, you can use replacements provid
|
|||
|
||||
Included simple replacements:
|
||||
|
||||
* `assert`: copy of node.js' version
|
||||
* `assert`: copy of node.js' version, small change
|
||||
* `buffer`: copy of node-browserify's version
|
||||
* `buffer_ieee754`: copy of node-browserify's version
|
||||
* `child_process`: disabled
|
||||
* `events`: copy of node.js' version
|
||||
* `path`: copy of node.js' version
|
||||
* `punycode`: copy of node.js' version, one line removed
|
||||
* `querystring`: copy of node.js' version
|
||||
* `string_decoder`: copy of node.js' version
|
||||
* `url`: copy of node.js' version
|
||||
* `util`: copy of node.js' version
|
||||
|
||||
Here is a list of possible useful replacements: (intentionally not by default)
|
||||
|
@ -369,7 +378,7 @@ free module variables which are replaced with a module. ex. `{ "$": "jquery" }`
|
|||
|
||||
`function(err, source / stats)`
|
||||
`source` if `options.output` is not set
|
||||
else `stats` as json see [example](modules-webpack/tree/master/examples/code-splitting)
|
||||
else `stats` as json see [example](/sokra/modules-webpack/tree/master/examples/code-splitting)
|
||||
|
||||
## Comparison
|
||||
|
||||
|
|
|
@ -40,6 +40,10 @@ var argv = require("optimist")
|
|||
.describe("json", "Output Stats as JSON")
|
||||
.default("json", false)
|
||||
|
||||
.boolean("verbose")
|
||||
.describe("verbose", "Output dependencies in Stats")
|
||||
.default("verbose", false)
|
||||
|
||||
.string("alias")
|
||||
.describe("alias", "Set a alias name for a module. ex. http=http-browserify")
|
||||
|
||||
|
@ -128,50 +132,75 @@ if(argv.single) {
|
|||
if(argv.json)
|
||||
console.log(util.inspect(stats, false, 10, argv.colors));
|
||||
else {
|
||||
console.log("Chunks: \033[1m" + stats.chunkCount + "\033[22m");
|
||||
console.log("Modules: \033[1m" + stats.modulesCount + "\033[22m");
|
||||
console.log("Modules including duplicates: \033[1m" + stats.modulesIncludingDuplicates + "\033[22m");
|
||||
console.log("Modules pre chunk: \033[1m" + stats.modulesPerChunk + "\033[22m");
|
||||
console.log("Modules first chunk: \033[1m" + stats.modulesFirstChunk + "\033[22m");
|
||||
function c(str) {
|
||||
return argv.colors ? str : "";
|
||||
}
|
||||
console.log("Chunks: "+c("\033[1m") + stats.chunkCount + c("\033[22m"));
|
||||
console.log("Modules: "+c("\033[1m") + stats.modulesCount + c("\033[22m"));
|
||||
console.log("Modules including duplicates: "+c("\033[1m") + stats.modulesIncludingDuplicates + c("\033[22m"));
|
||||
console.log("Modules pre chunk: "+c("\033[1m") + stats.modulesPerChunk + c("\033[22m"));
|
||||
console.log("Modules first chunk: "+c("\033[1m") + stats.modulesFirstChunk + c("\033[22m"));
|
||||
if(stats.fileSizes)
|
||||
for(var file in stats.fileSizes) {
|
||||
console.log("\033[1m" + sprintf("%" + (5 + options.output.length) + "s", file) + "\033[22m: \033[1m" + sprintf("%8d", stats.fileSizes[file]) + "\033[22m characters");
|
||||
console.log(c("\033[1m") + sprintf("%" + (5 + options.output.length) + "s", file) + c("\033[22m")+": "+c("\033[1m") + sprintf("%8d", stats.fileSizes[file]) + c("\033[22m") + " characters");
|
||||
};
|
||||
var cwd = process.cwd();
|
||||
var cwdParent = path.dirname(cwd);
|
||||
var buildins = path.join(__dirname, "..");
|
||||
cwd = cwd.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
|
||||
cwd = new RegExp("^" + cwd + "|(!)" + cwd, "g");
|
||||
cwdParent = cwdParent.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
|
||||
cwdParent = new RegExp("^" + cwdParent + "|(!)" + cwdParent, "g");
|
||||
buildins = buildins.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
|
||||
buildins = new RegExp("^" + buildins + "|(!)" + buildins, "g");
|
||||
function compressFilename(filename) {
|
||||
if(!filename)
|
||||
return filename;
|
||||
filename = filename.replace(cwd, "!.");
|
||||
filename = filename.replace(cwdParent, "!..");
|
||||
filename = filename.replace(buildins, "!(webpack)");
|
||||
return filename.replace(/^!/, "");
|
||||
}
|
||||
if(stats.fileModules) {
|
||||
for(var file in stats.fileModules) {
|
||||
console.log("\033[1m\033[32m" + file + "\033[39m\033[22m");
|
||||
console.log(c("\033[1m\033[32m") + file + c("\033[39m\033[22m"));
|
||||
var modules = stats.fileModules[file];
|
||||
modules.forEach(function(module) {
|
||||
console.log(" \033[1m" + sprintf("%3s", module.id+"") + " " + (module.filename || (module.dirname && ("generated " + module.dirname)) || "generated") + "\033[22m");
|
||||
module.reasons.forEach(function(reason) {
|
||||
switch(reason.type) {
|
||||
case "require":
|
||||
console.log(" \033[36mrequire (" + reason.count + "x) from " + reason.filename + "\033[39m");
|
||||
break;
|
||||
case "context":
|
||||
console.log(" \033[90mcontext from " + reason.filename + "\033[39m");
|
||||
break;
|
||||
case "async require":
|
||||
console.log(" \033[35masync require (" + reason.count + "x) from " + reason.filename + "\033[39m");
|
||||
break;
|
||||
case "async context":
|
||||
console.log(" \033[35masync context from " + reason.filename + "\033[39m");
|
||||
break;
|
||||
default:
|
||||
console.log(" \033[31m" + reason.type + "\033[39m");
|
||||
}
|
||||
});
|
||||
console.log(" "+c("\033[1m") + sprintf("%3s", module.id+"") + " " +
|
||||
(compressFilename(module.filename) ||
|
||||
(module.dirname && ("[context] " + compressFilename(module.dirname))) ||
|
||||
"[unknown]") + c("\033[22m"));
|
||||
if(argv.verbose) {
|
||||
module.reasons.forEach(function(reason) {
|
||||
switch(reason.type) {
|
||||
case "require":
|
||||
console.log(" "+c("\033[36m")+"require (" + reason.count + "x) from " + compressFilename(reason.filename) + c("\033[39m"));
|
||||
break;
|
||||
case "context":
|
||||
console.log(" "+c("\033[90m")+"context from " + compressFilename(reason.filename) + c("\033[39m"));
|
||||
break;
|
||||
case "async require":
|
||||
console.log(" "+c("\033[35m")+"async require (" + reason.count + "x) from " + compressFilename(reason.filename) + c("\033[39m"));
|
||||
break;
|
||||
case "async context":
|
||||
console.log(" "+c("\033[35ma")+"sync context from " + compressFilename(reason.filename) + c("\033[39m"));
|
||||
break;
|
||||
default:
|
||||
console.log(" "+c("\033[31m") + reason.type + c("\033[39m"));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
if(stats.warnings) {
|
||||
stats.warnings.forEach(function(warning) {
|
||||
console.log("\033[1m\033[33mWARNING: " + warning + "\033[39m\033[22m");
|
||||
console.log(c("\033[1m\033[33m")+"WARNING: " + warning + c("\033[39m\033[22m"));
|
||||
});
|
||||
}
|
||||
if(stats.errors) {
|
||||
stats.errors.forEach(function(error) {
|
||||
console.log("\033[1m\033[31mERROR: " + error + "\033[39m\033[22m");
|
||||
console.log(c("\033[1m\033[31m")+"ERROR: " + error + c("\033[39m\033[22m"));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,15 +1,14 @@
|
|||
var console = window.console;
|
||||
exports.log = (console && console.log) || function() {};
|
||||
exports.info = (console && console.info) || function() {};
|
||||
exports.error = (console && console.error) || function() {};
|
||||
exports.warn = (console && console.warn) || function() {};
|
||||
exports.dir = (console && console.dir) || function() {};
|
||||
exports.time = (console && console.time) || function(label) {
|
||||
module.exports = console;
|
||||
for(var name in {log:1, info:1, error:1, warn:1, dir:1, trace:1, assert:1})
|
||||
if(!console[name])
|
||||
console[name] = function() {};
|
||||
if(!console.time)
|
||||
console.time = function(label) {
|
||||
times[label] = Date.now();
|
||||
};
|
||||
exports.timeEnd = (console && console.timeEnd) || function() {
|
||||
if(!console.timeEnd)
|
||||
console.timeEnd = function() {
|
||||
var duration = Date.now() - times[label];
|
||||
exports.log('%s: %dms', label, duration);
|
||||
};
|
||||
exports.trace = (console && console.trace) || function() {};
|
||||
exports.assert = (console && console.assert) || function() {};
|
||||
console.log('%s: %dms', label, duration);
|
||||
};
|
|
@ -0,0 +1 @@
|
|||
module.exports = ".";
|
|
@ -0,0 +1 @@
|
|||
module.exports = "./index.js";
|
|
@ -1,2 +1,8 @@
|
|||
exports.deprecate = function() {};
|
||||
exports.id = "webpack";
|
||||
module.exports = function(module) {
|
||||
if(!module.webpackPolyfill) {
|
||||
module.deprecate = function() {};
|
||||
module.id = "webpack";
|
||||
module.webpackPolyfill = 1;
|
||||
}
|
||||
return module;
|
||||
}
|
||||
|
|
|
@ -6,16 +6,47 @@ if(Object.prototype.__defineGetter__) {
|
|||
exports.title = window.title;
|
||||
}
|
||||
exports.version = exports.arch =
|
||||
exports.platform = exports.execPath = "webpack";
|
||||
exports.execPath = "webpack";
|
||||
exports.platform = "browser";
|
||||
// TODO stdin, stdout, stderr
|
||||
exports.argv = ["webpack", "browser"];
|
||||
exports.pid = 1;
|
||||
exports.nextTick = function(func) {
|
||||
setTimeout(func, 0);
|
||||
exports.nextTick = (function(func) {
|
||||
// from https://github.com/substack/node-browserify/blob/master/wrappers/process.js
|
||||
var queue = [];
|
||||
var canPost = typeof window !== 'undefined'
|
||||
&& window.postMessage && window.addEventListener
|
||||
;
|
||||
|
||||
if (canPost) {
|
||||
window.addEventListener('message', function (ev) {
|
||||
if (ev.source === window && ev.data === 'webpack-tick') {
|
||||
ev.stopPropagation();
|
||||
if (queue.length > 0) {
|
||||
var fn = queue.shift();
|
||||
fn();
|
||||
}
|
||||
}
|
||||
}, true);
|
||||
}
|
||||
|
||||
return function (fn) {
|
||||
if (canPost) {
|
||||
queue.push(fn);
|
||||
window.postMessage('webpack-tick', '*');
|
||||
}
|
||||
else setTimeout(fn, 0);
|
||||
};
|
||||
}());
|
||||
exports.cwd = function() {
|
||||
return "/app";
|
||||
}
|
||||
exports.exit = exports.kill =
|
||||
exports.chdir = exports.cwd =
|
||||
exports.chdir =
|
||||
exports.umask = exports.dlopen =
|
||||
exports.uptime = exports.memoryUsage =
|
||||
exports.uvCounters = exports.binding = function() {};
|
||||
exports.features = {};
|
||||
exports.uvCounters = function() {};
|
||||
exports.features = {};
|
||||
exports.binding = function(str) {
|
||||
return {};
|
||||
}
|
|
@ -156,7 +156,7 @@ function _deepEqual(actual, expected) {
|
|||
if (actual === expected) {
|
||||
return true;
|
||||
|
||||
} else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) {
|
||||
} else if (require("buffer").Buffer.isBuffer(actual) && require("buffer").Buffer.isBuffer(expected)) {
|
||||
if (actual.length != expected.length) return false;
|
||||
|
||||
for (var i = 0; i < actual.length; i++) {
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,84 @@
|
|||
exports.readIEEE754 = function(buffer, offset, isBE, mLen, nBytes) {
|
||||
var e, m,
|
||||
eLen = nBytes * 8 - mLen - 1,
|
||||
eMax = (1 << eLen) - 1,
|
||||
eBias = eMax >> 1,
|
||||
nBits = -7,
|
||||
i = isBE ? 0 : (nBytes - 1),
|
||||
d = isBE ? 1 : -1,
|
||||
s = buffer[offset + i];
|
||||
|
||||
i += d;
|
||||
|
||||
e = s & ((1 << (-nBits)) - 1);
|
||||
s >>= (-nBits);
|
||||
nBits += eLen;
|
||||
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
|
||||
|
||||
m = e & ((1 << (-nBits)) - 1);
|
||||
e >>= (-nBits);
|
||||
nBits += mLen;
|
||||
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
|
||||
|
||||
if (e === 0) {
|
||||
e = 1 - eBias;
|
||||
} else if (e === eMax) {
|
||||
return m ? NaN : ((s ? -1 : 1) * Infinity);
|
||||
} else {
|
||||
m = m + Math.pow(2, mLen);
|
||||
e = e - eBias;
|
||||
}
|
||||
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
|
||||
};
|
||||
|
||||
exports.writeIEEE754 = function(buffer, value, offset, isBE, mLen, nBytes) {
|
||||
var e, m, c,
|
||||
eLen = nBytes * 8 - mLen - 1,
|
||||
eMax = (1 << eLen) - 1,
|
||||
eBias = eMax >> 1,
|
||||
rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
|
||||
i = isBE ? (nBytes - 1) : 0,
|
||||
d = isBE ? -1 : 1,
|
||||
s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
|
||||
|
||||
value = Math.abs(value);
|
||||
|
||||
if (isNaN(value) || value === Infinity) {
|
||||
m = isNaN(value) ? 1 : 0;
|
||||
e = eMax;
|
||||
} else {
|
||||
e = Math.floor(Math.log(value) / Math.LN2);
|
||||
if (value * (c = Math.pow(2, -e)) < 1) {
|
||||
e--;
|
||||
c *= 2;
|
||||
}
|
||||
if (e + eBias >= 1) {
|
||||
value += rt / c;
|
||||
} else {
|
||||
value += rt * Math.pow(2, 1 - eBias);
|
||||
}
|
||||
if (value * c >= 2) {
|
||||
e++;
|
||||
c /= 2;
|
||||
}
|
||||
|
||||
if (e + eBias >= eMax) {
|
||||
m = 0;
|
||||
e = eMax;
|
||||
} else if (e + eBias >= 1) {
|
||||
m = (value * c - 1) * Math.pow(2, mLen);
|
||||
e = e + eBias;
|
||||
} else {
|
||||
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
|
||||
e = 0;
|
||||
}
|
||||
}
|
||||
|
||||
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
|
||||
|
||||
e = (e << mLen) | m;
|
||||
eLen += mLen;
|
||||
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
|
||||
|
||||
buffer[offset + i - d] |= s * 128;
|
||||
};
|
|
@ -186,8 +186,6 @@ EventEmitter.prototype.removeListener = function(type, listener) {
|
|||
|
||||
if (position < 0) return this;
|
||||
list.splice(position, 1);
|
||||
if (list.length == 0)
|
||||
delete this._events[type];
|
||||
} else if (list === listener ||
|
||||
(list.listener && list.listener === listener))
|
||||
{
|
||||
|
@ -203,8 +201,15 @@ EventEmitter.prototype.removeAllListeners = function(type) {
|
|||
return this;
|
||||
}
|
||||
|
||||
// does not use listeners(), so no side effect of creating _events[type]
|
||||
if (type && this._events && this._events[type]) this._events[type] = null;
|
||||
var events = this._events && this._events[type];
|
||||
if (!events) return this;
|
||||
|
||||
if (isArray(events)) {
|
||||
events.splice(0);
|
||||
} else {
|
||||
this._events[type] = null;
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
|
|
|
@ -0,0 +1,450 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
|
||||
var isWindows = process.platform === 'win32';
|
||||
var _deprecationWarning = require('util')._deprecationWarning;
|
||||
|
||||
|
||||
// resolves . and .. elements in a path array with directory names there
|
||||
// must be no slashes, empty elements, or device names (c:\) in the array
|
||||
// (so also no leading and trailing slashes - it does not distinguish
|
||||
// relative and absolute paths)
|
||||
function normalizeArray(parts, allowAboveRoot) {
|
||||
// if the path tries to go above the root, `up` ends up > 0
|
||||
var up = 0;
|
||||
for (var i = parts.length - 1; i >= 0; i--) {
|
||||
var last = parts[i];
|
||||
if (last == '.') {
|
||||
parts.splice(i, 1);
|
||||
} else if (last === '..') {
|
||||
parts.splice(i, 1);
|
||||
up++;
|
||||
} else if (up) {
|
||||
parts.splice(i, 1);
|
||||
up--;
|
||||
}
|
||||
}
|
||||
|
||||
// if the path is allowed to go above the root, restore leading ..s
|
||||
if (allowAboveRoot) {
|
||||
for (; up--; up) {
|
||||
parts.unshift('..');
|
||||
}
|
||||
}
|
||||
|
||||
return parts;
|
||||
}
|
||||
|
||||
|
||||
if (isWindows) {
|
||||
// Regex to split a windows path into three parts: [*, device, slash,
|
||||
// tail] windows-only
|
||||
var splitDeviceRe =
|
||||
/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?([\\\/])?([\s\S]*?)$/;
|
||||
|
||||
// Regex to split the tail part of the above into [*, dir, basename, ext]
|
||||
var splitTailRe =
|
||||
/^([\s\S]+[\\\/](?!$)|[\\\/])?((?:\.{1,2}$|[\s\S]+?)?(\.[^.\/\\]*)?)$/;
|
||||
|
||||
// Function to split a filename into [root, dir, basename, ext]
|
||||
// windows version
|
||||
var splitPath = function(filename) {
|
||||
// Separate device+slash from tail
|
||||
var result = splitDeviceRe.exec(filename),
|
||||
device = (result[1] || '') + (result[2] || ''),
|
||||
tail = result[3] || '';
|
||||
// Split the tail into dir, basename and extension
|
||||
var result2 = splitTailRe.exec(tail),
|
||||
dir = result2[1] || '',
|
||||
basename = result2[2] || '',
|
||||
ext = result2[3] || '';
|
||||
return [device, dir, basename, ext];
|
||||
};
|
||||
|
||||
// path.resolve([from ...], to)
|
||||
// windows version
|
||||
exports.resolve = function() {
|
||||
var resolvedDevice = '',
|
||||
resolvedTail = '',
|
||||
resolvedAbsolute = false;
|
||||
|
||||
for (var i = arguments.length - 1; i >= -1; i--) {
|
||||
var path;
|
||||
if (i >= 0) {
|
||||
path = arguments[i];
|
||||
} else if (!resolvedDevice) {
|
||||
path = process.cwd();
|
||||
} else {
|
||||
// Windows has the concept of drive-specific current working
|
||||
// directories. If we've resolved a drive letter but not yet an
|
||||
// absolute path, get cwd for that drive. We're sure the device is not
|
||||
// an unc path at this points, because unc paths are always absolute.
|
||||
path = process.env['=' + resolvedDevice];
|
||||
// Verify that a drive-local cwd was found and that it actually points
|
||||
// to our drive. If not, default to the drive's root.
|
||||
if (!path || path.slice(0, 3).toLowerCase() !==
|
||||
resolvedDevice.toLowerCase() + '\\') {
|
||||
path = resolvedDevice + '\\';
|
||||
}
|
||||
}
|
||||
|
||||
// Skip empty and invalid entries
|
||||
if (typeof path !== 'string' || !path) {
|
||||
continue;
|
||||
}
|
||||
|
||||
var result = splitDeviceRe.exec(path),
|
||||
device = result[1] || '',
|
||||
isUnc = device && device.charAt(1) !== ':',
|
||||
isAbsolute = !!result[2] || isUnc, // UNC paths are always absolute
|
||||
tail = result[3];
|
||||
|
||||
if (device &&
|
||||
resolvedDevice &&
|
||||
device.toLowerCase() !== resolvedDevice.toLowerCase()) {
|
||||
// This path points to another device so it is not applicable
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!resolvedDevice) {
|
||||
resolvedDevice = device;
|
||||
}
|
||||
if (!resolvedAbsolute) {
|
||||
resolvedTail = tail + '\\' + resolvedTail;
|
||||
resolvedAbsolute = isAbsolute;
|
||||
}
|
||||
|
||||
if (resolvedDevice && resolvedAbsolute) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Replace slashes (in UNC share name) by backslashes
|
||||
resolvedDevice = resolvedDevice.replace(/\//g, '\\');
|
||||
|
||||
// At this point the path should be resolved to a full absolute path,
|
||||
// but handle relative paths to be safe (might happen when process.cwd()
|
||||
// fails)
|
||||
|
||||
// Normalize the tail path
|
||||
|
||||
function f(p) {
|
||||
return !!p;
|
||||
}
|
||||
|
||||
resolvedTail = normalizeArray(resolvedTail.split(/[\\\/]+/).filter(f),
|
||||
!resolvedAbsolute).join('\\');
|
||||
|
||||
return (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) ||
|
||||
'.';
|
||||
};
|
||||
|
||||
// windows version
|
||||
exports.normalize = function(path) {
|
||||
var result = splitDeviceRe.exec(path),
|
||||
device = result[1] || '',
|
||||
isUnc = device && device.charAt(1) !== ':',
|
||||
isAbsolute = !!result[2] || isUnc, // UNC paths are always absolute
|
||||
tail = result[3],
|
||||
trailingSlash = /[\\\/]$/.test(tail);
|
||||
|
||||
// Normalize the tail path
|
||||
tail = normalizeArray(tail.split(/[\\\/]+/).filter(function(p) {
|
||||
return !!p;
|
||||
}), !isAbsolute).join('\\');
|
||||
|
||||
if (!tail && !isAbsolute) {
|
||||
tail = '.';
|
||||
}
|
||||
if (tail && trailingSlash) {
|
||||
tail += '\\';
|
||||
}
|
||||
|
||||
return device + (isAbsolute ? '\\' : '') + tail;
|
||||
};
|
||||
|
||||
// windows version
|
||||
exports.join = function() {
|
||||
function f(p) {
|
||||
return p && typeof p === 'string';
|
||||
}
|
||||
|
||||
var paths = Array.prototype.slice.call(arguments, 0).filter(f);
|
||||
var joined = paths.join('\\');
|
||||
|
||||
// Make sure that the joined path doesn't start with two slashes
|
||||
// - it will be mistaken for an unc path by normalize() -
|
||||
// unless the paths[0] also starts with two slashes
|
||||
if (/^[\\\/]{2}/.test(joined) && !/^[\\\/]{2}/.test(paths[0])) {
|
||||
joined = joined.slice(1);
|
||||
}
|
||||
|
||||
return exports.normalize(joined);
|
||||
};
|
||||
|
||||
// path.relative(from, to)
|
||||
// it will solve the relative path from 'from' to 'to', for instance:
|
||||
// from = 'C:\\orandea\\test\\aaa'
|
||||
// to = 'C:\\orandea\\impl\\bbb'
|
||||
// The output of the function should be: '..\\..\\impl\\bbb'
|
||||
// windows version
|
||||
exports.relative = function(from, to) {
|
||||
from = exports.resolve(from);
|
||||
to = exports.resolve(to);
|
||||
|
||||
// windows is not case sensitive
|
||||
var lowerFrom = from.toLowerCase();
|
||||
var lowerTo = to.toLowerCase();
|
||||
|
||||
function trim(arr) {
|
||||
var start = 0;
|
||||
for (; start < arr.length; start++) {
|
||||
if (arr[start] !== '') break;
|
||||
}
|
||||
|
||||
var end = arr.length - 1;
|
||||
for (; end >= 0; end--) {
|
||||
if (arr[end] !== '') break;
|
||||
}
|
||||
|
||||
if (start > end) return [];
|
||||
return arr.slice(start, end - start + 1);
|
||||
}
|
||||
|
||||
var toParts = trim(to.split('\\'));
|
||||
|
||||
var lowerFromParts = trim(lowerFrom.split('\\'));
|
||||
var lowerToParts = trim(lowerTo.split('\\'));
|
||||
|
||||
var length = Math.min(lowerFromParts.length, lowerToParts.length);
|
||||
var samePartsLength = length;
|
||||
for (var i = 0; i < length; i++) {
|
||||
if (lowerFromParts[i] !== lowerToParts[i]) {
|
||||
samePartsLength = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (samePartsLength == 0) {
|
||||
return to;
|
||||
}
|
||||
|
||||
var outputParts = [];
|
||||
for (var i = samePartsLength; i < lowerFromParts.length; i++) {
|
||||
outputParts.push('..');
|
||||
}
|
||||
|
||||
outputParts = outputParts.concat(toParts.slice(samePartsLength));
|
||||
|
||||
return outputParts.join('\\');
|
||||
};
|
||||
|
||||
|
||||
} else /* posix */ {
|
||||
|
||||
// Split a filename into [root, dir, basename, ext], unix version
|
||||
// 'root' is just a slash, or nothing.
|
||||
var splitPathRe =
|
||||
/^(\/?)([\s\S]+\/(?!$)|\/)?((?:\.{1,2}$|[\s\S]+?)?(\.[^.\/]*)?)$/;
|
||||
var splitPath = function(filename) {
|
||||
var result = splitPathRe.exec(filename);
|
||||
return [result[1] || '', result[2] || '', result[3] || '', result[4] || ''];
|
||||
};
|
||||
|
||||
// path.resolve([from ...], to)
|
||||
// posix version
|
||||
exports.resolve = function() {
|
||||
var resolvedPath = '',
|
||||
resolvedAbsolute = false;
|
||||
|
||||
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
|
||||
var path = (i >= 0) ? arguments[i] : process.cwd();
|
||||
|
||||
// Skip empty and invalid entries
|
||||
if (typeof path !== 'string' || !path) {
|
||||
continue;
|
||||
}
|
||||
|
||||
resolvedPath = path + '/' + resolvedPath;
|
||||
resolvedAbsolute = path.charAt(0) === '/';
|
||||
}
|
||||
|
||||
// At this point the path should be resolved to a full absolute path, but
|
||||
// handle relative paths to be safe (might happen when process.cwd() fails)
|
||||
|
||||
// Normalize the path
|
||||
resolvedPath = normalizeArray(resolvedPath.split('/').filter(function(p) {
|
||||
return !!p;
|
||||
}), !resolvedAbsolute).join('/');
|
||||
|
||||
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
|
||||
};
|
||||
|
||||
// path.normalize(path)
|
||||
// posix version
|
||||
exports.normalize = function(path) {
|
||||
var isAbsolute = path.charAt(0) === '/',
|
||||
trailingSlash = path.slice(-1) === '/';
|
||||
|
||||
// Normalize the path
|
||||
path = normalizeArray(path.split('/').filter(function(p) {
|
||||
return !!p;
|
||||
}), !isAbsolute).join('/');
|
||||
|
||||
if (!path && !isAbsolute) {
|
||||
path = '.';
|
||||
}
|
||||
if (path && trailingSlash) {
|
||||
path += '/';
|
||||
}
|
||||
|
||||
return (isAbsolute ? '/' : '') + path;
|
||||
};
|
||||
|
||||
|
||||
// posix version
|
||||
exports.join = function() {
|
||||
var paths = Array.prototype.slice.call(arguments, 0);
|
||||
return exports.normalize(paths.filter(function(p, index) {
|
||||
return p && typeof p === 'string';
|
||||
}).join('/'));
|
||||
};
|
||||
|
||||
|
||||
// path.relative(from, to)
|
||||
// posix version
|
||||
exports.relative = function(from, to) {
|
||||
from = exports.resolve(from).substr(1);
|
||||
to = exports.resolve(to).substr(1);
|
||||
|
||||
function trim(arr) {
|
||||
var start = 0;
|
||||
for (; start < arr.length; start++) {
|
||||
if (arr[start] !== '') break;
|
||||
}
|
||||
|
||||
var end = arr.length - 1;
|
||||
for (; end >= 0; end--) {
|
||||
if (arr[end] !== '') break;
|
||||
}
|
||||
|
||||
if (start > end) return [];
|
||||
return arr.slice(start, end - start + 1);
|
||||
}
|
||||
|
||||
var fromParts = trim(from.split('/'));
|
||||
var toParts = trim(to.split('/'));
|
||||
|
||||
var length = Math.min(fromParts.length, toParts.length);
|
||||
var samePartsLength = length;
|
||||
for (var i = 0; i < length; i++) {
|
||||
if (fromParts[i] !== toParts[i]) {
|
||||
samePartsLength = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var outputParts = [];
|
||||
for (var i = samePartsLength; i < fromParts.length; i++) {
|
||||
outputParts.push('..');
|
||||
}
|
||||
|
||||
outputParts = outputParts.concat(toParts.slice(samePartsLength));
|
||||
|
||||
return outputParts.join('/');
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
|
||||
exports.dirname = function(path) {
|
||||
var result = splitPath(path),
|
||||
root = result[0],
|
||||
dir = result[1];
|
||||
|
||||
if (!root && !dir) {
|
||||
// No dirname whatsoever
|
||||
return '.';
|
||||
}
|
||||
|
||||
if (dir) {
|
||||
// It has a dirname, strip trailing slash
|
||||
dir = dir.substring(0, dir.length - 1);
|
||||
}
|
||||
|
||||
return root + dir;
|
||||
};
|
||||
|
||||
|
||||
exports.basename = function(path, ext) {
|
||||
var f = splitPath(path)[2];
|
||||
// TODO: make this comparison case-insensitive on windows?
|
||||
if (ext && f.substr(-1 * ext.length) === ext) {
|
||||
f = f.substr(0, f.length - ext.length);
|
||||
}
|
||||
return f;
|
||||
};
|
||||
|
||||
|
||||
exports.extname = function(path) {
|
||||
return splitPath(path)[3];
|
||||
};
|
||||
|
||||
/*
|
||||
exports.exists = function(path, callback) {
|
||||
require('fs').exists(path, callback);
|
||||
};
|
||||
module.deprecate('exists', 'It is now called `fs.exists`.');
|
||||
|
||||
|
||||
exports.existsSync = function(path) {
|
||||
return require('fs').existsSync(path);
|
||||
};
|
||||
module.deprecate('existsSync', 'It is now called `fs.existsSync`.');
|
||||
*/
|
||||
|
||||
if (isWindows) {
|
||||
exports._makeLong = function(path) {
|
||||
path = '' + path;
|
||||
if (!path) {
|
||||
return '';
|
||||
}
|
||||
|
||||
var resolvedPath = exports.resolve(path);
|
||||
|
||||
if (resolvedPath.match(/^[a-zA-Z]\:\\/)) {
|
||||
// path is local filesystem path, which needs to be converted
|
||||
// to long UNC path.
|
||||
return '\\\\?\\' + resolvedPath;
|
||||
} else if (resolvedPath.match(/^\\\\[^?.]/)) {
|
||||
// path is network UNC path, which needs to be converted
|
||||
// to long UNC path.
|
||||
return '\\\\?\\UNC\\' + resolvedPath.substring(2);
|
||||
}
|
||||
|
||||
return path;
|
||||
};
|
||||
} else {
|
||||
exports._makeLong = function(path) {
|
||||
return path;
|
||||
};
|
||||
}
|
|
@ -0,0 +1,512 @@
|
|||
/*! http://mths.be/punycode by @mathias */
|
||||
;(function(root) {
|
||||
|
||||
/**
|
||||
* The `punycode` object.
|
||||
* @name punycode
|
||||
* @type Object
|
||||
*/
|
||||
var punycode,
|
||||
|
||||
/** Detect free variables `define`, `exports`, `module` and `require` */
|
||||
freeDefine = typeof define == 'function' && typeof define.amd == 'object' &&
|
||||
define.amd && define,
|
||||
freeExports = typeof exports == 'object' && exports,
|
||||
freeModule = typeof module == 'object' && module,
|
||||
// freeRequire = typeof require == 'function' && require,
|
||||
|
||||
/** Highest positive signed 32-bit float value */
|
||||
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
|
||||
|
||||
/** Bootstring parameters */
|
||||
base = 36,
|
||||
tMin = 1,
|
||||
tMax = 26,
|
||||
skew = 38,
|
||||
damp = 700,
|
||||
initialBias = 72,
|
||||
initialN = 128, // 0x80
|
||||
delimiter = '-', // '\x2D'
|
||||
|
||||
/** Regular expressions */
|
||||
regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
|
||||
regexPunycode = /^xn--/,
|
||||
|
||||
/** Error messages */
|
||||
errors = {
|
||||
'overflow': 'Overflow: input needs wider integers to process.',
|
||||
'ucs2decode': 'UCS-2(decode): illegal sequence',
|
||||
'ucs2encode': 'UCS-2(encode): illegal value',
|
||||
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
|
||||
'invalid-input': 'Invalid input'
|
||||
},
|
||||
|
||||
/** Convenience shortcuts */
|
||||
baseMinusTMin = base - tMin,
|
||||
floor = Math.floor,
|
||||
stringFromCharCode = String.fromCharCode,
|
||||
|
||||
/** Temporary variable */
|
||||
key;
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* A generic error utility function.
|
||||
* @private
|
||||
* @param {String} type The error type.
|
||||
* @returns {Error} Throws a `RangeError` with the applicable error message.
|
||||
*/
|
||||
function error(type) {
|
||||
throw RangeError(errors[type]);
|
||||
}
|
||||
|
||||
/**
|
||||
* A generic `Array#map` utility function.
|
||||
* @private
|
||||
* @param {Array} array The array to iterate over.
|
||||
* @param {Function} callback The function that gets called for every array
|
||||
* item.
|
||||
* @returns {Array} A new array of values returned by the callback function.
|
||||
*/
|
||||
function map(array, fn) {
|
||||
var length = array.length;
|
||||
while (length--) {
|
||||
array[length] = fn(array[length]);
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* A simple `Array#map`-like wrapper to work with domain name strings.
|
||||
* @private
|
||||
* @param {String} domain The domain name.
|
||||
* @param {Function} callback The function that gets called for every
|
||||
* character.
|
||||
* @returns {Array} A new string of characters returned by the callback
|
||||
* function.
|
||||
*/
|
||||
function mapDomain(string, fn) {
|
||||
var glue = '.';
|
||||
return map(string.split(glue), fn).join(glue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an array containing the decimal code points of each Unicode
|
||||
* character in the string. While JavaScript uses UCS-2 internally,
|
||||
* this function will convert a pair of surrogate halves (each of which
|
||||
* UCS-2 exposes as separate characters) into a single code point,
|
||||
* matching UTF-16.
|
||||
* @see `punycode.ucs2.encode`
|
||||
* @see <http://mathiasbynens.be/notes/javascript-encoding>
|
||||
* @memberOf punycode.ucs2
|
||||
* @name decode
|
||||
* @param {String} string The Unicode input string (UCS-2).
|
||||
* @returns {Array} The new array of code points.
|
||||
*/
|
||||
function ucs2decode(string) {
|
||||
var output = [],
|
||||
counter = 0,
|
||||
length = string.length,
|
||||
value,
|
||||
extra;
|
||||
while (counter < length) {
|
||||
value = string.charCodeAt(counter++);
|
||||
if ((value & 0xF800) == 0xD800) {
|
||||
extra = string.charCodeAt(counter++);
|
||||
if ((value & 0xFC00) != 0xD800 || (extra & 0xFC00) != 0xDC00) {
|
||||
error('ucs2decode');
|
||||
}
|
||||
value = ((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
|
||||
}
|
||||
output.push(value);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a string based on an array of decimal code points.
|
||||
* @see `punycode.ucs2.decode`
|
||||
* @memberOf punycode.ucs2
|
||||
* @name encode
|
||||
* @param {Array} codePoints The array of decimal code points.
|
||||
* @returns {String} The new Unicode string (UCS-2).
|
||||
*/
|
||||
function ucs2encode(array) {
|
||||
return map(array, function(value) {
|
||||
var output = '';
|
||||
if ((value & 0xF800) == 0xD800) {
|
||||
error('ucs2encode');
|
||||
}
|
||||
if (value > 0xFFFF) {
|
||||
value -= 0x10000;
|
||||
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
|
||||
value = 0xDC00 | value & 0x3FF;
|
||||
}
|
||||
output += stringFromCharCode(value);
|
||||
return output;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a basic code point into a digit/integer.
|
||||
* @see `digitToBasic()`
|
||||
* @private
|
||||
* @param {Number} codePoint The basic (decimal) code point.
|
||||
* @returns {Number} The numeric value of a basic code point (for use in
|
||||
* representing integers) in the range `0` to `base - 1`, or `base` if
|
||||
* the code point does not represent a value.
|
||||
*/
|
||||
function basicToDigit(codePoint) {
|
||||
return codePoint - 48 < 10
|
||||
? codePoint - 22
|
||||
: codePoint - 65 < 26
|
||||
? codePoint - 65
|
||||
: codePoint - 97 < 26
|
||||
? codePoint - 97
|
||||
: base;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a digit/integer into a basic code point.
|
||||
* @see `basicToDigit()`
|
||||
* @private
|
||||
* @param {Number} digit The numeric value of a basic code point.
|
||||
* @returns {Number} The basic code point whose value (when used for
|
||||
* representing integers) is `digit`, which needs to be in the range
|
||||
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
|
||||
* used; else, the lowercase form is used. The behavior is undefined
|
||||
* if flag is non-zero and `digit` has no uppercase form.
|
||||
*/
|
||||
function digitToBasic(digit, flag) {
|
||||
// 0..25 map to ASCII a..z or A..Z
|
||||
// 26..35 map to ASCII 0..9
|
||||
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bias adaptation function as per section 3.4 of RFC 3492.
|
||||
* http://tools.ietf.org/html/rfc3492#section-3.4
|
||||
* @private
|
||||
*/
|
||||
function adapt(delta, numPoints, firstTime) {
|
||||
var k = 0;
|
||||
delta = firstTime ? floor(delta / damp) : delta >> 1;
|
||||
delta += floor(delta / numPoints);
|
||||
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
|
||||
delta = floor(delta / baseMinusTMin);
|
||||
}
|
||||
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a basic code point to lowercase is `flag` is falsy, or to
|
||||
* uppercase if `flag` is truthy. The code point is unchanged if it's
|
||||
* caseless. The behavior is undefined if `codePoint` is not a basic code
|
||||
* point.
|
||||
* @private
|
||||
* @param {Number} codePoint The numeric value of a basic code point.
|
||||
* @returns {Number} The resulting basic code point.
|
||||
*/
|
||||
function encodeBasic(codePoint, flag) {
|
||||
codePoint -= (codePoint - 97 < 26) << 5;
|
||||
return codePoint + (!flag && codePoint - 65 < 26) << 5;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a Punycode string of ASCII code points to a string of Unicode
|
||||
* code points.
|
||||
* @memberOf punycode
|
||||
* @param {String} input The Punycode string of ASCII code points.
|
||||
* @returns {String} The resulting string of Unicode code points.
|
||||
*/
|
||||
function decode(input) {
|
||||
// Don't use UCS-2
|
||||
var output = [],
|
||||
inputLength = input.length,
|
||||
out,
|
||||
i = 0,
|
||||
n = initialN,
|
||||
bias = initialBias,
|
||||
basic,
|
||||
j,
|
||||
index,
|
||||
oldi,
|
||||
w,
|
||||
k,
|
||||
digit,
|
||||
t,
|
||||
length,
|
||||
/** Cached calculation results */
|
||||
baseMinusT;
|
||||
|
||||
// Handle the basic code points: let `basic` be the number of input code
|
||||
// points before the last delimiter, or `0` if there is none, then copy
|
||||
// the first basic code points to the output.
|
||||
|
||||
basic = input.lastIndexOf(delimiter);
|
||||
if (basic < 0) {
|
||||
basic = 0;
|
||||
}
|
||||
|
||||
for (j = 0; j < basic; ++j) {
|
||||
// if it's not a basic code point
|
||||
if (input.charCodeAt(j) >= 0x80) {
|
||||
error('not-basic');
|
||||
}
|
||||
output.push(input.charCodeAt(j));
|
||||
}
|
||||
|
||||
// Main decoding loop: start just after the last delimiter if any basic code
|
||||
// points were copied; start at the beginning otherwise.
|
||||
|
||||
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
|
||||
|
||||
// `index` is the index of the next character to be consumed.
|
||||
// Decode a generalized variable-length integer into `delta`,
|
||||
// which gets added to `i`. The overflow checking is easier
|
||||
// if we increase `i` as we go, then subtract off its starting
|
||||
// value at the end to obtain `delta`.
|
||||
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
|
||||
|
||||
if (index >= inputLength) {
|
||||
error('invalid-input');
|
||||
}
|
||||
|
||||
digit = basicToDigit(input.charCodeAt(index++));
|
||||
|
||||
if (digit >= base || digit > floor((maxInt - i) / w)) {
|
||||
error('overflow');
|
||||
}
|
||||
|
||||
i += digit * w;
|
||||
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
|
||||
|
||||
if (digit < t) {
|
||||
break;
|
||||
}
|
||||
|
||||
baseMinusT = base - t;
|
||||
if (w > floor(maxInt / baseMinusT)) {
|
||||
error('overflow');
|
||||
}
|
||||
|
||||
w *= baseMinusT;
|
||||
|
||||
}
|
||||
|
||||
out = output.length + 1;
|
||||
bias = adapt(i - oldi, out, oldi == 0);
|
||||
|
||||
// `i` was supposed to wrap around from `out` to `0`,
|
||||
// incrementing `n` each time, so we'll fix that now:
|
||||
if (floor(i / out) > maxInt - n) {
|
||||
error('overflow');
|
||||
}
|
||||
|
||||
n += floor(i / out);
|
||||
i %= out;
|
||||
|
||||
// Insert `n` at position `i` of the output
|
||||
output.splice(i++, 0, n);
|
||||
|
||||
}
|
||||
|
||||
return ucs2encode(output);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a string of Unicode code points to a Punycode string of ASCII
|
||||
* code points.
|
||||
* @memberOf punycode
|
||||
* @param {String} input The string of Unicode code points.
|
||||
* @returns {String} The resulting Punycode string of ASCII code points.
|
||||
*/
|
||||
function encode(input) {
|
||||
var n,
|
||||
delta,
|
||||
handledCPCount,
|
||||
basicLength,
|
||||
bias,
|
||||
j,
|
||||
m,
|
||||
q,
|
||||
k,
|
||||
t,
|
||||
currentValue,
|
||||
output = [],
|
||||
/** `inputLength` will hold the number of code points in `input`. */
|
||||
inputLength,
|
||||
/** Cached calculation results */
|
||||
handledCPCountPlusOne,
|
||||
baseMinusT,
|
||||
qMinusT;
|
||||
|
||||
// Convert the input in UCS-2 to Unicode
|
||||
input = ucs2decode(input);
|
||||
|
||||
// Cache the length
|
||||
inputLength = input.length;
|
||||
|
||||
// Initialize the state
|
||||
n = initialN;
|
||||
delta = 0;
|
||||
bias = initialBias;
|
||||
|
||||
// Handle the basic code points
|
||||
for (j = 0; j < inputLength; ++j) {
|
||||
currentValue = input[j];
|
||||
if (currentValue < 0x80) {
|
||||
output.push(stringFromCharCode(currentValue));
|
||||
}
|
||||
}
|
||||
|
||||
handledCPCount = basicLength = output.length;
|
||||
|
||||
// `handledCPCount` is the number of code points that have been handled;
|
||||
// `basicLength` is the number of basic code points.
|
||||
|
||||
// Finish the basic string - if it is not empty - with a delimiter
|
||||
if (basicLength) {
|
||||
output.push(delimiter);
|
||||
}
|
||||
|
||||
// Main encoding loop:
|
||||
while (handledCPCount < inputLength) {
|
||||
|
||||
// All non-basic code points < n have been handled already. Find the next
|
||||
// larger one:
|
||||
for (m = maxInt, j = 0; j < inputLength; ++j) {
|
||||
currentValue = input[j];
|
||||
if (currentValue >= n && currentValue < m) {
|
||||
m = currentValue;
|
||||
}
|
||||
}
|
||||
|
||||
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
|
||||
// but guard against overflow
|
||||
handledCPCountPlusOne = handledCPCount + 1;
|
||||
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
|
||||
error('overflow');
|
||||
}
|
||||
|
||||
delta += (m - n) * handledCPCountPlusOne;
|
||||
n = m;
|
||||
|
||||
for (j = 0; j < inputLength; ++j) {
|
||||
currentValue = input[j];
|
||||
|
||||
if (currentValue < n && ++delta > maxInt) {
|
||||
error('overflow');
|
||||
}
|
||||
|
||||
if (currentValue == n) {
|
||||
// Represent delta as a generalized variable-length integer
|
||||
for (q = delta, k = base; /* no condition */; k += base) {
|
||||
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
|
||||
if (q < t) {
|
||||
break;
|
||||
}
|
||||
qMinusT = q - t;
|
||||
baseMinusT = base - t;
|
||||
output.push(
|
||||
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
|
||||
);
|
||||
q = floor(qMinusT / baseMinusT);
|
||||
}
|
||||
|
||||
output.push(stringFromCharCode(digitToBasic(q, 0)));
|
||||
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
|
||||
delta = 0;
|
||||
++handledCPCount;
|
||||
}
|
||||
}
|
||||
|
||||
++delta;
|
||||
++n;
|
||||
|
||||
}
|
||||
return output.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a Punycode string representing a domain name to Unicode. Only the
|
||||
* Punycoded parts of the domain name will be converted, i.e. it doesn't
|
||||
* matter if you call it on a string that has already been converted to
|
||||
* Unicode.
|
||||
* @memberOf punycode
|
||||
* @param {String} domain The Punycode domain name to convert to Unicode.
|
||||
* @returns {String} The Unicode representation of the given Punycode
|
||||
* string.
|
||||
*/
|
||||
function toUnicode(domain) {
|
||||
return mapDomain(domain, function(string) {
|
||||
return regexPunycode.test(string)
|
||||
? decode(string.slice(4).toLowerCase())
|
||||
: string;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a Unicode string representing a domain name to Punycode. Only the
|
||||
* non-ASCII parts of the domain name will be converted, i.e. it doesn't
|
||||
* matter if you call it with a domain that's already in ASCII.
|
||||
* @memberOf punycode
|
||||
* @param {String} domain The domain name to convert, as a Unicode string.
|
||||
* @returns {String} The Punycode representation of the given domain name.
|
||||
*/
|
||||
function toASCII(domain) {
|
||||
return mapDomain(domain, function(string) {
|
||||
return regexNonASCII.test(string)
|
||||
? 'xn--' + encode(string)
|
||||
: string;
|
||||
});
|
||||
}
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
/** Define the public API */
|
||||
punycode = {
|
||||
/**
|
||||
* A string representing the current Punycode.js version number.
|
||||
* @memberOf punycode
|
||||
* @type String
|
||||
*/
|
||||
'version': '1.0.0',
|
||||
/**
|
||||
* An object of methods to convert from JavaScript's internal character
|
||||
* representation (UCS-2) to decimal Unicode code points, and back.
|
||||
* @see <http://mathiasbynens.be/notes/javascript-encoding>
|
||||
* @memberOf punycode
|
||||
* @type Object
|
||||
*/
|
||||
'ucs2': {
|
||||
'decode': ucs2decode,
|
||||
'encode': ucs2encode
|
||||
},
|
||||
'decode': decode,
|
||||
'encode': encode,
|
||||
'toASCII': toASCII,
|
||||
'toUnicode': toUnicode
|
||||
};
|
||||
|
||||
/** Expose `punycode` */
|
||||
if (freeExports) {
|
||||
if (freeModule && freeModule.exports == freeExports) {
|
||||
// in Node.js or Ringo 0.8+
|
||||
freeModule.exports = punycode;
|
||||
} else {
|
||||
// in Narwhal or Ringo 0.7-
|
||||
for (key in punycode) {
|
||||
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
|
||||
}
|
||||
}
|
||||
} else if (freeDefine) {
|
||||
// via curl.js or RequireJS
|
||||
define('punycode', punycode);
|
||||
} else {
|
||||
// in a browser or Rhino
|
||||
root.punycode = punycode;
|
||||
}
|
||||
|
||||
}(this));
|
|
@ -0,0 +1,142 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
// Query String Utilities
|
||||
|
||||
var QueryString = exports;
|
||||
|
||||
|
||||
// If obj.hasOwnProperty has been overridden, then calling
|
||||
// obj.hasOwnProperty(prop) will break.
|
||||
// See: https://github.com/joyent/node/issues/1707
|
||||
function hasOwnProperty(obj, prop) {
|
||||
return Object.prototype.hasOwnProperty.call(obj, prop);
|
||||
}
|
||||
|
||||
|
||||
function charCode(c) {
|
||||
return c.charCodeAt(0);
|
||||
}
|
||||
|
||||
|
||||
QueryString.unescape = function(s, decodeSpaces) {
|
||||
return decodeURIComponent(s, decodeSpaces)
|
||||
};
|
||||
|
||||
|
||||
QueryString.escape = function(str) {
|
||||
return encodeURIComponent(str);
|
||||
};
|
||||
|
||||
var stringifyPrimitive = function(v) {
|
||||
switch (typeof v) {
|
||||
case 'string':
|
||||
return v;
|
||||
|
||||
case 'boolean':
|
||||
return v ? 'true' : 'false';
|
||||
|
||||
case 'number':
|
||||
return isFinite(v) ? v : '';
|
||||
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
QueryString.stringify = QueryString.encode = function(obj, sep, eq, name) {
|
||||
sep = sep || '&';
|
||||
eq = eq || '=';
|
||||
obj = (obj === null) ? undefined : obj;
|
||||
|
||||
switch (typeof obj) {
|
||||
case 'object':
|
||||
return Object.keys(obj).map(function(k) {
|
||||
if (Array.isArray(obj[k])) {
|
||||
return obj[k].map(function(v) {
|
||||
return QueryString.escape(stringifyPrimitive(k)) +
|
||||
eq +
|
||||
QueryString.escape(stringifyPrimitive(v));
|
||||
}).join(sep);
|
||||
} else {
|
||||
return QueryString.escape(stringifyPrimitive(k)) +
|
||||
eq +
|
||||
QueryString.escape(stringifyPrimitive(obj[k]));
|
||||
}
|
||||
}).join(sep);
|
||||
|
||||
default:
|
||||
if (!name) return '';
|
||||
return QueryString.escape(stringifyPrimitive(name)) + eq +
|
||||
QueryString.escape(stringifyPrimitive(obj));
|
||||
}
|
||||
};
|
||||
|
||||
// Parse a key=val string.
|
||||
QueryString.parse = QueryString.decode = function(qs, sep, eq, options) {
|
||||
sep = sep || '&';
|
||||
eq = eq || '=';
|
||||
var obj = {},
|
||||
maxKeys = 1000;
|
||||
|
||||
// Handle maxKeys = 0 case
|
||||
if (options && typeof options.maxKeys === 'number') {
|
||||
maxKeys = options.maxKeys;
|
||||
}
|
||||
|
||||
if (typeof qs !== 'string' || qs.length === 0) {
|
||||
return obj;
|
||||
}
|
||||
|
||||
var regexp = /\+/g;
|
||||
qs = qs.split(sep);
|
||||
|
||||
// maxKeys <= 0 means that we should not limit keys count
|
||||
if (maxKeys > 0) {
|
||||
qs = qs.slice(0, maxKeys);
|
||||
}
|
||||
|
||||
for (var i = 0, len = qs.length; i < len; ++i) {
|
||||
var x = qs[i].replace(regexp, '%20'),
|
||||
idx = x.indexOf(eq),
|
||||
kstr = x.substring(0, idx),
|
||||
vstr = x.substring(idx + 1), k, v;
|
||||
|
||||
try {
|
||||
k = decodeURIComponent(kstr);
|
||||
v = decodeURIComponent(vstr);
|
||||
} catch (e) {
|
||||
k = QueryString.unescape(kstr, true);
|
||||
v = QueryString.unescape(vstr, true);
|
||||
}
|
||||
|
||||
if (!hasOwnProperty(obj, k)) {
|
||||
obj[k] = v;
|
||||
} else if (!Array.isArray(obj[k])) {
|
||||
obj[k] = [obj[k], v];
|
||||
} else {
|
||||
obj[k].push(v);
|
||||
}
|
||||
}
|
||||
|
||||
return obj;
|
||||
};
|
|
@ -0,0 +1,635 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
var punycode = require('punycode');
|
||||
|
||||
exports.parse = urlParse;
|
||||
exports.resolve = urlResolve;
|
||||
exports.resolveObject = urlResolveObject;
|
||||
exports.format = urlFormat;
|
||||
|
||||
// Reference: RFC 3986, RFC 1808, RFC 2396
|
||||
|
||||
// define these here so at least they only have to be
|
||||
// compiled once on the first module load.
|
||||
var protocolPattern = /^([a-z0-9.+-]+:)/i,
|
||||
portPattern = /:[0-9]*$/,
|
||||
// RFC 2396: characters reserved for delimiting URLs.
|
||||
delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
|
||||
// RFC 2396: characters not allowed for various reasons.
|
||||
unwise = ['{', '}', '|', '\\', '^', '~', '`'].concat(delims),
|
||||
// Allowed by RFCs, but cause of XSS attacks. Always escape these.
|
||||
autoEscape = ['\''],
|
||||
// Characters that are never ever allowed in a hostname.
|
||||
// Note that any invalid chars are also handled, but these
|
||||
// are the ones that are *expected* to be seen, so we fast-path
|
||||
// them.
|
||||
nonHostChars = ['%', '/', '?', ';', '#']
|
||||
.concat(unwise).concat(autoEscape),
|
||||
nonAuthChars = ['/', '@', '?', '#'].concat(delims),
|
||||
hostnameMaxLen = 255,
|
||||
hostnamePartPattern = /^[a-zA-Z0-9][a-z0-9A-Z_-]{0,62}$/,
|
||||
hostnamePartStart = /^([a-zA-Z0-9][a-z0-9A-Z_-]{0,62})(.*)$/,
|
||||
// protocols that can allow "unsafe" and "unwise" chars.
|
||||
unsafeProtocol = {
|
||||
'javascript': true,
|
||||
'javascript:': true
|
||||
},
|
||||
// protocols that never have a hostname.
|
||||
hostlessProtocol = {
|
||||
'javascript': true,
|
||||
'javascript:': true
|
||||
},
|
||||
// protocols that always have a path component.
|
||||
pathedProtocol = {
|
||||
'http': true,
|
||||
'https': true,
|
||||
'ftp': true,
|
||||
'gopher': true,
|
||||
'file': true,
|
||||
'http:': true,
|
||||
'ftp:': true,
|
||||
'gopher:': true,
|
||||
'file:': true
|
||||
},
|
||||
// protocols that always contain a // bit.
|
||||
slashedProtocol = {
|
||||
'http': true,
|
||||
'https': true,
|
||||
'ftp': true,
|
||||
'gopher': true,
|
||||
'file': true,
|
||||
'http:': true,
|
||||
'https:': true,
|
||||
'ftp:': true,
|
||||
'gopher:': true,
|
||||
'file:': true
|
||||
},
|
||||
querystring = require('querystring');
|
||||
|
||||
function urlParse(url, parseQueryString, slashesDenoteHost) {
|
||||
if (url && typeof(url) === 'object' && url.href) return url;
|
||||
|
||||
if (typeof url !== 'string') {
|
||||
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
|
||||
}
|
||||
|
||||
var out = {},
|
||||
rest = url;
|
||||
|
||||
// cut off any delimiters.
|
||||
// This is to support parse stuff like "<http://foo.com>"
|
||||
for (var i = 0, l = rest.length; i < l; i++) {
|
||||
if (delims.indexOf(rest.charAt(i)) === -1) break;
|
||||
}
|
||||
if (i !== 0) rest = rest.substr(i);
|
||||
|
||||
|
||||
var proto = protocolPattern.exec(rest);
|
||||
if (proto) {
|
||||
proto = proto[0];
|
||||
var lowerProto = proto.toLowerCase();
|
||||
out.protocol = lowerProto;
|
||||
rest = rest.substr(proto.length);
|
||||
}
|
||||
|
||||
// figure out if it's got a host
|
||||
// user@server is *always* interpreted as a hostname, and url
|
||||
// resolution will treat //foo/bar as host=foo,path=bar because that's
|
||||
// how the browser resolves relative URLs.
|
||||
if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
|
||||
var slashes = rest.substr(0, 2) === '//';
|
||||
if (slashes && !(proto && hostlessProtocol[proto])) {
|
||||
rest = rest.substr(2);
|
||||
out.slashes = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hostlessProtocol[proto] &&
|
||||
(slashes || (proto && !slashedProtocol[proto]))) {
|
||||
// there's a hostname.
|
||||
// the first instance of /, ?, ;, or # ends the host.
|
||||
// don't enforce full RFC correctness, just be unstupid about it.
|
||||
|
||||
// If there is an @ in the hostname, then non-host chars *are* allowed
|
||||
// to the left of the first @ sign, unless some non-auth character
|
||||
// comes *before* the @-sign.
|
||||
// URLs are obnoxious.
|
||||
var atSign = rest.indexOf('@');
|
||||
if (atSign !== -1) {
|
||||
var auth = rest.slice(0, atSign);
|
||||
|
||||
// there *may be* an auth
|
||||
var hasAuth = true;
|
||||
for (var i = 0, l = nonAuthChars.length; i < l; i++) {
|
||||
if (auth.indexOf(nonAuthChars[i]) !== -1) {
|
||||
// not a valid auth. Something like http://foo.com/bar@baz/
|
||||
hasAuth = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasAuth) {
|
||||
// pluck off the auth portion.
|
||||
out.auth = decodeURIComponent(auth);
|
||||
rest = rest.substr(atSign + 1);
|
||||
}
|
||||
}
|
||||
|
||||
var firstNonHost = -1;
|
||||
for (var i = 0, l = nonHostChars.length; i < l; i++) {
|
||||
var index = rest.indexOf(nonHostChars[i]);
|
||||
if (index !== -1 &&
|
||||
(firstNonHost < 0 || index < firstNonHost)) firstNonHost = index;
|
||||
}
|
||||
|
||||
if (firstNonHost !== -1) {
|
||||
out.host = rest.substr(0, firstNonHost);
|
||||
rest = rest.substr(firstNonHost);
|
||||
} else {
|
||||
out.host = rest;
|
||||
rest = '';
|
||||
}
|
||||
|
||||
// pull out port.
|
||||
var p = parseHost(out.host);
|
||||
var keys = Object.keys(p);
|
||||
for (var i = 0, l = keys.length; i < l; i++) {
|
||||
var key = keys[i];
|
||||
out[key] = p[key];
|
||||
}
|
||||
|
||||
// we've indicated that there is a hostname,
|
||||
// so even if it's empty, it has to be present.
|
||||
out.hostname = out.hostname || '';
|
||||
|
||||
// if hostname begins with [ and ends with ]
|
||||
// assume that it's an IPv6 address.
|
||||
var ipv6Hostname = out.hostname[0] === '[' &&
|
||||
out.hostname[out.hostname.length - 1] === ']';
|
||||
|
||||
// validate a little.
|
||||
if (out.hostname.length > hostnameMaxLen) {
|
||||
out.hostname = '';
|
||||
} else if (!ipv6Hostname) {
|
||||
var hostparts = out.hostname.split(/\./);
|
||||
for (var i = 0, l = hostparts.length; i < l; i++) {
|
||||
var part = hostparts[i];
|
||||
if (!part) continue;
|
||||
if (!part.match(hostnamePartPattern)) {
|
||||
var newpart = '';
|
||||
for (var j = 0, k = part.length; j < k; j++) {
|
||||
if (part.charCodeAt(j) > 127) {
|
||||
// we replace non-ASCII char with a temporary placeholder
|
||||
// we need this to make sure size of hostname is not
|
||||
// broken by replacing non-ASCII by nothing
|
||||
newpart += 'x';
|
||||
} else {
|
||||
newpart += part[j];
|
||||
}
|
||||
}
|
||||
// we test again with ASCII char only
|
||||
if (!newpart.match(hostnamePartPattern)) {
|
||||
var validParts = hostparts.slice(0, i);
|
||||
var notHost = hostparts.slice(i + 1);
|
||||
var bit = part.match(hostnamePartStart);
|
||||
if (bit) {
|
||||
validParts.push(bit[1]);
|
||||
notHost.unshift(bit[2]);
|
||||
}
|
||||
if (notHost.length) {
|
||||
rest = '/' + notHost.join('.') + rest;
|
||||
}
|
||||
out.hostname = validParts.join('.');
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// hostnames are always lower case.
|
||||
out.hostname = out.hostname.toLowerCase();
|
||||
|
||||
if (!ipv6Hostname) {
|
||||
// IDNA Support: Returns a puny coded representation of "domain".
|
||||
// It only converts the part of the domain name that
|
||||
// has non ASCII characters. I.e. it dosent matter if
|
||||
// you call it with a domain that already is in ASCII.
|
||||
var domainArray = out.hostname.split('.');
|
||||
var newOut = [];
|
||||
for (var i = 0; i < domainArray.length; ++i) {
|
||||
var s = domainArray[i];
|
||||
newOut.push(s.match(/[^A-Za-z0-9_-]/) ?
|
||||
'xn--' + punycode.encode(s) : s);
|
||||
}
|
||||
out.hostname = newOut.join('.');
|
||||
}
|
||||
|
||||
out.host = (out.hostname || '') +
|
||||
((out.port) ? ':' + out.port : '');
|
||||
out.href += out.host;
|
||||
|
||||
// strip [ and ] from the hostname
|
||||
if (ipv6Hostname) {
|
||||
out.hostname = out.hostname.substr(1, out.hostname.length - 2);
|
||||
if (rest[0] !== '/') {
|
||||
rest = '/' + rest;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// now rest is set to the post-host stuff.
|
||||
// chop off any delim chars.
|
||||
if (!unsafeProtocol[lowerProto]) {
|
||||
|
||||
// First, make 100% sure that any "autoEscape" chars get
|
||||
// escaped, even if encodeURIComponent doesn't think they
|
||||
// need to be.
|
||||
for (var i = 0, l = autoEscape.length; i < l; i++) {
|
||||
var ae = autoEscape[i];
|
||||
var esc = encodeURIComponent(ae);
|
||||
if (esc === ae) {
|
||||
esc = escape(ae);
|
||||
}
|
||||
rest = rest.split(ae).join(esc);
|
||||
}
|
||||
|
||||
// Now make sure that delims never appear in a url.
|
||||
var chop = rest.length;
|
||||
for (var i = 0, l = delims.length; i < l; i++) {
|
||||
var c = rest.indexOf(delims[i]);
|
||||
if (c !== -1) {
|
||||
chop = Math.min(c, chop);
|
||||
}
|
||||
}
|
||||
rest = rest.substr(0, chop);
|
||||
}
|
||||
|
||||
|
||||
// chop off from the tail first.
|
||||
var hash = rest.indexOf('#');
|
||||
if (hash !== -1) {
|
||||
// got a fragment string.
|
||||
out.hash = rest.substr(hash);
|
||||
rest = rest.slice(0, hash);
|
||||
}
|
||||
var qm = rest.indexOf('?');
|
||||
if (qm !== -1) {
|
||||
out.search = rest.substr(qm);
|
||||
out.query = rest.substr(qm + 1);
|
||||
if (parseQueryString) {
|
||||
out.query = querystring.parse(out.query);
|
||||
}
|
||||
rest = rest.slice(0, qm);
|
||||
} else if (parseQueryString) {
|
||||
// no query string, but parseQueryString still requested
|
||||
out.search = '';
|
||||
out.query = {};
|
||||
}
|
||||
if (rest) out.pathname = rest;
|
||||
if (slashedProtocol[proto] &&
|
||||
out.hostname && !out.pathname) {
|
||||
out.pathname = '/';
|
||||
}
|
||||
|
||||
//to support http.request
|
||||
if (out.pathname || out.search) {
|
||||
out.path = (out.pathname ? out.pathname : '') +
|
||||
(out.search ? out.search : '');
|
||||
}
|
||||
|
||||
// finally, reconstruct the href based on what has been validated.
|
||||
out.href = urlFormat(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
// format a parsed object into a url string
|
||||
function urlFormat(obj) {
|
||||
// ensure it's an object, and not a string url.
|
||||
// If it's an obj, this is a no-op.
|
||||
// this way, you can call url_format() on strings
|
||||
// to clean up potentially wonky urls.
|
||||
if (typeof(obj) === 'string') obj = urlParse(obj);
|
||||
|
||||
var auth = obj.auth || '';
|
||||
if (auth) {
|
||||
auth = encodeURIComponent(auth);
|
||||
auth = auth.replace(/%3A/i, ':');
|
||||
auth += '@';
|
||||
}
|
||||
|
||||
var protocol = obj.protocol || '',
|
||||
pathname = obj.pathname || '',
|
||||
hash = obj.hash || '',
|
||||
host = false,
|
||||
query = '';
|
||||
|
||||
if (obj.host !== undefined) {
|
||||
host = auth + obj.host;
|
||||
} else if (obj.hostname !== undefined) {
|
||||
host = auth + (obj.hostname.indexOf(':') === -1 ?
|
||||
obj.hostname :
|
||||
'[' + obj.hostname + ']');
|
||||
if (obj.port) {
|
||||
host += ':' + obj.port;
|
||||
}
|
||||
}
|
||||
|
||||
if (obj.query && typeof obj.query === 'object' &&
|
||||
Object.keys(obj.query).length) {
|
||||
query = querystring.stringify(obj.query);
|
||||
}
|
||||
|
||||
var search = obj.search || (query && ('?' + query)) || '';
|
||||
|
||||
if (protocol && protocol.substr(-1) !== ':') protocol += ':';
|
||||
|
||||
// only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
|
||||
// unless they had them to begin with.
|
||||
if (obj.slashes ||
|
||||
(!protocol || slashedProtocol[protocol]) && host !== false) {
|
||||
host = '//' + (host || '');
|
||||
if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
|
||||
} else if (!host) {
|
||||
host = '';
|
||||
}
|
||||
|
||||
if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
|
||||
if (search && search.charAt(0) !== '?') search = '?' + search;
|
||||
|
||||
return protocol + host + pathname + search + hash;
|
||||
}
|
||||
|
||||
function urlResolve(source, relative) {
|
||||
return urlFormat(urlResolveObject(source, relative));
|
||||
}
|
||||
|
||||
function urlResolveObject(source, relative) {
|
||||
if (!source) return relative;
|
||||
|
||||
source = urlParse(urlFormat(source), false, true);
|
||||
relative = urlParse(urlFormat(relative), false, true);
|
||||
|
||||
// hash is always overridden, no matter what.
|
||||
source.hash = relative.hash;
|
||||
|
||||
if (relative.href === '') {
|
||||
source.href = urlFormat(source);
|
||||
return source;
|
||||
}
|
||||
|
||||
// hrefs like //foo/bar always cut to the protocol.
|
||||
if (relative.slashes && !relative.protocol) {
|
||||
relative.protocol = source.protocol;
|
||||
//urlParse appends trailing / to urls like http://www.example.com
|
||||
if (slashedProtocol[relative.protocol] &&
|
||||
relative.hostname && !relative.pathname) {
|
||||
relative.path = relative.pathname = '/';
|
||||
}
|
||||
relative.href = urlFormat(relative);
|
||||
return relative;
|
||||
}
|
||||
|
||||
if (relative.protocol && relative.protocol !== source.protocol) {
|
||||
// if it's a known url protocol, then changing
|
||||
// the protocol does weird things
|
||||
// first, if it's not file:, then we MUST have a host,
|
||||
// and if there was a path
|
||||
// to begin with, then we MUST have a path.
|
||||
// if it is file:, then the host is dropped,
|
||||
// because that's known to be hostless.
|
||||
// anything else is assumed to be absolute.
|
||||
if (!slashedProtocol[relative.protocol]) {
|
||||
relative.href = urlFormat(relative);
|
||||
return relative;
|
||||
}
|
||||
source.protocol = relative.protocol;
|
||||
if (!relative.host && !hostlessProtocol[relative.protocol]) {
|
||||
var relPath = (relative.pathname || '').split('/');
|
||||
while (relPath.length && !(relative.host = relPath.shift()));
|
||||
if (!relative.host) relative.host = '';
|
||||
if (!relative.hostname) relative.hostname = '';
|
||||
if (relPath[0] !== '') relPath.unshift('');
|
||||
if (relPath.length < 2) relPath.unshift('');
|
||||
relative.pathname = relPath.join('/');
|
||||
}
|
||||
source.pathname = relative.pathname;
|
||||
source.search = relative.search;
|
||||
source.query = relative.query;
|
||||
source.host = relative.host || '';
|
||||
source.auth = relative.auth;
|
||||
source.hostname = relative.hostname || relative.host;
|
||||
source.port = relative.port;
|
||||
//to support http.request
|
||||
if (source.pathname !== undefined || source.search !== undefined) {
|
||||
source.path = (source.pathname ? source.pathname : '') +
|
||||
(source.search ? source.search : '');
|
||||
}
|
||||
source.slashes = source.slashes || relative.slashes;
|
||||
source.href = urlFormat(source);
|
||||
return source;
|
||||
}
|
||||
|
||||
var isSourceAbs = (source.pathname && source.pathname.charAt(0) === '/'),
|
||||
isRelAbs = (
|
||||
relative.host !== undefined ||
|
||||
relative.pathname && relative.pathname.charAt(0) === '/'
|
||||
),
|
||||
mustEndAbs = (isRelAbs || isSourceAbs ||
|
||||
(source.host && relative.pathname)),
|
||||
removeAllDots = mustEndAbs,
|
||||
srcPath = source.pathname && source.pathname.split('/') || [],
|
||||
relPath = relative.pathname && relative.pathname.split('/') || [],
|
||||
psychotic = source.protocol &&
|
||||
!slashedProtocol[source.protocol];
|
||||
|
||||
// if the url is a non-slashed url, then relative
|
||||
// links like ../.. should be able
|
||||
// to crawl up to the hostname, as well. This is strange.
|
||||
// source.protocol has already been set by now.
|
||||
// Later on, put the first path part into the host field.
|
||||
if (psychotic) {
|
||||
|
||||
delete source.hostname;
|
||||
delete source.port;
|
||||
if (source.host) {
|
||||
if (srcPath[0] === '') srcPath[0] = source.host;
|
||||
else srcPath.unshift(source.host);
|
||||
}
|
||||
delete source.host;
|
||||
if (relative.protocol) {
|
||||
delete relative.hostname;
|
||||
delete relative.port;
|
||||
if (relative.host) {
|
||||
if (relPath[0] === '') relPath[0] = relative.host;
|
||||
else relPath.unshift(relative.host);
|
||||
}
|
||||
delete relative.host;
|
||||
}
|
||||
mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
|
||||
}
|
||||
|
||||
if (isRelAbs) {
|
||||
// it's absolute.
|
||||
source.host = (relative.host || relative.host === '') ?
|
||||
relative.host : source.host;
|
||||
source.hostname = (relative.hostname || relative.hostname === '') ?
|
||||
relative.hostname : source.hostname;
|
||||
source.search = relative.search;
|
||||
source.query = relative.query;
|
||||
srcPath = relPath;
|
||||
// fall through to the dot-handling below.
|
||||
} else if (relPath.length) {
|
||||
// it's relative
|
||||
// throw away the existing file, and take the new path instead.
|
||||
if (!srcPath) srcPath = [];
|
||||
srcPath.pop();
|
||||
srcPath = srcPath.concat(relPath);
|
||||
source.search = relative.search;
|
||||
source.query = relative.query;
|
||||
} else if ('search' in relative) {
|
||||
// just pull out the search.
|
||||
// like href='?foo'.
|
||||
// Put this after the other two cases because it simplifies the booleans
|
||||
if (psychotic) {
|
||||
source.hostname = source.host = srcPath.shift();
|
||||
//occationaly the auth can get stuck only in host
|
||||
//this especialy happens in cases like
|
||||
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
|
||||
var authInHost = source.host && source.host.indexOf('@') > 0 ?
|
||||
source.host.split('@') : false;
|
||||
if (authInHost) {
|
||||
source.auth = authInHost.shift();
|
||||
source.host = source.hostname = authInHost.shift();
|
||||
}
|
||||
}
|
||||
source.search = relative.search;
|
||||
source.query = relative.query;
|
||||
//to support http.request
|
||||
if (source.pathname !== undefined || source.search !== undefined) {
|
||||
source.path = (source.pathname ? source.pathname : '') +
|
||||
(source.search ? source.search : '');
|
||||
}
|
||||
source.href = urlFormat(source);
|
||||
return source;
|
||||
}
|
||||
if (!srcPath.length) {
|
||||
// no path at all. easy.
|
||||
// we've already handled the other stuff above.
|
||||
delete source.pathname;
|
||||
//to support http.request
|
||||
if (!source.search) {
|
||||
source.path = '/' + source.search;
|
||||
} else {
|
||||
delete source.path;
|
||||
}
|
||||
source.href = urlFormat(source);
|
||||
return source;
|
||||
}
|
||||
// if a url ENDs in . or .., then it must get a trailing slash.
|
||||
// however, if it ends in anything else non-slashy,
|
||||
// then it must NOT get a trailing slash.
|
||||
var last = srcPath.slice(-1)[0];
|
||||
var hasTrailingSlash = (
|
||||
(source.host || relative.host) && (last === '.' || last === '..') ||
|
||||
last === '');
|
||||
|
||||
// strip single dots, resolve double dots to parent dir
|
||||
// if the path tries to go above the root, `up` ends up > 0
|
||||
var up = 0;
|
||||
for (var i = srcPath.length; i >= 0; i--) {
|
||||
last = srcPath[i];
|
||||
if (last == '.') {
|
||||
srcPath.splice(i, 1);
|
||||
} else if (last === '..') {
|
||||
srcPath.splice(i, 1);
|
||||
up++;
|
||||
} else if (up) {
|
||||
srcPath.splice(i, 1);
|
||||
up--;
|
||||
}
|
||||
}
|
||||
|
||||
// if the path is allowed to go above the root, restore leading ..s
|
||||
if (!mustEndAbs && !removeAllDots) {
|
||||
for (; up--; up) {
|
||||
srcPath.unshift('..');
|
||||
}
|
||||
}
|
||||
|
||||
if (mustEndAbs && srcPath[0] !== '' &&
|
||||
(!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
|
||||
srcPath.unshift('');
|
||||
}
|
||||
|
||||
if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
|
||||
srcPath.push('');
|
||||
}
|
||||
|
||||
var isAbsolute = srcPath[0] === '' ||
|
||||
(srcPath[0] && srcPath[0].charAt(0) === '/');
|
||||
|
||||
// put the host back
|
||||
if (psychotic) {
|
||||
source.hostname = source.host = isAbsolute ? '' :
|
||||
srcPath.length ? srcPath.shift() : '';
|
||||
//occationaly the auth can get stuck only in host
|
||||
//this especialy happens in cases like
|
||||
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
|
||||
var authInHost = source.host && source.host.indexOf('@') > 0 ?
|
||||
source.host.split('@') : false;
|
||||
if (authInHost) {
|
||||
source.auth = authInHost.shift();
|
||||
source.host = source.hostname = authInHost.shift();
|
||||
}
|
||||
}
|
||||
|
||||
mustEndAbs = mustEndAbs || (source.host && srcPath.length);
|
||||
|
||||
if (mustEndAbs && !isAbsolute) {
|
||||
srcPath.unshift('');
|
||||
}
|
||||
|
||||
source.pathname = srcPath.join('/');
|
||||
//to support request.http
|
||||
if (source.pathname !== undefined || source.search !== undefined) {
|
||||
source.path = (source.pathname ? source.pathname : '') +
|
||||
(source.search ? source.search : '');
|
||||
}
|
||||
source.auth = relative.auth || source.auth;
|
||||
source.slashes = source.slashes || relative.slashes;
|
||||
source.href = urlFormat(source);
|
||||
return source;
|
||||
}
|
||||
|
||||
function parseHost(host) {
|
||||
var out = {};
|
||||
var port = portPattern.exec(host);
|
||||
if (port) {
|
||||
port = port[0];
|
||||
if (port !== ':') {
|
||||
out.port = port.substr(1);
|
||||
}
|
||||
host = host.substr(0, host.length - port.length);
|
||||
}
|
||||
if (host) out.hostname = host;
|
||||
return out;
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
require = require("../require-polyfill")(require.valueOf());
|
||||
|
||||
var cp = require('child_process');
|
||||
var tc = require("./template-common");
|
||||
|
||||
var argv = process.argv;
|
||||
argv.shift();
|
||||
argv.shift();
|
||||
var extraArgs = argv.join(" ");
|
||||
|
||||
cp.exec("node ../../bin/webpack.js --verbose "+extraArgs+" example.js js/output.js", function (error, stdout, stderr) {
|
||||
if(stderr)
|
||||
console.log(stderr);
|
||||
if (error !== null)
|
||||
console.log(error);
|
||||
var readme = tc(require("raw!"+require("path").join(process.cwd(), "template.md")), require.context("raw!"+process.cwd()), stdout.replace(/[\r\n]*$/, ""));
|
||||
cp.exec("node ../../bin/webpack.js --verbose --no-colors --min "+extraArgs+" example.js js/output.js", function (error, stdout, stderr) {
|
||||
if(stderr)
|
||||
console.log(stderr);
|
||||
if (error !== null)
|
||||
console.log(error);
|
||||
readme = tc(readme, require.context("raw!"+process.cwd()), stdout.replace(/[\r\n]*$/, ""), "min");
|
||||
require("fs").writeFile("README.md", readme, "utf-8", function() {});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,11 @@
|
|||
var cp = require('child_process');
|
||||
|
||||
function result(error, stdout, stderr) {
|
||||
console.log(stderr);
|
||||
}
|
||||
|
||||
cp.exec("cd code-splitted-require.context && node build.js", result);
|
||||
cp.exec("cd code-splitting && node build.js", result);
|
||||
cp.exec("cd coffee-script && node build.js", result);
|
||||
cp.exec("cd loader && node build.js", result);
|
||||
cp.exec("cd require.context && node build.js", result);
|
|
@ -39,6 +39,7 @@ getTemplate("b", function(b) {
|
|||
/******/ var head = document.getElementsByTagName('head')[0];
|
||||
/******/ var script = document.createElement('script');
|
||||
/******/ script.type = 'text/javascript';
|
||||
/******/ script.charset = 'utf-8';
|
||||
/******/ script.src = modules.c+chunkId+modules.a;
|
||||
/******/ head.appendChild(script);
|
||||
/******/ }
|
||||
|
@ -57,77 +58,38 @@ getTemplate("b", function(b) {
|
|||
/******/({a:".output.js",b:"webpackJsonp",c:"",
|
||||
/******/0: function(module, exports, require) {
|
||||
|
||||
/******/ /* WEBPACK FREE VAR INJECTION */ (function(console) {
|
||||
function getTemplate(templateName, callback) {
|
||||
require.ensure(1, function(require) {
|
||||
callback(require(/* ../require.context/templates */1)("./"+templateName));
|
||||
});
|
||||
}
|
||||
getTemplate("a", function(a) {
|
||||
require(/* __webpack_console */2).log(a);
|
||||
console.log(a);
|
||||
});
|
||||
getTemplate("b", function(b) {
|
||||
require(/* __webpack_console */2).log(b);
|
||||
console.log(b);
|
||||
});
|
||||
/******/ /* WEBPACK FREE VAR INJECTION */ }(require(/* __webpack_console */2)))
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/2: function(module, exports, require) {
|
||||
|
||||
var console = window.console;
|
||||
exports.log = (console && console.log) || function() {};
|
||||
exports.info = (console && console.info) || function() {};
|
||||
exports.error = (console && console.error) || function() {};
|
||||
exports.warn = (console && console.warn) || function() {};
|
||||
exports.dir = (console && console.dir) || function() {};
|
||||
exports.time = (console && console.time) || function(label) {
|
||||
module.exports = console;
|
||||
for(var name in {log:1, info:1, error:1, warn:1, dir:1, trace:1, assert:1})
|
||||
if(!console[name])
|
||||
console[name] = function() {};
|
||||
if(!console.time)
|
||||
console.time = function(label) {
|
||||
times[label] = Date.now();
|
||||
};
|
||||
exports.timeEnd = (console && console.timeEnd) || function() {
|
||||
if(!console.timeEnd)
|
||||
console.timeEnd = function() {
|
||||
var duration = Date.now() - times[label];
|
||||
exports.log('%s: %dms', label, duration);
|
||||
console.log('%s: %dms', label, duration);
|
||||
};
|
||||
exports.trace = (console && console.trace) || function() {};
|
||||
exports.assert = (console && console.assert) || function() {};
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/})
|
||||
```
|
||||
|
||||
# js/1.output.js
|
||||
|
||||
``` javascript
|
||||
/******/webpackJsonp(1, {
|
||||
/******/1: function(module, exports, require) {
|
||||
|
||||
/***/module.exports = function(name) {
|
||||
/***/ var map = {"./b.js":3,"./a.js":4,"./c.js":5};
|
||||
/***/ return require(map[name]||map[name+".web.js"]||map[name+".js"]||name);
|
||||
/***/};
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/3: function(module, exports, require) {
|
||||
|
||||
module.exports = function() {
|
||||
return "This text was generated by template B";
|
||||
}
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/4: function(module, exports, require) {
|
||||
|
||||
module.exports = function() {
|
||||
return "This text was generated by template A";
|
||||
}
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/5: function(module, exports, require) {
|
||||
|
||||
module.exports = function() {
|
||||
return "This text was generated by template C";
|
||||
}
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
|
@ -144,22 +106,22 @@ Modules: 6
|
|||
Modules including duplicates: 6
|
||||
Modules pre chunk: 3
|
||||
Modules first chunk: 2
|
||||
output.js: 2815 characters
|
||||
1.output.js: 735 characters
|
||||
output.js: 2707 characters
|
||||
1.output.js: 780 characters
|
||||
output.js
|
||||
0 [...]\examples\code-splitted-require.context\example.js
|
||||
0 .\example.js
|
||||
main
|
||||
2 [...]\buildin\__webpack_console.js
|
||||
require (2x) from [...]\examples\code-splitted-require.context\example.js
|
||||
2 (webpack)\buildin\__webpack_console.js
|
||||
require (2x) from .\example.js
|
||||
1.output.js
|
||||
1 generated [...]\examples\require.context\templates
|
||||
async context from [...]\examples\code-splitted-require.context\example.js
|
||||
3 [...]\examples\require.context\templates\b.js
|
||||
async context from [...]\examples\code-splitted-require.context\example.js
|
||||
4 [...]\examples\require.context\templates\a.js
|
||||
async context from [...]\examples\code-splitted-require.context\example.js
|
||||
5 [...]\examples\require.context\templates\c.js
|
||||
async context from [...]\examples\code-splitted-require.context\example.js
|
||||
1 [context] ..\require.context\templates
|
||||
sync context from .\example.js
|
||||
3 ..\require.context\templates\a.js
|
||||
sync context from .\example.js
|
||||
4 ..\require.context\templates\b.js
|
||||
sync context from .\example.js
|
||||
5 ..\require.context\templates\c.js
|
||||
sync context from .\example.js
|
||||
```
|
||||
|
||||
## Minimized (uglify-js, no zip)
|
||||
|
@ -170,20 +132,20 @@ Modules: 6
|
|||
Modules including duplicates: 6
|
||||
Modules pre chunk: 3
|
||||
Modules first chunk: 2
|
||||
output.js: 1149 characters
|
||||
1.output.js: 407 characters
|
||||
output.js: 1062 characters
|
||||
1.output.js: 436 characters
|
||||
output.js
|
||||
0 [...]\examples\code-splitted-require.context\example.js
|
||||
0 .\example.js
|
||||
main
|
||||
2 [...]\buildin\__webpack_console.js
|
||||
require (2x) from [...]\examples\code-splitted-require.context\example.js
|
||||
2 (webpack)\buildin\__webpack_console.js
|
||||
require (2x) from .\example.js
|
||||
1.output.js
|
||||
1 generated [...]\examples\require.context\templates
|
||||
async context from [...]\examples\code-splitted-require.context\example.js
|
||||
3 [...]\examples\require.context\templates\a.js
|
||||
async context from [...]\examples\code-splitted-require.context\example.js
|
||||
4 [...]\examples\require.context\templates\c.js
|
||||
async context from [...]\examples\code-splitted-require.context\example.js
|
||||
5 [...]\examples\require.context\templates\b.js
|
||||
async context from [...]\examples\code-splitted-require.context\example.js
|
||||
1 [context] ..\require.context\templates
|
||||
sync context from .\example.js
|
||||
3 ..\require.context\templates\a.js
|
||||
sync context from .\example.js
|
||||
4 ..\require.context\templates\b.js
|
||||
sync context from .\example.js
|
||||
5 ..\require.context\templates\c.js
|
||||
sync context from .\example.js
|
||||
```
|
||||
|
|
|
@ -1,18 +1 @@
|
|||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
var cp = require('child_process');
|
||||
|
||||
var argv = process.argv;
|
||||
argv.shift();
|
||||
argv.shift();
|
||||
var extraArgs = argv.join(" ");
|
||||
|
||||
cp.exec("node ../../bin/webpack.js "+extraArgs+" example.js js/output.js", function (error, stdout, stderr) {
|
||||
console.log('stdout:\n' + stdout);
|
||||
console.log('stderr:\n ' + stderr);
|
||||
if (error !== null) {
|
||||
console.log('error: ' + error);
|
||||
}
|
||||
});
|
||||
require("../build-common");
|
|
@ -0,0 +1,25 @@
|
|||
# example.js
|
||||
|
||||
``` javascript
|
||||
{{example.js}}
|
||||
```
|
||||
|
||||
# js/output.js
|
||||
|
||||
``` javascript
|
||||
{{js/output.js}}
|
||||
```
|
||||
|
||||
# Info
|
||||
|
||||
## Uncompressed
|
||||
|
||||
```
|
||||
{{stdout}}
|
||||
```
|
||||
|
||||
## Minimized (uglify-js, no zip)
|
||||
|
||||
```
|
||||
{{min:stdout}}
|
||||
```
|
|
@ -35,6 +35,7 @@ require.ensure(["c"], function(require) {
|
|||
/******/ var head = document.getElementsByTagName('head')[0];
|
||||
/******/ var script = document.createElement('script');
|
||||
/******/ script.type = 'text/javascript';
|
||||
/******/ script.charset = 'utf-8';
|
||||
/******/ script.src = modules.c+chunkId+modules.a;
|
||||
/******/ head.appendChild(script);
|
||||
/******/ }
|
||||
|
@ -53,24 +54,24 @@ require.ensure(["c"], function(require) {
|
|||
/******/({a:".output.js",b:"webpackJsonp",c:"",
|
||||
/******/0: function(module, exports, require) {
|
||||
|
||||
var a = require(/* a */1);
|
||||
var b = require(/* b */3);
|
||||
var a = require(/* a */4);
|
||||
var b = require(/* b */1);
|
||||
require.ensure(1, function(require) {
|
||||
require(/* b */3).xyz();
|
||||
var d = require(/* d */2);
|
||||
require(/* b */1).xyz();
|
||||
var d = require(/* d */3);
|
||||
});
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/1: function(module, exports, require) {
|
||||
|
||||
// module a
|
||||
// module b
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/3: function(module, exports, require) {
|
||||
/******/4: function(module, exports, require) {
|
||||
|
||||
// module b
|
||||
// module a
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
|
@ -83,13 +84,13 @@ require.ensure(1, function(require) {
|
|||
/******/webpackJsonp(1, {
|
||||
/******/2: function(module, exports, require) {
|
||||
|
||||
// module d
|
||||
// module c
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/4: function(module, exports, require) {
|
||||
/******/3: function(module, exports, require) {
|
||||
|
||||
// module c
|
||||
// module d
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
|
@ -99,7 +100,7 @@ require.ensure(1, function(require) {
|
|||
Minimized
|
||||
|
||||
``` javascript
|
||||
webpackJsonp(1,{2:function(a,b,c){},4:function(a,b,c){}})
|
||||
webpackJsonp(1,{3:function(a,b,c){},4:function(a,b,c){}})
|
||||
```
|
||||
|
||||
# Info
|
||||
|
@ -112,20 +113,20 @@ Modules: 5
|
|||
Modules including duplicates: 5
|
||||
Modules pre chunk: 2.5
|
||||
Modules first chunk: 3
|
||||
output.js: 2033 characters
|
||||
output.js: 2114 characters
|
||||
1.output.js: 200 characters
|
||||
output.js
|
||||
0 [...]\examples\code-splitting\example.js
|
||||
0 .\example.js
|
||||
main
|
||||
1 [...]\examples\code-splitting\node_modules\a.js
|
||||
require (1x) from [...]\examples\code-splitting\example.js
|
||||
3 [...]\examples\code-splitting\node_modules\b.js
|
||||
require (2x) from [...]\examples\code-splitting\example.js
|
||||
1 .\node_modules\b.js
|
||||
require (2x) from .\example.js
|
||||
4 .\node_modules\a.js
|
||||
require (1x) from .\example.js
|
||||
1.output.js
|
||||
2 [...]\examples\code-splitting\node_modules\d.js
|
||||
async require (1x) from [...]\examples\code-splitting\example.js
|
||||
4 [...]\examples\code-splitting\node_modules\c.js
|
||||
async require (1x) from [...]\examples\code-splitting\example.js
|
||||
2 .\node_modules\c.js
|
||||
async require (1x) from .\example.js
|
||||
3 .\node_modules\d.js
|
||||
async require (1x) from .\example.js
|
||||
```
|
||||
|
||||
## Minimized (uglify-js, no zip)
|
||||
|
@ -136,18 +137,18 @@ Modules: 5
|
|||
Modules including duplicates: 5
|
||||
Modules pre chunk: 2.5
|
||||
Modules first chunk: 3
|
||||
output.js: 729 characters
|
||||
output.js: 747 characters
|
||||
1.output.js: 57 characters
|
||||
output.js
|
||||
0 [...]\examples\code-splitting\example.js
|
||||
0 .\example.js
|
||||
main
|
||||
1 [...]\examples\code-splitting\node_modules\a.js
|
||||
require (1x) from [...]\examples\code-splitting\example.js
|
||||
3 [...]\examples\code-splitting\node_modules\b.js
|
||||
require (2x) from [...]\examples\code-splitting\example.js
|
||||
1 .\node_modules\a.js
|
||||
require (1x) from .\example.js
|
||||
2 .\node_modules\b.js
|
||||
require (2x) from .\example.js
|
||||
1.output.js
|
||||
2 [...]\examples\code-splitting\node_modules\c.js
|
||||
async require (1x) from [...]\examples\code-splitting\example.js
|
||||
4 [...]\examples\code-splitting\node_modules\d.js
|
||||
async require (1x) from [...]\examples\code-splitting\example.js
|
||||
3 .\node_modules\d.js
|
||||
async require (1x) from .\example.js
|
||||
4 .\node_modules\c.js
|
||||
async require (1x) from .\example.js
|
||||
```
|
||||
|
|
|
@ -1,18 +1 @@
|
|||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
var cp = require('child_process');
|
||||
|
||||
var argv = process.argv;
|
||||
argv.shift();
|
||||
argv.shift();
|
||||
var extraArgs = argv.join(" ");
|
||||
|
||||
cp.exec("node ../../bin/webpack.js "+extraArgs+" example.js js/output.js", function (error, stdout, stderr) {
|
||||
console.log('stdout:\n' + stdout);
|
||||
console.log('stderr:\n ' + stderr);
|
||||
if (error !== null) {
|
||||
console.log('error: ' + error);
|
||||
}
|
||||
});
|
||||
require("../build-common");
|
|
@ -0,0 +1,38 @@
|
|||
# example.js
|
||||
|
||||
``` javascript
|
||||
{{example.js}}
|
||||
```
|
||||
|
||||
|
||||
# js/output.js
|
||||
|
||||
``` javascript
|
||||
{{js/output.js}}
|
||||
```
|
||||
|
||||
# 1.output.js
|
||||
|
||||
``` javascript
|
||||
{{js/1.output.js}}
|
||||
```
|
||||
|
||||
Minimized
|
||||
|
||||
``` javascript
|
||||
{{min:js/1.output.js}}
|
||||
```
|
||||
|
||||
# Info
|
||||
|
||||
## Uncompressed
|
||||
|
||||
```
|
||||
{{stdout}}
|
||||
```
|
||||
|
||||
## Minimized (uglify-js, no zip)
|
||||
|
||||
```
|
||||
{{min:stdout}}
|
||||
```
|
|
@ -1,3 +1,4 @@
|
|||
|
||||
# example.js
|
||||
|
||||
``` javascript
|
||||
|
@ -45,27 +46,28 @@ module.exports = 42
|
|||
/******/({
|
||||
/******/0: function(module, exports, require) {
|
||||
|
||||
require(/* __webpack_console */1).log(require(/* ./cup1.coffee */2));
|
||||
/******/ /* WEBPACK FREE VAR INJECTION */ (function(console) {
|
||||
console.log(require(/* ./cup1.coffee */2));
|
||||
/******/ /* WEBPACK FREE VAR INJECTION */ }(require(/* __webpack_console */1)))
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/1: function(module, exports, require) {
|
||||
|
||||
var console = window.console;
|
||||
exports.log = (console && console.log) || function() {};
|
||||
exports.info = (console && console.info) || function() {};
|
||||
exports.error = (console && console.error) || function() {};
|
||||
exports.warn = (console && console.warn) || function() {};
|
||||
exports.dir = (console && console.dir) || function() {};
|
||||
exports.time = (console && console.time) || function(label) {
|
||||
module.exports = console;
|
||||
for(var name in {log:1, info:1, error:1, warn:1, dir:1, trace:1, assert:1})
|
||||
if(!console[name])
|
||||
console[name] = function() {};
|
||||
if(!console.time)
|
||||
console.time = function(label) {
|
||||
times[label] = Date.now();
|
||||
};
|
||||
exports.timeEnd = (console && console.timeEnd) || function() {
|
||||
if(!console.timeEnd)
|
||||
console.timeEnd = function() {
|
||||
var duration = Date.now() - times[label];
|
||||
exports.log('%s: %dms', label, duration);
|
||||
console.log('%s: %dms', label, duration);
|
||||
};
|
||||
exports.trace = (console && console.trace) || function() {};
|
||||
exports.assert = (console && console.assert) || function() {};
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
|
@ -87,14 +89,16 @@ exports.assert = (console && console.assert) || function() {};
|
|||
/******/
|
||||
/******/3: function(module, exports, require) {
|
||||
|
||||
/******/ /* WEBPACK FREE VAR INJECTION */ (function(console) {
|
||||
(function() {
|
||||
|
||||
require(/* __webpack_console */1).log("yeah coffee-script");
|
||||
console.log("yeah coffee-script");
|
||||
|
||||
module.exports = 42;
|
||||
|
||||
}).call(this);
|
||||
|
||||
/******/ /* WEBPACK FREE VAR INJECTION */ }(require(/* __webpack_console */1)))
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
|
@ -111,17 +115,17 @@ Modules: 4
|
|||
Modules including duplicates: 4
|
||||
Modules pre chunk: 4
|
||||
Modules first chunk: 4
|
||||
output.js: 2002 characters
|
||||
output.js: 1968 characters
|
||||
output.js
|
||||
0 [...]\examples\coffee-script\example.js
|
||||
0 .\example.js
|
||||
main
|
||||
1 [...]\buildin\__webpack_console.js
|
||||
require (1x) from [...]\examples\coffee-script\example.js
|
||||
require (1x) from [...]\examples\coffee-script\cup2.coffee
|
||||
2 [...]\node_modules\coffee-loader.js![...]\examples\coffee-script\cup1.coffee
|
||||
require (1x) from [...]\examples\coffee-script\example.js
|
||||
3 [...]\node_modules\coffee-loader.js![...]\examples\coffee-script\cup2.coffee
|
||||
require (2x) from [...]\examples\coffee-script\cup1.coffee
|
||||
1 (webpack)\buildin\__webpack_console.js
|
||||
require (1x) from .\example.js
|
||||
require (1x) from .\cup2.coffee
|
||||
2 (webpack)\node_modules\coffee-loader\index.js!.\cup1.coffee
|
||||
require (1x) from .\example.js
|
||||
3 (webpack)\node_modules\coffee-loader\index.js!.\cup2.coffee
|
||||
require (2x) from .\cup1.coffee
|
||||
```
|
||||
|
||||
## Minimized (uglify-js, no zip)
|
||||
|
@ -132,15 +136,15 @@ Modules: 4
|
|||
Modules including duplicates: 4
|
||||
Modules pre chunk: 4
|
||||
Modules first chunk: 4
|
||||
output.js: 868 characters
|
||||
output.js: 784 characters
|
||||
output.js
|
||||
0 [...]\examples\coffee-script\example.js
|
||||
0 .\example.js
|
||||
main
|
||||
1 [...]\buildin\__webpack_console.js
|
||||
require (1x) from [...]\examples\coffee-script\example.js
|
||||
require (1x) from [...]\examples\coffee-script\cup2.coffee
|
||||
2 [...]\node_modules\coffee-loader.js![...]\examples\coffee-script\cup1.coffee
|
||||
require (1x) from [...]\examples\coffee-script\example.js
|
||||
3 [...]\node_modules\coffee-loader.js![...]\examples\coffee-script\cup2.coffee
|
||||
require (2x) from [...]\examples\coffee-script\cup1.coffee
|
||||
1 (webpack)\buildin\__webpack_console.js
|
||||
require (1x) from .\example.js
|
||||
require (1x) from .\cup2.coffee
|
||||
2 (webpack)\node_modules\coffee-loader\index.js!.\cup1.coffee
|
||||
require (1x) from .\example.js
|
||||
3 (webpack)\node_modules\coffee-loader\index.js!.\cup2.coffee
|
||||
require (2x) from .\cup1.coffee
|
||||
```
|
|
@ -1,18 +1 @@
|
|||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
var cp = require('child_process');
|
||||
|
||||
var argv = process.argv;
|
||||
argv.shift();
|
||||
argv.shift();
|
||||
var extraArgs = argv.join(" ");
|
||||
|
||||
cp.exec("node ../../bin/webpack.js "+extraArgs+" example.js js/output.js", function (error, stdout, stderr) {
|
||||
console.log('stdout:\n' + stdout);
|
||||
console.log('stderr:\n ' + stderr);
|
||||
if (error !== null) {
|
||||
console.log('error: ' + error);
|
||||
}
|
||||
});
|
||||
require("../build-common");
|
|
@ -0,0 +1,38 @@
|
|||
|
||||
# example.js
|
||||
|
||||
``` javascript
|
||||
{{example.js}}
|
||||
```
|
||||
|
||||
# cup1.coffee
|
||||
|
||||
``` coffee-script
|
||||
{{cup1.coffee}}
|
||||
```
|
||||
|
||||
# cup2.coffee
|
||||
|
||||
``` coffee-script
|
||||
{{cup2.coffee}}
|
||||
```
|
||||
|
||||
# js/output.js
|
||||
|
||||
``` javascript
|
||||
{{js/output.js}}
|
||||
```
|
||||
|
||||
# Info
|
||||
|
||||
## Uncompressed
|
||||
|
||||
```
|
||||
{{stdout}}
|
||||
```
|
||||
|
||||
## Minimized (uglify-js, no zip)
|
||||
|
||||
```
|
||||
{{min:stdout}}
|
||||
```
|
|
@ -22,14 +22,14 @@ exports.foo = "bar";
|
|||
|
||||
``` javascript
|
||||
module.exports = function(contents, options, callback) {
|
||||
|
||||
|
||||
if(contents.length !== 1)
|
||||
throw new Error("loader takes exactly one file as parameter");
|
||||
|
||||
|
||||
if(callback) {
|
||||
// compile for web
|
||||
callback(null /* no error */,
|
||||
"exports.answer = 42;\n" +
|
||||
callback(null /* no error */,
|
||||
"exports.answer = 42;\n" +
|
||||
contents[0]);
|
||||
} else {
|
||||
// execute for node.js
|
||||
|
@ -74,55 +74,57 @@ module.exports = function(contents, options, callback) {
|
|||
/******/({
|
||||
/******/0: function(module, exports, require) {
|
||||
|
||||
/******/ /* WEBPACK FREE VAR INJECTION */ (function(console) {
|
||||
// Polyfill require for node.js usage of loaders
|
||||
require = require(/* ../../require-polyfill */3)(require.valueOf());
|
||||
require = require(/* ../../require-polyfill */1)(require.valueOf());
|
||||
|
||||
// use our loader
|
||||
require(/* __webpack_console */1).dir(require(/* ./loader!./file */2));
|
||||
console.dir(require(/* ./loader!./file */3));
|
||||
|
||||
// use buildin json loader
|
||||
require(/* __webpack_console */1).dir(require(/* ./test.json */4)); // default by extension
|
||||
require(/* __webpack_console */1).dir(require(/* json!./test.json */4)); // manual
|
||||
console.dir(require(/* ./test.json */4)); // default by extension
|
||||
console.dir(require(/* json!./test.json */4)); // manual
|
||||
/******/ /* WEBPACK FREE VAR INJECTION */ }(require(/* __webpack_console */2)))
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/1: function(module, exports, require) {
|
||||
|
||||
var console = window.console;
|
||||
exports.log = (console && console.log) || function() {};
|
||||
exports.info = (console && console.info) || function() {};
|
||||
exports.error = (console && console.error) || function() {};
|
||||
exports.warn = (console && console.warn) || function() {};
|
||||
exports.dir = (console && console.dir) || function() {};
|
||||
exports.time = (console && console.time) || function(label) {
|
||||
times[label] = Date.now();
|
||||
};
|
||||
exports.timeEnd = (console && console.timeEnd) || function() {
|
||||
var duration = Date.now() - times[label];
|
||||
exports.log('%s: %dms', label, duration);
|
||||
};
|
||||
exports.trace = (console && console.trace) || function() {};
|
||||
exports.assert = (console && console.assert) || function() {};
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/2: function(module, exports, require) {
|
||||
|
||||
exports.answer = 42;
|
||||
exports.foo = "bar";
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/3: function(module, exports, require) {
|
||||
|
||||
// No polyfill needed when compiled with webpack
|
||||
module.exports = function(r){return r}
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/2: function(module, exports, require) {
|
||||
|
||||
var console = window.console;
|
||||
module.exports = console;
|
||||
for(var name in {log:1, info:1, error:1, warn:1, dir:1, trace:1, assert:1})
|
||||
if(!console[name])
|
||||
console[name] = function() {};
|
||||
if(!console.time)
|
||||
console.time = function(label) {
|
||||
times[label] = Date.now();
|
||||
};
|
||||
if(!console.timeEnd)
|
||||
console.timeEnd = function() {
|
||||
var duration = Date.now() - times[label];
|
||||
console.log('%s: %dms', label, duration);
|
||||
};
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/3: function(module, exports, require) {
|
||||
|
||||
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/4: function(module, exports, require) {
|
||||
|
||||
module.exports = {"foobar":1234}
|
||||
module.exports = {
|
||||
"foobar": 1234
|
||||
}
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
|
@ -149,17 +151,17 @@ Modules: 5
|
|||
Modules including duplicates: 5
|
||||
Modules pre chunk: 5
|
||||
Modules first chunk: 5
|
||||
output.js: 2279 characters
|
||||
output.js: 2048 characters
|
||||
output.js
|
||||
0 [...]\examples\loader\example.js
|
||||
0 .\example.js
|
||||
main
|
||||
1 [...]\buildin\__webpack_console.js
|
||||
require (3x) from [...]\examples\loader\example.js
|
||||
2 [...]\examples\loader\loader.js![...]\examples\loader\file.js
|
||||
require (1x) from [...]\examples\loader\example.js
|
||||
3 [...]\require-polyfill.web.js
|
||||
require (1x) from [...]\examples\loader\example.js
|
||||
4 [...]\node_modules\json-loader.js![...]\examples\loader\test.json
|
||||
require (1x) from [...]\examples\loader\example.js
|
||||
require (1x) from [...]\examples\loader\example.js
|
||||
1 (webpack)\require-polyfill.web.js
|
||||
require (1x) from .\example.js
|
||||
2 (webpack)\buildin\__webpack_console.js
|
||||
require (3x) from .\example.js
|
||||
3 .\loader.js!.\file.js
|
||||
require (1x) from .\example.js
|
||||
4 (webpack)\node_modules\json-loader\index.js!.\test.json
|
||||
require (1x) from .\example.js
|
||||
require (1x) from .\example.js
|
||||
```
|
|
@ -1,18 +1 @@
|
|||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
var cp = require('child_process');
|
||||
|
||||
var argv = process.argv;
|
||||
argv.shift();
|
||||
argv.shift();
|
||||
var extraArgs = argv.join(" ");
|
||||
|
||||
cp.exec("node ../../bin/webpack.js "+extraArgs+" example.js js/output.js", function (error, stdout, stderr) {
|
||||
console.log('stdout:\n' + stdout);
|
||||
console.log('stderr:\n ' + stderr);
|
||||
if (error !== null) {
|
||||
console.log('error: ' + error);
|
||||
}
|
||||
});
|
||||
require("../build-common");
|
|
@ -0,0 +1,47 @@
|
|||
# example.js
|
||||
|
||||
``` javascript
|
||||
{{example.js}}
|
||||
```
|
||||
|
||||
# file.js
|
||||
|
||||
``` javascript
|
||||
{{file.js}}
|
||||
```
|
||||
|
||||
# loader.js
|
||||
|
||||
``` javascript
|
||||
{{loader.js}}
|
||||
```
|
||||
|
||||
# test.json
|
||||
|
||||
``` javascript
|
||||
{{test.json}}
|
||||
```
|
||||
|
||||
# js/output.js
|
||||
|
||||
``` javascript
|
||||
{{js/output.js}}
|
||||
```
|
||||
|
||||
# Console output
|
||||
|
||||
Prints in node.js (`node example.js`) and in browser:
|
||||
|
||||
```
|
||||
{ answer: 42, foo: 'bar' }
|
||||
{ foobar: 1234 }
|
||||
{ foobar: 1234 }
|
||||
```
|
||||
|
||||
# Info
|
||||
|
||||
## Uncompressed
|
||||
|
||||
```
|
||||
{{stdout}}
|
||||
```
|
|
@ -45,40 +45,41 @@ module.exports = function() {
|
|||
/******/({
|
||||
/******/0: function(module, exports, require) {
|
||||
|
||||
/******/ /* WEBPACK FREE VAR INJECTION */ (function(console) {
|
||||
function getTemplate(templateName) {
|
||||
return require(/* ./templates */2)("./"+templateName);
|
||||
return require(/* ./templates */1)("./"+templateName);
|
||||
}
|
||||
require(/* __webpack_console */1).log(getTemplate("a"));
|
||||
require(/* __webpack_console */1).log(getTemplate("b"));
|
||||
console.log(getTemplate("a"));
|
||||
console.log(getTemplate("b"));
|
||||
/******/ /* WEBPACK FREE VAR INJECTION */ }(require(/* __webpack_console */2)))
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/1: function(module, exports, require) {
|
||||
|
||||
var console = window.console;
|
||||
exports.log = (console && console.log) || function() {};
|
||||
exports.info = (console && console.info) || function() {};
|
||||
exports.error = (console && console.error) || function() {};
|
||||
exports.warn = (console && console.warn) || function() {};
|
||||
exports.dir = (console && console.dir) || function() {};
|
||||
exports.time = (console && console.time) || function(label) {
|
||||
times[label] = Date.now();
|
||||
};
|
||||
exports.timeEnd = (console && console.timeEnd) || function() {
|
||||
var duration = Date.now() - times[label];
|
||||
exports.log('%s: %dms', label, duration);
|
||||
};
|
||||
exports.trace = (console && console.trace) || function() {};
|
||||
exports.assert = (console && console.assert) || function() {};
|
||||
/***/module.exports = function(name) {
|
||||
/***/ var map = {"./a.js":3,"./b.js":4,"./c.js":5};
|
||||
/***/ return require(map[name]||map[name+""]||map[name+".webpack.js"]||map[name+".web.js"]||map[name+".js"]||name);
|
||||
/***/};
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
/******/2: function(module, exports, require) {
|
||||
|
||||
/***/module.exports = function(name) {
|
||||
/***/ var map = {"./a.js":3,"./b.js":5,"./c.js":4};
|
||||
/***/ return require(map[name]||map[name+".web.js"]||map[name+".js"]||name);
|
||||
/***/};
|
||||
var console = window.console;
|
||||
module.exports = console;
|
||||
for(var name in {log:1, info:1, error:1, warn:1, dir:1, trace:1, assert:1})
|
||||
if(!console[name])
|
||||
console[name] = function() {};
|
||||
if(!console.time)
|
||||
console.time = function(label) {
|
||||
times[label] = Date.now();
|
||||
};
|
||||
if(!console.timeEnd)
|
||||
console.timeEnd = function() {
|
||||
var duration = Date.now() - times[label];
|
||||
console.log('%s: %dms', label, duration);
|
||||
};
|
||||
|
||||
/******/},
|
||||
/******/
|
||||
|
@ -93,7 +94,7 @@ module.exports = function() {
|
|||
/******/4: function(module, exports, require) {
|
||||
|
||||
module.exports = function() {
|
||||
return "This text was generated by template C";
|
||||
return "This text was generated by template B";
|
||||
}
|
||||
|
||||
/******/},
|
||||
|
@ -101,7 +102,7 @@ module.exports = function() {
|
|||
/******/5: function(module, exports, require) {
|
||||
|
||||
module.exports = function() {
|
||||
return "This text was generated by template B";
|
||||
return "This text was generated by template C";
|
||||
}
|
||||
|
||||
/******/},
|
||||
|
@ -119,20 +120,20 @@ Modules: 6
|
|||
Modules including duplicates: 6
|
||||
Modules pre chunk: 6
|
||||
Modules first chunk: 6
|
||||
output.js: 2402 characters
|
||||
output.js: 2274 characters
|
||||
output.js
|
||||
0 [...]\examples\require.context\example.js
|
||||
0 .\example.js
|
||||
main
|
||||
1 [...]\buildin\__webpack_console.js
|
||||
require (2x) from [...]\examples\require.context\example.js
|
||||
2 generated [...]\examples\require.context\templates
|
||||
context from [...]\examples\require.context\example.js
|
||||
3 [...]\examples\require.context\templates\a.js
|
||||
context from [...]\examples\require.context\example.js
|
||||
4 [...]\examples\require.context\templates\c.js
|
||||
context from [...]\examples\require.context\example.js
|
||||
5 [...]\examples\require.context\templates\b.js
|
||||
context from [...]\examples\require.context\example.js
|
||||
1 [context] .\templates
|
||||
context from .\example.js
|
||||
2 (webpack)\buildin\__webpack_console.js
|
||||
require (2x) from .\example.js
|
||||
3 .\templates\a.js
|
||||
context from .\example.js
|
||||
4 .\templates\b.js
|
||||
context from .\example.js
|
||||
5 .\templates\c.js
|
||||
context from .\example.js
|
||||
```
|
||||
|
||||
## Minimized (uglify-js, no zip)
|
||||
|
@ -143,20 +144,20 @@ Modules: 6
|
|||
Modules including duplicates: 6
|
||||
Modules pre chunk: 6
|
||||
Modules first chunk: 6
|
||||
output.js: 1119 characters
|
||||
output.js: 1043 characters
|
||||
output.js
|
||||
0 [...]\examples\require.context\example.js
|
||||
0 .\example.js
|
||||
main
|
||||
1 generated [...]\examples\require.context\templates
|
||||
context from [...]\examples\require.context\example.js
|
||||
2 [...]\examples\require.context\templates\a.js
|
||||
context from [...]\examples\require.context\example.js
|
||||
3 [...]\examples\require.context\templates\b.js
|
||||
context from [...]\examples\require.context\example.js
|
||||
4 [...]\examples\require.context\templates\c.js
|
||||
context from [...]\examples\require.context\example.js
|
||||
5 [...]\buildin\__webpack_console.js
|
||||
require (2x) from [...]\examples\require.context\example.js
|
||||
1 [context] .\templates
|
||||
context from .\example.js
|
||||
2 (webpack)\buildin\__webpack_console.js
|
||||
require (2x) from .\example.js
|
||||
3 .\templates\a.js
|
||||
context from .\example.js
|
||||
4 .\templates\b.js
|
||||
context from .\example.js
|
||||
5 .\templates\c.js
|
||||
context from .\example.js
|
||||
```
|
||||
|
||||
# Code Splitting
|
||||
|
|
|
@ -1,18 +1 @@
|
|||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
var cp = require('child_process');
|
||||
|
||||
var argv = process.argv;
|
||||
argv.shift();
|
||||
argv.shift();
|
||||
var extraArgs = argv.join(" ");
|
||||
|
||||
cp.exec("node ../../bin/webpack.js "+extraArgs+" example.js js/output.js", function (error, stdout, stderr) {
|
||||
console.log('stdout:\n' + stdout);
|
||||
console.log('stderr:\n ' + stderr);
|
||||
if (error !== null) {
|
||||
console.log('error: ' + error);
|
||||
}
|
||||
});
|
||||
require("../build-common");
|
|
@ -0,0 +1,43 @@
|
|||
# example.js
|
||||
|
||||
``` javascript
|
||||
{{example.js}}
|
||||
```
|
||||
|
||||
# templates/
|
||||
|
||||
* a.js
|
||||
* b.js
|
||||
* c.js
|
||||
|
||||
All templates are of this pattern:
|
||||
|
||||
``` javascript
|
||||
module.exports = function() {
|
||||
return "This text was generated by template X";
|
||||
}
|
||||
```
|
||||
|
||||
# js/output.js
|
||||
|
||||
``` javascript
|
||||
{{js/output.js}}
|
||||
```
|
||||
|
||||
# Info
|
||||
|
||||
## Uncompressed
|
||||
|
||||
```
|
||||
{{stdout}}
|
||||
```
|
||||
|
||||
## Minimized (uglify-js, no zip)
|
||||
|
||||
```
|
||||
{{min:stdout}}
|
||||
```
|
||||
|
||||
# Code Splitting
|
||||
|
||||
See [this example combined with code splitting](/sokra/modules-webpack/tree/master/examples/code-splitted-require.context)
|
|
@ -0,0 +1,16 @@
|
|||
require = require("../require-polyfill")(require.valueOf());
|
||||
|
||||
var fs = require("fs");
|
||||
|
||||
module.exports = function(template, filesReq, stdout, prefix) {
|
||||
|
||||
var regexp = new RegExp("\\{\\{" + (prefix ? prefix+":" : "") + "([^:\\}]+)\\}\\}", "g")
|
||||
|
||||
return template.replace(regexp, function(match) {
|
||||
match = match.substr(2 + (prefix ? prefix.length+1 : 0), match.length - 4 - (prefix ? prefix.length+1 : 0));
|
||||
if(match === "stdout")
|
||||
return stdout;
|
||||
return filesReq("./" + match);
|
||||
});
|
||||
|
||||
}
|
39
lib/parse.js
39
lib/parse.js
|
@ -78,7 +78,7 @@ function walkStatement(context, statement) {
|
|||
|
||||
// Declarations
|
||||
case "FunctionDeclaration":
|
||||
if(statement.name in context.options.overwrites) {
|
||||
if(context.options.overwrites.hasOwnProperty(statement.name)) {
|
||||
context.overwrite.push(statement.name);
|
||||
}
|
||||
var old = addOverwrites(context, statement.params);
|
||||
|
@ -116,7 +116,7 @@ function walkVariableDeclarators(context, declarators) {
|
|||
switch(declarator.type) {
|
||||
case "VariableDeclarator":
|
||||
if(declarator.id.type === "Identifier" &&
|
||||
declarator.id.name in context.options.overwrites) {
|
||||
context.options.overwrites.hasOwnProperty(declarator.id.name)) {
|
||||
context.overwrite.push(declarator.id.name);
|
||||
}
|
||||
if(declarator.init)
|
||||
|
@ -251,9 +251,8 @@ function walkExpression(context, expression) {
|
|||
expression.callee.object.type === "Identifier" &&
|
||||
expression.callee.object.name === "require" &&
|
||||
expression.callee.property.type === "Identifier" &&
|
||||
expression.callee.property.name in {async:1, ensure:1}) {
|
||||
{async:1, ensure:1}.hasOwnProperty(expression.callee.property.name)) {
|
||||
var param = parseStringArray(expression.arguments[0]);
|
||||
context.asyncs = context.asyncs || [];
|
||||
var newContext = {
|
||||
requires: [],
|
||||
namesRange: expression.arguments[0].range,
|
||||
|
@ -266,6 +265,16 @@ function walkExpression(context, expression) {
|
|||
param.forEach(function(r) {
|
||||
newContext.requires.push({name: r});
|
||||
});
|
||||
if(expression.arguments.length >= 2 &&
|
||||
expression.arguments[1].type === "FunctionExpression" &&
|
||||
expression.arguments[1].body &&
|
||||
expression.arguments[1].body.type === "BlockStatement" &&
|
||||
expression.arguments[1].body.range)
|
||||
newContext.blockRange = [
|
||||
expression.arguments[1].body.range[0]+1,
|
||||
expression.arguments[1].body.range[1]-1
|
||||
];
|
||||
context.asyncs = context.asyncs || [];
|
||||
context.asyncs.push(newContext);
|
||||
context = newContext;
|
||||
noCallee = true;
|
||||
|
@ -277,7 +286,7 @@ function walkExpression(context, expression) {
|
|||
expression.callee.object.type === "Identifier" &&
|
||||
expression.callee.object.name === "require" &&
|
||||
expression.callee.property.type === "Identifier" &&
|
||||
expression.callee.property.name in {context:1}) {
|
||||
expression.callee.property.name === "context") {
|
||||
var param = parseString(expression.arguments[0]);
|
||||
context.contexts = context.contexts || [];
|
||||
var newContext = {
|
||||
|
@ -295,7 +304,7 @@ function walkExpression(context, expression) {
|
|||
expression.callee.object.type === "Identifier" &&
|
||||
expression.callee.object.name === "require" &&
|
||||
expression.callee.property.type === "Identifier" &&
|
||||
expression.callee.property.name in {valueOf:1}) {
|
||||
expression.callee.property.name === "valueOf") {
|
||||
noCallee = true;
|
||||
}
|
||||
|
||||
|
@ -328,13 +337,20 @@ function walkExpression(context, expression) {
|
|||
};
|
||||
context.contexts.push(newContext);
|
||||
} else if(context.overwrite.indexOf(expression.name) === -1 &&
|
||||
expression.name in context.options.overwrites) {
|
||||
context.options.overwrites.hasOwnProperty(expression.name)) {
|
||||
context.requires = context.requires || [];
|
||||
var overwrite = context.options.overwrites[expression.name];
|
||||
var append = undefined;
|
||||
if(overwrite.indexOf("+") !== -1) {
|
||||
append = overwrite.substr(overwrite.indexOf("+")+1);
|
||||
overwrite = overwrite.substr(0, overwrite.indexOf("+"));
|
||||
}
|
||||
context.requires.push({
|
||||
name: context.options.overwrites[expression.name],
|
||||
expressionRange: expression.range,
|
||||
name: overwrite,
|
||||
line: expression.loc.start.line,
|
||||
column: expression.loc.start.column
|
||||
column: expression.loc.start.column,
|
||||
variable: expression.name,
|
||||
append: append
|
||||
});
|
||||
}
|
||||
break;
|
||||
|
@ -350,7 +366,7 @@ function addOverwrites(context, params) {
|
|||
return;
|
||||
}
|
||||
if(param.type === "Identifier" &&
|
||||
param.name in context.options.overwrites)
|
||||
context.options.overwrites.hasOwnProperty(param.name))
|
||||
context.overwrite.push(param.name);
|
||||
});
|
||||
return l;
|
||||
|
@ -430,5 +446,6 @@ module.exports = function parse(source, options) {
|
|||
overwrite: []
|
||||
};
|
||||
walkStatements(context, ast.body);
|
||||
delete context.options;
|
||||
return context;
|
||||
}
|
|
@ -20,6 +20,7 @@
|
|||
/******/ var head = document.getElementsByTagName('head')[0];
|
||||
/******/ var script = document.createElement('script');
|
||||
/******/ script.type = 'text/javascript';
|
||||
/******/ script.charset = 'utf-8';
|
||||
/******/ script.src = modules.c+chunkId+modules.a;
|
||||
/******/ head.appendChild(script);
|
||||
/******/ }
|
||||
|
|
|
@ -70,9 +70,12 @@ module.exports = function(context, moduleName, options, callback) {
|
|||
options.parse = options.parse || {};
|
||||
options.parse.overwrites = options.parse.overwrites || {};
|
||||
options.parse.overwrites.process = options.parse.overwrites.process || ("__webpack_process");
|
||||
options.parse.overwrites.module = options.parse.overwrites.module || ("__webpack_module");
|
||||
options.parse.overwrites.module = options.parse.overwrites.module || ("__webpack_module+(module)");
|
||||
options.parse.overwrites.console = options.parse.overwrites.console || ("__webpack_console");
|
||||
options.parse.overwrites.global = options.parse.overwrites.global || ("__webpack_global");
|
||||
options.parse.overwrites.Buffer = options.parse.overwrites.Buffer || ("buffer+.Buffer");
|
||||
options.parse.overwrites["__dirname"] = options.parse.overwrites["__dirname"] || ("__webpack_dirname");
|
||||
options.parse.overwrites["__filename"] = options.parse.overwrites["__filename"] || ("__webpack_filename");
|
||||
options.resolve = options.resolve || {};
|
||||
options.resolve.paths = options.resolve.paths || [];
|
||||
options.resolve.paths.push(path.join(path.dirname(__dirname), "buildin"));
|
||||
|
|
|
@ -20,7 +20,10 @@ module.exports = function(module, options) {
|
|||
}
|
||||
return;
|
||||
}
|
||||
var freeVars = {};
|
||||
var replaces = []; // { from: 123, to: 125, value: "4" }
|
||||
var modulePrepends = [];
|
||||
var moduleAppends = [];
|
||||
function genReplaceRequire(requireItem) {
|
||||
if(requireItem.id !== undefined) {
|
||||
var prefix = "";
|
||||
|
@ -30,7 +33,7 @@ module.exports = function(module, options) {
|
|||
replaces.push({
|
||||
from: requireItem.expressionRange[0],
|
||||
to: requireItem.expressionRange[1],
|
||||
value: "require(" + prefix + requireItem.id + ")"
|
||||
value: "require(" + prefix + requireItem.id + ")" + (requireItem.append || "")
|
||||
});
|
||||
} else if(requireItem.valueRange) {
|
||||
replaces.push({
|
||||
|
@ -38,6 +41,10 @@ module.exports = function(module, options) {
|
|||
to: requireItem.valueRange[1],
|
||||
value: prefix + requireItem.id
|
||||
});
|
||||
} else if(requireItem.variable) {
|
||||
if(!freeVars[requireItem.variable]) {
|
||||
freeVars[requireItem.variable] = requireItem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -74,6 +81,8 @@ module.exports = function(module, options) {
|
|||
}
|
||||
if(module.asyncs) {
|
||||
module.asyncs.forEach(function genReplacesAsync(asyncItem) {
|
||||
var oldFreeVars = freeVars;
|
||||
freeVars = {};
|
||||
if(asyncItem.requires) {
|
||||
asyncItem.requires.forEach(genReplaceRequire);
|
||||
}
|
||||
|
@ -90,8 +99,54 @@ module.exports = function(module, options) {
|
|||
value: ((asyncItem.chunkId || "0") + "")
|
||||
});
|
||||
}
|
||||
if(asyncItem.blockRange) {
|
||||
genReplacesFreeVars(asyncItem.blockRange, freeVars);
|
||||
}
|
||||
freeVars = oldFreeVars;
|
||||
});
|
||||
}
|
||||
function genReplacesFreeVars(blockRange, freeVars) {
|
||||
var keys = Object.keys(freeVars);
|
||||
var values = [];
|
||||
var removeKeys = [];
|
||||
keys.forEach(function(key, idx) {
|
||||
if(freeVars[key].id === module.id) {
|
||||
removeKeys.push(idx);
|
||||
} else {
|
||||
values.push(freeVars[key]);
|
||||
}
|
||||
});
|
||||
removeKeys.reverse().forEach(function(idx) {
|
||||
keys.splice(idx, 1);
|
||||
});
|
||||
if(keys.length === 0) return;
|
||||
values.forEach(function(requireItem, idx) {
|
||||
if(requireItem.id !== undefined) {
|
||||
var prefix = "";
|
||||
if(requireItem.name)
|
||||
prefix += "/* " + requireItem.name + " */";
|
||||
values[idx] = "require(" + prefix + requireItem.id + ")" + (requireItem.append || "");
|
||||
}
|
||||
});
|
||||
var start = "/* WEBPACK FREE VAR INJECTION */ (function(" + keys.join(",") + ") {";
|
||||
var end = "/* WEBPACK FREE VAR INJECTION */ }(" + values.join(",") + "))"
|
||||
if(blockRange) {
|
||||
replaces.push({
|
||||
from: blockRange[0],
|
||||
to: blockRange[0]-1,
|
||||
value: start
|
||||
});
|
||||
replaces.push({
|
||||
from: blockRange[1],
|
||||
to: blockRange[1]-1,
|
||||
value: end
|
||||
});
|
||||
} else {
|
||||
modulePrepends.unshift("/******/ " + start + "\n");
|
||||
moduleAppends.push("\n/******/ " + end);
|
||||
}
|
||||
}
|
||||
genReplacesFreeVars(null, freeVars);
|
||||
replaces.sort(function(a, b) {
|
||||
return b.from - a.from;
|
||||
});
|
||||
|
@ -111,9 +166,12 @@ module.exports = function(module, options) {
|
|||
}
|
||||
result.push("\n\n// WEBPACK FOOTER //\n"+
|
||||
"// module.id = " + module.id + "\n" +
|
||||
"// module.chunks = " + module.chunks.join(", ") + "\n" +
|
||||
"//@ sourceURL=webpack-module://" + encodeURI(module.filename).replace(/%5C|%2F/g, "/"));
|
||||
return "eval(" + JSON.stringify(result.join("")) + ")";
|
||||
result = ["eval(", JSON.stringify(result.join("")), ")"];
|
||||
}
|
||||
result.unshift.apply(result, modulePrepends.reverse());
|
||||
result.push.apply(result, moduleAppends);
|
||||
return result.join("");
|
||||
}
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "webpack",
|
||||
"version": "0.3.0",
|
||||
"version": "0.3.1",
|
||||
"author": "Tobias Koppers @sokra",
|
||||
"description": "Packs CommonJs Modules for the browser. Allows to split your codebase into multiple bundles, which can be loaded on demand.",
|
||||
"dependencies": {
|
||||
|
|
|
@ -9,24 +9,38 @@ argv.shift();
|
|||
argv.shift();
|
||||
var extraArgs = argv.join(" ");
|
||||
|
||||
cp.exec("node ../../bin/webpack.js "+extraArgs+" --colors --single --libary libary1 node_modules/libary1 js/libary1.js", function (error, stdout, stderr) {
|
||||
console.log('libary1 stdout:\n' + stdout);
|
||||
console.log('libary1 stderr:\n ' + stderr);
|
||||
if (error !== null) {
|
||||
console.log('libary1 error: ' + error);
|
||||
}
|
||||
});
|
||||
cp.exec("node ../../bin/webpack.js "+extraArgs+" --colors --script-src-prefix js/ --libary libary2 node_modules/libary2 js/libary2.js", function (error, stdout, stderr) {
|
||||
console.log('libary2 stdout:\n' + stdout);
|
||||
console.log('libary2 stderr:\n ' + stderr);
|
||||
if (error !== null) {
|
||||
console.log('libary2 error: ' + error);
|
||||
}
|
||||
});
|
||||
cp.exec("node ../../bin/webpack.js "+extraArgs+" --colors --script-src-prefix js/ lib/index js/web.js", function (error, stdout, stderr) {
|
||||
console.log('web stdout:\n' + stdout);
|
||||
console.log('web stderr:\n ' + stderr);
|
||||
if (error !== null) {
|
||||
console.log('web error: ' + error);
|
||||
}
|
||||
});
|
||||
try {
|
||||
require("vm-browserify");
|
||||
compile();
|
||||
} catch(e) {
|
||||
console.log("install vm-browserify...");
|
||||
cp.exec("npm install vm-browserify", function (error, stdout, stderr) {
|
||||
console.log(stdout);
|
||||
compile();
|
||||
});
|
||||
}
|
||||
function compile() {
|
||||
console.log("compile scripts...");
|
||||
|
||||
cp.exec("node ../../bin/webpack.js "+extraArgs+" --colors --single --libary libary1 node_modules/libary1 js/libary1.js", function (error, stdout, stderr) {
|
||||
console.log('libary1 stdout:\n' + stdout);
|
||||
console.log('libary1 stderr:\n ' + stderr);
|
||||
if (error !== null) {
|
||||
console.log('libary1 error: ' + error);
|
||||
}
|
||||
});
|
||||
cp.exec("node ../../bin/webpack.js "+extraArgs+" --colors --script-src-prefix js/ --libary libary2 node_modules/libary2 js/libary2.js", function (error, stdout, stderr) {
|
||||
console.log('libary2 stdout:\n' + stdout);
|
||||
console.log('libary2 stderr:\n ' + stderr);
|
||||
if (error !== null) {
|
||||
console.log('libary2 error: ' + error);
|
||||
}
|
||||
});
|
||||
cp.exec("node ../../bin/webpack.js "+extraArgs+" --colors --alias vm=vm-browserify --script-src-prefix js/ lib/index js/web.js", function (error, stdout, stderr) {
|
||||
console.log('web stdout:\n' + stdout);
|
||||
console.log('web stderr:\n ' + stderr);
|
||||
if (error !== null) {
|
||||
console.log('web error: ' + error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
|
@ -127,3 +127,8 @@ var abc = "abc", scr = "script.coffee";
|
|||
window.test(require("../resources/" + scr) === "coffee test", "context should process extensions");
|
||||
window.test(require("raw!../resources/" + abc + ".txt") === "abc", "raw loader with context");
|
||||
|
||||
|
||||
require.ensure([], function(require) {
|
||||
// Tests from node.js
|
||||
require("../nodetests");
|
||||
});
|
||||
|
|
|
@ -0,0 +1,146 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
var path = require('path');
|
||||
var assert = require('assert');
|
||||
|
||||
exports.testDir = path.dirname(__filename);
|
||||
exports.fixturesDir = path.join(exports.testDir, 'fixtures');
|
||||
exports.libDir = path.join(exports.testDir, '../lib');
|
||||
exports.tmpDir = path.join(exports.testDir, 'tmp');
|
||||
exports.PORT = 12346;
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
exports.PIPE = '\\\\.\\pipe\\libuv-test';
|
||||
} else {
|
||||
exports.PIPE = exports.tmpDir + '/test.sock';
|
||||
}
|
||||
|
||||
var util = require('util');
|
||||
for (var i in util) exports[i] = util[i];
|
||||
//for (var i in exports) global[i] = exports[i];
|
||||
|
||||
function protoCtrChain(o) {
|
||||
var result = [];
|
||||
for (; o; o = o.__proto__) { result.push(o.constructor); }
|
||||
return result.join();
|
||||
}
|
||||
|
||||
exports.indirectInstanceOf = function(obj, cls) {
|
||||
if (obj instanceof cls) { return true; }
|
||||
var clsChain = protoCtrChain(cls.prototype);
|
||||
var objChain = protoCtrChain(obj);
|
||||
return objChain.slice(-clsChain.length) === clsChain;
|
||||
};
|
||||
|
||||
|
||||
exports.ddCommand = function(filename, kilobytes) {
|
||||
if (process.platform === 'win32') {
|
||||
var p = path.resolve(exports.fixturesDir, 'create-file.js');
|
||||
return '"' + process.argv[0] + '" "' + p + '" "' +
|
||||
filename + '" ' + (kilobytes * 1024);
|
||||
} else {
|
||||
return 'dd if=/dev/zero of="' + filename + '" bs=1024 count=' + kilobytes;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
exports.spawnPwd = function(options) {
|
||||
var spawn = require('child_process').spawn;
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
return spawn('cmd.exe', ['/c', 'cd'], options);
|
||||
} else {
|
||||
return spawn('pwd', [], options);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// Turn this off if the test should not check for global leaks.
|
||||
exports.globalCheck = true;
|
||||
|
||||
process.on('exit', function() {
|
||||
if (!exports.globalCheck) return;
|
||||
var knownGlobals = [setTimeout,
|
||||
setInterval,
|
||||
clearTimeout,
|
||||
clearInterval,
|
||||
console,
|
||||
Buffer,
|
||||
process,
|
||||
global];
|
||||
|
||||
if (global.errno) {
|
||||
knownGlobals.push(errno);
|
||||
}
|
||||
|
||||
if (global.gc) {
|
||||
knownGlobals.push(gc);
|
||||
}
|
||||
|
||||
if (global.DTRACE_HTTP_SERVER_RESPONSE) {
|
||||
knownGlobals.push(DTRACE_HTTP_SERVER_RESPONSE);
|
||||
knownGlobals.push(DTRACE_HTTP_SERVER_REQUEST);
|
||||
knownGlobals.push(DTRACE_HTTP_CLIENT_RESPONSE);
|
||||
knownGlobals.push(DTRACE_HTTP_CLIENT_REQUEST);
|
||||
knownGlobals.push(DTRACE_NET_STREAM_END);
|
||||
knownGlobals.push(DTRACE_NET_SERVER_CONNECTION);
|
||||
knownGlobals.push(DTRACE_NET_SOCKET_READ);
|
||||
knownGlobals.push(DTRACE_NET_SOCKET_WRITE);
|
||||
}
|
||||
|
||||
if (global.ArrayBuffer) {
|
||||
knownGlobals.push(ArrayBuffer);
|
||||
knownGlobals.push(Int8Array);
|
||||
knownGlobals.push(Uint8Array);
|
||||
knownGlobals.push(Uint8ClampedArray);
|
||||
knownGlobals.push(Int16Array);
|
||||
knownGlobals.push(Uint16Array);
|
||||
knownGlobals.push(Int32Array);
|
||||
knownGlobals.push(Uint32Array);
|
||||
knownGlobals.push(Float32Array);
|
||||
knownGlobals.push(Float64Array);
|
||||
knownGlobals.push(DataView);
|
||||
}
|
||||
|
||||
for (var x in global) {
|
||||
var found = false;
|
||||
|
||||
for (var y in knownGlobals) {
|
||||
if (global[x] === knownGlobals[y]) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
console.error('Unknown global: %s', x);
|
||||
assert.ok(false, 'Unknown global found');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// This function allows one two run an HTTP test agaist both HTTPS and
|
||||
// normal HTTP modules. This ensures they fit the same API.
|
||||
exports.httpTest = function httpTest(cb) {
|
||||
};
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
foo = 'foo';
|
||||
global.bar = 'bar';
|
||||
|
||||
exports.fooBar = {foo: global.foo, bar: bar};
|
|
@ -0,0 +1,26 @@
|
|||
require("./common").globalCheck = false;
|
||||
|
||||
require("./simple/test-assert.js");
|
||||
require("./simple/test-event-emitter-check-listener-leaks.js");
|
||||
require("./simple/test-event-emitter-modify-in-emit.js");
|
||||
require("./simple/test-event-emitter-num-args.js");
|
||||
require("./simple/test-event-emitter-remove-all-listeners.js");
|
||||
require("./simple/test-global.js");
|
||||
require("./simple/test-next-tick-doesnt-hang.js");
|
||||
require("./simple/test-next-tick-ordering2.js");
|
||||
require("./simple/test-path.js");
|
||||
require("./simple/test-querystring.js");
|
||||
require("./simple/test-sys.js");
|
||||
require("./simple/test-timers-zero-timeout.js");
|
||||
require("./simple/test-timers.js");
|
||||
require("./simple/test-url.js");
|
||||
require("./simple/test-util-format.js");
|
||||
require("./simple/test-util-inspect.js");
|
||||
require("./simple/test-util.js");
|
||||
|
||||
window.test(true, "Node.js simple tests should complete");
|
||||
|
||||
setTimeout(function() {
|
||||
process.emit("exit");
|
||||
window.test(true, "Node.js simple tests should complete on process exit");
|
||||
}, 3000);
|
|
@ -0,0 +1,285 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
var a = require('assert');
|
||||
|
||||
function makeBlock(f) {
|
||||
var args = Array.prototype.slice.call(arguments, 1);
|
||||
return function() {
|
||||
return f.apply(this, args);
|
||||
};
|
||||
}
|
||||
|
||||
assert.ok(common.indirectInstanceOf(a.AssertionError.prototype, Error),
|
||||
'a.AssertionError instanceof Error');
|
||||
|
||||
assert.throws(makeBlock(a, false), a.AssertionError, 'ok(false)');
|
||||
|
||||
assert.doesNotThrow(makeBlock(a, true), a.AssertionError, 'ok(true)');
|
||||
|
||||
assert.doesNotThrow(makeBlock(a, 'test', 'ok(\'test\')'));
|
||||
|
||||
assert.throws(makeBlock(a.ok, false),
|
||||
a.AssertionError, 'ok(false)');
|
||||
|
||||
assert.doesNotThrow(makeBlock(a.ok, true),
|
||||
a.AssertionError, 'ok(true)');
|
||||
|
||||
assert.doesNotThrow(makeBlock(a.ok, 'test'), 'ok(\'test\')');
|
||||
|
||||
assert.throws(makeBlock(a.equal, true, false), a.AssertionError, 'equal');
|
||||
|
||||
assert.doesNotThrow(makeBlock(a.equal, null, null), 'equal');
|
||||
|
||||
assert.doesNotThrow(makeBlock(a.equal, undefined, undefined), 'equal');
|
||||
|
||||
assert.doesNotThrow(makeBlock(a.equal, null, undefined), 'equal');
|
||||
|
||||
assert.doesNotThrow(makeBlock(a.equal, true, true), 'equal');
|
||||
|
||||
assert.doesNotThrow(makeBlock(a.equal, 2, '2'), 'equal');
|
||||
|
||||
assert.doesNotThrow(makeBlock(a.notEqual, true, false), 'notEqual');
|
||||
|
||||
assert.throws(makeBlock(a.notEqual, true, true),
|
||||
a.AssertionError, 'notEqual');
|
||||
|
||||
assert.throws(makeBlock(a.strictEqual, 2, '2'),
|
||||
a.AssertionError, 'strictEqual');
|
||||
|
||||
assert.throws(makeBlock(a.strictEqual, null, undefined),
|
||||
a.AssertionError, 'strictEqual');
|
||||
|
||||
assert.doesNotThrow(makeBlock(a.notStrictEqual, 2, '2'), 'notStrictEqual');
|
||||
|
||||
// deepEquals joy!
|
||||
// 7.2
|
||||
assert.doesNotThrow(makeBlock(a.deepEqual, new Date(2000, 3, 14),
|
||||
new Date(2000, 3, 14)), 'deepEqual date');
|
||||
|
||||
assert.throws(makeBlock(a.deepEqual, new Date(), new Date(2000, 3, 14)),
|
||||
a.AssertionError,
|
||||
'deepEqual date');
|
||||
|
||||
// 7.3
|
||||
assert.doesNotThrow(makeBlock(a.deepEqual, /a/, /a/));
|
||||
assert.doesNotThrow(makeBlock(a.deepEqual, /a/g, /a/g));
|
||||
assert.doesNotThrow(makeBlock(a.deepEqual, /a/i, /a/i));
|
||||
assert.doesNotThrow(makeBlock(a.deepEqual, /a/m, /a/m));
|
||||
assert.doesNotThrow(makeBlock(a.deepEqual, /a/igm, /a/igm));
|
||||
assert.throws(makeBlock(a.deepEqual, /ab/, /a/));
|
||||
assert.throws(makeBlock(a.deepEqual, /a/g, /a/));
|
||||
assert.throws(makeBlock(a.deepEqual, /a/i, /a/));
|
||||
assert.throws(makeBlock(a.deepEqual, /a/m, /a/));
|
||||
assert.throws(makeBlock(a.deepEqual, /a/igm, /a/im));
|
||||
|
||||
var re1 = /a/;
|
||||
re1.lastIndex = 3;
|
||||
assert.throws(makeBlock(a.deepEqual, re1, /a/));
|
||||
|
||||
|
||||
// 7.4
|
||||
assert.doesNotThrow(makeBlock(a.deepEqual, 4, '4'), 'deepEqual == check');
|
||||
assert.doesNotThrow(makeBlock(a.deepEqual, true, 1), 'deepEqual == check');
|
||||
assert.throws(makeBlock(a.deepEqual, 4, '5'),
|
||||
a.AssertionError,
|
||||
'deepEqual == check');
|
||||
|
||||
// 7.5
|
||||
// having the same number of owned properties && the same set of keys
|
||||
assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4}, {a: 4}));
|
||||
assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '2'}, {a: 4, b: '2'}));
|
||||
assert.doesNotThrow(makeBlock(a.deepEqual, [4], ['4']));
|
||||
assert.throws(makeBlock(a.deepEqual, {a: 4}, {a: 4, b: true}),
|
||||
a.AssertionError);
|
||||
assert.doesNotThrow(makeBlock(a.deepEqual, ['a'], {0: 'a'}));
|
||||
//(although not necessarily the same order),
|
||||
assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '1'}, {b: '1', a: 4}));
|
||||
var a1 = [1, 2, 3];
|
||||
var a2 = [1, 2, 3];
|
||||
a1.a = 'test';
|
||||
a1.b = true;
|
||||
a2.b = true;
|
||||
a2.a = 'test';
|
||||
assert.throws(makeBlock(a.deepEqual, Object.keys(a1), Object.keys(a2)),
|
||||
a.AssertionError);
|
||||
assert.doesNotThrow(makeBlock(a.deepEqual, a1, a2));
|
||||
|
||||
// having an identical prototype property
|
||||
var nbRoot = {
|
||||
toString: function() { return this.first + ' ' + this.last; }
|
||||
};
|
||||
|
||||
function nameBuilder(first, last) {
|
||||
this.first = first;
|
||||
this.last = last;
|
||||
return this;
|
||||
}
|
||||
nameBuilder.prototype = nbRoot;
|
||||
|
||||
function nameBuilder2(first, last) {
|
||||
this.first = first;
|
||||
this.last = last;
|
||||
return this;
|
||||
}
|
||||
nameBuilder2.prototype = nbRoot;
|
||||
|
||||
var nb1 = new nameBuilder('Ryan', 'Dahl');
|
||||
var nb2 = new nameBuilder2('Ryan', 'Dahl');
|
||||
|
||||
assert.doesNotThrow(makeBlock(a.deepEqual, nb1, nb2));
|
||||
|
||||
nameBuilder2.prototype = Object;
|
||||
nb2 = new nameBuilder2('Ryan', 'Dahl');
|
||||
assert.throws(makeBlock(a.deepEqual, nb1, nb2), a.AssertionError);
|
||||
|
||||
// String literal + object blew up my implementation...
|
||||
assert.throws(makeBlock(a.deepEqual, 'a', {}), a.AssertionError);
|
||||
|
||||
// Testing the throwing
|
||||
function thrower(errorConstructor) {
|
||||
throw new errorConstructor('test');
|
||||
}
|
||||
var aethrow = makeBlock(thrower, a.AssertionError);
|
||||
aethrow = makeBlock(thrower, a.AssertionError);
|
||||
|
||||
// the basic calls work
|
||||
assert.throws(makeBlock(thrower, a.AssertionError),
|
||||
a.AssertionError, 'message');
|
||||
assert.throws(makeBlock(thrower, a.AssertionError), a.AssertionError);
|
||||
assert.throws(makeBlock(thrower, a.AssertionError));
|
||||
|
||||
// if not passing an error, catch all.
|
||||
assert.throws(makeBlock(thrower, TypeError));
|
||||
|
||||
// when passing a type, only catch errors of the appropriate type
|
||||
var threw = false;
|
||||
try {
|
||||
a.throws(makeBlock(thrower, TypeError), a.AssertionError);
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
assert.ok(e instanceof TypeError, 'type');
|
||||
}
|
||||
assert.equal(true, threw,
|
||||
'a.throws with an explicit error is eating extra errors',
|
||||
a.AssertionError);
|
||||
threw = false;
|
||||
|
||||
// doesNotThrow should pass through all errors
|
||||
try {
|
||||
a.doesNotThrow(makeBlock(thrower, TypeError), a.AssertionError);
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
assert.ok(e instanceof TypeError);
|
||||
}
|
||||
assert.equal(true, threw,
|
||||
'a.doesNotThrow with an explicit error is eating extra errors');
|
||||
|
||||
// key difference is that throwing our correct error makes an assertion error
|
||||
try {
|
||||
a.doesNotThrow(makeBlock(thrower, TypeError), TypeError);
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
assert.ok(e instanceof a.AssertionError);
|
||||
}
|
||||
assert.equal(true, threw,
|
||||
'a.doesNotThrow is not catching type matching errors');
|
||||
|
||||
assert.throws(function() {assert.ifError(new Error('test error'))});
|
||||
assert.doesNotThrow(function() {assert.ifError(null)});
|
||||
assert.doesNotThrow(function() {assert.ifError()});
|
||||
|
||||
// make sure that validating using constructor really works
|
||||
threw = false;
|
||||
try {
|
||||
assert.throws(
|
||||
function() {
|
||||
throw ({});
|
||||
},
|
||||
Array
|
||||
);
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
}
|
||||
assert.ok(threw, 'wrong constructor validation');
|
||||
|
||||
// use a RegExp to validate error message
|
||||
a.throws(makeBlock(thrower, TypeError), /test/);
|
||||
|
||||
// use a fn to validate error object
|
||||
a.throws(makeBlock(thrower, TypeError), function(err) {
|
||||
if ((err instanceof TypeError) && /test/.test(err)) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// GH-207. Make sure deepEqual doesn't loop forever on circular refs
|
||||
|
||||
var b = {};
|
||||
b.b = b;
|
||||
|
||||
var c = {};
|
||||
c.b = c;
|
||||
|
||||
var gotError = false;
|
||||
try {
|
||||
assert.deepEqual(b, c);
|
||||
} catch (e) {
|
||||
gotError = true;
|
||||
}
|
||||
|
||||
console.log('All OK');
|
||||
assert.ok(gotError);
|
||||
|
||||
|
||||
// #217
|
||||
function testAssertionMessage(actual, expected) {
|
||||
try {
|
||||
assert.equal(actual, '');
|
||||
} catch (e) {
|
||||
assert.equal(e.toString(),
|
||||
['AssertionError:', expected, '==', '""'].join(' '));
|
||||
}
|
||||
}
|
||||
testAssertionMessage(undefined, '"undefined"');
|
||||
testAssertionMessage(null, 'null');
|
||||
testAssertionMessage(true, 'true');
|
||||
testAssertionMessage(false, 'false');
|
||||
testAssertionMessage(0, '0');
|
||||
testAssertionMessage(100, '100');
|
||||
testAssertionMessage(NaN, '"NaN"');
|
||||
testAssertionMessage(Infinity, '"Infinity"');
|
||||
testAssertionMessage(-Infinity, '"-Infinity"');
|
||||
testAssertionMessage('', '""');
|
||||
testAssertionMessage('foo', '"foo"');
|
||||
testAssertionMessage([], '[]');
|
||||
testAssertionMessage([1, 2, 3], '[1,2,3]');
|
||||
testAssertionMessage(/a/, '"/a/"');
|
||||
testAssertionMessage(/abc/gim, '"/abc/gim"');
|
||||
testAssertionMessage(function f() {}, '"function f() {}"');
|
||||
testAssertionMessage({}, '{}');
|
||||
testAssertionMessage({a: undefined, b: null}, '{"a":"undefined","b":null}');
|
||||
testAssertionMessage({a: NaN, b: Infinity, c: -Infinity},
|
||||
'{"a":"NaN","b":"Infinity","c":"-Infinity"}');
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
var events = require('events');
|
||||
|
||||
var e = new events.EventEmitter();
|
||||
|
||||
// default
|
||||
for (var i = 0; i < 10; i++) {
|
||||
e.on('default', function() {});
|
||||
}
|
||||
assert.ok(!e._events['default'].hasOwnProperty('warned'));
|
||||
e.on('default', function() {});
|
||||
assert.ok(e._events['default'].warned);
|
||||
|
||||
// specific
|
||||
e.setMaxListeners(5);
|
||||
for (var i = 0; i < 5; i++) {
|
||||
e.on('specific', function() {});
|
||||
}
|
||||
assert.ok(!e._events['specific'].hasOwnProperty('warned'));
|
||||
e.on('specific', function() {});
|
||||
assert.ok(e._events['specific'].warned);
|
||||
|
||||
// only one
|
||||
e.setMaxListeners(1);
|
||||
e.on('only one', function() {});
|
||||
assert.ok(!e._events['only one'].hasOwnProperty('warned'));
|
||||
e.on('only one', function() {});
|
||||
assert.ok(e._events['only one'].hasOwnProperty('warned'));
|
||||
|
||||
// unlimited
|
||||
e.setMaxListeners(0);
|
||||
for (var i = 0; i < 1000; i++) {
|
||||
e.on('unlimited', function() {});
|
||||
}
|
||||
assert.ok(!e._events['unlimited'].hasOwnProperty('warned'));
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
var events = require('events');
|
||||
|
||||
var callbacks_called = [];
|
||||
|
||||
var e = new events.EventEmitter();
|
||||
|
||||
function callback1() {
|
||||
callbacks_called.push('callback1');
|
||||
e.on('foo', callback2);
|
||||
e.on('foo', callback3);
|
||||
e.removeListener('foo', callback1);
|
||||
}
|
||||
|
||||
function callback2() {
|
||||
callbacks_called.push('callback2');
|
||||
e.removeListener('foo', callback2);
|
||||
}
|
||||
|
||||
function callback3() {
|
||||
callbacks_called.push('callback3');
|
||||
e.removeListener('foo', callback3);
|
||||
}
|
||||
|
||||
e.on('foo', callback1);
|
||||
assert.equal(1, e.listeners('foo').length);
|
||||
|
||||
e.emit('foo');
|
||||
assert.equal(2, e.listeners('foo').length);
|
||||
assert.deepEqual(['callback1'], callbacks_called);
|
||||
|
||||
e.emit('foo');
|
||||
assert.equal(0, e.listeners('foo').length);
|
||||
assert.deepEqual(['callback1', 'callback2', 'callback3'], callbacks_called);
|
||||
|
||||
e.emit('foo');
|
||||
assert.equal(0, e.listeners('foo').length);
|
||||
assert.deepEqual(['callback1', 'callback2', 'callback3'], callbacks_called);
|
||||
|
||||
e.on('foo', callback1);
|
||||
e.on('foo', callback2);
|
||||
assert.equal(2, e.listeners('foo').length);
|
||||
e.removeAllListeners('foo');
|
||||
assert.equal(0, e.listeners('foo').length);
|
||||
|
||||
// Verify that removing callbacks while in emit allows emits to propagate to
|
||||
// all listeners
|
||||
callbacks_called = [];
|
||||
|
||||
e.on('foo', callback2);
|
||||
e.on('foo', callback3);
|
||||
assert.equal(2, e.listeners('foo').length);
|
||||
e.emit('foo');
|
||||
assert.deepEqual(['callback2', 'callback3'], callbacks_called);
|
||||
assert.equal(0, e.listeners('foo').length);
|
|
@ -0,0 +1,48 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
var events = require('events');
|
||||
|
||||
var e = new events.EventEmitter(),
|
||||
num_args_emited = [];
|
||||
|
||||
e.on('numArgs', function() {
|
||||
var numArgs = arguments.length;
|
||||
console.log('numArgs: ' + numArgs);
|
||||
num_args_emited.push(numArgs);
|
||||
});
|
||||
|
||||
console.log('start');
|
||||
|
||||
e.emit('numArgs');
|
||||
e.emit('numArgs', null);
|
||||
e.emit('numArgs', null, null);
|
||||
e.emit('numArgs', null, null, null);
|
||||
e.emit('numArgs', null, null, null, null);
|
||||
e.emit('numArgs', null, null, null, null, null);
|
||||
|
||||
process.on('exit', function() {
|
||||
assert.deepEqual([0, 1, 2, 3, 4, 5], num_args_emited);
|
||||
});
|
||||
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
var events = require('events');
|
||||
|
||||
|
||||
function listener() {}
|
||||
|
||||
var e1 = new events.EventEmitter();
|
||||
e1.on('foo', listener);
|
||||
e1.on('bar', listener);
|
||||
e1.on('baz', listener);
|
||||
e1.on('baz', listener);
|
||||
var fooListeners = e1.listeners('foo');
|
||||
var barListeners = e1.listeners('bar');
|
||||
var bazListeners = e1.listeners('baz');
|
||||
e1.removeAllListeners('bar');
|
||||
e1.removeAllListeners('baz');
|
||||
assert.deepEqual(e1.listeners('foo'), [listener]);
|
||||
assert.deepEqual(e1.listeners('bar'), []);
|
||||
assert.deepEqual(e1.listeners('baz'), []);
|
||||
// identity check, the array should not change
|
||||
assert.equal(e1.listeners('foo'), fooListeners);
|
||||
assert.equal(e1.listeners('bar'), barListeners);
|
||||
assert.equal(e1.listeners('baz'), bazListeners);
|
||||
|
||||
var e2 = new events.EventEmitter();
|
||||
e2.on('foo', listener);
|
||||
e2.on('bar', listener);
|
||||
e2.removeAllListeners();
|
||||
console.error(e2);
|
||||
assert.deepEqual([], e2.listeners('foo'));
|
||||
assert.deepEqual([], e2.listeners('bar'));
|
|
@ -0,0 +1,39 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
|
||||
common.globalCheck = false;
|
||||
|
||||
baseFoo = 'foo';
|
||||
global.baseBar = 'bar';
|
||||
|
||||
assert.equal('foo', global.baseFoo, 'x -> global.x in base level not working');
|
||||
|
||||
assert.equal('bar', baseBar, 'global.x -> x in base level not working');
|
||||
|
||||
var module = require('../fixtures/global/plain'),
|
||||
fooBar = module.fooBar;
|
||||
|
||||
assert.equal('foo', fooBar.foo, 'x -> global.x in sub level not working');
|
||||
|
||||
assert.equal('bar', fooBar.bar, 'global.x -> x in sub level not working');
|
|
@ -0,0 +1,30 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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 test verifies that having a single nextTick statement and nothing else
|
||||
* does not hang the event loop. If this test times out it has failed.
|
||||
*/
|
||||
|
||||
process.nextTick(function() {
|
||||
// Nothing
|
||||
});
|
|
@ -0,0 +1,38 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
|
||||
var order = [];
|
||||
process.nextTick(function() {
|
||||
setTimeout(function() {
|
||||
order.push('setTimeout');
|
||||
}, 0);
|
||||
|
||||
process.nextTick(function() {
|
||||
order.push('nextTick');
|
||||
});
|
||||
});
|
||||
|
||||
process.on('exit', function() {
|
||||
assert.deepEqual(order, ['nextTick', 'setTimeout']);
|
||||
});
|
|
@ -0,0 +1,275 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
|
||||
var path = require('path');
|
||||
|
||||
var isWindows = process.platform === 'win32';
|
||||
|
||||
var f = "nodetest/simple/test-path.js";
|
||||
|
||||
assert.equal(path.basename(f), 'test-path.js');
|
||||
assert.equal(path.basename(f, '.js'), 'test-path');
|
||||
|
||||
// POSIX filenames may include control characters
|
||||
// c.f. http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html
|
||||
if (!isWindows) {
|
||||
var controlCharFilename = 'Icon' + String.fromCharCode(13);
|
||||
assert.equal(path.basename('/a/b/' + controlCharFilename),
|
||||
controlCharFilename);
|
||||
}
|
||||
|
||||
assert.equal(path.extname(f), '.js');
|
||||
|
||||
assert.equal(path.dirname(f).substr(-11),
|
||||
isWindows ? 'test\\simple' : 'test/simple');
|
||||
assert.equal(path.dirname('/a/b/'), '/a');
|
||||
assert.equal(path.dirname('/a/b'), '/a');
|
||||
assert.equal(path.dirname('/a'), '/');
|
||||
assert.equal(path.dirname('/'), '/');
|
||||
|
||||
if (isWindows) {
|
||||
assert.equal(path.dirname('c:\\'), 'c:\\');
|
||||
assert.equal(path.dirname('c:\\foo'), 'c:\\');
|
||||
assert.equal(path.dirname('c:\\foo\\'), 'c:\\');
|
||||
assert.equal(path.dirname('c:\\foo\\bar'), 'c:\\foo');
|
||||
assert.equal(path.dirname('c:\\foo\\bar\\'), 'c:\\foo');
|
||||
assert.equal(path.dirname('c:\\foo\\bar\\baz'), 'c:\\foo\\bar');
|
||||
assert.equal(path.dirname('\\'), '\\');
|
||||
assert.equal(path.dirname('\\foo'), '\\');
|
||||
assert.equal(path.dirname('\\foo\\'), '\\');
|
||||
assert.equal(path.dirname('\\foo\\bar'), '\\foo');
|
||||
assert.equal(path.dirname('\\foo\\bar\\'), '\\foo');
|
||||
assert.equal(path.dirname('\\foo\\bar\\baz'), '\\foo\\bar');
|
||||
assert.equal(path.dirname('c:'), 'c:');
|
||||
assert.equal(path.dirname('c:foo'), 'c:');
|
||||
assert.equal(path.dirname('c:foo\\'), 'c:');
|
||||
assert.equal(path.dirname('c:foo\\bar'), 'c:foo');
|
||||
assert.equal(path.dirname('c:foo\\bar\\'), 'c:foo');
|
||||
assert.equal(path.dirname('c:foo\\bar\\baz'), 'c:foo\\bar');
|
||||
assert.equal(path.dirname('\\\\unc\\share'), '\\\\unc\\share');
|
||||
assert.equal(path.dirname('\\\\unc\\share\\foo'), '\\\\unc\\share\\');
|
||||
assert.equal(path.dirname('\\\\unc\\share\\foo\\'), '\\\\unc\\share\\');
|
||||
assert.equal(path.dirname('\\\\unc\\share\\foo\\bar'),
|
||||
'\\\\unc\\share\\foo');
|
||||
assert.equal(path.dirname('\\\\unc\\share\\foo\\bar\\'),
|
||||
'\\\\unc\\share\\foo');
|
||||
assert.equal(path.dirname('\\\\unc\\share\\foo\\bar\\baz'),
|
||||
'\\\\unc\\share\\foo\\bar');
|
||||
}
|
||||
|
||||
|
||||
assert.equal(path.extname(''), '');
|
||||
assert.equal(path.extname('/path/to/file'), '');
|
||||
assert.equal(path.extname('/path/to/file.ext'), '.ext');
|
||||
assert.equal(path.extname('/path.to/file.ext'), '.ext');
|
||||
assert.equal(path.extname('/path.to/file'), '');
|
||||
assert.equal(path.extname('/path.to/.file'), '');
|
||||
assert.equal(path.extname('/path.to/.file.ext'), '.ext');
|
||||
assert.equal(path.extname('/path/to/f.ext'), '.ext');
|
||||
assert.equal(path.extname('/path/to/..ext'), '.ext');
|
||||
assert.equal(path.extname('file'), '');
|
||||
assert.equal(path.extname('file.ext'), '.ext');
|
||||
assert.equal(path.extname('.file'), '');
|
||||
assert.equal(path.extname('.file.ext'), '.ext');
|
||||
assert.equal(path.extname('/file'), '');
|
||||
assert.equal(path.extname('/file.ext'), '.ext');
|
||||
assert.equal(path.extname('/.file'), '');
|
||||
assert.equal(path.extname('/.file.ext'), '.ext');
|
||||
assert.equal(path.extname('.path/file.ext'), '.ext');
|
||||
assert.equal(path.extname('file.ext.ext'), '.ext');
|
||||
assert.equal(path.extname('file.'), '.');
|
||||
assert.equal(path.extname('.'), '');
|
||||
assert.equal(path.extname('./'), '');
|
||||
assert.equal(path.extname('.file.ext'), '.ext');
|
||||
assert.equal(path.extname('.file'), '');
|
||||
assert.equal(path.extname('.file.'), '.');
|
||||
assert.equal(path.extname('.file..'), '.');
|
||||
assert.equal(path.extname('..'), '');
|
||||
assert.equal(path.extname('../'), '');
|
||||
assert.equal(path.extname('..file.ext'), '.ext');
|
||||
assert.equal(path.extname('..file'), '.file');
|
||||
assert.equal(path.extname('..file.'), '.');
|
||||
assert.equal(path.extname('..file..'), '.');
|
||||
assert.equal(path.extname('...'), '.');
|
||||
assert.equal(path.extname('...ext'), '.ext');
|
||||
assert.equal(path.extname('....'), '.');
|
||||
assert.equal(path.extname('file.ext/'), '');
|
||||
|
||||
if (isWindows) {
|
||||
// On windows, backspace is a path separator.
|
||||
assert.equal(path.extname('.\\'), '');
|
||||
assert.equal(path.extname('..\\'), '');
|
||||
assert.equal(path.extname('file.ext\\'), '');
|
||||
} else {
|
||||
// On unix, backspace is a valid name component like any other character.
|
||||
assert.equal(path.extname('.\\'), '');
|
||||
assert.equal(path.extname('..\\'), '.\\');
|
||||
assert.equal(path.extname('file.ext\\'), '.ext\\');
|
||||
}
|
||||
|
||||
// path.join tests
|
||||
var failures = [];
|
||||
var joinTests =
|
||||
// arguments result
|
||||
[[['.', 'x/b', '..', '/b/c.js'], 'x/b/c.js'],
|
||||
[['/.', 'x/b', '..', '/b/c.js'], '/x/b/c.js'],
|
||||
[['/foo', '../../../bar'], '/bar'],
|
||||
[['foo', '../../../bar'], '../../bar'],
|
||||
[['foo/', '../../../bar'], '../../bar'],
|
||||
[['foo/x', '../../../bar'], '../bar'],
|
||||
[['foo/x', './bar'], 'foo/x/bar'],
|
||||
[['foo/x/', './bar'], 'foo/x/bar'],
|
||||
[['foo/x/', '.', 'bar'], 'foo/x/bar'],
|
||||
[['./'], './'],
|
||||
[['.', './'], './'],
|
||||
[['.', '.', '.'], '.'],
|
||||
[['.', './', '.'], '.'],
|
||||
[['.', '/./', '.'], '.'],
|
||||
[['.', '/////./', '.'], '.'],
|
||||
[['.'], '.'],
|
||||
[['', '.'], '.'],
|
||||
[['', 'foo'], 'foo'],
|
||||
[['foo', '/bar'], 'foo/bar'],
|
||||
[['', '/foo'], '/foo'],
|
||||
[['', '', '/foo'], '/foo'],
|
||||
[['', '', 'foo'], 'foo'],
|
||||
[['foo', ''], 'foo'],
|
||||
[['foo/', ''], 'foo/'],
|
||||
[['foo', '', '/bar'], 'foo/bar'],
|
||||
[['./', '..', '/foo'], '../foo'],
|
||||
[['./', '..', '..', '/foo'], '../../foo'],
|
||||
[['.', '..', '..', '/foo'], '../../foo'],
|
||||
[['', '..', '..', '/foo'], '../../foo'],
|
||||
[['/'], '/'],
|
||||
[['/', '.'], '/'],
|
||||
[['/', '..'], '/'],
|
||||
[['/', '..', '..'], '/'],
|
||||
[[''], '.'],
|
||||
[['', ''], '.'],
|
||||
[[' /foo'], ' /foo'],
|
||||
[[' ', 'foo'], ' /foo'],
|
||||
[[' ', '.'], ' '],
|
||||
[[' ', '/'], ' /'],
|
||||
[[' ', ''], ' '],
|
||||
// filtration of non-strings.
|
||||
[['x', true, 7, 'y', null, {}], 'x/y']
|
||||
];
|
||||
joinTests.forEach(function(test) {
|
||||
var actual = path.join.apply(path, test[0]);
|
||||
var expected = isWindows ? test[1].replace(/\//g, '\\') : test[1];
|
||||
var message = 'path.join(' + test[0].map(JSON.stringify).join(',') + ')' +
|
||||
'\n expect=' + JSON.stringify(expected) +
|
||||
'\n actual=' + JSON.stringify(actual);
|
||||
if (actual !== expected) failures.push('\n' + message);
|
||||
// assert.equal(actual, expected, message);
|
||||
});
|
||||
assert.equal(failures.length, 0, failures.join(''));
|
||||
|
||||
// path normalize tests
|
||||
if (isWindows) {
|
||||
assert.equal(path.normalize('./fixtures///b/../b/c.js'),
|
||||
'fixtures\\b\\c.js');
|
||||
assert.equal(path.normalize('/foo/../../../bar'), '\\bar');
|
||||
assert.equal(path.normalize('a//b//../b'), 'a\\b');
|
||||
assert.equal(path.normalize('a//b//./c'), 'a\\b\\c');
|
||||
assert.equal(path.normalize('a//b//.'), 'a\\b');
|
||||
} else {
|
||||
assert.equal(path.normalize('./fixtures///b/../b/c.js'),
|
||||
'fixtures/b/c.js');
|
||||
assert.equal(path.normalize('/foo/../../../bar'), '/bar');
|
||||
assert.equal(path.normalize('a//b//../b'), 'a/b');
|
||||
assert.equal(path.normalize('a//b//./c'), 'a/b/c');
|
||||
assert.equal(path.normalize('a//b//.'), 'a/b');
|
||||
}
|
||||
|
||||
// path.resolve tests
|
||||
if (isWindows) {
|
||||
// windows
|
||||
var resolveTests =
|
||||
// arguments result
|
||||
[[['c:/blah\\blah', 'd:/games', 'c:../a'], 'c:\\blah\\a'],
|
||||
[['c:/ignore', 'd:\\a/b\\c/d', '\\e.exe'], 'd:\\e.exe'],
|
||||
[['c:/ignore', 'c:/some/file'], 'c:\\some\\file'],
|
||||
[['d:/ignore', 'd:some/dir//'], 'd:\\ignore\\some\\dir'],
|
||||
[['.'], process.cwd()],
|
||||
[['//server/share', '..', 'relative\\'], '\\\\server\\share\\relative']];
|
||||
} else {
|
||||
// Posix
|
||||
var resolveTests =
|
||||
// arguments result
|
||||
[[['/var/lib', '../', 'file/'], '/var/file'],
|
||||
[['/var/lib', '/../', 'file/'], '/file'],
|
||||
[['a/b/c/', '../../..'], process.cwd()],
|
||||
[['.'], process.cwd()],
|
||||
[['/some/dir', '.', '/absolute/'], '/absolute']];
|
||||
}
|
||||
var failures = [];
|
||||
resolveTests.forEach(function(test) {
|
||||
var actual = path.resolve.apply(path, test[0]);
|
||||
var expected = test[1];
|
||||
var message = 'path.resolve(' + test[0].map(JSON.stringify).join(',') + ')' +
|
||||
'\n expect=' + JSON.stringify(expected) +
|
||||
'\n actual=' + JSON.stringify(actual);
|
||||
if (actual !== expected) failures.push('\n' + message);
|
||||
// assert.equal(actual, expected, message);
|
||||
});
|
||||
assert.equal(failures.length, 0, failures.join(''));
|
||||
|
||||
// path.relative tests
|
||||
if (isWindows) {
|
||||
// windows
|
||||
var relativeTests =
|
||||
// arguments result
|
||||
[['c:/blah\\blah', 'd:/games', 'd:\\games'],
|
||||
['c:/aaaa/bbbb', 'c:/aaaa', '..'],
|
||||
['c:/aaaa/bbbb', 'c:/cccc', '..\\..\\cccc'],
|
||||
['c:/aaaa/bbbb', 'c:/aaaa/bbbb', ''],
|
||||
['c:/aaaa/bbbb', 'c:/aaaa/cccc', '..\\cccc'],
|
||||
['c:/aaaa/', 'c:/aaaa/cccc', 'cccc'],
|
||||
['c:/', 'c:\\aaaa\\bbbb', 'aaaa\\bbbb'],
|
||||
['c:/aaaa/bbbb', 'd:\\', 'd:\\']];
|
||||
} else {
|
||||
// posix
|
||||
var relativeTests =
|
||||
// arguments result
|
||||
[['/var/lib', '/var', '..'],
|
||||
['/var/lib', '/bin', '../../bin'],
|
||||
['/var/lib', '/var/lib', ''],
|
||||
['/var/lib', '/var/apache', '../apache'],
|
||||
['/var/', '/var/lib', 'lib'],
|
||||
['/', '/var/lib', 'var/lib']];
|
||||
}
|
||||
var failures = [];
|
||||
relativeTests.forEach(function(test) {
|
||||
var actual = path.relative(test[0], test[1]);
|
||||
var expected = test[2];
|
||||
var message = 'path.relative(' +
|
||||
test.slice(0, 2).map(JSON.stringify).join(',') +
|
||||
')' +
|
||||
'\n expect=' + JSON.stringify(expected) +
|
||||
'\n actual=' + JSON.stringify(actual);
|
||||
if (actual !== expected) failures.push('\n' + message);
|
||||
});
|
||||
assert.equal(failures.length, 0, failures.join(''));
|
||||
|
|
@ -0,0 +1,230 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
|
||||
// test using assert
|
||||
var qs = require('querystring');
|
||||
|
||||
// folding block, commented to pass gjslint
|
||||
// {{{
|
||||
// [ wonkyQS, canonicalQS, obj ]
|
||||
var qsTestCases = [
|
||||
['foo=918854443121279438895193',
|
||||
'foo=918854443121279438895193',
|
||||
{'foo': '918854443121279438895193'}],
|
||||
['foo=bar', 'foo=bar', {'foo': 'bar'}],
|
||||
['foo=bar&foo=quux', 'foo=bar&foo=quux', {'foo': ['bar', 'quux']}],
|
||||
['foo=1&bar=2', 'foo=1&bar=2', {'foo': '1', 'bar': '2'}],
|
||||
['my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F',
|
||||
'my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F',
|
||||
{'my weird field': 'q1!2"\'w$5&7/z8)?' }],
|
||||
['foo%3Dbaz=bar', 'foo%3Dbaz=bar', {'foo=baz': 'bar'}],
|
||||
['foo=baz=bar', 'foo=baz%3Dbar', {'foo': 'baz=bar'}],
|
||||
['str=foo&arr=1&arr=2&arr=3&somenull=&undef=',
|
||||
'str=foo&arr=1&arr=2&arr=3&somenull=&undef=',
|
||||
{ 'str': 'foo',
|
||||
'arr': ['1', '2', '3'],
|
||||
'somenull': '',
|
||||
'undef': ''}],
|
||||
[' foo = bar ', '%20foo%20=%20bar%20', {' foo ': ' bar '}],
|
||||
// ['foo=%zx', 'foo=%25zx', {'foo': '%zx'}],
|
||||
['foo=%EF%BF%BD', 'foo=%EF%BF%BD', {'foo': '\ufffd' }],
|
||||
// See: https://github.com/joyent/node/issues/1707
|
||||
['hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz',
|
||||
'hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz',
|
||||
{ hasOwnProperty: 'x',
|
||||
toString: 'foo',
|
||||
valueOf: 'bar',
|
||||
__defineGetter__: 'baz' }]
|
||||
];
|
||||
|
||||
// [ wonkyQS, canonicalQS, obj ]
|
||||
var qsColonTestCases = [
|
||||
['foo:bar', 'foo:bar', {'foo': 'bar'}],
|
||||
['foo:bar;foo:quux', 'foo:bar;foo:quux', {'foo': ['bar', 'quux']}],
|
||||
['foo:1&bar:2;baz:quux',
|
||||
'foo:1%26bar%3A2;baz:quux',
|
||||
{'foo': '1&bar:2', 'baz': 'quux'}],
|
||||
['foo%3Abaz:bar', 'foo%3Abaz:bar', {'foo:baz': 'bar'}],
|
||||
['foo:baz:bar', 'foo:baz%3Abar', {'foo': 'baz:bar'}]
|
||||
];
|
||||
|
||||
// [wonkyObj, qs, canonicalObj]
|
||||
var extendedFunction = function() {};
|
||||
extendedFunction.prototype = {a: 'b'};
|
||||
var qsWeirdObjects = [
|
||||
[{regexp: /./g}, 'regexp=', {'regexp': ''}],
|
||||
[{regexp: new RegExp('.', 'g')}, 'regexp=', {'regexp': ''}],
|
||||
[{fn: function() {}}, 'fn=', {'fn': ''}],
|
||||
[{fn: new Function('')}, 'fn=', {'fn': ''}],
|
||||
[{math: Math}, 'math=', {'math': ''}],
|
||||
[{e: extendedFunction}, 'e=', {'e': ''}],
|
||||
[{d: new Date()}, 'd=', {'d': ''}],
|
||||
[{d: Date}, 'd=', {'d': ''}],
|
||||
[{f: new Boolean(false), t: new Boolean(true)}, 'f=&t=', {'f': '', 't': ''}],
|
||||
[{f: false, t: true}, 'f=false&t=true', {'f': 'false', 't': 'true'}],
|
||||
[{n: null}, 'n=', {'n': ''}],
|
||||
[{nan: NaN}, 'nan=', {'nan': ''}],
|
||||
[{inf: Infinity}, 'inf=', {'inf': ''}]
|
||||
];
|
||||
// }}}
|
||||
|
||||
var Script = require('vm').Script;
|
||||
var foreignObject = Script.runInContext('({"foo": ["bar", "baz"]})',
|
||||
Script.createContext());
|
||||
|
||||
var qsNoMungeTestCases = [
|
||||
['', {}],
|
||||
['foo=bar&foo=baz', {'foo': ['bar', 'baz']}],
|
||||
['foo=bar&foo=baz', foreignObject],
|
||||
['blah=burp', {'blah': 'burp'}],
|
||||
['gragh=1&gragh=3&goo=2', {'gragh': ['1', '3'], 'goo': '2'}],
|
||||
['frappucino=muffin&goat%5B%5D=scone&pond=moose',
|
||||
{'frappucino': 'muffin', 'goat[]': 'scone', 'pond': 'moose'}],
|
||||
['trololol=yes&lololo=no', {'trololol': 'yes', 'lololo': 'no'}]
|
||||
];
|
||||
|
||||
assert.strictEqual('918854443121279438895193',
|
||||
qs.parse('id=918854443121279438895193').id);
|
||||
|
||||
// test that the canonical qs is parsed properly.
|
||||
qsTestCases.forEach(function(testCase) {
|
||||
assert.deepEqual(testCase[2], qs.parse(testCase[0]));
|
||||
});
|
||||
|
||||
// test that the colon test cases can do the same
|
||||
qsColonTestCases.forEach(function(testCase) {
|
||||
assert.deepEqual(testCase[2], qs.parse(testCase[0], ';', ':'));
|
||||
});
|
||||
|
||||
// test the weird objects, that they get parsed properly
|
||||
qsWeirdObjects.forEach(function(testCase) {
|
||||
assert.deepEqual(testCase[2], qs.parse(testCase[1]));
|
||||
});
|
||||
|
||||
qsNoMungeTestCases.forEach(function(testCase) {
|
||||
assert.deepEqual(testCase[0], qs.stringify(testCase[1], '&', '=', false));
|
||||
});
|
||||
|
||||
// test the nested qs-in-qs case
|
||||
(function() {
|
||||
var f = qs.parse('a=b&q=x%3Dy%26y%3Dz');
|
||||
f.q = qs.parse(f.q);
|
||||
assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } });
|
||||
})();
|
||||
|
||||
// nested in colon
|
||||
(function() {
|
||||
var f = qs.parse('a:b;q:x%3Ay%3By%3Az', ';', ':');
|
||||
f.q = qs.parse(f.q, ';', ':');
|
||||
assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } });
|
||||
})();
|
||||
|
||||
// now test stringifying
|
||||
|
||||
// basic
|
||||
qsTestCases.forEach(function(testCase) {
|
||||
assert.equal(testCase[1], qs.stringify(testCase[2]));
|
||||
});
|
||||
|
||||
qsColonTestCases.forEach(function(testCase) {
|
||||
assert.equal(testCase[1], qs.stringify(testCase[2], ';', ':'));
|
||||
});
|
||||
|
||||
qsWeirdObjects.forEach(function(testCase) {
|
||||
assert.equal(testCase[1], qs.stringify(testCase[0]));
|
||||
});
|
||||
|
||||
// nested
|
||||
var f = qs.stringify({
|
||||
a: 'b',
|
||||
q: qs.stringify({
|
||||
x: 'y',
|
||||
y: 'z'
|
||||
})
|
||||
});
|
||||
assert.equal(f, 'a=b&q=x%3Dy%26y%3Dz');
|
||||
|
||||
assert.doesNotThrow(function() {
|
||||
qs.parse(undefined);
|
||||
});
|
||||
|
||||
// nested in colon
|
||||
var f = qs.stringify({
|
||||
a: 'b',
|
||||
q: qs.stringify({
|
||||
x: 'y',
|
||||
y: 'z'
|
||||
}, ';', ':')
|
||||
}, ';', ':');
|
||||
assert.equal(f, 'a:b;q:x%3Ay%3By%3Az');
|
||||
|
||||
|
||||
assert.deepEqual({}, qs.parse());
|
||||
|
||||
|
||||
// Test limiting
|
||||
assert.equal(
|
||||
Object.keys(qs.parse('a=1&b=1&c=1', null, null, { maxKeys: 1 })).length,
|
||||
1);
|
||||
|
||||
// Test removing limit
|
||||
function testUnlimitedKeys() {
|
||||
var query = {},
|
||||
url;
|
||||
|
||||
for (var i = 0; i < 2000; i++) query[i] = i;
|
||||
|
||||
url = qs.stringify(query);
|
||||
|
||||
assert.equal(
|
||||
Object.keys(qs.parse(url, null, null, { maxKeys: 0 })).length,
|
||||
2000);
|
||||
}
|
||||
testUnlimitedKeys();
|
||||
|
||||
/*
|
||||
var b = qs.unescapeBuffer('%d3%f2Ug%1f6v%24%5e%98%cb' +
|
||||
'%0d%ac%a2%2f%9d%eb%d8%a2%e6');
|
||||
// <Buffer d3 f2 55 67 1f 36 76 24 5e 98 cb 0d ac a2 2f 9d eb d8 a2 e6>
|
||||
assert.equal(0xd3, b[0]);
|
||||
assert.equal(0xf2, b[1]);
|
||||
assert.equal(0x55, b[2]);
|
||||
assert.equal(0x67, b[3]);
|
||||
assert.equal(0x1f, b[4]);
|
||||
assert.equal(0x36, b[5]);
|
||||
assert.equal(0x76, b[6]);
|
||||
assert.equal(0x24, b[7]);
|
||||
assert.equal(0x5e, b[8]);
|
||||
assert.equal(0x98, b[9]);
|
||||
assert.equal(0xcb, b[10]);
|
||||
assert.equal(0x0d, b[11]);
|
||||
assert.equal(0xac, b[12]);
|
||||
assert.equal(0xa2, b[13]);
|
||||
assert.equal(0x2f, b[14]);
|
||||
assert.equal(0x9d, b[15]);
|
||||
assert.equal(0xeb, b[16]);
|
||||
assert.equal(0xd8, b[17]);
|
||||
assert.equal(0xa2, b[18]);
|
||||
assert.equal(0xe6, b[19]);
|
||||
*/
|
|
@ -0,0 +1,129 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
|
||||
assert.equal('0', common.inspect(0));
|
||||
assert.equal('1', common.inspect(1));
|
||||
assert.equal('false', common.inspect(false));
|
||||
assert.equal("''", common.inspect(''));
|
||||
assert.equal("'hello'", common.inspect('hello'));
|
||||
assert.equal('[Function]', common.inspect(function() {}));
|
||||
assert.equal('undefined', common.inspect(undefined));
|
||||
assert.equal('null', common.inspect(null));
|
||||
assert.equal('/foo(bar\\n)?/gi', common.inspect(/foo(bar\n)?/gi));
|
||||
assert.equal(new Date('2010-02-14T12:48:40+01:00').toString(),
|
||||
common.inspect(new Date('Sun, 14 Feb 2010 11:48:40 GMT')));
|
||||
|
||||
assert.equal("'\\n\\u0001'", common.inspect('\n\u0001'));
|
||||
|
||||
assert.equal('[]', common.inspect([]));
|
||||
assert.equal('{}', common.inspect(Object.create([])));
|
||||
assert.equal('[ 1, 2 ]', common.inspect([1, 2]));
|
||||
assert.equal('[ 1, [ 2, 3 ] ]', common.inspect([1, [2, 3]]));
|
||||
|
||||
assert.equal('{}', common.inspect({}));
|
||||
assert.equal('{ a: 1 }', common.inspect({a: 1}));
|
||||
assert.equal('{ a: [Function] }', common.inspect({a: function() {}}));
|
||||
assert.equal('{ a: 1, b: 2 }', common.inspect({a: 1, b: 2}));
|
||||
assert.equal('{ a: {} }', common.inspect({'a': {}}));
|
||||
assert.equal('{ a: { b: 2 } }', common.inspect({'a': {'b': 2}}));
|
||||
assert.equal('{ a: { b: { c: [Object] } } }',
|
||||
common.inspect({'a': {'b': { 'c': { 'd': 2 }}}}));
|
||||
assert.equal('{ a: { b: { c: { d: 2 } } } }',
|
||||
common.inspect({'a': {'b': { 'c': { 'd': 2 }}}}, false, null));
|
||||
assert.equal('[ 1, 2, 3, [length]: 3 ]', common.inspect([1, 2, 3], true));
|
||||
assert.equal('{ a: [Object] }',
|
||||
common.inspect({'a': {'b': { 'c': 2}}}, false, 0));
|
||||
assert.equal('{ a: { b: [Object] } }',
|
||||
common.inspect({'a': {'b': { 'c': 2}}}, false, 1));
|
||||
assert.equal('{ visible: 1 }',
|
||||
common.inspect(Object.create({},
|
||||
{visible: {value: 1, enumerable: true}, hidden: {value: 2}}))
|
||||
);
|
||||
|
||||
// Due to the hash seed randomization it's not deterministic the order that
|
||||
// the following ways this hash is displayed.
|
||||
// See http://codereview.chromium.org/9124004/
|
||||
|
||||
var out = common.inspect(Object.create({},
|
||||
{visible: {value: 1, enumerable: true}, hidden: {value: 2}}), true);
|
||||
if (out !== '{ [hidden]: 2, visible: 1 }' &&
|
||||
out !== '{ visible: 1, [hidden]: 2 }') {
|
||||
assert.ok(false);
|
||||
}
|
||||
|
||||
|
||||
// Objects without prototype
|
||||
var out = common.inspect(Object.create(null,
|
||||
{ name: {value: 'Tim', enumerable: true},
|
||||
hidden: {value: 'secret'}}), true);
|
||||
if (out !== "{ [hidden]: 'secret', name: 'Tim' }" &&
|
||||
out !== "{ name: 'Tim', [hidden]: 'secret' }") {
|
||||
assert(false);
|
||||
}
|
||||
|
||||
|
||||
assert.equal('{ name: \'Tim\' }',
|
||||
common.inspect(Object.create(null,
|
||||
{name: {value: 'Tim', enumerable: true},
|
||||
hidden: {value: 'secret'}}))
|
||||
);
|
||||
|
||||
|
||||
// Dynamic properties
|
||||
assert.equal('{ readonly: [Getter] }',
|
||||
common.inspect({get readonly() {}}));
|
||||
|
||||
assert.equal('{ readwrite: [Getter/Setter] }',
|
||||
common.inspect({get readwrite() {},set readwrite(val) {}}));
|
||||
|
||||
assert.equal('{ writeonly: [Setter] }',
|
||||
common.inspect({set writeonly(val) {}}));
|
||||
|
||||
var value = {};
|
||||
value['a'] = value;
|
||||
assert.equal('{ a: [Circular] }', common.inspect(value));
|
||||
|
||||
// Array with dynamic properties
|
||||
value = [1, 2, 3];
|
||||
value.__defineGetter__('growingLength', function() {
|
||||
this.push(true); return this.length;
|
||||
});
|
||||
assert.equal('[ 1, 2, 3, growingLength: [Getter] ]', common.inspect(value));
|
||||
|
||||
// Function with properties
|
||||
value = function() {};
|
||||
value.aprop = 42;
|
||||
assert.equal('{ [Function] aprop: 42 }', common.inspect(value));
|
||||
|
||||
// Regular expressions with properties
|
||||
value = /123/ig;
|
||||
value.aprop = 42;
|
||||
assert.equal('{ /123/gi aprop: 42 }', common.inspect(value));
|
||||
|
||||
// Dates with properties
|
||||
value = new Date('Sun, 14 Feb 2010 11:48:40 GMT');
|
||||
value.aprop = 42;
|
||||
assert.equal('{ Sun, 14 Feb 2010 11:48:40 GMT aprop: 42 }',
|
||||
common.inspect(value)
|
||||
);
|
|
@ -0,0 +1,59 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
|
||||
// https://github.com/joyent/node/issues/2079 - zero timeout drops extra args
|
||||
(function() {
|
||||
var ncalled = 0;
|
||||
|
||||
setTimeout(f, 0, 'foo', 'bar', 'baz');
|
||||
var timer = setTimeout(function() {}, 0);
|
||||
|
||||
function f(a, b, c) {
|
||||
assert.equal(a, 'foo');
|
||||
assert.equal(b, 'bar');
|
||||
assert.equal(c, 'baz');
|
||||
ncalled++;
|
||||
}
|
||||
|
||||
process.on('exit', function() {
|
||||
assert.equal(ncalled, 1);
|
||||
});
|
||||
})();
|
||||
|
||||
(function() {
|
||||
var ncalled = 0;
|
||||
|
||||
var iv = setInterval(f, 0, 'foo', 'bar', 'baz');
|
||||
|
||||
function f(a, b, c) {
|
||||
assert.equal(a, 'foo');
|
||||
assert.equal(b, 'bar');
|
||||
assert.equal(c, 'baz');
|
||||
if (++ncalled == 3) clearTimeout(iv);
|
||||
}
|
||||
|
||||
process.on('exit', function() {
|
||||
assert.equal(ncalled, 3);
|
||||
});
|
||||
})();
|
|
@ -0,0 +1,71 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
|
||||
var inputs = [
|
||||
undefined,
|
||||
null,
|
||||
true,
|
||||
false,
|
||||
'',
|
||||
[],
|
||||
{},
|
||||
NaN,
|
||||
+Infinity,
|
||||
-Infinity,
|
||||
(1.0 / 0.0), // sanity check
|
||||
parseFloat('x'), // NaN
|
||||
-10,
|
||||
-1,
|
||||
-0.5,
|
||||
-0.0,
|
||||
0,
|
||||
0.0,
|
||||
0.5,
|
||||
1,
|
||||
1.0,
|
||||
10,
|
||||
2147483648 // browser behaviour: timeouts > 2^31-1 run on next tick
|
||||
];
|
||||
|
||||
var timeouts = [];
|
||||
var intervals = [];
|
||||
|
||||
inputs.forEach(function(value, index) {
|
||||
setTimeout(function() {
|
||||
timeouts[index] = true;
|
||||
}, value);
|
||||
|
||||
var handle = setInterval(function() {
|
||||
clearInterval(handle); // disarm timer or we'll never finish
|
||||
intervals[index] = true;
|
||||
}, value);
|
||||
});
|
||||
|
||||
process.on('exit', function() {
|
||||
// assert that all timers have run
|
||||
inputs.forEach(function(value, index) {
|
||||
assert.equal(true, timeouts[index]);
|
||||
assert.equal(true, intervals[index]);
|
||||
});
|
||||
});
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,62 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
|
||||
|
||||
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
var util = require('util');
|
||||
|
||||
assert.equal(util.format(), '');
|
||||
assert.equal(util.format(''), '');
|
||||
assert.equal(util.format([]), '[]');
|
||||
assert.equal(util.format({}), '{}');
|
||||
assert.equal(util.format(null), 'null');
|
||||
assert.equal(util.format(true), 'true');
|
||||
assert.equal(util.format(false), 'false');
|
||||
assert.equal(util.format('test'), 'test');
|
||||
|
||||
// CHECKME this is for console.log() compatibility - but is it *right*?
|
||||
assert.equal(util.format('foo', 'bar', 'baz'), 'foo bar baz');
|
||||
|
||||
assert.equal(util.format('%d', 42.0), '42');
|
||||
assert.equal(util.format('%d', 42), '42');
|
||||
assert.equal(util.format('%s', 42), '42');
|
||||
assert.equal(util.format('%j', 42), '42');
|
||||
|
||||
assert.equal(util.format('%d', '42.0'), '42');
|
||||
assert.equal(util.format('%d', '42'), '42');
|
||||
assert.equal(util.format('%s', '42'), '42');
|
||||
assert.equal(util.format('%j', '42'), '"42"');
|
||||
|
||||
assert.equal(util.format('%%s%s', 'foo'), '%sfoo');
|
||||
|
||||
assert.equal(util.format('%s'), '%s');
|
||||
assert.equal(util.format('%s', undefined), 'undefined');
|
||||
assert.equal(util.format('%s', 'foo'), 'foo');
|
||||
assert.equal(util.format('%s:%s'), '%s:%s');
|
||||
assert.equal(util.format('%s:%s', undefined), 'undefined:%s');
|
||||
assert.equal(util.format('%s:%s', 'foo'), 'foo:%s');
|
||||
assert.equal(util.format('%s:%s', 'foo', 'bar'), 'foo:bar');
|
||||
assert.equal(util.format('%s:%s', 'foo', 'bar', 'baz'), 'foo:bar baz');
|
||||
assert.equal(util.format('%%%s%%', 'hi'), '%hi%');
|
||||
assert.equal(util.format('%%%s%%%%', 'hi'), '%hi%%');
|
|
@ -0,0 +1,102 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
|
||||
|
||||
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
var util = require('util');
|
||||
|
||||
// test the internal isDate implementation
|
||||
var Date2 = require('vm').runInNewContext('Date');
|
||||
var d = new Date2();
|
||||
var orig = util.inspect(d);
|
||||
Date2.prototype.foo = 'bar';
|
||||
var after = util.inspect(d);
|
||||
assert.equal(orig, after);
|
||||
|
||||
// test for sparse array
|
||||
var a = ['foo', 'bar', 'baz'];
|
||||
assert.equal(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]');
|
||||
delete a[1];
|
||||
assert.equal(util.inspect(a), '[ \'foo\', , \'baz\' ]');
|
||||
assert.equal(util.inspect(a, true), '[ \'foo\', , \'baz\', [length]: 3 ]');
|
||||
assert.equal(util.inspect(new Array(5)), '[ , , , , ]');
|
||||
|
||||
// test for property descriptors
|
||||
var getter = Object.create(null, {
|
||||
a: {
|
||||
get: function() { return 'aaa'; }
|
||||
}
|
||||
});
|
||||
var setter = Object.create(null, {
|
||||
b: {
|
||||
set: function() {}
|
||||
}
|
||||
});
|
||||
var getterAndSetter = Object.create(null, {
|
||||
c: {
|
||||
get: function() { return 'ccc'; },
|
||||
set: function() {}
|
||||
}
|
||||
});
|
||||
assert.equal(util.inspect(getter, true), '{ [a]: [Getter] }');
|
||||
assert.equal(util.inspect(setter, true), '{ [b]: [Setter] }');
|
||||
assert.equal(util.inspect(getterAndSetter, true), '{ [c]: [Getter/Setter] }');
|
||||
|
||||
// exceptions should print the error message, not '{}'
|
||||
assert.equal(util.inspect(new Error()), '[Error]');
|
||||
assert.equal(util.inspect(new Error('FAIL')), '[Error: FAIL]');
|
||||
assert.equal(util.inspect(new TypeError('FAIL')), '[TypeError: FAIL]');
|
||||
assert.equal(util.inspect(new SyntaxError('FAIL')), '[SyntaxError: FAIL]');
|
||||
try {
|
||||
undef();
|
||||
} catch (e) {
|
||||
assert.equal(util.inspect(e), '[ReferenceError: undef is not defined]');
|
||||
}
|
||||
var ex = util.inspect(new Error('FAIL'), true);
|
||||
assert.ok(ex.indexOf('[Error: FAIL]') != -1);
|
||||
assert.ok(ex.indexOf('[stack]') != -1);
|
||||
assert.ok(ex.indexOf('[message]') != -1);
|
||||
assert.ok(ex.indexOf('[arguments]') != -1);
|
||||
assert.ok(ex.indexOf('[type]') != -1);
|
||||
|
||||
// GH-1941
|
||||
// should not throw:
|
||||
assert.equal(util.inspect(Object.create(Date.prototype)), '{}');
|
||||
|
||||
// GH-1944
|
||||
assert.doesNotThrow(function() {
|
||||
var d = new Date();
|
||||
d.toUTCString = null;
|
||||
util.inspect(d);
|
||||
});
|
||||
|
||||
assert.doesNotThrow(function() {
|
||||
var r = /regexp/;
|
||||
r.toString = null;
|
||||
util.inspect(r);
|
||||
});
|
||||
|
||||
// GH-2225
|
||||
var x = { inspect: util.inspect };
|
||||
assert.ok(util.inspect(x).indexOf('inspect') != -1);
|
|
@ -0,0 +1,71 @@
|
|||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
var util = require('util');
|
||||
var context = require('vm').runInNewContext;
|
||||
|
||||
// isArray
|
||||
assert.equal(true, util.isArray([]));
|
||||
assert.equal(true, util.isArray(Array()));
|
||||
assert.equal(true, util.isArray(new Array()));
|
||||
assert.equal(true, util.isArray(new Array(5)));
|
||||
assert.equal(true, util.isArray(new Array('with', 'some', 'entries')));
|
||||
assert.equal(true, util.isArray(context('Array')()));
|
||||
assert.equal(false, util.isArray({}));
|
||||
assert.equal(false, util.isArray({ push: function() {} }));
|
||||
assert.equal(false, util.isArray(/regexp/));
|
||||
assert.equal(false, util.isArray(new Error));
|
||||
assert.equal(false, util.isArray(Object.create(Array.prototype)));
|
||||
|
||||
// isRegExp
|
||||
assert.equal(true, util.isRegExp(/regexp/));
|
||||
assert.equal(true, util.isRegExp(RegExp()));
|
||||
assert.equal(true, util.isRegExp(new RegExp()));
|
||||
assert.equal(true, util.isRegExp(context('RegExp')()));
|
||||
assert.equal(false, util.isRegExp({}));
|
||||
assert.equal(false, util.isRegExp([]));
|
||||
assert.equal(false, util.isRegExp(new Date()));
|
||||
assert.equal(false, util.isRegExp(Object.create(RegExp.prototype)));
|
||||
|
||||
// isDate
|
||||
assert.equal(true, util.isDate(new Date()));
|
||||
assert.equal(true, util.isDate(new Date(0)));
|
||||
assert.equal(true, util.isDate(new (context('Date'))));
|
||||
assert.equal(false, util.isDate(Date()));
|
||||
assert.equal(false, util.isDate({}));
|
||||
assert.equal(false, util.isDate([]));
|
||||
assert.equal(false, util.isDate(new Error));
|
||||
assert.equal(false, util.isDate(Object.create(Date.prototype)));
|
||||
|
||||
// isError
|
||||
assert.equal(true, util.isError(new Error));
|
||||
assert.equal(true, util.isError(new TypeError));
|
||||
assert.equal(true, util.isError(new SyntaxError));
|
||||
assert.equal(true, util.isError(new (context('Error'))));
|
||||
assert.equal(true, util.isError(new (context('TypeError'))));
|
||||
assert.equal(true, util.isError(new (context('SyntaxError'))));
|
||||
assert.equal(false, util.isError({}));
|
||||
assert.equal(false, util.isError({ name: 'Error', message: '' }));
|
||||
assert.equal(false, util.isError([]));
|
||||
assert.equal(false, util.isError(Object.create(Error.prototype)));
|
|
@ -10,15 +10,15 @@
|
|||
};
|
||||
window.writing = true;
|
||||
</script>
|
||||
<script src="js/libary1.js"></script>
|
||||
<script src="js/libary2.js"></script>
|
||||
<script src="js/web.js"></script>
|
||||
<script src="js/libary1.js" charset="utf-8"></script>
|
||||
<script src="js/libary2.js" charset="utf-8"></script>
|
||||
<script src="js/web.js" charset="utf-8"></script>
|
||||
<script>
|
||||
window.test = function(ok, message) {
|
||||
var p = document.createElement("p");
|
||||
p.appendChild(document.createTextNode((ok?"OK: ":"FAILED: ")+message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")));
|
||||
if(!ok)
|
||||
p.style = "color: red; font-weight: bold;";
|
||||
p.setAttribute("style", "color: red; font-weight: bold;");
|
||||
document.body.appendChild(p);
|
||||
};
|
||||
window.writing = false;
|
||||
|
|
Loading…
Reference in New Issue