text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```javascript // Generated by CoffeeScript 1.12.7 (function() { var XMLStringifier, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, hasProp = {}.hasOwnProperty; module.exports = XMLStringifier = (function() { function XMLStringifier(options) { this.assertLegalName = bind(this.assertLegalName, this); this.assertLegalChar = bind(this.assertLegalChar, this); var key, ref, value; options || (options = {}); this.options = options; if (!this.options.version) { this.options.version = '1.0'; } ref = options.stringify || {}; for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; this[key] = value; } } XMLStringifier.prototype.name = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalName('' + val || ''); }; XMLStringifier.prototype.text = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar(this.textEscape('' + val || '')); }; XMLStringifier.prototype.cdata = function(val) { if (this.options.noValidation) { return val; } val = '' + val || ''; val = val.replace(']]>', ']]]]><![CDATA[>'); return this.assertLegalChar(val); }; XMLStringifier.prototype.comment = function(val) { if (this.options.noValidation) { return val; } val = '' + val || ''; if (val.match(/--/)) { throw new Error("Comment text cannot contain double-hypen: " + val); } return this.assertLegalChar(val); }; XMLStringifier.prototype.raw = function(val) { if (this.options.noValidation) { return val; } return '' + val || ''; }; XMLStringifier.prototype.attValue = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar(this.attEscape(val = '' + val || '')); }; XMLStringifier.prototype.insTarget = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.insValue = function(val) { if (this.options.noValidation) { return val; } val = '' + val || ''; if (val.match(/\?>/)) { throw new Error("Invalid processing instruction value: " + val); } return this.assertLegalChar(val); }; XMLStringifier.prototype.xmlVersion = function(val) { if (this.options.noValidation) { return val; } val = '' + val || ''; if (!val.match(/1\.[0-9]+/)) { throw new Error("Invalid version number: " + val); } return val; }; XMLStringifier.prototype.xmlEncoding = function(val) { if (this.options.noValidation) { return val; } val = '' + val || ''; if (!val.match(/^[A-Za-z](?:[A-Za-z0-9._-])*$/)) { throw new Error("Invalid encoding: " + val); } return this.assertLegalChar(val); }; XMLStringifier.prototype.xmlStandalone = function(val) { if (this.options.noValidation) { return val; } if (val) { return "yes"; } else { return "no"; } }; XMLStringifier.prototype.dtdPubID = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.dtdSysID = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.dtdElementValue = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.dtdAttType = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.dtdAttDefault = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.dtdEntityValue = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.dtdNData = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.convertAttKey = '@'; XMLStringifier.prototype.convertPIKey = '?'; XMLStringifier.prototype.convertTextKey = '#text'; XMLStringifier.prototype.convertCDataKey = '#cdata'; XMLStringifier.prototype.convertCommentKey = '#comment'; XMLStringifier.prototype.convertRawKey = '#raw'; XMLStringifier.prototype.assertLegalChar = function(str) { var regex, res; if (this.options.noValidation) { return str; } regex = ''; if (this.options.version === '1.0') { regex = /[\0-\x08\x0B\f\x0E-\x1F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; if (res = str.match(regex)) { throw new Error("Invalid character in string: " + str + " at index " + res.index); } } else if (this.options.version === '1.1') { regex = /[\0\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; if (res = str.match(regex)) { throw new Error("Invalid character in string: " + str + " at index " + res.index); } } return str; }; XMLStringifier.prototype.assertLegalName = function(str) { var regex; if (this.options.noValidation) { return str; } this.assertLegalChar(str); regex = /^([:A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])([\x2D\.0-:A-Z_a-z\xB7\xC0-\xD6\xD8-\xF6\xF8-\u037D\u037F-\u1FFF\u200C\u200D\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])*$/; if (!str.match(regex)) { throw new Error("Invalid character in name"); } return str; }; XMLStringifier.prototype.textEscape = function(str) { var ampregex; if (this.options.noValidation) { return str; } ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g; return str.replace(ampregex, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\r/g, '&#xD;'); }; XMLStringifier.prototype.attEscape = function(str) { var ampregex; if (this.options.noValidation) { return str; } ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g; return str.replace(ampregex, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;').replace(/\t/g, '&#x9;').replace(/\n/g, '&#xA;').replace(/\r/g, '&#xD;'); }; return XMLStringifier; })(); }).call(this); ```
/content/code_sandbox/node_modules/xmlbuilder/lib/XMLStringifier.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,937
```javascript // Generated by CoffeeScript 1.12.7 (function() { "use strict"; exports.stripBOM = function(str) { if (str[0] === '\uFEFF') { return str.substring(1); } else { return str; } }; }).call(this); ```
/content/code_sandbox/node_modules/xml2js/lib/bom.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
68
```javascript // Generated by CoffeeScript 1.12.7 (function() { "use strict"; var builder, defaults, escapeCDATA, requiresCDATA, wrapCDATA, hasProp = {}.hasOwnProperty; builder = require('xmlbuilder'); defaults = require('./defaults').defaults; requiresCDATA = function(entry) { return typeof entry === "string" && (entry.indexOf('&') >= 0 || entry.indexOf('>') >= 0 || entry.indexOf('<') >= 0); }; wrapCDATA = function(entry) { return "<![CDATA[" + (escapeCDATA(entry)) + "]]>"; }; escapeCDATA = function(entry) { return entry.replace(']]>', ']]]]><![CDATA[>'); }; exports.Builder = (function() { function Builder(opts) { var key, ref, value; this.options = {}; ref = defaults["0.2"]; for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; this.options[key] = value; } for (key in opts) { if (!hasProp.call(opts, key)) continue; value = opts[key]; this.options[key] = value; } } Builder.prototype.buildObject = function(rootObj) { var attrkey, charkey, render, rootElement, rootName; attrkey = this.options.attrkey; charkey = this.options.charkey; if ((Object.keys(rootObj).length === 1) && (this.options.rootName === defaults['0.2'].rootName)) { rootName = Object.keys(rootObj)[0]; rootObj = rootObj[rootName]; } else { rootName = this.options.rootName; } render = (function(_this) { return function(element, obj) { var attr, child, entry, index, key, value; if (typeof obj !== 'object') { if (_this.options.cdata && requiresCDATA(obj)) { element.raw(wrapCDATA(obj)); } else { element.txt(obj); } } else if (Array.isArray(obj)) { for (index in obj) { if (!hasProp.call(obj, index)) continue; child = obj[index]; for (key in child) { entry = child[key]; element = render(element.ele(key), entry).up(); } } } else { for (key in obj) { if (!hasProp.call(obj, key)) continue; child = obj[key]; if (key === attrkey) { if (typeof child === "object") { for (attr in child) { value = child[attr]; element = element.att(attr, value); } } } else if (key === charkey) { if (_this.options.cdata && requiresCDATA(child)) { element = element.raw(wrapCDATA(child)); } else { element = element.txt(child); } } else if (Array.isArray(child)) { for (index in child) { if (!hasProp.call(child, index)) continue; entry = child[index]; if (typeof entry === 'string') { if (_this.options.cdata && requiresCDATA(entry)) { element = element.ele(key).raw(wrapCDATA(entry)).up(); } else { element = element.ele(key, entry).up(); } } else { element = render(element.ele(key), entry).up(); } } } else if (typeof child === "object") { element = render(element.ele(key), child).up(); } else { if (typeof child === 'string' && _this.options.cdata && requiresCDATA(child)) { element = element.ele(key).raw(wrapCDATA(child)).up(); } else { if (child == null) { child = ''; } element = element.ele(key, child.toString()).up(); } } } } return element; }; })(this); rootElement = builder.create(rootName, this.options.xmldec, this.options.doctype, { headless: this.options.headless, allowSurrogateChars: this.options.allowSurrogateChars }); return render(rootElement, rootObj).end(this.options.renderOpts); }; return Builder; })(); }).call(this); ```
/content/code_sandbox/node_modules/xml2js/lib/builder.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
939
```javascript // Generated by CoffeeScript 1.12.7 (function() { "use strict"; var builder, defaults, parser, processors, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; defaults = require('./defaults'); builder = require('./builder'); parser = require('./parser'); processors = require('./processors'); exports.defaults = defaults.defaults; exports.processors = processors; exports.ValidationError = (function(superClass) { extend(ValidationError, superClass); function ValidationError(message) { this.message = message; } return ValidationError; })(Error); exports.Builder = builder.Builder; exports.Parser = parser.Parser; exports.parseString = parser.parseString; exports.parseStringPromise = parser.parseStringPromise; }).call(this); ```
/content/code_sandbox/node_modules/xml2js/lib/xml2js.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
226
```javascript // Generated by CoffeeScript 1.12.7 (function() { "use strict"; var prefixMatch; prefixMatch = new RegExp(/(?!xmlns)^.*:/); exports.normalize = function(str) { return str.toLowerCase(); }; exports.firstCharLowerCase = function(str) { return str.charAt(0).toLowerCase() + str.slice(1); }; exports.stripPrefix = function(str) { return str.replace(prefixMatch, ''); }; exports.parseNumbers = function(str) { if (!isNaN(str)) { str = str % 1 === 0 ? parseInt(str, 10) : parseFloat(str); } return str; }; exports.parseBooleans = function(str) { if (/^(?:true|false)$/i.test(str)) { str = str.toLowerCase() === 'true'; } return str; }; }).call(this); ```
/content/code_sandbox/node_modules/xml2js/lib/processors.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
192
```javascript // Generated by CoffeeScript 1.12.7 (function() { exports.defaults = { "0.1": { explicitCharkey: false, trim: true, normalize: true, normalizeTags: false, attrkey: "@", charkey: "#", explicitArray: false, ignoreAttrs: false, mergeAttrs: false, explicitRoot: false, validator: null, xmlns: false, explicitChildren: false, childkey: '@@', charsAsChildren: false, includeWhiteChars: false, async: false, strict: true, attrNameProcessors: null, attrValueProcessors: null, tagNameProcessors: null, valueProcessors: null, emptyTag: '' }, "0.2": { explicitCharkey: false, trim: false, normalize: false, normalizeTags: false, attrkey: "$", charkey: "_", explicitArray: true, ignoreAttrs: false, mergeAttrs: false, explicitRoot: true, validator: null, xmlns: false, explicitChildren: false, preserveChildrenOrder: false, childkey: '$$', charsAsChildren: false, includeWhiteChars: false, async: false, strict: true, attrNameProcessors: null, attrValueProcessors: null, tagNameProcessors: null, valueProcessors: null, rootName: 'root', xmldec: { 'version': '1.0', 'encoding': 'UTF-8', 'standalone': true }, doctype: null, renderOpts: { 'pretty': true, 'indent': ' ', 'newline': '\n' }, headless: false, chunkSize: 10000, emptyTag: '', cdata: false } }; }).call(this); ```
/content/code_sandbox/node_modules/xml2js/lib/defaults.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
426
```javascript 'use strict' module.exports = clone var getPrototypeOf = Object.getPrototypeOf || function (obj) { return obj.__proto__ } function clone (obj) { if (obj === null || typeof obj !== 'object') return obj if (obj instanceof Object) var copy = { __proto__: getPrototypeOf(obj) } else var copy = Object.create(null) Object.getOwnPropertyNames(obj).forEach(function (key) { Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) }) return copy } ```
/content/code_sandbox/node_modules/graceful-fs/clone.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
115
```javascript // Generated by CoffeeScript 1.12.7 (function() { "use strict"; var bom, defaults, events, isEmpty, processItem, processors, sax, setImmediate, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; sax = require('sax'); events = require('events'); bom = require('./bom'); processors = require('./processors'); setImmediate = require('timers').setImmediate; defaults = require('./defaults').defaults; isEmpty = function(thing) { return typeof thing === "object" && (thing != null) && Object.keys(thing).length === 0; }; processItem = function(processors, item, key) { var i, len, process; for (i = 0, len = processors.length; i < len; i++) { process = processors[i]; item = process(item, key); } return item; }; exports.Parser = (function(superClass) { extend(Parser, superClass); function Parser(opts) { this.parseStringPromise = bind(this.parseStringPromise, this); this.parseString = bind(this.parseString, this); this.reset = bind(this.reset, this); this.assignOrPush = bind(this.assignOrPush, this); this.processAsync = bind(this.processAsync, this); var key, ref, value; if (!(this instanceof exports.Parser)) { return new exports.Parser(opts); } this.options = {}; ref = defaults["0.2"]; for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; this.options[key] = value; } for (key in opts) { if (!hasProp.call(opts, key)) continue; value = opts[key]; this.options[key] = value; } if (this.options.xmlns) { this.options.xmlnskey = this.options.attrkey + "ns"; } if (this.options.normalizeTags) { if (!this.options.tagNameProcessors) { this.options.tagNameProcessors = []; } this.options.tagNameProcessors.unshift(processors.normalize); } this.reset(); } Parser.prototype.processAsync = function() { var chunk, err; try { if (this.remaining.length <= this.options.chunkSize) { chunk = this.remaining; this.remaining = ''; this.saxParser = this.saxParser.write(chunk); return this.saxParser.close(); } else { chunk = this.remaining.substr(0, this.options.chunkSize); this.remaining = this.remaining.substr(this.options.chunkSize, this.remaining.length); this.saxParser = this.saxParser.write(chunk); return setImmediate(this.processAsync); } } catch (error1) { err = error1; if (!this.saxParser.errThrown) { this.saxParser.errThrown = true; return this.emit(err); } } }; Parser.prototype.assignOrPush = function(obj, key, newValue) { if (!(key in obj)) { if (!this.options.explicitArray) { return obj[key] = newValue; } else { return obj[key] = [newValue]; } } else { if (!(obj[key] instanceof Array)) { obj[key] = [obj[key]]; } return obj[key].push(newValue); } }; Parser.prototype.reset = function() { var attrkey, charkey, ontext, stack; this.removeAllListeners(); this.saxParser = sax.parser(this.options.strict, { trim: false, normalize: false, xmlns: this.options.xmlns }); this.saxParser.errThrown = false; this.saxParser.onerror = (function(_this) { return function(error) { _this.saxParser.resume(); if (!_this.saxParser.errThrown) { _this.saxParser.errThrown = true; return _this.emit("error", error); } }; })(this); this.saxParser.onend = (function(_this) { return function() { if (!_this.saxParser.ended) { _this.saxParser.ended = true; return _this.emit("end", _this.resultObject); } }; })(this); this.saxParser.ended = false; this.EXPLICIT_CHARKEY = this.options.explicitCharkey; this.resultObject = null; stack = []; attrkey = this.options.attrkey; charkey = this.options.charkey; this.saxParser.onopentag = (function(_this) { return function(node) { var key, newValue, obj, processedKey, ref; obj = {}; obj[charkey] = ""; if (!_this.options.ignoreAttrs) { ref = node.attributes; for (key in ref) { if (!hasProp.call(ref, key)) continue; if (!(attrkey in obj) && !_this.options.mergeAttrs) { obj[attrkey] = {}; } newValue = _this.options.attrValueProcessors ? processItem(_this.options.attrValueProcessors, node.attributes[key], key) : node.attributes[key]; processedKey = _this.options.attrNameProcessors ? processItem(_this.options.attrNameProcessors, key) : key; if (_this.options.mergeAttrs) { _this.assignOrPush(obj, processedKey, newValue); } else { obj[attrkey][processedKey] = newValue; } } } obj["#name"] = _this.options.tagNameProcessors ? processItem(_this.options.tagNameProcessors, node.name) : node.name; if (_this.options.xmlns) { obj[_this.options.xmlnskey] = { uri: node.uri, local: node.local }; } return stack.push(obj); }; })(this); this.saxParser.onclosetag = (function(_this) { return function() { var cdata, emptyStr, key, node, nodeName, obj, objClone, old, s, xpath; obj = stack.pop(); nodeName = obj["#name"]; if (!_this.options.explicitChildren || !_this.options.preserveChildrenOrder) { delete obj["#name"]; } if (obj.cdata === true) { cdata = obj.cdata; delete obj.cdata; } s = stack[stack.length - 1]; if (obj[charkey].match(/^\s*$/) && !cdata) { emptyStr = obj[charkey]; delete obj[charkey]; } else { if (_this.options.trim) { obj[charkey] = obj[charkey].trim(); } if (_this.options.normalize) { obj[charkey] = obj[charkey].replace(/\s{2,}/g, " ").trim(); } obj[charkey] = _this.options.valueProcessors ? processItem(_this.options.valueProcessors, obj[charkey], nodeName) : obj[charkey]; if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) { obj = obj[charkey]; } } if (isEmpty(obj)) { obj = _this.options.emptyTag !== '' ? _this.options.emptyTag : emptyStr; } if (_this.options.validator != null) { xpath = "/" + ((function() { var i, len, results; results = []; for (i = 0, len = stack.length; i < len; i++) { node = stack[i]; results.push(node["#name"]); } return results; })()).concat(nodeName).join("/"); (function() { var err; try { return obj = _this.options.validator(xpath, s && s[nodeName], obj); } catch (error1) { err = error1; return _this.emit("error", err); } })(); } if (_this.options.explicitChildren && !_this.options.mergeAttrs && typeof obj === 'object') { if (!_this.options.preserveChildrenOrder) { node = {}; if (_this.options.attrkey in obj) { node[_this.options.attrkey] = obj[_this.options.attrkey]; delete obj[_this.options.attrkey]; } if (!_this.options.charsAsChildren && _this.options.charkey in obj) { node[_this.options.charkey] = obj[_this.options.charkey]; delete obj[_this.options.charkey]; } if (Object.getOwnPropertyNames(obj).length > 0) { node[_this.options.childkey] = obj; } obj = node; } else if (s) { s[_this.options.childkey] = s[_this.options.childkey] || []; objClone = {}; for (key in obj) { if (!hasProp.call(obj, key)) continue; objClone[key] = obj[key]; } s[_this.options.childkey].push(objClone); delete obj["#name"]; if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) { obj = obj[charkey]; } } } if (stack.length > 0) { return _this.assignOrPush(s, nodeName, obj); } else { if (_this.options.explicitRoot) { old = obj; obj = {}; obj[nodeName] = old; } _this.resultObject = obj; _this.saxParser.ended = true; return _this.emit("end", _this.resultObject); } }; })(this); ontext = (function(_this) { return function(text) { var charChild, s; s = stack[stack.length - 1]; if (s) { s[charkey] += text; if (_this.options.explicitChildren && _this.options.preserveChildrenOrder && _this.options.charsAsChildren && (_this.options.includeWhiteChars || text.replace(/\\n/g, '').trim() !== '')) { s[_this.options.childkey] = s[_this.options.childkey] || []; charChild = { '#name': '__text__' }; charChild[charkey] = text; if (_this.options.normalize) { charChild[charkey] = charChild[charkey].replace(/\s{2,}/g, " ").trim(); } s[_this.options.childkey].push(charChild); } return s; } }; })(this); this.saxParser.ontext = ontext; return this.saxParser.oncdata = (function(_this) { return function(text) { var s; s = ontext(text); if (s) { return s.cdata = true; } }; })(this); }; Parser.prototype.parseString = function(str, cb) { var err; if ((cb != null) && typeof cb === "function") { this.on("end", function(result) { this.reset(); return cb(null, result); }); this.on("error", function(err) { this.reset(); return cb(err); }); } try { str = str.toString(); if (str.trim() === '') { this.emit("end", null); return true; } str = bom.stripBOM(str); if (this.options.async) { this.remaining = str; setImmediate(this.processAsync); return this.saxParser; } return this.saxParser.write(str).close(); } catch (error1) { err = error1; if (!(this.saxParser.errThrown || this.saxParser.ended)) { this.emit('error', err); return this.saxParser.errThrown = true; } else if (this.saxParser.ended) { throw err; } } }; Parser.prototype.parseStringPromise = function(str) { return new Promise((function(_this) { return function(resolve, reject) { return _this.parseString(str, function(err, value) { if (err) { return reject(err); } else { return resolve(value); } }); }; })(this)); }; return Parser; })(events); exports.parseString = function(str, a, b) { var cb, options, parser; if (b != null) { if (typeof b === 'function') { cb = b; } if (typeof a === 'object') { options = a; } } else { if (typeof a === 'function') { cb = a; } options = {}; } parser = new exports.Parser(options); return parser.parseString(str, cb); }; exports.parseStringPromise = function(str, a) { var options, parser; if (typeof a === 'object') { options = a; } parser = new exports.Parser(options); return parser.parseStringPromise(str); }; }).call(this); ```
/content/code_sandbox/node_modules/xml2js/lib/parser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,890
```javascript var Stream = require('stream').Stream module.exports = legacy function legacy (fs) { return { ReadStream: ReadStream, WriteStream: WriteStream } function ReadStream (path, options) { if (!(this instanceof ReadStream)) return new ReadStream(path, options); Stream.call(this); var self = this; this.path = path; this.fd = null; this.readable = true; this.paused = false; this.flags = 'r'; this.mode = 438; /*=0666*/ this.bufferSize = 64 * 1024; options = options || {}; // Mixin options into this var keys = Object.keys(options); for (var index = 0, length = keys.length; index < length; index++) { var key = keys[index]; this[key] = options[key]; } if (this.encoding) this.setEncoding(this.encoding); if (this.start !== undefined) { if ('number' !== typeof this.start) { throw TypeError('start must be a Number'); } if (this.end === undefined) { this.end = Infinity; } else if ('number' !== typeof this.end) { throw TypeError('end must be a Number'); } if (this.start > this.end) { throw new Error('start must be <= end'); } this.pos = this.start; } if (this.fd !== null) { process.nextTick(function() { self._read(); }); return; } fs.open(this.path, this.flags, this.mode, function (err, fd) { if (err) { self.emit('error', err); self.readable = false; return; } self.fd = fd; self.emit('open', fd); self._read(); }) } function WriteStream (path, options) { if (!(this instanceof WriteStream)) return new WriteStream(path, options); Stream.call(this); this.path = path; this.fd = null; this.writable = true; this.flags = 'w'; this.encoding = 'binary'; this.mode = 438; /*=0666*/ this.bytesWritten = 0; options = options || {}; // Mixin options into this var keys = Object.keys(options); for (var index = 0, length = keys.length; index < length; index++) { var key = keys[index]; this[key] = options[key]; } if (this.start !== undefined) { if ('number' !== typeof this.start) { throw TypeError('start must be a Number'); } if (this.start < 0) { throw new Error('start must be >= zero'); } this.pos = this.start; } this.busy = false; this._queue = []; if (this.fd === null) { this._open = fs.open; this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); this.flush(); } } } ```
/content/code_sandbox/node_modules/graceful-fs/legacy-streams.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
673
```javascript var fs = require('fs') var polyfills = require('./polyfills.js') var legacy = require('./legacy-streams.js') var clone = require('./clone.js') var util = require('util') /* istanbul ignore next - node 0.x polyfill */ var gracefulQueue var previousSymbol /* istanbul ignore else - node 0.x polyfill */ if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { gracefulQueue = Symbol.for('graceful-fs.queue') // This is used in testing by future versions previousSymbol = Symbol.for('graceful-fs.previous') } else { gracefulQueue = '___graceful-fs.queue' previousSymbol = '___graceful-fs.previous' } function noop () {} function publishQueue(context, queue) { Object.defineProperty(context, gracefulQueue, { get: function() { return queue } }) } var debug = noop if (util.debuglog) debug = util.debuglog('gfs4') else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) debug = function() { var m = util.format.apply(util, arguments) m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') console.error(m) } // Once time initialization if (!fs[gracefulQueue]) { // This queue can be shared by multiple loaded instances var queue = global[gracefulQueue] || [] publishQueue(fs, queue) // Patch fs.close/closeSync to shared queue version, because we need // to retry() whenever a close happens *anywhere* in the program. // This is essential when multiple graceful-fs instances are // in play at the same time. fs.close = (function (fs$close) { function close (fd, cb) { return fs$close.call(fs, fd, function (err) { // This function uses the graceful-fs shared queue if (!err) { resetQueue() } if (typeof cb === 'function') cb.apply(this, arguments) }) } Object.defineProperty(close, previousSymbol, { value: fs$close }) return close })(fs.close) fs.closeSync = (function (fs$closeSync) { function closeSync (fd) { // This function uses the graceful-fs shared queue fs$closeSync.apply(fs, arguments) resetQueue() } Object.defineProperty(closeSync, previousSymbol, { value: fs$closeSync }) return closeSync })(fs.closeSync) if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { process.on('exit', function() { debug(fs[gracefulQueue]) require('assert').equal(fs[gracefulQueue].length, 0) }) } } if (!global[gracefulQueue]) { publishQueue(global, fs[gracefulQueue]); } module.exports = patch(clone(fs)) if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { module.exports = patch(fs) fs.__patched = true; } function patch (fs) { // Everything that references the open() function needs to be in here polyfills(fs) fs.gracefulify = patch fs.createReadStream = createReadStream fs.createWriteStream = createWriteStream var fs$readFile = fs.readFile fs.readFile = readFile function readFile (path, options, cb) { if (typeof options === 'function') cb = options, options = null return go$readFile(path, options, cb) function go$readFile (path, options, cb, startTime) { return fs$readFile(path, options, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$writeFile = fs.writeFile fs.writeFile = writeFile function writeFile (path, data, options, cb) { if (typeof options === 'function') cb = options, options = null return go$writeFile(path, data, options, cb) function go$writeFile (path, data, options, cb, startTime) { return fs$writeFile(path, data, options, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$appendFile = fs.appendFile if (fs$appendFile) fs.appendFile = appendFile function appendFile (path, data, options, cb) { if (typeof options === 'function') cb = options, options = null return go$appendFile(path, data, options, cb) function go$appendFile (path, data, options, cb, startTime) { return fs$appendFile(path, data, options, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$copyFile = fs.copyFile if (fs$copyFile) fs.copyFile = copyFile function copyFile (src, dest, flags, cb) { if (typeof flags === 'function') { cb = flags flags = 0 } return go$copyFile(src, dest, flags, cb) function go$copyFile (src, dest, flags, cb, startTime) { return fs$copyFile(src, dest, flags, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$readdir = fs.readdir fs.readdir = readdir var noReaddirOptionVersions = /^v[0-5]\./ function readdir (path, options, cb) { if (typeof options === 'function') cb = options, options = null var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir (path, options, cb, startTime) { return fs$readdir(path, fs$readdirCallback( path, options, cb, startTime )) } : function go$readdir (path, options, cb, startTime) { return fs$readdir(path, options, fs$readdirCallback( path, options, cb, startTime )) } return go$readdir(path, options, cb) function fs$readdirCallback (path, options, cb, startTime) { return function (err, files) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([ go$readdir, [path, options, cb], err, startTime || Date.now(), Date.now() ]) else { if (files && files.sort) files.sort() if (typeof cb === 'function') cb.call(this, err, files) } } } } if (process.version.substr(0, 4) === 'v0.8') { var legStreams = legacy(fs) ReadStream = legStreams.ReadStream WriteStream = legStreams.WriteStream } var fs$ReadStream = fs.ReadStream if (fs$ReadStream) { ReadStream.prototype = Object.create(fs$ReadStream.prototype) ReadStream.prototype.open = ReadStream$open } var fs$WriteStream = fs.WriteStream if (fs$WriteStream) { WriteStream.prototype = Object.create(fs$WriteStream.prototype) WriteStream.prototype.open = WriteStream$open } Object.defineProperty(fs, 'ReadStream', { get: function () { return ReadStream }, set: function (val) { ReadStream = val }, enumerable: true, configurable: true }) Object.defineProperty(fs, 'WriteStream', { get: function () { return WriteStream }, set: function (val) { WriteStream = val }, enumerable: true, configurable: true }) // legacy names var FileReadStream = ReadStream Object.defineProperty(fs, 'FileReadStream', { get: function () { return FileReadStream }, set: function (val) { FileReadStream = val }, enumerable: true, configurable: true }) var FileWriteStream = WriteStream Object.defineProperty(fs, 'FileWriteStream', { get: function () { return FileWriteStream }, set: function (val) { FileWriteStream = val }, enumerable: true, configurable: true }) function ReadStream (path, options) { if (this instanceof ReadStream) return fs$ReadStream.apply(this, arguments), this else return ReadStream.apply(Object.create(ReadStream.prototype), arguments) } function ReadStream$open () { var that = this open(that.path, that.flags, that.mode, function (err, fd) { if (err) { if (that.autoClose) that.destroy() that.emit('error', err) } else { that.fd = fd that.emit('open', fd) that.read() } }) } function WriteStream (path, options) { if (this instanceof WriteStream) return fs$WriteStream.apply(this, arguments), this else return WriteStream.apply(Object.create(WriteStream.prototype), arguments) } function WriteStream$open () { var that = this open(that.path, that.flags, that.mode, function (err, fd) { if (err) { that.destroy() that.emit('error', err) } else { that.fd = fd that.emit('open', fd) } }) } function createReadStream (path, options) { return new fs.ReadStream(path, options) } function createWriteStream (path, options) { return new fs.WriteStream(path, options) } var fs$open = fs.open fs.open = open function open (path, flags, mode, cb) { if (typeof mode === 'function') cb = mode, mode = null return go$open(path, flags, mode, cb) function go$open (path, flags, mode, cb, startTime) { return fs$open(path, flags, mode, function (err, fd) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } return fs } function enqueue (elem) { debug('ENQUEUE', elem[0].name, elem[1]) fs[gracefulQueue].push(elem) retry() } // keep track of the timeout between retry() calls var retryTimer // reset the startTime and lastTime to now // this resets the start of the 60 second overall timeout as well as the // delay between attempts so that we'll retry these jobs sooner function resetQueue () { var now = Date.now() for (var i = 0; i < fs[gracefulQueue].length; ++i) { // entries that are only a length of 2 are from an older version, don't // bother modifying those since they'll be retried anyway. if (fs[gracefulQueue][i].length > 2) { fs[gracefulQueue][i][3] = now // startTime fs[gracefulQueue][i][4] = now // lastTime } } // call retry to make sure we're actively processing the queue retry() } function retry () { // clear the timer and remove it to help prevent unintended concurrency clearTimeout(retryTimer) retryTimer = undefined if (fs[gracefulQueue].length === 0) return var elem = fs[gracefulQueue].shift() var fn = elem[0] var args = elem[1] // these items may be unset if they were added by an older graceful-fs var err = elem[2] var startTime = elem[3] var lastTime = elem[4] // if we don't have a startTime we have no way of knowing if we've waited // long enough, so go ahead and retry this item now if (startTime === undefined) { debug('RETRY', fn.name, args) fn.apply(null, args) } else if (Date.now() - startTime >= 60000) { // it's been more than 60 seconds total, bail now debug('TIMEOUT', fn.name, args) var cb = args.pop() if (typeof cb === 'function') cb.call(null, err) } else { // the amount of time between the last attempt and right now var sinceAttempt = Date.now() - lastTime // the amount of time between when we first tried, and when we last tried // rounded up to at least 1 var sinceStart = Math.max(lastTime - startTime, 1) // backoff. wait longer than the total time we've been retrying, but only // up to a maximum of 100ms var desiredDelay = Math.min(sinceStart * 1.2, 100) // it's been long enough since the last retry, do it again if (sinceAttempt >= desiredDelay) { debug('RETRY', fn.name, args) fn.apply(null, args.concat([startTime])) } else { // if we can't do this job yet, push it to the end of the queue // and let the next iteration check again fs[gracefulQueue].push(elem) } } // schedule our next run if one isn't already scheduled if (retryTimer === undefined) { retryTimer = setTimeout(retry, 0) } } ```
/content/code_sandbox/node_modules/graceful-fs/graceful-fs.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,334
```javascript module.exports = function (grunt) { grunt.initConfig({ jshint: { options: {}, default: { files: { src: ['gruntfile.js', 'src/**/*.js', '!src/libs/jsbn.js'] } }, libs: { files: { src: ['src/libs/**/*'] } } }, simplemocha: { options: { reporter: 'list' }, all: {src: ['test/**/*.js']} } }); require('jit-grunt')(grunt, { 'simplemocha': 'grunt-simple-mocha' }); grunt.registerTask('lint', ['jshint:default']); grunt.registerTask('test', ['simplemocha']); grunt.registerTask('default', ['lint', 'test']); }; ```
/content/code_sandbox/node_modules/node-rsa/gruntfile.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
174
```javascript var constants = require('constants') var origCwd = process.cwd var cwd = null var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform process.cwd = function() { if (!cwd) cwd = origCwd.call(process) return cwd } try { process.cwd() } catch (er) {} // This check is needed until node.js 12 is required if (typeof process.chdir === 'function') { var chdir = process.chdir process.chdir = function (d) { cwd = null chdir.call(process, d) } if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) } module.exports = patch function patch (fs) { // (re-)implement some things that are known busted or missing. // lchmod, broken prior to 0.6.2 // back-port the fix here. if (constants.hasOwnProperty('O_SYMLINK') && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { patchLchmod(fs) } // lutimes implementation, or no-op if (!fs.lutimes) { patchLutimes(fs) } // path_to_url // Chown should not fail on einval or eperm if non-root. // It should not fail on enosys ever, as this just indicates // that a fs doesn't support the intended operation. fs.chown = chownFix(fs.chown) fs.fchown = chownFix(fs.fchown) fs.lchown = chownFix(fs.lchown) fs.chmod = chmodFix(fs.chmod) fs.fchmod = chmodFix(fs.fchmod) fs.lchmod = chmodFix(fs.lchmod) fs.chownSync = chownFixSync(fs.chownSync) fs.fchownSync = chownFixSync(fs.fchownSync) fs.lchownSync = chownFixSync(fs.lchownSync) fs.chmodSync = chmodFixSync(fs.chmodSync) fs.fchmodSync = chmodFixSync(fs.fchmodSync) fs.lchmodSync = chmodFixSync(fs.lchmodSync) fs.stat = statFix(fs.stat) fs.fstat = statFix(fs.fstat) fs.lstat = statFix(fs.lstat) fs.statSync = statFixSync(fs.statSync) fs.fstatSync = statFixSync(fs.fstatSync) fs.lstatSync = statFixSync(fs.lstatSync) // if lchmod/lchown do not exist, then make them no-ops if (fs.chmod && !fs.lchmod) { fs.lchmod = function (path, mode, cb) { if (cb) process.nextTick(cb) } fs.lchmodSync = function () {} } if (fs.chown && !fs.lchown) { fs.lchown = function (path, uid, gid, cb) { if (cb) process.nextTick(cb) } fs.lchownSync = function () {} } // on Windows, A/V software can lock the directory, causing this // to fail with an EACCES or EPERM if the directory contains newly // created files. Try again on failure, for up to 60 seconds. // Set the timeout this long because some Windows Anti-Virus, such as Parity // bit9, may lock files for up to a minute, causing npm package install // failures. Also, take care to yield the scheduler. Windows scheduling gives // CPU to a busy looping process, which can cause the program causing the lock // contention to be starved of CPU by node, so the contention doesn't resolve. if (platform === "win32") { fs.rename = typeof fs.rename !== 'function' ? fs.rename : (function (fs$rename) { function rename (from, to, cb) { var start = Date.now() var backoff = 0; fs$rename(from, to, function CB (er) { if (er && (er.code === "EACCES" || er.code === "EPERM") && Date.now() - start < 60000) { setTimeout(function() { fs.stat(to, function (stater, st) { if (stater && stater.code === "ENOENT") fs$rename(from, to, CB); else cb(er) }) }, backoff) if (backoff < 100) backoff += 10; return; } if (cb) cb(er) }) } if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) return rename })(fs.rename) } // if read() returns EAGAIN, then just try it again. fs.read = typeof fs.read !== 'function' ? fs.read : (function (fs$read) { function read (fd, buffer, offset, length, position, callback_) { var callback if (callback_ && typeof callback_ === 'function') { var eagCounter = 0 callback = function (er, _, __) { if (er && er.code === 'EAGAIN' && eagCounter < 10) { eagCounter ++ return fs$read.call(fs, fd, buffer, offset, length, position, callback) } callback_.apply(this, arguments) } } return fs$read.call(fs, fd, buffer, offset, length, position, callback) } // This ensures `util.promisify` works as it does for native `fs.read`. if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) return read })(fs.read) fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { var eagCounter = 0 while (true) { try { return fs$readSync.call(fs, fd, buffer, offset, length, position) } catch (er) { if (er.code === 'EAGAIN' && eagCounter < 10) { eagCounter ++ continue } throw er } } }})(fs.readSync) function patchLchmod (fs) { fs.lchmod = function (path, mode, callback) { fs.open( path , constants.O_WRONLY | constants.O_SYMLINK , mode , function (err, fd) { if (err) { if (callback) callback(err) return } // prefer to return the chmod error, if one occurs, // but still try to close, and report closing errors if they occur. fs.fchmod(fd, mode, function (err) { fs.close(fd, function(err2) { if (callback) callback(err || err2) }) }) }) } fs.lchmodSync = function (path, mode) { var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) // prefer to return the chmod error, if one occurs, // but still try to close, and report closing errors if they occur. var threw = true var ret try { ret = fs.fchmodSync(fd, mode) threw = false } finally { if (threw) { try { fs.closeSync(fd) } catch (er) {} } else { fs.closeSync(fd) } } return ret } } function patchLutimes (fs) { if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { fs.lutimes = function (path, at, mt, cb) { fs.open(path, constants.O_SYMLINK, function (er, fd) { if (er) { if (cb) cb(er) return } fs.futimes(fd, at, mt, function (er) { fs.close(fd, function (er2) { if (cb) cb(er || er2) }) }) }) } fs.lutimesSync = function (path, at, mt) { var fd = fs.openSync(path, constants.O_SYMLINK) var ret var threw = true try { ret = fs.futimesSync(fd, at, mt) threw = false } finally { if (threw) { try { fs.closeSync(fd) } catch (er) {} } else { fs.closeSync(fd) } } return ret } } else if (fs.futimes) { fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } fs.lutimesSync = function () {} } } function chmodFix (orig) { if (!orig) return orig return function (target, mode, cb) { return orig.call(fs, target, mode, function (er) { if (chownErOk(er)) er = null if (cb) cb.apply(this, arguments) }) } } function chmodFixSync (orig) { if (!orig) return orig return function (target, mode) { try { return orig.call(fs, target, mode) } catch (er) { if (!chownErOk(er)) throw er } } } function chownFix (orig) { if (!orig) return orig return function (target, uid, gid, cb) { return orig.call(fs, target, uid, gid, function (er) { if (chownErOk(er)) er = null if (cb) cb.apply(this, arguments) }) } } function chownFixSync (orig) { if (!orig) return orig return function (target, uid, gid) { try { return orig.call(fs, target, uid, gid) } catch (er) { if (!chownErOk(er)) throw er } } } function statFix (orig) { if (!orig) return orig // Older versions of Node erroneously returned signed integers for // uid + gid. return function (target, options, cb) { if (typeof options === 'function') { cb = options options = null } function callback (er, stats) { if (stats) { if (stats.uid < 0) stats.uid += 0x100000000 if (stats.gid < 0) stats.gid += 0x100000000 } if (cb) cb.apply(this, arguments) } return options ? orig.call(fs, target, options, callback) : orig.call(fs, target, callback) } } function statFixSync (orig) { if (!orig) return orig // Older versions of Node erroneously returned signed integers for // uid + gid. return function (target, options) { var stats = options ? orig.call(fs, target, options) : orig.call(fs, target) if (stats) { if (stats.uid < 0) stats.uid += 0x100000000 if (stats.gid < 0) stats.gid += 0x100000000 } return stats; } } // ENOSYS means that the fs doesn't support the op. Just ignore // that, because it doesn't matter. // // if there's no getuid, or if getuid() is something other // than 0, and the error is EINVAL or EPERM, then just ignore // it. // // This specific case is a silent failure in cp, install, tar, // and most other unix tools that manage permissions. // // When running as root, or if other types of errors are // encountered, then it's strict. function chownErOk (er) { if (!er) return true if (er.code === "ENOSYS") return true var nonroot = !process.getuid || process.getuid() !== 0 if (nonroot) { if (er.code === "EINVAL" || er.code === "EPERM") return true } return false } } ```
/content/code_sandbox/node_modules/graceful-fs/polyfills.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,754
```javascript /* * Utils functions * */ var crypt = require('crypto'); /** * Break string str each maxLen symbols * @param str * @param maxLen * @returns {string} */ module.exports.linebrk = function (str, maxLen) { var res = ''; var i = 0; while (i + maxLen < str.length) { res += str.substring(i, i + maxLen) + "\n"; i += maxLen; } return res + str.substring(i, str.length); }; module.exports.detectEnvironment = function () { if (typeof(window) !== 'undefined' && window && !(process && process.title === 'node')) { return 'browser'; } return 'node'; }; /** * Trying get a 32-bit unsigned integer from the partial buffer * @param buffer * @param offset * @returns {Number} */ module.exports.get32IntFromBuffer = function (buffer, offset) { offset = offset || 0; var size = 0; if ((size = buffer.length - offset) > 0) { if (size >= 4) { return buffer.readUInt32BE(offset); } else { var res = 0; for (var i = offset + size, d = 0; i > offset; i--, d += 2) { res += buffer[i - 1] * Math.pow(16, d); } return res; } } else { return NaN; } }; module.exports._ = { isObject: function (value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); }, isString: function (value) { return typeof value == 'string' || value instanceof String; }, isNumber: function (value) { return typeof value == 'number' || !isNaN(parseFloat(value)) && isFinite(value); }, /** * Returns copy of `obj` without `removeProp` field. * @param obj * @param removeProp * @returns Object */ omit: function (obj, removeProp) { var newObj = {}; for (var prop in obj) { if (!obj.hasOwnProperty(prop) || prop === removeProp) { continue; } newObj[prop] = obj[prop]; } return newObj; } }; /** * Strips everything around the opening and closing lines, including the lines * themselves. */ module.exports.trimSurroundingText = function (data, opening, closing) { var trimStartIndex = 0; var trimEndIndex = data.length; var openingBoundaryIndex = data.indexOf(opening); if (openingBoundaryIndex >= 0) { trimStartIndex = openingBoundaryIndex + opening.length; } var closingBoundaryIndex = data.indexOf(closing, openingBoundaryIndex); if (closingBoundaryIndex >= 0) { trimEndIndex = closingBoundaryIndex; } return data.substring(trimStartIndex, trimEndIndex); } ```
/content/code_sandbox/node_modules/node-rsa/src/utils.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
664
```javascript /*! * RSA library for Node.js * * Author: rzcoder */ var constants = require('constants'); var rsa = require('./libs/rsa.js'); var crypt = require('crypto'); var ber = require('asn1').Ber; var _ = require('./utils')._; var utils = require('./utils'); var schemes = require('./schemes/schemes.js'); var formats = require('./formats/formats.js'); if (typeof constants.RSA_NO_PADDING === "undefined") { //patch for node v0.10.x, constants do not defined constants.RSA_NO_PADDING = 3; } module.exports = (function () { var SUPPORTED_HASH_ALGORITHMS = { node10: ['md4', 'md5', 'ripemd160', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'], node: ['md4', 'md5', 'ripemd160', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'], iojs: ['md4', 'md5', 'ripemd160', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'], browser: ['md5', 'ripemd160', 'sha1', 'sha256', 'sha512'] }; var DEFAULT_ENCRYPTION_SCHEME = 'pkcs1_oaep'; var DEFAULT_SIGNING_SCHEME = 'pkcs1'; var DEFAULT_EXPORT_FORMAT = 'private'; var EXPORT_FORMAT_ALIASES = { 'private': 'pkcs1-private-pem', 'private-der': 'pkcs1-private-der', 'public': 'pkcs8-public-pem', 'public-der': 'pkcs8-public-der', }; /** * @param key {string|buffer|object} Key in PEM format, or data for generate key {b: bits, e: exponent} * @constructor */ function NodeRSA(key, format, options) { if (!(this instanceof NodeRSA)) { return new NodeRSA(key, format, options); } if (_.isObject(format)) { options = format; format = undefined; } this.$options = { signingScheme: DEFAULT_SIGNING_SCHEME, signingSchemeOptions: { hash: 'sha256', saltLength: null }, encryptionScheme: DEFAULT_ENCRYPTION_SCHEME, encryptionSchemeOptions: { hash: 'sha1', label: null }, environment: utils.detectEnvironment(), rsaUtils: this }; this.keyPair = new rsa.Key(); this.$cache = {}; if (Buffer.isBuffer(key) || _.isString(key)) { this.importKey(key, format); } else if (_.isObject(key)) { this.generateKeyPair(key.b, key.e); } this.setOptions(options); } /** * Set and validate options for key instance * @param options */ NodeRSA.prototype.setOptions = function (options) { options = options || {}; if (options.environment) { this.$options.environment = options.environment; } if (options.signingScheme) { if (_.isString(options.signingScheme)) { var signingScheme = options.signingScheme.toLowerCase().split('-'); if (signingScheme.length == 1) { if (SUPPORTED_HASH_ALGORITHMS.node.indexOf(signingScheme[0]) > -1) { this.$options.signingSchemeOptions = { hash: signingScheme[0] }; this.$options.signingScheme = DEFAULT_SIGNING_SCHEME; } else { this.$options.signingScheme = signingScheme[0]; this.$options.signingSchemeOptions = { hash: null }; } } else { this.$options.signingSchemeOptions = { hash: signingScheme[1] }; this.$options.signingScheme = signingScheme[0]; } } else if (_.isObject(options.signingScheme)) { this.$options.signingScheme = options.signingScheme.scheme || DEFAULT_SIGNING_SCHEME; this.$options.signingSchemeOptions = _.omit(options.signingScheme, 'scheme'); } if (!schemes.isSignature(this.$options.signingScheme)) { throw Error('Unsupported signing scheme'); } if (this.$options.signingSchemeOptions.hash && SUPPORTED_HASH_ALGORITHMS[this.$options.environment].indexOf(this.$options.signingSchemeOptions.hash) === -1) { throw Error('Unsupported hashing algorithm for ' + this.$options.environment + ' environment'); } } if (options.encryptionScheme) { if (_.isString(options.encryptionScheme)) { this.$options.encryptionScheme = options.encryptionScheme.toLowerCase(); this.$options.encryptionSchemeOptions = {}; } else if (_.isObject(options.encryptionScheme)) { this.$options.encryptionScheme = options.encryptionScheme.scheme || DEFAULT_ENCRYPTION_SCHEME; this.$options.encryptionSchemeOptions = _.omit(options.encryptionScheme, 'scheme'); } if (!schemes.isEncryption(this.$options.encryptionScheme)) { throw Error('Unsupported encryption scheme'); } if (this.$options.encryptionSchemeOptions.hash && SUPPORTED_HASH_ALGORITHMS[this.$options.environment].indexOf(this.$options.encryptionSchemeOptions.hash) === -1) { throw Error('Unsupported hashing algorithm for ' + this.$options.environment + ' environment'); } } this.keyPair.setOptions(this.$options); }; /** * Generate private/public keys pair * * @param bits {int} length key in bits. Default 2048. * @param exp {int} public exponent. Default 65537. * @returns {NodeRSA} */ NodeRSA.prototype.generateKeyPair = function (bits, exp) { bits = bits || 2048; exp = exp || 65537; if (bits % 8 !== 0) { throw Error('Key size must be a multiple of 8.'); } this.keyPair.generate(bits, exp.toString(16)); this.$cache = {}; return this; }; /** * Importing key * @param keyData {string|buffer|Object} * @param format {string} */ NodeRSA.prototype.importKey = function (keyData, format) { if (!keyData) { throw Error("Empty key given"); } if (format) { format = EXPORT_FORMAT_ALIASES[format] || format; } if (!formats.detectAndImport(this.keyPair, keyData, format) && format === undefined) { throw Error("Key format must be specified"); } this.$cache = {}; return this; }; /** * Exporting key * @param [format] {string} */ NodeRSA.prototype.exportKey = function (format) { format = format || DEFAULT_EXPORT_FORMAT; format = EXPORT_FORMAT_ALIASES[format] || format; if (!this.$cache[format]) { this.$cache[format] = formats.detectAndExport(this.keyPair, format); } return this.$cache[format]; }; /** * Check if key pair contains private key */ NodeRSA.prototype.isPrivate = function () { return this.keyPair.isPrivate(); }; /** * Check if key pair contains public key * @param [strict] {boolean} - public key only, return false if have private exponent */ NodeRSA.prototype.isPublic = function (strict) { return this.keyPair.isPublic(strict); }; /** * Check if key pair doesn't contains any data */ NodeRSA.prototype.isEmpty = function (strict) { return !(this.keyPair.n || this.keyPair.e || this.keyPair.d); }; /** * Encrypting data method with public key * * @param buffer {string|number|object|array|Buffer} - data for encrypting. Object and array will convert to JSON string. * @param encoding {string} - optional. Encoding for output result, may be 'buffer', 'binary', 'hex' or 'base64'. Default 'buffer'. * @param source_encoding {string} - optional. Encoding for given string. Default utf8. * @returns {string|Buffer} */ NodeRSA.prototype.encrypt = function (buffer, encoding, source_encoding) { return this.$$encryptKey(false, buffer, encoding, source_encoding); }; /** * Decrypting data method with private key * * @param buffer {Buffer} - buffer for decrypting * @param encoding - encoding for result string, can also take 'json' or 'buffer' for the automatic conversion of this type * @returns {Buffer|object|string} */ NodeRSA.prototype.decrypt = function (buffer, encoding) { return this.$$decryptKey(false, buffer, encoding); }; /** * Encrypting data method with private key * * Parameters same as `encrypt` method */ NodeRSA.prototype.encryptPrivate = function (buffer, encoding, source_encoding) { return this.$$encryptKey(true, buffer, encoding, source_encoding); }; /** * Decrypting data method with public key * * Parameters same as `decrypt` method */ NodeRSA.prototype.decryptPublic = function (buffer, encoding) { return this.$$decryptKey(true, buffer, encoding); }; /** * Encrypting data method with custom key */ NodeRSA.prototype.$$encryptKey = function (usePrivate, buffer, encoding, source_encoding) { try { var res = this.keyPair.encrypt(this.$getDataForEncrypt(buffer, source_encoding), usePrivate); if (encoding == 'buffer' || !encoding) { return res; } else { return res.toString(encoding); } } catch (e) { throw Error('Error during encryption. Original error: ' + e); } }; /** * Decrypting data method with custom key */ NodeRSA.prototype.$$decryptKey = function (usePublic, buffer, encoding) { try { buffer = _.isString(buffer) ? Buffer.from(buffer, 'base64') : buffer; var res = this.keyPair.decrypt(buffer, usePublic); if (res === null) { throw Error('Key decrypt method returns null.'); } return this.$getDecryptedData(res, encoding); } catch (e) { throw Error('Error during decryption (probably incorrect key). Original error: ' + e); } }; /** * Signing data * * @param buffer {string|number|object|array|Buffer} - data for signing. Object and array will convert to JSON string. * @param encoding {string} - optional. Encoding for output result, may be 'buffer', 'binary', 'hex' or 'base64'. Default 'buffer'. * @param source_encoding {string} - optional. Encoding for given string. Default utf8. * @returns {string|Buffer} */ NodeRSA.prototype.sign = function (buffer, encoding, source_encoding) { if (!this.isPrivate()) { throw Error("This is not private key"); } var res = this.keyPair.sign(this.$getDataForEncrypt(buffer, source_encoding)); if (encoding && encoding != 'buffer') { res = res.toString(encoding); } return res; }; /** * Verifying signed data * * @param buffer - signed data * @param signature * @param source_encoding {string} - optional. Encoding for given string. Default utf8. * @param signature_encoding - optional. Encoding of given signature. May be 'buffer', 'binary', 'hex' or 'base64'. Default 'buffer'. * @returns {*} */ NodeRSA.prototype.verify = function (buffer, signature, source_encoding, signature_encoding) { if (!this.isPublic()) { throw Error("This is not public key"); } signature_encoding = (!signature_encoding || signature_encoding == 'buffer' ? null : signature_encoding); return this.keyPair.verify(this.$getDataForEncrypt(buffer, source_encoding), signature, signature_encoding); }; /** * Returns key size in bits * @returns {int} */ NodeRSA.prototype.getKeySize = function () { return this.keyPair.keySize; }; /** * Returns max message length in bytes (for 1 chunk) depending on current encryption scheme * @returns {int} */ NodeRSA.prototype.getMaxMessageSize = function () { return this.keyPair.maxMessageLength; }; /** * Preparing given data for encrypting/signing. Just make new/return Buffer object. * * @param buffer {string|number|object|array|Buffer} - data for encrypting. Object and array will convert to JSON string. * @param encoding {string} - optional. Encoding for given string. Default utf8. * @returns {Buffer} */ NodeRSA.prototype.$getDataForEncrypt = function (buffer, encoding) { if (_.isString(buffer) || _.isNumber(buffer)) { return Buffer.from('' + buffer, encoding || 'utf8'); } else if (Buffer.isBuffer(buffer)) { return buffer; } else if (_.isObject(buffer)) { return Buffer.from(JSON.stringify(buffer)); } else { throw Error("Unexpected data type"); } }; /** * * @param buffer {Buffer} - decrypted data. * @param encoding - optional. Encoding for result output. May be 'buffer', 'json' or any of Node.js Buffer supported encoding. * @returns {*} */ NodeRSA.prototype.$getDecryptedData = function (buffer, encoding) { encoding = encoding || 'buffer'; if (encoding == 'buffer') { return buffer; } else if (encoding == 'json') { return JSON.parse(buffer.toString()); } else { return buffer.toString(encoding); } }; return NodeRSA; })(); ```
/content/code_sandbox/node_modules/node-rsa/src/NodeRSA.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,062
```javascript /* * RSA Encryption / Decryption with PKCS1 v2 Padding. * * All Rights Reserved. * * 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" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * In addition, the following condition applies: * * All redistributions must retain an intact copy of this copyright notice * and disclaimer. */ /* * Node.js adaptation * long message support implementation * signing/verifying * * 2014 rzcoder */ var _ = require('../utils')._; var crypt = require('crypto'); var BigInteger = require('./jsbn.js'); var utils = require('../utils.js'); var schemes = require('../schemes/schemes.js'); var encryptEngines = require('../encryptEngines/encryptEngines.js'); exports.BigInteger = BigInteger; module.exports.Key = (function () { /** * RSA key constructor * * n - modulus * e - publicExponent * d - privateExponent * p - prime1 * q - prime2 * dmp1 - exponent1 -- d mod (p1) * dmq1 - exponent2 -- d mod (q-1) * coeff - coefficient -- (inverse of q) mod p */ function RSAKey() { this.n = null; this.e = 0; this.d = null; this.p = null; this.q = null; this.dmp1 = null; this.dmq1 = null; this.coeff = null; } RSAKey.prototype.setOptions = function (options) { var signingSchemeProvider = schemes[options.signingScheme]; var encryptionSchemeProvider = schemes[options.encryptionScheme]; if (signingSchemeProvider === encryptionSchemeProvider) { this.signingScheme = this.encryptionScheme = encryptionSchemeProvider.makeScheme(this, options); } else { this.encryptionScheme = encryptionSchemeProvider.makeScheme(this, options); this.signingScheme = signingSchemeProvider.makeScheme(this, options); } this.encryptEngine = encryptEngines.getEngine(this, options); }; /** * Generate a new random private key B bits long, using public expt E * @param B * @param E */ RSAKey.prototype.generate = function (B, E) { var qs = B >> 1; this.e = parseInt(E, 16); var ee = new BigInteger(E, 16); while (true) { while (true) { this.p = new BigInteger(B - qs, 1); if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) === 0 && this.p.isProbablePrime(10)) break; } while (true) { this.q = new BigInteger(qs, 1); if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) === 0 && this.q.isProbablePrime(10)) break; } if (this.p.compareTo(this.q) <= 0) { var t = this.p; this.p = this.q; this.q = t; } var p1 = this.p.subtract(BigInteger.ONE); var q1 = this.q.subtract(BigInteger.ONE); var phi = p1.multiply(q1); if (phi.gcd(ee).compareTo(BigInteger.ONE) === 0) { this.n = this.p.multiply(this.q); if (this.n.bitLength() < B) { continue; } this.d = ee.modInverse(phi); this.dmp1 = this.d.mod(p1); this.dmq1 = this.d.mod(q1); this.coeff = this.q.modInverse(this.p); break; } } this.$$recalculateCache(); }; /** * Set the private key fields N, e, d and CRT params from buffers * * @param N * @param E * @param D * @param P * @param Q * @param DP * @param DQ * @param C */ RSAKey.prototype.setPrivate = function (N, E, D, P, Q, DP, DQ, C) { if (N && E && D && N.length > 0 && (_.isNumber(E) || E.length > 0) && D.length > 0) { this.n = new BigInteger(N); this.e = _.isNumber(E) ? E : utils.get32IntFromBuffer(E, 0); this.d = new BigInteger(D); if (P && Q && DP && DQ && C) { this.p = new BigInteger(P); this.q = new BigInteger(Q); this.dmp1 = new BigInteger(DP); this.dmq1 = new BigInteger(DQ); this.coeff = new BigInteger(C); } else { // TODO: re-calculate any missing CRT params } this.$$recalculateCache(); } else { throw Error("Invalid RSA private key"); } }; /** * Set the public key fields N and e from hex strings * @param N * @param E */ RSAKey.prototype.setPublic = function (N, E) { if (N && E && N.length > 0 && (_.isNumber(E) || E.length > 0)) { this.n = new BigInteger(N); this.e = _.isNumber(E) ? E : utils.get32IntFromBuffer(E, 0); this.$$recalculateCache(); } else { throw Error("Invalid RSA public key"); } }; /** * private * Perform raw private operation on "x": return x^d (mod n) * * @param x * @returns {*} */ RSAKey.prototype.$doPrivate = function (x) { if (this.p || this.q) { return x.modPow(this.d, this.n); } // TODO: re-calculate any missing CRT params var xp = x.mod(this.p).modPow(this.dmp1, this.p); var xq = x.mod(this.q).modPow(this.dmq1, this.q); while (xp.compareTo(xq) < 0) { xp = xp.add(this.p); } return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq); }; /** * private * Perform raw public operation on "x": return x^e (mod n) * * @param x * @returns {*} */ RSAKey.prototype.$doPublic = function (x) { return x.modPowInt(this.e, this.n); }; /** * Return the PKCS#1 RSA encryption of buffer * @param buffer {Buffer} * @returns {Buffer} */ RSAKey.prototype.encrypt = function (buffer, usePrivate) { var buffers = []; var results = []; var bufferSize = buffer.length; var buffersCount = Math.ceil(bufferSize / this.maxMessageLength) || 1; // total buffers count for encrypt var dividedSize = Math.ceil(bufferSize / buffersCount || 1); // each buffer size if (buffersCount == 1) { buffers.push(buffer); } else { for (var bufNum = 0; bufNum < buffersCount; bufNum++) { buffers.push(buffer.slice(bufNum * dividedSize, (bufNum + 1) * dividedSize)); } } for (var i = 0; i < buffers.length; i++) { results.push(this.encryptEngine.encrypt(buffers[i], usePrivate)); } return Buffer.concat(results); }; /** * Return the PKCS#1 RSA decryption of buffer * @param buffer {Buffer} * @returns {Buffer} */ RSAKey.prototype.decrypt = function (buffer, usePublic) { if (buffer.length % this.encryptedDataLength > 0) { throw Error('Incorrect data or key'); } var result = []; var offset = 0; var length = 0; var buffersCount = buffer.length / this.encryptedDataLength; for (var i = 0; i < buffersCount; i++) { offset = i * this.encryptedDataLength; length = offset + this.encryptedDataLength; result.push(this.encryptEngine.decrypt(buffer.slice(offset, Math.min(length, buffer.length)), usePublic)); } return Buffer.concat(result); }; RSAKey.prototype.sign = function (buffer) { return this.signingScheme.sign.apply(this.signingScheme, arguments); }; RSAKey.prototype.verify = function (buffer, signature, signature_encoding) { return this.signingScheme.verify.apply(this.signingScheme, arguments); }; /** * Check if key pair contains private key */ RSAKey.prototype.isPrivate = function () { return this.n && this.e && this.d || false; }; /** * Check if key pair contains public key * @param strict {boolean} - public key only, return false if have private exponent */ RSAKey.prototype.isPublic = function (strict) { return this.n && this.e && !(strict && this.d) || false; }; Object.defineProperty(RSAKey.prototype, 'keySize', { get: function () { return this.cache.keyBitLength; } }); Object.defineProperty(RSAKey.prototype, 'encryptedDataLength', { get: function () { return this.cache.keyByteLength; } }); Object.defineProperty(RSAKey.prototype, 'maxMessageLength', { get: function () { return this.encryptionScheme.maxMessageLength(); } }); /** * Caching key data */ RSAKey.prototype.$$recalculateCache = function () { this.cache = this.cache || {}; // Bit & byte length this.cache.keyBitLength = this.n.bitLength(); this.cache.keyByteLength = (this.cache.keyBitLength + 6) >> 3; }; return RSAKey; })(); ```
/content/code_sandbox/node_modules/node-rsa/src/libs/rsa.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,414
```javascript /** * PKCS_OAEP signature scheme */ var BigInteger = require('../libs/jsbn'); var crypt = require('crypto'); module.exports = { isEncryption: true, isSignature: false }; module.exports.digestLength = { md4: 16, md5: 16, ripemd160: 20, rmd160: 20, sha1: 20, sha224: 28, sha256: 32, sha384: 48, sha512: 64 }; var DEFAULT_HASH_FUNCTION = 'sha1'; /* * OAEP Mask Generation Function 1 * Generates a buffer full of pseudorandom bytes given seed and maskLength. * Giving the same seed, maskLength, and hashFunction will result in the same exact byte values in the buffer. * * path_to_url#appendix-B.2.1 * * Parameters: * seed [Buffer] The pseudo random seed for this function * maskLength [int] The length of the output * hashFunction [String] The hashing function to use. Will accept any valid crypto hash. Default "sha1" * Supports "sha1" and "sha256". * To add another algorythm the algorythem must be accepted by crypto.createHash, and then the length of the output of the hash function (the digest) must be added to the digestLength object below. * Most RSA implementations will be expecting sha1 */ module.exports.eme_oaep_mgf1 = function (seed, maskLength, hashFunction) { hashFunction = hashFunction || DEFAULT_HASH_FUNCTION; var hLen = module.exports.digestLength[hashFunction]; var count = Math.ceil(maskLength / hLen); var T = Buffer.alloc(hLen * count); var c = Buffer.alloc(4); for (var i = 0; i < count; ++i) { var hash = crypt.createHash(hashFunction); hash.update(seed); c.writeUInt32BE(i, 0); hash.update(c); hash.digest().copy(T, i * hLen); } return T.slice(0, maskLength); }; module.exports.makeScheme = function (key, options) { function Scheme(key, options) { this.key = key; this.options = options; } Scheme.prototype.maxMessageLength = function () { return this.key.encryptedDataLength - 2 * module.exports.digestLength[this.options.encryptionSchemeOptions.hash || DEFAULT_HASH_FUNCTION] - 2; }; /** * Pad input * alg: PKCS1_OAEP * * path_to_url#section-7.1.1 */ Scheme.prototype.encPad = function (buffer) { var hash = this.options.encryptionSchemeOptions.hash || DEFAULT_HASH_FUNCTION; var mgf = this.options.encryptionSchemeOptions.mgf || module.exports.eme_oaep_mgf1; var label = this.options.encryptionSchemeOptions.label || Buffer.alloc(0); var emLen = this.key.encryptedDataLength; var hLen = module.exports.digestLength[hash]; // Make sure we can put message into an encoded message of emLen bytes if (buffer.length > emLen - 2 * hLen - 2) { throw new Error("Message is too long to encode into an encoded message with a length of " + emLen + " bytes, increase" + "emLen to fix this error (minimum value for given parameters and options: " + (emLen - 2 * hLen - 2) + ")"); } var lHash = crypt.createHash(hash); lHash.update(label); lHash = lHash.digest(); var PS = Buffer.alloc(emLen - buffer.length - 2 * hLen - 1); // Padding "String" PS.fill(0); // Fill the buffer with octets of 0 PS[PS.length - 1] = 1; var DB = Buffer.concat([lHash, PS, buffer]); var seed = crypt.randomBytes(hLen); // mask = dbMask var mask = mgf(seed, DB.length, hash); // XOR DB and dbMask together. for (var i = 0; i < DB.length; i++) { DB[i] ^= mask[i]; } // DB = maskedDB // mask = seedMask mask = mgf(DB, hLen, hash); // XOR seed and seedMask together. for (i = 0; i < seed.length; i++) { seed[i] ^= mask[i]; } // seed = maskedSeed var em = Buffer.alloc(1 + seed.length + DB.length); em[0] = 0; seed.copy(em, 1); DB.copy(em, 1 + seed.length); return em; }; /** * Unpad input * alg: PKCS1_OAEP * * Note: This method works within the buffer given and modifies the values. It also returns a slice of the EM as the return Message. * If the implementation requires that the EM parameter be unmodified then the implementation should pass in a clone of the EM buffer. * * path_to_url#section-7.1.2 */ Scheme.prototype.encUnPad = function (buffer) { var hash = this.options.encryptionSchemeOptions.hash || DEFAULT_HASH_FUNCTION; var mgf = this.options.encryptionSchemeOptions.mgf || module.exports.eme_oaep_mgf1; var label = this.options.encryptionSchemeOptions.label || Buffer.alloc(0); var hLen = module.exports.digestLength[hash]; // Check to see if buffer is a properly encoded OAEP message if (buffer.length < 2 * hLen + 2) { throw new Error("Error decoding message, the supplied message is not long enough to be a valid OAEP encoded message"); } var seed = buffer.slice(1, hLen + 1); // seed = maskedSeed var DB = buffer.slice(1 + hLen); // DB = maskedDB var mask = mgf(DB, hLen, hash); // seedMask // XOR maskedSeed and seedMask together to get the original seed. for (var i = 0; i < seed.length; i++) { seed[i] ^= mask[i]; } mask = mgf(seed, DB.length, hash); // dbMask // XOR DB and dbMask together to get the original data block. for (i = 0; i < DB.length; i++) { DB[i] ^= mask[i]; } var lHash = crypt.createHash(hash); lHash.update(label); lHash = lHash.digest(); var lHashEM = DB.slice(0, hLen); if (lHashEM.toString("hex") != lHash.toString("hex")) { throw new Error("Error decoding message, the lHash calculated from the label provided and the lHash in the encrypted data do not match."); } // Filter out padding i = hLen; while (DB[i++] === 0 && i < DB.length); if (DB[i - 1] != 1) { throw new Error("Error decoding message, there is no padding message separator byte"); } return DB.slice(i); // Message }; return new Scheme(key, options); }; ```
/content/code_sandbox/node_modules/node-rsa/src/schemes/oaep.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,613
```javascript /** * PSS signature scheme */ var BigInteger = require('../libs/jsbn'); var crypt = require('crypto'); module.exports = { isEncryption: false, isSignature: true }; var DEFAULT_HASH_FUNCTION = 'sha1'; var DEFAULT_SALT_LENGTH = 20; module.exports.makeScheme = function (key, options) { var OAEP = require('./schemes').pkcs1_oaep; /** * @param key * @param options * options [Object] An object that contains the following keys that specify certain options for encoding. * >signingSchemeOptions * >hash [String] Hash function to use when encoding and generating masks. Must be a string accepted by node's crypto.createHash function. (default = "sha1") * >mgf [function] The mask generation function to use when encoding. (default = mgf1SHA1) * >sLen [uint] The length of the salt to generate. (default = 20) * @constructor */ function Scheme(key, options) { this.key = key; this.options = options; } Scheme.prototype.sign = function (buffer) { var mHash = crypt.createHash(this.options.signingSchemeOptions.hash || DEFAULT_HASH_FUNCTION); mHash.update(buffer); var encoded = this.emsa_pss_encode(mHash.digest(), this.key.keySize - 1); return this.key.$doPrivate(new BigInteger(encoded)).toBuffer(this.key.encryptedDataLength); }; Scheme.prototype.verify = function (buffer, signature, signature_encoding) { if (signature_encoding) { signature = Buffer.from(signature, signature_encoding); } signature = new BigInteger(signature); var emLen = Math.ceil((this.key.keySize - 1) / 8); var m = this.key.$doPublic(signature).toBuffer(emLen); var mHash = crypt.createHash(this.options.signingSchemeOptions.hash || DEFAULT_HASH_FUNCTION); mHash.update(buffer); return this.emsa_pss_verify(mHash.digest(), m, this.key.keySize - 1); }; /* * path_to_url#section-9.1.1 * * mHash [Buffer] Hashed message to encode * emBits [uint] Maximum length of output in bits. Must be at least 8hLen + 8sLen + 9 (hLen = Hash digest length in bytes | sLen = length of salt in bytes) * @returns {Buffer} The encoded message */ Scheme.prototype.emsa_pss_encode = function (mHash, emBits) { var hash = this.options.signingSchemeOptions.hash || DEFAULT_HASH_FUNCTION; var mgf = this.options.signingSchemeOptions.mgf || OAEP.eme_oaep_mgf1; var sLen = this.options.signingSchemeOptions.saltLength || DEFAULT_SALT_LENGTH; var hLen = OAEP.digestLength[hash]; var emLen = Math.ceil(emBits / 8); if (emLen < hLen + sLen + 2) { throw new Error("Output length passed to emBits(" + emBits + ") is too small for the options " + "specified(" + hash + ", " + sLen + "). To fix this issue increase the value of emBits. (minimum size: " + (8 * hLen + 8 * sLen + 9) + ")" ); } var salt = crypt.randomBytes(sLen); var Mapostrophe = Buffer.alloc(8 + hLen + sLen); Mapostrophe.fill(0, 0, 8); mHash.copy(Mapostrophe, 8); salt.copy(Mapostrophe, 8 + mHash.length); var H = crypt.createHash(hash); H.update(Mapostrophe); H = H.digest(); var PS = Buffer.alloc(emLen - salt.length - hLen - 2); PS.fill(0); var DB = Buffer.alloc(PS.length + 1 + salt.length); PS.copy(DB); DB[PS.length] = 0x01; salt.copy(DB, PS.length + 1); var dbMask = mgf(H, DB.length, hash); // XOR DB and dbMask together var maskedDB = Buffer.alloc(DB.length); for (var i = 0; i < dbMask.length; i++) { maskedDB[i] = DB[i] ^ dbMask[i]; } var bits = 8 * emLen - emBits; var mask = 255 ^ (255 >> 8 - bits << 8 - bits); maskedDB[0] = maskedDB[0] & mask; var EM = Buffer.alloc(maskedDB.length + H.length + 1); maskedDB.copy(EM, 0); H.copy(EM, maskedDB.length); EM[EM.length - 1] = 0xbc; return EM; }; /* * path_to_url#section-9.1.2 * * mHash [Buffer] Hashed message * EM [Buffer] Signature * emBits [uint] Length of EM in bits. Must be at least 8hLen + 8sLen + 9 to be a valid signature. (hLen = Hash digest length in bytes | sLen = length of salt in bytes) * @returns {Boolean} True if signature(EM) matches message(M) */ Scheme.prototype.emsa_pss_verify = function (mHash, EM, emBits) { var hash = this.options.signingSchemeOptions.hash || DEFAULT_HASH_FUNCTION; var mgf = this.options.signingSchemeOptions.mgf || OAEP.eme_oaep_mgf1; var sLen = this.options.signingSchemeOptions.saltLength || DEFAULT_SALT_LENGTH; var hLen = OAEP.digestLength[hash]; var emLen = Math.ceil(emBits / 8); if (emLen < hLen + sLen + 2 || EM[EM.length - 1] != 0xbc) { return false; } var DB = Buffer.alloc(emLen - hLen - 1); EM.copy(DB, 0, 0, emLen - hLen - 1); var mask = 0; for (var i = 0, bits = 8 * emLen - emBits; i < bits; i++) { mask |= 1 << (7 - i); } if ((DB[0] & mask) !== 0) { return false; } var H = EM.slice(emLen - hLen - 1, emLen - 1); var dbMask = mgf(H, DB.length, hash); // Unmask DB for (i = 0; i < DB.length; i++) { DB[i] ^= dbMask[i]; } bits = 8 * emLen - emBits; mask = 255 ^ (255 >> 8 - bits << 8 - bits); DB[0] = DB[0] & mask; // Filter out padding for (i = 0; DB[i] === 0 && i < DB.length; i++); if (DB[i] != 1) { return false; } var salt = DB.slice(DB.length - sLen); var Mapostrophe = Buffer.alloc(8 + hLen + sLen); Mapostrophe.fill(0, 0, 8); mHash.copy(Mapostrophe, 8); salt.copy(Mapostrophe, 8 + mHash.length); var Hapostrophe = crypt.createHash(hash); Hapostrophe.update(Mapostrophe); Hapostrophe = Hapostrophe.digest(); return H.toString("hex") === Hapostrophe.toString("hex"); }; return new Scheme(key, options); }; ```
/content/code_sandbox/node_modules/node-rsa/src/schemes/pss.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,734
```javascript module.exports = { pkcs1: require('./pkcs1'), pkcs1_oaep: require('./oaep'), pss: require('./pss'), /** * Check if scheme has padding methods * @param scheme {string} * @returns {Boolean} */ isEncryption: function (scheme) { return module.exports[scheme] && module.exports[scheme].isEncryption; }, /** * Check if scheme has sign/verify methods * @param scheme {string} * @returns {Boolean} */ isSignature: function (scheme) { return module.exports[scheme] && module.exports[scheme].isSignature; } }; ```
/content/code_sandbox/node_modules/node-rsa/src/schemes/schemes.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
151
```javascript /** * PKCS1 padding and signature scheme */ var BigInteger = require('../libs/jsbn'); var crypt = require('crypto'); var constants = require('constants'); var SIGN_INFO_HEAD = { md2: Buffer.from('3020300c06082a864886f70d020205000410', 'hex'), md5: Buffer.from('3020300c06082a864886f70d020505000410', 'hex'), sha1: Buffer.from('3021300906052b0e03021a05000414', 'hex'), sha224: Buffer.from('302d300d06096086480165030402040500041c', 'hex'), sha256: Buffer.from('3031300d060960864801650304020105000420', 'hex'), sha384: Buffer.from('3041300d060960864801650304020205000430', 'hex'), sha512: Buffer.from('3051300d060960864801650304020305000440', 'hex'), ripemd160: Buffer.from('3021300906052b2403020105000414', 'hex'), rmd160: Buffer.from('3021300906052b2403020105000414', 'hex') }; var SIGN_ALG_TO_HASH_ALIASES = { 'ripemd160': 'rmd160' }; var DEFAULT_HASH_FUNCTION = 'sha256'; module.exports = { isEncryption: true, isSignature: true }; module.exports.makeScheme = function (key, options) { function Scheme(key, options) { this.key = key; this.options = options; } Scheme.prototype.maxMessageLength = function () { if (this.options.encryptionSchemeOptions && this.options.encryptionSchemeOptions.padding == constants.RSA_NO_PADDING) { return this.key.encryptedDataLength; } return this.key.encryptedDataLength - 11; }; /** * Pad input Buffer to encryptedDataLength bytes, and return Buffer.from * alg: PKCS#1 * @param buffer * @returns {Buffer} */ Scheme.prototype.encPad = function (buffer, options) { options = options || {}; var filled; if (buffer.length > this.key.maxMessageLength) { throw new Error("Message too long for RSA (n=" + this.key.encryptedDataLength + ", l=" + buffer.length + ")"); } if (this.options.encryptionSchemeOptions && this.options.encryptionSchemeOptions.padding == constants.RSA_NO_PADDING) { //RSA_NO_PADDING treated like JAVA left pad with zero character filled = Buffer.alloc(this.key.maxMessageLength - buffer.length); filled.fill(0); return Buffer.concat([filled, buffer]); } /* Type 1: zeros padding for private key encrypt */ if (options.type === 1) { filled = Buffer.alloc(this.key.encryptedDataLength - buffer.length - 1); filled.fill(0xff, 0, filled.length - 1); filled[0] = 1; filled[filled.length - 1] = 0; return Buffer.concat([filled, buffer]); } else { /* random padding for public key encrypt */ filled = Buffer.alloc(this.key.encryptedDataLength - buffer.length); filled[0] = 0; filled[1] = 2; var rand = crypt.randomBytes(filled.length - 3); for (var i = 0; i < rand.length; i++) { var r = rand[i]; while (r === 0) { // non-zero only r = crypt.randomBytes(1)[0]; } filled[i + 2] = r; } filled[filled.length - 1] = 0; return Buffer.concat([filled, buffer]); } }; /** * Unpad input Buffer and, if valid, return the Buffer object * alg: PKCS#1 (type 2, random) * @param buffer * @returns {Buffer} */ Scheme.prototype.encUnPad = function (buffer, options) { options = options || {}; var i = 0; if (this.options.encryptionSchemeOptions && this.options.encryptionSchemeOptions.padding == constants.RSA_NO_PADDING) { //RSA_NO_PADDING treated like JAVA left pad with zero character var unPad; if (typeof buffer.lastIndexOf == "function") { //patch for old node version unPad = buffer.slice(buffer.lastIndexOf('\0') + 1, buffer.length); } else { unPad = buffer.slice(String.prototype.lastIndexOf.call(buffer, '\0') + 1, buffer.length); } return unPad; } if (buffer.length < 4) { return null; } /* Type 1: zeros padding for private key decrypt */ if (options.type === 1) { if (buffer[0] !== 0 && buffer[1] !== 1) { return null; } i = 3; while (buffer[i] !== 0) { if (buffer[i] != 0xFF || ++i >= buffer.length) { return null; } } } else { /* random padding for public key decrypt */ if (buffer[0] !== 0 && buffer[1] !== 2) { return null; } i = 3; while (buffer[i] !== 0) { if (++i >= buffer.length) { return null; } } } return buffer.slice(i + 1, buffer.length); }; Scheme.prototype.sign = function (buffer) { var hashAlgorithm = this.options.signingSchemeOptions.hash || DEFAULT_HASH_FUNCTION; if (this.options.environment === 'browser') { hashAlgorithm = SIGN_ALG_TO_HASH_ALIASES[hashAlgorithm] || hashAlgorithm; var hasher = crypt.createHash(hashAlgorithm); hasher.update(buffer); var hash = this.pkcs1pad(hasher.digest(), hashAlgorithm); var res = this.key.$doPrivate(new BigInteger(hash)).toBuffer(this.key.encryptedDataLength); return res; } else { var signer = crypt.createSign('RSA-' + hashAlgorithm.toUpperCase()); signer.update(buffer); return signer.sign(this.options.rsaUtils.exportKey('private')); } }; Scheme.prototype.verify = function (buffer, signature, signature_encoding) { if (this.options.encryptionSchemeOptions && this.options.encryptionSchemeOptions.padding == constants.RSA_NO_PADDING) { //RSA_NO_PADDING has no verify data return false; } var hashAlgorithm = this.options.signingSchemeOptions.hash || DEFAULT_HASH_FUNCTION; if (this.options.environment === 'browser') { hashAlgorithm = SIGN_ALG_TO_HASH_ALIASES[hashAlgorithm] || hashAlgorithm; if (signature_encoding) { signature = Buffer.from(signature, signature_encoding); } var hasher = crypt.createHash(hashAlgorithm); hasher.update(buffer); var hash = this.pkcs1pad(hasher.digest(), hashAlgorithm); var m = this.key.$doPublic(new BigInteger(signature)); return m.toBuffer().toString('hex') == hash.toString('hex'); } else { var verifier = crypt.createVerify('RSA-' + hashAlgorithm.toUpperCase()); verifier.update(buffer); return verifier.verify(this.options.rsaUtils.exportKey('public'), signature, signature_encoding); } }; /** * PKCS#1 zero pad input buffer to max data length * @param hashBuf * @param hashAlgorithm * @returns {*} */ Scheme.prototype.pkcs0pad = function (buffer) { var filled = Buffer.alloc(this.key.maxMessageLength - buffer.length); filled.fill(0); return Buffer.concat([filled, buffer]); }; Scheme.prototype.pkcs0unpad = function (buffer) { var unPad; if (typeof buffer.lastIndexOf == "function") { //patch for old node version unPad = buffer.slice(buffer.lastIndexOf('\0') + 1, buffer.length); } else { unPad = buffer.slice(String.prototype.lastIndexOf.call(buffer, '\0') + 1, buffer.length); } return unPad; }; /** * PKCS#1 pad input buffer to max data length * @param hashBuf * @param hashAlgorithm * @returns {*} */ Scheme.prototype.pkcs1pad = function (hashBuf, hashAlgorithm) { var digest = SIGN_INFO_HEAD[hashAlgorithm]; if (!digest) { throw Error('Unsupported hash algorithm'); } var data = Buffer.concat([digest, hashBuf]); if (data.length + 10 > this.key.encryptedDataLength) { throw Error('Key is too short for signing algorithm (' + hashAlgorithm + ')'); } var filled = Buffer.alloc(this.key.encryptedDataLength - data.length - 1); filled.fill(0xff, 0, filled.length - 1); filled[0] = 1; filled[filled.length - 1] = 0; var res = Buffer.concat([filled, data]); return res; }; return new Scheme(key, options); }; ```
/content/code_sandbox/node_modules/node-rsa/src/schemes/pkcs1.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,991
```javascript var crypto = require('crypto'); var constants = require('constants'); var schemes = require('../schemes/schemes.js'); module.exports = function (keyPair, options) { var pkcs1Scheme = schemes.pkcs1.makeScheme(keyPair, options); return { encrypt: function (buffer, usePrivate) { var padding; if (usePrivate) { padding = constants.RSA_PKCS1_PADDING; if (options.encryptionSchemeOptions && options.encryptionSchemeOptions.padding) { padding = options.encryptionSchemeOptions.padding; } return crypto.privateEncrypt({ key: options.rsaUtils.exportKey('private'), padding: padding }, buffer); } else { padding = constants.RSA_PKCS1_OAEP_PADDING; if (options.encryptionScheme === 'pkcs1') { padding = constants.RSA_PKCS1_PADDING; } if (options.encryptionSchemeOptions && options.encryptionSchemeOptions.padding) { padding = options.encryptionSchemeOptions.padding; } var data = buffer; if (padding === constants.RSA_NO_PADDING) { data = pkcs1Scheme.pkcs0pad(buffer); } return crypto.publicEncrypt({ key: options.rsaUtils.exportKey('public'), padding: padding }, data); } }, decrypt: function (buffer, usePublic) { var padding; if (usePublic) { padding = constants.RSA_PKCS1_PADDING; if (options.encryptionSchemeOptions && options.encryptionSchemeOptions.padding) { padding = options.encryptionSchemeOptions.padding; } return crypto.publicDecrypt({ key: options.rsaUtils.exportKey('public'), padding: padding }, buffer); } else { padding = constants.RSA_PKCS1_OAEP_PADDING; if (options.encryptionScheme === 'pkcs1') { padding = constants.RSA_PKCS1_PADDING; } if (options.encryptionSchemeOptions && options.encryptionSchemeOptions.padding) { padding = options.encryptionSchemeOptions.padding; } var res = crypto.privateDecrypt({ key: options.rsaUtils.exportKey('private'), padding: padding }, buffer); if (padding === constants.RSA_NO_PADDING) { return pkcs1Scheme.pkcs0unpad(res); } return res; } } }; }; ```
/content/code_sandbox/node_modules/node-rsa/src/encryptEngines/io.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
515
```javascript var BigInteger = require('../libs/jsbn.js'); var schemes = require('../schemes/schemes.js'); module.exports = function (keyPair, options) { var pkcs1Scheme = schemes.pkcs1.makeScheme(keyPair, options); return { encrypt: function (buffer, usePrivate) { var m, c; if (usePrivate) { /* Type 1: zeros padding for private key encrypt */ m = new BigInteger(pkcs1Scheme.encPad(buffer, {type: 1})); c = keyPair.$doPrivate(m); } else { m = new BigInteger(keyPair.encryptionScheme.encPad(buffer)); c = keyPair.$doPublic(m); } return c.toBuffer(keyPair.encryptedDataLength); }, decrypt: function (buffer, usePublic) { var m, c = new BigInteger(buffer); if (usePublic) { m = keyPair.$doPublic(c); /* Type 1: zeros padding for private key decrypt */ return pkcs1Scheme.encUnPad(m.toBuffer(keyPair.encryptedDataLength), {type: 1}); } else { m = keyPair.$doPrivate(c); return keyPair.encryptionScheme.encUnPad(m.toBuffer(keyPair.encryptedDataLength)); } } }; }; ```
/content/code_sandbox/node_modules/node-rsa/src/encryptEngines/js.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
281
```javascript var crypt = require('crypto'); module.exports = { getEngine: function (keyPair, options) { var engine = require('./js.js'); if (options.environment === 'node') { if (typeof crypt.publicEncrypt === 'function' && typeof crypt.privateDecrypt === 'function') { if (typeof crypt.privateEncrypt === 'function' && typeof crypt.publicDecrypt === 'function') { engine = require('./io.js'); } else { engine = require('./node12.js'); } } } return engine(keyPair, options); } }; ```
/content/code_sandbox/node_modules/node-rsa/src/encryptEngines/encryptEngines.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
123
```javascript /* * Basic JavaScript BN library - subset useful for RSA encryption. * * All Rights Reserved. * * 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" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * In addition, the following condition applies: * * All redistributions must retain an intact copy of this copyright notice * and disclaimer. */ /* * Added Node.js Buffers support * 2014 rzcoder */ var crypt = require('crypto'); var _ = require('../utils')._; // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary & 0xffffff) == 0xefcafe); // (public) Constructor function BigInteger(a, b) { if (a != null) { if ("number" == typeof a) { this.fromNumber(a, b); } else if (Buffer.isBuffer(a)) { this.fromBuffer(a); } else if (b == null && "string" != typeof a) { this.fromByteArray(a); } else { this.fromString(a, b); } } } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i, x, w, j, c, n) { while (--n >= 0) { var v = x * this[i++] + w[j] + c; c = Math.floor(v / 0x4000000); w[j++] = v & 0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i, x, w, j, c, n) { var xl = x & 0x7fff, xh = x >> 15; while (--n >= 0) { var l = this[i] & 0x7fff; var h = this[i++] >> 15; var m = xh * l + h * xl; l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); w[j++] = l & 0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i, x, w, j, c, n) { var xl = x & 0x3fff, xh = x >> 14; while (--n >= 0) { var l = this[i] & 0x3fff; var h = this[i++] >> 14; var m = xh * l + h * xl; l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; c = (l >> 28) + (m >> 14) + xh * h; w[j++] = l & 0xfffffff; } return c; } // We need to select the fastest one that works in this environment. //if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) { // BigInteger.prototype.am = am2; // dbits = 30; //} else if (j_lm && (navigator.appName != "Netscape")) { // BigInteger.prototype.am = am1; // dbits = 26; //} else { // Mozilla/Netscape seems to prefer am3 // BigInteger.prototype.am = am3; // dbits = 28; //} // For node.js, we pick am3 with max dbits to 28. BigInteger.prototype.am = am3; dbits = 28; BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1 << dbits) - 1); BigInteger.prototype.DV = (1 << dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2, BI_FP); BigInteger.prototype.F1 = BI_FP - dbits; BigInteger.prototype.F2 = 2 * dbits - BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = new Array(); var rr, vv; rr = "0".charCodeAt(0); for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s, i) { var c = BI_RC[s.charCodeAt(i)]; return (c == null) ? -1 : c; } // (protected) copy this to r function bnpCopyTo(r) { for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x < 0) ? -1 : 0; if (x > 0) this[0] = x; else if (x < -1) this[0] = x + DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(data, radix, unsigned) { var k; switch (radix) { case 2: k = 1; break; case 4: k = 2; break; case 8: k = 3; break; case 16: k = 4; break; case 32: k = 5; break; case 256: k = 8; break; default: this.fromRadix(data, radix); return; } this.t = 0; this.s = 0; var i = data.length; var mi = false; var sh = 0; while (--i >= 0) { var x = (k == 8) ? data[i] & 0xff : intAt(data, i); if (x < 0) { if (data.charAt(i) == "-") mi = true; continue; } mi = false; if (sh === 0) this[this.t++] = x; else if (sh + k > this.DB) { this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; this[this.t++] = (x >> (this.DB - sh)); } else this[this.t - 1] |= x << sh; sh += k; if (sh >= this.DB) sh -= this.DB; } if ((!unsigned) && k == 8 && (data[0] & 0x80) != 0) { this.s = -1; if (sh > 0) this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; } this.clamp(); if (mi) BigInteger.ZERO.subTo(this, this); } function bnpFromByteArray(a, unsigned) { this.fromString(a, 256, unsigned) } function bnpFromBuffer(a) { this.fromString(a, 256, true) } // (protected) clamp off excess high words function bnpClamp() { var c = this.s & this.DM; while (this.t > 0 && this[this.t - 1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if (this.s < 0) return "-" + this.negate().toString(b); var k; if (b == 16) k = 4; else if (b == 8) k = 3; else if (b == 2) k = 1; else if (b == 32) k = 5; else if (b == 4) k = 2; else return this.toRadix(b); var km = (1 << k) - 1, d, m = false, r = "", i = this.t; var p = this.DB - (i * this.DB) % k; if (i-- > 0) { if (p < this.DB && (d = this[i] >> p) > 0) { m = true; r = int2char(d); } while (i >= 0) { if (p < k) { d = (this[i] & ((1 << p) - 1)) << (k - p); d |= this[--i] >> (p += this.DB - k); } else { d = (this[i] >> (p -= k)) & km; if (p <= 0) { p += this.DB; --i; } } if (d > 0) m = true; if (m) r += int2char(d); } } return m ? r : "0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this, r); return r; } // (public) |this| function bnAbs() { return (this.s < 0) ? this.negate() : this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s - a.s; if (r != 0) return r; var i = this.t; r = i - a.t; if (r != 0) return (this.s < 0) ? -r : r; while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if ((t = x >>> 16) != 0) { x = t; r += 16; } if ((t = x >> 8) != 0) { x = t; r += 8; } if ((t = x >> 4) != 0) { x = t; r += 4; } if ((t = x >> 2) != 0) { x = t; r += 2; } if ((t = x >> 1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if (this.t <= 0) return 0; return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n, r) { var i; for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]; for (i = n - 1; i >= 0; --i) r[i] = 0; r.t = this.t + n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n, r) { for (var i = n; i < this.t; ++i) r[i - n] = this[i]; r.t = Math.max(this.t - n, 0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n, r) { var bs = n % this.DB; var cbs = this.DB - bs; var bm = (1 << cbs) - 1; var ds = Math.floor(n / this.DB), c = (this.s << bs) & this.DM, i; for (i = this.t - 1; i >= 0; --i) { r[i + ds + 1] = (this[i] >> cbs) | c; c = (this[i] & bm) << bs; } for (i = ds - 1; i >= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t + ds + 1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n, r) { r.s = this.s; var ds = Math.floor(n / this.DB); if (ds >= this.t) { r.t = 0; return; } var bs = n % this.DB; var cbs = this.DB - bs; var bm = (1 << bs) - 1; r[0] = this[ds] >> bs; for (var i = ds + 1; i < this.t; ++i) { r[i - ds - 1] |= (this[i] & bm) << cbs; r[i - ds] = this[i] >> bs; } if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; r.t = this.t - ds; r.clamp(); } // (protected) r = this - a function bnpSubTo(a, r) { var i = 0, c = 0, m = Math.min(a.t, this.t); while (i < m) { c += this[i] - a[i]; r[i++] = c & this.DM; c >>= this.DB; } if (a.t < this.t) { c -= a.s; while (i < this.t) { c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while (i < a.t) { c -= a[i]; r[i++] = c & this.DM; c >>= this.DB; } c -= a.s; } r.s = (c < 0) ? -1 : 0; if (c < -1) r[i++] = this.DV + c; else if (c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a, r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i + y.t; while (--i >= 0) r[i] = 0; for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); r.s = 0; r.clamp(); if (this.s != a.s) BigInteger.ZERO.subTo(r, r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2 * x.t; while (--i >= 0) r[i] = 0; for (i = 0; i < x.t - 1; ++i) { var c = x.am(i, x[i], r, 2 * i, 0, 1); if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { r[i + x.t] -= x.DV; r[i + x.t + 1] = 1; } } if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m, q, r) { var pm = m.abs(); if (pm.t <= 0) return; var pt = this.abs(); if (pt.t < pm.t) { if (q != null) q.fromInt(0); if (r != null) this.copyTo(r); return; } if (r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus if (nsh > 0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys - 1]; if (y0 === 0) return; var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0); var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2; var i = r.t, j = i - ys, t = (q == null) ? nbi() : q; y.dlShiftTo(j, t); if (r.compareTo(t) >= 0) { r[r.t++] = 1; r.subTo(t, r); } BigInteger.ONE.dlShiftTo(ys, t); t.subTo(y, y); // "negative" y so we can replace sub with am later while (y.t < ys) y[y.t++] = 0; while (--j >= 0) { // Estimate quotient digit var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out y.dlShiftTo(j, t); r.subTo(t, r); while (r[i] < --qd) r.subTo(t, r); } } if (q != null) { r.drShiftTo(ys, q); if (ts != ms) BigInteger.ZERO.subTo(q, q); } r.t = ys; r.clamp(); if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder if (ts < 0) BigInteger.ZERO.subTo(r, r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a, null, r); if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m, null, x); } function cMulTo(x, y, r) { x.multiplyTo(y, r); this.reduce(r); } function cSqrTo(x, r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if (this.t < 1) return 0; var x = this[0]; if ((x & 1) === 0) return 0; var y = x & 3; // y == 1/x mod 2^2 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y > 0) ? this.DV - y : -y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp & 0x7fff; this.mph = this.mp >> 15; this.um = (1 << (m.DB - 15)) - 1; this.mt2 = 2 * m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t, r); r.divRemTo(this.m, null, r); if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while (x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; for (var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i] & 0x7fff; var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; // use am to combine the multiply-shift-add into one call j = i + this.m.t; x[j] += this.m.am(0, u0, x, i, 0, this.m.t); // propagate carry while (x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t, x); if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); } // r = "x^2/R mod m"; x != r function montSqrTo(x, r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x, y, r) { x.multiplyTo(y, r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (protected) true iff this is even function bnpIsEven() { return ((this.t > 0) ? (this[0] & 1) : this.s) === 0; } // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) function bnpExp(e, z) { if (e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e) - 1; g.copyTo(r); while (--i >= 0) { z.sqrTo(r, r2); if ((e & (1 << i)) > 0) z.mulTo(r2, g, r); else { var t = r; r = r2; r2 = t; } } return z.revert(r); } // (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e, m) { var z; if (e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); return this.exp(e, z); } // All Rights Reserved. // See "LICENSE" for details. // Extended JavaScript BN functions, required for RSA private ops. // Version 1.1: new BigInteger("0", 10) returns "proper" zero // Version 1.2: square() API, isProbablePrime fix //(public) function bnClone() { var r = nbi(); this.copyTo(r); return r; } //(public) return value as integer function bnIntValue() { if (this.s < 0) { if (this.t == 1) return this[0] - this.DV; else if (this.t === 0) return -1; } else if (this.t == 1) return this[0]; else if (this.t === 0) return 0; // assumes 16 < DB < 32 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; } //(public) return value as byte function bnByteValue() { return (this.t == 0) ? this.s : (this[0] << 24) >> 24; } //(public) return value as short (assumes DB>=16) function bnShortValue() { return (this.t == 0) ? this.s : (this[0] << 16) >> 16; } //(protected) return x s.t. r^x < DV function bnpChunkSize(r) { return Math.floor(Math.LN2 * this.DB / Math.log(r)); } //(public) 0 if this === 0, 1 if this > 0 function bnSigNum() { if (this.s < 0) return -1; else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; else return 1; } //(protected) convert to radix string function bnpToRadix(b) { if (b == null) b = 10; if (this.signum() === 0 || b < 2 || b > 36) return "0"; var cs = this.chunkSize(b); var a = Math.pow(b, cs); var d = nbv(a), y = nbi(), z = nbi(), r = ""; this.divRemTo(d, y, z); while (y.signum() > 0) { r = (a + z.intValue()).toString(b).substr(1) + r; y.divRemTo(d, y, z); } return z.intValue().toString(b) + r; } //(protected) convert from radix string function bnpFromRadix(s, b) { this.fromInt(0); if (b == null) b = 10; var cs = this.chunkSize(b); var d = Math.pow(b, cs), mi = false, j = 0, w = 0; for (var i = 0; i < s.length; ++i) { var x = intAt(s, i); if (x < 0) { if (s.charAt(i) == "-" && this.signum() === 0) mi = true; continue; } w = b * w + x; if (++j >= cs) { this.dMultiply(d); this.dAddOffset(w, 0); j = 0; w = 0; } } if (j > 0) { this.dMultiply(Math.pow(b, j)); this.dAddOffset(w, 0); } if (mi) BigInteger.ZERO.subTo(this, this); } //(protected) alternate constructor function bnpFromNumber(a, b) { if ("number" == typeof b) { // new BigInteger(int,int,RNG) if (a < 2) this.fromInt(1); else { this.fromNumber(a); if (!this.testBit(a - 1)) // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); if (this.isEven()) this.dAddOffset(1, 0); // force odd while (!this.isProbablePrime(b)) { this.dAddOffset(2, 0); if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); } } } else { // new BigInteger(int,RNG) var x = crypt.randomBytes((a >> 3) + 1) var t = a & 7; if (t > 0) x[0] &= ((1 << t) - 1); else x[0] = 0; this.fromByteArray(x); } } //(public) convert to bigendian byte array function bnToByteArray() { var i = this.t, r = new Array(); r[0] = this.s; var p = this.DB - (i * this.DB) % 8, d, k = 0; if (i-- > 0) { if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) r[k++] = d | (this.s << (this.DB - p)); while (i >= 0) { if (p < 8) { d = (this[i] & ((1 << p) - 1)) << (8 - p); d |= this[--i] >> (p += this.DB - 8); } else { d = (this[i] >> (p -= 8)) & 0xff; if (p <= 0) { p += this.DB; --i; } } if ((d & 0x80) != 0) d |= -256; if (k === 0 && (this.s & 0x80) != (d & 0x80)) ++k; if (k > 0 || d != this.s) r[k++] = d; } } return r; } /** * return Buffer object * @param trim {boolean} slice buffer if first element == 0 * @returns {Buffer} */ function bnToBuffer(trimOrSize) { var res = Buffer.from(this.toByteArray()); if (trimOrSize === true && res[0] === 0) { res = res.slice(1); } else if (_.isNumber(trimOrSize)) { if (res.length > trimOrSize) { for (var i = 0; i < res.length - trimOrSize; i++) { if (res[i] !== 0) { return null; } } return res.slice(res.length - trimOrSize); } else if (res.length < trimOrSize) { var padded = Buffer.alloc(trimOrSize); padded.fill(0, 0, trimOrSize - res.length); res.copy(padded, trimOrSize - res.length); return padded; } } return res; } function bnEquals(a) { return (this.compareTo(a) == 0); } function bnMin(a) { return (this.compareTo(a) < 0) ? this : a; } function bnMax(a) { return (this.compareTo(a) > 0) ? this : a; } //(protected) r = this op a (bitwise) function bnpBitwiseTo(a, op, r) { var i, f, m = Math.min(a.t, this.t); for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]); if (a.t < this.t) { f = a.s & this.DM; for (i = m; i < this.t; ++i) r[i] = op(this[i], f); r.t = this.t; } else { f = this.s & this.DM; for (i = m; i < a.t; ++i) r[i] = op(f, a[i]); r.t = a.t; } r.s = op(this.s, a.s); r.clamp(); } //(public) this & a function op_and(x, y) { return x & y; } function bnAnd(a) { var r = nbi(); this.bitwiseTo(a, op_and, r); return r; } //(public) this | a function op_or(x, y) { return x | y; } function bnOr(a) { var r = nbi(); this.bitwiseTo(a, op_or, r); return r; } //(public) this ^ a function op_xor(x, y) { return x ^ y; } function bnXor(a) { var r = nbi(); this.bitwiseTo(a, op_xor, r); return r; } //(public) this & ~a function op_andnot(x, y) { return x & ~y; } function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a, op_andnot, r); return r; } //(public) ~this function bnNot() { var r = nbi(); for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]; r.t = this.t; r.s = ~this.s; return r; } //(public) this << n function bnShiftLeft(n) { var r = nbi(); if (n < 0) this.rShiftTo(-n, r); else this.lShiftTo(n, r); return r; } //(public) this >> n function bnShiftRight(n) { var r = nbi(); if (n < 0) this.lShiftTo(-n, r); else this.rShiftTo(n, r); return r; } //return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if (x === 0) return -1; var r = 0; if ((x & 0xffff) === 0) { x >>= 16; r += 16; } if ((x & 0xff) === 0) { x >>= 8; r += 8; } if ((x & 0xf) === 0) { x >>= 4; r += 4; } if ((x & 3) === 0) { x >>= 2; r += 2; } if ((x & 1) === 0) ++r; return r; } //(public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { for (var i = 0; i < this.t; ++i) if (this[i] != 0) return i * this.DB + lbit(this[i]); if (this.s < 0) return this.t * this.DB; return -1; } //return number of 1 bits in x function cbit(x) { var r = 0; while (x != 0) { x &= x - 1; ++r; } return r; } //(public) return number of set bits function bnBitCount() { var r = 0, x = this.s & this.DM; for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); return r; } //(public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n / this.DB); if (j >= this.t) return (this.s != 0); return ((this[j] & (1 << (n % this.DB))) != 0); } //(protected) this op (1<<n) function bnpChangeBit(n, op) { var r = BigInteger.ONE.shiftLeft(n); this.bitwiseTo(r, op, r); return r; } //(public) this | (1<<n) function bnSetBit(n) { return this.changeBit(n, op_or); } //(public) this & ~(1<<n) function bnClearBit(n) { return this.changeBit(n, op_andnot); } //(public) this ^ (1<<n) function bnFlipBit(n) { return this.changeBit(n, op_xor); } //(protected) r = this + a function bnpAddTo(a, r) { var i = 0, c = 0, m = Math.min(a.t, this.t); while (i < m) { c += this[i] + a[i]; r[i++] = c & this.DM; c >>= this.DB; } if (a.t < this.t) { c += a.s; while (i < this.t) { c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while (i < a.t) { c += a[i]; r[i++] = c & this.DM; c >>= this.DB; } c += a.s; } r.s = (c < 0) ? -1 : 0; if (c > 0) r[i++] = c; else if (c < -1) r[i++] = this.DV + c; r.t = i; r.clamp(); } //(public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a, r); return r; } //(public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a, r); return r; } //(public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a, r); return r; } // (public) this^2 function bnSquare() { var r = nbi(); this.squareTo(r); return r; } //(public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a, r, null); return r; } //(public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a, null, r); return r; } //(public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a, q, r); return new Array(q, r); } //(protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); ++this.t; this.clamp(); } //(protected) this += n << w words, this >= 0 function bnpDAddOffset(n, w) { if (n === 0) return; while (this.t <= w) this[this.t++] = 0; this[w] += n; while (this[w] >= this.DV) { this[w] -= this.DV; if (++w >= this.t) this[this.t++] = 0; ++this[w]; } } //A "null" reducer function NullExp() { } function nNop(x) { return x; } function nMulTo(x, y, r) { x.multiplyTo(y, r); } function nSqrTo(x, r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; //(public) this^e function bnPow(e) { return this.exp(e, new NullExp()); } //(protected) r = lower n words of "this * a", a.t <= n //"this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a, n, r) { var i = Math.min(this.t + a.t, n); r.s = 0; // assumes a,this >= 0 r.t = i; while (i > 0) r[--i] = 0; var j; for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i); r.clamp(); } //(protected) r = "this * a" without lower n words, n > 0 //"this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a, n, r) { --n; var i = r.t = this.t + a.t - n; r.s = 0; // assumes a,this >= 0 while (--i >= 0) r[i] = 0; for (i = Math.max(n - this.t, 0); i < a.t; ++i) r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); r.clamp(); r.drShiftTo(1, r); } //Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); else if (x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } //x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t - 1, this.r2); if (x.t > this.m.t + 1) { x.t = this.m.t + 1; x.clamp(); } this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); x.subTo(this.r2, x); while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); } //r = x^2 mod m; x != r function barrettSqrTo(x, r) { x.squareTo(r); this.reduce(r); } //r = x*y mod m; x,y != r function barrettMulTo(x, y, r) { x.multiplyTo(y, r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; //(public) this^e % m (HAC 14.85) function bnModPow(e, m) { var i = e.bitLength(), k, r = nbv(1), z; if (i <= 0) return r; else if (i < 18) k = 1; else if (i < 48) k = 3; else if (i < 144) k = 4; else if (i < 768) k = 5; else k = 6; if (i < 8) z = new Classic(m); else if (m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1; g[1] = z.convert(this); if (k > 1) { var g2 = nbi(); z.sqrTo(g[1], g2); while (n <= km) { g[n] = nbi(); z.mulTo(g2, g[n - 2], g[n]); n += 2; } } var j = e.t - 1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j]) - 1; while (j >= 0) { if (i >= k1) w = (e[j] >> (i - k1)) & km; else { w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); if (j > 0) w |= e[j - 1] >> (this.DB + i - k1); } n = k; while ((w & 1) === 0) { w >>= 1; --n; } if ((i -= n) < 0) { i += this.DB; --j; } if (is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while (n > 1) { z.sqrTo(r, r2); z.sqrTo(r2, r); n -= 2; } if (n > 0) z.sqrTo(r, r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2, g[w], r); } while (j >= 0 && (e[j] & (1 << i)) === 0) { z.sqrTo(r, r2); t = r; r = r2; r2 = t; if (--i < 0) { i = this.DB - 1; --j; } } } return z.revert(r); } //(public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s < 0) ? this.negate() : this.clone(); var y = (a.s < 0) ? a.negate() : a.clone(); if (x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if (g < 0) return x; if (i < g) g = i; if (g > 0) { x.rShiftTo(g, x); y.rShiftTo(g, y); } while (x.signum() > 0) { if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); if (x.compareTo(y) >= 0) { x.subTo(y, x); x.rShiftTo(1, x); } else { y.subTo(x, y); y.rShiftTo(1, y); } } if (g > 0) y.lShiftTo(g, y); return y; } //(protected) this % n, n < 2^26 function bnpModInt(n) { if (n <= 0) return 0; var d = this.DV % n, r = (this.s < 0) ? n - 1 : 0; if (this.t > 0) if (d === 0) r = this[0] % n; else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n; return r; } //(public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if ((this.isEven() && ac) || m.signum() === 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while (u.signum() != 0) { while (u.isEven()) { u.rShiftTo(1, u); if (ac) { if (!a.isEven() || !b.isEven()) { a.addTo(this, a); b.subTo(m, b); } a.rShiftTo(1, a); } else if (!b.isEven()) b.subTo(m, b); b.rShiftTo(1, b); } while (v.isEven()) { v.rShiftTo(1, v); if (ac) { if (!c.isEven() || !d.isEven()) { c.addTo(this, c); d.subTo(m, d); } c.rShiftTo(1, c); } else if (!d.isEven()) d.subTo(m, d); d.rShiftTo(1, d); } if (u.compareTo(v) >= 0) { u.subTo(v, u); if (ac) a.subTo(c, a); b.subTo(d, b); } else { v.subTo(u, v); if (ac) c.subTo(a, c); d.subTo(b, d); } } if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if (d.compareTo(m) >= 0) return d.subtract(m); if (d.signum() < 0) d.addTo(m, d); else return d; if (d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; //(public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { for (i = 0; i < lowprimes.length; ++i) if (x[0] == lowprimes[i]) return true; return false; } if (x.isEven()) return false; i = 1; while (i < lowprimes.length) { var m = lowprimes[i], j = i + 1; while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while (i < j) if (m % lowprimes[i++] === 0) return false; } return x.millerRabin(t); } //(protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if (k <= 0) return false; var r = n1.shiftRight(k); t = (t + 1) >> 1; if (t > lowprimes.length) t = lowprimes.length; var a = nbi(); for (var i = 0; i < t; ++i) { //Pick bases at random, instead of starting at 2 a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); var y = a.modPow(r, this); if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while (j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2, this); if (y.compareTo(BigInteger.ONE) === 0) return false; } if (y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.fromByteArray = bnpFromByteArray; BigInteger.prototype.fromBuffer = bnpFromBuffer; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.isEven = bnpIsEven; BigInteger.prototype.exp = bnpExp; BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.modPowInt = bnModPowInt; BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.toBuffer = bnToBuffer; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; BigInteger.int2char = int2char; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); // JSBN-specific extension BigInteger.prototype.square = bnSquare; //BigInteger interfaces not implemented in jsbn: //BigInteger(int signum, byte[] magnitude) //double doubleValue() //float floatValue() //int hashCode() //long longValue() //static BigInteger valueOf(long val) module.exports = BigInteger; ```
/content/code_sandbox/node_modules/node-rsa/src/libs/jsbn.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
14,063
```javascript var crypto = require('crypto'); var constants = require('constants'); var schemes = require('../schemes/schemes.js'); module.exports = function (keyPair, options) { var jsEngine = require('./js.js')(keyPair, options); var pkcs1Scheme = schemes.pkcs1.makeScheme(keyPair, options); return { encrypt: function (buffer, usePrivate) { if (usePrivate) { return jsEngine.encrypt(buffer, usePrivate); } var padding = constants.RSA_PKCS1_OAEP_PADDING; if (options.encryptionScheme === 'pkcs1') { padding = constants.RSA_PKCS1_PADDING; } if (options.encryptionSchemeOptions && options.encryptionSchemeOptions.padding) { padding = options.encryptionSchemeOptions.padding; } var data = buffer; if (padding === constants.RSA_NO_PADDING) { data = pkcs1Scheme.pkcs0pad(buffer); } return crypto.publicEncrypt({ key: options.rsaUtils.exportKey('public'), padding: padding }, data); }, decrypt: function (buffer, usePublic) { if (usePublic) { return jsEngine.decrypt(buffer, usePublic); } var padding = constants.RSA_PKCS1_OAEP_PADDING; if (options.encryptionScheme === 'pkcs1') { padding = constants.RSA_PKCS1_PADDING; } if (options.encryptionSchemeOptions && options.encryptionSchemeOptions.padding) { padding = options.encryptionSchemeOptions.padding; } var res = crypto.privateDecrypt({ key: options.rsaUtils.exportKey('private'), padding: padding }, buffer); if (padding === constants.RSA_NO_PADDING) { return pkcs1Scheme.pkcs0unpad(res); } return res; } }; }; ```
/content/code_sandbox/node_modules/node-rsa/src/encryptEngines/node12.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
402
```javascript var _ = require('../utils')._; var utils = require('../utils'); module.exports = { privateExport: function (key, options) { return { n: key.n.toBuffer(), e: key.e, d: key.d.toBuffer(), p: key.p.toBuffer(), q: key.q.toBuffer(), dmp1: key.dmp1.toBuffer(), dmq1: key.dmq1.toBuffer(), coeff: key.coeff.toBuffer() }; }, privateImport: function (key, data, options) { if (data.n && data.e && data.d && data.p && data.q && data.dmp1 && data.dmq1 && data.coeff) { key.setPrivate( data.n, data.e, data.d, data.p, data.q, data.dmp1, data.dmq1, data.coeff ); } else { throw Error("Invalid key data"); } }, publicExport: function (key, options) { return { n: key.n.toBuffer(), e: key.e }; }, publicImport: function (key, data, options) { if (data.n && data.e) { key.setPublic( data.n, data.e ); } else { throw Error("Invalid key data"); } }, /** * Trying autodetect and import key * @param key * @param data */ autoImport: function (key, data) { if (data.n && data.e) { if (data.d && data.p && data.q && data.dmp1 && data.dmq1 && data.coeff) { module.exports.privateImport(key, data); return true; } else { module.exports.publicImport(key, data); return true; } } return false; } }; ```
/content/code_sandbox/node_modules/node-rsa/src/formats/components.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
412
```javascript var _ = require('../utils')._; function formatParse(format) { format = format.split('-'); var keyType = 'private'; var keyOpt = {type: 'default'}; for (var i = 1; i < format.length; i++) { if (format[i]) { switch (format[i]) { case 'public': keyType = format[i]; break; case 'private': keyType = format[i]; break; case 'pem': keyOpt.type = format[i]; break; case 'der': keyOpt.type = format[i]; break; } } } return {scheme: format[0], keyType: keyType, keyOpt: keyOpt}; } module.exports = { pkcs1: require('./pkcs1'), pkcs8: require('./pkcs8'), components: require('./components'), isPrivateExport: function (format) { return module.exports[format] && typeof module.exports[format].privateExport === 'function'; }, isPrivateImport: function (format) { return module.exports[format] && typeof module.exports[format].privateImport === 'function'; }, isPublicExport: function (format) { return module.exports[format] && typeof module.exports[format].publicExport === 'function'; }, isPublicImport: function (format) { return module.exports[format] && typeof module.exports[format].publicImport === 'function'; }, detectAndImport: function (key, data, format) { if (format === undefined) { for (var scheme in module.exports) { if (typeof module.exports[scheme].autoImport === 'function' && module.exports[scheme].autoImport(key, data)) { return true; } } } else if (format) { var fmt = formatParse(format); if (module.exports[fmt.scheme]) { if (fmt.keyType === 'private') { module.exports[fmt.scheme].privateImport(key, data, fmt.keyOpt); } else { module.exports[fmt.scheme].publicImport(key, data, fmt.keyOpt); } } else { throw Error('Unsupported key format'); } } return false; }, detectAndExport: function (key, format) { if (format) { var fmt = formatParse(format); if (module.exports[fmt.scheme]) { if (fmt.keyType === 'private') { if (!key.isPrivate()) { throw Error("This is not private key"); } return module.exports[fmt.scheme].privateExport(key, fmt.keyOpt); } else { if (!key.isPublic()) { throw Error("This is not public key"); } return module.exports[fmt.scheme].publicExport(key, fmt.keyOpt); } } else { throw Error('Unsupported key format'); } } } }; ```
/content/code_sandbox/node_modules/node-rsa/src/formats/formats.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
636
```javascript var ber = require('asn1').Ber; var _ = require('../utils')._; var utils = require('../utils'); const PRIVATE_OPENING_BOUNDARY = '-----BEGIN RSA PRIVATE KEY-----'; const PRIVATE_CLOSING_BOUNDARY = '-----END RSA PRIVATE KEY-----'; const PUBLIC_OPENING_BOUNDARY = '-----BEGIN RSA PUBLIC KEY-----'; const PUBLIC_CLOSING_BOUNDARY = '-----END RSA PUBLIC KEY-----'; module.exports = { privateExport: function (key, options) { options = options || {}; var n = key.n.toBuffer(); var d = key.d.toBuffer(); var p = key.p.toBuffer(); var q = key.q.toBuffer(); var dmp1 = key.dmp1.toBuffer(); var dmq1 = key.dmq1.toBuffer(); var coeff = key.coeff.toBuffer(); var length = n.length + d.length + p.length + q.length + dmp1.length + dmq1.length + coeff.length + 512; // magic var writer = new ber.Writer({size: length}); writer.startSequence(); writer.writeInt(0); writer.writeBuffer(n, 2); writer.writeInt(key.e); writer.writeBuffer(d, 2); writer.writeBuffer(p, 2); writer.writeBuffer(q, 2); writer.writeBuffer(dmp1, 2); writer.writeBuffer(dmq1, 2); writer.writeBuffer(coeff, 2); writer.endSequence(); if (options.type === 'der') { return writer.buffer; } else { return PRIVATE_OPENING_BOUNDARY + '\n' + utils.linebrk(writer.buffer.toString('base64'), 64) + '\n' + PRIVATE_CLOSING_BOUNDARY; } }, privateImport: function (key, data, options) { options = options || {}; var buffer; if (options.type !== 'der') { if (Buffer.isBuffer(data)) { data = data.toString('utf8'); } if (_.isString(data)) { var pem = utils.trimSurroundingText(data, PRIVATE_OPENING_BOUNDARY, PRIVATE_CLOSING_BOUNDARY) .replace(/\s+|\n\r|\n|\r$/gm, ''); buffer = Buffer.from(pem, 'base64'); } else { throw Error('Unsupported key format'); } } else if (Buffer.isBuffer(data)) { buffer = data; } else { throw Error('Unsupported key format'); } var reader = new ber.Reader(buffer); reader.readSequence(); reader.readString(2, true); // just zero key.setPrivate( reader.readString(2, true), // modulus reader.readString(2, true), // publicExponent reader.readString(2, true), // privateExponent reader.readString(2, true), // prime1 reader.readString(2, true), // prime2 reader.readString(2, true), // exponent1 -- d mod (p1) reader.readString(2, true), // exponent2 -- d mod (q-1) reader.readString(2, true) // coefficient -- (inverse of q) mod p ); }, publicExport: function (key, options) { options = options || {}; var n = key.n.toBuffer(); var length = n.length + 512; // magic var bodyWriter = new ber.Writer({size: length}); bodyWriter.startSequence(); bodyWriter.writeBuffer(n, 2); bodyWriter.writeInt(key.e); bodyWriter.endSequence(); if (options.type === 'der') { return bodyWriter.buffer; } else { return PUBLIC_OPENING_BOUNDARY + '\n' + utils.linebrk(bodyWriter.buffer.toString('base64'), 64) + '\n' + PUBLIC_CLOSING_BOUNDARY; } }, publicImport: function (key, data, options) { options = options || {}; var buffer; if (options.type !== 'der') { if (Buffer.isBuffer(data)) { data = data.toString('utf8'); } if (_.isString(data)) { var pem = utils.trimSurroundingText(data, PUBLIC_OPENING_BOUNDARY, PUBLIC_CLOSING_BOUNDARY) .replace(/\s+|\n\r|\n|\r$/gm, ''); buffer = Buffer.from(pem, 'base64'); } } else if (Buffer.isBuffer(data)) { buffer = data; } else { throw Error('Unsupported key format'); } var body = new ber.Reader(buffer); body.readSequence(); key.setPublic( body.readString(0x02, true), // modulus body.readString(0x02, true) // publicExponent ); }, /** * Trying autodetect and import key * @param key * @param data */ autoImport: function (key, data) { // [\S\s]* matches zero or more of any character if (/^[\S\s]*-----BEGIN RSA PRIVATE KEY-----\s*(?=(([A-Za-z0-9+/=]+\s*)+))\1-----END RSA PRIVATE KEY-----[\S\s]*$/g.test(data)) { module.exports.privateImport(key, data); return true; } if (/^[\S\s]*-----BEGIN RSA PUBLIC KEY-----\s*(?=(([A-Za-z0-9+/=]+\s*)+))\1-----END RSA PUBLIC KEY-----[\S\s]*$/g.test(data)) { module.exports.publicImport(key, data); return true; } return false; } }; ```
/content/code_sandbox/node_modules/node-rsa/src/formats/pkcs1.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,227
```javascript module.exports.BinarySearchTree = require('./lib/bst'); module.exports.AVLTree = require('./lib/avltree'); ```
/content/code_sandbox/node_modules/binary-search-tree/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
26
```javascript var ber = require('asn1').Ber; var _ = require('../utils')._; var PUBLIC_RSA_OID = '1.2.840.113549.1.1.1'; var utils = require('../utils'); const PRIVATE_OPENING_BOUNDARY = '-----BEGIN PRIVATE KEY-----'; const PRIVATE_CLOSING_BOUNDARY = '-----END PRIVATE KEY-----'; const PUBLIC_OPENING_BOUNDARY = '-----BEGIN PUBLIC KEY-----'; const PUBLIC_CLOSING_BOUNDARY = '-----END PUBLIC KEY-----'; module.exports = { privateExport: function (key, options) { options = options || {}; var n = key.n.toBuffer(); var d = key.d.toBuffer(); var p = key.p.toBuffer(); var q = key.q.toBuffer(); var dmp1 = key.dmp1.toBuffer(); var dmq1 = key.dmq1.toBuffer(); var coeff = key.coeff.toBuffer(); var length = n.length + d.length + p.length + q.length + dmp1.length + dmq1.length + coeff.length + 512; // magic var bodyWriter = new ber.Writer({size: length}); bodyWriter.startSequence(); bodyWriter.writeInt(0); bodyWriter.writeBuffer(n, 2); bodyWriter.writeInt(key.e); bodyWriter.writeBuffer(d, 2); bodyWriter.writeBuffer(p, 2); bodyWriter.writeBuffer(q, 2); bodyWriter.writeBuffer(dmp1, 2); bodyWriter.writeBuffer(dmq1, 2); bodyWriter.writeBuffer(coeff, 2); bodyWriter.endSequence(); var writer = new ber.Writer({size: length}); writer.startSequence(); writer.writeInt(0); writer.startSequence(); writer.writeOID(PUBLIC_RSA_OID); writer.writeNull(); writer.endSequence(); writer.writeBuffer(bodyWriter.buffer, 4); writer.endSequence(); if (options.type === 'der') { return writer.buffer; } else { return PRIVATE_OPENING_BOUNDARY + '\n' + utils.linebrk(writer.buffer.toString('base64'), 64) + '\n' + PRIVATE_CLOSING_BOUNDARY; } }, privateImport: function (key, data, options) { options = options || {}; var buffer; if (options.type !== 'der') { if (Buffer.isBuffer(data)) { data = data.toString('utf8'); } if (_.isString(data)) { var pem = utils.trimSurroundingText(data, PRIVATE_OPENING_BOUNDARY, PRIVATE_CLOSING_BOUNDARY) .replace('-----END PRIVATE KEY-----', '') .replace(/\s+|\n\r|\n|\r$/gm, ''); buffer = Buffer.from(pem, 'base64'); } else { throw Error('Unsupported key format'); } } else if (Buffer.isBuffer(data)) { buffer = data; } else { throw Error('Unsupported key format'); } var reader = new ber.Reader(buffer); reader.readSequence(); reader.readInt(0); var header = new ber.Reader(reader.readString(0x30, true)); if (header.readOID(0x06, true) !== PUBLIC_RSA_OID) { throw Error('Invalid Public key format'); } var body = new ber.Reader(reader.readString(0x04, true)); body.readSequence(); body.readString(2, true); // just zero key.setPrivate( body.readString(2, true), // modulus body.readString(2, true), // publicExponent body.readString(2, true), // privateExponent body.readString(2, true), // prime1 body.readString(2, true), // prime2 body.readString(2, true), // exponent1 -- d mod (p1) body.readString(2, true), // exponent2 -- d mod (q-1) body.readString(2, true) // coefficient -- (inverse of q) mod p ); }, publicExport: function (key, options) { options = options || {}; var n = key.n.toBuffer(); var length = n.length + 512; // magic var bodyWriter = new ber.Writer({size: length}); bodyWriter.writeByte(0); bodyWriter.startSequence(); bodyWriter.writeBuffer(n, 2); bodyWriter.writeInt(key.e); bodyWriter.endSequence(); var writer = new ber.Writer({size: length}); writer.startSequence(); writer.startSequence(); writer.writeOID(PUBLIC_RSA_OID); writer.writeNull(); writer.endSequence(); writer.writeBuffer(bodyWriter.buffer, 3); writer.endSequence(); if (options.type === 'der') { return writer.buffer; } else { return PUBLIC_OPENING_BOUNDARY + '\n' + utils.linebrk(writer.buffer.toString('base64'), 64) + '\n' + PUBLIC_CLOSING_BOUNDARY; } }, publicImport: function (key, data, options) { options = options || {}; var buffer; if (options.type !== 'der') { if (Buffer.isBuffer(data)) { data = data.toString('utf8'); } if (_.isString(data)) { var pem = utils.trimSurroundingText(data, PUBLIC_OPENING_BOUNDARY, PUBLIC_CLOSING_BOUNDARY) .replace(/\s+|\n\r|\n|\r$/gm, ''); buffer = Buffer.from(pem, 'base64'); } } else if (Buffer.isBuffer(data)) { buffer = data; } else { throw Error('Unsupported key format'); } var reader = new ber.Reader(buffer); reader.readSequence(); var header = new ber.Reader(reader.readString(0x30, true)); if (header.readOID(0x06, true) !== PUBLIC_RSA_OID) { throw Error('Invalid Public key format'); } var body = new ber.Reader(reader.readString(0x03, true)); body.readByte(); body.readSequence(); key.setPublic( body.readString(0x02, true), // modulus body.readString(0x02, true) // publicExponent ); }, /** * Trying autodetect and import key * @param key * @param data */ autoImport: function (key, data) { if (/^[\S\s]*-----BEGIN PRIVATE KEY-----\s*(?=(([A-Za-z0-9+/=]+\s*)+))\1-----END PRIVATE KEY-----[\S\s]*$/g.test(data)) { module.exports.privateImport(key, data); return true; } if (/^[\S\s]*-----BEGIN PUBLIC KEY-----\s*(?=(([A-Za-z0-9+/=]+\s*)+))\1-----END PUBLIC KEY-----[\S\s]*$/g.test(data)) { module.exports.publicImport(key, data); return true; } return false; } }; ```
/content/code_sandbox/node_modules/node-rsa/src/formats/pkcs8.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,520
```javascript /** * Return an array with the numbers from 0 to n-1, in a random order */ function getRandomArray (n) { var res, next; if (n === 0) { return []; } if (n === 1) { return [0]; } res = getRandomArray(n - 1); next = Math.floor(Math.random() * n); res.splice(next, 0, n - 1); // Add n-1 at a random position in the array return res; }; module.exports.getRandomArray = getRandomArray; /* * Default compareKeys function will work for numbers, strings and dates */ function defaultCompareKeysFunction (a, b) { if (a < b) { return -1; } if (a > b) { return 1; } if (a === b) { return 0; } var err = new Error("Couldn't compare elements"); err.a = a; err.b = b; throw err; } module.exports.defaultCompareKeysFunction = defaultCompareKeysFunction; /** * Check whether two values are equal (used in non-unique deletion) */ function defaultCheckValueEquality (a, b) { return a === b; } module.exports.defaultCheckValueEquality = defaultCheckValueEquality; ```
/content/code_sandbox/node_modules/binary-search-tree/lib/customUtils.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
277
```javascript /** * Simple binary search tree */ var customUtils = require('./customUtils'); /** * Constructor * @param {Object} options Optional * @param {Boolean} options.unique Whether to enforce a 'unique' constraint on the key or not * @param {Key} options.key Initialize this BST's key with key * @param {Value} options.value Initialize this BST's data with [value] * @param {Function} options.compareKeys Initialize this BST's compareKeys */ function BinarySearchTree (options) { options = options || {}; this.left = null; this.right = null; this.parent = options.parent !== undefined ? options.parent : null; if (options.hasOwnProperty('key')) { this.key = options.key; } this.data = options.hasOwnProperty('value') ? [options.value] : []; this.unique = options.unique || false; this.compareKeys = options.compareKeys || customUtils.defaultCompareKeysFunction; this.checkValueEquality = options.checkValueEquality || customUtils.defaultCheckValueEquality; } // ================================ // Methods used to test the tree // ================================ /** * Get the descendant with max key */ BinarySearchTree.prototype.getMaxKeyDescendant = function () { if (this.right) { return this.right.getMaxKeyDescendant(); } else { return this; } }; /** * Get the maximum key */ BinarySearchTree.prototype.getMaxKey = function () { return this.getMaxKeyDescendant().key; }; /** * Get the descendant with min key */ BinarySearchTree.prototype.getMinKeyDescendant = function () { if (this.left) { return this.left.getMinKeyDescendant() } else { return this; } }; /** * Get the minimum key */ BinarySearchTree.prototype.getMinKey = function () { return this.getMinKeyDescendant().key; }; /** * Check that all nodes (incl. leaves) fullfil condition given by fn * test is a function passed every (key, data) and which throws if the condition is not met */ BinarySearchTree.prototype.checkAllNodesFullfillCondition = function (test) { if (!this.hasOwnProperty('key')) { return; } test(this.key, this.data); if (this.left) { this.left.checkAllNodesFullfillCondition(test); } if (this.right) { this.right.checkAllNodesFullfillCondition(test); } }; /** * Check that the core BST properties on node ordering are verified * Throw if they aren't */ BinarySearchTree.prototype.checkNodeOrdering = function () { var self = this; if (!this.hasOwnProperty('key')) { return; } if (this.left) { this.left.checkAllNodesFullfillCondition(function (k) { if (self.compareKeys(k, self.key) >= 0) { throw new Error('Tree with root ' + self.key + ' is not a binary search tree'); } }); this.left.checkNodeOrdering(); } if (this.right) { this.right.checkAllNodesFullfillCondition(function (k) { if (self.compareKeys(k, self.key) <= 0) { throw new Error('Tree with root ' + self.key + ' is not a binary search tree'); } }); this.right.checkNodeOrdering(); } }; /** * Check that all pointers are coherent in this tree */ BinarySearchTree.prototype.checkInternalPointers = function () { if (this.left) { if (this.left.parent !== this) { throw new Error('Parent pointer broken for key ' + this.key); } this.left.checkInternalPointers(); } if (this.right) { if (this.right.parent !== this) { throw new Error('Parent pointer broken for key ' + this.key); } this.right.checkInternalPointers(); } }; /** * Check that a tree is a BST as defined here (node ordering and pointer references) */ BinarySearchTree.prototype.checkIsBST = function () { this.checkNodeOrdering(); this.checkInternalPointers(); if (this.parent) { throw new Error("The root shouldn't have a parent"); } }; /** * Get number of keys inserted */ BinarySearchTree.prototype.getNumberOfKeys = function () { var res; if (!this.hasOwnProperty('key')) { return 0; } res = 1; if (this.left) { res += this.left.getNumberOfKeys(); } if (this.right) { res += this.right.getNumberOfKeys(); } return res; }; // ============================================ // Methods used to actually work on the tree // ============================================ /** * Create a BST similar (i.e. same options except for key and value) to the current one * Use the same constructor (i.e. BinarySearchTree, AVLTree etc) * @param {Object} options see constructor */ BinarySearchTree.prototype.createSimilar = function (options) { options = options || {}; options.unique = this.unique; options.compareKeys = this.compareKeys; options.checkValueEquality = this.checkValueEquality; return new this.constructor(options); }; /** * Create the left child of this BST and return it */ BinarySearchTree.prototype.createLeftChild = function (options) { var leftChild = this.createSimilar(options); leftChild.parent = this; this.left = leftChild; return leftChild; }; /** * Create the right child of this BST and return it */ BinarySearchTree.prototype.createRightChild = function (options) { var rightChild = this.createSimilar(options); rightChild.parent = this; this.right = rightChild; return rightChild; }; /** * Insert a new element */ BinarySearchTree.prototype.insert = function (key, value) { // Empty tree, insert as root if (!this.hasOwnProperty('key')) { this.key = key; this.data.push(value); return; } // Same key as root if (this.compareKeys(this.key, key) === 0) { if (this.unique) { var err = new Error("Can't insert key " + key + ", it violates the unique constraint"); err.key = key; err.errorType = 'uniqueViolated'; throw err; } else { this.data.push(value); } return; } if (this.compareKeys(key, this.key) < 0) { // Insert in left subtree if (this.left) { this.left.insert(key, value); } else { this.createLeftChild({ key: key, value: value }); } } else { // Insert in right subtree if (this.right) { this.right.insert(key, value); } else { this.createRightChild({ key: key, value: value }); } } }; /** * Search for all data corresponding to a key */ BinarySearchTree.prototype.search = function (key) { if (!this.hasOwnProperty('key')) { return []; } if (this.compareKeys(this.key, key) === 0) { return this.data; } if (this.compareKeys(key, this.key) < 0) { if (this.left) { return this.left.search(key); } else { return []; } } else { if (this.right) { return this.right.search(key); } else { return []; } } }; /** * Return a function that tells whether a given key matches a lower bound */ BinarySearchTree.prototype.getLowerBoundMatcher = function (query) { var self = this; // No lower bound if (!query.hasOwnProperty('$gt') && !query.hasOwnProperty('$gte')) { return function () { return true; }; } if (query.hasOwnProperty('$gt') && query.hasOwnProperty('$gte')) { if (self.compareKeys(query.$gte, query.$gt) === 0) { return function (key) { return self.compareKeys(key, query.$gt) > 0; }; } if (self.compareKeys(query.$gte, query.$gt) > 0) { return function (key) { return self.compareKeys(key, query.$gte) >= 0; }; } else { return function (key) { return self.compareKeys(key, query.$gt) > 0; }; } } if (query.hasOwnProperty('$gt')) { return function (key) { return self.compareKeys(key, query.$gt) > 0; }; } else { return function (key) { return self.compareKeys(key, query.$gte) >= 0; }; } }; /** * Return a function that tells whether a given key matches an upper bound */ BinarySearchTree.prototype.getUpperBoundMatcher = function (query) { var self = this; // No lower bound if (!query.hasOwnProperty('$lt') && !query.hasOwnProperty('$lte')) { return function () { return true; }; } if (query.hasOwnProperty('$lt') && query.hasOwnProperty('$lte')) { if (self.compareKeys(query.$lte, query.$lt) === 0) { return function (key) { return self.compareKeys(key, query.$lt) < 0; }; } if (self.compareKeys(query.$lte, query.$lt) < 0) { return function (key) { return self.compareKeys(key, query.$lte) <= 0; }; } else { return function (key) { return self.compareKeys(key, query.$lt) < 0; }; } } if (query.hasOwnProperty('$lt')) { return function (key) { return self.compareKeys(key, query.$lt) < 0; }; } else { return function (key) { return self.compareKeys(key, query.$lte) <= 0; }; } }; // Append all elements in toAppend to array function append (array, toAppend) { var i; for (i = 0; i < toAppend.length; i += 1) { array.push(toAppend[i]); } } /** * Get all data for a key between bounds * Return it in key order * @param {Object} query Mongo-style query where keys are $lt, $lte, $gt or $gte (other keys are not considered) * @param {Functions} lbm/ubm matching functions calculated at the first recursive step */ BinarySearchTree.prototype.betweenBounds = function (query, lbm, ubm) { var res = []; if (!this.hasOwnProperty('key')) { return []; } // Empty tree lbm = lbm || this.getLowerBoundMatcher(query); ubm = ubm || this.getUpperBoundMatcher(query); if (lbm(this.key) && this.left) { append(res, this.left.betweenBounds(query, lbm, ubm)); } if (lbm(this.key) && ubm(this.key)) { append(res, this.data); } if (ubm(this.key) && this.right) { append(res, this.right.betweenBounds(query, lbm, ubm)); } return res; }; /** * Delete the current node if it is a leaf * Return true if it was deleted */ BinarySearchTree.prototype.deleteIfLeaf = function () { if (this.left || this.right) { return false; } // The leaf is itself a root if (!this.parent) { delete this.key; this.data = []; return true; } if (this.parent.left === this) { this.parent.left = null; } else { this.parent.right = null; } return true; }; /** * Delete the current node if it has only one child * Return true if it was deleted */ BinarySearchTree.prototype.deleteIfOnlyOneChild = function () { var child; if (this.left && !this.right) { child = this.left; } if (!this.left && this.right) { child = this.right; } if (!child) { return false; } // Root if (!this.parent) { this.key = child.key; this.data = child.data; this.left = null; if (child.left) { this.left = child.left; child.left.parent = this; } this.right = null; if (child.right) { this.right = child.right; child.right.parent = this; } return true; } if (this.parent.left === this) { this.parent.left = child; child.parent = this.parent; } else { this.parent.right = child; child.parent = this.parent; } return true; }; /** * Delete a key or just a value * @param {Key} key * @param {Value} value Optional. If not set, the whole key is deleted. If set, only this value is deleted */ BinarySearchTree.prototype.delete = function (key, value) { var newData = [], replaceWith , self = this ; if (!this.hasOwnProperty('key')) { return; } if (this.compareKeys(key, this.key) < 0) { if (this.left) { this.left.delete(key, value); } return; } if (this.compareKeys(key, this.key) > 0) { if (this.right) { this.right.delete(key, value); } return; } if (!this.compareKeys(key, this.key) === 0) { return; } // Delete only a value if (this.data.length > 1 && value !== undefined) { this.data.forEach(function (d) { if (!self.checkValueEquality(d, value)) { newData.push(d); } }); self.data = newData; return; } // Delete the whole node if (this.deleteIfLeaf()) { return; } if (this.deleteIfOnlyOneChild()) { return; } // We are in the case where the node to delete has two children if (Math.random() >= 0.5) { // Randomize replacement to avoid unbalancing the tree too much // Use the in-order predecessor replaceWith = this.left.getMaxKeyDescendant(); this.key = replaceWith.key; this.data = replaceWith.data; if (this === replaceWith.parent) { // Special case this.left = replaceWith.left; if (replaceWith.left) { replaceWith.left.parent = replaceWith.parent; } } else { replaceWith.parent.right = replaceWith.left; if (replaceWith.left) { replaceWith.left.parent = replaceWith.parent; } } } else { // Use the in-order successor replaceWith = this.right.getMinKeyDescendant(); this.key = replaceWith.key; this.data = replaceWith.data; if (this === replaceWith.parent) { // Special case this.right = replaceWith.right; if (replaceWith.right) { replaceWith.right.parent = replaceWith.parent; } } else { replaceWith.parent.left = replaceWith.right; if (replaceWith.right) { replaceWith.right.parent = replaceWith.parent; } } } }; /** * Execute a function on every node of the tree, in key order * @param {Function} fn Signature: node. Most useful will probably be node.key and node.data */ BinarySearchTree.prototype.executeOnEveryNode = function (fn) { if (this.left) { this.left.executeOnEveryNode(fn); } fn(this); if (this.right) { this.right.executeOnEveryNode(fn); } }; /** * Pretty print a tree * @param {Boolean} printData To print the nodes' data along with the key */ BinarySearchTree.prototype.prettyPrint = function (printData, spacing) { spacing = spacing || ""; console.log(spacing + "* " + this.key); if (printData) { console.log(spacing + "* " + this.data); } if (!this.left && !this.right) { return; } if (this.left) { this.left.prettyPrint(printData, spacing + " "); } else { console.log(spacing + " *"); } if (this.right) { this.right.prettyPrint(printData, spacing + " "); } else { console.log(spacing + " *"); } }; // Interface module.exports = BinarySearchTree; ```
/content/code_sandbox/node_modules/binary-search-tree/lib/bst.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,490
```javascript /** * Self-balancing binary search tree using the AVL implementation */ var BinarySearchTree = require('./bst') , customUtils = require('./customUtils') , util = require('util') , _ = require('underscore') ; /** * Constructor * We can't use a direct pointer to the root node (as in the simple binary search tree) * as the root will change during tree rotations * @param {Boolean} options.unique Whether to enforce a 'unique' constraint on the key or not * @param {Function} options.compareKeys Initialize this BST's compareKeys */ function AVLTree (options) { this.tree = new _AVLTree(options); } /** * Constructor of the internal AVLTree * @param {Object} options Optional * @param {Boolean} options.unique Whether to enforce a 'unique' constraint on the key or not * @param {Key} options.key Initialize this BST's key with key * @param {Value} options.value Initialize this BST's data with [value] * @param {Function} options.compareKeys Initialize this BST's compareKeys */ function _AVLTree (options) { options = options || {}; this.left = null; this.right = null; this.parent = options.parent !== undefined ? options.parent : null; if (options.hasOwnProperty('key')) { this.key = options.key; } this.data = options.hasOwnProperty('value') ? [options.value] : []; this.unique = options.unique || false; this.compareKeys = options.compareKeys || customUtils.defaultCompareKeysFunction; this.checkValueEquality = options.checkValueEquality || customUtils.defaultCheckValueEquality; } /** * Inherit basic functions from the basic binary search tree */ util.inherits(_AVLTree, BinarySearchTree); /** * Keep a pointer to the internal tree constructor for testing purposes */ AVLTree._AVLTree = _AVLTree; /** * Check the recorded height is correct for every node * Throws if one height doesn't match */ _AVLTree.prototype.checkHeightCorrect = function () { var leftH, rightH; if (!this.hasOwnProperty('key')) { return; } // Empty tree if (this.left && this.left.height === undefined) { throw new Error("Undefined height for node " + this.left.key); } if (this.right && this.right.height === undefined) { throw new Error("Undefined height for node " + this.right.key); } if (this.height === undefined) { throw new Error("Undefined height for node " + this.key); } leftH = this.left ? this.left.height : 0; rightH = this.right ? this.right.height : 0; if (this.height !== 1 + Math.max(leftH, rightH)) { throw new Error("Height constraint failed for node " + this.key); } if (this.left) { this.left.checkHeightCorrect(); } if (this.right) { this.right.checkHeightCorrect(); } }; /** * Return the balance factor */ _AVLTree.prototype.balanceFactor = function () { var leftH = this.left ? this.left.height : 0 , rightH = this.right ? this.right.height : 0 ; return leftH - rightH; }; /** * Check that the balance factors are all between -1 and 1 */ _AVLTree.prototype.checkBalanceFactors = function () { if (Math.abs(this.balanceFactor()) > 1) { throw new Error('Tree is unbalanced at node ' + this.key); } if (this.left) { this.left.checkBalanceFactors(); } if (this.right) { this.right.checkBalanceFactors(); } }; /** * When checking if the BST conditions are met, also check that the heights are correct * and the tree is balanced */ _AVLTree.prototype.checkIsAVLT = function () { _AVLTree.super_.prototype.checkIsBST.call(this); this.checkHeightCorrect(); this.checkBalanceFactors(); }; AVLTree.prototype.checkIsAVLT = function () { this.tree.checkIsAVLT(); }; /** * Perform a right rotation of the tree if possible * and return the root of the resulting tree * The resulting tree's nodes' heights are also updated */ _AVLTree.prototype.rightRotation = function () { var q = this , p = this.left , b , ah, bh, ch; if (!p) { return this; } // No change b = p.right; // Alter tree structure if (q.parent) { p.parent = q.parent; if (q.parent.left === q) { q.parent.left = p; } else { q.parent.right = p; } } else { p.parent = null; } p.right = q; q.parent = p; q.left = b; if (b) { b.parent = q; } // Update heights ah = p.left ? p.left.height : 0; bh = b ? b.height : 0; ch = q.right ? q.right.height : 0; q.height = Math.max(bh, ch) + 1; p.height = Math.max(ah, q.height) + 1; return p; }; /** * Perform a left rotation of the tree if possible * and return the root of the resulting tree * The resulting tree's nodes' heights are also updated */ _AVLTree.prototype.leftRotation = function () { var p = this , q = this.right , b , ah, bh, ch; if (!q) { return this; } // No change b = q.left; // Alter tree structure if (p.parent) { q.parent = p.parent; if (p.parent.left === p) { p.parent.left = q; } else { p.parent.right = q; } } else { q.parent = null; } q.left = p; p.parent = q; p.right = b; if (b) { b.parent = p; } // Update heights ah = p.left ? p.left.height : 0; bh = b ? b.height : 0; ch = q.right ? q.right.height : 0; p.height = Math.max(ah, bh) + 1; q.height = Math.max(ch, p.height) + 1; return q; }; /** * Modify the tree if its right subtree is too small compared to the left * Return the new root if any */ _AVLTree.prototype.rightTooSmall = function () { if (this.balanceFactor() <= 1) { return this; } // Right is not too small, don't change if (this.left.balanceFactor() < 0) { this.left.leftRotation(); } return this.rightRotation(); }; /** * Modify the tree if its left subtree is too small compared to the right * Return the new root if any */ _AVLTree.prototype.leftTooSmall = function () { if (this.balanceFactor() >= -1) { return this; } // Left is not too small, don't change if (this.right.balanceFactor() > 0) { this.right.rightRotation(); } return this.leftRotation(); }; /** * Rebalance the tree along the given path. The path is given reversed (as he was calculated * in the insert and delete functions). * Returns the new root of the tree * Of course, the first element of the path must be the root of the tree */ _AVLTree.prototype.rebalanceAlongPath = function (path) { var newRoot = this , rotated , i; if (!this.hasOwnProperty('key')) { delete this.height; return this; } // Empty tree // Rebalance the tree and update all heights for (i = path.length - 1; i >= 0; i -= 1) { path[i].height = 1 + Math.max(path[i].left ? path[i].left.height : 0, path[i].right ? path[i].right.height : 0); if (path[i].balanceFactor() > 1) { rotated = path[i].rightTooSmall(); if (i === 0) { newRoot = rotated; } } if (path[i].balanceFactor() < -1) { rotated = path[i].leftTooSmall(); if (i === 0) { newRoot = rotated; } } } return newRoot; }; /** * Insert a key, value pair in the tree while maintaining the AVL tree height constraint * Return a pointer to the root node, which may have changed */ _AVLTree.prototype.insert = function (key, value) { var insertPath = [] , currentNode = this ; // Empty tree, insert as root if (!this.hasOwnProperty('key')) { this.key = key; this.data.push(value); this.height = 1; return this; } // Insert new leaf at the right place while (true) { // Same key: no change in the tree structure if (currentNode.compareKeys(currentNode.key, key) === 0) { if (currentNode.unique) { var err = new Error("Can't insert key " + key + ", it violates the unique constraint"); err.key = key; err.errorType = 'uniqueViolated'; throw err; } else { currentNode.data.push(value); } return this; } insertPath.push(currentNode); if (currentNode.compareKeys(key, currentNode.key) < 0) { if (!currentNode.left) { insertPath.push(currentNode.createLeftChild({ key: key, value: value })); break; } else { currentNode = currentNode.left; } } else { if (!currentNode.right) { insertPath.push(currentNode.createRightChild({ key: key, value: value })); break; } else { currentNode = currentNode.right; } } } return this.rebalanceAlongPath(insertPath); }; // Insert in the internal tree, update the pointer to the root if needed AVLTree.prototype.insert = function (key, value) { var newTree = this.tree.insert(key, value); // If newTree is undefined, that means its structure was not modified if (newTree) { this.tree = newTree; } }; /** * Delete a key or just a value and return the new root of the tree * @param {Key} key * @param {Value} value Optional. If not set, the whole key is deleted. If set, only this value is deleted */ _AVLTree.prototype.delete = function (key, value) { var newData = [], replaceWith , self = this , currentNode = this , deletePath = [] ; if (!this.hasOwnProperty('key')) { return this; } // Empty tree // Either no match is found and the function will return from within the loop // Or a match is found and deletePath will contain the path from the root to the node to delete after the loop while (true) { if (currentNode.compareKeys(key, currentNode.key) === 0) { break; } deletePath.push(currentNode); if (currentNode.compareKeys(key, currentNode.key) < 0) { if (currentNode.left) { currentNode = currentNode.left; } else { return this; // Key not found, no modification } } else { // currentNode.compareKeys(key, currentNode.key) is > 0 if (currentNode.right) { currentNode = currentNode.right; } else { return this; // Key not found, no modification } } } // Delete only a value (no tree modification) if (currentNode.data.length > 1 && value) { currentNode.data.forEach(function (d) { if (!currentNode.checkValueEquality(d, value)) { newData.push(d); } }); currentNode.data = newData; return this; } // Delete a whole node // Leaf if (!currentNode.left && !currentNode.right) { if (currentNode === this) { // This leaf is also the root delete currentNode.key; currentNode.data = []; delete currentNode.height; return this; } else { if (currentNode.parent.left === currentNode) { currentNode.parent.left = null; } else { currentNode.parent.right = null; } return this.rebalanceAlongPath(deletePath); } } // Node with only one child if (!currentNode.left || !currentNode.right) { replaceWith = currentNode.left ? currentNode.left : currentNode.right; if (currentNode === this) { // This node is also the root replaceWith.parent = null; return replaceWith; // height of replaceWith is necessarily 1 because the tree was balanced before deletion } else { if (currentNode.parent.left === currentNode) { currentNode.parent.left = replaceWith; replaceWith.parent = currentNode.parent; } else { currentNode.parent.right = replaceWith; replaceWith.parent = currentNode.parent; } return this.rebalanceAlongPath(deletePath); } } // Node with two children // Use the in-order predecessor (no need to randomize since we actively rebalance) deletePath.push(currentNode); replaceWith = currentNode.left; // Special case: the in-order predecessor is right below the node to delete if (!replaceWith.right) { currentNode.key = replaceWith.key; currentNode.data = replaceWith.data; currentNode.left = replaceWith.left; if (replaceWith.left) { replaceWith.left.parent = currentNode; } return this.rebalanceAlongPath(deletePath); } // After this loop, replaceWith is the right-most leaf in the left subtree // and deletePath the path from the root (inclusive) to replaceWith (exclusive) while (true) { if (replaceWith.right) { deletePath.push(replaceWith); replaceWith = replaceWith.right; } else { break; } } currentNode.key = replaceWith.key; currentNode.data = replaceWith.data; replaceWith.parent.right = replaceWith.left; if (replaceWith.left) { replaceWith.left.parent = replaceWith.parent; } return this.rebalanceAlongPath(deletePath); }; // Delete a value AVLTree.prototype.delete = function (key, value) { var newTree = this.tree.delete(key, value); // If newTree is undefined, that means its structure was not modified if (newTree) { this.tree = newTree; } }; /** * Other functions we want to use on an AVLTree as if it were the internal _AVLTree */ ['getNumberOfKeys', 'search', 'betweenBounds', 'prettyPrint', 'executeOnEveryNode'].forEach(function (fn) { AVLTree.prototype[fn] = function () { return this.tree[fn].apply(this.tree, arguments); }; }); // Interface module.exports = AVLTree; ```
/content/code_sandbox/node_modules/binary-search-tree/lib/avltree.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,272
```javascript var should = require('chai').should() , assert = require('chai').assert , BinarySearchTree = require('../index').BinarySearchTree , _ = require('underscore') , customUtils = require('../lib/customUtils') ; describe('Binary search tree', function () { it('Upon creation, left, right are null, key and data can be set', function () { var bst = new BinarySearchTree(); assert.isNull(bst.left); assert.isNull(bst.right); bst.hasOwnProperty('key').should.equal(false); bst.data.length.should.equal(0); bst = new BinarySearchTree({ key: 6, value: 'ggg' }); assert.isNull(bst.left); assert.isNull(bst.right); bst.key.should.equal(6); bst.data.length.should.equal(1); bst.data[0].should.equal('ggg'); }); describe('Sanity checks', function () { it('Can get maxkey and minkey descendants', function () { var t = new BinarySearchTree({ key: 10 }) , l = new BinarySearchTree({ key: 5 }) , r = new BinarySearchTree({ key: 15 }) , ll = new BinarySearchTree({ key: 3 }) , lr = new BinarySearchTree({ key: 8 }) , rl = new BinarySearchTree({ key: 11 }) , rr = new BinarySearchTree({ key: 42 }) ; t.left = l; t.right = r; l.left = ll; l.right = lr; r.left = rl; r.right = rr; // Getting min and max key descendants t.getMinKeyDescendant().key.should.equal(3); t.getMaxKeyDescendant().key.should.equal(42); t.left.getMinKeyDescendant().key.should.equal(3); t.left.getMaxKeyDescendant().key.should.equal(8); t.right.getMinKeyDescendant().key.should.equal(11); t.right.getMaxKeyDescendant().key.should.equal(42); t.right.left.getMinKeyDescendant().key.should.equal(11); t.right.left.getMaxKeyDescendant().key.should.equal(11); // Getting min and max keys t.getMinKey().should.equal(3); t.getMaxKey().should.equal(42); t.left.getMinKey().should.equal(3); t.left.getMaxKey().should.equal(8); t.right.getMinKey().should.equal(11); t.right.getMaxKey().should.equal(42); t.right.left.getMinKey().should.equal(11); t.right.left.getMaxKey().should.equal(11); }); it('Can check a condition against every node in a tree', function () { var t = new BinarySearchTree({ key: 10 }) , l = new BinarySearchTree({ key: 6 }) , r = new BinarySearchTree({ key: 16 }) , ll = new BinarySearchTree({ key: 4 }) , lr = new BinarySearchTree({ key: 8 }) , rl = new BinarySearchTree({ key: 12 }) , rr = new BinarySearchTree({ key: 42 }) ; t.left = l; t.right = r; l.left = ll; l.right = lr; r.left = rl; r.right = rr; function test (k, v) { if (k % 2 !== 0) { throw 'Key is not even'; } } t.checkAllNodesFullfillCondition(test); [l, r, ll, lr, rl, rr].forEach(function (node) { node.key += 1; (function () { t.checkAllNodesFullfillCondition(test); }).should.throw(); node.key -= 1; }); t.checkAllNodesFullfillCondition(test); }); it('Can check that a tree verifies node ordering', function () { var t = new BinarySearchTree({ key: 10 }) , l = new BinarySearchTree({ key: 5 }) , r = new BinarySearchTree({ key: 15 }) , ll = new BinarySearchTree({ key: 3 }) , lr = new BinarySearchTree({ key: 8 }) , rl = new BinarySearchTree({ key: 11 }) , rr = new BinarySearchTree({ key: 42 }) ; t.left = l; t.right = r; l.left = ll; l.right = lr; r.left = rl; r.right = rr; t.checkNodeOrdering(); // Let's be paranoid and check all cases... l.key = 12; (function () { t.checkNodeOrdering(); }).should.throw(); l.key = 5; r.key = 9; (function () { t.checkNodeOrdering(); }).should.throw(); r.key = 15; ll.key = 6; (function () { t.checkNodeOrdering(); }).should.throw(); ll.key = 11; (function () { t.checkNodeOrdering(); }).should.throw(); ll.key = 3; lr.key = 4; (function () { t.checkNodeOrdering(); }).should.throw(); lr.key = 11; (function () { t.checkNodeOrdering(); }).should.throw(); lr.key = 8; rl.key = 16; (function () { t.checkNodeOrdering(); }).should.throw(); rl.key = 9; (function () { t.checkNodeOrdering(); }).should.throw(); rl.key = 11; rr.key = 12; (function () { t.checkNodeOrdering(); }).should.throw(); rr.key = 7; (function () { t.checkNodeOrdering(); }).should.throw(); rr.key = 10.5; (function () { t.checkNodeOrdering(); }).should.throw(); rr.key = 42; t.checkNodeOrdering(); }); it('Checking if a tree\'s internal pointers (i.e. parents) are correct', function () { var t = new BinarySearchTree({ key: 10 }) , l = new BinarySearchTree({ key: 5 }) , r = new BinarySearchTree({ key: 15 }) , ll = new BinarySearchTree({ key: 3 }) , lr = new BinarySearchTree({ key: 8 }) , rl = new BinarySearchTree({ key: 11 }) , rr = new BinarySearchTree({ key: 42 }) ; t.left = l; t.right = r; l.left = ll; l.right = lr; r.left = rl; r.right = rr; (function () { t.checkInternalPointers(); }).should.throw(); l.parent = t; (function () { t.checkInternalPointers(); }).should.throw(); r.parent = t; (function () { t.checkInternalPointers(); }).should.throw(); ll.parent = l; (function () { t.checkInternalPointers(); }).should.throw(); lr.parent = l; (function () { t.checkInternalPointers(); }).should.throw(); rl.parent = r; (function () { t.checkInternalPointers(); }).should.throw(); rr.parent = r; t.checkInternalPointers(); }); it('Can get the number of inserted keys', function () { var bst = new BinarySearchTree(); bst.getNumberOfKeys().should.equal(0); bst.insert(10); bst.getNumberOfKeys().should.equal(1); bst.insert(5); bst.getNumberOfKeys().should.equal(2); bst.insert(3); bst.getNumberOfKeys().should.equal(3); bst.insert(8); bst.getNumberOfKeys().should.equal(4); bst.insert(15); bst.getNumberOfKeys().should.equal(5); bst.insert(12); bst.getNumberOfKeys().should.equal(6); bst.insert(37); bst.getNumberOfKeys().should.equal(7); }); }); describe('Insertion', function () { it('Insert at the root if its the first insertion', function () { var bst = new BinarySearchTree(); bst.insert(10, 'some data'); bst.checkIsBST(); bst.key.should.equal(10); _.isEqual(bst.data, ['some data']).should.equal(true); assert.isNull(bst.left); assert.isNull(bst.right); }); it("Insert on the left if key is less than the root's", function () { var bst = new BinarySearchTree(); bst.insert(10, 'some data'); bst.insert(7, 'some other data'); bst.checkIsBST(); assert.isNull(bst.right); bst.left.key.should.equal(7); _.isEqual(bst.left.data, ['some other data']).should.equal(true); assert.isNull(bst.left.left); assert.isNull(bst.left.right); }); it("Insert on the right if key is greater than the root's", function () { var bst = new BinarySearchTree(); bst.insert(10, 'some data'); bst.insert(14, 'some other data'); bst.checkIsBST(); assert.isNull(bst.left); bst.right.key.should.equal(14); _.isEqual(bst.right.data, ['some other data']).should.equal(true); assert.isNull(bst.right.left); assert.isNull(bst.right.right); }); it("Recursive insertion on the left works", function () { var bst = new BinarySearchTree(); bst.insert(10, 'some data'); bst.insert(7, 'some other data'); bst.insert(1, 'hello'); bst.insert(9, 'world'); bst.checkIsBST(); assert.isNull(bst.right); bst.left.key.should.equal(7); _.isEqual(bst.left.data, ['some other data']).should.equal(true); bst.left.left.key.should.equal(1); _.isEqual(bst.left.left.data, ['hello']).should.equal(true); bst.left.right.key.should.equal(9); _.isEqual(bst.left.right.data, ['world']).should.equal(true); }); it("Recursive insertion on the right works", function () { var bst = new BinarySearchTree(); bst.insert(10, 'some data'); bst.insert(17, 'some other data'); bst.insert(11, 'hello'); bst.insert(19, 'world'); bst.checkIsBST(); assert.isNull(bst.left); bst.right.key.should.equal(17); _.isEqual(bst.right.data, ['some other data']).should.equal(true); bst.right.left.key.should.equal(11); _.isEqual(bst.right.left.data, ['hello']).should.equal(true); bst.right.right.key.should.equal(19); _.isEqual(bst.right.right.data, ['world']).should.equal(true); }); it('If uniqueness constraint not enforced, we can insert different data for same key', function () { var bst = new BinarySearchTree(); bst.insert(10, 'some data'); bst.insert(3, 'hello'); bst.insert(3, 'world'); bst.checkIsBST(); bst.left.key.should.equal(3); _.isEqual(bst.left.data, ['hello', 'world']).should.equal(true); bst.insert(12, 'a'); bst.insert(12, 'b'); bst.checkIsBST(); bst.right.key.should.equal(12); _.isEqual(bst.right.data, ['a', 'b']).should.equal(true); }); it('If uniqueness constraint is enforced, we cannot insert different data for same key', function () { var bst = new BinarySearchTree({ unique: true }); bst.insert(10, 'some data'); bst.insert(3, 'hello'); try { bst.insert(3, 'world'); } catch (e) { e.errorType.should.equal('uniqueViolated'); e.key.should.equal(3); } bst.checkIsBST(); bst.left.key.should.equal(3); _.isEqual(bst.left.data, ['hello']).should.equal(true); bst.insert(12, 'a'); try { bst.insert(12, 'world'); } catch (e) { e.errorType.should.equal('uniqueViolated'); e.key.should.equal(12); } bst.checkIsBST(); bst.right.key.should.equal(12); _.isEqual(bst.right.data, ['a']).should.equal(true); }); it('Can insert 0 or the empty string', function () { var bst = new BinarySearchTree(); bst.insert(0, 'some data'); bst.checkIsBST(); bst.key.should.equal(0); _.isEqual(bst.data, ['some data']).should.equal(true); assert.isNull(bst.left); assert.isNull(bst.right); bst = new BinarySearchTree(); bst.insert('', 'some other data'); bst.checkIsBST(); bst.key.should.equal(''); _.isEqual(bst.data, ['some other data']).should.equal(true); assert.isNull(bst.left); assert.isNull(bst.right); }); it('Can insert a lot of keys and still get a BST (sanity check)', function () { var bst = new BinarySearchTree({ unique: true }); customUtils.getRandomArray(100).forEach(function (n) { bst.insert(n, 'some data'); }); bst.checkIsBST(); }); it('All children get a pointer to their parent, the root doesnt', function () { var bst = new BinarySearchTree(); bst.insert(10, 'root'); bst.insert(5, 'yes'); bst.insert(15, 'no'); bst.checkIsBST(); assert.isNull(bst.parent); bst.left.parent.should.equal(bst); bst.right.parent.should.equal(bst); }); }); // ==== End of 'Insertion' ==== // describe('Search', function () { it('Can find data in a BST', function () { var bst = new BinarySearchTree() , i; customUtils.getRandomArray(100).forEach(function (n) { bst.insert(n, 'some data for ' + n); }); bst.checkIsBST(); for (i = 0; i < 100; i += 1) { _.isEqual(bst.search(i), ['some data for ' + i]).should.equal(true); } }); it('If no data can be found, return an empty array', function () { var bst = new BinarySearchTree(); customUtils.getRandomArray(100).forEach(function (n) { if (n !== 63) { bst.insert(n, 'some data for ' + n); } }); bst.checkIsBST(); bst.search(-2).length.should.equal(0); bst.search(100).length.should.equal(0); bst.search(101).length.should.equal(0); bst.search(63).length.should.equal(0); }); it('Can search for data between two bounds', function () { var bst = new BinarySearchTree(); [10, 5, 15, 3, 8, 13, 18].forEach(function (k) { bst.insert(k, 'data ' + k); }); assert.deepEqual(bst.betweenBounds({ $gte: 8, $lte: 15 }), ['data 8', 'data 10', 'data 13', 'data 15']); assert.deepEqual(bst.betweenBounds({ $gt: 8, $lt: 15 }), ['data 10', 'data 13']); }); it('Bounded search can handle cases where query contains both $lt and $lte, or both $gt and $gte', function () { var bst = new BinarySearchTree(); [10, 5, 15, 3, 8, 13, 18].forEach(function (k) { bst.insert(k, 'data ' + k); }); assert.deepEqual(bst.betweenBounds({ $gt:8, $gte: 8, $lte: 15 }), ['data 10', 'data 13', 'data 15']); assert.deepEqual(bst.betweenBounds({ $gt:5, $gte: 8, $lte: 15 }), ['data 8', 'data 10', 'data 13', 'data 15']); assert.deepEqual(bst.betweenBounds({ $gt:8, $gte: 5, $lte: 15 }), ['data 10', 'data 13', 'data 15']); assert.deepEqual(bst.betweenBounds({ $gte: 8, $lte: 15, $lt: 15 }), ['data 8', 'data 10', 'data 13']); assert.deepEqual(bst.betweenBounds({ $gte: 8, $lte: 18, $lt: 15 }), ['data 8', 'data 10', 'data 13']); assert.deepEqual(bst.betweenBounds({ $gte: 8, $lte: 15, $lt: 18 }), ['data 8', 'data 10', 'data 13', 'data 15']); }); it('Bounded search can work when one or both boundaries are missing', function () { var bst = new BinarySearchTree(); [10, 5, 15, 3, 8, 13, 18].forEach(function (k) { bst.insert(k, 'data ' + k); }); assert.deepEqual(bst.betweenBounds({ $gte: 11 }), ['data 13', 'data 15', 'data 18']); assert.deepEqual(bst.betweenBounds({ $lte: 9 }), ['data 3', 'data 5', 'data 8']); }); }); /// ==== End of 'Search' ==== // describe('Deletion', function () { it('Deletion does nothing on an empty tree', function () { var bst = new BinarySearchTree() , bstu = new BinarySearchTree({ unique: true }); bst.getNumberOfKeys().should.equal(0); bstu.getNumberOfKeys().should.equal(0); bst.delete(5); bstu.delete(5); bst.hasOwnProperty('key').should.equal(false); bstu.hasOwnProperty('key').should.equal(false); bst.data.length.should.equal(0); bstu.data.length.should.equal(0); bst.getNumberOfKeys().should.equal(0); bstu.getNumberOfKeys().should.equal(0); }); it('Deleting a non-existent key doesnt have any effect', function () { var bst = new BinarySearchTree(); [10, 5, 3, 8, 15, 12, 37].forEach(function (k) { bst.insert(k, 'some ' + k); }); function checkBst () { [10, 5, 3, 8, 15, 12, 37].forEach(function (k) { _.isEqual(bst.search(k), ['some ' + k]).should.equal(true); }); } checkBst(); bst.getNumberOfKeys().should.equal(7); bst.delete(2); checkBst(); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(7); bst.delete(4); checkBst(); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(7); bst.delete(9); checkBst(); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(7); bst.delete(6); checkBst(); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(7); bst.delete(11); checkBst(); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(7); bst.delete(14); checkBst(); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(7); bst.delete(20); checkBst(); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(7); bst.delete(200); checkBst(); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(7); }); it('Able to delete the root if it is also a leaf', function () { var bst = new BinarySearchTree(); bst.insert(10, 'hello'); bst.key.should.equal(10); _.isEqual(bst.data, ['hello']).should.equal(true); bst.getNumberOfKeys().should.equal(1); bst.delete(10); bst.hasOwnProperty('key').should.equal(false); bst.data.length.should.equal(0); bst.getNumberOfKeys().should.equal(0); }); it('Able to delete leaf nodes that are non-root', function () { var bst; function recreateBst () { bst = new BinarySearchTree(); // With this insertion order the tree is well balanced // So we know the leaves are 3, 8, 12, 37 [10, 5, 3, 8, 15, 12, 37].forEach(function (k) { bst.insert(k, 'some ' + k); }); bst.getNumberOfKeys().should.equal(7); } function checkOnlyOneWasRemoved (theRemoved) { [10, 5, 3, 8, 15, 12, 37].forEach(function (k) { if (k === theRemoved) { bst.search(k).length.should.equal(0); } else { _.isEqual(bst.search(k), ['some ' + k]).should.equal(true); } }); bst.getNumberOfKeys().should.equal(6); } recreateBst(); bst.delete(3); bst.checkIsBST(); checkOnlyOneWasRemoved(3); assert.isNull(bst.left.left); recreateBst(); bst.delete(8); bst.checkIsBST(); checkOnlyOneWasRemoved(8); assert.isNull(bst.left.right); recreateBst(); bst.delete(12); bst.checkIsBST(); checkOnlyOneWasRemoved(12); assert.isNull(bst.right.left); recreateBst(); bst.delete(37); bst.checkIsBST(); checkOnlyOneWasRemoved(37); assert.isNull(bst.right.right); }); it('Able to delete the root if it has only one child', function () { var bst; // Root has only one child, on the left bst = new BinarySearchTree(); [10, 5, 3, 6].forEach(function (k) { bst.insert(k, 'some ' + k); }); bst.getNumberOfKeys().should.equal(4); bst.delete(10); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(3); [5, 3, 6].forEach(function (k) { _.isEqual(bst.search(k), ['some ' + k]).should.equal(true); }); bst.search(10).length.should.equal(0); // Root has only one child, on the right bst = new BinarySearchTree(); [10, 15, 13, 16].forEach(function (k) { bst.insert(k, 'some ' + k); }); bst.getNumberOfKeys().should.equal(4); bst.delete(10); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(3); [15, 13, 16].forEach(function (k) { _.isEqual(bst.search(k), ['some ' + k]).should.equal(true); }); bst.search(10).length.should.equal(0); }); it('Able to delete non root nodes that have only one child', function () { var bst; function recreateBst () { bst = new BinarySearchTree(); [10, 5, 15, 3, 1, 4, 20, 17, 25].forEach(function (k) { bst.insert(k, 'some ' + k); }); bst.getNumberOfKeys().should.equal(9); } function checkOnlyOneWasRemoved (theRemoved) { [10, 5, 15, 3, 1, 4, 20, 17, 25].forEach(function (k) { if (k === theRemoved) { bst.search(k).length.should.equal(0); } else { _.isEqual(bst.search(k), ['some ' + k]).should.equal(true); } }); bst.getNumberOfKeys().should.equal(8); } recreateBst(); bst.delete(5); bst.checkIsBST(); checkOnlyOneWasRemoved(5); recreateBst(); bst.delete(15); bst.checkIsBST(); checkOnlyOneWasRemoved(15); }); it('Can delete the root if it has 2 children', function () { var bst; bst = new BinarySearchTree(); [10, 5, 3, 8, 15, 12, 37].forEach(function (k) { bst.insert(k, 'some ' + k); }); bst.getNumberOfKeys().should.equal(7); bst.delete(10); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(6); [5, 3, 8, 15, 12, 37].forEach(function (k) { _.isEqual(bst.search(k), ['some ' + k]).should.equal(true); }); bst.search(10).length.should.equal(0); }); it('Can delete a non-root node that has two children', function () { var bst; bst = new BinarySearchTree(); [10, 5, 3, 1, 4, 8, 6, 9, 15, 12, 11, 13, 20, 19, 42].forEach(function (k) { bst.insert(k, 'some ' + k); }); bst.getNumberOfKeys().should.equal(15); bst.delete(5); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(14); [10, 3, 1, 4, 8, 6, 9, 15, 12, 11, 13, 20, 19, 42].forEach(function (k) { _.isEqual(bst.search(k), ['some ' + k]).should.equal(true); }); bst.search(5).length.should.equal(0); bst = new BinarySearchTree(); [10, 5, 3, 1, 4, 8, 6, 9, 15, 12, 11, 13, 20, 19, 42].forEach(function (k) { bst.insert(k, 'some ' + k); }); bst.getNumberOfKeys().should.equal(15); bst.delete(15); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(14); [10, 5, 3, 1, 4, 8, 6, 9, 12, 11, 13, 20, 19, 42].forEach(function (k) { _.isEqual(bst.search(k), ['some ' + k]).should.equal(true); }); bst.search(15).length.should.equal(0); }); it('If no value is provided, it will delete the entire node even if there are multiple pieces of data', function () { var bst = new BinarySearchTree(); bst.insert(10, 'yes'); bst.insert(5, 'hello'); bst.insert(3, 'yes'); bst.insert(5, 'world'); bst.insert(8, 'yes'); assert.deepEqual(bst.search(5), ['hello', 'world']); bst.getNumberOfKeys().should.equal(4); bst.delete(5); bst.search(5).length.should.equal(0); bst.getNumberOfKeys().should.equal(3); }); it('Can remove only one value from an array', function () { var bst = new BinarySearchTree(); bst.insert(10, 'yes'); bst.insert(5, 'hello'); bst.insert(3, 'yes'); bst.insert(5, 'world'); bst.insert(8, 'yes'); assert.deepEqual(bst.search(5), ['hello', 'world']); bst.getNumberOfKeys().should.equal(4); bst.delete(5, 'hello'); assert.deepEqual(bst.search(5), ['world']); bst.getNumberOfKeys().should.equal(4); }); it('Removes nothing if value doesnt match', function () { var bst = new BinarySearchTree(); bst.insert(10, 'yes'); bst.insert(5, 'hello'); bst.insert(3, 'yes'); bst.insert(5, 'world'); bst.insert(8, 'yes'); assert.deepEqual(bst.search(5), ['hello', 'world']); bst.getNumberOfKeys().should.equal(4); bst.delete(5, 'nope'); assert.deepEqual(bst.search(5), ['hello', 'world']); bst.getNumberOfKeys().should.equal(4); }); it('If value provided but node contains only one value, remove entire node', function () { var bst = new BinarySearchTree(); bst.insert(10, 'yes'); bst.insert(5, 'hello'); bst.insert(3, 'yes2'); bst.insert(5, 'world'); bst.insert(8, 'yes3'); assert.deepEqual(bst.search(3), ['yes2']); bst.getNumberOfKeys().should.equal(4); bst.delete(3, 'yes2'); bst.search(3).length.should.equal(0); bst.getNumberOfKeys().should.equal(3); }); it('Can remove the root from a tree with height 2 when the root has two children (special case)', function () { var bst = new BinarySearchTree(); bst.insert(10, 'maybe'); bst.insert(5, 'no'); bst.insert(15, 'yes'); bst.getNumberOfKeys().should.equal(3); bst.delete(10); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(2); assert.deepEqual(bst.search(5), ['no']); assert.deepEqual(bst.search(15), ['yes']); }); it('Can remove the root from a tree with height 3 when the root has two children (special case where the two children themselves have children)', function () { var bst = new BinarySearchTree(); bst.insert(10, 'maybe'); bst.insert(5, 'no'); bst.insert(15, 'yes'); bst.insert(2, 'no'); bst.insert(35, 'yes'); bst.getNumberOfKeys().should.equal(5); bst.delete(10); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(4); assert.deepEqual(bst.search(5), ['no']); assert.deepEqual(bst.search(15), ['yes']); }); }); // ==== End of 'Deletion' ==== // it('Can use undefined as key and value', function () { function compareKeys (a, b) { if (a === undefined && b === undefined) { return 0; } if (a === undefined) { return -1; } if (b === undefined) { return 1; } if (a < b) { return -1; } if (a > b) { return 1; } if (a === b) { return 0; } } var bst = new BinarySearchTree({ compareKeys: compareKeys }); bst.insert(2, undefined); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(1); assert.deepEqual(bst.search(2), [undefined]); assert.deepEqual(bst.search(undefined), []); bst.insert(undefined, 'hello'); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(2); assert.deepEqual(bst.search(2), [undefined]); assert.deepEqual(bst.search(undefined), ['hello']); bst.insert(undefined, 'world'); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(2); assert.deepEqual(bst.search(2), [undefined]); assert.deepEqual(bst.search(undefined), ['hello', 'world']); bst.insert(4, undefined); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(3); assert.deepEqual(bst.search(2), [undefined]); assert.deepEqual(bst.search(4), [undefined]); assert.deepEqual(bst.search(undefined), ['hello', 'world']); bst.delete(undefined, 'hello'); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(3); assert.deepEqual(bst.search(2), [undefined]); assert.deepEqual(bst.search(4), [undefined]); assert.deepEqual(bst.search(undefined), ['world']); bst.delete(undefined); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(2); assert.deepEqual(bst.search(2), [undefined]); assert.deepEqual(bst.search(4), [undefined]); assert.deepEqual(bst.search(undefined), []); bst.delete(2, undefined); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(1); assert.deepEqual(bst.search(2), []); assert.deepEqual(bst.search(4), [undefined]); assert.deepEqual(bst.search(undefined), []); bst.delete(4); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(0); assert.deepEqual(bst.search(2), []); assert.deepEqual(bst.search(4), []); assert.deepEqual(bst.search(undefined), []); }); it('Can use null as key and value', function () { function compareKeys (a, b) { if (a === null && b === null) { return 0; } if (a === null) { return -1; } if (b === null) { return 1; } if (a < b) { return -1; } if (a > b) { return 1; } if (a === b) { return 0; } } var bst = new BinarySearchTree({ compareKeys: compareKeys }); bst.insert(2, null); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(1); assert.deepEqual(bst.search(2), [null]); assert.deepEqual(bst.search(null), []); bst.insert(null, 'hello'); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(2); assert.deepEqual(bst.search(2), [null]); assert.deepEqual(bst.search(null), ['hello']); bst.insert(null, 'world'); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(2); assert.deepEqual(bst.search(2), [null]); assert.deepEqual(bst.search(null), ['hello', 'world']); bst.insert(4, null); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(3); assert.deepEqual(bst.search(2), [null]); assert.deepEqual(bst.search(4), [null]); assert.deepEqual(bst.search(null), ['hello', 'world']); bst.delete(null, 'hello'); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(3); assert.deepEqual(bst.search(2), [null]); assert.deepEqual(bst.search(4), [null]); assert.deepEqual(bst.search(null), ['world']); bst.delete(null); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(2); assert.deepEqual(bst.search(2), [null]); assert.deepEqual(bst.search(4), [null]); assert.deepEqual(bst.search(null), []); bst.delete(2, null); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(1); assert.deepEqual(bst.search(2), []); assert.deepEqual(bst.search(4), [null]); assert.deepEqual(bst.search(null), []); bst.delete(4); bst.checkIsBST(); bst.getNumberOfKeys().should.equal(0); assert.deepEqual(bst.search(2), []); assert.deepEqual(bst.search(4), []); assert.deepEqual(bst.search(null), []); }); describe('Execute on every node (=tree traversal)', function () { it('Can execute a function on every node', function () { var bst = new BinarySearchTree() , keys = [] , executed = 0 ; bst.insert(10, 'yes'); bst.insert(5, 'hello'); bst.insert(3, 'yes2'); bst.insert(8, 'yes3'); bst.insert(15, 'yes3'); bst.insert(159, 'yes3'); bst.insert(11, 'yes3'); bst.executeOnEveryNode(function (node) { keys.push(node.key); executed += 1; }); assert.deepEqual(keys, [3, 5, 8, 10, 11, 15, 159]); executed.should.equal(7); }); }); // ==== End of 'Execute on every node' ==== // // This test performs several inserts and deletes at random, always checking the content // of the tree are as expected and the binary search tree constraint is respected // This test is important because it can catch bugs other tests can't // By their nature, BSTs can be hard to test (many possible cases, bug at one operation whose // effect begins to be felt only after several operations etc.) describe('Randomized test (takes much longer than the rest of the test suite)', function () { var bst = new BinarySearchTree() , data = {}; // Check a bst against a simple key => [data] object function checkDataIsTheSame (bst, data) { var bstDataElems = []; // bstDataElems is a simple array containing every piece of data in the tree bst.executeOnEveryNode(function (node) { var i; for (i = 0; i < node.data.length; i += 1) { bstDataElems.push(node.data[i]); } }); // Number of key and number of pieces of data match bst.getNumberOfKeys().should.equal(Object.keys(data).length); _.reduce(_.map(data, function (d) { return d.length; }), function (memo, n) { return memo + n; }, 0).should.equal(bstDataElems.length); // Compare data Object.keys(data).forEach(function (key) { checkDataEquality(bst.search(key), data[key]); }); } // Check two pieces of data coming from the bst and data are the same function checkDataEquality (fromBst, fromData) { if (fromBst.length === 0) { if (fromData) { fromData.length.should.equal(0); } } assert.deepEqual(fromBst, fromData); } // Tests the tree structure (deletions concern the whole tree, deletion of some data in a node is well tested above) it('Inserting and deleting entire nodes', function () { // You can skew to be more insertive or deletive, to test all cases function launchRandomTest (nTests, proba) { var i, key, dataPiece, possibleKeys; for (i = 0; i < nTests; i += 1) { if (Math.random() > proba) { // Deletion possibleKeys = Object.keys(data); if (possibleKeys.length > 0) { key = possibleKeys[Math.floor(possibleKeys.length * Math.random()).toString()]; } else { key = Math.floor(70 * Math.random()).toString(); } delete data[key]; bst.delete(key); } else { // Insertion key = Math.floor(70 * Math.random()).toString(); dataPiece = Math.random().toString().substring(0, 6); bst.insert(key, dataPiece); if (data[key]) { data[key].push(dataPiece); } else { data[key] = [dataPiece]; } } // Check the bst constraint are still met and the data is correct bst.checkIsBST(); checkDataIsTheSame(bst, data); } } launchRandomTest(1000, 0.65); launchRandomTest(2000, 0.35); }); }); // ==== End of 'Randomized test' ==== // }); ```
/content/code_sandbox/node_modules/binary-search-tree/test/bst.test.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
8,721
```javascript var v1 = require('./v1'); var v4 = require('./v4'); var uuid = v4; uuid.v1 = v1; uuid.v4 = v4; module.exports = uuid; ```
/content/code_sandbox/node_modules/uuid/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
44
```javascript var rng = require('./lib/rng'); var bytesToUuid = require('./lib/bytesToUuid'); function v4(options, buf, offset) { var i = buf && offset || 0; if (typeof(options) == 'string') { buf = options === 'binary' ? new Array(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80; // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ++ii) { buf[i + ii] = rnds[ii]; } } return buf || bytesToUuid(rnds); } module.exports = v4; ```
/content/code_sandbox/node_modules/uuid/v4.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
239
```javascript var v35 = require('./lib/v35.js'); var md5 = require('./lib/md5'); module.exports = v35('v3', 0x30, md5); ```
/content/code_sandbox/node_modules/uuid/v3.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
39
```javascript var v35 = require('./lib/v35.js'); var sha1 = require('./lib/sha1'); module.exports = v35('v5', 0x50, sha1); ```
/content/code_sandbox/node_modules/uuid/v5.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
40
```javascript var rng = require('./lib/rng'); var bytesToUuid = require('./lib/bytesToUuid'); // **`v1()` - Generate time-based UUID** // // Inspired by path_to_url // and path_to_url var _nodeId; var _clockseq; // Previous uuid creation time var _lastMSecs = 0; var _lastNSecs = 0; // See path_to_url for API details function v1(options, buf, offset) { var i = buf && offset || 0; var b = buf || []; options = options || {}; var node = options.node || _nodeId; var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not // specified. We do this lazily to minimize issues related to insufficient // system entropy. See #189 if (node == null || clockseq == null) { var seedBytes = rng(); if (node == null) { // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) node = _nodeId = [ seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5] ]; } if (clockseq == null) { // Per 4.2.2, randomize (14 bit) clockseq clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } } // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; // `time_mid` var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` b[i++] = clockseq & 0xff; // `node` for (var n = 0; n < 6; ++n) { b[i + n] = node[n]; } return buf ? buf : bytesToUuid(b); } module.exports = v1; ```
/content/code_sandbox/node_modules/uuid/v1.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,099
```javascript // Adapted from Chris Veness' SHA1 code at // path_to_url 'use strict'; function f(s, x, y, z) { switch (s) { case 0: return (x & y) ^ (~x & z); case 1: return x ^ y ^ z; case 2: return (x & y) ^ (x & z) ^ (y & z); case 3: return x ^ y ^ z; } } function ROTL(x, n) { return (x << n) | (x>>> (32 - n)); } function sha1(bytes) { var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; if (typeof(bytes) == 'string') { var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape bytes = new Array(msg.length); for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i); } bytes.push(0x80); var l = bytes.length/4 + 2; var N = Math.ceil(l/16); var M = new Array(N); for (var i=0; i<N; i++) { M[i] = new Array(16); for (var j=0; j<16; j++) { M[i][j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; } } M[N - 1][14] = ((bytes.length - 1) * 8) / Math.pow(2, 32); M[N - 1][14] = Math.floor(M[N - 1][14]); M[N - 1][15] = ((bytes.length - 1) * 8) & 0xffffffff; for (var i=0; i<N; i++) { var W = new Array(80); for (var t=0; t<16; t++) W[t] = M[i][t]; for (var t=16; t<80; t++) { W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); } var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; for (var t=0; t<80; t++) { var s = Math.floor(t/20); var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; e = d; d = c; c = ROTL(b, 30) >>> 0; b = a; a = T; } H[0] = (H[0] + a) >>> 0; H[1] = (H[1] + b) >>> 0; H[2] = (H[2] + c) >>> 0; H[3] = (H[3] + d) >>> 0; H[4] = (H[4] + e) >>> 0; } return [ H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff ]; } module.exports = sha1; ```
/content/code_sandbox/node_modules/uuid/lib/sha1-browser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,083
```javascript var should = require('chai').should() , assert = require('chai').assert , AVLTree = require('../index').AVLTree , _ = require('underscore') , customUtils = require('../lib/customUtils') ; describe('AVL tree', function () { describe('Sanity checks', function () { it('Checking that all nodes heights are correct', function () { var _AVLTree = AVLTree._AVLTree , avlt = new _AVLTree({ key: 10 }) , l = new _AVLTree({ key: 5 }) , r = new _AVLTree({ key: 15 }) , ll = new _AVLTree({ key: 3 }) , lr = new _AVLTree({ key: 8 }) , rl = new _AVLTree({ key: 13 }) , rr = new _AVLTree({ key: 18 }) , lrl = new _AVLTree({ key: 7 }) , lrll = new _AVLTree({ key: 6 }) ; // With a balanced tree avlt.left = l; avlt.right = r; l.left = ll; l.right = lr; r.left = rl; r.right = rr; (function () { avlt.checkHeightCorrect() }).should.throw(); avlt.height = 1; (function () { avlt.checkHeightCorrect() }).should.throw(); l.height = 1; (function () { avlt.checkHeightCorrect() }).should.throw(); r.height = 1; (function () { avlt.checkHeightCorrect() }).should.throw(); ll.height = 1; (function () { avlt.checkHeightCorrect() }).should.throw(); lr.height = 1; (function () { avlt.checkHeightCorrect() }).should.throw(); rl.height = 1; (function () { avlt.checkHeightCorrect() }).should.throw(); rr.height = 1; (function () { avlt.checkHeightCorrect() }).should.throw(); avlt.height = 2; (function () { avlt.checkHeightCorrect() }).should.throw(); l.height = 2; (function () { avlt.checkHeightCorrect() }).should.throw(); r.height = 2; (function () { avlt.checkHeightCorrect() }).should.throw(); avlt.height = 3; avlt.checkHeightCorrect(); // Correct // With an unbalanced tree lr.left = lrl; (function () { avlt.checkHeightCorrect() }).should.throw(); lrl.left = lrll; (function () { avlt.checkHeightCorrect() }).should.throw(); lrl.height = 1; (function () { avlt.checkHeightCorrect() }).should.throw(); lrll.height = 1; (function () { avlt.checkHeightCorrect() }).should.throw(); lrl.height = 2; (function () { avlt.checkHeightCorrect() }).should.throw(); lr.height = 3; (function () { avlt.checkHeightCorrect() }).should.throw(); l.height = 4; (function () { avlt.checkHeightCorrect() }).should.throw(); avlt.height = 5; avlt.checkHeightCorrect(); // Correct }); it('Calculate the balance factor', function () { var _AVLTree = AVLTree._AVLTree , avlt = new _AVLTree({ key: 10 }) , l = new _AVLTree({ key: 5 }) , r = new _AVLTree({ key: 15 }) , ll = new _AVLTree({ key: 3 }) , lr = new _AVLTree({ key: 8 }) , rl = new _AVLTree({ key: 13 }) , rr = new _AVLTree({ key: 18 }) , lrl = new _AVLTree({ key: 7 }) , lrll = new _AVLTree({ key: 6 }) ; // With a balanced tree avlt.left = l; avlt.right = r; l.left = ll; l.right = lr; r.left = rl; r.right = rr; ll.height = 1; rl.height = 1; rr.height = 1; avlt.height = 2; r.height = 2; lr.left = lrl; lrl.left = lrll; lrl.height = 1; lrll.height = 1; lrl.height = 2; lr.height = 3; l.height = 4; avlt.height = 5; avlt.checkHeightCorrect(); // Correct lrll.balanceFactor().should.equal(0); lrl.balanceFactor().should.equal(1); ll.balanceFactor().should.equal(0); lr.balanceFactor().should.equal(2); rl.balanceFactor().should.equal(0); rr.balanceFactor().should.equal(0); l.balanceFactor().should.equal(-2); r.balanceFactor().should.equal(0); avlt.balanceFactor().should.equal(2); }); it('Can check that a tree is balanced', function () { var _AVLTree = AVLTree._AVLTree , avlt = new _AVLTree({ key: 10 }) , l = new _AVLTree({ key: 5 }) , r = new _AVLTree({ key: 15 }) , ll = new _AVLTree({ key: 3 }) , lr = new _AVLTree({ key: 8 }) , rl = new _AVLTree({ key: 13 }) , rr = new _AVLTree({ key: 18 }) avlt.left = l; avlt.right = r; l.left = ll; l.right = lr; r.left = rl; r.right = rr; ll.height = 1; lr.height = 1; rl.height = 1; rr.height = 1; l.height = 2; r.height = 2; avlt.height = 3; avlt.checkBalanceFactors(); r.height = 0; (function () { avlt.checkBalanceFactors(); }).should.throw(); r.height = 4; (function () { avlt.checkBalanceFactors(); }).should.throw(); r.height = 2; avlt.checkBalanceFactors(); ll.height = -1; (function () { avlt.checkBalanceFactors(); }).should.throw(); ll.height = 3; (function () { avlt.checkBalanceFactors(); }).should.throw(); ll.height = 1; avlt.checkBalanceFactors(); rl.height = -1; (function () { avlt.checkBalanceFactors(); }).should.throw(); rl.height = 3; (function () { avlt.checkBalanceFactors(); }).should.throw(); rl.height = 1; avlt.checkBalanceFactors(); }); }); // ==== End of 'Sanity checks' ==== // describe('Insertion', function () { it('The root has a height of 1', function () { var avlt = new AVLTree(); avlt.insert(10, 'root'); avlt.tree.height.should.equal(1); }); it('Insert at the root if its the first insertion', function () { var avlt = new AVLTree(); avlt.insert(10, 'some data'); avlt.checkIsAVLT(); avlt.tree.key.should.equal(10); _.isEqual(avlt.tree.data, ['some data']).should.equal(true); assert.isNull(avlt.tree.left); assert.isNull(avlt.tree.right); }); it('If uniqueness constraint not enforced, we can insert different data for same key', function () { var avlt = new AVLTree(); avlt.insert(10, 'some data'); avlt.insert(3, 'hello'); avlt.insert(3, 'world'); avlt.checkIsAVLT(); _.isEqual(avlt.search(3), ['hello', 'world']).should.equal(true); avlt.insert(12, 'a'); avlt.insert(12, 'b'); avlt.checkIsAVLT(); _.isEqual(avlt.search(12), ['a', 'b']).should.equal(true); }); it('If uniqueness constraint is enforced, we cannot insert different data for same key', function () { var avlt = new AVLTree({ unique: true }); avlt.insert(10, 'some data'); avlt.insert(3, 'hello'); try { avlt.insert(3, 'world'); } catch (e) { e.errorType.should.equal('uniqueViolated'); e.key.should.equal(3); } avlt.checkIsAVLT(); _.isEqual(avlt.search(3), ['hello']).should.equal(true); avlt.insert(12, 'a'); try { avlt.insert(12, 'world'); } catch (e) { e.errorType.should.equal('uniqueViolated'); e.key.should.equal(12); } avlt.checkIsAVLT(); _.isEqual(avlt.search(12), ['a']).should.equal(true); }); it('Can insert 0 or the empty string', function () { var avlt = new AVLTree(); avlt.insert(0, 'some data'); avlt.checkIsAVLT(); avlt.tree.key.should.equal(0); _.isEqual(avlt.tree.data, ['some data']).should.equal(true); avlt = new AVLTree(); avlt.insert('', 'some other data'); avlt.checkIsAVLT(); avlt.tree.key.should.equal(''); _.isEqual(avlt.tree.data, ['some other data']).should.equal(true); }); it('Auto-balancing insertions', function () { var avlt = new AVLTree() , avlt2 = new AVLTree() , avlt3 = new AVLTree() ; // Balancing insertions on the left avlt.tree.getNumberOfKeys().should.equal(0); avlt.insert(18); avlt.tree.getNumberOfKeys().should.equal(1); avlt.tree.checkIsAVLT(); avlt.insert(15); avlt.tree.getNumberOfKeys().should.equal(2); avlt.tree.checkIsAVLT(); avlt.insert(13); avlt.tree.getNumberOfKeys().should.equal(3); avlt.tree.checkIsAVLT(); avlt.insert(10); avlt.tree.getNumberOfKeys().should.equal(4); avlt.tree.checkIsAVLT(); avlt.insert(8); avlt.tree.getNumberOfKeys().should.equal(5); avlt.tree.checkIsAVLT(); avlt.insert(5); avlt.tree.getNumberOfKeys().should.equal(6); avlt.tree.checkIsAVLT(); avlt.insert(3); avlt.tree.getNumberOfKeys().should.equal(7); avlt.tree.checkIsAVLT(); // Balancing insertions on the right avlt2.tree.getNumberOfKeys().should.equal(0); avlt2.insert(3); avlt2.tree.getNumberOfKeys().should.equal(1); avlt2.tree.checkIsAVLT(); avlt2.insert(5); avlt2.tree.getNumberOfKeys().should.equal(2); avlt2.tree.checkIsAVLT(); avlt2.insert(8); avlt2.tree.getNumberOfKeys().should.equal(3); avlt2.tree.checkIsAVLT(); avlt2.insert(10); avlt2.tree.getNumberOfKeys().should.equal(4); avlt2.tree.checkIsAVLT(); avlt2.insert(13); avlt2.tree.getNumberOfKeys().should.equal(5); avlt2.tree.checkIsAVLT(); avlt2.insert(15); avlt2.tree.getNumberOfKeys().should.equal(6); avlt2.tree.checkIsAVLT(); avlt2.insert(18); avlt2.tree.getNumberOfKeys().should.equal(7); avlt2.tree.checkIsAVLT(); // Balancing already-balanced insertions avlt3.tree.getNumberOfKeys().should.equal(0); avlt3.insert(10); avlt3.tree.getNumberOfKeys().should.equal(1); avlt3.tree.checkIsAVLT(); avlt3.insert(5); avlt3.tree.getNumberOfKeys().should.equal(2); avlt3.tree.checkIsAVLT(); avlt3.insert(15); avlt3.tree.getNumberOfKeys().should.equal(3); avlt3.tree.checkIsAVLT(); avlt3.insert(3); avlt3.tree.getNumberOfKeys().should.equal(4); avlt3.tree.checkIsAVLT(); avlt3.insert(8); avlt3.tree.getNumberOfKeys().should.equal(5); avlt3.tree.checkIsAVLT(); avlt3.insert(13); avlt3.tree.getNumberOfKeys().should.equal(6); avlt3.tree.checkIsAVLT(); avlt3.insert(18); avlt3.tree.getNumberOfKeys().should.equal(7); avlt3.tree.checkIsAVLT(); }); it('Can insert a lot of keys and still get an AVLT (sanity check)', function () { var avlt = new AVLTree({ unique: true }); customUtils.getRandomArray(1000).forEach(function (n) { avlt.insert(n, 'some data'); avlt.checkIsAVLT(); }); }); }); // ==== End of 'Insertion' ==== // describe('Search', function () { it('Can find data in an AVLT', function () { var avlt = new AVLTree() , i; customUtils.getRandomArray(100).forEach(function (n) { avlt.insert(n, 'some data for ' + n); }); avlt.checkIsAVLT(); for (i = 0; i < 100; i += 1) { _.isEqual(avlt.search(i), ['some data for ' + i]).should.equal(true); } }); it('If no data can be found, return an empty array', function () { var avlt = new AVLTree(); customUtils.getRandomArray(100).forEach(function (n) { if (n !== 63) { avlt.insert(n, 'some data for ' + n); } }); avlt.checkIsAVLT(); avlt.search(-2).length.should.equal(0); avlt.search(100).length.should.equal(0); avlt.search(101).length.should.equal(0); avlt.search(63).length.should.equal(0); }); it('Can search for data between two bounds', function () { var avlt = new AVLTree(); [10, 5, 15, 3, 8, 13, 18].forEach(function (k) { avlt.insert(k, 'data ' + k); }); assert.deepEqual(avlt.betweenBounds({ $gte: 8, $lte: 15 }), ['data 8', 'data 10', 'data 13', 'data 15']); assert.deepEqual(avlt.betweenBounds({ $gt: 8, $lt: 15 }), ['data 10', 'data 13']); }); it('Bounded search can handle cases where query contains both $lt and $lte, or both $gt and $gte', function () { var avlt = new AVLTree(); [10, 5, 15, 3, 8, 13, 18].forEach(function (k) { avlt.insert(k, 'data ' + k); }); assert.deepEqual(avlt.betweenBounds({ $gt:8, $gte: 8, $lte: 15 }), ['data 10', 'data 13', 'data 15']); assert.deepEqual(avlt.betweenBounds({ $gt:5, $gte: 8, $lte: 15 }), ['data 8', 'data 10', 'data 13', 'data 15']); assert.deepEqual(avlt.betweenBounds({ $gt:8, $gte: 5, $lte: 15 }), ['data 10', 'data 13', 'data 15']); assert.deepEqual(avlt.betweenBounds({ $gte: 8, $lte: 15, $lt: 15 }), ['data 8', 'data 10', 'data 13']); assert.deepEqual(avlt.betweenBounds({ $gte: 8, $lte: 18, $lt: 15 }), ['data 8', 'data 10', 'data 13']); assert.deepEqual(avlt.betweenBounds({ $gte: 8, $lte: 15, $lt: 18 }), ['data 8', 'data 10', 'data 13', 'data 15']); }); it('Bounded search can work when one or both boundaries are missing', function () { var avlt = new AVLTree(); [10, 5, 15, 3, 8, 13, 18].forEach(function (k) { avlt.insert(k, 'data ' + k); }); assert.deepEqual(avlt.betweenBounds({ $gte: 11 }), ['data 13', 'data 15', 'data 18']); assert.deepEqual(avlt.betweenBounds({ $lte: 9 }), ['data 3', 'data 5', 'data 8']); }); }); /// ==== End of 'Search' ==== // describe('Deletion', function () { it('Deletion does nothing on an empty tree', function () { var avlt = new AVLTree() , avltu = new AVLTree({ unique: true }); avlt.getNumberOfKeys().should.equal(0); avltu.getNumberOfKeys().should.equal(0); avlt.delete(5); avltu.delete(5); avlt.tree.hasOwnProperty('key').should.equal(false); avltu.tree.hasOwnProperty('key').should.equal(false); avlt.tree.data.length.should.equal(0); avltu.tree.data.length.should.equal(0); avlt.getNumberOfKeys().should.equal(0); avltu.getNumberOfKeys().should.equal(0); }); it('Deleting a non-existent key doesnt have any effect', function () { var avlt = new AVLTree(); [10, 5, 3, 8, 15, 12, 37].forEach(function (k) { avlt.insert(k, 'some ' + k); }); function checkavlt () { [10, 5, 3, 8, 15, 12, 37].forEach(function (k) { _.isEqual(avlt.search(k), ['some ' + k]).should.equal(true); }); } checkavlt(); avlt.getNumberOfKeys().should.equal(7); avlt.delete(2); checkavlt(); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(7); avlt.delete(4); checkavlt(); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(7); avlt.delete(9); checkavlt(); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(7); avlt.delete(6); checkavlt(); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(7); avlt.delete(11); checkavlt(); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(7); avlt.delete(14); checkavlt(); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(7); avlt.delete(20); checkavlt(); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(7); avlt.delete(200); checkavlt(); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(7); }); it('Able to delete the root if it is also a leaf', function () { var avlt = new AVLTree(); avlt.insert(10, 'hello'); avlt.tree.key.should.equal(10); _.isEqual(avlt.tree.data, ['hello']).should.equal(true); avlt.getNumberOfKeys().should.equal(1); avlt.delete(10); avlt.tree.hasOwnProperty('key').should.equal(false); avlt.tree.data.length.should.equal(0); avlt.getNumberOfKeys().should.equal(0); }); it('Able to delete leaf nodes that are non-root', function () { var avlt; // This will create an AVL tree with leaves 3, 8, 12, 37 // (do a pretty print to see this) function recreateavlt () { avlt = new AVLTree(); [10, 5, 3, 8, 15, 12, 37].forEach(function (k) { avlt.insert(k, 'some ' + k); }); avlt.getNumberOfKeys().should.equal(7); } // Check that only keys in array theRemoved were removed function checkRemoved (theRemoved) { [10, 5, 3, 8, 15, 12, 37].forEach(function (k) { if (theRemoved.indexOf(k) !== -1) { avlt.search(k).length.should.equal(0); } else { _.isEqual(avlt.search(k), ['some ' + k]).should.equal(true); } }); avlt.getNumberOfKeys().should.equal(7 - theRemoved.length); } recreateavlt(); avlt.delete(3); avlt.checkIsAVLT(); checkRemoved([3]); recreateavlt(); avlt.delete(8); avlt.checkIsAVLT(); checkRemoved([8]); recreateavlt(); avlt.delete(12); avlt.checkIsAVLT(); checkRemoved([12]); // Delete all leaves in a way that makes the tree unbalanced recreateavlt(); avlt.delete(37); avlt.checkIsAVLT(); checkRemoved([37]); avlt.delete(12); avlt.checkIsAVLT(); checkRemoved([12, 37]); avlt.delete(15); avlt.checkIsAVLT(); checkRemoved([12, 15, 37]); avlt.delete(3); avlt.checkIsAVLT(); checkRemoved([3, 12, 15, 37]); avlt.delete(5); avlt.checkIsAVLT(); checkRemoved([3, 5, 12, 15, 37]); avlt.delete(10); avlt.checkIsAVLT(); checkRemoved([3, 5, 10, 12, 15, 37]); avlt.delete(8); avlt.checkIsAVLT(); checkRemoved([3, 5, 8, 10, 12, 15, 37]); }); it('Able to delete the root if it has only one child', function () { var avlt; // Root has only one child, on the left avlt = new AVLTree(); [10, 5].forEach(function (k) { avlt.insert(k, 'some ' + k); }); avlt.getNumberOfKeys().should.equal(2); avlt.delete(10); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(1); _.isEqual(avlt.search(5), ['some 5']).should.equal(true); avlt.search(10).length.should.equal(0); // Root has only one child, on the right avlt = new AVLTree(); [10, 15].forEach(function (k) { avlt.insert(k, 'some ' + k); }); avlt.getNumberOfKeys().should.equal(2); avlt.delete(10); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(1); _.isEqual(avlt.search(15), ['some 15']).should.equal(true); avlt.search(10).length.should.equal(0); }); it('Able to delete non root nodes that have only one child', function () { var avlt = new AVLTree() , firstSet = [10, 5, 15, 3, 1, 4, 20] , secondSet = [10, 5, 15, 3, 1, 4, 20, 17, 25] ; // Check that only keys in array theRemoved were removed function checkRemoved (set, theRemoved) { set.forEach(function (k) { if (theRemoved.indexOf(k) !== -1) { avlt.search(k).length.should.equal(0); } else { _.isEqual(avlt.search(k), ['some ' + k]).should.equal(true); } }); avlt.getNumberOfKeys().should.equal(set.length - theRemoved.length); } // First set: no rebalancing necessary firstSet.forEach(function (k) { avlt.insert(k, 'some ' + k); }); avlt.getNumberOfKeys().should.equal(7); avlt.checkIsAVLT(); avlt.delete(4); // Leaf avlt.checkIsAVLT(); checkRemoved(firstSet, [4]); avlt.delete(3); // Node with only one child (on the left) avlt.checkIsAVLT(); checkRemoved(firstSet, [3, 4]); avlt.delete(10); // Leaf avlt.checkIsAVLT(); checkRemoved(firstSet, [3, 4, 10]); avlt.delete(15); // Node with only one child (on the right) avlt.checkIsAVLT(); checkRemoved(firstSet, [3, 4, 10, 15]); // Second set: some rebalancing necessary avlt = new AVLTree(); secondSet.forEach(function (k) { avlt.insert(k, 'some ' + k); }); avlt.delete(4); // Leaf avlt.checkIsAVLT(); checkRemoved(secondSet, [4]); avlt.delete(3); // Node with only one child (on the left), causes rebalancing avlt.checkIsAVLT(); checkRemoved(secondSet, [3, 4]); }); it('Can delete the root if it has 2 children', function () { var avlt = new AVLTree(); // No rebalancing needed [10, 5, 15, 3, 8, 12, 37].forEach(function (k) { avlt.insert(k, 'some ' + k); }); avlt.getNumberOfKeys().should.equal(7); avlt.delete(10); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(6); [5, 3, 8, 15, 12, 37].forEach(function (k) { _.isEqual(avlt.search(k), ['some ' + k]).should.equal(true); }); avlt.search(10).length.should.equal(0); // Rebalancing needed avlt = new AVLTree(); [10, 5, 15, 8, 12, 37, 42].forEach(function (k) { avlt.insert(k, 'some ' + k); }); avlt.getNumberOfKeys().should.equal(7); avlt.delete(10); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(6); [5, 8, 15, 12, 37, 42].forEach(function (k) { _.isEqual(avlt.search(k), ['some ' + k]).should.equal(true); }); avlt.search(10).length.should.equal(0); }); it('Can delete a non-root node that has two children', function () { var avlt; // On the left avlt = new AVLTree(); [10, 5, 15, 3, 8, 12, 20, 1, 4, 6, 9, 11, 13, 19, 42, 3.5].forEach(function (k) { avlt.insert(k, 'some ' + k); }); avlt.getNumberOfKeys().should.equal(16); avlt.delete(5); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(15); [10, 3, 1, 4, 8, 6, 9, 15, 12, 11, 13, 20, 19, 42, 3.5].forEach(function (k) { _.isEqual(avlt.search(k), ['some ' + k]).should.equal(true); }); avlt.search(5).length.should.equal(0); // On the right avlt = new AVLTree(); [10, 5, 15, 3, 8, 12, 20, 1, 4, 6, 9, 11, 13, 19, 42, 12.5].forEach(function (k) { avlt.insert(k, 'some ' + k); }); avlt.getNumberOfKeys().should.equal(16); avlt.delete(15); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(15); [10, 3, 1, 4, 8, 6, 9, 5, 12, 11, 13, 20, 19, 42, 12.5].forEach(function (k) { _.isEqual(avlt.search(k), ['some ' + k]).should.equal(true); }); avlt.search(15).length.should.equal(0); }); it('If no value is provided, it will delete the entire node even if there are multiple pieces of data', function () { var avlt = new AVLTree(); avlt.insert(10, 'yes'); avlt.insert(5, 'hello'); avlt.insert(3, 'yes'); avlt.insert(5, 'world'); avlt.insert(8, 'yes'); assert.deepEqual(avlt.search(5), ['hello', 'world']); avlt.getNumberOfKeys().should.equal(4); avlt.delete(5); avlt.checkIsAVLT(); avlt.search(5).length.should.equal(0); avlt.getNumberOfKeys().should.equal(3); }); it('Can remove only one value from an array', function () { var avlt = new AVLTree(); avlt.insert(10, 'yes'); avlt.insert(5, 'hello'); avlt.insert(3, 'yes'); avlt.insert(5, 'world'); avlt.insert(8, 'yes'); assert.deepEqual(avlt.search(5), ['hello', 'world']); avlt.getNumberOfKeys().should.equal(4); avlt.delete(5, 'hello'); avlt.checkIsAVLT(); assert.deepEqual(avlt.search(5), ['world']); avlt.getNumberOfKeys().should.equal(4); }); it('Removes nothing if value doesnt match', function () { var avlt = new AVLTree(); avlt.insert(10, 'yes'); avlt.insert(5, 'hello'); avlt.insert(3, 'yes'); avlt.insert(5, 'world'); avlt.insert(8, 'yes'); assert.deepEqual(avlt.search(5), ['hello', 'world']); avlt.getNumberOfKeys().should.equal(4); avlt.delete(5, 'nope'); avlt.checkIsAVLT(); assert.deepEqual(avlt.search(5), ['hello', 'world']); avlt.getNumberOfKeys().should.equal(4); }); it('If value provided but node contains only one value, remove entire node', function () { var avlt = new AVLTree(); avlt.insert(10, 'yes'); avlt.insert(5, 'hello'); avlt.insert(3, 'yes2'); avlt.insert(5, 'world'); avlt.insert(8, 'yes3'); assert.deepEqual(avlt.search(3), ['yes2']); avlt.getNumberOfKeys().should.equal(4); avlt.delete(3, 'yes2'); avlt.checkIsAVLT(); avlt.search(3).length.should.equal(0); avlt.getNumberOfKeys().should.equal(3); }); it('Can remove the root from a tree with height 2 when the root has two children (special case)', function () { var avlt = new AVLTree(); avlt.insert(10, 'maybe'); avlt.insert(5, 'no'); avlt.insert(15, 'yes'); avlt.getNumberOfKeys().should.equal(3); avlt.delete(10); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(2); assert.deepEqual(avlt.search(5), ['no']); assert.deepEqual(avlt.search(15), ['yes']); }); it('Can remove the root from a tree with height 3 when the root has two children (special case where the two children themselves have children)', function () { var avlt = new AVLTree(); avlt.insert(10, 'maybe'); avlt.insert(5, 'no'); avlt.insert(15, 'yes'); avlt.insert(2, 'no'); avlt.insert(35, 'yes'); avlt.getNumberOfKeys().should.equal(5); avlt.delete(10); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(4); assert.deepEqual(avlt.search(5), ['no']); assert.deepEqual(avlt.search(15), ['yes']); }); }); // ==== End of 'Deletion' ==== // it('Can use undefined as key and value', function () { function compareKeys (a, b) { if (a === undefined && b === undefined) { return 0; } if (a === undefined) { return -1; } if (b === undefined) { return 1; } if (a < b) { return -1; } if (a > b) { return 1; } if (a === b) { return 0; } } var avlt = new AVLTree({ compareKeys: compareKeys }); avlt.insert(2, undefined); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(1); assert.deepEqual(avlt.search(2), [undefined]); assert.deepEqual(avlt.search(undefined), []); avlt.insert(undefined, 'hello'); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(2); assert.deepEqual(avlt.search(2), [undefined]); assert.deepEqual(avlt.search(undefined), ['hello']); avlt.insert(undefined, 'world'); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(2); assert.deepEqual(avlt.search(2), [undefined]); assert.deepEqual(avlt.search(undefined), ['hello', 'world']); avlt.insert(4, undefined); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(3); assert.deepEqual(avlt.search(2), [undefined]); assert.deepEqual(avlt.search(4), [undefined]); assert.deepEqual(avlt.search(undefined), ['hello', 'world']); avlt.delete(undefined, 'hello'); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(3); assert.deepEqual(avlt.search(2), [undefined]); assert.deepEqual(avlt.search(4), [undefined]); assert.deepEqual(avlt.search(undefined), ['world']); avlt.delete(undefined); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(2); assert.deepEqual(avlt.search(2), [undefined]); assert.deepEqual(avlt.search(4), [undefined]); assert.deepEqual(avlt.search(undefined), []); avlt.delete(2, undefined); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(1); assert.deepEqual(avlt.search(2), []); assert.deepEqual(avlt.search(4), [undefined]); assert.deepEqual(avlt.search(undefined), []); avlt.delete(4); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(0); assert.deepEqual(avlt.search(2), []); assert.deepEqual(avlt.search(4), []); assert.deepEqual(avlt.search(undefined), []); }); it('Can use null as key and value', function () { function compareKeys (a, b) { if (a === null && b === null) { return 0; } if (a === null) { return -1; } if (b === null) { return 1; } if (a < b) { return -1; } if (a > b) { return 1; } if (a === b) { return 0; } } var avlt = new AVLTree({ compareKeys: compareKeys }); avlt.insert(2, null); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(1); assert.deepEqual(avlt.search(2), [null]); assert.deepEqual(avlt.search(null), []); avlt.insert(null, 'hello'); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(2); assert.deepEqual(avlt.search(2), [null]); assert.deepEqual(avlt.search(null), ['hello']); avlt.insert(null, 'world'); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(2); assert.deepEqual(avlt.search(2), [null]); assert.deepEqual(avlt.search(null), ['hello', 'world']); avlt.insert(4, null); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(3); assert.deepEqual(avlt.search(2), [null]); assert.deepEqual(avlt.search(4), [null]); assert.deepEqual(avlt.search(null), ['hello', 'world']); avlt.delete(null, 'hello'); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(3); assert.deepEqual(avlt.search(2), [null]); assert.deepEqual(avlt.search(4), [null]); assert.deepEqual(avlt.search(null), ['world']); avlt.delete(null); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(2); assert.deepEqual(avlt.search(2), [null]); assert.deepEqual(avlt.search(4), [null]); assert.deepEqual(avlt.search(null), []); avlt.delete(2, null); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(1); assert.deepEqual(avlt.search(2), []); assert.deepEqual(avlt.search(4), [null]); assert.deepEqual(avlt.search(null), []); avlt.delete(4); avlt.checkIsAVLT(); avlt.getNumberOfKeys().should.equal(0); assert.deepEqual(avlt.search(2), []); assert.deepEqual(avlt.search(4), []); assert.deepEqual(avlt.search(null), []); }); describe('Execute on every node (=tree traversal)', function () { it('Can execute a function on every node', function () { var avlt = new AVLTree() , keys = [] , executed = 0 ; avlt.insert(10, 'yes'); avlt.insert(5, 'hello'); avlt.insert(3, 'yes2'); avlt.insert(8, 'yes3'); avlt.insert(15, 'yes3'); avlt.insert(159, 'yes3'); avlt.insert(11, 'yes3'); avlt.executeOnEveryNode(function (node) { keys.push(node.key); executed += 1; }); assert.deepEqual(keys, [3, 5, 8, 10, 11, 15, 159]); executed.should.equal(7); }); }); // ==== End of 'Execute on every node' ==== // // This test performs several inserts and deletes at random, always checking the content // of the tree are as expected and the binary search tree constraint is respected // This test is important because it can catch bugs other tests can't // By their nature, BSTs can be hard to test (many possible cases, bug at one operation whose // effect begins to be felt only after several operations etc.) describe('Randomized test (takes much longer than the rest of the test suite)', function () { var avlt = new AVLTree() , data = {}; // Check a avlt against a simple key => [data] object function checkDataIsTheSame (avlt, data) { var avltDataElems = []; // avltDataElems is a simple array containing every piece of data in the tree avlt.executeOnEveryNode(function (node) { var i; for (i = 0; i < node.data.length; i += 1) { avltDataElems.push(node.data[i]); } }); // Number of key and number of pieces of data match avlt.getNumberOfKeys().should.equal(Object.keys(data).length); _.reduce(_.map(data, function (d) { return d.length; }), function (memo, n) { return memo + n; }, 0).should.equal(avltDataElems.length); // Compare data Object.keys(data).forEach(function (key) { checkDataEquality(avlt.search(key), data[key]); }); } // Check two pieces of data coming from the avlt and data are the same function checkDataEquality (fromavlt, fromData) { if (fromavlt.length === 0) { if (fromData) { fromData.length.should.equal(0); } } assert.deepEqual(fromavlt, fromData); } // Tests the tree structure (deletions concern the whole tree, deletion of some data in a node is well tested above) it('Inserting and deleting entire nodes', function () { // You can skew to be more insertive or deletive, to test all cases function launchRandomTest (nTests, proba) { var i, key, dataPiece, possibleKeys; for (i = 0; i < nTests; i += 1) { if (Math.random() > proba) { // Deletion possibleKeys = Object.keys(data); if (possibleKeys.length > 0) { key = possibleKeys[Math.floor(possibleKeys.length * Math.random()).toString()]; } else { key = Math.floor(70 * Math.random()).toString(); } delete data[key]; avlt.delete(key); } else { // Insertion key = Math.floor(70 * Math.random()).toString(); dataPiece = Math.random().toString().substring(0, 6); avlt.insert(key, dataPiece); if (data[key]) { data[key].push(dataPiece); } else { data[key] = [dataPiece]; } } // Check the avlt constraint are still met and the data is correct avlt.checkIsAVLT(); checkDataIsTheSame(avlt, data); } } launchRandomTest(1000, 0.65); launchRandomTest(2000, 0.35); }); }); // ==== End of 'Randomized test' ==== // }); ```
/content/code_sandbox/node_modules/binary-search-tree/test/avltree.test.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
9,673
```javascript var bytesToUuid = require('./bytesToUuid'); function uuidToBytes(uuid) { // Note: We assume we're being passed a valid uuid string var bytes = []; uuid.replace(/[a-fA-F0-9]{2}/g, function(hex) { bytes.push(parseInt(hex, 16)); }); return bytes; } function stringToBytes(str) { str = unescape(encodeURIComponent(str)); // UTF8 escape var bytes = new Array(str.length); for (var i = 0; i < str.length; i++) { bytes[i] = str.charCodeAt(i); } return bytes; } module.exports = function(name, version, hashfunc) { var generateUUID = function(value, namespace, buf, offset) { var off = buf && offset || 0; if (typeof(value) == 'string') value = stringToBytes(value); if (typeof(namespace) == 'string') namespace = uuidToBytes(namespace); if (!Array.isArray(value)) throw TypeError('value must be an array of bytes'); if (!Array.isArray(namespace) || namespace.length !== 16) throw TypeError('namespace must be uuid string or an Array of 16 byte values'); // Per 4.3 var bytes = hashfunc(namespace.concat(value)); bytes[6] = (bytes[6] & 0x0f) | version; bytes[8] = (bytes[8] & 0x3f) | 0x80; if (buf) { for (var idx = 0; idx < 16; ++idx) { buf[off+idx] = bytes[idx]; } } return buf || bytesToUuid(bytes); }; // Function#name is not settable on some platforms (#270) try { generateUUID.name = name; } catch (err) { } // Pre-defined namespaces, per Appendix C generateUUID.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; generateUUID.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; return generateUUID; }; ```
/content/code_sandbox/node_modules/uuid/lib/v35.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
485
```javascript 'use strict'; var crypto = require('crypto'); function sha1(bytes) { if (typeof Buffer.from === 'function') { // Modern Buffer API if (Array.isArray(bytes)) { bytes = Buffer.from(bytes); } else if (typeof bytes === 'string') { bytes = Buffer.from(bytes, 'utf8'); } } else { // Pre-v4 Buffer API if (Array.isArray(bytes)) { bytes = new Buffer(bytes); } else if (typeof bytes === 'string') { bytes = new Buffer(bytes, 'utf8'); } } return crypto.createHash('sha1').update(bytes).digest(); } module.exports = sha1; ```
/content/code_sandbox/node_modules/uuid/lib/sha1.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
149
```javascript // Unique ID creation requires a high quality random # generator. In the // browser this is a little complicated due to unknown quality of Math.random() // and inconsistent support for the `crypto` API. We do the best we can via // feature-detection // getRandomValues needs to be invoked in a context where "this" is a Crypto // implementation. Also, find the complete implementation of crypto on IE11. var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) || (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto)); if (getRandomValues) { // WHATWG crypto RNG - path_to_url var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef module.exports = function whatwgRNG() { getRandomValues(rnds8); return rnds8; }; } else { // Math.random()-based (RNG) // // If all else fails, use Math.random(). It's fast, but is of unspecified // quality. var rnds = new Array(16); module.exports = function mathRNG() { for (var i = 0, r; i < 16; i++) { if ((i & 0x03) === 0) r = Math.random() * 0x100000000; rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; } return rnds; }; } ```
/content/code_sandbox/node_modules/uuid/lib/rng-browser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
352
```javascript /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ var byteToHex = []; for (var i = 0; i < 256; ++i) { byteToHex[i] = (i + 0x100).toString(16).substr(1); } function bytesToUuid(buf, offset) { var i = offset || 0; var bth = byteToHex; // join used to fix memory issue caused by concatenation: path_to_url#c4 return ([ bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]] ]).join(''); } module.exports = bytesToUuid; ```
/content/code_sandbox/node_modules/uuid/lib/bytesToUuid.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
270
```javascript // Unique ID creation requires a high quality random # generator. In node.js // this is pretty straight-forward - we use the crypto API. var crypto = require('crypto'); module.exports = function nodeRNG() { return crypto.randomBytes(16); }; ```
/content/code_sandbox/node_modules/uuid/lib/rng.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
56
```javascript 'use strict'; var crypto = require('crypto'); function md5(bytes) { if (typeof Buffer.from === 'function') { // Modern Buffer API if (Array.isArray(bytes)) { bytes = Buffer.from(bytes); } else if (typeof bytes === 'string') { bytes = Buffer.from(bytes, 'utf8'); } } else { // Pre-v4 Buffer API if (Array.isArray(bytes)) { bytes = new Buffer(bytes); } else if (typeof bytes === 'string') { bytes = new Buffer(bytes, 'utf8'); } } return crypto.createHash('md5').update(bytes).digest(); } module.exports = md5; ```
/content/code_sandbox/node_modules/uuid/lib/md5.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
149
```javascript var parse = require('acorn').parse; var isArray = require('isarray'); var objectKeys = require('object-keys'); var forEach = require('foreach'); module.exports = function (src, opts, fn) { if (typeof opts === 'function') { fn = opts; opts = {}; } if (src && typeof src === 'object' && src.constructor.name === 'Buffer') { src = src.toString(); } else if (src && typeof src === 'object') { opts = src; src = opts.source; delete opts.source; } src = src === undefined ? opts.source : src; if (typeof src !== 'string') src = String(src); if (opts.parser) parse = opts.parser.parse; var ast = parse(src, opts); var result = { chunks : src.split(''), toString : function () { return result.chunks.join('') }, inspect : function () { return result.toString() } }; var index = 0; (function walk (node, parent) { insertHelpers(node, parent, result.chunks); forEach(objectKeys(node), function (key) { if (key === 'parent') return; var child = node[key]; if (isArray(child)) { forEach(child, function (c) { if (c && typeof c.type === 'string') { walk(c, node); } }); } else if (child && typeof child.type === 'string') { walk(child, node); } }); fn(node); })(ast, undefined); return result; }; function insertHelpers (node, parent, chunks) { node.parent = parent; node.source = function () { return chunks.slice(node.start, node.end).join(''); }; if (node.update && typeof node.update === 'object') { var prev = node.update; forEach(objectKeys(prev), function (key) { update[key] = prev[key]; }); node.update = update; } else { node.update = update; } function update (s) { chunks[node.start] = s; for (var i = node.start + 1; i < node.end; i++) { chunks[i] = ''; } } } ```
/content/code_sandbox/node_modules/falafel/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
503
```javascript /* * Browser-compatible JavaScript MD5 * * Modification of JavaScript MD5 * path_to_url * * path_to_url * * path_to_url * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * See path_to_url for more info. */ 'use strict'; function md5(bytes) { if (typeof(bytes) == 'string') { var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape bytes = new Array(msg.length); for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i); } return md5ToHexEncodedArray( wordsToMd5( bytesToWords(bytes) , bytes.length * 8) ); } /* * Convert an array of little-endian words to an array of bytes */ function md5ToHexEncodedArray(input) { var i; var x; var output = []; var length32 = input.length * 32; var hexTab = '0123456789abcdef'; var hex; for (i = 0; i < length32; i += 8) { x = (input[i >> 5] >>> (i % 32)) & 0xFF; hex = parseInt(hexTab.charAt((x >>> 4) & 0x0F) + hexTab.charAt(x & 0x0F), 16); output.push(hex); } return output; } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function wordsToMd5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var i; var olda; var oldb; var oldc; var oldd; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5ff(a, b, c, d, x[i], 7, -680876936); d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5ff(c, d, a, b, x[i + 10], 17, -42063); b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5gg(b, c, d, a, x[i], 20, -373897302); a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5hh(a, b, c, d, x[i + 5], 4, -378558); d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5hh(d, a, b, c, x[i], 11, -358537222); c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5ii(a, b, c, d, x[i], 6, -198630844); d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); a = safeAdd(a, olda); b = safeAdd(b, oldb); c = safeAdd(c, oldc); d = safeAdd(d, oldd); } return [a, b, c, d]; } /* * Convert an array bytes to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function bytesToWords(input) { var i; var output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } var length8 = input.length * 8; for (i = 0; i < length8; i += 8) { output[i >> 5] |= (input[(i / 8)] & 0xFF) << (i % 32); } return output; } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safeAdd(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bitRotateLeft(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * These functions implement the four basic operations the algorithm uses. */ function md5cmn(q, a, b, x, s, t) { return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); } function md5ff(a, b, c, d, x, s, t) { return md5cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5gg(a, b, c, d, x, s, t) { return md5cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5hh(a, b, c, d, x, s, t) { return md5cmn(b ^ c ^ d, a, b, x, s, t); } function md5ii(a, b, c, d, x, s, t) { return md5cmn(c ^ (b | (~d)), a, b, x, s, t); } module.exports = md5; ```
/content/code_sandbox/node_modules/uuid/lib/md5-browser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,945
```javascript var falafel = require('../'); var src = 'console.log(beep "boop", "BOOP");'; function isKeyword (id) { if (id === 'beep') return true; } var output = falafel(src, { isKeyword: isKeyword }, function (node) { if (node.type === 'UnaryExpression' && node.operator === 'beep') { node.update( 'String(' + node.argument.source() + ').toUpperCase()' ); } }); console.log(output); ```
/content/code_sandbox/node_modules/falafel/example/keyword.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
113
```javascript var falafel = require('../'); var src = '(' + function () { var xs = [ 1, 2, [ 3, 4 ] ]; var ys = [ 5, 6 ]; console.dir([ xs, ys ]); } + ')()'; var output = falafel(src, function (node) { if (node.type === 'ArrayExpression') { node.update('fn(' + node.source() + ')'); } }); console.log(output); ```
/content/code_sandbox/node_modules/falafel/example/array.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
104
```markdown # falafel Transform the [ast](path_to_url on a recursive walk. [![browser support](path_to_url [![build status](path_to_url This modules uses [acorn](path_to_url to create an AST from source code. ![falafel dner](path_to_url # example ## array.js Put a function wrapper around all array literals. ``` js var falafel = require('falafel'); var src = '(' + function () { var xs = [ 1, 2, [ 3, 4 ] ]; var ys = [ 5, 6 ]; console.dir([ xs, ys ]); } + ')()'; var output = falafel(src, function (node) { if (node.type === 'ArrayExpression') { node.update('fn(' + node.source() + ')'); } }); console.log(output); ``` output: ``` (function () { var xs = fn([ 1, 2, fn([ 3, 4 ]) ]); var ys = fn([ 5, 6 ]); console.dir(fn([ xs, ys ])); })() ``` # methods ``` js var falafel = require('falafel') ``` ## falafel(src, opts={}, fn) Transform the string source `src` with the function `fn`, returning a string-like transformed output object. For every node in the ast, `fn(node)` fires. The recursive walk is a pre-traversal, so children get called before their parents. Performing a pre-traversal makes it easier to write nested transforms since transforming parents often requires transforming all its children first. The return value is string-like (it defines `.toString()` and `.inspect()`) so that you can call `node.update()` asynchronously after the function has returned and still capture the output. Instead of passing a `src` you can also use `opts.source`. All of the `opts` will be passed directly to [acorn](path_to_url ## custom parser You may pass in an instance of acorn to the opts as `opts.parser` to use that version instead of the version of acorn packaged with this library. ```js var acorn = require('acorn-jsx'); falafel(src, {parser: acorn, plugins: { jsx: true }}, function(node) { // this will parse jsx }); ``` # nodes Aside from the regular [esprima](path_to_url data, you can also call some inserted methods on nodes. Aside from updating the current node, you can also reach into sub-nodes to call update functions on children from parent nodes. ## node.source() Return the source for the given node, including any modifications made to children nodes. ## node.update(s) Transform the source for the present node to the string `s`. Note that in `'ForStatement'` node types, there is an existing subnode called `update`. For those nodes all the properties are copied over onto the `node.update()` function. ## node.parent Reference to the parent element or `null` at the root element. # install With [npm](path_to_url do: ``` npm install falafel ``` # license MIT ```
/content/code_sandbox/node_modules/falafel/readme.markdown
markdown
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
695
```javascript var falafel = require('../'); var vm = require('vm'); var termExps = [ 'Identifier', 'CallExpression', 'BinaryExpression', 'UpdateExpression', 'UnaryExpression' ].reduce(function (acc, key) { acc[key] = true; return acc }, {}); function terminated (node) { for (var p = node; p.parent; p = p.parent) { if (termExps[p.type]) return true; } return false; } var src = '{"a":[2,~9,prompt(":d")],"b":4,"c":prompt("beep"),"d":6}'; var offsets = []; var output = falafel('(' + src + ')', function (node) { var isLeaf = node.parent && !terminated(node.parent) && terminated(node) ; if (isLeaf) { var s = node.source(); var prompted = false; var res = vm.runInNewContext('(' + s + ')', { prompt : function (x) { setTimeout(function () { node.update(x.toUpperCase()); }, Math.random() * 50); prompted = true; } }); if (!prompted) { var s_ = JSON.stringify(res); node.update(s_); } } }); setTimeout(function () { console.log(src); console.log('---'); console.log(output); }, 200); ```
/content/code_sandbox/node_modules/falafel/example/prompt.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
305
```javascript var falafel = require('../'); var test = require('tape'); test('array', function (t) { t.plan(5); var src = '(function () {' + 'var xs = [ 1, 2, [ 3, 4 ] ];' + 'var ys = [ 5, 6 ];' + 'g([ xs, ys ]);' + '})()'; var pending = 0; var output = falafel(src, function (node) { if (node.type === 'ArrayExpression') { pending ++; setTimeout(function () { node.update('fn(' + node.source() + ')'); if (--pending === 0) check(); }, 50 * pending * 2); } }); var arrays = [ [ 3, 4 ], [ 1, 2, [ 3, 4 ] ], [ 5, 6 ], [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], ]; function check () { Function([ 'fn', 'g' ], output)( function (xs) { t.same(arrays.shift(), xs); return xs; }, function (xs) { t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); } ); } }); ```
/content/code_sandbox/node_modules/falafel/test/async.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
317
```javascript var falafel = require('../'); var test = require('tape'); test('for loop', function (t) { t.plan(7); var src = '(function () {' + 'var sum = 0;' + 'for (var i = 0; i < 10; i++)' + 'sum += i;' + 'if (true)' + 'for (var i = 0; i < 10; i++)' + 'sum += i;' + 'return sum;' + '})()'; var output = falafel(src, function (node) { if (node.type === 'ForStatement') { t.equal(node.update.source(), 'i++'); t.equal(node.update.type, "UpdateExpression"); node.update.update('i+=2'); } if (node.type === 'UpdateExpression') { t.equal(node.source(), 'i++'); } }); var res = Function('return ' + output)(); t.equal(res, 2 + 4 + 6 + 8 + 2 + 4 + 6 + 8); }); ```
/content/code_sandbox/node_modules/falafel/test/for.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
248
```javascript var falafel = require('../'); var test = require('tape'); test('inspect', function (t) { t.plan(6); var src = '(function () {' + 'var xs = [ 1, 2, [ 3, 4 ] ];' + 'var ys = [ 5, 6 ];' + 'g([ xs, ys ]);' + '})()'; var output = falafel(src, function (node) { if (node.type === 'ArrayExpression') { node.update('fn(' + node.source() + ')'); } }); t.equal(output.inspect(), output.toString()); var arrays = [ [ 3, 4 ], [ 1, 2, [ 3, 4 ] ], [ 5, 6 ], [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], ]; Function(['fn','g'], output)( function (xs) { t.same(arrays.shift(), xs); return xs; }, function (xs) { t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); } ); }); ```
/content/code_sandbox/node_modules/falafel/test/inspect.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
281
```javascript var falafel = require('../'); var test = require('tape'); test('array', function (t) { t.plan(5); var src = '(' + function () { var xs = [ 1, 2, [ 3, 4 ] ]; var ys = [ 5, 6 ]; g([ xs, ys ]); } + ')()'; var output = falafel(src, function (node) { if (node.type === 'ArrayExpression') { node.update('fn(' + node.source() + ')'); } }); var arrays = [ [ 3, 4 ], [ 1, 2, [ 3, 4 ] ], [ 5, 6 ], [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], ]; Function(['fn','g'], output)( function (xs) { t.same(arrays.shift(), xs); return xs; }, function (xs) { t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); } ); }); ```
/content/code_sandbox/node_modules/falafel/test/array.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
263
```javascript var falafel = require('../'); var test = require('tape'); test('parent', function (t) { t.plan(5); var src = '(function () {' + 'var xs = [ 1, 2, 3 ];' + 'fn(ys);' + '})()'; var output = falafel(src, function (node) { if (node.type === 'ArrayExpression') { t.equal(node.parent.type, 'VariableDeclarator'); t.equal( ffBracket(node.parent.source()), 'xs = [ 1, 2, 3 ]' ); t.equal(node.parent.parent.type, 'VariableDeclaration'); t.equal( ffBracket(node.parent.parent.source()), 'var xs = [ 1, 2, 3 ];' ); node.parent.update('ys = 4;'); } }); Function(['fn'], output)(function (x) { t.equal(x, 4) }); }); function ffBracket (s) { return s.replace(/\[\s*/, '[ ').replace(/\s*\]/, ' ]'); } ```
/content/code_sandbox/node_modules/falafel/test/parent.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
244
```javascript var falafel = require('../'); var acorn = require('acorn-jsx'); var test = require('tape'); test('custom parser', function (t) { var src = '(function() { var f = {a: "b"}; var a = <div {...f} className="test"></div>; })()'; var nodeTypes = [ 'Identifier', 'Identifier', 'Literal', 'Property', 'ObjectExpression', 'VariableDeclarator', 'VariableDeclaration', 'Identifier', 'Identifier', 'JSXSpreadAttribute', 'JSXIdentifier', 'Literal', 'JSXAttribute', 'JSXIdentifier', 'JSXOpeningElement', 'JSXIdentifier', 'JSXClosingElement', 'JSXElement', 'VariableDeclarator', 'VariableDeclaration', 'BlockStatement', 'FunctionExpression', 'CallExpression', 'ExpressionStatement', 'Program' ]; t.plan(nodeTypes.length); var output = falafel(src, {parser: acorn, ecmaVersion: 6, plugins: { jsx: true }}, function(node) { t.equal(node.type, nodeTypes.shift()); }); }); ```
/content/code_sandbox/node_modules/falafel/test/custom-parser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
266
```javascript var falafel = require('../'); var test = require('tape'); test('generators', function (t) { t.plan(1); var src = 'console.log((function * () { yield 3 })().next().value)'; var output = falafel(src, { ecmaVersion: 6 }, function (node) { if (node.type === 'Literal') { node.update('555'); } }); Function(['console'],output)({log:log}); function log (n) { t.equal(n, 555) } }); ```
/content/code_sandbox/node_modules/falafel/test/es6.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
124
```javascript var path = require('path'); for (var i = 2; i < process.argv.length; i++) { require(path.resolve(process.cwd(), process.argv[i])); } ```
/content/code_sandbox/node_modules/falafel/test/bin/run.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
37
```javascript var falafel = require('../'); var test = require('tape'); test('first opts arg', function (t) { t.plan(5); var src = '(function () {' + 'var xs = [ 1, 2, [ 3, 4 ] ];' + 'var ys = [ 5, 6 ];' + 'g([ xs, ys ]);' + '})()'; var output = falafel({ source: src }, function (node) { if (node.type === 'ArrayExpression') { node.update('fn(' + node.source() + ')'); } }); var arrays = [ [ 3, 4 ], [ 1, 2, [ 3, 4 ] ], [ 5, 6 ], [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], ]; Function(['fn','g'], output)( function (xs) { t.same(arrays.shift(), xs); return xs; }, function (xs) { t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); } ); }); test('opts.source', function (t) { t.plan(5); var src = '(function () {' + 'var xs = [ 1, 2, [ 3, 4 ] ];' + 'var ys = [ 5, 6 ];' + 'g([ xs, ys ]);' + '})()'; var output = falafel(undefined, { source: src }, function (node) { if (node.type === 'ArrayExpression') { node.update('fn(' + node.source() + ')'); } }); var arrays = [ [ 3, 4 ], [ 1, 2, [ 3, 4 ] ], [ 5, 6 ], [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], ]; Function(['fn','g'], output)( function (xs) { t.same(arrays.shift(), xs); return xs; }, function (xs) { t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); } ); }); test('Buffer opts.source', function (t) { t.plan(5); var src = Buffer('(function () {' + 'var xs = [ 1, 2, [ 3, 4 ] ];' + 'var ys = [ 5, 6 ];' + 'g([ xs, ys ]);' + '})()'); var output = falafel({ source: src }, function (node) { if (node.type === 'ArrayExpression') { node.update('fn(' + node.source() + ')'); } }); var arrays = [ [ 3, 4 ], [ 1, 2, [ 3, 4 ] ], [ 5, 6 ], [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], ]; Function(['fn','g'], output)( function (xs) { t.same(arrays.shift(), xs); return xs; }, function (xs) { t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); } ); }); test('Buffer source', function (t) { t.plan(5); var src = Buffer('(function () {' + 'var xs = [ 1, 2, [ 3, 4 ] ];' + 'var ys = [ 5, 6 ];' + 'g([ xs, ys ]);' + '})()'); var output = falafel(src, function (node) { if (node.type === 'ArrayExpression') { node.update('fn(' + node.source() + ')'); } }); var arrays = [ [ 3, 4 ], [ 1, 2, [ 3, 4 ] ], [ 5, 6 ], [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], ]; Function(['fn','g'], output)( function (xs) { t.same(arrays.shift(), xs); return xs; }, function (xs) { t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); } ); }); ```
/content/code_sandbox/node_modules/falafel/test/opts.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,059
```javascript "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; const events_1 = require("events"); const debug_1 = __importDefault(require("debug")); const promisify_1 = __importDefault(require("./promisify")); const debug = debug_1.default('agent-base'); function isAgent(v) { return Boolean(v) && typeof v.addRequest === 'function'; } function isSecureEndpoint() { const { stack } = new Error(); if (typeof stack !== 'string') return false; return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); } function createAgent(callback, opts) { return new createAgent.Agent(callback, opts); } (function (createAgent) { /** * Base `http.Agent` implementation. * No pooling/keep-alive is implemented by default. * * @param {Function} callback * @api public */ class Agent extends events_1.EventEmitter { constructor(callback, _opts) { super(); let opts = _opts; if (typeof callback === 'function') { this.callback = callback; } else if (callback) { opts = callback; } // Timeout for the socket to be returned from the callback this.timeout = null; if (opts && typeof opts.timeout === 'number') { this.timeout = opts.timeout; } // These aren't actually used by `agent-base`, but are required // for the TypeScript definition files in `@types/node` :/ this.maxFreeSockets = 1; this.maxSockets = 1; this.maxTotalSockets = Infinity; this.sockets = {}; this.freeSockets = {}; this.requests = {}; this.options = {}; } get defaultPort() { if (typeof this.explicitDefaultPort === 'number') { return this.explicitDefaultPort; } return isSecureEndpoint() ? 443 : 80; } set defaultPort(v) { this.explicitDefaultPort = v; } get protocol() { if (typeof this.explicitProtocol === 'string') { return this.explicitProtocol; } return isSecureEndpoint() ? 'https:' : 'http:'; } set protocol(v) { this.explicitProtocol = v; } callback(req, opts, fn) { throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); } /** * Called by node-core's "_http_client.js" module when creating * a new HTTP request with this Agent instance. * * @api public */ addRequest(req, _opts) { const opts = Object.assign({}, _opts); if (typeof opts.secureEndpoint !== 'boolean') { opts.secureEndpoint = isSecureEndpoint(); } if (opts.host == null) { opts.host = 'localhost'; } if (opts.port == null) { opts.port = opts.secureEndpoint ? 443 : 80; } if (opts.protocol == null) { opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; } if (opts.host && opts.path) { // If both a `host` and `path` are specified then it's most // likely the result of a `url.parse()` call... we need to // remove the `path` portion so that `net.connect()` doesn't // attempt to open that as a unix socket file. delete opts.path; } delete opts.agent; delete opts.hostname; delete opts._defaultAgent; delete opts.defaultPort; delete opts.createConnection; // Hint to use "Connection: close" // XXX: non-documented `http` module API :( req._last = true; req.shouldKeepAlive = false; let timedOut = false; let timeoutId = null; const timeoutMs = opts.timeout || this.timeout; const onerror = (err) => { if (req._hadError) return; req.emit('error', err); // For Safety. Some additional errors might fire later on // and we need to make sure we don't double-fire the error event. req._hadError = true; }; const ontimeout = () => { timeoutId = null; timedOut = true; const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); err.code = 'ETIMEOUT'; onerror(err); }; const callbackError = (err) => { if (timedOut) return; if (timeoutId !== null) { clearTimeout(timeoutId); timeoutId = null; } onerror(err); }; const onsocket = (socket) => { if (timedOut) return; if (timeoutId != null) { clearTimeout(timeoutId); timeoutId = null; } if (isAgent(socket)) { // `socket` is actually an `http.Agent` instance, so // relinquish responsibility for this `req` to the Agent // from here on debug('Callback returned another Agent instance %o', socket.constructor.name); socket.addRequest(req, opts); return; } if (socket) { socket.once('free', () => { this.freeSocket(socket, opts); }); req.onSocket(socket); return; } const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); onerror(err); }; if (typeof this.callback !== 'function') { onerror(new Error('`callback` is not defined')); return; } if (!this.promisifiedCallback) { if (this.callback.length >= 3) { debug('Converting legacy callback function to promise'); this.promisifiedCallback = promisify_1.default(this.callback); } else { this.promisifiedCallback = this.callback; } } if (typeof timeoutMs === 'number' && timeoutMs > 0) { timeoutId = setTimeout(ontimeout, timeoutMs); } if ('port' in opts && typeof opts.port !== 'number') { opts.port = Number(opts.port); } try { debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); } catch (err) { Promise.reject(err).catch(callbackError); } } freeSocket(socket, opts) { debug('Freeing socket %o %o', socket.constructor.name, opts); socket.destroy(); } destroy() { debug('Destroying agent %o', this.constructor.name); } } createAgent.Agent = Agent; // So that `instanceof` works correctly createAgent.prototype = createAgent.Agent.prototype; })(createAgent || (createAgent = {})); module.exports = createAgent; //# sourceMappingURL=index.js.map ```
/content/code_sandbox/node_modules/agent-base/dist/src/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,586
```javascript "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function promisify(fn) { return function (req, opts) { return new Promise((resolve, reject) => { fn.call(this, req, opts, (err, rtn) => { if (err) { reject(err); } else { resolve(rtn); } }); }); }; } exports.default = promisify; //# sourceMappingURL=promisify.js.map ```
/content/code_sandbox/node_modules/agent-base/dist/src/promisify.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
100
```javascript if (parseInt(process.versions.node.split('.')[0]) < 6) throw new Error('vm2 requires Node.js version 6 or newer.'); module.exports = require('./lib/main'); ```
/content/code_sandbox/node_modules/vm2/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
39
```javascript module.exports = { env: { es6: true, node: true }, extends: [ 'integromat' ], parserOptions: { 'ecmaVersion': 2017, 'ecmaFeatures': { 'globalReturn': true } }, globals: { }, rules: { } }; ```
/content/code_sandbox/node_modules/vm2/.eslintrc.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
83
```javascript 'use strict'; const pa = require('path'); const {NodeVM, VMError} = require('../'); if (process.argv[2]) { const path = pa.resolve(process.argv[2]); console.log(`\x1B[90m[vm] creating VM for ${path}\x1B[39m`); const started = Date.now(); try { NodeVM.file(path, { verbose: true, require: { external: true } }); console.log(`\x1B[90m[vm] VM completed in ${Date.now() - started}ms\x1B[39m`); } catch (ex) { if (ex instanceof VMError) { console.error(`\x1B[31m[vm:error] ${ex.message}\x1B[39m`); } else { const {stack} = ex; if (stack) { console.error(`\x1B[31m[vm:error] ${stack}\x1B[39m`); } else { console.error(`\x1B[31m[vm:error] ${ex}\x1B[39m`); } } } } ```
/content/code_sandbox/node_modules/vm2/lib/cli.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
261
```javascript 'use strict'; const {Script} = require('vm'); const { lookupCompiler, removeShebang } = require('./compiler'); const { transformer } = require('./transformer'); const objectDefineProperties = Object.defineProperties; const MODULE_PREFIX = '(function (exports, require, module, __filename, __dirname) { '; const STRICT_MODULE_PREFIX = MODULE_PREFIX + '"use strict"; '; const MODULE_SUFFIX = '\n});'; /** * Class Script * * @public */ class VMScript { /** * The script code with wrapping. If set will invalidate the cache.<br> * Writable only for backwards compatibility. * * @public * @readonly * @member {string} code * @memberOf VMScript# */ /** * The filename used for this script. * * @public * @readonly * @since v3.9.0 * @member {string} filename * @memberOf VMScript# */ /** * The line offset use for stack traces. * * @public * @readonly * @since v3.9.0 * @member {number} lineOffset * @memberOf VMScript# */ /** * The column offset use for stack traces. * * @public * @readonly * @since v3.9.0 * @member {number} columnOffset * @memberOf VMScript# */ /** * The compiler to use to get the JavaScript code. * * @public * @readonly * @since v3.9.0 * @member {(string|compileCallback)} compiler * @memberOf VMScript# */ /** * The prefix for the script. * * @private * @member {string} _prefix * @memberOf VMScript# */ /** * The suffix for the script. * * @private * @member {string} _suffix * @memberOf VMScript# */ /** * The compiled vm.Script for the VM or if not compiled <code>null</code>. * * @private * @member {?vm.Script} _compiledVM * @memberOf VMScript# */ /** * The compiled vm.Script for the NodeVM or if not compiled <code>null</code>. * * @private * @member {?vm.Script} _compiledNodeVM * @memberOf VMScript# */ /** * The compiled vm.Script for the NodeVM in strict mode or if not compiled <code>null</code>. * * @private * @member {?vm.Script} _compiledNodeVMStrict * @memberOf VMScript# */ /** * The resolved compiler to use to get the JavaScript code. * * @private * @readonly * @member {compileCallback} _compiler * @memberOf VMScript# */ /** * The script to run without wrapping. * * @private * @member {string} _code * @memberOf VMScript# */ /** * Whether or not the script contains async functions. * * @private * @member {boolean} _hasAsync * @memberOf VMScript# */ /** * Create VMScript instance. * * @public * @param {string} code - Code to run. * @param {(string|Object)} [options] - Options map or filename. * @param {string} [options.filename="vm.js"] - Filename that shows up in any stack traces produced from this script. * @param {number} [options.lineOffset=0] - Passed to vm.Script options. * @param {number} [options.columnOffset=0] - Passed to vm.Script options. * @param {(string|compileCallback)} [options.compiler="javascript"] - The compiler to use. * @throws {VMError} If the compiler is unknown or if coffee-script was requested but the module not found. */ constructor(code, options) { const sCode = `${code}`; let useFileName; let useOptions; if (arguments.length === 2) { if (typeof options === 'object') { useOptions = options || {__proto__: null}; useFileName = useOptions.filename; } else { useOptions = {__proto__: null}; useFileName = options; } } else if (arguments.length > 2) { // We do it this way so that there are no more arguments in the function. // eslint-disable-next-line prefer-rest-params useOptions = arguments[2] || {__proto__: null}; useFileName = options || useOptions.filename; } else { useOptions = {__proto__: null}; } const { compiler = 'javascript', lineOffset = 0, columnOffset = 0 } = useOptions; // Throw if the compiler is unknown. const resolvedCompiler = lookupCompiler(compiler); objectDefineProperties(this, { __proto__: null, code: { __proto__: null, // Put this here so that it is enumerable, and looks like a property. get() { return this._prefix + this._code + this._suffix; }, set(value) { const strNewCode = String(value); if (strNewCode === this._code && this._prefix === '' && this._suffix === '') return; this._code = strNewCode; this._prefix = ''; this._suffix = ''; this._compiledVM = null; this._compiledNodeVM = null; this._compiledCode = null; }, enumerable: true }, filename: { __proto__: null, value: useFileName || 'vm.js', enumerable: true }, lineOffset: { __proto__: null, value: lineOffset, enumerable: true }, columnOffset: { __proto__: null, value: columnOffset, enumerable: true }, compiler: { __proto__: null, value: compiler, enumerable: true }, _code: { __proto__: null, value: sCode, writable: true }, _prefix: { __proto__: null, value: '', writable: true }, _suffix: { __proto__: null, value: '', writable: true }, _compiledVM: { __proto__: null, value: null, writable: true }, _compiledNodeVM: { __proto__: null, value: null, writable: true }, _compiledNodeVMStrict: { __proto__: null, value: null, writable: true }, _compiledCode: { __proto__: null, value: null, writable: true }, _hasAsync: { __proto__: null, value: false, writable: true }, _compiler: {__proto__: null, value: resolvedCompiler} }); } /** * Wraps the code.<br> * This will replace the old wrapping.<br> * Will invalidate the code cache. * * @public * @deprecated Since v3.9.0. Wrap your code before passing it into the VMScript object. * @param {string} prefix - String that will be appended before the script code. * @param {script} suffix - String that will be appended behind the script code. * @return {this} This for chaining. * @throws {TypeError} If prefix or suffix is a Symbol. */ wrap(prefix, suffix) { const strPrefix = `${prefix}`; const strSuffix = `${suffix}`; if (this._prefix === strPrefix && this._suffix === strSuffix) return this; this._prefix = strPrefix; this._suffix = strSuffix; this._compiledVM = null; this._compiledNodeVM = null; this._compiledNodeVMStrict = null; return this; } /** * Compile this script. <br> * This is useful to detect syntax errors in the script. * * @public * @return {this} This for chaining. * @throws {SyntaxError} If there is a syntax error in the script. */ compile() { this._compileVM(); return this; } /** * Get the compiled code. * * @private * @return {string} The code. */ getCompiledCode() { if (!this._compiledCode) { const comp = this._compiler(this._prefix + removeShebang(this._code) + this._suffix, this.filename); const res = transformer(null, comp, false, false, this.filename); this._compiledCode = res.code; this._hasAsync = res.hasAsync; } return this._compiledCode; } /** * Compiles this script to a vm.Script. * * @private * @param {string} prefix - JavaScript code that will be used as prefix. * @param {string} suffix - JavaScript code that will be used as suffix. * @return {vm.Script} The compiled vm.Script. * @throws {SyntaxError} If there is a syntax error in the script. */ _compile(prefix, suffix) { return new Script(prefix + this.getCompiledCode() + suffix, { __proto__: null, filename: this.filename, displayErrors: false, lineOffset: this.lineOffset, columnOffset: this.columnOffset }); } /** * Will return the cached version of the script intended for VM or compile it. * * @private * @return {vm.Script} The compiled script * @throws {SyntaxError} If there is a syntax error in the script. */ _compileVM() { let script = this._compiledVM; if (!script) { this._compiledVM = script = this._compile('', ''); } return script; } /** * Will return the cached version of the script intended for NodeVM or compile it. * * @private * @return {vm.Script} The compiled script * @throws {SyntaxError} If there is a syntax error in the script. */ _compileNodeVM() { let script = this._compiledNodeVM; if (!script) { this._compiledNodeVM = script = this._compile(MODULE_PREFIX, MODULE_SUFFIX); } return script; } /** * Will return the cached version of the script intended for NodeVM in strict mode or compile it. * * @private * @return {vm.Script} The compiled script * @throws {SyntaxError} If there is a syntax error in the script. */ _compileNodeVMStrict() { let script = this._compiledNodeVMStrict; if (!script) { this._compiledNodeVMStrict = script = this._compile(STRICT_MODULE_PREFIX, MODULE_SUFFIX); } return script; } } exports.MODULE_PREFIX = MODULE_PREFIX; exports.STRICT_MODULE_PREFIX = STRICT_MODULE_PREFIX; exports.MODULE_SUFFIX = MODULE_SUFFIX; exports.VMScript = VMScript; ```
/content/code_sandbox/node_modules/vm2/lib/script.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,580
```javascript 'use strict'; /** * This callback will be called to resolve a module if it couldn't be found. * * @callback resolveCallback * @param {string} moduleName - Name of the module used to resolve. * @param {string} dirname - Name of the current directory. * @return {(string|undefined)} The file or directory to use to load the requested module. */ /** * This callback will be called to require a module instead of node's require. * * @callback customRequire * @param {string} moduleName - Name of the module requested. * @return {*} The required module object. */ const fs = require('fs'); const pa = require('path'); const { Script } = require('vm'); const { VMError } = require('./bridge'); const { VMScript, MODULE_PREFIX, STRICT_MODULE_PREFIX, MODULE_SUFFIX } = require('./script'); const { transformer } = require('./transformer'); const { VM } = require('./vm'); const { resolverFromOptions } = require('./resolver-compat'); const objectDefineProperty = Object.defineProperty; const objectDefineProperties = Object.defineProperties; /** * Host objects * * @private */ const HOST = Object.freeze({ __proto__: null, version: parseInt(process.versions.node.split('.')[0]), process, console, setTimeout, setInterval, setImmediate, clearTimeout, clearInterval, clearImmediate }); /** * Compile a script. * * @private * @param {string} filename - Filename of the script. * @param {string} script - Script. * @return {vm.Script} The compiled script. */ function compileScript(filename, script) { return new Script(script, { __proto__: null, filename, displayErrors: false }); } let cacheSandboxScript = null; let cacheMakeNestingScript = null; const NESTING_OVERRIDE = Object.freeze({ __proto__: null, vm2: vm2NestingLoader }); /** * Event caused by a <code>console.debug</code> call if <code>options.console="redirect"</code> is specified. * * @public * @event NodeVM."console.debug" * @type {...*} */ /** * Event caused by a <code>console.log</code> call if <code>options.console="redirect"</code> is specified. * * @public * @event NodeVM."console.log" * @type {...*} */ /** * Event caused by a <code>console.info</code> call if <code>options.console="redirect"</code> is specified. * * @public * @event NodeVM."console.info" * @type {...*} */ /** * Event caused by a <code>console.warn</code> call if <code>options.console="redirect"</code> is specified. * * @public * @event NodeVM."console.warn" * @type {...*} */ /** * Event caused by a <code>console.error</code> call if <code>options.console="redirect"</code> is specified. * * @public * @event NodeVM."console.error" * @type {...*} */ /** * Event caused by a <code>console.dir</code> call if <code>options.console="redirect"</code> is specified. * * @public * @event NodeVM."console.dir" * @type {...*} */ /** * Event caused by a <code>console.trace</code> call if <code>options.console="redirect"</code> is specified. * * @public * @event NodeVM."console.trace" * @type {...*} */ /** * Class NodeVM. * * @public * @extends {VM} * @extends {EventEmitter} */ class NodeVM extends VM { /** * Create a new NodeVM instance.<br> * * Unlike VM, NodeVM lets you use require same way like in regular node.<br> * * However, it does not use the timeout. * * @public * @param {Object} [options] - VM options. * @param {Object} [options.sandbox] - Objects that will be copied into the global object of the sandbox. * @param {(string|compileCallback)} [options.compiler="javascript"] - The compiler to use. * @param {boolean} [options.eval=true] - Allow the dynamic evaluation of code via eval(code) or Function(code)().<br> * Only available for node v10+. * @param {boolean} [options.wasm=true] - Allow to run wasm code.<br> * Only available for node v10+. * @param {("inherit"|"redirect"|"off")} [options.console="inherit"] - Sets the behavior of the console in the sandbox. * <code>inherit</code> to enable console, <code>redirect</code> to redirect to events, <code>off</code> to disable console. * @param {Object|boolean} [options.require=false] - Allow require inside the sandbox. * @param {(boolean|string[]|Object)} [options.require.external=false] - <b>WARNING: When allowing require the option <code>options.require.root</code> * should be set to restrict the script from requiring any module. Values can be true, an array of allowed external modules or an object. * @param {(string[])} [options.require.external.modules] - Array of allowed external modules. Also supports wildcards, so specifying ['@scope/*-ver-??], * for instance, will allow using all modules having a name of the form @scope/something-ver-aa, @scope/other-ver-11, etc. * @param {boolean} [options.require.external.transitive=false] - Boolean which indicates if transitive dependencies of external modules are allowed. * @param {string[]} [options.require.builtin=[]] - Array of allowed built-in modules, accepts ["*"] for all. * @param {(string|string[])} [options.require.root] - Restricted path(s) where local modules can be required. If omitted every path is allowed. * @param {Object} [options.require.mock] - Collection of mock modules (both external or built-in). * @param {("host"|"sandbox")} [options.require.context="host"] - <code>host</code> to require modules in host and proxy them to sandbox. * <code>sandbox</code> to load, compile and require modules in sandbox. * Builtin modules except <code>events</code> always required in host and proxied to sandbox. * @param {string[]} [options.require.import] - Array of modules to be loaded into NodeVM on start. * @param {resolveCallback} [options.require.resolve] - An additional lookup function in case a module wasn't * found in one of the traditional node lookup paths. * @param {customRequire} [options.require.customRequire=require] - Custom require to require host and built-in modules. * @param {boolean} [options.nesting=false] - * <b>WARNING: Allowing this is a security risk as scripts can create a NodeVM which can require any host module.</b> * Allow nesting of VMs. * @param {("commonjs"|"none")} [options.wrapper="commonjs"] - <code>commonjs</code> to wrap script into CommonJS wrapper, * <code>none</code> to retrieve value returned by the script. * @param {string[]} [options.sourceExtensions=["js"]] - Array of file extensions to treat as source code. * @param {string[]} [options.argv=[]] - Array of arguments passed to <code>process.argv</code>. * This object will not be copied and the script can change this object. * @param {Object} [options.env={}] - Environment map passed to <code>process.env</code>. * This object will not be copied and the script can change this object. * @param {boolean} [options.strict=false] - If modules should be loaded in strict mode. * @throws {VMError} If the compiler is unknown. */ constructor(options = {}) { const { compiler, eval: allowEval, wasm, console: consoleType = 'inherit', require: requireOpts = false, nesting = false, wrapper = 'commonjs', sourceExtensions = ['js'], argv, env, strict = false, sandbox } = options; // Throw this early if (sandbox && 'object' !== typeof sandbox) { throw new VMError('Sandbox must be an object.'); } super({__proto__: null, compiler: compiler, eval: allowEval, wasm}); // This is only here for backwards compatibility. objectDefineProperty(this, 'options', {__proto__: null, value: { console: consoleType, require: requireOpts, nesting, wrapper, sourceExtensions, strict }}); const resolver = resolverFromOptions(this, requireOpts, nesting && NESTING_OVERRIDE, this._compiler); objectDefineProperty(this, '_resolver', {__proto__: null, value: resolver}); if (!cacheSandboxScript) { cacheSandboxScript = compileScript(`${__dirname}/setup-node-sandbox.js`, `(function (host, data) { ${fs.readFileSync(`${__dirname}/setup-node-sandbox.js`, 'utf8')}\n})`); } const closure = this._runScript(cacheSandboxScript); const extensions = { __proto__: null }; const loadJS = (mod, filename) => resolver.loadJS(this, mod, filename); for (let i = 0; i < sourceExtensions.length; i++) { extensions['.' + sourceExtensions[i]] = loadJS; } if (!extensions['.json']) extensions['.json'] = (mod, filename) => resolver.loadJSON(this, mod, filename); if (!extensions['.node']) extensions['.node'] = (mod, filename) => resolver.loadNode(this, mod, filename); this.readonly(HOST); this.readonly(resolver); this.readonly(this); const { Module, jsonParse, createRequireForModule, requireImpl } = closure(HOST, { __proto__: null, argv, env, console: consoleType, vm: this, resolver, extensions }); objectDefineProperties(this, { __proto__: null, _Module: {__proto__: null, value: Module}, _jsonParse: {__proto__: null, value: jsonParse}, _createRequireForModule: {__proto__: null, value: createRequireForModule}, _requireImpl: {__proto__: null, value: requireImpl}, _cacheRequireModule: {__proto__: null, value: null, writable: true} }); resolver.init(this); // prepare global sandbox if (sandbox) { this.setGlobals(sandbox); } if (requireOpts && requireOpts.import) { if (Array.isArray(requireOpts.import)) { for (let i = 0, l = requireOpts.import.length; i < l; i++) { this.require(requireOpts.import[i]); } } else { this.require(requireOpts.import); } } } /** * @ignore * @deprecated Just call the method yourself like <code>method(args);</code> * @param {function} method - Function to invoke. * @param {...*} args - Arguments to pass to the function. * @return {*} Return value of the function. * @todo Can we remove this function? It even had a bug that would use args as this parameter. * @throws {*} Rethrows anything the method throws. * @throws {VMError} If method is not a function. * @throws {Error} If method is a class. */ call(method, ...args) { if ('function' === typeof method) { return method(...args); } else { throw new VMError('Unrecognized method type.'); } } /** * Require a module in VM and return it's exports. * * @public * @param {string} module - Module name. * @return {*} Exported module. * @throws {*} If the module couldn't be found or loading it threw an error. */ require(module) { const path = this._resolver.pathResolve('.'); let mod = this._cacheRequireModule; if (!mod || mod.path !== path) { const filename = this._resolver.pathConcat(path, '/vm.js'); mod = new (this._Module)(filename, path); this._resolver.registerModule(mod, filename, path, null, false); this._cacheRequireModule = mod; } return this._requireImpl(mod, module, true); } /** * Run the code in NodeVM. * * First time you run this method, code is executed same way like in node's regular `require` - it's executed with * `module`, `require`, `exports`, `__dirname`, `__filename` variables and expect result in `module.exports'. * * @param {(string|VMScript)} code - Code to run. * @param {(string|Object)} [options] - Options map or filename. * @param {string} [options.filename="vm.js"] - Filename that shows up in any stack traces produced from this script.<br> * This is only used if code is a String. * @param {boolean} [options.strict] - If modules should be loaded in strict mode. Defaults to NodeVM options. * @param {("commonjs"|"none")} [options.wrapper] - <code>commonjs</code> to wrap script into CommonJS wrapper, * <code>none</code> to retrieve value returned by the script. Defaults to NodeVM options. * @return {*} Result of executed code. * @throws {SyntaxError} If there is a syntax error in the script. * @throws {*} If the script execution terminated with an exception it is propagated. * @fires NodeVM."console.debug" * @fires NodeVM."console.log" * @fires NodeVM."console.info" * @fires NodeVM."console.warn" * @fires NodeVM."console.error" * @fires NodeVM."console.dir" * @fires NodeVM."console.trace" */ run(code, options) { let script; let filename; if (typeof options === 'object') { filename = options.filename; } else { filename = options; options = {__proto__: null}; } const { strict = this.options.strict, wrapper = this.options.wrapper, module: customModule, require: customRequire, dirname: customDirname = null } = options; let sandboxModule = customModule; let dirname = customDirname; if (code instanceof VMScript) { script = strict ? code._compileNodeVMStrict() : code._compileNodeVM(); if (!sandboxModule) { const resolvedFilename = this._resolver.pathResolve(code.filename); dirname = this._resolver.pathDirname(resolvedFilename); sandboxModule = new (this._Module)(resolvedFilename, dirname); this._resolver.registerModule(sandboxModule, resolvedFilename, dirname, null, false); } } else { const unresolvedFilename = filename || 'vm.js'; if (!sandboxModule) { if (filename) { const resolvedFilename = this._resolver.pathResolve(filename); dirname = this._resolver.pathDirname(resolvedFilename); sandboxModule = new (this._Module)(resolvedFilename, dirname); this._resolver.registerModule(sandboxModule, resolvedFilename, dirname, null, false); } else { sandboxModule = new (this._Module)(null, null); sandboxModule.id = unresolvedFilename; } } const prefix = strict ? STRICT_MODULE_PREFIX : MODULE_PREFIX; let scriptCode = this._compiler(code, unresolvedFilename); scriptCode = transformer(null, scriptCode, false, false, unresolvedFilename).code; script = new Script(prefix + scriptCode + MODULE_SUFFIX, { __proto__: null, filename: unresolvedFilename, displayErrors: false }); } const closure = this._runScript(script); const usedRequire = customRequire || this._createRequireForModule(sandboxModule); const ret = Reflect.apply(closure, this.sandbox, [sandboxModule.exports, usedRequire, sandboxModule, filename, dirname]); return wrapper === 'commonjs' ? sandboxModule.exports : ret; } /** * Create NodeVM and run code inside it. * * @public * @static * @param {string} script - Code to execute. * @param {string} [filename] - File name (used in stack traces only). * @param {Object} [options] - VM options. * @param {string} [options.filename] - File name (used in stack traces only). Used if <code>filename</code> is omitted. * @return {*} Result of executed code. * @see {@link NodeVM} for the options. * @throws {SyntaxError} If there is a syntax error in the script. * @throws {*} If the script execution terminated with an exception it is propagated. */ static code(script, filename, options) { let unresolvedFilename; if (filename != null) { if ('object' === typeof filename) { options = filename; unresolvedFilename = options.filename; } else if ('string' === typeof filename) { unresolvedFilename = filename; } else { throw new VMError('Invalid arguments.'); } } else if ('object' === typeof options) { unresolvedFilename = options.filename; } if (arguments.length > 3) { throw new VMError('Invalid number of arguments.'); } const resolvedFilename = typeof unresolvedFilename === 'string' ? pa.resolve(unresolvedFilename) : undefined; return new NodeVM(options).run(script, resolvedFilename); } /** * Create NodeVM and run script from file inside it. * * @public * @static * @param {string} filename - Filename of file to load and execute in a NodeVM. * @param {Object} [options] - NodeVM options. * @return {*} Result of executed code. * @see {@link NodeVM} for the options. * @throws {Error} If filename is not a valid filename. * @throws {SyntaxError} If there is a syntax error in the script. * @throws {*} If the script execution terminated with an exception it is propagated. */ static file(filename, options) { const resolvedFilename = pa.resolve(filename); if (!fs.existsSync(resolvedFilename)) { throw new VMError(`Script '${filename}' not found.`); } if (fs.statSync(resolvedFilename).isDirectory()) { throw new VMError('Script must be file, got directory.'); } return new NodeVM(options).run(fs.readFileSync(resolvedFilename, 'utf8'), resolvedFilename); } } function vm2NestingLoader(resolver, vm, id) { if (!cacheMakeNestingScript) { cacheMakeNestingScript = compileScript('nesting.js', '(vm, nodevm) => ({VM: vm, NodeVM: nodevm})'); } const makeNesting = vm._runScript(cacheMakeNestingScript); return makeNesting(vm.readonly(VM), vm.readonly(NodeVM)); } exports.NodeVM = NodeVM; ```
/content/code_sandbox/node_modules/vm2/lib/nodevm.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
4,342
```javascript 'use strict'; /** * __ ___ ____ _ _ ___ _ _ ____ * \ \ / / \ | _ \| \ | |_ _| \ | |/ ___| * \ \ /\ / / _ \ | |_) | \| || || \| | | _ * \ V V / ___ \| _ <| |\ || || |\ | |_| | * \_/\_/_/ \_\_| \_\_| \_|___|_| \_|\____| * * This file is critical for vm2. It implements the bridge between the host and the sandbox. * If you do not know exactly what you are doing, you should NOT edit this file. * * The file is loaded in the host and sandbox to handle objects in both directions. * This is done to ensure that RangeErrors are from the correct context. * The boundary between the sandbox and host might throw RangeErrors from both contexts. * Therefore, thisFromOther and friends can handle objects from both domains. * * Method parameters have comments to tell from which context they came. * */ const globalsList = [ 'Number', 'String', 'Boolean', 'Date', 'RegExp', 'Map', 'WeakMap', 'Set', 'WeakSet', 'Promise', 'Function' ]; const errorsList = [ 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'EvalError', 'URIError', 'Error' ]; const OPNA = 'Operation not allowed on contextified object.'; const thisGlobalPrototypes = { __proto__: null, Object: Object.prototype, Array: Array.prototype }; for (let i = 0; i < globalsList.length; i++) { const key = globalsList[i]; const g = global[key]; if (g) thisGlobalPrototypes[key] = g.prototype; } for (let i = 0; i < errorsList.length; i++) { const key = errorsList[i]; const g = global[key]; if (g) thisGlobalPrototypes[key] = g.prototype; } const { getPrototypeOf: thisReflectGetPrototypeOf, setPrototypeOf: thisReflectSetPrototypeOf, defineProperty: thisReflectDefineProperty, deleteProperty: thisReflectDeleteProperty, getOwnPropertyDescriptor: thisReflectGetOwnPropertyDescriptor, isExtensible: thisReflectIsExtensible, preventExtensions: thisReflectPreventExtensions, apply: thisReflectApply, construct: thisReflectConstruct, set: thisReflectSet, get: thisReflectGet, has: thisReflectHas, ownKeys: thisReflectOwnKeys, enumerate: thisReflectEnumerate, } = Reflect; const thisObject = Object; const { freeze: thisObjectFreeze, prototype: thisObjectPrototype } = thisObject; const thisObjectHasOwnProperty = thisObjectPrototype.hasOwnProperty; const ThisProxy = Proxy; const ThisWeakMap = WeakMap; const { get: thisWeakMapGet, set: thisWeakMapSet } = ThisWeakMap.prototype; const ThisMap = Map; const thisMapGet = ThisMap.prototype.get; const thisMapSet = ThisMap.prototype.set; const thisFunction = Function; const thisFunctionBind = thisFunction.prototype.bind; const thisArrayIsArray = Array.isArray; const thisErrorCaptureStackTrace = Error.captureStackTrace; const thisSymbolToString = Symbol.prototype.toString; const thisSymbolToStringTag = Symbol.toStringTag; const thisSymbolIterator = Symbol.iterator; const thisSymbolNodeJSUtilInspectCustom = Symbol.for('nodejs.util.inspect.custom'); /** * VMError. * * @public * @extends {Error} */ class VMError extends Error { /** * Create VMError instance. * * @public * @param {string} message - Error message. * @param {string} code - Error code. */ constructor(message, code) { super(message); this.name = 'VMError'; this.code = code; thisErrorCaptureStackTrace(this, this.constructor); } } thisGlobalPrototypes['VMError'] = VMError.prototype; function thisUnexpected() { return new VMError('Unexpected'); } if (!thisReflectSetPrototypeOf(exports, null)) throw thisUnexpected(); function thisSafeGetOwnPropertyDescriptor(obj, key) { const desc = thisReflectGetOwnPropertyDescriptor(obj, key); if (!desc) return desc; if (!thisReflectSetPrototypeOf(desc, null)) throw thisUnexpected(); return desc; } function thisThrowCallerCalleeArgumentsAccess(key) { 'use strict'; thisThrowCallerCalleeArgumentsAccess[key]; return thisUnexpected(); } function thisIdMapping(factory, other) { return other; } const thisThrowOnKeyAccessHandler = thisObjectFreeze({ __proto__: null, get(target, key, receiver) { if (typeof key === 'symbol') { key = thisReflectApply(thisSymbolToString, key, []); } throw new VMError(`Unexpected access to key '${key}'`); } }); const emptyForzenObject = thisObjectFreeze({ __proto__: null }); const thisThrowOnKeyAccess = new ThisProxy(emptyForzenObject, thisThrowOnKeyAccessHandler); function SafeBase() {} if (!thisReflectDefineProperty(SafeBase, 'prototype', { __proto__: null, value: thisThrowOnKeyAccess })) throw thisUnexpected(); function SHARED_FUNCTION() {} const TEST_PROXY_HANDLER = thisObjectFreeze({ __proto__: thisThrowOnKeyAccess, construct() { return this; } }); function thisIsConstructor(obj) { // Note: obj@any(unsafe) const Func = new ThisProxy(obj, TEST_PROXY_HANDLER); try { // eslint-disable-next-line no-new new Func(); return true; } catch (e) { return false; } } function thisCreateTargetObject(obj, proto) { // Note: obj@any(unsafe) proto@any(unsafe) returns@this(unsafe) throws@this(unsafe) let base; if (typeof obj === 'function') { if (thisIsConstructor(obj)) { // Bind the function since bound functions do not have a prototype property. base = thisReflectApply(thisFunctionBind, SHARED_FUNCTION, [null]); } else { base = () => {}; } } else if (thisArrayIsArray(obj)) { base = []; } else { return {__proto__: proto}; } if (!thisReflectSetPrototypeOf(base, proto)) throw thisUnexpected(); return base; } function createBridge(otherInit, registerProxy) { const mappingOtherToThis = new ThisWeakMap(); const protoMappings = new ThisMap(); const protoName = new ThisMap(); function thisAddProtoMapping(proto, other, name) { // Note: proto@this(unsafe) other@other(unsafe) name@this(unsafe) throws@this(unsafe) thisReflectApply(thisMapSet, protoMappings, [proto, thisIdMapping]); thisReflectApply(thisMapSet, protoMappings, [other, (factory, object) => thisProxyOther(factory, object, proto)]); if (name) thisReflectApply(thisMapSet, protoName, [proto, name]); } function thisAddProtoMappingFactory(protoFactory, other, name) { // Note: protoFactory@this(unsafe) other@other(unsafe) name@this(unsafe) throws@this(unsafe) let proto; thisReflectApply(thisMapSet, protoMappings, [other, (factory, object) => { if (!proto) { proto = protoFactory(); thisReflectApply(thisMapSet, protoMappings, [proto, thisIdMapping]); if (name) thisReflectApply(thisMapSet, protoName, [proto, name]); } return thisProxyOther(factory, object, proto); }]); } const result = { __proto__: null, globalPrototypes: thisGlobalPrototypes, safeGetOwnPropertyDescriptor: thisSafeGetOwnPropertyDescriptor, fromArguments: thisFromOtherArguments, from: thisFromOther, fromWithFactory: thisFromOtherWithFactory, ensureThis: thisEnsureThis, mapping: mappingOtherToThis, connect: thisConnect, reflectSet: thisReflectSet, reflectGet: thisReflectGet, reflectDefineProperty: thisReflectDefineProperty, reflectDeleteProperty: thisReflectDeleteProperty, reflectApply: thisReflectApply, reflectConstruct: thisReflectConstruct, reflectHas: thisReflectHas, reflectOwnKeys: thisReflectOwnKeys, reflectEnumerate: thisReflectEnumerate, reflectGetPrototypeOf: thisReflectGetPrototypeOf, reflectIsExtensible: thisReflectIsExtensible, reflectPreventExtensions: thisReflectPreventExtensions, objectHasOwnProperty: thisObjectHasOwnProperty, weakMapSet: thisWeakMapSet, addProtoMapping: thisAddProtoMapping, addProtoMappingFactory: thisAddProtoMappingFactory, defaultFactory, protectedFactory, readonlyFactory, VMError }; const isHost = typeof otherInit !== 'object'; if (isHost) { otherInit = otherInit(result, registerProxy); } result.other = otherInit; const { globalPrototypes: otherGlobalPrototypes, safeGetOwnPropertyDescriptor: otherSafeGetOwnPropertyDescriptor, fromArguments: otherFromThisArguments, from: otherFromThis, mapping: mappingThisToOther, reflectSet: otherReflectSet, reflectGet: otherReflectGet, reflectDefineProperty: otherReflectDefineProperty, reflectDeleteProperty: otherReflectDeleteProperty, reflectApply: otherReflectApply, reflectConstruct: otherReflectConstruct, reflectHas: otherReflectHas, reflectOwnKeys: otherReflectOwnKeys, reflectEnumerate: otherReflectEnumerate, reflectGetPrototypeOf: otherReflectGetPrototypeOf, reflectIsExtensible: otherReflectIsExtensible, reflectPreventExtensions: otherReflectPreventExtensions, objectHasOwnProperty: otherObjectHasOwnProperty, weakMapSet: otherWeakMapSet } = otherInit; function thisOtherHasOwnProperty(object, key) { // Note: object@other(safe) key@prim throws@this(unsafe) try { return otherReflectApply(otherObjectHasOwnProperty, object, [key]) === true; } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } } function thisDefaultGet(handler, object, key, desc) { // Note: object@other(unsafe) key@prim desc@other(safe) let ret; // @other(unsafe) if (desc.get || desc.set) { const getter = desc.get; if (!getter) return undefined; try { ret = otherReflectApply(getter, object, [key]); } catch (e) { throw thisFromOtherForThrow(e); } } else { ret = desc.value; } return handler.fromOtherWithContext(ret); } function otherFromThisIfAvailable(to, from, key) { // Note: to@other(safe) from@this(safe) key@prim throws@this(unsafe) if (!thisReflectApply(thisObjectHasOwnProperty, from, [key])) return false; try { to[key] = otherFromThis(from[key]); } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } return true; } class BaseHandler extends SafeBase { constructor(object) { // Note: object@other(unsafe) throws@this(unsafe) super(); this.objectWrapper = () => object; } getObject() { return this.objectWrapper(); } getFactory() { return defaultFactory; } fromOtherWithContext(other) { // Note: other@other(unsafe) throws@this(unsafe) return thisFromOtherWithFactory(this.getFactory(), other); } doPreventExtensions(target, object, factory) { // Note: target@this(unsafe) object@other(unsafe) throws@this(unsafe) let keys; // @other(safe-array-of-prim) try { keys = otherReflectOwnKeys(object); } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } for (let i = 0; i < keys.length; i++) { const key = keys[i]; // @prim let desc; try { desc = otherSafeGetOwnPropertyDescriptor(object, key); } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } if (!desc) continue; if (!desc.configurable) { const current = thisSafeGetOwnPropertyDescriptor(target, key); if (current && !current.configurable) continue; if (desc.get || desc.set) { desc.get = this.fromOtherWithContext(desc.get); desc.set = this.fromOtherWithContext(desc.set); } else if (typeof object === 'function' && (key === 'caller' || key === 'callee' || key === 'arguments')) { desc.value = null; } else { desc.value = this.fromOtherWithContext(desc.value); } } else { if (desc.get || desc.set) { desc = { __proto__: null, configurable: true, enumerable: desc.enumerable, writable: true, value: null }; } else { desc.value = null; } } if (!thisReflectDefineProperty(target, key, desc)) throw thisUnexpected(); } if (!thisReflectPreventExtensions(target)) throw thisUnexpected(); } get(target, key, receiver) { // Note: target@this(unsafe) key@prim receiver@this(unsafe) throws@this(unsafe) const object = this.getObject(); // @other(unsafe) switch (key) { case 'constructor': { const desc = otherSafeGetOwnPropertyDescriptor(object, key); if (desc) return thisDefaultGet(this, object, key, desc); const proto = thisReflectGetPrototypeOf(target); return proto === null ? undefined : proto.constructor; } case '__proto__': { const desc = otherSafeGetOwnPropertyDescriptor(object, key); if (desc) return thisDefaultGet(this, object, key, desc); return thisReflectGetPrototypeOf(target); } case thisSymbolToStringTag: if (!thisOtherHasOwnProperty(object, thisSymbolToStringTag)) { const proto = thisReflectGetPrototypeOf(target); const name = thisReflectApply(thisMapGet, protoName, [proto]); if (name) return name; } break; case 'arguments': case 'caller': case 'callee': if (typeof object === 'function' && thisOtherHasOwnProperty(object, key)) { throw thisThrowCallerCalleeArgumentsAccess(key); } break; } let ret; // @other(unsafe) try { ret = otherReflectGet(object, key); } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } return this.fromOtherWithContext(ret); } set(target, key, value, receiver) { // Note: target@this(unsafe) key@prim value@this(unsafe) receiver@this(unsafe) throws@this(unsafe) const object = this.getObject(); // @other(unsafe) if (key === '__proto__' && !thisOtherHasOwnProperty(object, key)) { return this.setPrototypeOf(target, value); } try { value = otherFromThis(value); return otherReflectSet(object, key, value) === true; } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } } getPrototypeOf(target) { // Note: target@this(unsafe) return thisReflectGetPrototypeOf(target); } setPrototypeOf(target, value) { // Note: target@this(unsafe) throws@this(unsafe) throw new VMError(OPNA); } apply(target, context, args) { // Note: target@this(unsafe) context@this(unsafe) args@this(safe-array) throws@this(unsafe) const object = this.getObject(); // @other(unsafe) let ret; // @other(unsafe) try { context = otherFromThis(context); args = otherFromThisArguments(args); ret = otherReflectApply(object, context, args); } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } return thisFromOther(ret); } construct(target, args, newTarget) { // Note: target@this(unsafe) args@this(safe-array) newTarget@this(unsafe) throws@this(unsafe) const object = this.getObject(); // @other(unsafe) let ret; // @other(unsafe) try { args = otherFromThisArguments(args); ret = otherReflectConstruct(object, args); } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } return thisFromOtherWithFactory(this.getFactory(), ret, thisFromOther(object)); } getOwnPropertyDescriptorDesc(target, prop, desc) { // Note: target@this(unsafe) prop@prim desc@other{safe} throws@this(unsafe) const object = this.getObject(); // @other(unsafe) if (desc && typeof object === 'function' && (prop === 'arguments' || prop === 'caller' || prop === 'callee')) desc.value = null; return desc; } getOwnPropertyDescriptor(target, prop) { // Note: target@this(unsafe) prop@prim throws@this(unsafe) const object = this.getObject(); // @other(unsafe) let desc; // @other(safe) try { desc = otherSafeGetOwnPropertyDescriptor(object, prop); } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } desc = this.getOwnPropertyDescriptorDesc(target, prop, desc); if (!desc) return undefined; let thisDesc; if (desc.get || desc.set) { thisDesc = { __proto__: null, get: this.fromOtherWithContext(desc.get), set: this.fromOtherWithContext(desc.set), enumerable: desc.enumerable === true, configurable: desc.configurable === true }; } else { thisDesc = { __proto__: null, value: this.fromOtherWithContext(desc.value), writable: desc.writable === true, enumerable: desc.enumerable === true, configurable: desc.configurable === true }; } if (!thisDesc.configurable) { const oldDesc = thisSafeGetOwnPropertyDescriptor(target, prop); if (!oldDesc || oldDesc.configurable || oldDesc.writable !== thisDesc.writable) { if (!thisReflectDefineProperty(target, prop, thisDesc)) throw thisUnexpected(); } } return thisDesc; } definePropertyDesc(target, prop, desc) { // Note: target@this(unsafe) prop@prim desc@this(safe) throws@this(unsafe) return desc; } defineProperty(target, prop, desc) { // Note: target@this(unsafe) prop@prim desc@this(unsafe) throws@this(unsafe) const object = this.getObject(); // @other(unsafe) if (!thisReflectSetPrototypeOf(desc, null)) throw thisUnexpected(); desc = this.definePropertyDesc(target, prop, desc); if (!desc) return false; let otherDesc = {__proto__: null}; let hasFunc = true; let hasValue = true; let hasBasic = true; hasFunc &= otherFromThisIfAvailable(otherDesc, desc, 'get'); hasFunc &= otherFromThisIfAvailable(otherDesc, desc, 'set'); hasValue &= otherFromThisIfAvailable(otherDesc, desc, 'value'); hasValue &= otherFromThisIfAvailable(otherDesc, desc, 'writable'); hasBasic &= otherFromThisIfAvailable(otherDesc, desc, 'enumerable'); hasBasic &= otherFromThisIfAvailable(otherDesc, desc, 'configurable'); try { if (!otherReflectDefineProperty(object, prop, otherDesc)) return false; if (otherDesc.configurable !== true && (!hasBasic || !(hasFunc || hasValue))) { otherDesc = otherSafeGetOwnPropertyDescriptor(object, prop); } } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } if (!otherDesc.configurable) { let thisDesc; if (otherDesc.get || otherDesc.set) { thisDesc = { __proto__: null, get: this.fromOtherWithContext(otherDesc.get), set: this.fromOtherWithContext(otherDesc.set), enumerable: otherDesc.enumerable, configurable: otherDesc.configurable }; } else { thisDesc = { __proto__: null, value: this.fromOtherWithContext(otherDesc.value), writable: otherDesc.writable, enumerable: otherDesc.enumerable, configurable: otherDesc.configurable }; } if (!thisReflectDefineProperty(target, prop, thisDesc)) throw thisUnexpected(); } return true; } deleteProperty(target, prop) { // Note: target@this(unsafe) prop@prim throws@this(unsafe) const object = this.getObject(); // @other(unsafe) try { return otherReflectDeleteProperty(object, prop) === true; } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } } has(target, key) { // Note: target@this(unsafe) key@prim throws@this(unsafe) const object = this.getObject(); // @other(unsafe) try { return otherReflectHas(object, key) === true; } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } } isExtensible(target) { // Note: target@this(unsafe) throws@this(unsafe) const object = this.getObject(); // @other(unsafe) try { if (otherReflectIsExtensible(object)) return true; } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } if (thisReflectIsExtensible(target)) { this.doPreventExtensions(target, object, this); } return false; } ownKeys(target) { // Note: target@this(unsafe) throws@this(unsafe) const object = this.getObject(); // @other(unsafe) let res; // @other(unsafe) try { res = otherReflectOwnKeys(object); } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } return thisFromOther(res); } preventExtensions(target) { // Note: target@this(unsafe) throws@this(unsafe) const object = this.getObject(); // @other(unsafe) try { if (!otherReflectPreventExtensions(object)) return false; } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } if (thisReflectIsExtensible(target)) { this.doPreventExtensions(target, object, this); } return true; } enumerate(target) { // Note: target@this(unsafe) throws@this(unsafe) const object = this.getObject(); // @other(unsafe) let res; // @other(unsafe) try { res = otherReflectEnumerate(object); } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } return this.fromOtherWithContext(res); } } BaseHandler.prototype[thisSymbolNodeJSUtilInspectCustom] = undefined; BaseHandler.prototype[thisSymbolToStringTag] = 'VM2 Wrapper'; BaseHandler.prototype[thisSymbolIterator] = undefined; function defaultFactory(object) { // Note: other@other(unsafe) returns@this(unsafe) throws@this(unsafe) return new BaseHandler(object); } class ProtectedHandler extends BaseHandler { getFactory() { return protectedFactory; } set(target, key, value, receiver) { // Note: target@this(unsafe) key@prim value@this(unsafe) receiver@this(unsafe) throws@this(unsafe) if (typeof value === 'function') { return thisReflectDefineProperty(receiver, key, { __proto__: null, value: value, writable: true, enumerable: true, configurable: true }) === true; } return super.set(target, key, value, receiver); } definePropertyDesc(target, prop, desc) { // Note: target@this(unsafe) prop@prim desc@this(safe) throws@this(unsafe) if (desc && (desc.set || desc.get || typeof desc.value === 'function')) return undefined; return desc; } } function protectedFactory(object) { // Note: other@other(unsafe) returns@this(unsafe) throws@this(unsafe) return new ProtectedHandler(object); } class ReadOnlyHandler extends BaseHandler { getFactory() { return readonlyFactory; } set(target, key, value, receiver) { // Note: target@this(unsafe) key@prim value@this(unsafe) receiver@this(unsafe) throws@this(unsafe) return thisReflectDefineProperty(receiver, key, { __proto__: null, value: value, writable: true, enumerable: true, configurable: true }); } setPrototypeOf(target, value) { // Note: target@this(unsafe) throws@this(unsafe) return false; } defineProperty(target, prop, desc) { // Note: target@this(unsafe) prop@prim desc@this(unsafe) throws@this(unsafe) return false; } deleteProperty(target, prop) { // Note: target@this(unsafe) prop@prim throws@this(unsafe) return false; } isExtensible(target) { // Note: target@this(unsafe) throws@this(unsafe) return false; } preventExtensions(target) { // Note: target@this(unsafe) throws@this(unsafe) return false; } } function readonlyFactory(object) { // Note: other@other(unsafe) returns@this(unsafe) throws@this(unsafe) return new ReadOnlyHandler(object); } class ReadOnlyMockHandler extends ReadOnlyHandler { constructor(object, mock) { // Note: object@other(unsafe) mock:this(unsafe) throws@this(unsafe) super(object); this.mock = mock; } get(target, key, receiver) { // Note: target@this(unsafe) key@prim receiver@this(unsafe) throws@this(unsafe) const object = this.getObject(); // @other(unsafe) const mock = this.mock; if (thisReflectApply(thisObjectHasOwnProperty, mock, key) && !thisOtherHasOwnProperty(object, key)) { return mock[key]; } return super.get(target, key, receiver); } } function thisFromOther(other) { // Note: other@other(unsafe) returns@this(unsafe) throws@this(unsafe) return thisFromOtherWithFactory(defaultFactory, other); } function thisProxyOther(factory, other, proto) { const target = thisCreateTargetObject(other, proto); const handler = factory(other); const proxy = new ThisProxy(target, handler); try { otherReflectApply(otherWeakMapSet, mappingThisToOther, [proxy, other]); registerProxy(proxy, handler); } catch (e) { throw new VMError('Unexpected error'); } if (!isHost) { thisReflectApply(thisWeakMapSet, mappingOtherToThis, [other, proxy]); return proxy; } const proxy2 = new ThisProxy(proxy, emptyForzenObject); try { otherReflectApply(otherWeakMapSet, mappingThisToOther, [proxy2, other]); registerProxy(proxy2, handler); } catch (e) { throw new VMError('Unexpected error'); } thisReflectApply(thisWeakMapSet, mappingOtherToThis, [other, proxy2]); return proxy2; } function thisEnsureThis(other) { const type = typeof other; switch (type) { case 'object': if (other === null) { return null; } // fallthrough case 'function': let proto = thisReflectGetPrototypeOf(other); if (!proto) { return other; } while (proto) { const mapping = thisReflectApply(thisMapGet, protoMappings, [proto]); if (mapping) { const mapped = thisReflectApply(thisWeakMapGet, mappingOtherToThis, [other]); if (mapped) return mapped; return mapping(defaultFactory, other); } proto = thisReflectGetPrototypeOf(proto); } return other; case 'undefined': case 'string': case 'number': case 'boolean': case 'symbol': case 'bigint': return other; default: // new, unknown types can be dangerous throw new VMError(`Unknown type '${type}'`); } } function thisFromOtherForThrow(other) { for (let loop = 0; loop < 10; loop++) { const type = typeof other; switch (type) { case 'object': if (other === null) { return null; } // fallthrough case 'function': const mapped = thisReflectApply(thisWeakMapGet, mappingOtherToThis, [other]); if (mapped) return mapped; let proto; try { proto = otherReflectGetPrototypeOf(other); } catch (e) { // @other(unsafe) other = e; break; } if (!proto) { return thisProxyOther(defaultFactory, other, null); } for (;;) { const mapping = thisReflectApply(thisMapGet, protoMappings, [proto]); if (mapping) return mapping(defaultFactory, other); try { proto = otherReflectGetPrototypeOf(proto); } catch (e) { // @other(unsafe) other = e; break; } if (!proto) return thisProxyOther(defaultFactory, other, thisObjectPrototype); } break; case 'undefined': case 'string': case 'number': case 'boolean': case 'symbol': case 'bigint': return other; default: // new, unknown types can be dangerous throw new VMError(`Unknown type '${type}'`); } } throw new VMError('Exception recursion depth'); } function thisFromOtherWithFactory(factory, other, proto) { const type = typeof other; switch (type) { case 'object': if (other === null) { return null; } // fallthrough case 'function': const mapped = thisReflectApply(thisWeakMapGet, mappingOtherToThis, [other]); if (mapped) return mapped; if (proto) { return thisProxyOther(factory, other, proto); } try { proto = otherReflectGetPrototypeOf(other); } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } if (!proto) { return thisProxyOther(factory, other, null); } do { const mapping = thisReflectApply(thisMapGet, protoMappings, [proto]); if (mapping) return mapping(factory, other); try { proto = otherReflectGetPrototypeOf(proto); } catch (e) { // @other(unsafe) throw thisFromOtherForThrow(e); } } while (proto); return thisProxyOther(factory, other, thisObjectPrototype); case 'undefined': case 'string': case 'number': case 'boolean': case 'symbol': case 'bigint': return other; default: // new, unknown types can be dangerous throw new VMError(`Unknown type '${type}'`); } } function thisFromOtherArguments(args) { // Note: args@other(safe-array) returns@this(safe-array) throws@this(unsafe) const arr = []; for (let i = 0; i < args.length; i++) { const value = thisFromOther(args[i]); thisReflectDefineProperty(arr, i, { __proto__: null, value: value, writable: true, enumerable: true, configurable: true }); } return arr; } function thisConnect(obj, other) { // Note: obj@this(unsafe) other@other(unsafe) throws@this(unsafe) try { otherReflectApply(otherWeakMapSet, mappingThisToOther, [obj, other]); } catch (e) { throw new VMError('Unexpected error'); } thisReflectApply(thisWeakMapSet, mappingOtherToThis, [other, obj]); } thisAddProtoMapping(thisGlobalPrototypes.Object, otherGlobalPrototypes.Object); thisAddProtoMapping(thisGlobalPrototypes.Array, otherGlobalPrototypes.Array); for (let i = 0; i < globalsList.length; i++) { const key = globalsList[i]; const tp = thisGlobalPrototypes[key]; const op = otherGlobalPrototypes[key]; if (tp && op) thisAddProtoMapping(tp, op, key); } for (let i = 0; i < errorsList.length; i++) { const key = errorsList[i]; const tp = thisGlobalPrototypes[key]; const op = otherGlobalPrototypes[key]; if (tp && op) thisAddProtoMapping(tp, op, 'Error'); } thisAddProtoMapping(thisGlobalPrototypes.VMError, otherGlobalPrototypes.VMError, 'Error'); result.BaseHandler = BaseHandler; result.ProtectedHandler = ProtectedHandler; result.ReadOnlyHandler = ReadOnlyHandler; result.ReadOnlyMockHandler = ReadOnlyMockHandler; return result; } exports.createBridge = createBridge; exports.VMError = VMError; ```
/content/code_sandbox/node_modules/vm2/lib/bridge.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
7,725
```javascript // // 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. // Modified by the vm2 team to make this a standalone module to be loaded into the sandbox. 'use strict'; const host = fromhost; const { Boolean, Error, String, Symbol } = globalThis; const ReflectApply = Reflect.apply; const ReflectOwnKeys = Reflect.ownKeys; const ErrorCaptureStackTrace = Error.captureStackTrace; const NumberIsNaN = Number.isNaN; const ObjectCreate = Object.create; const ObjectDefineProperty = Object.defineProperty; const ObjectDefineProperties = Object.defineProperties; const ObjectGetPrototypeOf = Object.getPrototypeOf; const SymbolFor = Symbol.for; function uncurryThis(func) { return (thiz, ...args) => ReflectApply(func, thiz, args); } const ArrayPrototypeIndexOf = uncurryThis(Array.prototype.indexOf); const ArrayPrototypeJoin = uncurryThis(Array.prototype.join); const ArrayPrototypeSlice = uncurryThis(Array.prototype.slice); const ArrayPrototypeSplice = uncurryThis(Array.prototype.splice); const ArrayPrototypeUnshift = uncurryThis(Array.prototype.unshift); const kRejection = SymbolFor('nodejs.rejection'); function inspect(obj) { return typeof obj === 'symbol' ? obj.toString() : `${obj}`; } function spliceOne(list, index) { for (; index + 1 < list.length; index++) list[index] = list[index + 1]; list.pop(); } function assert(what, message) { if (!what) throw new Error(message); } function E(key, msg, Base) { return function NodeError(...args) { const error = new Base(); const message = ReflectApply(msg, error, args); ObjectDefineProperties(error, { message: { value: message, enumerable: false, writable: true, configurable: true, }, toString: { value() { return `${this.name} [${key}]: ${this.message}`; }, enumerable: false, writable: true, configurable: true, }, }); error.code = key; return error; }; } const ERR_INVALID_ARG_TYPE = E('ERR_INVALID_ARG_TYPE', (name, expected, actual) => { assert(typeof name === 'string', "'name' must be a string"); if (!ArrayIsArray(expected)) { expected = [expected]; } let msg = 'The '; if (StringPrototypeEndsWith(name, ' argument')) { // For cases like 'first argument' msg += `${name} `; } else { const type = StringPrototypeIncludes(name, '.') ? 'property' : 'argument'; msg += `"${name}" ${type} `; } msg += 'must be '; const types = []; const instances = []; const other = []; for (const value of expected) { assert(typeof value === 'string', 'All expected entries have to be of type string'); if (ArrayPrototypeIncludes(kTypes, value)) { ArrayPrototypePush(types, StringPrototypeToLowerCase(value)); } else if (RegExpPrototypeTest(classRegExp, value)) { ArrayPrototypePush(instances, value); } else { assert(value !== 'object', 'The value "object" should be written as "Object"'); ArrayPrototypePush(other, value); } } // Special handle `object` in case other instances are allowed to outline // the differences between each other. if (instances.length > 0) { const pos = ArrayPrototypeIndexOf(types, 'object'); if (pos !== -1) { ArrayPrototypeSplice(types, pos, 1); ArrayPrototypePush(instances, 'Object'); } } if (types.length > 0) { if (types.length > 2) { const last = ArrayPrototypePop(types); msg += `one of type ${ArrayPrototypeJoin(types, ', ')}, or ${last}`; } else if (types.length === 2) { msg += `one of type ${types[0]} or ${types[1]}`; } else { msg += `of type ${types[0]}`; } if (instances.length > 0 || other.length > 0) msg += ' or '; } if (instances.length > 0) { if (instances.length > 2) { const last = ArrayPrototypePop(instances); msg += `an instance of ${ArrayPrototypeJoin(instances, ', ')}, or ${last}`; } else { msg += `an instance of ${instances[0]}`; if (instances.length === 2) { msg += ` or ${instances[1]}`; } } if (other.length > 0) msg += ' or '; } if (other.length > 0) { if (other.length > 2) { const last = ArrayPrototypePop(other); msg += `one of ${ArrayPrototypeJoin(other, ', ')}, or ${last}`; } else if (other.length === 2) { msg += `one of ${other[0]} or ${other[1]}`; } else { if (StringPrototypeToLowerCase(other[0]) !== other[0]) msg += 'an '; msg += `${other[0]}`; } } if (actual == null) { msg += `. Received ${actual}`; } else if (typeof actual === 'function' && actual.name) { msg += `. Received function ${actual.name}`; } else if (typeof actual === 'object') { if (actual.constructor && actual.constructor.name) { msg += `. Received an instance of ${actual.constructor.name}`; } else { const inspected = inspect(actual, { depth: -1 }); msg += `. Received ${inspected}`; } } else { let inspected = inspect(actual, { colors: false }); if (inspected.length > 25) inspected = `${StringPrototypeSlice(inspected, 0, 25)}...`; msg += `. Received type ${typeof actual} (${inspected})`; } return msg; }, TypeError); const ERR_INVALID_THIS = E('ERR_INVALID_THIS', s => `Value of "this" must be of type ${s}`, TypeError); const ERR_OUT_OF_RANGE = E('ERR_OUT_OF_RANGE', (str, range, input, replaceDefaultBoolean = false) => { assert(range, 'Missing "range" argument'); let msg = replaceDefaultBoolean ? str : `The value of "${str}" is out of range.`; const received = inspect(input); msg += ` It must be ${range}. Received ${received}`; return msg; }, RangeError); const ERR_UNHANDLED_ERROR = E('ERR_UNHANDLED_ERROR', err => { const msg = 'Unhandled error.'; if (err === undefined) return msg; return `${msg} (${err})`; }, Error); function validateBoolean(value, name) { if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value); } function validateFunction(value, name) { if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value); } function validateString(value, name) { if (typeof value !== 'string') throw new ERR_INVALID_ARG_TYPE(name, 'string', value); } function nc(cond, e) { return cond === undefined || cond === null ? e : cond; } function oc(base, key) { return base === undefined || base === null ? undefined : base[key]; } const kCapture = Symbol('kCapture'); const kErrorMonitor = host.kErrorMonitor || Symbol('events.errorMonitor'); const kMaxEventTargetListeners = Symbol('events.maxEventTargetListeners'); const kMaxEventTargetListenersWarned = Symbol('events.maxEventTargetListenersWarned'); const kIsEventTarget = SymbolFor('nodejs.event_target'); function isEventTarget(obj) { return oc(oc(obj, 'constructor'), kIsEventTarget); } /** * Creates a new `EventEmitter` instance. * @param {{ captureRejections?: boolean; }} [opts] * @constructs {EventEmitter} */ function EventEmitter(opts) { EventEmitter.init.call(this, opts); } module.exports = EventEmitter; if (host.once) module.exports.once = host.once; if (host.on) module.exports.on = host.on; if (host.getEventListeners) module.exports.getEventListeners = host.getEventListeners; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.usingDomains = false; EventEmitter.captureRejectionSymbol = kRejection; ObjectDefineProperty(EventEmitter, 'captureRejections', { get() { return EventEmitter.prototype[kCapture]; }, set(value) { validateBoolean(value, 'EventEmitter.captureRejections'); EventEmitter.prototype[kCapture] = value; }, enumerable: true }); if (host.EventEmitterReferencingAsyncResource) { const kAsyncResource = Symbol('kAsyncResource'); const EventEmitterReferencingAsyncResource = host.EventEmitterReferencingAsyncResource; class EventEmitterAsyncResource extends EventEmitter { /** * @param {{ * name?: string, * triggerAsyncId?: number, * requireManualDestroy?: boolean, * }} [options] */ constructor(options = undefined) { let name; if (typeof options === 'string') { name = options; options = undefined; } else { if (new.target === EventEmitterAsyncResource) { validateString(oc(options, 'name'), 'options.name'); } name = oc(options, 'name') || new.target.name; } super(options); this[kAsyncResource] = new EventEmitterReferencingAsyncResource(this, name, options); } /** * @param {symbol,string} event * @param {...any} args * @returns {boolean} */ emit(event, ...args) { if (this[kAsyncResource] === undefined) throw new ERR_INVALID_THIS('EventEmitterAsyncResource'); const { asyncResource } = this; ArrayPrototypeUnshift(args, super.emit, this, event); return ReflectApply(asyncResource.runInAsyncScope, asyncResource, args); } /** * @returns {void} */ emitDestroy() { if (this[kAsyncResource] === undefined) throw new ERR_INVALID_THIS('EventEmitterAsyncResource'); this.asyncResource.emitDestroy(); } /** * @type {number} */ get asyncId() { if (this[kAsyncResource] === undefined) throw new ERR_INVALID_THIS('EventEmitterAsyncResource'); return this.asyncResource.asyncId(); } /** * @type {number} */ get triggerAsyncId() { if (this[kAsyncResource] === undefined) throw new ERR_INVALID_THIS('EventEmitterAsyncResource'); return this.asyncResource.triggerAsyncId(); } /** * @type {EventEmitterReferencingAsyncResource} */ get asyncResource() { if (this[kAsyncResource] === undefined) throw new ERR_INVALID_THIS('EventEmitterAsyncResource'); return this[kAsyncResource]; } } EventEmitter.EventEmitterAsyncResource = EventEmitterAsyncResource; } EventEmitter.errorMonitor = kErrorMonitor; // The default for captureRejections is false ObjectDefineProperty(EventEmitter.prototype, kCapture, { value: false, writable: true, enumerable: false }); EventEmitter.prototype._events = undefined; EventEmitter.prototype._eventsCount = 0; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. let defaultMaxListeners = 10; function checkListener(listener) { validateFunction(listener, 'listener'); } ObjectDefineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { throw new ERR_OUT_OF_RANGE('defaultMaxListeners', 'a non-negative number', arg); } defaultMaxListeners = arg; } }); ObjectDefineProperties(EventEmitter, { kMaxEventTargetListeners: { value: kMaxEventTargetListeners, enumerable: false, configurable: false, writable: false, }, kMaxEventTargetListenersWarned: { value: kMaxEventTargetListenersWarned, enumerable: false, configurable: false, writable: false, } }); /** * Sets the max listeners. * @param {number} n * @param {EventTarget[] | EventEmitter[]} [eventTargets] * @returns {void} */ EventEmitter.setMaxListeners = function(n = defaultMaxListeners, ...eventTargets) { if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) throw new ERR_OUT_OF_RANGE('n', 'a non-negative number', n); if (eventTargets.length === 0) { defaultMaxListeners = n; } else { for (let i = 0; i < eventTargets.length; i++) { const target = eventTargets[i]; if (isEventTarget(target)) { target[kMaxEventTargetListeners] = n; target[kMaxEventTargetListenersWarned] = false; } else if (typeof target.setMaxListeners === 'function') { target.setMaxListeners(n); } else { throw new ERR_INVALID_ARG_TYPE( 'eventTargets', ['EventEmitter', 'EventTarget'], target); } } } }; // If you're updating this function definition, please also update any // re-definitions, such as the one in the Domain module (lib/domain.js). EventEmitter.init = function(opts) { if (this._events === undefined || this._events === ObjectGetPrototypeOf(this)._events) { this._events = ObjectCreate(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; if (oc(opts, 'captureRejections')) { validateBoolean(opts.captureRejections, 'options.captureRejections'); this[kCapture] = Boolean(opts.captureRejections); } else { // Assigning the kCapture property directly saves an expensive // prototype lookup in a very sensitive hot path. this[kCapture] = EventEmitter.prototype[kCapture]; } }; function addCatch(that, promise, type, args) { if (!that[kCapture]) { return; } // Handle Promises/A+ spec, then could be a getter // that throws on second use. try { const then = promise.then; if (typeof then === 'function') { then.call(promise, undefined, function(err) { // The callback is called with nextTick to avoid a follow-up // rejection from this promise. process.nextTick(emitUnhandledRejectionOrErr, that, err, type, args); }); } } catch (err) { that.emit('error', err); } } function emitUnhandledRejectionOrErr(ee, err, type, args) { if (typeof ee[kRejection] === 'function') { ee[kRejection](err, type, ...args); } else { // We have to disable the capture rejections mechanism, otherwise // we might end up in an infinite loop. const prev = ee[kCapture]; // If the error handler throws, it is not catchable and it // will end up in 'uncaughtException'. We restore the previous // value of kCapture in case the uncaughtException is present // and the exception is handled. try { ee[kCapture] = false; ee.emit('error', err); } finally { ee[kCapture] = prev; } } } /** * Increases the max listeners of the event emitter. * @param {number} n * @returns {EventEmitter} */ EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { throw new ERR_OUT_OF_RANGE('n', 'a non-negative number', n); } this._maxListeners = n; return this; }; function _getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } /** * Returns the current max listener value for the event emitter. * @returns {number} */ EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return _getMaxListeners(this); }; /** * Synchronously calls each of the listeners registered * for the event. * @param {string | symbol} type * @param {...any} [args] * @returns {boolean} */ EventEmitter.prototype.emit = function emit(type, ...args) { let doError = (type === 'error'); const events = this._events; if (events !== undefined) { if (doError && events[kErrorMonitor] !== undefined) this.emit(kErrorMonitor, ...args); doError = (doError && events.error === undefined); } else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { let er; if (args.length > 0) er = args[0]; if (er instanceof Error) { try { const capture = {}; ErrorCaptureStackTrace(capture, EventEmitter.prototype.emit); } catch (e) {} // Note: The comments on the `throw` lines are intentional, they show // up in Node's output if this results in an unhandled exception. throw er; // Unhandled 'error' event } let stringifiedEr; try { stringifiedEr = inspect(er); } catch (e) { stringifiedEr = er; } // At least give some kind of context to the user const err = new ERR_UNHANDLED_ERROR(stringifiedEr); err.context = er; throw err; // Unhandled 'error' event } const handler = events[type]; if (handler === undefined) return false; if (typeof handler === 'function') { const result = handler.apply(this, args); // We check if result is undefined first because that // is the most common case so we do not pay any perf // penalty if (result !== undefined && result !== null) { addCatch(this, result, type, args); } } else { const len = handler.length; const listeners = arrayClone(handler); for (let i = 0; i < len; ++i) { const result = listeners[i].apply(this, args); // We check if result is undefined first because that // is the most common case so we do not pay any perf // penalty. // This code is duplicated because extracting it away // would make it non-inlineable. if (result !== undefined && result !== null) { addCatch(this, result, type, args); } } } return true; }; function _addListener(target, type, listener, prepend) { let m; let events; let existing; checkListener(listener); events = target._events; if (events === undefined) { events = target._events = ObjectCreate(null); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener !== undefined) { target.emit('newListener', type, nc(listener.listener, listener)); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (existing === undefined) { // Optimize the case of one listener. Don't need the extra array object. events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; // If we've already got an array, just append. } else if (prepend) { existing.unshift(listener); } else { existing.push(listener); } // Check for listener leak m = _getMaxListeners(target); if (m > 0 && existing.length > m && !existing.warned) { existing.warned = true; // No error code for this since it is a Warning // eslint-disable-next-line no-restricted-syntax const w = new Error('Possible EventEmitter memory leak detected. ' + `${existing.length} ${String(type)} listeners ` + `added to ${inspect(target, { depth: -1 })}. Use ` + 'emitter.setMaxListeners() to increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; process.emitWarning(w); } } return target; } /** * Adds a listener to the event emitter. * @param {string | symbol} type * @param {Function} listener * @returns {EventEmitter} */ EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; /** * Adds the `listener` function to the beginning of * the listeners array. * @param {string | symbol} type * @param {Function} listener * @returns {EventEmitter} */ EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; if (arguments.length === 0) return this.listener.call(this.target); return this.listener.apply(this.target, arguments); } } function _onceWrap(target, type, listener) { const state = { fired: false, wrapFn: undefined, target, type, listener }; const wrapped = onceWrapper.bind(state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } /** * Adds a one-time `listener` function to the event emitter. * @param {string | symbol} type * @param {Function} listener * @returns {EventEmitter} */ EventEmitter.prototype.once = function once(type, listener) { checkListener(listener); this.on(type, _onceWrap(this, type, listener)); return this; }; /** * Adds a one-time `listener` function to the beginning of * the listeners array. * @param {string | symbol} type * @param {Function} listener * @returns {EventEmitter} */ EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { checkListener(listener); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; /** * Removes the specified `listener` from the listeners array. * @param {string | symbol} type * @param {Function} listener * @returns {EventEmitter} */ EventEmitter.prototype.removeListener = function removeListener(type, listener) { checkListener(listener); const events = this._events; if (events === undefined) return this; const list = events[type]; if (list === undefined) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = ObjectCreate(null); else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { let position = -1; for (let i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { position = i; break; } } if (position < 0) return this; if (position === 0) list.shift(); else { spliceOne(list, position); } if (list.length === 1) events[type] = list[0]; if (events.removeListener !== undefined) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.off = EventEmitter.prototype.removeListener; /** * Removes all listeners from the event emitter. (Only * removes listeners for a specific event name if specified * as `type`). * @param {string | symbol} [type] * @returns {EventEmitter} */ EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { const events = this._events; if (events === undefined) return this; // Not listening for removeListener, no need to emit if (events.removeListener === undefined) { if (arguments.length === 0) { this._events = ObjectCreate(null); this._eventsCount = 0; } else if (events[type] !== undefined) { if (--this._eventsCount === 0) this._events = ObjectCreate(null); else delete events[type]; } return this; } // Emit removeListener for all listeners on all events if (arguments.length === 0) { for (const key of ReflectOwnKeys(events)) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = ObjectCreate(null); this._eventsCount = 0; return this; } const listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners !== undefined) { // LIFO order for (let i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return this; }; function _listeners(target, type, unwrap) { const events = target._events; if (events === undefined) return []; const evlistener = events[type]; if (evlistener === undefined) return []; if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener); } /** * Returns a copy of the array of listeners for the event name * specified as `type`. * @param {string | symbol} type * @returns {Function[]} */ EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; /** * Returns a copy of the array of listeners and wrappers for * the event name specified as `type`. * @param {string | symbol} type * @returns {Function[]} */ EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; /** * Returns the number of listeners listening to the event name * specified as `type`. * @deprecated since v3.2.0 * @param {EventEmitter} emitter * @param {string | symbol} type * @returns {number} */ EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } return emitter.listenerCount(type); }; EventEmitter.prototype.listenerCount = listenerCount; /** * Returns the number of listeners listening to event name * specified as `type`. * @param {string | symbol} type * @returns {number} */ function listenerCount(type) { const events = this._events; if (events !== undefined) { const evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener !== undefined) { return evlistener.length; } } return 0; } /** * Returns an array listing the events for which * the emitter has registered listeners. * @returns {any[]} */ EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; }; function arrayClone(arr) { // At least since V8 8.3, this implementation is faster than the previous // which always used a simple for-loop switch (arr.length) { case 2: return [arr[0], arr[1]]; case 3: return [arr[0], arr[1], arr[2]]; case 4: return [arr[0], arr[1], arr[2], arr[3]]; case 5: return [arr[0], arr[1], arr[2], arr[3], arr[4]]; case 6: return [arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]]; } return ArrayPrototypeSlice(arr); } function unwrapListeners(arr) { const ret = arrayClone(arr); for (let i = 0; i < ret.length; ++i) { const orig = ret[i].listener; if (typeof orig === 'function') ret[i] = orig; } return ret; } ```
/content/code_sandbox/node_modules/vm2/lib/events.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
6,672
```javascript 'use strict'; /** * This callback will be called to transform a script to JavaScript. * * @callback compileCallback * @param {string} code - Script code to transform to JavaScript. * @param {string} filename - Filename of this script. * @return {string} JavaScript code that represents the script code. */ /** * This callback will be called to resolve a module if it couldn't be found. * * @callback resolveCallback * @param {string} moduleName - Name of the modulusedRequiree to resolve. * @param {string} dirname - Name of the current directory. * @return {(string|undefined)} The file or directory to use to load the requested module. */ const fs = require('fs'); const pa = require('path'); const { Script, createContext } = require('vm'); const { EventEmitter } = require('events'); const { INSPECT_MAX_BYTES } = require('buffer'); const { createBridge, VMError } = require('./bridge'); const { transformer, INTERNAL_STATE_NAME } = require('./transformer'); const { lookupCompiler } = require('./compiler'); const { VMScript } = require('./script'); const objectDefineProperties = Object.defineProperties; /** * Host objects * * @private */ const HOST = Object.freeze({ Buffer, Function, Object, transformAndCheck, INSPECT_MAX_BYTES, INTERNAL_STATE_NAME }); /** * Compile a script. * * @private * @param {string} filename - Filename of the script. * @param {string} script - Script. * @return {vm.Script} The compiled script. */ function compileScript(filename, script) { return new Script(script, { __proto__: null, filename, displayErrors: false }); } /** * Default run options for vm.Script.runInContext * * @private */ const DEFAULT_RUN_OPTIONS = Object.freeze({__proto__: null, displayErrors: false}); function checkAsync(allow) { if (!allow) throw new VMError('Async not available'); } function transformAndCheck(args, code, isAsync, isGenerator, allowAsync) { const ret = transformer(args, code, isAsync, isGenerator, undefined); checkAsync(allowAsync || !ret.hasAsync); return ret.code; } /** * * This callback will be called and has a specific time to finish.<br> * No parameters will be supplied.<br> * If parameters are required, use a closure. * * @private * @callback runWithTimeout * @return {*} * */ let cacheTimeoutContext = null; let cacheTimeoutScript = null; /** * Run a function with a specific timeout. * * @private * @param {runWithTimeout} fn - Function to run with the specific timeout. * @param {number} timeout - The amount of time to give the function to finish. * @return {*} The value returned by the function. * @throws {Error} If the function took to long. */ function doWithTimeout(fn, timeout) { if (!cacheTimeoutContext) { cacheTimeoutContext = createContext(); cacheTimeoutScript = new Script('fn()', { __proto__: null, filename: 'timeout_bridge.js', displayErrors: false }); } cacheTimeoutContext.fn = fn; try { return cacheTimeoutScript.runInContext(cacheTimeoutContext, { __proto__: null, displayErrors: false, timeout }); } finally { cacheTimeoutContext.fn = null; } } const bridgeScript = compileScript(`${__dirname}/bridge.js`, `(function(global) {"use strict"; const exports = {};${fs.readFileSync(`${__dirname}/bridge.js`, 'utf8')}\nreturn exports;})`); const setupSandboxScript = compileScript(`${__dirname}/setup-sandbox.js`, `(function(global, host, bridge, data, context) { ${fs.readFileSync(`${__dirname}/setup-sandbox.js`, 'utf8')}\n})`); const getGlobalScript = compileScript('get_global.js', 'this'); let getGeneratorFunctionScript = null; let getAsyncFunctionScript = null; let getAsyncGeneratorFunctionScript = null; try { getGeneratorFunctionScript = compileScript('get_generator_function.js', '(function*(){}).constructor'); } catch (ex) {} try { getAsyncFunctionScript = compileScript('get_async_function.js', '(async function(){}).constructor'); } catch (ex) {} try { getAsyncGeneratorFunctionScript = compileScript('get_async_generator_function.js', '(async function*(){}).constructor'); } catch (ex) {} /** * Class VM. * * @public */ class VM extends EventEmitter { /** * The timeout for {@link VM#run} calls. * * @public * @since v3.9.0 * @member {number} timeout * @memberOf VM# */ /** * Get the global sandbox object. * * @public * @readonly * @since v3.9.0 * @member {Object} sandbox * @memberOf VM# */ /** * The compiler to use to get the JavaScript code. * * @public * @readonly * @since v3.9.0 * @member {(string|compileCallback)} compiler * @memberOf VM# */ /** * The resolved compiler to use to get the JavaScript code. * * @private * @readonly * @member {compileCallback} _compiler * @memberOf VM# */ /** * Create a new VM instance. * * @public * @param {Object} [options] - VM options. * @param {number} [options.timeout] - The amount of time until a call to {@link VM#run} will timeout. * @param {Object} [options.sandbox] - Objects that will be copied into the global object of the sandbox. * @param {(string|compileCallback)} [options.compiler="javascript"] - The compiler to use. * @param {boolean} [options.eval=true] - Allow the dynamic evaluation of code via eval(code) or Function(code)().<br> * Only available for node v10+. * @param {boolean} [options.wasm=true] - Allow to run wasm code.<br> * Only available for node v10+. * @param {boolean} [options.allowAsync=true] - Allows for async functions. * @throws {VMError} If the compiler is unknown. */ constructor(options = {}) { super(); // Read all options const { timeout, sandbox, compiler = 'javascript', allowAsync: optAllowAsync = true } = options; const allowEval = options.eval !== false; const allowWasm = options.wasm !== false; const allowAsync = optAllowAsync && !options.fixAsync; // Early error if sandbox is not an object. if (sandbox && 'object' !== typeof sandbox) { throw new VMError('Sandbox must be object.'); } // Early error if compiler can't be found. const resolvedCompiler = lookupCompiler(compiler); // Create a new context for this vm. const _context = createContext(undefined, { __proto__: null, codeGeneration: { __proto__: null, strings: allowEval, wasm: allowWasm } }); const sandboxGlobal = getGlobalScript.runInContext(_context, DEFAULT_RUN_OPTIONS); // Initialize the sandbox bridge const { createBridge: sandboxCreateBridge } = bridgeScript.runInContext(_context, DEFAULT_RUN_OPTIONS)(sandboxGlobal); // Initialize the bridge const bridge = createBridge(sandboxCreateBridge, () => {}); const data = { __proto__: null, allowAsync }; if (getGeneratorFunctionScript) { data.GeneratorFunction = getGeneratorFunctionScript.runInContext(_context, DEFAULT_RUN_OPTIONS); } if (getAsyncFunctionScript) { data.AsyncFunction = getAsyncFunctionScript.runInContext(_context, DEFAULT_RUN_OPTIONS); } if (getAsyncGeneratorFunctionScript) { data.AsyncGeneratorFunction = getAsyncGeneratorFunctionScript.runInContext(_context, DEFAULT_RUN_OPTIONS); } // Create the bridge between the host and the sandbox. const internal = setupSandboxScript.runInContext(_context, DEFAULT_RUN_OPTIONS)(sandboxGlobal, HOST, bridge.other, data, _context); const runScript = (script) => { // This closure is intentional to hide _context and bridge since the allow to access the sandbox directly which is unsafe. let ret; try { ret = script.runInContext(_context, DEFAULT_RUN_OPTIONS); } catch (e) { throw bridge.from(e); } return bridge.from(ret); }; const makeReadonly = (value, mock) => { try { internal.readonly(value, mock); } catch (e) { throw bridge.from(e); } return value; }; const makeProtected = (value) => { const sandboxBridge = bridge.other; try { sandboxBridge.fromWithFactory(sandboxBridge.protectedFactory, value); } catch (e) { throw bridge.from(e); } return value; }; const addProtoMapping = (hostProto, sandboxProto) => { const sandboxBridge = bridge.other; let otherProto; try { otherProto = sandboxBridge.from(sandboxProto); sandboxBridge.addProtoMapping(otherProto, hostProto); } catch (e) { throw bridge.from(e); } bridge.addProtoMapping(hostProto, otherProto); }; const addProtoMappingFactory = (hostProto, sandboxProtoFactory) => { const sandboxBridge = bridge.other; const factory = () => { const proto = sandboxProtoFactory(this); bridge.addProtoMapping(hostProto, proto); return proto; }; try { const otherProtoFactory = sandboxBridge.from(factory); sandboxBridge.addProtoMappingFactory(otherProtoFactory, hostProto); } catch (e) { throw bridge.from(e); } }; // Define the properties of this object. // Use Object.defineProperties here to be able to // hide and set properties read-only. objectDefineProperties(this, { __proto__: null, timeout: { __proto__: null, value: timeout, writable: true, enumerable: true }, compiler: { __proto__: null, value: compiler, enumerable: true }, sandbox: { __proto__: null, value: bridge.from(sandboxGlobal), enumerable: true }, _runScript: {__proto__: null, value: runScript}, _makeReadonly: {__proto__: null, value: makeReadonly}, _makeProtected: {__proto__: null, value: makeProtected}, _addProtoMapping: {__proto__: null, value: addProtoMapping}, _addProtoMappingFactory: {__proto__: null, value: addProtoMappingFactory}, _compiler: {__proto__: null, value: resolvedCompiler}, _allowAsync: {__proto__: null, value: allowAsync} }); // prepare global sandbox if (sandbox) { this.setGlobals(sandbox); } } /** * Adds all the values to the globals. * * @public * @since v3.9.0 * @param {Object} values - All values that will be added to the globals. * @return {this} This for chaining. * @throws {*} If the setter of a global throws an exception it is propagated. And the remaining globals will not be written. */ setGlobals(values) { for (const name in values) { if (Object.prototype.hasOwnProperty.call(values, name)) { this.sandbox[name] = values[name]; } } return this; } /** * Set a global value. * * @public * @since v3.9.0 * @param {string} name - The name of the global. * @param {*} value - The value of the global. * @return {this} This for chaining. * @throws {*} If the setter of the global throws an exception it is propagated. */ setGlobal(name, value) { this.sandbox[name] = value; return this; } /** * Get a global value. * * @public * @since v3.9.0 * @param {string} name - The name of the global. * @return {*} The value of the global. * @throws {*} If the getter of the global throws an exception it is propagated. */ getGlobal(name) { return this.sandbox[name]; } /** * Freezes the object inside VM making it read-only. Not available for primitive values. * * @public * @param {*} value - Object to freeze. * @param {string} [globalName] - Whether to add the object to global. * @return {*} Object to freeze. * @throws {*} If the setter of the global throws an exception it is propagated. */ freeze(value, globalName) { this.readonly(value); if (globalName) this.sandbox[globalName] = value; return value; } /** * Freezes the object inside VM making it read-only. Not available for primitive values. * * @public * @param {*} value - Object to freeze. * @param {*} [mock] - When the object does not have a property the mock is used before prototype lookup. * @return {*} Object to freeze. */ readonly(value, mock) { return this._makeReadonly(value, mock); } /** * Protects the object inside VM making impossible to set functions as it's properties. Not available for primitive values. * * @public * @param {*} value - Object to protect. * @param {string} [globalName] - Whether to add the object to global. * @return {*} Object to protect. * @throws {*} If the setter of the global throws an exception it is propagated. */ protect(value, globalName) { this._makeProtected(value); if (globalName) this.sandbox[globalName] = value; return value; } /** * Run the code in VM. * * @public * @param {(string|VMScript)} code - Code to run. * @param {(string|Object)} [options] - Options map or filename. * @param {string} [options.filename="vm.js"] - Filename that shows up in any stack traces produced from this script.<br> * This is only used if code is a String. * @return {*} Result of executed code. * @throws {SyntaxError} If there is a syntax error in the script. * @throws {Error} An error is thrown when the script took to long and there is a timeout. * @throws {*} If the script execution terminated with an exception it is propagated. */ run(code, options) { let script; let filename; if (typeof options === 'object') { filename = options.filename; } else { filename = options; } if (code instanceof VMScript) { script = code._compileVM(); checkAsync(this._allowAsync || !code._hasAsync); } else { const useFileName = filename || 'vm.js'; let scriptCode = this._compiler(code, useFileName); const ret = transformer(null, scriptCode, false, false, useFileName); scriptCode = ret.code; checkAsync(this._allowAsync || !ret.hasAsync); // Compile the script here so that we don't need to create a instance of VMScript. script = new Script(scriptCode, { __proto__: null, filename: useFileName, displayErrors: false }); } if (!this.timeout) { return this._runScript(script); } return doWithTimeout(() => { return this._runScript(script); }, this.timeout); } /** * Run the code in VM. * * @public * @since v3.9.0 * @param {string} filename - Filename of file to load and execute in a NodeVM. * @return {*} Result of executed code. * @throws {Error} If filename is not a valid filename. * @throws {SyntaxError} If there is a syntax error in the script. * @throws {Error} An error is thrown when the script took to long and there is a timeout. * @throws {*} If the script execution terminated with an exception it is propagated. */ runFile(filename) { const resolvedFilename = pa.resolve(filename); if (!fs.existsSync(resolvedFilename)) { throw new VMError(`Script '${filename}' not found.`); } if (fs.statSync(resolvedFilename).isDirectory()) { throw new VMError('Script must be file, got directory.'); } return this.run(fs.readFileSync(resolvedFilename, 'utf8'), resolvedFilename); } } exports.VM = VM; ```
/content/code_sandbox/node_modules/vm2/lib/vm.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,847
```javascript 'use strict'; const { VMError } = require('./bridge'); let cacheCoffeeScriptCompiler; /** * Returns the cached coffee script compiler or loads it * if it is not found in the cache. * * @private * @return {compileCallback} The coffee script compiler. * @throws {VMError} If the coffee-script module can't be found. */ function getCoffeeScriptCompiler() { if (!cacheCoffeeScriptCompiler) { try { // The warning generated by webpack can be disabled by setting: // ignoreWarnings[].message = /Can't resolve 'coffee-script'/ /* eslint-disable-next-line global-require */ const coffeeScript = require('coffee-script'); cacheCoffeeScriptCompiler = (code, filename) => { return coffeeScript.compile(code, {header: false, bare: true}); }; } catch (e) { throw new VMError('Coffee-Script compiler is not installed.'); } } return cacheCoffeeScriptCompiler; } /** * Remove the shebang from source code. * * @private * @param {string} code - Code from which to remove the shebang. * @return {string} code without the shebang. */ function removeShebang(code) { if (!code.startsWith('#!')) return code; return '//' + code.substring(2); } /** * The JavaScript compiler, just a identity function. * * @private * @type {compileCallback} * @param {string} code - The JavaScript code. * @param {string} filename - Filename of this script. * @return {string} The code. */ function jsCompiler(code, filename) { return removeShebang(code); } /** * Look up the compiler for a specific name. * * @private * @param {(string|compileCallback)} compiler - A compile callback or the name of the compiler. * @return {compileCallback} The resolved compiler. * @throws {VMError} If the compiler is unknown or the coffee script module was needed and couldn't be found. */ function lookupCompiler(compiler) { if ('function' === typeof compiler) return compiler; switch (compiler) { case 'coffeescript': case 'coffee-script': case 'cs': case 'text/coffeescript': return getCoffeeScriptCompiler(); case 'javascript': case 'java-script': case 'js': case 'text/javascript': return jsCompiler; default: throw new VMError(`Unsupported compiler '${compiler}'.`); } } exports.removeShebang = removeShebang; exports.lookupCompiler = lookupCompiler; ```
/content/code_sandbox/node_modules/vm2/lib/compiler.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
553
```javascript 'use strict'; const { VMError } = require('./bridge'); const { VMScript } = require('./script'); const { VM } = require('./vm'); const { NodeVM } = require('./nodevm'); exports.VMError = VMError; exports.VMScript = VMScript; exports.NodeVM = NodeVM; exports.VM = VM; ```
/content/code_sandbox/node_modules/vm2/lib/main.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
81
```javascript const {Parser: AcornParser, isNewLine: acornIsNewLine, getLineInfo: acornGetLineInfo} = require('acorn'); const {full: acornWalkFull} = require('acorn-walk'); const INTERNAL_STATE_NAME = 'VM2_INTERNAL_STATE_DO_NOT_USE_OR_PROGRAM_WILL_FAIL'; function assertType(node, type) { if (!node) throw new Error(`None existent node expected '${type}'`); if (node.type !== type) throw new Error(`Invalid node type '${node.type}' expected '${type}'`); return node; } function makeNiceSyntaxError(message, code, filename, location, tokenizer) { const loc = acornGetLineInfo(code, location); let end = location; while (end < code.length && !acornIsNewLine(code.charCodeAt(end))) { end++; } let markerEnd = tokenizer.start === location ? tokenizer.end : location + 1; if (!markerEnd || markerEnd > end) markerEnd = end; let markerLen = markerEnd - location; if (markerLen <= 0) markerLen = 1; if (message === 'Unexpected token') { const type = tokenizer.type; if (type.label === 'name' || type.label === 'privateId') { message = 'Unexpected identifier'; } else if (type.label === 'eof') { message = 'Unexpected end of input'; } else if (type.label === 'num') { message = 'Unexpected number'; } else if (type.label === 'string') { message = 'Unexpected string'; } else if (type.label === 'regexp') { message = 'Unexpected token \'/\''; markerLen = 1; } else { const token = tokenizer.value || type.label; message = `Unexpected token '${token}'`; } } const error = new SyntaxError(message); if (!filename) return error; const line = code.slice(location - loc.column, end); const marker = line.slice(0, loc.column).replace(/\S/g, ' ') + '^'.repeat(markerLen); error.stack = `${filename}:${loc.line}\n${line}\n${marker}\n\n${error.stack}`; return error; } function transformer(args, body, isAsync, isGenerator, filename) { let code; let argsOffset; if (args === null) { code = body; // Note: Keywords are not allows to contain u escapes if (!/\b(?:catch|import|async)\b/.test(code)) { return {__proto__: null, code, hasAsync: false}; } } else { code = isAsync ? '(async function' : '(function'; if (isGenerator) code += '*'; code += ' anonymous('; code += args; argsOffset = code.length; code += '\n) {\n'; code += body; code += '\n})'; } const parser = new AcornParser({ __proto__: null, ecmaVersion: 2022, allowAwaitOutsideFunction: args === null && isAsync, allowReturnOutsideFunction: args === null }, code); let ast; try { ast = parser.parse(); } catch (e) { // Try to generate a nicer error message. if (e instanceof SyntaxError && e.pos !== undefined) { let message = e.message; const match = message.match(/^(.*) \(\d+:\d+\)$/); if (match) message = match[1]; e = makeNiceSyntaxError(message, code, filename, e.pos, parser); } throw e; } if (args !== null) { const pBody = assertType(ast, 'Program').body; if (pBody.length !== 1) throw new SyntaxError('Single function literal required'); const expr = pBody[0]; if (expr.type !== 'ExpressionStatement') throw new SyntaxError('Single function literal required'); const func = expr.expression; if (func.type !== 'FunctionExpression') throw new SyntaxError('Single function literal required'); if (func.body.start !== argsOffset + 3) throw new SyntaxError('Unexpected end of arg string'); } const insertions = []; let hasAsync = false; const TO_LEFT = -100; const TO_RIGHT = 100; let internStateValiable = undefined; acornWalkFull(ast, (node, state, type) => { if (type === 'Function') { if (node.async) hasAsync = true; } const nodeType = node.type; if (nodeType === 'CatchClause') { const param = node.param; if (param) { const name = assertType(param, 'Identifier').name; const cBody = assertType(node.body, 'BlockStatement'); if (cBody.body.length > 0) { insertions.push({ __proto__: null, pos: cBody.body[0].start, order: TO_LEFT, code: `${name}=${INTERNAL_STATE_NAME}.handleException(${name});` }); } } } else if (nodeType === 'WithStatement') { insertions.push({ __proto__: null, pos: node.object.start, order: TO_LEFT, code: INTERNAL_STATE_NAME + '.wrapWith(' }); insertions.push({ __proto__: null, pos: node.object.end, order: TO_RIGHT, code: ')' }); } else if (nodeType === 'Identifier') { if (node.name === INTERNAL_STATE_NAME) { if (internStateValiable === undefined || internStateValiable.start > node.start) { internStateValiable = node; } } } else if (nodeType === 'ImportExpression') { insertions.push({ __proto__: null, pos: node.start, order: TO_RIGHT, code: INTERNAL_STATE_NAME + '.' }); } }); if (internStateValiable) { throw makeNiceSyntaxError('Use of internal vm2 state variable', code, filename, internStateValiable.start, { __proto__: null, start: internStateValiable.start, end: internStateValiable.end }); } if (insertions.length === 0) return {__proto__: null, code, hasAsync}; insertions.sort((a, b) => (a.pos == b.pos ? a.order - b.order : a.pos - b.pos)); let ncode = ''; let curr = 0; for (let i = 0; i < insertions.length; i++) { const change = insertions[i]; ncode += code.substring(curr, change.pos) + change.code; curr = change.pos; } ncode += code.substring(curr); return {__proto__: null, code: ncode, hasAsync}; } exports.INTERNAL_STATE_NAME = INTERNAL_STATE_NAME; exports.transformer = transformer; ```
/content/code_sandbox/node_modules/vm2/lib/transformer.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,524
```javascript /* global host, data, VMError */ 'use strict'; const LocalError = Error; const LocalTypeError = TypeError; const LocalWeakMap = WeakMap; const { apply: localReflectApply, defineProperty: localReflectDefineProperty } = Reflect; const { set: localWeakMapSet, get: localWeakMapGet } = LocalWeakMap.prototype; const { isArray: localArrayIsArray } = Array; function uncurryThis(func) { return (thiz, ...args) => localReflectApply(func, thiz, args); } const localArrayPrototypeSlice = uncurryThis(Array.prototype.slice); const localArrayPrototypeIncludes = uncurryThis(Array.prototype.includes); const localArrayPrototypePush = uncurryThis(Array.prototype.push); const localArrayPrototypeIndexOf = uncurryThis(Array.prototype.indexOf); const localArrayPrototypeSplice = uncurryThis(Array.prototype.splice); const localStringPrototypeStartsWith = uncurryThis(String.prototype.startsWith); const localStringPrototypeSlice = uncurryThis(String.prototype.slice); const localStringPrototypeIndexOf = uncurryThis(String.prototype.indexOf); const { argv: optionArgv, env: optionEnv, console: optionConsole, vm, resolver, extensions } = data; function ensureSandboxArray(a) { return localArrayPrototypeSlice(a); } const globalPaths = ensureSandboxArray(resolver.globalPaths); class Module { constructor(id, path, parent) { this.id = id; this.filename = id; this.path = path; this.parent = parent; this.loaded = false; this.paths = path ? ensureSandboxArray(resolver.genLookupPaths(path)) : []; this.children = []; this.exports = {}; } _updateChildren(child, isNew) { const children = this.children; if (children && (isNew || !localArrayPrototypeIncludes(children, child))) { localArrayPrototypePush(children, child); } } require(id) { return requireImpl(this, id, false); } } const originalRequire = Module.prototype.require; const cacheBuiltins = {__proto__: null}; function requireImpl(mod, id, direct) { if (direct && mod.require !== originalRequire) { return mod.require(id); } const filename = resolver.resolve(mod, id, undefined, Module._extensions, direct); if (localStringPrototypeStartsWith(filename, 'node:')) { id = localStringPrototypeSlice(filename, 5); let nmod = cacheBuiltins[id]; if (!nmod) { nmod = resolver.loadBuiltinModule(vm, id); if (!nmod) throw new VMError(`Cannot find module '${filename}'`, 'ENOTFOUND'); cacheBuiltins[id] = nmod; } return nmod; } const cachedModule = Module._cache[filename]; if (cachedModule !== undefined) { mod._updateChildren(cachedModule, false); return cachedModule.exports; } let nmod = cacheBuiltins[id]; if (nmod) return nmod; nmod = resolver.loadBuiltinModule(vm, id); if (nmod) { cacheBuiltins[id] = nmod; return nmod; } const path = resolver.pathDirname(filename); const module = new Module(filename, path, mod); resolver.registerModule(module, filename, path, mod, direct); mod._updateChildren(module, true); try { Module._cache[filename] = module; const handler = findBestExtensionHandler(filename); handler(module, filename); module.loaded = true; } catch (e) { delete Module._cache[filename]; const children = mod.children; if (localArrayIsArray(children)) { const index = localArrayPrototypeIndexOf(children, module); if (index !== -1) { localArrayPrototypeSplice(children, index, 1); } } throw e; } return module.exports; } Module.builtinModules = ensureSandboxArray(resolver.getBuiltinModulesList()); Module.globalPaths = globalPaths; Module._extensions = {__proto__: null}; Module._cache = {__proto__: null}; { const keys = Object.getOwnPropertyNames(extensions); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const handler = extensions[key]; Module._extensions[key] = (mod, filename) => handler(mod, filename); } } function findBestExtensionHandler(filename) { const name = resolver.pathBasename(filename); for (let i = 0; (i = localStringPrototypeIndexOf(name, '.', i + 1)) !== -1;) { const ext = localStringPrototypeSlice(name, i); const handler = Module._extensions[ext]; if (handler) return handler; } const js = Module._extensions['.js']; if (js) return js; const keys = Object.getOwnPropertyNames(Module._extensions); if (keys.length === 0) throw new VMError(`Failed to load '${filename}': Unknown type.`, 'ELOADFAIL'); return Module._extensions[keys[0]]; } function createRequireForModule(mod) { // eslint-disable-next-line no-shadow function require(id) { return requireImpl(mod, id, true); } function resolve(id, options) { return resolver.resolve(mod, id, options, Module._extensions, true); } require.resolve = resolve; function paths(id) { return ensureSandboxArray(resolver.lookupPaths(mod, id)); } resolve.paths = paths; require.extensions = Module._extensions; require.cache = Module._cache; return require; } /** * Prepare sandbox. */ const TIMERS = new LocalWeakMap(); class Timeout { } class Interval { } class Immediate { } function clearTimer(timer) { const obj = localReflectApply(localWeakMapGet, TIMERS, [timer]); if (obj) { obj.clear(obj.value); } } // This is a function and not an arrow function, since the original is also a function // eslint-disable-next-line no-shadow global.setTimeout = function setTimeout(callback, delay, ...args) { if (typeof callback !== 'function') throw new LocalTypeError('"callback" argument must be a function'); const obj = new Timeout(callback, args); const cb = () => { localReflectApply(callback, null, args); }; const tmr = host.setTimeout(cb, delay); const ref = { __proto__: null, clear: host.clearTimeout, value: tmr }; localReflectApply(localWeakMapSet, TIMERS, [obj, ref]); return obj; }; // eslint-disable-next-line no-shadow global.setInterval = function setInterval(callback, interval, ...args) { if (typeof callback !== 'function') throw new LocalTypeError('"callback" argument must be a function'); const obj = new Interval(); const cb = () => { localReflectApply(callback, null, args); }; const tmr = host.setInterval(cb, interval); const ref = { __proto__: null, clear: host.clearInterval, value: tmr }; localReflectApply(localWeakMapSet, TIMERS, [obj, ref]); return obj; }; // eslint-disable-next-line no-shadow global.setImmediate = function setImmediate(callback, ...args) { if (typeof callback !== 'function') throw new LocalTypeError('"callback" argument must be a function'); const obj = new Immediate(); const cb = () => { localReflectApply(callback, null, args); }; const tmr = host.setImmediate(cb); const ref = { __proto__: null, clear: host.clearImmediate, value: tmr }; localReflectApply(localWeakMapSet, TIMERS, [obj, ref]); return obj; }; // eslint-disable-next-line no-shadow global.clearTimeout = function clearTimeout(timeout) { clearTimer(timeout); }; // eslint-disable-next-line no-shadow global.clearInterval = function clearInterval(interval) { clearTimer(interval); }; // eslint-disable-next-line no-shadow global.clearImmediate = function clearImmediate(immediate) { clearTimer(immediate); }; const localProcess = host.process; function vmEmitArgs(event, args) { const allargs = [event]; for (let i = 0; i < args.length; i++) { if (!localReflectDefineProperty(allargs, i + 1, { __proto__: null, value: args[i], writable: true, enumerable: true, configurable: true })) throw new LocalError('Unexpected'); } return localReflectApply(vm.emit, vm, allargs); } const LISTENERS = new LocalWeakMap(); const LISTENER_HANDLER = new LocalWeakMap(); /** * * @param {*} name * @param {*} handler * @this process * @return {this} */ function addListener(name, handler) { if (name !== 'beforeExit' && name !== 'exit') { throw new LocalError(`Access denied to listen for '${name}' event.`); } let cb = localReflectApply(localWeakMapGet, LISTENERS, [handler]); if (!cb) { cb = () => { handler(); }; localReflectApply(localWeakMapSet, LISTENER_HANDLER, [cb, handler]); localReflectApply(localWeakMapSet, LISTENERS, [handler, cb]); } localProcess.on(name, cb); return this; } /** * * @this process * @return {this} */ // eslint-disable-next-line no-shadow function process() { return this; } const baseUptime = localProcess.uptime(); // FIXME wrong class structure global.process = { __proto__: process.prototype, argv: optionArgv !== undefined ? optionArgv : [], title: localProcess.title, version: localProcess.version, versions: localProcess.versions, arch: localProcess.arch, platform: localProcess.platform, env: optionEnv !== undefined ? optionEnv : {}, pid: localProcess.pid, features: localProcess.features, nextTick: function nextTick(callback, ...args) { if (typeof callback !== 'function') { throw new LocalError('Callback must be a function.'); } localProcess.nextTick(()=>{ localReflectApply(callback, null, args); }); }, hrtime: function hrtime(time) { return localProcess.hrtime(time); }, uptime: function uptime() { return localProcess.uptime() - baseUptime; }, cwd: function cwd() { return localProcess.cwd(); }, addListener, on: addListener, once: function once(name, handler) { if (name !== 'beforeExit' && name !== 'exit') { throw new LocalError(`Access denied to listen for '${name}' event.`); } let triggered = false; const cb = () => { if (triggered) return; triggered = true; localProcess.removeListener(name, cb); handler(); }; localReflectApply(localWeakMapSet, LISTENER_HANDLER, [cb, handler]); localProcess.on(name, cb); return this; }, listeners: function listeners(name) { if (name !== 'beforeExit' && name !== 'exit') { // Maybe add ({__proto__:null})[name] to throw when name fails in path_to_url#sec-topropertykey. return []; } // Filter out listeners, which were not created in this sandbox const all = localProcess.listeners(name); const filtered = []; let j = 0; for (let i = 0; i < all.length; i++) { const h = localReflectApply(localWeakMapGet, LISTENER_HANDLER, [all[i]]); if (h) { if (!localReflectDefineProperty(filtered, j, { __proto__: null, value: h, writable: true, enumerable: true, configurable: true })) throw new LocalError('Unexpected'); j++; } } return filtered; }, removeListener: function removeListener(name, handler) { if (name !== 'beforeExit' && name !== 'exit') { return this; } const cb = localReflectApply(localWeakMapGet, LISTENERS, [handler]); if (cb) localProcess.removeListener(name, cb); return this; }, umask: function umask() { if (arguments.length) { throw new LocalError('Access denied to set umask.'); } return localProcess.umask(); } }; if (optionConsole === 'inherit') { global.console = host.console; } else if (optionConsole === 'redirect') { global.console = { debug(...args) { vmEmitArgs('console.debug', args); }, log(...args) { vmEmitArgs('console.log', args); }, info(...args) { vmEmitArgs('console.info', args); }, warn(...args) { vmEmitArgs('console.warn', args); }, error(...args) { vmEmitArgs('console.error', args); }, dir(...args) { vmEmitArgs('console.dir', args); }, time() {}, timeEnd() {}, trace(...args) { vmEmitArgs('console.trace', args); } }; } return { __proto__: null, Module, jsonParse: JSON.parse, createRequireForModule, requireImpl }; ```
/content/code_sandbox/node_modules/vm2/lib/setup-node-sandbox.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,900
```javascript /* global host, bridge, data, context */ 'use strict'; const { Object: localObject, Array: localArray, Error: LocalError, Reflect: localReflect, Proxy: LocalProxy, WeakMap: LocalWeakMap, Function: localFunction, Promise: localPromise, eval: localEval } = global; const { freeze: localObjectFreeze } = localObject; const { getPrototypeOf: localReflectGetPrototypeOf, apply: localReflectApply, deleteProperty: localReflectDeleteProperty, has: localReflectHas, defineProperty: localReflectDefineProperty, setPrototypeOf: localReflectSetPrototypeOf, getOwnPropertyDescriptor: localReflectGetOwnPropertyDescriptor } = localReflect; const { isArray: localArrayIsArray } = localArray; const { ensureThis, ReadOnlyHandler, from, fromWithFactory, readonlyFactory, connect, addProtoMapping, VMError, ReadOnlyMockHandler } = bridge; const { allowAsync, GeneratorFunction, AsyncFunction, AsyncGeneratorFunction } = data; const { get: localWeakMapGet, set: localWeakMapSet } = LocalWeakMap.prototype; function localUnexpected() { return new VMError('Should not happen'); } // global is originally prototype of host.Object so it can be used to climb up from the sandbox. if (!localReflectSetPrototypeOf(context, localObject.prototype)) throw localUnexpected(); Object.defineProperties(global, { global: {value: global, writable: true, configurable: true, enumerable: true}, globalThis: {value: global, writable: true, configurable: true}, GLOBAL: {value: global, writable: true, configurable: true}, root: {value: global, writable: true, configurable: true} }); if (!localReflectDefineProperty(global, 'VMError', { __proto__: null, value: VMError, writable: true, enumerable: false, configurable: true })) throw localUnexpected(); // Fixes buffer unsafe allocation /* eslint-disable no-use-before-define */ class BufferHandler extends ReadOnlyHandler { apply(target, thiz, args) { if (args.length > 0 && typeof args[0] === 'number') { return LocalBuffer.alloc(args[0]); } return localReflectApply(LocalBuffer.from, LocalBuffer, args); } construct(target, args, newTarget) { if (args.length > 0 && typeof args[0] === 'number') { return LocalBuffer.alloc(args[0]); } return localReflectApply(LocalBuffer.from, LocalBuffer, args); } } /* eslint-enable no-use-before-define */ const LocalBuffer = fromWithFactory(obj => new BufferHandler(obj), host.Buffer); if (!localReflectDefineProperty(global, 'Buffer', { __proto__: null, value: LocalBuffer, writable: true, enumerable: false, configurable: true })) throw localUnexpected(); addProtoMapping(LocalBuffer.prototype, host.Buffer.prototype, 'Uint8Array'); /** * * @param {*} size Size of new buffer * @this LocalBuffer * @return {LocalBuffer} */ function allocUnsafe(size) { return LocalBuffer.alloc(size); } connect(allocUnsafe, host.Buffer.allocUnsafe); /** * * @param {*} size Size of new buffer * @this LocalBuffer * @return {LocalBuffer} */ function allocUnsafeSlow(size) { return LocalBuffer.alloc(size); } connect(allocUnsafeSlow, host.Buffer.allocUnsafeSlow); /** * Replacement for Buffer inspect * * @param {*} recurseTimes * @param {*} ctx * @this LocalBuffer * @return {string} */ function inspect(recurseTimes, ctx) { // Mimic old behavior, could throw but didn't pass a test. const max = host.INSPECT_MAX_BYTES; const actualMax = Math.min(max, this.length); const remaining = this.length - max; let str = this.hexSlice(0, actualMax).replace(/(.{2})/g, '$1 ').trim(); if (remaining > 0) str += ` ... ${remaining} more byte${remaining > 1 ? 's' : ''}`; return `<${this.constructor.name} ${str}>`; } connect(inspect, host.Buffer.prototype.inspect); connect(localFunction.prototype.bind, host.Function.prototype.bind); connect(localObject.prototype.__defineGetter__, host.Object.prototype.__defineGetter__); connect(localObject.prototype.__defineSetter__, host.Object.prototype.__defineSetter__); connect(localObject.prototype.__lookupGetter__, host.Object.prototype.__lookupGetter__); connect(localObject.prototype.__lookupSetter__, host.Object.prototype.__lookupSetter__); /* * PrepareStackTrace sanitization */ const oldPrepareStackTraceDesc = localReflectGetOwnPropertyDescriptor(LocalError, 'prepareStackTrace'); let currentPrepareStackTrace = LocalError.prepareStackTrace; const wrappedPrepareStackTrace = new LocalWeakMap(); if (typeof currentPrepareStackTrace === 'function') { wrappedPrepareStackTrace.set(currentPrepareStackTrace, currentPrepareStackTrace); } let OriginalCallSite; LocalError.prepareStackTrace = (e, sst) => { OriginalCallSite = sst[0].constructor; }; new LocalError().stack; if (typeof OriginalCallSite === 'function') { LocalError.prepareStackTrace = undefined; function makeCallSiteGetters(list) { const callSiteGetters = []; for (let i=0; i<list.length; i++) { const name = list[i]; const func = OriginalCallSite.prototype[name]; callSiteGetters[i] = {__proto__: null, name, propName: '_' + name, func: (thiz) => { return localReflectApply(func, thiz, []); } }; } return callSiteGetters; } function applyCallSiteGetters(thiz, callSite, getters) { for (let i=0; i<getters.length; i++) { const getter = getters[i]; localReflectDefineProperty(thiz, getter.propName, { __proto__: null, value: getter.func(callSite) }); } } const callSiteGetters = makeCallSiteGetters([ 'getTypeName', 'getFunctionName', 'getMethodName', 'getFileName', 'getLineNumber', 'getColumnNumber', 'getEvalOrigin', 'isToplevel', 'isEval', 'isNative', 'isConstructor', 'isAsync', 'isPromiseAll', 'getPromiseIndex' ]); class CallSite { constructor(callSite) { applyCallSiteGetters(this, callSite, callSiteGetters); } getThis() { return undefined; } getFunction() { return undefined; } toString() { return 'CallSite {}'; } } for (let i=0; i<callSiteGetters.length; i++) { const name = callSiteGetters[i].name; const funcProp = localReflectGetOwnPropertyDescriptor(OriginalCallSite.prototype, name); if (!funcProp) continue; const propertyName = callSiteGetters[i].propName; const func = {func() { return this[propertyName]; }}.func; const nameProp = localReflectGetOwnPropertyDescriptor(func, 'name'); if (!nameProp) throw localUnexpected(); nameProp.value = name; if (!localReflectDefineProperty(func, 'name', nameProp)) throw localUnexpected(); funcProp.value = func; if (!localReflectDefineProperty(CallSite.prototype, name, funcProp)) throw localUnexpected(); } if (!localReflectDefineProperty(LocalError, 'prepareStackTrace', { configurable: false, enumerable: false, get() { return currentPrepareStackTrace; }, set(value) { if (typeof(value) !== 'function') { currentPrepareStackTrace = value; return; } const wrapped = localReflectApply(localWeakMapGet, wrappedPrepareStackTrace, [value]); if (wrapped) { currentPrepareStackTrace = wrapped; return; } const newWrapped = (error, sst) => { if (localArrayIsArray(sst)) { for (let i=0; i < sst.length; i++) { const cs = sst[i]; if (typeof cs === 'object' && localReflectGetPrototypeOf(cs) === OriginalCallSite.prototype) { sst[i] = new CallSite(cs); } } } return value(error, sst); }; localReflectApply(localWeakMapSet, wrappedPrepareStackTrace, [value, newWrapped]); localReflectApply(localWeakMapSet, wrappedPrepareStackTrace, [newWrapped, newWrapped]); currentPrepareStackTrace = newWrapped; } })) throw localUnexpected(); } else if (oldPrepareStackTraceDesc) { localReflectDefineProperty(LocalError, 'prepareStackTrace', oldPrepareStackTraceDesc); } else { localReflectDeleteProperty(LocalError, 'prepareStackTrace'); } /* * Exception sanitization */ const withProxy = localObjectFreeze({ __proto__: null, has(target, key) { if (key === host.INTERNAL_STATE_NAME) return false; return localReflectHas(target, key); } }); const interanState = localObjectFreeze({ __proto__: null, wrapWith(x) { if (x === null || x === undefined) return x; return new LocalProxy(localObject(x), withProxy); }, handleException: ensureThis, import(what) { throw new VMError('Dynamic Import not supported'); } }); if (!localReflectDefineProperty(global, host.INTERNAL_STATE_NAME, { __proto__: null, configurable: false, enumerable: false, writable: false, value: interanState })) throw localUnexpected(); /* * Eval sanitization */ function throwAsync() { return new VMError('Async not available'); } function makeFunction(inputArgs, isAsync, isGenerator) { const lastArgs = inputArgs.length - 1; let code = lastArgs >= 0 ? `${inputArgs[lastArgs]}` : ''; let args = lastArgs > 0 ? `${inputArgs[0]}` : ''; for (let i = 1; i < lastArgs; i++) { args += `,${inputArgs[i]}`; } try { code = host.transformAndCheck(args, code, isAsync, isGenerator, allowAsync); } catch (e) { throw bridge.from(e); } return localEval(code); } const FunctionHandler = { __proto__: null, apply(target, thiz, args) { return makeFunction(args, this.isAsync, this.isGenerator); }, construct(target, args, newTarget) { return makeFunction(args, this.isAsync, this.isGenerator); } }; const EvalHandler = { __proto__: null, apply(target, thiz, args) { if (args.length === 0) return undefined; let code = `${args[0]}`; try { code = host.transformAndCheck(null, code, false, false, allowAsync); } catch (e) { throw bridge.from(e); } return localEval(code); } }; const AsyncErrorHandler = { __proto__: null, apply(target, thiz, args) { throw throwAsync(); }, construct(target, args, newTarget) { throw throwAsync(); } }; function makeCheckFunction(isAsync, isGenerator) { if (isAsync && !allowAsync) return AsyncErrorHandler; return { __proto__: FunctionHandler, isAsync, isGenerator }; } function overrideWithProxy(obj, prop, value, handler) { const proxy = new LocalProxy(value, handler); if (!localReflectDefineProperty(obj, prop, {__proto__: null, value: proxy})) throw localUnexpected(); return proxy; } const proxiedFunction = overrideWithProxy(localFunction.prototype, 'constructor', localFunction, makeCheckFunction(false, false)); if (GeneratorFunction) { if (!localReflectSetPrototypeOf(GeneratorFunction, proxiedFunction)) throw localUnexpected(); overrideWithProxy(GeneratorFunction.prototype, 'constructor', GeneratorFunction, makeCheckFunction(false, true)); } if (AsyncFunction) { if (!localReflectSetPrototypeOf(AsyncFunction, proxiedFunction)) throw localUnexpected(); overrideWithProxy(AsyncFunction.prototype, 'constructor', AsyncFunction, makeCheckFunction(true, false)); } if (AsyncGeneratorFunction) { if (!localReflectSetPrototypeOf(AsyncGeneratorFunction, proxiedFunction)) throw localUnexpected(); overrideWithProxy(AsyncGeneratorFunction.prototype, 'constructor', AsyncGeneratorFunction, makeCheckFunction(true, true)); } global.Function = proxiedFunction; global.eval = new LocalProxy(localEval, EvalHandler); /* * Promise sanitization */ if (localPromise && !allowAsync) { const PromisePrototype = localPromise.prototype; overrideWithProxy(PromisePrototype, 'then', PromisePrototype.then, AsyncErrorHandler); // This seems not to work, and will produce // UnhandledPromiseRejectionWarning: TypeError: Method Promise.prototype.then called on incompatible receiver [object Object]. // This is likely caused since the host.Promise.prototype.then cannot use the VM Proxy object. // Contextify.connect(host.Promise.prototype.then, Promise.prototype.then); if (PromisePrototype.finally) { overrideWithProxy(PromisePrototype, 'finally', PromisePrototype.finally, AsyncErrorHandler); // Contextify.connect(host.Promise.prototype.finally, Promise.prototype.finally); } if (Promise.prototype.catch) { overrideWithProxy(PromisePrototype, 'catch', PromisePrototype.catch, AsyncErrorHandler); // Contextify.connect(host.Promise.prototype.catch, Promise.prototype.catch); } } function readonly(other, mock) { // Note: other@other(unsafe) mock@other(unsafe) returns@this(unsafe) throws@this(unsafe) if (!mock) return fromWithFactory(readonlyFactory, other); const tmock = from(mock); return fromWithFactory(obj=>new ReadOnlyMockHandler(obj, tmock), other); } return { __proto__: null, readonly, global }; ```
/content/code_sandbox/node_modules/vm2/lib/setup-sandbox.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,031
```javascript 'use strict'; // Translate the old options to the new Resolver functionality. const fs = require('fs'); const pa = require('path'); const nmod = require('module'); const {EventEmitter} = require('events'); const util = require('util'); const { Resolver, DefaultResolver } = require('./resolver'); const {VMScript} = require('./script'); const {VM} = require('./vm'); const {VMError} = require('./bridge'); /** * Require wrapper to be able to annotate require with webpackIgnore. * * @private * @param {string} moduleName - Name of module to load. * @return {*} Module exports. */ function defaultRequire(moduleName) { // Set module.parser.javascript.commonjsMagicComments=true in your webpack config. // eslint-disable-next-line global-require return require(/* webpackIgnore: true */ moduleName); } // source: path_to_url#Escaping function escapeRegExp(string) { return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } function makeExternalMatcherRegex(obj) { return escapeRegExp(obj).replace(/\\\\|\//g, '[\\\\/]') .replace(/\\\*\\\*/g, '.*').replace(/\\\*/g, '[^\\\\/]*').replace(/\\\?/g, '[^\\\\/]'); } function makeExternalMatcher(obj) { const regexString = makeExternalMatcherRegex(obj); return new RegExp(`[\\\\/]node_modules[\\\\/]${regexString}(?:[\\\\/](?!(?:.*[\\\\/])?node_modules[\\\\/]).*)?$`); } class LegacyResolver extends DefaultResolver { constructor(builtinModules, checkPath, globalPaths, pathContext, customResolver, hostRequire, compiler, externals, allowTransitive) { super(builtinModules, checkPath, globalPaths, pathContext, customResolver, hostRequire, compiler); this.externals = externals; this.currMod = undefined; this.trustedMods = new WeakMap(); this.allowTransitive = allowTransitive; } isPathAllowed(path) { return this.isPathAllowedForModule(path, this.currMod); } isPathAllowedForModule(path, mod) { if (!super.isPathAllowed(path)) return false; if (mod) { if (mod.allowTransitive) return true; if (path.startsWith(mod.path)) { const rem = path.slice(mod.path.length); if (!/(?:^|[\\\\/])node_modules(?:$|[\\\\/])/.test(rem)) return true; } } return this.externals.some(regex => regex.test(path)); } registerModule(mod, filename, path, parent, direct) { const trustedParent = this.trustedMods.get(parent); this.trustedMods.set(mod, { filename, path, paths: this.genLookupPaths(path), allowTransitive: this.allowTransitive && ((direct && trustedParent && trustedParent.allowTransitive) || this.externals.some(regex => regex.test(filename))) }); } resolveFull(mod, x, options, ext, direct) { this.currMod = undefined; if (!direct) return super.resolveFull(mod, x, options, ext, false); const trustedMod = this.trustedMods.get(mod); if (!trustedMod || mod.path !== trustedMod.path) return super.resolveFull(mod, x, options, ext, false); const paths = [...mod.paths]; if (paths.length === trustedMod.length) { for (let i = 0; i < paths.length; i++) { if (paths[i] !== trustedMod.paths[i]) { return super.resolveFull(mod, x, options, ext, false); } } } const extCopy = Object.assign({__proto__: null}, ext); try { this.currMod = trustedMod; return super.resolveFull(trustedMod, x, undefined, extCopy, true); } finally { this.currMod = undefined; } } checkAccess(mod, filename) { const trustedMod = this.trustedMods.get(mod); if ((!trustedMod || trustedMod.filename !== filename) && !this.isPathAllowedForModule(filename, undefined)) { throw new VMError(`Module '${filename}' is not allowed to be required. The path is outside the border!`, 'EDENIED'); } } loadJS(vm, mod, filename) { filename = this.pathResolve(filename); this.checkAccess(mod, filename); if (this.pathContext(filename, 'js') === 'sandbox') { const trustedMod = this.trustedMods.get(mod); const script = this.readScript(filename); vm.run(script, {filename, strict: true, module: mod, wrapper: 'none', dirname: trustedMod ? trustedMod.path : mod.path}); } else { const m = this.hostRequire(filename); mod.exports = vm.readonly(m); } } } function defaultBuiltinLoader(resolver, vm, id) { const mod = resolver.hostRequire(id); return vm.readonly(mod); } const eventsModules = new WeakMap(); function defaultBuiltinLoaderEvents(resolver, vm, id) { return eventsModules.get(vm); } let cacheBufferScript; function defaultBuiltinLoaderBuffer(resolver, vm, id) { if (!cacheBufferScript) { cacheBufferScript = new VMScript('return buffer=>({Buffer: buffer});', {__proto__: null, filename: 'buffer.js'}); } const makeBuffer = vm.run(cacheBufferScript, {__proto__: null, strict: true, wrapper: 'none'}); return makeBuffer(Buffer); } let cacheUtilScript; function defaultBuiltinLoaderUtil(resolver, vm, id) { if (!cacheUtilScript) { cacheUtilScript = new VMScript(`return function inherits(ctor, superCtor) { ctor.super_ = superCtor; Object.setPrototypeOf(ctor.prototype, superCtor.prototype); }`, {__proto__: null, filename: 'util.js'}); } const inherits = vm.run(cacheUtilScript, {__proto__: null, strict: true, wrapper: 'none'}); const copy = Object.assign({}, util); copy.inherits = inherits; return vm.readonly(copy); } const BUILTIN_MODULES = (nmod.builtinModules || Object.getOwnPropertyNames(process.binding('natives'))).filter(s=>!s.startsWith('internal/')); let EventEmitterReferencingAsyncResourceClass = null; if (EventEmitter.EventEmitterAsyncResource) { // eslint-disable-next-line global-require const {AsyncResource} = require('async_hooks'); const kEventEmitter = Symbol('kEventEmitter'); class EventEmitterReferencingAsyncResource extends AsyncResource { constructor(ee, type, options) { super(type, options); this[kEventEmitter] = ee; } get eventEmitter() { return this[kEventEmitter]; } } EventEmitterReferencingAsyncResourceClass = EventEmitterReferencingAsyncResource; } let cacheEventsScript; const SPECIAL_MODULES = { events(vm) { if (!cacheEventsScript) { const eventsSource = fs.readFileSync(`${__dirname}/events.js`, 'utf8'); cacheEventsScript = new VMScript(`(function (fromhost) { const module = {}; module.exports={};{ ${eventsSource} } return module.exports;})`, {filename: 'events.js'}); } const closure = VM.prototype.run.call(vm, cacheEventsScript); const eventsInstance = closure(vm.readonly({ kErrorMonitor: EventEmitter.errorMonitor, once: EventEmitter.once, on: EventEmitter.on, getEventListeners: EventEmitter.getEventListeners, EventEmitterReferencingAsyncResource: EventEmitterReferencingAsyncResourceClass })); eventsModules.set(vm, eventsInstance); vm._addProtoMapping(EventEmitter.prototype, eventsInstance.EventEmitter.prototype); return defaultBuiltinLoaderEvents; }, buffer(vm) { return defaultBuiltinLoaderBuffer; }, util(vm) { return defaultBuiltinLoaderUtil; } }; function addDefaultBuiltin(builtins, key, vm) { if (builtins[key]) return; const special = SPECIAL_MODULES[key]; builtins[key] = special ? special(vm) : defaultBuiltinLoader; } function genBuiltinsFromOptions(vm, builtinOpt, mockOpt, override) { const builtins = {__proto__: null}; if (mockOpt) { const keys = Object.getOwnPropertyNames(mockOpt); for (let i = 0; i < keys.length; i++) { const key = keys[i]; builtins[key] = (resolver, tvm, id) => tvm.readonly(mockOpt[key]); } } if (override) { const keys = Object.getOwnPropertyNames(override); for (let i = 0; i < keys.length; i++) { const key = keys[i]; builtins[key] = override[key]; } } if (Array.isArray(builtinOpt)) { const def = builtinOpt.indexOf('*') >= 0; if (def) { for (let i = 0; i < BUILTIN_MODULES.length; i++) { const name = BUILTIN_MODULES[i]; if (builtinOpt.indexOf(`-${name}`) === -1) { addDefaultBuiltin(builtins, name, vm); } } } else { for (let i = 0; i < BUILTIN_MODULES.length; i++) { const name = BUILTIN_MODULES[i]; if (builtinOpt.indexOf(name) !== -1) { addDefaultBuiltin(builtins, name, vm); } } } } else if (builtinOpt) { for (let i = 0; i < BUILTIN_MODULES.length; i++) { const name = BUILTIN_MODULES[i]; if (builtinOpt[name]) { addDefaultBuiltin(builtins, name, vm); } } } return builtins; } function defaultCustomResolver() { return undefined; } const DENY_RESOLVER = new Resolver({__proto__: null}, [], id => { throw new VMError(`Access denied to require '${id}'`, 'EDENIED'); }); function resolverFromOptions(vm, options, override, compiler) { if (!options) { if (!override) return DENY_RESOLVER; const builtins = genBuiltinsFromOptions(vm, undefined, undefined, override); return new Resolver(builtins, [], defaultRequire); } const { builtin: builtinOpt, mock: mockOpt, external: externalOpt, root: rootPaths, resolve: customResolver, customRequire: hostRequire = defaultRequire, context = 'host' } = options; const builtins = genBuiltinsFromOptions(vm, builtinOpt, mockOpt, override); if (!externalOpt) return new Resolver(builtins, [], hostRequire); let checkPath; if (rootPaths) { const checkedRootPaths = (Array.isArray(rootPaths) ? rootPaths : [rootPaths]).map(f => pa.resolve(f)); checkPath = (filename) => { return checkedRootPaths.some(path => { if (!filename.startsWith(path)) return false; const len = path.length; if (filename.length === len || (len > 0 && path[len-1] === pa.sep)) return true; const sep = filename[len]; return sep === '/' || sep === pa.sep; }); }; } else { checkPath = () => true; } let newCustomResolver = defaultCustomResolver; let externals = undefined; let external = undefined; if (customResolver) { let externalCache; newCustomResolver = (resolver, x, path, extList) => { if (external && !(resolver.pathIsAbsolute(x) || resolver.pathIsRelative(x))) { if (!externalCache) { externalCache = external.map(ext => new RegExp(makeExternalMatcherRegex(ext))); } if (!externalCache.some(regex => regex.test(x))) return undefined; } const resolved = customResolver(x, path); if (!resolved) return undefined; if (externals) externals.push(new RegExp('^' + escapeRegExp(resolved))); return resolver.loadAsFileOrDirecotry(resolved, extList); }; } if (typeof externalOpt !== 'object') { return new DefaultResolver(builtins, checkPath, [], () => context, newCustomResolver, hostRequire, compiler); } let transitive = false; if (Array.isArray(externalOpt)) { external = externalOpt; } else { external = externalOpt.modules; transitive = context === 'sandbox' && externalOpt.transitive; } externals = external.map(makeExternalMatcher); return new LegacyResolver(builtins, checkPath, [], () => context, newCustomResolver, hostRequire, compiler, externals, transitive); } exports.resolverFromOptions = resolverFromOptions; ```
/content/code_sandbox/node_modules/vm2/lib/resolver-compat.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,813
```javascript 'use strict'; // The Resolver is currently experimental and might be exposed to users in the future. const pa = require('path'); const fs = require('fs'); const { VMError } = require('./bridge'); const { VMScript } = require('./script'); // This should match. Note that '\', '%' are invalid characters // 1. name/.* // 2. @scope/name/.* const EXPORTS_PATTERN = /^((?:@[^/\\%]+\/)?[^/\\%]+)(\/.*)?$/; // See path_to_url#integer-index function isArrayIndex(key) { const keyNum = +key; if (`${keyNum}` !== key) return false; return keyNum >= 0 && keyNum < 0xFFFFFFFF; } class Resolver { constructor(builtinModules, globalPaths, hostRequire) { this.builtinModules = builtinModules; this.globalPaths = globalPaths; this.hostRequire = hostRequire; } init(vm) { } pathResolve(path) { return pa.resolve(path); } pathIsRelative(path) { if (path === '' || path[0] !== '.') return false; if (path.length === 1) return true; const idx = path[1] === '.' ? 2 : 1; if (path.length <= idx) return false; return path[idx] === '/' || path[idx] === pa.sep; } pathIsAbsolute(path) { return pa.isAbsolute(path); } pathConcat(...paths) { return pa.join(...paths); } pathBasename(path) { return pa.basename(path); } pathDirname(path) { return pa.dirname(path); } lookupPaths(mod, id) { if (typeof id === 'string') throw new Error('Id is not a string'); if (this.pathIsRelative(id)) return [mod.path || '.']; return [...mod.paths, ...this.globalPaths]; } getBuiltinModulesList() { return Object.getOwnPropertyNames(this.builtinModules); } loadBuiltinModule(vm, id) { const handler = this.builtinModules[id]; return handler && handler(this, vm, id); } loadJS(vm, mod, filename) { throw new VMError(`Access denied to require '${filename}'`, 'EDENIED'); } loadJSON(vm, mod, filename) { throw new VMError(`Access denied to require '${filename}'`, 'EDENIED'); } loadNode(vm, mod, filename) { throw new VMError(`Access denied to require '${filename}'`, 'EDENIED'); } registerModule(mod, filename, path, parent, direct) { } resolve(mod, x, options, ext, direct) { if (typeof x !== 'string') throw new Error('Id is not a string'); if (x.startsWith('node:') || this.builtinModules[x]) { // a. return the core module // b. STOP return x; } return this.resolveFull(mod, x, options, ext, direct); } resolveFull(mod, x, options, ext, direct) { // 7. THROW "not found" throw new VMError(`Cannot find module '${x}'`, 'ENOTFOUND'); } // NODE_MODULES_PATHS(START) genLookupPaths(path) { // 1. let PARTS = path split(START) // 2. let I = count of PARTS - 1 // 3. let DIRS = [] const dirs = []; // 4. while I >= 0, while (true) { const name = this.pathBasename(path); // a. if PARTS[I] = "node_modules" CONTINUE if (name !== 'node_modules') { // b. DIR = path join(PARTS[0 .. I] + "node_modules") // c. DIRS = DIR + DIRS // Note: this seems wrong. Should be DIRS + DIR dirs.push(this.pathConcat(path, 'node_modules')); } const dir = this.pathDirname(path); if (dir == path) break; // d. let I = I - 1 path = dir; } return dirs; // This is done later on // 5. return DIRS + GLOBAL_FOLDERS } } class DefaultResolver extends Resolver { constructor(builtinModules, checkPath, globalPaths, pathContext, customResolver, hostRequire, compiler) { super(builtinModules, globalPaths, hostRequire); this.checkPath = checkPath; this.pathContext = pathContext; this.customResolver = customResolver; this.compiler = compiler; this.packageCache = {__proto__: null}; this.scriptCache = {__proto__: null}; } isPathAllowed(path) { return this.checkPath(path); } pathTestIsDirectory(path) { try { const stat = fs.statSync(path, {__proto__: null, throwIfNoEntry: false}); return stat && stat.isDirectory(); } catch (e) { return false; } } pathTestIsFile(path) { try { const stat = fs.statSync(path, {__proto__: null, throwIfNoEntry: false}); return stat && stat.isFile(); } catch (e) { return false; } } readFile(path) { return fs.readFileSync(path, {encoding: 'utf8'}); } readFileWhenExists(path) { return this.pathTestIsFile(path) ? this.readFile(path) : undefined; } readScript(filename) { let script = this.scriptCache[filename]; if (!script) { script = new VMScript(this.readFile(filename), {filename, compiler: this.compiler}); this.scriptCache[filename] = script; } return script; } checkAccess(mod, filename) { if (!this.isPathAllowed(filename)) { throw new VMError(`Module '${filename}' is not allowed to be required. The path is outside the border!`, 'EDENIED'); } } loadJS(vm, mod, filename) { filename = this.pathResolve(filename); this.checkAccess(mod, filename); if (this.pathContext(filename, 'js') === 'sandbox') { const script = this.readScript(filename); vm.run(script, {filename, strict: true, module: mod, wrapper: 'none', dirname: mod.path}); } else { const m = this.hostRequire(filename); mod.exports = vm.readonly(m); } } loadJSON(vm, mod, filename) { filename = this.pathResolve(filename); this.checkAccess(mod, filename); const json = this.readFile(filename); mod.exports = vm._jsonParse(json); } loadNode(vm, mod, filename) { filename = this.pathResolve(filename); this.checkAccess(mod, filename); if (this.pathContext(filename, 'node') === 'sandbox') throw new VMError('Native modules can be required only with context set to \'host\'.'); const m = this.hostRequire(filename); mod.exports = vm.readonly(m); } // require(X) from module at path Y resolveFull(mod, x, options, ext, direct) { // Note: core module handled by caller const extList = Object.getOwnPropertyNames(ext); const path = mod.path || '.'; // 5. LOAD_PACKAGE_SELF(X, dirname(Y)) let f = this.loadPackageSelf(x, path, extList); if (f) return f; // 4. If X begins with '#' if (x[0] === '#') { // a. LOAD_PACKAGE_IMPORTS(X, dirname(Y)) f = this.loadPackageImports(x, path, extList); if (f) return f; } // 2. If X begins with '/' if (this.pathIsAbsolute(x)) { // a. set Y to be the filesystem root f = this.loadAsFileOrDirecotry(x, extList); if (f) return f; // c. THROW "not found" throw new VMError(`Cannot find module '${x}'`, 'ENOTFOUND'); // 3. If X begins with './' or '/' or '../' } else if (this.pathIsRelative(x)) { if (typeof options === 'object' && options !== null) { const paths = options.paths; if (Array.isArray(paths)) { for (let i = 0; i < paths.length; i++) { // a. LOAD_AS_FILE(Y + X) // b. LOAD_AS_DIRECTORY(Y + X) f = this.loadAsFileOrDirecotry(this.pathConcat(paths[i], x), extList); if (f) return f; } } else if (paths === undefined) { // a. LOAD_AS_FILE(Y + X) // b. LOAD_AS_DIRECTORY(Y + X) f = this.loadAsFileOrDirecotry(this.pathConcat(path, x), extList); if (f) return f; } else { throw new VMError('Invalid options.paths option.'); } } else { // a. LOAD_AS_FILE(Y + X) // b. LOAD_AS_DIRECTORY(Y + X) f = this.loadAsFileOrDirecotry(this.pathConcat(path, x), extList); if (f) return f; } // c. THROW "not found" throw new VMError(`Cannot find module '${x}'`, 'ENOTFOUND'); } let dirs; if (typeof options === 'object' && options !== null) { const paths = options.paths; if (Array.isArray(paths)) { dirs = []; for (let i = 0; i < paths.length; i++) { const lookups = this.genLookupPaths(paths[i]); for (let j = 0; j < lookups.length; j++) { if (!dirs.includes(lookups[j])) dirs.push(lookups[j]); } if (i === 0) { const globalPaths = this.globalPaths; for (let j = 0; j < globalPaths.length; j++) { if (!dirs.includes(globalPaths[j])) dirs.push(globalPaths[j]); } } } } else if (paths === undefined) { dirs = [...mod.paths, ...this.globalPaths]; } else { throw new VMError('Invalid options.paths option.'); } } else { dirs = [...mod.paths, ...this.globalPaths]; } // 6. LOAD_NODE_MODULES(X, dirname(Y)) f = this.loadNodeModules(x, dirs, extList); if (f) return f; f = this.customResolver(this, x, path, extList); if (f) return f; return super.resolveFull(mod, x, options, ext, direct); } loadAsFileOrDirecotry(x, extList) { // a. LOAD_AS_FILE(X) const f = this.loadAsFile(x, extList); if (f) return f; // b. LOAD_AS_DIRECTORY(X) return this.loadAsDirectory(x, extList); } tryFile(x) { x = this.pathResolve(x); return this.isPathAllowed(x) && this.pathTestIsFile(x) ? x : undefined; } tryWithExtension(x, extList) { for (let i = 0; i < extList.length; i++) { const ext = extList[i]; if (ext !== this.pathBasename(ext)) continue; const f = this.tryFile(x + ext); if (f) return f; } return undefined; } readPackage(path) { const packagePath = this.pathResolve(this.pathConcat(path, 'package.json')); const cache = this.packageCache[packagePath]; if (cache !== undefined) return cache; if (!this.isPathAllowed(packagePath)) return undefined; const content = this.readFileWhenExists(packagePath); if (!content) { this.packageCache[packagePath] = false; return false; } let parsed; try { parsed = JSON.parse(content); } catch (e) { e.path = packagePath; e.message = 'Error parsing ' + packagePath + ': ' + e.message; throw e; } const filtered = { name: parsed.name, main: parsed.main, exports: parsed.exports, imports: parsed.imports, type: parsed.type }; this.packageCache[packagePath] = filtered; return filtered; } readPackageScope(path) { while (true) { const dir = this.pathDirname(path); if (dir === path) break; const basename = this.pathBasename(dir); if (basename === 'node_modules') break; const pack = this.readPackage(dir); if (pack) return {data: pack, scope: dir}; path = dir; } return {data: undefined, scope: undefined}; } // LOAD_AS_FILE(X) loadAsFile(x, extList) { // 1. If X is a file, load X as its file extension format. STOP const f = this.tryFile(x); if (f) return f; // 2. If X.js is a file, load X.js as JavaScript text. STOP // 3. If X.json is a file, parse X.json to a JavaScript Object. STOP // 4. If X.node is a file, load X.node as binary addon. STOP return this.tryWithExtension(x, extList); } // LOAD_INDEX(X) loadIndex(x, extList) { // 1. If X/index.js is a file, load X/index.js as JavaScript text. STOP // 2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP // 3. If X/index.node is a file, load X/index.node as binary addon. STOP return this.tryWithExtension(this.pathConcat(x, 'index'), extList); } // LOAD_AS_DIRECTORY(X) loadAsPackage(x, pack, extList) { // 1. If X/package.json is a file, // already done. if (pack) { // a. Parse X/package.json, and look for "main" field. // b. If "main" is a falsy value, GOTO 2. if (typeof pack.main === 'string') { // c. let M = X + (json main field) const m = this.pathConcat(x, pack.main); // d. LOAD_AS_FILE(M) let f = this.loadAsFile(m, extList); if (f) return f; // e. LOAD_INDEX(M) f = this.loadIndex(m, extList); if (f) return f; // f. LOAD_INDEX(X) DEPRECATED f = this.loadIndex(x, extList); if (f) return f; // g. THROW "not found" throw new VMError(`Cannot find module '${x}'`, 'ENOTFOUND'); } } // 2. LOAD_INDEX(X) return this.loadIndex(x, extList); } // LOAD_AS_DIRECTORY(X) loadAsDirectory(x, extList) { // 1. If X/package.json is a file, const pack = this.readPackage(x); return this.loadAsPackage(x, pack, extList); } // LOAD_NODE_MODULES(X, START) loadNodeModules(x, dirs, extList) { // 1. let DIRS = NODE_MODULES_PATHS(START) // This step is already done. // 2. for each DIR in DIRS: for (let i = 0; i < dirs.length; i++) { const dir = dirs[i]; // a. LOAD_PACKAGE_EXPORTS(X, DIR) let f = this.loadPackageExports(x, dir, extList); if (f) return f; // b. LOAD_AS_FILE(DIR/X) f = this.loadAsFile(dir + '/' + x, extList); if (f) return f; // c. LOAD_AS_DIRECTORY(DIR/X) f = this.loadAsDirectory(dir + '/' + x, extList); if (f) return f; } return undefined; } // LOAD_PACKAGE_IMPORTS(X, DIR) loadPackageImports(x, dir, extList) { // 1. Find the closest package scope SCOPE to DIR. const {data, scope} = this.readPackageScope(dir); // 2. If no scope was found, return. if (!data) return undefined; // 3. If the SCOPE/package.json "imports" is null or undefined, return. if (typeof data.imports !== 'object' || data.imports === null || Array.isArray(data.imports)) return undefined; // 4. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE), // ["node", "require"]) defined in the ESM resolver. // PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, conditions) // 1. Assert: specifier begins with "#". // 2. If specifier is exactly equal to "#" or starts with "#/", then if (x === '#' || x.startsWith('#/')) { // a. Throw an Invalid Module Specifier error. throw new VMError(`Invalid module specifier '${x}'`, 'ERR_INVALID_MODULE_SPECIFIER'); } // 3. Let packageURL be the result of LOOKUP_PACKAGE_SCOPE(parentURL). // Note: packageURL === parentURL === scope // 4. If packageURL is not null, then // Always true // a. Let pjson be the result of READ_PACKAGE_JSON(packageURL). // pjson === data // b. If pjson.imports is a non-null Object, then // Already tested // x. Let resolved be the result of PACKAGE_IMPORTS_EXPORTS_RESOLVE( specifier, pjson.imports, packageURL, true, conditions). const match = this.packageImportsExportsResolve(x, data.imports, scope, true, ['node', 'require'], extList); // y. If resolved is not null or undefined, return resolved. if (!match) { // 5. Throw a Package Import Not Defined error. throw new VMError(`Package import not defined for '${x}'`, 'ERR_PACKAGE_IMPORT_NOT_DEFINED'); } // END PACKAGE_IMPORTS_RESOLVE // 5. RESOLVE_ESM_MATCH(MATCH). return this.resolveEsmMatch(match, x, extList); } // LOAD_PACKAGE_EXPORTS(X, DIR) loadPackageExports(x, dir, extList) { // 1. Try to interpret X as a combination of NAME and SUBPATH where the name // may have a @scope/ prefix and the subpath begins with a slash (`/`). const res = x.match(EXPORTS_PATTERN); // 2. If X does not match this pattern or DIR/NAME/package.json is not a file, // return. if (!res) return undefined; const scope = this.pathConcat(dir, res[1]); const pack = this.readPackage(scope); if (!pack) return undefined; // 3. Parse DIR/NAME/package.json, and look for "exports" field. // 4. If "exports" is null or undefined, return. if (!pack.exports) return undefined; // 5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH, // `package.json` "exports", ["node", "require"]) defined in the ESM resolver. const match = this.packageExportsResolve(scope, '.' + (res[2] || ''), pack.exports, ['node', 'require'], extList); // 6. RESOLVE_ESM_MATCH(MATCH) return this.resolveEsmMatch(match, x, extList); } // LOAD_PACKAGE_SELF(X, DIR) loadPackageSelf(x, dir, extList) { // 1. Find the closest package scope SCOPE to DIR. const {data, scope} = this.readPackageScope(dir); // 2. If no scope was found, return. if (!data) return undefined; // 3. If the SCOPE/package.json "exports" is null or undefined, return. if (!data.exports) return undefined; // 4. If the SCOPE/package.json "name" is not the first segment of X, return. if (x !== data.name && !x.startsWith(data.name + '/')) return undefined; // 5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE), // "." + X.slice("name".length), `package.json` "exports", ["node", "require"]) // defined in the ESM resolver. const match = this.packageExportsResolve(scope, '.' + x.slice(data.name.length), data.exports, ['node', 'require'], extList); // 6. RESOLVE_ESM_MATCH(MATCH) return this.resolveEsmMatch(match, x, extList); } // RESOLVE_ESM_MATCH(MATCH) resolveEsmMatch(match, x, extList) { // 1. let { RESOLVED, EXACT } = MATCH const resolved = match; const exact = true; // 2. let RESOLVED_PATH = fileURLToPath(RESOLVED) const resolvedPath = resolved; let f; // 3. If EXACT is true, if (exact) { // a. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension // format. STOP f = this.tryFile(resolvedPath); // 4. Otherwise, if EXACT is false, } else { // a. LOAD_AS_FILE(RESOLVED_PATH) // b. LOAD_AS_DIRECTORY(RESOLVED_PATH) f = this.loadAsFileOrDirecotry(resolvedPath, extList); } if (f) return f; // 5. THROW "not found" throw new VMError(`Cannot find module '${x}'`, 'ENOTFOUND'); } // PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, exports, conditions) packageExportsResolve(packageURL, subpath, rexports, conditions, extList) { // 1. If exports is an Object with both a key starting with "." and a key not starting with ".", throw an Invalid Package Configuration error. let hasDots = false; if (typeof rexports === 'object' && !Array.isArray(rexports)) { const keys = Object.getOwnPropertyNames(rexports); if (keys.length > 0) { hasDots = keys[0][0] === '.'; for (let i = 0; i < keys.length; i++) { if (hasDots !== (keys[i][0] === '.')) { throw new VMError('Invalid package configuration', 'ERR_INVALID_PACKAGE_CONFIGURATION'); } } } } // 2. If subpath is equal to ".", then if (subpath === '.') { // a. Let mainExport be undefined. let mainExport = undefined; // b. If exports is a String or Array, or an Object containing no keys starting with ".", then if (typeof rexports === 'string' || Array.isArray(rexports) || !hasDots) { // x. Set mainExport to exports. mainExport = rexports; // c. Otherwise if exports is an Object containing a "." property, then } else if (hasDots) { // x. Set mainExport to exports["."]. mainExport = rexports['.']; } // d. If mainExport is not undefined, then if (mainExport) { // x. Let resolved be the result of PACKAGE_TARGET_RESOLVE( packageURL, mainExport, "", false, false, conditions). const resolved = this.packageTargetResolve(packageURL, mainExport, '', false, false, conditions, extList); // y. If resolved is not null or undefined, return resolved. if (resolved) return resolved; } // 3. Otherwise, if exports is an Object and all keys of exports start with ".", then } else if (hasDots) { // a. Let matchKey be the string "./" concatenated with subpath. // Note: Here subpath starts already with './' // b. Let resolved be the result of PACKAGE_IMPORTS_EXPORTS_RESOLVE( matchKey, exports, packageURL, false, conditions). const resolved = this.packageImportsExportsResolve(subpath, rexports, packageURL, false, conditions, extList); // c. If resolved is not null or undefined, return resolved. if (resolved) return resolved; } // 4. Throw a Package Path Not Exported error. throw new VMError(`Package path '${subpath}' is not exported`, 'ERR_PACKAGE_PATH_NOT_EXPORTED'); } // PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL, isImports, conditions) packageImportsExportsResolve(matchKey, matchObj, packageURL, isImports, conditions, extList) { // 1. If matchKey is a key of matchObj and does not contain "*", then let target = matchObj[matchKey]; if (target && matchKey.indexOf('*') === -1) { // a. Let target be the value of matchObj[matchKey]. // b. Return the result of PACKAGE_TARGET_RESOLVE(packageURL, target, "", false, isImports, conditions). return this.packageTargetResolve(packageURL, target, '', false, isImports, conditions, extList); } // 2. Let expansionKeys be the list of keys of matchObj containing only a single "*", // sorted by the sorting function PATTERN_KEY_COMPARE which orders in descending order of specificity. const expansionKeys = Object.getOwnPropertyNames(matchObj); let bestKey = ''; let bestSubpath; // 3. For each key expansionKey in expansionKeys, do for (let i = 0; i < expansionKeys.length; i++) { const expansionKey = expansionKeys[i]; if (matchKey.length < expansionKey.length) continue; // a. Let patternBase be the substring of expansionKey up to but excluding the first "*" character. const star = expansionKey.indexOf('*'); if (star === -1) continue; // Note: expansionKeys was not filtered const patternBase = expansionKey.slice(0, star); // b. If matchKey starts with but is not equal to patternBase, then if (matchKey.startsWith(patternBase) && expansionKey.indexOf('*', star + 1) === -1) { // Note: expansionKeys was not filtered // 1. Let patternTrailer be the substring of expansionKey from the index after the first "*" character. const patternTrailer = expansionKey.slice(star + 1); // 2. If patternTrailer has zero length, or if matchKey ends with patternTrailer and the length of matchKey is greater than or // equal to the length of expansionKey, then if (matchKey.endsWith(patternTrailer) && this.patternKeyCompare(bestKey, expansionKey) === 1) { // Note: expansionKeys was not sorted // a. Let target be the value of matchObj[expansionKey]. target = matchObj[expansionKey]; // b. Let subpath be the substring of matchKey starting at the index of the length of patternBase up to the length of // matchKey minus the length of patternTrailer. bestKey = expansionKey; bestSubpath = matchKey.slice(patternBase.length, matchKey.length - patternTrailer.length); } } } if (bestSubpath) { // Note: expansionKeys was not sorted // c. Return the result of PACKAGE_TARGET_RESOLVE(packageURL, target, subpath, true, isImports, conditions). return this.packageTargetResolve(packageURL, target, bestSubpath, true, isImports, conditions, extList); } // 4. Return null. return null; } // PATTERN_KEY_COMPARE(keyA, keyB) patternKeyCompare(keyA, keyB) { // 1. Assert: keyA ends with "/" or contains only a single "*". // 2. Assert: keyB ends with "/" or contains only a single "*". // 3. Let baseLengthA be the index of "*" in keyA plus one, if keyA contains "*", or the length of keyA otherwise. const baseAStar = keyA.indexOf('*'); const baseLengthA = baseAStar === -1 ? keyA.length : baseAStar + 1; // 4. Let baseLengthB be the index of "*" in keyB plus one, if keyB contains "*", or the length of keyB otherwise. const baseBStar = keyB.indexOf('*'); const baseLengthB = baseBStar === -1 ? keyB.length : baseBStar + 1; // 5. If baseLengthA is greater than baseLengthB, return -1. if (baseLengthA > baseLengthB) return -1; // 6. If baseLengthB is greater than baseLengthA, return 1. if (baseLengthB > baseLengthA) return 1; // 7. If keyA does not contain "*", return 1. if (baseAStar === -1) return 1; // 8. If keyB does not contain "*", return -1. if (baseBStar === -1) return -1; // 9. If the length of keyA is greater than the length of keyB, return -1. if (keyA.length > keyB.length) return -1; // 10. If the length of keyB is greater than the length of keyA, return 1. if (keyB.length > keyA.length) return 1; // 11. Return 0. return 0; } // PACKAGE_TARGET_RESOLVE(packageURL, target, subpath, pattern, internal, conditions) packageTargetResolve(packageURL, target, subpath, pattern, internal, conditions, extList) { // 1. If target is a String, then if (typeof target === 'string') { // a. If pattern is false, subpath has non-zero length and target does not end with "/", throw an Invalid Module Specifier error. if (!pattern && subpath.length > 0 && !target.endsWith('/')) { throw new VMError(`Invalid package specifier '${subpath}'`, 'ERR_INVALID_MODULE_SPECIFIER'); } // b. If target does not start with "./", then if (!target.startsWith('./')) { // 1. If internal is true and target does not start with "../" or "/" and is not a valid URL, then if (internal && !target.startsWith('../') && !target.startsWith('/')) { let isURL = false; try { // eslint-disable-next-line no-new new URL(target); isURL = true; } catch (e) {} if (!isURL) { // a. If pattern is true, then if (pattern) { // 1. Return PACKAGE_RESOLVE(target with every instance of "*" replaced by subpath, packageURL + "/"). return this.packageResolve(target.replace(/\*/g, subpath), packageURL, conditions, extList); } // b. Return PACKAGE_RESOLVE(target + subpath, packageURL + "/"). return this.packageResolve(this.pathConcat(target, subpath), packageURL, conditions, extList); } } // Otherwise, throw an Invalid Package Target error. throw new VMError(`Invalid package target for '${subpath}'`, 'ERR_INVALID_PACKAGE_TARGET'); } target = decodeURI(target); // c. If target split on "/" or "\" contains any ".", ".." or "node_modules" segments after the first segment, case insensitive // and including percent encoded variants, throw an Invalid Package Target error. if (target.split(/[/\\]/).slice(1).findIndex(x => x === '.' || x === '..' || x.toLowerCase() === 'node_modules') !== -1) { throw new VMError(`Invalid package target for '${subpath}'`, 'ERR_INVALID_PACKAGE_TARGET'); } // d. Let resolvedTarget be the URL resolution of the concatenation of packageURL and target. const resolvedTarget = this.pathConcat(packageURL, target); // e. Assert: resolvedTarget is contained in packageURL. subpath = decodeURI(subpath); // f. If subpath split on "/" or "\" contains any ".", ".." or "node_modules" segments, case insensitive and including percent // encoded variants, throw an Invalid Module Specifier error. if (subpath.split(/[/\\]/).findIndex(x => x === '.' || x === '..' || x.toLowerCase() === 'node_modules') !== -1) { throw new VMError(`Invalid package specifier '${subpath}'`, 'ERR_INVALID_MODULE_SPECIFIER'); } // g. If pattern is true, then if (pattern) { // 1. Return the URL resolution of resolvedTarget with every instance of "*" replaced with subpath. return resolvedTarget.replace(/\*/g, subpath); } // h. Otherwise, // 1. Return the URL resolution of the concatenation of subpath and resolvedTarget. return this.pathConcat(resolvedTarget, subpath); // 3. Otherwise, if target is an Array, then } else if (Array.isArray(target)) { // a. If target.length is zero, return null. if (target.length === 0) return null; let lastException = undefined; // b. For each item targetValue in target, do for (let i = 0; i < target.length; i++) { const targetValue = target[i]; // 1. Let resolved be the result of PACKAGE_TARGET_RESOLVE( packageURL, targetValue, subpath, pattern, internal, conditions), // continuing the loop on any Invalid Package Target error. let resolved; try { resolved = this.packageTargetResolve(packageURL, targetValue, subpath, pattern, internal, conditions, extList); } catch (e) { if (e.code !== 'ERR_INVALID_PACKAGE_TARGET') throw e; lastException = e; continue; } // 2. If resolved is undefined, continue the loop. // 3. Return resolved. if (resolved !== undefined) return resolved; if (resolved === null) { lastException = null; } } // c. Return or throw the last fallback resolution null return or error. if (lastException === undefined || lastException === null) return lastException; throw lastException; // 2. Otherwise, if target is a non-null Object, then } else if (typeof target === 'object' && target !== null) { const keys = Object.getOwnPropertyNames(target); // a. If exports contains any index property keys, as defined in ECMA-262 6.1.7 Array Index, throw an Invalid Package Configuration error. for (let i = 0; i < keys.length; i++) { const p = keys[i]; if (isArrayIndex(p)) throw new VMError(`Invalid package configuration for '${subpath}'`, 'ERR_INVALID_PACKAGE_CONFIGURATION'); } // b. For each property p of target, in object insertion order as, for (let i = 0; i < keys.length; i++) { const p = keys[i]; // 1. If p equals "default" or conditions contains an entry for p, then if (p === 'default' || conditions.includes(p)) { // a. Let targetValue be the value of the p property in target. const targetValue = target[p]; // b. Let resolved be the result of PACKAGE_TARGET_RESOLVE( packageURL, targetValue, subpath, pattern, internal, conditions). const resolved = this.packageTargetResolve(packageURL, targetValue, subpath, pattern, internal, conditions, extList); // c. If resolved is equal to undefined, continue the loop. // d. Return resolved. if (resolved !== undefined) return resolved; } } // c. Return undefined. return undefined; // 4. Otherwise, if target is null, return null. } else if (target == null) { return null; } // Otherwise throw an Invalid Package Target error. throw new VMError(`Invalid package target for '${subpath}'`, 'ERR_INVALID_PACKAGE_TARGET'); } // PACKAGE_RESOLVE(packageSpecifier, parentURL) packageResolve(packageSpecifier, parentURL, conditions, extList) { // 1. Let packageName be undefined. let packageName = undefined; // 2. If packageSpecifier is an empty string, then if (packageSpecifier === '') { // a. Throw an Invalid Module Specifier error. throw new VMError(`Invalid package specifier '${packageSpecifier}'`, 'ERR_INVALID_MODULE_SPECIFIER'); } // 3. If packageSpecifier is a Node.js builtin module name, then if (this.builtinModules[packageSpecifier]) { // a. Return the string "node:" concatenated with packageSpecifier. return 'node:' + packageSpecifier; } let idx = packageSpecifier.indexOf('/'); // 5. Otherwise, if (packageSpecifier[0] === '@') { // a. If packageSpecifier does not contain a "/" separator, then if (idx === -1) { // x. Throw an Invalid Module Specifier error. throw new VMError(`Invalid package specifier '${packageSpecifier}'`, 'ERR_INVALID_MODULE_SPECIFIER'); } // b. Set packageName to the substring of packageSpecifier until the second "/" separator or the end of the string. idx = packageSpecifier.indexOf('/', idx + 1); } // else // 4. If packageSpecifier does not start with "@", then // a. Set packageName to the substring of packageSpecifier until the first "/" separator or the end of the string. packageName = idx === -1 ? packageSpecifier : packageSpecifier.slice(0, idx); // 6. If packageName starts with "." or contains "\" or "%", then if (idx !== 0 && (packageName[0] === '.' || packageName.indexOf('\\') >= 0 || packageName.indexOf('%') >= 0)) { // a. Throw an Invalid Module Specifier error. throw new VMError(`Invalid package specifier '${packageSpecifier}'`, 'ERR_INVALID_MODULE_SPECIFIER'); } // 7. Let packageSubpath be "." concatenated with the substring of packageSpecifier from the position at the length of packageName. const packageSubpath = '.' + packageSpecifier.slice(packageName.length); // 8. If packageSubpath ends in "/", then if (packageSubpath[packageSubpath.length - 1] === '/') { // a. Throw an Invalid Module Specifier error. throw new VMError(`Invalid package specifier '${packageSpecifier}'`, 'ERR_INVALID_MODULE_SPECIFIER'); } // 9. Let selfUrl be the result of PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL). const selfUrl = this.packageSelfResolve(packageName, packageSubpath, parentURL); // 10. If selfUrl is not undefined, return selfUrl. if (selfUrl) return selfUrl; // 11. While parentURL is not the file system root, let packageURL; while (true) { // a. Let packageURL be the URL resolution of "node_modules/" concatenated with packageSpecifier, relative to parentURL. packageURL = this.pathResolve(this.pathConcat(parentURL, 'node_modules', packageSpecifier)); // b. Set parentURL to the parent folder URL of parentURL. const parentParentURL = this.pathDirname(parentURL); // c. If the folder at packageURL does not exist, then if (this.isPathAllowed(packageURL) && this.pathTestIsDirectory(packageURL)) break; // 1. Continue the next loop iteration. if (parentParentURL === parentURL) { // 12. Throw a Module Not Found error. throw new VMError(`Cannot find module '${packageSpecifier}'`, 'ENOTFOUND'); } parentURL = parentParentURL; } // d. Let pjson be the result of READ_PACKAGE_JSON(packageURL). const pack = this.readPackage(packageURL); // e. If pjson is not null and pjson.exports is not null or undefined, then if (pack && pack.exports) { // 1. Return the result of PACKAGE_EXPORTS_RESOLVE(packageURL, packageSubpath, pjson.exports, defaultConditions). return this.packageExportsResolve(packageURL, packageSubpath, pack.exports, conditions, extList); } // f. Otherwise, if packageSubpath is equal to ".", then if (packageSubpath === '.') { // 1. If pjson.main is a string, then // a. Return the URL resolution of main in packageURL. return this.loadAsPackage(packageSubpath, pack, extList); } // g. Otherwise, // 1. Return the URL resolution of packageSubpath in packageURL. return this.pathConcat(packageURL, packageSubpath); } } exports.Resolver = Resolver; exports.DefaultResolver = DefaultResolver; ```
/content/code_sandbox/node_modules/vm2/lib/resolver.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
9,397
```javascript 'use strict'; var path = require('path'); var fs = require('fs'); var acorn = require('./acorn.js'); function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n["default"] = e; return Object.freeze(n); } var acorn__namespace = /*#__PURE__*/_interopNamespace(acorn); var inputFilePaths = [], forceFileName = false, fileMode = false, silent = false, compact = false, tokenize = false; var options = {}; function help(status) { var print = (status === 0) ? console.log : console.error; print("usage: " + path.basename(process.argv[1]) + " [--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|...|--ecma2015|--ecma2016|--ecma2017|--ecma2018|...]"); print(" [--tokenize] [--locations] [--allow-hash-bang] [--allow-await-outside-function] [--compact] [--silent] [--module] [--help] [--] [<infile>...]"); process.exit(status); } for (var i = 2; i < process.argv.length; ++i) { var arg = process.argv[i]; if (arg[0] !== "-" || arg === "-") { inputFilePaths.push(arg); } else if (arg === "--") { inputFilePaths.push.apply(inputFilePaths, process.argv.slice(i + 1)); forceFileName = true; break } else if (arg === "--locations") { options.locations = true; } else if (arg === "--allow-hash-bang") { options.allowHashBang = true; } else if (arg === "--allow-await-outside-function") { options.allowAwaitOutsideFunction = true; } else if (arg === "--silent") { silent = true; } else if (arg === "--compact") { compact = true; } else if (arg === "--help") { help(0); } else if (arg === "--tokenize") { tokenize = true; } else if (arg === "--module") { options.sourceType = "module"; } else { var match = arg.match(/^--ecma(\d+)$/); if (match) { options.ecmaVersion = +match[1]; } else { help(1); } } } function run(codeList) { var result = [], fileIdx = 0; try { codeList.forEach(function (code, idx) { fileIdx = idx; if (!tokenize) { result = acorn__namespace.parse(code, options); options.program = result; } else { var tokenizer = acorn__namespace.tokenizer(code, options), token; do { token = tokenizer.getToken(); result.push(token); } while (token.type !== acorn__namespace.tokTypes.eof) } }); } catch (e) { console.error(fileMode ? e.message.replace(/\(\d+:\d+\)$/, function (m) { return m.slice(0, 1) + inputFilePaths[fileIdx] + " " + m.slice(1); }) : e.message); process.exit(1); } if (!silent) { console.log(JSON.stringify(result, null, compact ? null : 2)); } } if (fileMode = inputFilePaths.length && (forceFileName || !inputFilePaths.includes("-") || inputFilePaths.length !== 1)) { run(inputFilePaths.map(function (path) { return fs.readFileSync(path, "utf8"); })); } else { var code = ""; process.stdin.resume(); process.stdin.on("data", function (chunk) { return code += chunk; }); process.stdin.on("end", function () { return run([code]); }); } ```
/content/code_sandbox/node_modules/vm2/node_modules/acorn/dist/bin.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
906
```javascript // Underscore.js 1.4.4 // path_to_url // (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc. // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `global` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Establish the object that gets returned to break out of a loop iteration. var breaker = {}; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, concat = ArrayProto.concat, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeForEach = ArrayProto.forEach, nativeMap = ArrayProto.map, nativeReduce = ArrayProto.reduce, nativeReduceRight = ArrayProto.reduceRight, nativeFilter = ArrayProto.filter, nativeEvery = ArrayProto.every, nativeSome = ArrayProto.some, nativeIndexOf = ArrayProto.indexOf, nativeLastIndexOf = ArrayProto.lastIndexOf, nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object via a string identifier, // for Closure Compiler "advanced" mode. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.4.4'; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles objects with the built-in `forEach`, arrays, and raw objects. // Delegates to **ECMAScript 5**'s native `forEach` if available. var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i++) { if (iterator.call(context, obj[i], i, obj) === breaker) return; } } else { for (var key in obj) { if (_.has(obj, key)) { if (iterator.call(context, obj[key], key, obj) === breaker) return; } } } }; // Return the results of applying the iterator to each element. // Delegates to **ECMAScript 5**'s native `map` if available. _.map = _.collect = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); each(obj, function(value, index, list) { results[results.length] = iterator.call(context, value, index, list); }); return results; }; var reduceError = 'Reduce of empty array with no initial value'; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduce && obj.reduce === nativeReduce) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); } each(obj, function(value, index, list) { if (!initial) { memo = value; initial = true; } else { memo = iterator.call(context, memo, value, index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // The right-associative version of reduce, also known as `foldr`. // Delegates to **ECMAScript 5**'s native `reduceRight` if available. _.reduceRight = _.foldr = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); } var length = obj.length; if (length !== +length) { var keys = _.keys(obj); length = keys.length; } each(obj, function(value, index, list) { index = keys ? keys[--length] : --length; if (!initial) { memo = obj[index]; initial = true; } else { memo = iterator.call(context, memo, obj[index], index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, iterator, context) { var result; any(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Delegates to **ECMAScript 5**'s native `filter` if available. // Aliased as `select`. _.filter = _.select = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); each(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) results[results.length] = value; }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, iterator, context) { return _.filter(obj, function(value, index, list) { return !iterator.call(context, value, index, list); }, context); }; // Determine whether all of the elements match a truth test. // Delegates to **ECMAScript 5**'s native `every` if available. // Aliased as `all`. _.every = _.all = function(obj, iterator, context) { iterator || (iterator = _.identity); var result = true; if (obj == null) return result; if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); each(obj, function(value, index, list) { if (!(result = result && iterator.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if at least one element in the object matches a truth test. // Delegates to **ECMAScript 5**'s native `some` if available. // Aliased as `any`. var any = _.some = _.any = function(obj, iterator, context) { iterator || (iterator = _.identity); var result = false; if (obj == null) return result; if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); each(obj, function(value, index, list) { if (result || (result = iterator.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if the array or object contains a given value (using `===`). // Aliased as `include`. _.contains = _.include = function(obj, target) { if (obj == null) return false; if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; return any(obj, function(value) { return value === target; }); }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { return (isFunc ? method : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, function(value){ return value[key]; }); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs, first) { if (_.isEmpty(attrs)) return first ? null : []; return _[first ? 'find' : 'filter'](obj, function(value) { for (var key in attrs) { if (attrs[key] !== value[key]) return false; } return true; }); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.where(obj, attrs, true); }; // Return the maximum element or (element-based computation). // Can't optimize arrays of integers longer than 65,535 elements. // See: path_to_url _.max = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.max.apply(Math, obj); } if (!iterator && _.isEmpty(obj)) return -Infinity; var result = {computed : -Infinity, value: -Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed >= result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Return the minimum element (or element-based computation). _.min = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.min.apply(Math, obj); } if (!iterator && _.isEmpty(obj)) return Infinity; var result = {computed : Infinity, value: Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed < result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Shuffle an array. _.shuffle = function(obj) { var rand; var index = 0; var shuffled = []; each(obj, function(value) { rand = _.random(index++); shuffled[index - 1] = shuffled[rand]; shuffled[rand] = value; }); return shuffled; }; // An internal function to generate lookup iterators. var lookupIterator = function(value) { return _.isFunction(value) ? value : function(obj){ return obj[value]; }; }; // Sort the object's values by a criterion produced by an iterator. _.sortBy = function(obj, value, context) { var iterator = lookupIterator(value); return _.pluck(_.map(obj, function(value, index, list) { return { value : value, index : index, criteria : iterator.call(context, value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index < right.index ? -1 : 1; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(obj, value, context, behavior) { var result = {}; var iterator = lookupIterator(value || _.identity); each(obj, function(value, index) { var key = iterator.call(context, value, index, obj); behavior(result, key, value); }); return result; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = function(obj, value, context) { return group(obj, value, context, function(result, key, value) { (_.has(result, key) ? result[key] : (result[key] = [])).push(value); }); }; // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = function(obj, value, context) { return group(obj, value, context, function(result, key) { if (!_.has(result, key)) result[key] = 0; result[key]++; }); }; // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iterator, context) { iterator = iterator == null ? _.identity : lookupIterator(iterator); var value = iterator.call(context, obj); var low = 0, high = array.length; while (low < high) { var mid = (low + high) >>> 1; iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; } return low; }; // Safely convert anything iterable into a real, live array. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (obj.length === +obj.length) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if (array == null) return void 0; if ((n != null) && !guard) { return slice.call(array, Math.max(array.length - n, 0)); } else { return array[array.length - 1]; } }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, (n == null) || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, output) { each(input, function(value) { if (_.isArray(value)) { shallow ? push.apply(output, value) : flatten(value, shallow, output); } else { output.push(value); } }); return output; }; // Return a completely flattened version of an array. _.flatten = function(array, shallow) { return flatten(array, shallow, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iterator, context) { if (_.isFunction(isSorted)) { context = iterator; iterator = isSorted; isSorted = false; } var initial = iterator ? _.map(array, iterator, context) : array; var results = []; var seen = []; each(initial, function(value, index) { if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { seen.push(value); results.push(array[index]); } }); return results; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(concat.apply(ArrayProto, arguments)); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { var rest = slice.call(arguments, 1); return _.filter(_.uniq(array), function(item) { return _.every(rest, function(other) { return _.indexOf(other, item) >= 0; }); }); }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function() { var args = slice.call(arguments); var length = _.max(_.pluck(args, 'length')); var results = new Array(length); for (var i = 0; i < length; i++) { results[i] = _.pluck(args, "" + i); } return results; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { if (list == null) return {}; var result = {}; for (var i = 0, l = list.length; i < l; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), // we need this function. Return the position of the first occurrence of an // item in an array, or -1 if the item is not included in the array. // Delegates to **ECMAScript 5**'s native `indexOf` if available. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i = 0, l = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted); } else { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } } if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); for (; i < l; i++) if (array[i] === item) return i; return -1; }; // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. _.lastIndexOf = function(array, item, from) { if (array == null) return -1; var hasIndex = from != null; if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); } var i = (hasIndex ? from : array.length); while (i--) if (array[i] === item) return i; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](path_to_url#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = arguments[2] || 1; var len = Math.max(Math.ceil((stop - start) / step), 0); var idx = 0; var range = new Array(len); while(idx < len) { range[idx++] = start; start += step; } return range; }; // Function (ahem) Functions // ------------------ // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = function(func, context) { if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); var args = slice.call(arguments, 2); return function() { return func.apply(context, args.concat(slice.call(arguments))); }; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _.partial = function(func) { var args = slice.call(arguments, 1); return function() { return func.apply(this, args.concat(slice.call(arguments))); }; }; // Bind all of an object's methods to that object. Useful for ensuring that // all callbacks defined on an object belong to it. _.bindAll = function(obj) { var funcs = slice.call(arguments, 1); if (funcs.length === 0) funcs = _.functions(obj); each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memo = {}; hasher || (hasher = _.identity); return function() { var key = hasher.apply(this, arguments); return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); }; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. _.throttle = function(func, wait) { var context, args, timeout, result; var previous = 0; var later = function() { previous = new Date; timeout = null; result = func.apply(context, args); }; return function() { var now = new Date; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, result; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) result = func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) result = func.apply(context, args); return result; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = function(func) { var ran = false, memo; return function() { if (ran) return memo; ran = true; memo = func.apply(this, arguments); func = null; return memo; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return function() { var args = [func]; push.apply(args, arguments); return wrapper.apply(this, args); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var funcs = arguments; return function() { var args = arguments; for (var i = funcs.length - 1; i >= 0; i--) { args = [funcs[i].apply(this, args)]; } return args[0]; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { if (times <= 0) return func(); return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = nativeKeys || function(obj) { if (obj !== Object(obj)) throw new TypeError('Invalid object'); var keys = []; for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key; return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var values = []; for (var key in obj) if (_.has(obj, key)) values.push(obj[key]); return values; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var pairs = []; for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]); return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key; return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { obj[prop] = source[prop]; } } }); return obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); each(keys, function(key) { if (key in obj) copy[key] = obj[key]; }); return copy; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); for (var key in obj) { if (!_.contains(keys, key)) copy[key] = obj[key]; } return copy; }; // Fill in a given object with default properties. _.defaults = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { if (obj[prop] == null) obj[prop] = source[prop]; } } }); return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the Harmony `egal` proposal: path_to_url if (a === b) return a !== 0 || 1 / a == 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className != toString.call(b)) return false; switch (className) { // Strings, numbers, dates, and booleans are compared by value. case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return a == String(b); case '[object Number]': // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for // other numeric values. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a == +b; // RegExps are compared by their source patterns and flags. case '[object RegExp]': return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] == a) return bStack[length] == b; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size = 0, result = true; // Recursively compare objects and arrays. if (className == '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size == b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!(result = eq(a[size], b[size], aStack, bStack))) break; } } } else { // Objects with different constructors are not equivalent, but `Object`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && _.isFunction(bCtor) && (bCtor instanceof bCtor))) { return false; } // Deep compare objects. for (var key in a) { if (_.has(a, key)) { // Count the expected number of properties. size++; // Deep compare each member. if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; } } // Ensure that both objects contain the same number of properties. if (result) { for (key in b) { if (_.has(b, key) && !(size--)) break; } result = !size; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, [], []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) == '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { return obj === Object(obj); }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) == '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return !!(obj && _.has(obj, 'callee')); }; } // Optimize `isFunction` if appropriate. if (typeof (/./) !== 'function') { _.isFunction = function(obj) { return typeof obj === 'function'; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj != +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iterators. _.identity = function(value) { return value; }; // Run a function **n** times. _.times = function(n, iterator, context) { var accum = Array(n); for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // List of HTML entities for escaping. var entityMap = { escape: { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '/': '&#x2F;' } }; entityMap.unescape = _.invert(entityMap.escape); // Regexes containing the keys and values listed immediately above. var entityRegexes = { escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') }; // Functions for escaping and unescaping strings to/from HTML interpolation. _.each(['escape', 'unescape'], function(method) { _[method] = function(string) { if (string == null) return ''; return ('' + string).replace(entityRegexes[method], function(match) { return entityMap[method][match]; }); }; }); // If the value of the named property is a function then invoke it; // otherwise, return it. _.result = function(object, property) { if (object == null) return null; var value = object[property]; return _.isFunction(value) ? value.call(object) : value; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { each(_.functions(obj), function(name){ var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result.call(this, func.apply(_, args)); }; }); }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\t': 't', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. _.template = function(text, data, settings) { var render; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = new RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset) .replace(escaper, function(match) { return '\\' + escapes[match]; }); if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } index = offset + match.length; return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + "return __p;\n"; try { render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } if (data) return render(data, _); var template = function(data) { return render.call(this, data, _); }; // Provide the compiled function source as a convenience for precompilation. template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; return template; }; // Add a "chain" function, which will delegate to the wrapper. _.chain = function(obj) { return _(obj).chain(); }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var result = function(obj) { return this._chain ? _(obj).chain() : obj; }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; return result.call(this, obj); }; }); // Add all accessor Array functions to the wrapper. each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result.call(this, method.apply(this._wrapped, arguments)); }; }); _.extend(_.prototype, { // Start chaining a wrapped Underscore object. chain: function() { this._chain = true; return this; }, // Extracts the result from a wrapped and chained object. value: function() { return this._wrapped; } }); }).call(this); ```
/content/code_sandbox/node_modules/underscore/underscore.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
10,405
```javascript module.exports = require('./underscore'); ```
/content/code_sandbox/node_modules/underscore/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
8
```javascript (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.acorn = {})); })(this, (function (exports) { 'use strict'; // This file was generated. Do not modify manually! var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 357, 0, 62, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; // This file was generated. Do not modify manually! var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1070, 4050, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 46, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 482, 44, 11, 6, 17, 0, 322, 29, 19, 43, 1269, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4152, 8, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938]; // This file was generated. Do not modify manually! var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; // This file was generated. Do not modify manually! var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; // These are a run-length and offset encoded representation of the // Reserved word lists for various dialects of the language var reservedWords = { 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", 5: "class enum extends super const export import", 6: "enum", strict: "implements interface let package private protected public static yield", strictBind: "eval arguments" }; // And the keywords var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; var keywords$1 = { 5: ecma5AndLessKeywords, "5module": ecma5AndLessKeywords + " export import", 6: ecma5AndLessKeywords + " const class extends export import super" }; var keywordRelationalOperator = /^in(stanceof)?$/; // ## Character categories var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); // This has a complexity linear to the value of the code. The // assumption is that looking up astral identifier characters is // rare. function isInAstralSet(code, set) { var pos = 0x10000; for (var i = 0; i < set.length; i += 2) { pos += set[i]; if (pos > code) { return false } pos += set[i + 1]; if (pos >= code) { return true } } } // Test whether a given character code starts an identifier. function isIdentifierStart(code, astral) { if (code < 65) { return code === 36 } if (code < 91) { return true } if (code < 97) { return code === 95 } if (code < 123) { return true } if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet(code, astralIdentifierStartCodes) } // Test whether a given character is part of an identifier. function isIdentifierChar(code, astral) { if (code < 48) { return code === 36 } if (code < 58) { return true } if (code < 65) { return false } if (code < 91) { return true } if (code < 97) { return code === 95 } if (code < 123) { return true } if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) } // ## Token types // The assignment of fine-grained, information-carrying type objects // allows the tokenizer to store the information it has about a // token in a way that is very cheap for the parser to look up. // All token type variables start with an underscore, to make them // easy to recognize. // The `beforeExpr` property is used to disambiguate between regular // expressions and divisions. It is set on all token types that can // be followed by an expression (thus, a slash after them would be a // regular expression). // // The `startsExpr` property is used to check if the token ends a // `yield` expression. It is set on all token types that either can // directly start an expression (like a quotation mark) or can // continue an expression (like the body of a string). // // `isLoop` marks a keyword as starting a loop, which is important // to know when parsing a label, in order to allow or disallow // continue jumps to that label. var TokenType = function TokenType(label, conf) { if ( conf === void 0 ) conf = {}; this.label = label; this.keyword = conf.keyword; this.beforeExpr = !!conf.beforeExpr; this.startsExpr = !!conf.startsExpr; this.isLoop = !!conf.isLoop; this.isAssign = !!conf.isAssign; this.prefix = !!conf.prefix; this.postfix = !!conf.postfix; this.binop = conf.binop || null; this.updateContext = null; }; function binop(name, prec) { return new TokenType(name, {beforeExpr: true, binop: prec}) } var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; // Map keyword names to token types. var keywords = {}; // Succinct definitions of keyword token types function kw(name, options) { if ( options === void 0 ) options = {}; options.keyword = name; return keywords[name] = new TokenType(name, options) } var types$1 = { num: new TokenType("num", startsExpr), regexp: new TokenType("regexp", startsExpr), string: new TokenType("string", startsExpr), name: new TokenType("name", startsExpr), privateId: new TokenType("privateId", startsExpr), eof: new TokenType("eof"), // Punctuation token types. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), bracketR: new TokenType("]"), braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), braceR: new TokenType("}"), parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), parenR: new TokenType(")"), comma: new TokenType(",", beforeExpr), semi: new TokenType(";", beforeExpr), colon: new TokenType(":", beforeExpr), dot: new TokenType("."), question: new TokenType("?", beforeExpr), questionDot: new TokenType("?."), arrow: new TokenType("=>", beforeExpr), template: new TokenType("template"), invalidTemplate: new TokenType("invalidTemplate"), ellipsis: new TokenType("...", beforeExpr), backQuote: new TokenType("`", startsExpr), dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), // Operators. These carry several kinds of properties to help the // parser use them properly (the presence of these properties is // what categorizes them as operators). // // `binop`, when present, specifies that this operator is a binary // operator, and will refer to its precedence. // // `prefix` and `postfix` mark the operator as a prefix or postfix // unary operator. // // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as // binary operators with a very low precedence, that should result // in AssignmentExpression nodes. eq: new TokenType("=", {beforeExpr: true, isAssign: true}), assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), logicalOR: binop("||", 1), logicalAND: binop("&&", 2), bitwiseOR: binop("|", 3), bitwiseXOR: binop("^", 4), bitwiseAND: binop("&", 5), equality: binop("==/!=/===/!==", 6), relational: binop("</>/<=/>=", 7), bitShift: binop("<</>>/>>>", 8), plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), modulo: binop("%", 10), star: binop("*", 10), slash: binop("/", 10), starstar: new TokenType("**", {beforeExpr: true}), coalesce: binop("??", 1), // Keyword token types. _break: kw("break"), _case: kw("case", beforeExpr), _catch: kw("catch"), _continue: kw("continue"), _debugger: kw("debugger"), _default: kw("default", beforeExpr), _do: kw("do", {isLoop: true, beforeExpr: true}), _else: kw("else", beforeExpr), _finally: kw("finally"), _for: kw("for", {isLoop: true}), _function: kw("function", startsExpr), _if: kw("if"), _return: kw("return", beforeExpr), _switch: kw("switch"), _throw: kw("throw", beforeExpr), _try: kw("try"), _var: kw("var"), _const: kw("const"), _while: kw("while", {isLoop: true}), _with: kw("with"), _new: kw("new", {beforeExpr: true, startsExpr: true}), _this: kw("this", startsExpr), _super: kw("super", startsExpr), _class: kw("class", startsExpr), _extends: kw("extends", beforeExpr), _export: kw("export"), _import: kw("import", startsExpr), _null: kw("null", startsExpr), _true: kw("true", startsExpr), _false: kw("false", startsExpr), _in: kw("in", {beforeExpr: true, binop: 7}), _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) }; // Matches a whole line break (where CRLF is considered a single // line break). Used to count lines. var lineBreak = /\r\n?|\n|\u2028|\u2029/; var lineBreakG = new RegExp(lineBreak.source, "g"); function isNewLine(code) { return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 } function nextLineBreak(code, from, end) { if ( end === void 0 ) end = code.length; for (var i = from; i < end; i++) { var next = code.charCodeAt(i); if (isNewLine(next)) { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 } } return -1 } var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; var ref = Object.prototype; var hasOwnProperty = ref.hasOwnProperty; var toString = ref.toString; var hasOwn = Object.hasOwn || (function (obj, propName) { return ( hasOwnProperty.call(obj, propName) ); }); var isArray = Array.isArray || (function (obj) { return ( toString.call(obj) === "[object Array]" ); }); function wordsRegexp(words) { return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") } function codePointToString(code) { // UTF-16 Decoding if (code <= 0xFFFF) { return String.fromCharCode(code) } code -= 0x10000; return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) } var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; // These are used when `options.locations` is on, for the // `startLoc` and `endLoc` properties. var Position = function Position(line, col) { this.line = line; this.column = col; }; Position.prototype.offset = function offset (n) { return new Position(this.line, this.column + n) }; var SourceLocation = function SourceLocation(p, start, end) { this.start = start; this.end = end; if (p.sourceFile !== null) { this.source = p.sourceFile; } }; // The `getLineInfo` function is mostly useful when the // `locations` option is off (for performance reasons) and you // want to find the line/column position for a given character // offset. `input` should be the code string that the offset refers // into. function getLineInfo(input, offset) { for (var line = 1, cur = 0;;) { var nextBreak = nextLineBreak(input, cur, offset); if (nextBreak < 0) { return new Position(line, offset - cur) } ++line; cur = nextBreak; } } // A second argument must be given to configure the parser process. // These options are recognized (only `ecmaVersion` is required): var defaultOptions = { // `ecmaVersion` indicates the ECMAScript version to parse. Must be // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the // latest version the library supports). This influences support // for strict mode, the set of reserved words, and support for // new syntax features. ecmaVersion: null, // `sourceType` indicates the mode the code should be parsed in. // Can be either `"script"` or `"module"`. This influences global // strict mode and parsing of `import` and `export` declarations. sourceType: "script", // `onInsertedSemicolon` can be a callback that will be called // when a semicolon is automatically inserted. It will be passed // the position of the comma as an offset, and if `locations` is // enabled, it is given the location as a `{line, column}` object // as second argument. onInsertedSemicolon: null, // `onTrailingComma` is similar to `onInsertedSemicolon`, but for // trailing commas. onTrailingComma: null, // By default, reserved words are only enforced if ecmaVersion >= 5. // Set `allowReserved` to a boolean value to explicitly turn this on // an off. When this option has the value "never", reserved words // and keywords can also not be used as property names. allowReserved: null, // When enabled, a return at the top level is not considered an // error. allowReturnOutsideFunction: false, // When enabled, import/export statements are not constrained to // appearing at the top of the program, and an import.meta expression // in a script isn't considered an error. allowImportExportEverywhere: false, // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. // When enabled, await identifiers are allowed to appear at the top-level scope, // but they are still not allowed in non-async functions. allowAwaitOutsideFunction: null, // When enabled, super identifiers are not constrained to // appearing in methods and do not raise an error when they appear elsewhere. allowSuperOutsideMethod: null, // When enabled, hashbang directive in the beginning of file // is allowed and treated as a line comment. allowHashBang: false, // When `locations` is on, `loc` properties holding objects with // `start` and `end` properties in `{line, column}` form (with // line being 1-based and column 0-based) will be attached to the // nodes. locations: false, // A function can be passed as `onToken` option, which will // cause Acorn to call that function with object in the same // format as tokens returned from `tokenizer().getToken()`. Note // that you are not allowed to call the parser from the // callbackthat will corrupt its internal state. onToken: null, // A function can be passed as `onComment` option, which will // cause Acorn to call that function with `(block, text, start, // end)` parameters whenever a comment is skipped. `block` is a // boolean indicating whether this is a block (`/* */`) comment, // `text` is the content of the comment, and `start` and `end` are // character offsets that denote the start and end of the comment. // When the `locations` option is on, two more parameters are // passed, the full `{line, column}` locations of the start and // end of the comments. Note that you are not allowed to call the // parser from the callbackthat will corrupt its internal state. onComment: null, // Nodes have their start and end characters offsets recorded in // `start` and `end` properties (directly on the node, rather than // the `loc` object, which holds line/column data. To also add a // [semi-standardized][range] `range` property holding a `[start, // end]` array with the same numbers, set the `ranges` option to // `true`. // // [range]: path_to_url ranges: false, // It is possible to parse multiple files into a single AST by // passing the tree produced by parsing the first file as // `program` option in subsequent parses. This will add the // toplevel forms of the parsed file to the `Program` (top) node // of an existing parse tree. program: null, // When `locations` is on, you can pass this to record the source // file in every node's `loc` object. sourceFile: null, // This value, if given, is stored in every node, whether // `locations` is on or off. directSourceFile: null, // When enabled, parenthesized expressions are represented by // (non-standard) ParenthesizedExpression nodes preserveParens: false }; // Interpret and default an options object var warnedAboutEcmaVersion = false; function getOptions(opts) { var options = {}; for (var opt in defaultOptions) { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; } if (options.ecmaVersion === "latest") { options.ecmaVersion = 1e8; } else if (options.ecmaVersion == null) { if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { warnedAboutEcmaVersion = true; console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); } options.ecmaVersion = 11; } else if (options.ecmaVersion >= 2015) { options.ecmaVersion -= 2009; } if (options.allowReserved == null) { options.allowReserved = options.ecmaVersion < 5; } if (isArray(options.onToken)) { var tokens = options.onToken; options.onToken = function (token) { return tokens.push(token); }; } if (isArray(options.onComment)) { options.onComment = pushComment(options, options.onComment); } return options } function pushComment(options, array) { return function(block, text, start, end, startLoc, endLoc) { var comment = { type: block ? "Block" : "Line", value: text, start: start, end: end }; if (options.locations) { comment.loc = new SourceLocation(this, startLoc, endLoc); } if (options.ranges) { comment.range = [start, end]; } array.push(comment); } } // Each scope gets a bitset that may contain these flags var SCOPE_TOP = 1, SCOPE_FUNCTION = 2, SCOPE_ASYNC = 4, SCOPE_GENERATOR = 8, SCOPE_ARROW = 16, SCOPE_SIMPLE_CATCH = 32, SCOPE_SUPER = 64, SCOPE_DIRECT_SUPER = 128, SCOPE_CLASS_STATIC_BLOCK = 256, SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; function functionFlags(async, generator) { return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) } // Used in checkLVal* and declareName to determine the type of a binding var BIND_NONE = 0, // Not a binding BIND_VAR = 1, // Var-style binding BIND_LEXICAL = 2, // Let- or const-style binding BIND_FUNCTION = 3, // Function declaration BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding BIND_OUTSIDE = 5; // Special case for function names as bound inside the function var Parser = function Parser(options, input, startPos) { this.options = options = getOptions(options); this.sourceFile = options.sourceFile; this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); var reserved = ""; if (options.allowReserved !== true) { reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; if (options.sourceType === "module") { reserved += " await"; } } this.reservedWords = wordsRegexp(reserved); var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; this.reservedWordsStrict = wordsRegexp(reservedStrict); this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); this.input = String(input); // Used to signal to callers of `readWord1` whether the word // contained any escape sequences. This is needed because words with // escape sequences must not be interpreted as keywords. this.containsEsc = false; // Set up token state // The current position of the tokenizer in the input. if (startPos) { this.pos = startPos; this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; } else { this.pos = this.lineStart = 0; this.curLine = 1; } // Properties of the current token: // Its type this.type = types$1.eof; // For tokens that include more information than their type, the value this.value = null; // Its start and end offset this.start = this.end = this.pos; // And, if locations are used, the {line, column} object // corresponding to those offsets this.startLoc = this.endLoc = this.curPosition(); // Position information for the previous token this.lastTokEndLoc = this.lastTokStartLoc = null; this.lastTokStart = this.lastTokEnd = this.pos; // The context stack is used to superficially track syntactic // context to predict whether a regular expression is allowed in a // given position. this.context = this.initialContext(); this.exprAllowed = true; // Figure out if it's a module code. this.inModule = options.sourceType === "module"; this.strict = this.inModule || this.strictDirective(this.pos); // Used to signify the start of a potential arrow function this.potentialArrowAt = -1; this.potentialArrowInForAwait = false; // Positions to delayed-check that yield/await does not exist in default parameters. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; // Labels in scope. this.labels = []; // Thus-far undefined exports. this.undefinedExports = Object.create(null); // If enabled, skip leading hashbang line. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") { this.skipLineComment(2); } // Scope tracking for duplicate variable names (see scope.js) this.scopeStack = []; this.enterScope(SCOPE_TOP); // For RegExp validation this.regexpState = null; // The stack of private names. // Each element has two properties: 'declared' and 'used'. // When it exited from the outermost class definition, all used private names must be declared. this.privateNameStack = []; }; var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } }; Parser.prototype.parse = function parse () { var node = this.options.program || this.startNode(); this.nextToken(); return this.parseTopLevel(node) }; prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit }; prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit }; prototypeAccessors.canAwait.get = function () { for (var i = this.scopeStack.length - 1; i >= 0; i--) { var scope = this.scopeStack[i]; if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false } if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 } } return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction }; prototypeAccessors.allowSuper.get = function () { var ref = this.currentThisScope(); var flags = ref.flags; var inClassFieldInit = ref.inClassFieldInit; return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod }; prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; prototypeAccessors.allowNewDotTarget.get = function () { var ref = this.currentThisScope(); var flags = ref.flags; var inClassFieldInit = ref.inClassFieldInit; return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit }; prototypeAccessors.inClassStaticBlock.get = function () { return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0 }; Parser.extend = function extend () { var plugins = [], len = arguments.length; while ( len-- ) plugins[ len ] = arguments[ len ]; var cls = this; for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } return cls }; Parser.parse = function parse (input, options) { return new this(options, input).parse() }; Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { var parser = new this(options, input, pos); parser.nextToken(); return parser.parseExpression() }; Parser.tokenizer = function tokenizer (input, options) { return new this(options, input) }; Object.defineProperties( Parser.prototype, prototypeAccessors ); var pp$9 = Parser.prototype; // ## Parser utilities var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; pp$9.strictDirective = function(start) { if (this.options.ecmaVersion < 5) { return false } for (;;) { // Try to find string literal. skipWhiteSpace.lastIndex = start; start += skipWhiteSpace.exec(this.input)[0].length; var match = literal.exec(this.input.slice(start)); if (!match) { return false } if ((match[1] || match[2]) === "use strict") { skipWhiteSpace.lastIndex = start + match[0].length; var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; var next = this.input.charAt(end); return next === ";" || next === "}" || (lineBreak.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) } start += match[0].length; // Skip semicolon, if any. skipWhiteSpace.lastIndex = start; start += skipWhiteSpace.exec(this.input)[0].length; if (this.input[start] === ";") { start++; } } }; // Predicate that tests whether the next token is of the given // type, and if yes, consumes it as a side effect. pp$9.eat = function(type) { if (this.type === type) { this.next(); return true } else { return false } }; // Tests whether parsed token is a contextual keyword. pp$9.isContextual = function(name) { return this.type === types$1.name && this.value === name && !this.containsEsc }; // Consumes contextual keyword if possible. pp$9.eatContextual = function(name) { if (!this.isContextual(name)) { return false } this.next(); return true }; // Asserts that following token is given contextual keyword. pp$9.expectContextual = function(name) { if (!this.eatContextual(name)) { this.unexpected(); } }; // Test whether a semicolon can be inserted at the current position. pp$9.canInsertSemicolon = function() { return this.type === types$1.eof || this.type === types$1.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }; pp$9.insertSemicolon = function() { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon) { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } return true } }; // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. pp$9.semicolon = function() { if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); } }; pp$9.afterTrailingComma = function(tokType, notNext) { if (this.type === tokType) { if (this.options.onTrailingComma) { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } if (!notNext) { this.next(); } return true } }; // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error. pp$9.expect = function(type) { this.eat(type) || this.unexpected(); }; // Raise an unexpected token error. pp$9.unexpected = function(pos) { this.raise(pos != null ? pos : this.start, "Unexpected token"); }; var DestructuringErrors = function DestructuringErrors() { this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1; }; pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) { if (!refDestructuringErrors) { return } if (refDestructuringErrors.trailingComma > -1) { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); } }; pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) { if (!refDestructuringErrors) { return false } var shorthandAssign = refDestructuringErrors.shorthandAssign; var doubleProto = refDestructuringErrors.doubleProto; if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } if (shorthandAssign >= 0) { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } if (doubleProto >= 0) { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } }; pp$9.checkYieldAwaitInDefaultParams = function() { if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } if (this.awaitPos) { this.raise(this.awaitPos, "Await expression cannot be a default value"); } }; pp$9.isSimpleAssignTarget = function(expr) { if (expr.type === "ParenthesizedExpression") { return this.isSimpleAssignTarget(expr.expression) } return expr.type === "Identifier" || expr.type === "MemberExpression" }; var pp$8 = Parser.prototype; // ### Statement parsing // Parse a program. Initializes the parser, reads any number of // statements, and wraps them in a Program node. Optionally takes a // `program` argument. If present, the statements will be appended // to its body instead of creating a new node. pp$8.parseTopLevel = function(node) { var exports = Object.create(null); if (!node.body) { node.body = []; } while (this.type !== types$1.eof) { var stmt = this.parseStatement(null, true, exports); node.body.push(stmt); } if (this.inModule) { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) { var name = list[i]; this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); } } this.adaptDirectivePrologue(node.body); this.next(); node.sourceType = this.options.sourceType; return this.finishNode(node, "Program") }; var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; pp$8.isLet = function(context) { if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } skipWhiteSpace.lastIndex = this.pos; var skip = skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); // For ambiguous cases, determine if a LexicalDeclaration (or only a // Statement) is allowed here. If context is not empty then only a Statement // is allowed. However, `let [` is an explicit negative lookahead for // ExpressionStatement, so special-case it first. if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral if (context) { return false } if (nextCh === 123) { return true } // '{' if (isIdentifierStart(nextCh, true)) { var pos = next + 1; while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } var ident = this.input.slice(next, pos); if (!keywordRelationalOperator.test(ident)) { return true } } return false }; // check 'async [no LineTerminator here] function' // - 'async /*foo*/ function' is OK. // - 'async /*\n*/ function' is invalid. pp$8.isAsyncFunction = function() { if (this.options.ecmaVersion < 8 || !this.isContextual("async")) { return false } skipWhiteSpace.lastIndex = this.pos; var skip = skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length, after; return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) }; // Parse a single statement. // // If expecting a statement and finding a slash operator, parse a // regular expression literal. This is to handle cases like // `if (foo) /blah/.exec(foo)`, where looking at the previous token // does not help. pp$8.parseStatement = function(context, topLevel, exports) { var starttype = this.type, node = this.startNode(), kind; if (this.isLet(context)) { starttype = types$1._var; kind = "let"; } // Most types of statements are recognized by the keyword they // start with. Many are trivial to parse, some require a bit of // complexity. switch (starttype) { case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword) case types$1._debugger: return this.parseDebuggerStatement(node) case types$1._do: return this.parseDoStatement(node) case types$1._for: return this.parseForStatement(node) case types$1._function: // Function as sole body of either an if statement or a labeled statement // works, but not when it is part of a labeled statement that is the sole // body of an if statement. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } return this.parseFunctionStatement(node, false, !context) case types$1._class: if (context) { this.unexpected(); } return this.parseClass(node, true) case types$1._if: return this.parseIfStatement(node) case types$1._return: return this.parseReturnStatement(node) case types$1._switch: return this.parseSwitchStatement(node) case types$1._throw: return this.parseThrowStatement(node) case types$1._try: return this.parseTryStatement(node) case types$1._const: case types$1._var: kind = kind || this.value; if (context && kind !== "var") { this.unexpected(); } return this.parseVarStatement(node, kind) case types$1._while: return this.parseWhileStatement(node) case types$1._with: return this.parseWithStatement(node) case types$1.braceL: return this.parseBlock(true, node) case types$1.semi: return this.parseEmptyStatement(node) case types$1._export: case types$1._import: if (this.options.ecmaVersion > 10 && starttype === types$1._import) { skipWhiteSpace.lastIndex = this.pos; var skip = skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); if (nextCh === 40 || nextCh === 46) // '(' or '.' { return this.parseExpressionStatement(node, this.parseExpression()) } } if (!this.options.allowImportExportEverywhere) { if (!topLevel) { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } if (!this.inModule) { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } } return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports) // If the statement does not start with a statement keyword or a // brace, it's an ExpressionStatement or LabeledStatement. We // simply start parsing an expression, and afterwards, if the // next token is a colon and the expression was a simple // Identifier node, we switch to interpreting it as a label. default: if (this.isAsyncFunction()) { if (context) { this.unexpected(); } this.next(); return this.parseFunctionStatement(node, true, !context) } var maybeName = this.value, expr = this.parseExpression(); if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) { return this.parseLabeledStatement(node, maybeName, expr, context) } else { return this.parseExpressionStatement(node, expr) } } }; pp$8.parseBreakContinueStatement = function(node, keyword) { var isBreak = keyword === "break"; this.next(); if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; } else if (this.type !== types$1.name) { this.unexpected(); } else { node.label = this.parseIdent(); this.semicolon(); } // Verify that there is an actual destination to break or // continue to. var i = 0; for (; i < this.labels.length; ++i) { var lab = this.labels[i]; if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } if (node.label && isBreak) { break } } } if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") }; pp$8.parseDebuggerStatement = function(node) { this.next(); this.semicolon(); return this.finishNode(node, "DebuggerStatement") }; pp$8.parseDoStatement = function(node) { this.next(); this.labels.push(loopLabel); node.body = this.parseStatement("do"); this.labels.pop(); this.expect(types$1._while); node.test = this.parseParenExpression(); if (this.options.ecmaVersion >= 6) { this.eat(types$1.semi); } else { this.semicolon(); } return this.finishNode(node, "DoWhileStatement") }; // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpression`), and then check // whether the next token is `in` or `of`. When there is no init // part (semicolon immediately after the opening parenthesis), it // is a regular `for` loop. pp$8.parseForStatement = function(node) { this.next(); var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; this.labels.push(loopLabel); this.enterScope(0); this.expect(types$1.parenL); if (this.type === types$1.semi) { if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, null) } var isLet = this.isLet(); if (this.type === types$1._var || this.type === types$1._const || isLet) { var init$1 = this.startNode(), kind = isLet ? "let" : this.value; this.next(); this.parseVar(init$1, true, kind); this.finishNode(init$1, "VariableDeclaration"); if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { if (this.options.ecmaVersion >= 9) { if (this.type === types$1._in) { if (awaitAt > -1) { this.unexpected(awaitAt); } } else { node.await = awaitAt > -1; } } return this.parseForIn(node, init$1) } if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, init$1) } var startsWithLet = this.isContextual("let"), isForOf = false; var refDestructuringErrors = new DestructuringErrors; var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { if (this.options.ecmaVersion >= 9) { if (this.type === types$1._in) { if (awaitAt > -1) { this.unexpected(awaitAt); } } else { node.await = awaitAt > -1; } } if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); } this.toAssignable(init, false, refDestructuringErrors); this.checkLValPattern(init); return this.parseForIn(node, init) } else { this.checkExpressionErrors(refDestructuringErrors, true); } if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, init) }; pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) { this.next(); return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) }; pp$8.parseIfStatement = function(node) { this.next(); node.test = this.parseParenExpression(); // allow function declarations in branches, but only in non-strict mode node.consequent = this.parseStatement("if"); node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null; return this.finishNode(node, "IfStatement") }; pp$8.parseReturnStatement = function(node) { if (!this.inFunction && !this.options.allowReturnOutsideFunction) { this.raise(this.start, "'return' outside of function"); } this.next(); // In `return` (and `break`/`continue`), the keywords with // optional arguments, we eagerly look for a semicolon or the // possibility to insert one. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; } else { node.argument = this.parseExpression(); this.semicolon(); } return this.finishNode(node, "ReturnStatement") }; pp$8.parseSwitchStatement = function(node) { this.next(); node.discriminant = this.parseParenExpression(); node.cases = []; this.expect(types$1.braceL); this.labels.push(switchLabel); this.enterScope(0); // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is used to keep the node that we are currently // adding statements to. var cur; for (var sawDefault = false; this.type !== types$1.braceR;) { if (this.type === types$1._case || this.type === types$1._default) { var isCase = this.type === types$1._case; if (cur) { this.finishNode(cur, "SwitchCase"); } node.cases.push(cur = this.startNode()); cur.consequent = []; this.next(); if (isCase) { cur.test = this.parseExpression(); } else { if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } sawDefault = true; cur.test = null; } this.expect(types$1.colon); } else { if (!cur) { this.unexpected(); } cur.consequent.push(this.parseStatement(null)); } } this.exitScope(); if (cur) { this.finishNode(cur, "SwitchCase"); } this.next(); // Closing brace this.labels.pop(); return this.finishNode(node, "SwitchStatement") }; pp$8.parseThrowStatement = function(node) { this.next(); if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) { this.raise(this.lastTokEnd, "Illegal newline after throw"); } node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement") }; // Reused empty array added for node fields that are always empty. var empty$1 = []; pp$8.parseTryStatement = function(node) { this.next(); node.block = this.parseBlock(); node.handler = null; if (this.type === types$1._catch) { var clause = this.startNode(); this.next(); if (this.eat(types$1.parenL)) { clause.param = this.parseBindingAtom(); var simple = clause.param.type === "Identifier"; this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); this.expect(types$1.parenR); } else { if (this.options.ecmaVersion < 10) { this.unexpected(); } clause.param = null; this.enterScope(0); } clause.body = this.parseBlock(false); this.exitScope(); node.handler = this.finishNode(clause, "CatchClause"); } node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) { this.raise(node.start, "Missing catch or finally clause"); } return this.finishNode(node, "TryStatement") }; pp$8.parseVarStatement = function(node, kind) { this.next(); this.parseVar(node, false, kind); this.semicolon(); return this.finishNode(node, "VariableDeclaration") }; pp$8.parseWhileStatement = function(node) { this.next(); node.test = this.parseParenExpression(); this.labels.push(loopLabel); node.body = this.parseStatement("while"); this.labels.pop(); return this.finishNode(node, "WhileStatement") }; pp$8.parseWithStatement = function(node) { if (this.strict) { this.raise(this.start, "'with' in strict mode"); } this.next(); node.object = this.parseParenExpression(); node.body = this.parseStatement("with"); return this.finishNode(node, "WithStatement") }; pp$8.parseEmptyStatement = function(node) { this.next(); return this.finishNode(node, "EmptyStatement") }; pp$8.parseLabeledStatement = function(node, maybeName, expr, context) { for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) { var label = list[i$1]; if (label.name === maybeName) { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); } } var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null; for (var i = this.labels.length - 1; i >= 0; i--) { var label$1 = this.labels[i]; if (label$1.statementStart === node.start) { // Update information about previous labels on this node label$1.statementStart = this.start; label$1.kind = kind; } else { break } } this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); this.labels.pop(); node.label = expr; return this.finishNode(node, "LabeledStatement") }; pp$8.parseExpressionStatement = function(node, expr) { node.expression = expr; this.semicolon(); return this.finishNode(node, "ExpressionStatement") }; // Parse a semicolon-enclosed block of statements, handling `"use // strict"` declarations when `allowStrict` is true (used for // function bodies). pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) { if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; if ( node === void 0 ) node = this.startNode(); node.body = []; this.expect(types$1.braceL); if (createNewLexicalScope) { this.enterScope(0); } while (this.type !== types$1.braceR) { var stmt = this.parseStatement(null); node.body.push(stmt); } if (exitStrict) { this.strict = false; } this.next(); if (createNewLexicalScope) { this.exitScope(); } return this.finishNode(node, "BlockStatement") }; // Parse a regular `for` loop. The disambiguation code in // `parseStatement` will already have parsed the init statement or // expression. pp$8.parseFor = function(node, init) { node.init = init; this.expect(types$1.semi); node.test = this.type === types$1.semi ? null : this.parseExpression(); this.expect(types$1.semi); node.update = this.type === types$1.parenR ? null : this.parseExpression(); this.expect(types$1.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, "ForStatement") }; // Parse a `for`/`in` and `for`/`of` loop, which are almost // same from parser's perspective. pp$8.parseForIn = function(node, init) { var isForIn = this.type === types$1._in; this.next(); if ( init.type === "VariableDeclaration" && init.declarations[0].init != null && ( !isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier" ) ) { this.raise( init.start, ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") ); } node.left = init; node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); this.expect(types$1.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") }; // Parse a list of variable declarations. pp$8.parseVar = function(node, isFor, kind) { node.declarations = []; node.kind = kind; for (;;) { var decl = this.startNode(); this.parseVarId(decl, kind); if (this.eat(types$1.eq)) { decl.init = this.parseMaybeAssign(isFor); } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { this.unexpected(); } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) { this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); } else { decl.init = null; } node.declarations.push(this.finishNode(decl, "VariableDeclarator")); if (!this.eat(types$1.comma)) { break } } return node }; pp$8.parseVarId = function(decl, kind) { decl.id = this.parseBindingAtom(); this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); }; var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; // Parse a function declaration or literal (depending on the // `statement & FUNC_STATEMENT`). // Remove `allowExpressionBody` for 7.0.0, as it is only called with false pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { this.initFunction(node); if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT)) { this.unexpected(); } node.generator = this.eat(types$1.star); } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } if (statement & FUNC_STATEMENT) { node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent(); if (node.id && !(statement & FUNC_HANGING_STATEMENT)) // If it is a regular function declaration in sloppy mode, then it is // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding // mode depends on properties of the current scope (see // treatFunctionsAsVar). { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } } var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags(node.async, node.generator)); if (!(statement & FUNC_STATEMENT)) { node.id = this.type === types$1.name ? this.parseIdent() : null; } this.parseFunctionParams(node); this.parseFunctionBody(node, allowExpressionBody, false, forInit); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") }; pp$8.parseFunctionParams = function(node) { this.expect(types$1.parenL); node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); }; // Parse a class declaration or literal (depending on the // `isStatement` parameter). pp$8.parseClass = function(node, isStatement) { this.next(); // ecma-262 14.6 Class Definitions // A class definition is always strict mode code. var oldStrict = this.strict; this.strict = true; this.parseClassId(node, isStatement); this.parseClassSuper(node); var privateNameMap = this.enterClassBody(); var classBody = this.startNode(); var hadConstructor = false; classBody.body = []; this.expect(types$1.braceL); while (this.type !== types$1.braceR) { var element = this.parseClassElement(node.superClass !== null); if (element) { classBody.body.push(element); if (element.type === "MethodDefinition" && element.kind === "constructor") { if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); } hadConstructor = true; } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); } } } this.strict = oldStrict; this.next(); node.body = this.finishNode(classBody, "ClassBody"); this.exitClassBody(); return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") }; pp$8.parseClassElement = function(constructorAllowsSuper) { if (this.eat(types$1.semi)) { return null } var ecmaVersion = this.options.ecmaVersion; var node = this.startNode(); var keyName = ""; var isGenerator = false; var isAsync = false; var kind = "method"; var isStatic = false; if (this.eatContextual("static")) { // Parse static init block if (ecmaVersion >= 13 && this.eat(types$1.braceL)) { this.parseClassStaticBlock(node); return node } if (this.isClassElementNameStart() || this.type === types$1.star) { isStatic = true; } else { keyName = "static"; } } node.static = isStatic; if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) { isAsync = true; } else { keyName = "async"; } } if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) { isGenerator = true; } if (!keyName && !isAsync && !isGenerator) { var lastValue = this.value; if (this.eatContextual("get") || this.eatContextual("set")) { if (this.isClassElementNameStart()) { kind = lastValue; } else { keyName = lastValue; } } } // Parse element name if (keyName) { // 'async', 'get', 'set', or 'static' were not a keyword contextually. // The last token is any of those. Make it the element name. node.computed = false; node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); node.key.name = keyName; this.finishNode(node.key, "Identifier"); } else { this.parseClassElementName(node); } // Parse element value if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) { var isConstructor = !node.static && checkKeyName(node, "constructor"); var allowsDirectSuper = isConstructor && constructorAllowsSuper; // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } node.kind = isConstructor ? "constructor" : kind; this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); } else { this.parseClassField(node); } return node }; pp$8.isClassElementNameStart = function() { return ( this.type === types$1.name || this.type === types$1.privateId || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword ) }; pp$8.parseClassElementName = function(element) { if (this.type === types$1.privateId) { if (this.value === "constructor") { this.raise(this.start, "Classes can't have an element named '#constructor'"); } element.computed = false; element.key = this.parsePrivateIdent(); } else { this.parsePropertyName(element); } }; pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { // Check key and flags var key = method.key; if (method.kind === "constructor") { if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } } else if (method.static && checkKeyName(method, "prototype")) { this.raise(key.start, "Classes may not have a static property named prototype"); } // Parse value var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); // Check value if (method.kind === "get" && value.params.length !== 0) { this.raiseRecoverable(value.start, "getter should have no params"); } if (method.kind === "set" && value.params.length !== 1) { this.raiseRecoverable(value.start, "setter should have exactly one param"); } if (method.kind === "set" && value.params[0].type === "RestElement") { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } return this.finishNode(method, "MethodDefinition") }; pp$8.parseClassField = function(field) { if (checkKeyName(field, "constructor")) { this.raise(field.key.start, "Classes can't have a field named 'constructor'"); } else if (field.static && checkKeyName(field, "prototype")) { this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); } if (this.eat(types$1.eq)) { // To raise SyntaxError if 'arguments' exists in the initializer. var scope = this.currentThisScope(); var inClassFieldInit = scope.inClassFieldInit; scope.inClassFieldInit = true; field.value = this.parseMaybeAssign(); scope.inClassFieldInit = inClassFieldInit; } else { field.value = null; } this.semicolon(); return this.finishNode(field, "PropertyDefinition") }; pp$8.parseClassStaticBlock = function(node) { node.body = []; var oldLabels = this.labels; this.labels = []; this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); while (this.type !== types$1.braceR) { var stmt = this.parseStatement(null); node.body.push(stmt); } this.next(); this.exitScope(); this.labels = oldLabels; return this.finishNode(node, "StaticBlock") }; pp$8.parseClassId = function(node, isStatement) { if (this.type === types$1.name) { node.id = this.parseIdent(); if (isStatement) { this.checkLValSimple(node.id, BIND_LEXICAL, false); } } else { if (isStatement === true) { this.unexpected(); } node.id = null; } }; pp$8.parseClassSuper = function(node) { node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(false) : null; }; pp$8.enterClassBody = function() { var element = {declared: Object.create(null), used: []}; this.privateNameStack.push(element); return element.declared }; pp$8.exitClassBody = function() { var ref = this.privateNameStack.pop(); var declared = ref.declared; var used = ref.used; var len = this.privateNameStack.length; var parent = len === 0 ? null : this.privateNameStack[len - 1]; for (var i = 0; i < used.length; ++i) { var id = used[i]; if (!hasOwn(declared, id.name)) { if (parent) { parent.used.push(id); } else { this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); } } } }; function isPrivateNameConflicted(privateNameMap, element) { var name = element.key.name; var curr = privateNameMap[name]; var next = "true"; if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { next = (element.static ? "s" : "i") + element.kind; } // `class { get #a(){}; static set #a(_){} }` is also conflict. if ( curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget" ) { privateNameMap[name] = "true"; return false } else if (!curr) { privateNameMap[name] = next; return false } else { return true } } function checkKeyName(node, name) { var computed = node.computed; var key = node.key; return !computed && ( key.type === "Identifier" && key.name === name || key.type === "Literal" && key.value === name ) } // Parses module export declaration. pp$8.parseExport = function(node, exports) { this.next(); // export * from '...' if (this.eat(types$1.star)) { if (this.options.ecmaVersion >= 11) { if (this.eatContextual("as")) { node.exported = this.parseModuleExportName(); this.checkExport(exports, node.exported, this.lastTokStart); } else { node.exported = null; } } this.expectContextual("from"); if (this.type !== types$1.string) { this.unexpected(); } node.source = this.parseExprAtom(); this.semicolon(); return this.finishNode(node, "ExportAllDeclaration") } if (this.eat(types$1._default)) { // export default ... this.checkExport(exports, "default", this.lastTokStart); var isAsync; if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) { var fNode = this.startNode(); this.next(); if (isAsync) { this.next(); } node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); } else if (this.type === types$1._class) { var cNode = this.startNode(); node.declaration = this.parseClass(cNode, "nullableID"); } else { node.declaration = this.parseMaybeAssign(); this.semicolon(); } return this.finishNode(node, "ExportDefaultDeclaration") } // export var|const|let|function|class ... if (this.shouldParseExportStatement()) { node.declaration = this.parseStatement(null); if (node.declaration.type === "VariableDeclaration") { this.checkVariableExport(exports, node.declaration.declarations); } else { this.checkExport(exports, node.declaration.id, node.declaration.id.start); } node.specifiers = []; node.source = null; } else { // export { x, y as z } [from '...'] node.declaration = null; node.specifiers = this.parseExportSpecifiers(exports); if (this.eatContextual("from")) { if (this.type !== types$1.string) { this.unexpected(); } node.source = this.parseExprAtom(); } else { for (var i = 0, list = node.specifiers; i < list.length; i += 1) { // check for keywords used as local names var spec = list[i]; this.checkUnreserved(spec.local); // check if export is defined this.checkLocalExport(spec.local); if (spec.local.type === "Literal") { this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); } } node.source = null; } this.semicolon(); } return this.finishNode(node, "ExportNamedDeclaration") }; pp$8.checkExport = function(exports, name, pos) { if (!exports) { return } if (typeof name !== "string") { name = name.type === "Identifier" ? name.name : name.value; } if (hasOwn(exports, name)) { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } exports[name] = true; }; pp$8.checkPatternExport = function(exports, pat) { var type = pat.type; if (type === "Identifier") { this.checkExport(exports, pat, pat.start); } else if (type === "ObjectPattern") { for (var i = 0, list = pat.properties; i < list.length; i += 1) { var prop = list[i]; this.checkPatternExport(exports, prop); } } else if (type === "ArrayPattern") { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { var elt = list$1[i$1]; if (elt) { this.checkPatternExport(exports, elt); } } } else if (type === "Property") { this.checkPatternExport(exports, pat.value); } else if (type === "AssignmentPattern") { this.checkPatternExport(exports, pat.left); } else if (type === "RestElement") { this.checkPatternExport(exports, pat.argument); } else if (type === "ParenthesizedExpression") { this.checkPatternExport(exports, pat.expression); } }; pp$8.checkVariableExport = function(exports, decls) { if (!exports) { return } for (var i = 0, list = decls; i < list.length; i += 1) { var decl = list[i]; this.checkPatternExport(exports, decl.id); } }; pp$8.shouldParseExportStatement = function() { return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction() }; // Parses a comma-separated list of module exports. pp$8.parseExportSpecifiers = function(exports) { var nodes = [], first = true; // export { x, y as z } [from '...'] this.expect(types$1.braceL); while (!this.eat(types$1.braceR)) { if (!first) { this.expect(types$1.comma); if (this.afterTrailingComma(types$1.braceR)) { break } } else { first = false; } var node = this.startNode(); node.local = this.parseModuleExportName(); node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; this.checkExport( exports, node.exported, node.exported.start ); nodes.push(this.finishNode(node, "ExportSpecifier")); } return nodes }; // Parses import declaration. pp$8.parseImport = function(node) { this.next(); // import '...' if (this.type === types$1.string) { node.specifiers = empty$1; node.source = this.parseExprAtom(); } else { node.specifiers = this.parseImportSpecifiers(); this.expectContextual("from"); node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected(); } this.semicolon(); return this.finishNode(node, "ImportDeclaration") }; // Parses a comma-separated list of module imports. pp$8.parseImportSpecifiers = function() { var nodes = [], first = true; if (this.type === types$1.name) { // import defaultObj, { x, y as z } from '...' var node = this.startNode(); node.local = this.parseIdent(); this.checkLValSimple(node.local, BIND_LEXICAL); nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); if (!this.eat(types$1.comma)) { return nodes } } if (this.type === types$1.star) { var node$1 = this.startNode(); this.next(); this.expectContextual("as"); node$1.local = this.parseIdent(); this.checkLValSimple(node$1.local, BIND_LEXICAL); nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); return nodes } this.expect(types$1.braceL); while (!this.eat(types$1.braceR)) { if (!first) { this.expect(types$1.comma); if (this.afterTrailingComma(types$1.braceR)) { break } } else { first = false; } var node$2 = this.startNode(); node$2.imported = this.parseModuleExportName(); if (this.eatContextual("as")) { node$2.local = this.parseIdent(); } else { this.checkUnreserved(node$2.imported); node$2.local = node$2.imported; } this.checkLValSimple(node$2.local, BIND_LEXICAL); nodes.push(this.finishNode(node$2, "ImportSpecifier")); } return nodes }; pp$8.parseModuleExportName = function() { if (this.options.ecmaVersion >= 13 && this.type === types$1.string) { var stringLiteral = this.parseLiteral(this.value); if (loneSurrogate.test(stringLiteral.value)) { this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); } return stringLiteral } return this.parseIdent(true) }; // Set `ExpressionStatement#directive` property for directive prologues. pp$8.adaptDirectivePrologue = function(statements) { for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { statements[i].directive = statements[i].expression.raw.slice(1, -1); } }; pp$8.isDirectiveCandidate = function(statement) { return ( statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && // Reject parenthesized strings. (this.input[statement.start] === "\"" || this.input[statement.start] === "'") ) }; var pp$7 = Parser.prototype; // Convert existing expression atom to assignable pattern // if possible. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) { if (this.options.ecmaVersion >= 6 && node) { switch (node.type) { case "Identifier": if (this.inAsync && node.name === "await") { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } break case "ObjectPattern": case "ArrayPattern": case "AssignmentPattern": case "RestElement": break case "ObjectExpression": node.type = "ObjectPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } for (var i = 0, list = node.properties; i < list.length; i += 1) { var prop = list[i]; this.toAssignable(prop, isBinding); // Early error: // AssignmentRestProperty[Yield, Await] : // `...` DestructuringAssignmentTarget[Yield, Await] // // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. if ( prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") ) { this.raise(prop.argument.start, "Unexpected token"); } } break case "Property": // AssignmentProperty has type === "Property" if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } this.toAssignable(node.value, isBinding); break case "ArrayExpression": node.type = "ArrayPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } this.toAssignableList(node.elements, isBinding); break case "SpreadElement": node.type = "RestElement"; this.toAssignable(node.argument, isBinding); if (node.argument.type === "AssignmentPattern") { this.raise(node.argument.start, "Rest elements cannot have a default value"); } break case "AssignmentExpression": if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } node.type = "AssignmentPattern"; delete node.operator; this.toAssignable(node.left, isBinding); break case "ParenthesizedExpression": this.toAssignable(node.expression, isBinding, refDestructuringErrors); break case "ChainExpression": this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); break case "MemberExpression": if (!isBinding) { break } default: this.raise(node.start, "Assigning to rvalue"); } } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } return node }; // Convert list of expression atoms to binding list. pp$7.toAssignableList = function(exprList, isBinding) { var end = exprList.length; for (var i = 0; i < end; i++) { var elt = exprList[i]; if (elt) { this.toAssignable(elt, isBinding); } } if (end) { var last = exprList[end - 1]; if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") { this.unexpected(last.argument.start); } } return exprList }; // Parses spread element. pp$7.parseSpread = function(refDestructuringErrors) { var node = this.startNode(); this.next(); node.argument = this.parseMaybeAssign(false, refDestructuringErrors); return this.finishNode(node, "SpreadElement") }; pp$7.parseRestBinding = function() { var node = this.startNode(); this.next(); // RestElement inside of a function parameter must be an identifier if (this.options.ecmaVersion === 6 && this.type !== types$1.name) { this.unexpected(); } node.argument = this.parseBindingAtom(); return this.finishNode(node, "RestElement") }; // Parses lvalue (assignable) atom. pp$7.parseBindingAtom = function() { if (this.options.ecmaVersion >= 6) { switch (this.type) { case types$1.bracketL: var node = this.startNode(); this.next(); node.elements = this.parseBindingList(types$1.bracketR, true, true); return this.finishNode(node, "ArrayPattern") case types$1.braceL: return this.parseObj(true) } } return this.parseIdent() }; pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) { var elts = [], first = true; while (!this.eat(close)) { if (first) { first = false; } else { this.expect(types$1.comma); } if (allowEmpty && this.type === types$1.comma) { elts.push(null); } else if (allowTrailingComma && this.afterTrailingComma(close)) { break } else if (this.type === types$1.ellipsis) { var rest = this.parseRestBinding(); this.parseBindingListItem(rest); elts.push(rest); if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } this.expect(close); break } else { var elem = this.parseMaybeDefault(this.start, this.startLoc); this.parseBindingListItem(elem); elts.push(elem); } } return elts }; pp$7.parseBindingListItem = function(param) { return param }; // Parses assignment pattern around given atom if possible. pp$7.parseMaybeDefault = function(startPos, startLoc, left) { left = left || this.parseBindingAtom(); if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left } var node = this.startNodeAt(startPos, startLoc); node.left = left; node.right = this.parseMaybeAssign(); return this.finishNode(node, "AssignmentPattern") }; // The following three functions all verify that a node is an lvalue // something that can be bound, or assigned to. In order to do so, they perform // a variety of checks: // // - Check that none of the bound/assigned-to identifiers are reserved words. // - Record name declarations for bindings in the appropriate scope. // - Check duplicate argument names, if checkClashes is set. // // If a complex binding pattern is encountered (e.g., object and array // destructuring), the entire pattern is recursively checked. // // There are three versions of checkLVal*() appropriate for different // circumstances: // // - checkLValSimple() shall be used if the syntactic construct supports // nothing other than identifiers and member expressions. Parenthesized // expressions are also correctly handled. This is generally appropriate for // constructs for which the spec says // // > It is a Syntax Error if AssignmentTargetType of [the production] is not // > simple. // // It is also appropriate for checking if an identifier is valid and not // defined elsewhere, like import declarations or function/class identifiers. // // Examples where this is used include: // a += ; // import a from ''; // where a is the node to be checked. // // - checkLValPattern() shall be used if the syntactic construct supports // anything checkLValSimple() supports, as well as object and array // destructuring patterns. This is generally appropriate for constructs for // which the spec says // // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor // > an ArrayLiteral and AssignmentTargetType of [the production] is not // > simple. // // Examples where this is used include: // (a = ); // const a = ; // try { } catch (a) { } // where a is the node to be checked. // // - checkLValInnerPattern() shall be used if the syntactic construct supports // anything checkLValPattern() supports, as well as default assignment // patterns, rest elements, and other constructs that may appear within an // object or array destructuring pattern. // // As a special case, function parameters also use checkLValInnerPattern(), // as they also support defaults and rest constructs. // // These functions deliberately support both assignment and binding constructs, // as the logic for both is exceedingly similar. If the node is the target of // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it // should be set to the appropriate BIND_* constant, like BIND_VAR or // BIND_LEXICAL. // // If the function is called with a non-BIND_NONE bindingType, then // additionally a checkClashes object may be specified to allow checking for // duplicate argument names. checkClashes is ignored if the provided construct // is an assignment (i.e., bindingType is BIND_NONE). pp$7.checkLValSimple = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE; var isBind = bindingType !== BIND_NONE; switch (expr.type) { case "Identifier": if (this.strict && this.reservedWordsStrictBind.test(expr.name)) { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } if (isBind) { if (bindingType === BIND_LEXICAL && expr.name === "let") { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } if (checkClashes) { if (hasOwn(checkClashes, expr.name)) { this.raiseRecoverable(expr.start, "Argument name clash"); } checkClashes[expr.name] = true; } if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } } break case "ChainExpression": this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); break case "MemberExpression": if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } break case "ParenthesizedExpression": if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } return this.checkLValSimple(expr.expression, bindingType, checkClashes) default: this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); } }; pp$7.checkLValPattern = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE; switch (expr.type) { case "ObjectPattern": for (var i = 0, list = expr.properties; i < list.length; i += 1) { var prop = list[i]; this.checkLValInnerPattern(prop, bindingType, checkClashes); } break case "ArrayPattern": for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { var elem = list$1[i$1]; if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } } break default: this.checkLValSimple(expr, bindingType, checkClashes); } }; pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE; switch (expr.type) { case "Property": // AssignmentProperty has type === "Property" this.checkLValInnerPattern(expr.value, bindingType, checkClashes); break case "AssignmentPattern": this.checkLValPattern(expr.left, bindingType, checkClashes); break case "RestElement": this.checkLValPattern(expr.argument, bindingType, checkClashes); break default: this.checkLValPattern(expr, bindingType, checkClashes); } }; // The algorithm used to determine whether a regexp can appear at a var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override; this.generator = !!generator; }; var types = { b_stat: new TokContext("{", false), b_expr: new TokContext("{", true), b_tmpl: new TokContext("${", false), p_stat: new TokContext("(", false), p_expr: new TokContext("(", true), q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), f_stat: new TokContext("function", false), f_expr: new TokContext("function", true), f_expr_gen: new TokContext("function", true, false, null, true), f_gen: new TokContext("function", false, false, null, true) }; var pp$6 = Parser.prototype; pp$6.initialContext = function() { return [types.b_stat] }; pp$6.curContext = function() { return this.context[this.context.length - 1] }; pp$6.braceIsBlock = function(prevType) { var parent = this.curContext(); if (parent === types.f_expr || parent === types.f_stat) { return true } if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr)) { return !parent.isExpr } // The check for `tt.name && exprAllowed` detects whether we are // after a `yield` or `of` construct. See the `updateContext` for // `tt.name`. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) { return true } if (prevType === types$1.braceL) { return parent === types.b_stat } if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) { return false } return !this.exprAllowed }; pp$6.inGeneratorContext = function() { for (var i = this.context.length - 1; i >= 1; i--) { var context = this.context[i]; if (context.token === "function") { return context.generator } } return false }; pp$6.updateContext = function(prevType) { var update, type = this.type; if (type.keyword && prevType === types$1.dot) { this.exprAllowed = false; } else if (update = type.updateContext) { update.call(this, prevType); } else { this.exprAllowed = type.beforeExpr; } }; // Used to handle egde case when token context could not be inferred correctly in tokenize phase pp$6.overrideContext = function(tokenCtx) { if (this.curContext() !== tokenCtx) { this.context[this.context.length - 1] = tokenCtx; } }; // Token-specific context update code types$1.parenR.updateContext = types$1.braceR.updateContext = function() { if (this.context.length === 1) { this.exprAllowed = true; return } var out = this.context.pop(); if (out === types.b_stat && this.curContext().token === "function") { out = this.context.pop(); } this.exprAllowed = !out.isExpr; }; types$1.braceL.updateContext = function(prevType) { this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr); this.exprAllowed = true; }; types$1.dollarBraceL.updateContext = function() { this.context.push(types.b_tmpl); this.exprAllowed = true; }; types$1.parenL.updateContext = function(prevType) { var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while; this.context.push(statementParens ? types.p_stat : types.p_expr); this.exprAllowed = true; }; types$1.incDec.updateContext = function() { // tokExprAllowed stays unchanged }; types$1._function.updateContext = types$1._class.updateContext = function(prevType) { if (prevType.beforeExpr && prevType !== types$1._else && !(prevType === types$1.semi && this.curContext() !== types.p_stat) && !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat)) { this.context.push(types.f_expr); } else { this.context.push(types.f_stat); } this.exprAllowed = false; }; types$1.backQuote.updateContext = function() { if (this.curContext() === types.q_tmpl) { this.context.pop(); } else { this.context.push(types.q_tmpl); } this.exprAllowed = false; }; types$1.star.updateContext = function(prevType) { if (prevType === types$1._function) { var index = this.context.length - 1; if (this.context[index] === types.f_expr) { this.context[index] = types.f_expr_gen; } else { this.context[index] = types.f_gen; } } this.exprAllowed = true; }; types$1.name.updateContext = function(prevType) { var allowed = false; if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) { if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) { allowed = true; } } this.exprAllowed = allowed; }; // A recursive descent parser operates by defining functions for all var pp$5 = Parser.prototype; // Check if property name clashes with already added. // Object/class getters and setters are not allowed to clash // either with each other or with an init property and in // strict mode, init properties are also not allowed to be repeated. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) { if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") { return } if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) { return } var key = prop.key; var name; switch (key.type) { case "Identifier": name = key.name; break case "Literal": name = String(key.value); break default: return } var kind = prop.kind; if (this.options.ecmaVersion >= 6) { if (name === "__proto__" && kind === "init") { if (propHash.proto) { if (refDestructuringErrors) { if (refDestructuringErrors.doubleProto < 0) { refDestructuringErrors.doubleProto = key.start; } } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } } propHash.proto = true; } return } name = "$" + name; var other = propHash[name]; if (other) { var redefinition; if (kind === "init") { redefinition = this.strict && other.init || other.get || other.set; } else { redefinition = other.init || other[kind]; } if (redefinition) { this.raiseRecoverable(key.start, "Redefinition of property"); } } else { other = propHash[name] = { init: false, get: false, set: false }; } other[kind] = true; }; // ### Expression parsing // These nest, from the most general expression type at the top to // 'atomic', nondivisible expression types at the bottom. Most of // the functions will simply let the function(s) below them parse, // and, *if* the syntactic construct they handle is present, wrap // the AST node that the inner parser gave them in another node. // Parse a full expression. The optional arguments are used to // forbid the `in` operator (in for loops initalization expressions) // and provide reference for storing '=' operator inside shorthand // property assignment in contexts where both object expression // and object pattern might appear (so it's possible to raise // delayed syntax error at correct position). pp$5.parseExpression = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); if (this.type === types$1.comma) { var node = this.startNodeAt(startPos, startLoc); node.expressions = [expr]; while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } return this.finishNode(node, "SequenceExpression") } return expr }; // Parse an assignment expression. This includes applications of // operators like `+=`. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { if (this.isContextual("yield")) { if (this.inGenerator) { return this.parseYield(forInit) } // The tokenizer will assume an expression is allowed after // `yield`, but this isn't that kind of yield else { this.exprAllowed = false; } } var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; if (refDestructuringErrors) { oldParenAssign = refDestructuringErrors.parenthesizedAssign; oldTrailingComma = refDestructuringErrors.trailingComma; oldDoubleProto = refDestructuringErrors.doubleProto; refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; } else { refDestructuringErrors = new DestructuringErrors; ownDestructuringErrors = true; } var startPos = this.start, startLoc = this.startLoc; if (this.type === types$1.parenL || this.type === types$1.name) { this.potentialArrowAt = this.start; this.potentialArrowInForAwait = forInit === "await"; } var left = this.parseMaybeConditional(forInit, refDestructuringErrors); if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } if (this.type.isAssign) { var node = this.startNodeAt(startPos, startLoc); node.operator = this.value; if (this.type === types$1.eq) { left = this.toAssignable(left, false, refDestructuringErrors); } if (!ownDestructuringErrors) { refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; } if (refDestructuringErrors.shorthandAssign >= left.start) { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly if (this.type === types$1.eq) { this.checkLValPattern(left); } else { this.checkLValSimple(left); } node.left = left; this.next(); node.right = this.parseMaybeAssign(forInit); if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; } return this.finishNode(node, "AssignmentExpression") } else { if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } } if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } return left }; // Parse a ternary conditional (`?:`) operator. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprOps(forInit, refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } if (this.eat(types$1.question)) { var node = this.startNodeAt(startPos, startLoc); node.test = expr; node.consequent = this.parseMaybeAssign(); this.expect(types$1.colon); node.alternate = this.parseMaybeAssign(forInit); return this.finishNode(node, "ConditionalExpression") } return expr }; // Start the precedence parser. pp$5.parseExprOps = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) }; // Parse binary operators with the operator precedence parsing // algorithm. `left` is the left-hand side of the operator. // `minPrec` provides context that allows the function to stop and // defer further parser to one of its callers when it encounters an // operator that has a lower precedence than the set it is parsing. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { var prec = this.type.binop; if (prec != null && (!forInit || this.type !== types$1._in)) { if (prec > minPrec) { var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND; var coalesce = this.type === types$1.coalesce; if (coalesce) { // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. prec = types$1.logicalAND.binop; } var op = this.value; this.next(); var startPos = this.start, startLoc = this.startLoc; var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) { this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); } return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) } } return left }; pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) { if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); } var node = this.startNodeAt(startPos, startLoc); node.left = left; node.operator = op; node.right = right; return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") }; // Parse unary operators, both prefix and postfix. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { var startPos = this.start, startLoc = this.startLoc, expr; if (this.isContextual("await") && this.canAwait) { expr = this.parseAwait(forInit); sawUnary = true; } else if (this.type.prefix) { var node = this.startNode(), update = this.type === types$1.incDec; node.operator = this.value; node.prefix = true; this.next(); node.argument = this.parseMaybeUnary(null, true, update, forInit); this.checkExpressionErrors(refDestructuringErrors, true); if (update) { this.checkLValSimple(node.argument); } else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } else { sawUnary = true; } expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); } else if (!sawUnary && this.type === types$1.privateId) { if (forInit || this.privateNameStack.length === 0) { this.unexpected(); } expr = this.parsePrivateIdent(); // only could be private fields in 'in', such as #x in obj if (this.type !== types$1._in) { this.unexpected(); } } else { expr = this.parseExprSubscripts(refDestructuringErrors, forInit); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } while (this.type.postfix && !this.canInsertSemicolon()) { var node$1 = this.startNodeAt(startPos, startLoc); node$1.operator = this.value; node$1.prefix = false; node$1.argument = expr; this.checkLValSimple(expr); this.next(); expr = this.finishNode(node$1, "UpdateExpression"); } } if (!incDec && this.eat(types$1.starstar)) { if (sawUnary) { this.unexpected(this.lastTokStart); } else { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) } } else { return expr } }; function isPrivateFieldAccess(node) { return ( node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) ) } // Parse call, dot, and `[]`-subscript expressions. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprAtom(refDestructuringErrors, forInit); if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") { return expr } var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); if (refDestructuringErrors && result.type === "MemberExpression") { if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } } return result }; pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.potentialArrowAt === base.start; var optionalChained = false; while (true) { var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); if (element.optional) { optionalChained = true; } if (element === base || element.type === "ArrowFunctionExpression") { if (optionalChained) { var chainNode = this.startNodeAt(startPos, startLoc); chainNode.expression = element; element = this.finishNode(chainNode, "ChainExpression"); } return element } base = element; } }; pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { var optionalSupported = this.options.ecmaVersion >= 11; var optional = optionalSupported && this.eat(types$1.questionDot); if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } var computed = this.eat(types$1.bracketL); if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) { var node = this.startNodeAt(startPos, startLoc); node.object = base; if (computed) { node.property = this.parseExpression(); this.expect(types$1.bracketR); } else if (this.type === types$1.privateId && base.type !== "Super") { node.property = this.parsePrivateIdent(); } else { node.property = this.parseIdent(this.options.allowReserved !== "never"); } node.computed = !!computed; if (optionalSupported) { node.optional = optional; } base = this.finishNode(node, "MemberExpression"); } else if (!noCalls && this.eat(types$1.parenL)) { var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); if (this.awaitIdentPos > 0) { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit) } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; var node$1 = this.startNodeAt(startPos, startLoc); node$1.callee = base; node$1.arguments = exprList; if (optionalSupported) { node$1.optional = optional; } base = this.finishNode(node$1, "CallExpression"); } else if (this.type === types$1.backQuote) { if (optional || optionalChained) { this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); } var node$2 = this.startNodeAt(startPos, startLoc); node$2.tag = base; node$2.quasi = this.parseTemplate({isTagged: true}); base = this.finishNode(node$2, "TaggedTemplateExpression"); } return base }; // Parse an atomic expression either a single token that is an // expression, an expression started by a keyword like `function` or // `new`, or an expression wrapped in punctuation like `()`, `[]`, // or `{}`. pp$5.parseExprAtom = function(refDestructuringErrors, forInit) { // If a division operator appears in an expression position, the // tokenizer got confused, and we force it to read a regexp instead. if (this.type === types$1.slash) { this.readRegexp(); } var node, canBeArrow = this.potentialArrowAt === this.start; switch (this.type) { case types$1._super: if (!this.allowSuper) { this.raise(this.start, "'super' keyword outside a method"); } node = this.startNode(); this.next(); if (this.type === types$1.parenL && !this.allowDirectSuper) { this.raise(node.start, "super() call outside constructor of a subclass"); } // The `super` keyword can appear at below: // SuperProperty: // super [ Expression ] // super . IdentifierName // SuperCall: // super ( Arguments ) if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) { this.unexpected(); } return this.finishNode(node, "Super") case types$1._this: node = this.startNode(); this.next(); return this.finishNode(node, "ThisExpression") case types$1.name: var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; var id = this.parseIdent(false); if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) { this.overrideContext(types.f_expr); return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit) } if (canBeArrow && !this.canInsertSemicolon()) { if (this.eat(types$1.arrow)) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) } if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { id = this.parseIdent(false); if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) { this.unexpected(); } return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit) } } return id case types$1.regexp: var value = this.value; node = this.parseLiteral(value.value); node.regex = {pattern: value.pattern, flags: value.flags}; return node case types$1.num: case types$1.string: return this.parseLiteral(this.value) case types$1._null: case types$1._true: case types$1._false: node = this.startNode(); node.value = this.type === types$1._null ? null : this.type === types$1._true; node.raw = this.type.keyword; this.next(); return this.finishNode(node, "Literal") case types$1.parenL: var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); if (refDestructuringErrors) { if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) { refDestructuringErrors.parenthesizedAssign = start; } if (refDestructuringErrors.parenthesizedBind < 0) { refDestructuringErrors.parenthesizedBind = start; } } return expr case types$1.bracketL: node = this.startNode(); this.next(); node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors); return this.finishNode(node, "ArrayExpression") case types$1.braceL: this.overrideContext(types.b_expr); return this.parseObj(false, refDestructuringErrors) case types$1._function: node = this.startNode(); this.next(); return this.parseFunction(node, 0) case types$1._class: return this.parseClass(this.startNode(), false) case types$1._new: return this.parseNew() case types$1.backQuote: return this.parseTemplate() case types$1._import: if (this.options.ecmaVersion >= 11) { return this.parseExprImport() } else { return this.unexpected() } default: this.unexpected(); } }; pp$5.parseExprImport = function() { var node = this.startNode(); // Consume `import` as an identifier for `import.meta`. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } var meta = this.parseIdent(true); switch (this.type) { case types$1.parenL: return this.parseDynamicImport(node) case types$1.dot: node.meta = meta; return this.parseImportMeta(node) default: this.unexpected(); } }; pp$5.parseDynamicImport = function(node) { this.next(); // skip `(` // Parse node.source. node.source = this.parseMaybeAssign(); // Verify ending. if (!this.eat(types$1.parenR)) { var errorPos = this.start; if (this.eat(types$1.comma) && this.eat(types$1.parenR)) { this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); } else { this.unexpected(errorPos); } } return this.finishNode(node, "ImportExpression") }; pp$5.parseImportMeta = function(node) { this.next(); // skip `.` var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "meta") { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } if (containsEsc) { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } return this.finishNode(node, "MetaProperty") }; pp$5.parseLiteral = function(value) { var node = this.startNode(); node.value = value; node.raw = this.input.slice(this.start, this.end); if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } this.next(); return this.finishNode(node, "Literal") }; pp$5.parseParenExpression = function() { this.expect(types$1.parenL); var val = this.parseExpression(); this.expect(types$1.parenR); return val }; pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; if (this.options.ecmaVersion >= 6) { this.next(); var innerStartPos = this.start, innerStartLoc = this.startLoc; var exprList = [], first = true, lastIsComma = false; var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; this.yieldPos = 0; this.awaitPos = 0; // Do not save awaitIdentPos to allow checking awaits nested in parameters while (this.type !== types$1.parenR) { first ? first = false : this.expect(types$1.comma); if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) { lastIsComma = true; break } else if (this.type === types$1.ellipsis) { spreadStart = this.start; exprList.push(this.parseParenItem(this.parseRestBinding())); if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } break } else { exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); } } var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; this.expect(types$1.parenR); if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; return this.parseParenArrowList(startPos, startLoc, exprList, forInit) } if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } if (spreadStart) { this.unexpected(spreadStart); } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; if (exprList.length > 1) { val = this.startNodeAt(innerStartPos, innerStartLoc); val.expressions = exprList; this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); } else { val = exprList[0]; } } else { val = this.parseParenExpression(); } if (this.options.preserveParens) { var par = this.startNodeAt(startPos, startLoc); par.expression = val; return this.finishNode(par, "ParenthesizedExpression") } else { return val } }; pp$5.parseParenItem = function(item) { return item }; pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit) }; // New's precedence is slightly tricky. It must allow its argument to // be a `[]` or dot subscript expression, but not a call at least, // not without wrapping it in parentheses. Thus, it uses the noCalls // argument to parseSubscripts to prevent it from consuming the // argument list. var empty = []; pp$5.parseNew = function() { if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } var node = this.startNode(); var meta = this.parseIdent(true); if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) { node.meta = meta; var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "target") { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } if (containsEsc) { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } if (!this.allowNewDotTarget) { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); } return this.finishNode(node, "MetaProperty") } var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import; node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false); if (isImport && node.callee.type === "ImportExpression") { this.raise(startPos, "Cannot use new with import()"); } if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); } else { node.arguments = empty; } return this.finishNode(node, "NewExpression") }; // Parse template expression. pp$5.parseTemplateElement = function(ref) { var isTagged = ref.isTagged; var elem = this.startNode(); if (this.type === types$1.invalidTemplate) { if (!isTagged) { this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); } elem.value = { raw: this.value, cooked: null }; } else { elem.value = { raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), cooked: this.value }; } this.next(); elem.tail = this.type === types$1.backQuote; return this.finishNode(elem, "TemplateElement") }; pp$5.parseTemplate = function(ref) { if ( ref === void 0 ) ref = {}; var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; var node = this.startNode(); this.next(); node.expressions = []; var curElt = this.parseTemplateElement({isTagged: isTagged}); node.quasis = [curElt]; while (!curElt.tail) { if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); } this.expect(types$1.dollarBraceL); node.expressions.push(this.parseExpression()); this.expect(types$1.braceR); node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); } this.next(); return this.finishNode(node, "TemplateLiteral") }; pp$5.isAsyncProp = function(prop) { return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }; // Parse an object literal or binding pattern. pp$5.parseObj = function(isPattern, refDestructuringErrors) { var node = this.startNode(), first = true, propHash = {}; node.properties = []; this.next(); while (!this.eat(types$1.braceR)) { if (!first) { this.expect(types$1.comma); if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break } } else { first = false; } var prop = this.parseProperty(isPattern, refDestructuringErrors); if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } node.properties.push(prop); } return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") }; pp$5.parseProperty = function(isPattern, refDestructuringErrors) { var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) { if (isPattern) { prop.argument = this.parseIdent(false); if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } return this.finishNode(prop, "RestElement") } // To disallow parenthesized identifier via `this.toAssignable()`. if (this.type === types$1.parenL && refDestructuringErrors) { if (refDestructuringErrors.parenthesizedAssign < 0) { refDestructuringErrors.parenthesizedAssign = this.start; } if (refDestructuringErrors.parenthesizedBind < 0) { refDestructuringErrors.parenthesizedBind = this.start; } } // Parse argument. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); // To disallow trailing comma via `this.toAssignable()`. if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this.start; } // Finish return this.finishNode(prop, "SpreadElement") } if (this.options.ecmaVersion >= 6) { prop.method = false; prop.shorthand = false; if (isPattern || refDestructuringErrors) { startPos = this.start; startLoc = this.startLoc; } if (!isPattern) { isGenerator = this.eat(types$1.star); } } var containsEsc = this.containsEsc; this.parsePropertyName(prop); if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { isAsync = true; isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star); this.parsePropertyName(prop, refDestructuringErrors); } else { isAsync = false; } this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); return this.finishNode(prop, "Property") }; pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { if ((isGenerator || isAsync) && this.type === types$1.colon) { this.unexpected(); } if (this.eat(types$1.colon)) { prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); prop.kind = "init"; } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) { if (isPattern) { this.unexpected(); } prop.kind = "init"; prop.method = true; prop.value = this.parseMethod(isGenerator, isAsync); } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) { if (isGenerator || isAsync) { this.unexpected(); } prop.kind = prop.key.name; this.parsePropertyName(prop); prop.value = this.parseMethod(false); var paramCount = prop.kind === "get" ? 0 : 1; if (prop.value.params.length !== paramCount) { var start = prop.value.start; if (prop.kind === "get") { this.raiseRecoverable(start, "getter should have no params"); } else { this.raiseRecoverable(start, "setter should have exactly one param"); } } else { if (prop.kind === "set" && prop.value.params[0].type === "RestElement") { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } } } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { if (isGenerator || isAsync) { this.unexpected(); } this.checkUnreserved(prop.key); if (prop.key.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = startPos; } prop.kind = "init"; if (isPattern) { prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); } else if (this.type === types$1.eq && refDestructuringErrors) { if (refDestructuringErrors.shorthandAssign < 0) { refDestructuringErrors.shorthandAssign = this.start; } prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); } else { prop.value = this.copyNode(prop.key); } prop.shorthand = true; } else { this.unexpected(); } }; pp$5.parsePropertyName = function(prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(types$1.bracketL)) { prop.computed = true; prop.key = this.parseMaybeAssign(); this.expect(types$1.bracketR); return prop.key } else { prop.computed = false; } } return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") }; // Initialize empty function node. pp$5.initFunction = function(node) { node.id = null; if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } if (this.options.ecmaVersion >= 8) { node.async = false; } }; // Parse object or class method. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.initFunction(node); if (this.options.ecmaVersion >= 6) { node.generator = isGenerator; } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); this.expect(types$1.parenL); node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); this.parseFunctionBody(node, false, true, false); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "FunctionExpression") }; // Parse arrow function expression with given parameters. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) { var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); this.initFunction(node); if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; node.params = this.toAssignableList(params, true); this.parseFunctionBody(node, true, false, forInit); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "ArrowFunctionExpression") }; // Parse function body and check parameters. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { var isExpression = isArrowFunction && this.type !== types$1.braceL; var oldStrict = this.strict, useStrict = false; if (isExpression) { node.body = this.parseMaybeAssign(forInit); node.expression = true; this.checkParams(node, false); } else { var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); if (!oldStrict || nonSimple) { useStrict = this.strictDirective(this.end); // If this is a strict mode function, verify that argument names // are not repeated, and it does not try to bind the words `eval` // or `arguments`. if (useStrict && nonSimple) { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } } // Start a new scope with regard to labels and the `inFunction` // flag (restore them to their old value afterwards). var oldLabels = this.labels; this.labels = []; if (useStrict) { this.strict = true; } // Add the params to varDeclaredNames to ensure that an error is thrown // if a let/const declaration in the function clashes with one of the params. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); node.expression = false; this.adaptDirectivePrologue(node.body.body); this.labels = oldLabels; } this.exitScope(); }; pp$5.isSimpleParamList = function(params) { for (var i = 0, list = params; i < list.length; i += 1) { var param = list[i]; if (param.type !== "Identifier") { return false } } return true }; // Checks function params for various disallowed patterns such as using "eval" // or "arguments" and duplicate parameters. pp$5.checkParams = function(node, allowDuplicates) { var nameHash = Object.create(null); for (var i = 0, list = node.params; i < list.length; i += 1) { var param = list[i]; this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); } }; // Parses a comma-separated list of expressions, and returns them as // an array. `close` is the token type that ends the list, and // `allowEmpty` can be turned on to allow subsequent commas with // nothing in between them to be parsed as `null` (which is needed // for array literals). pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { var elts = [], first = true; while (!this.eat(close)) { if (!first) { this.expect(types$1.comma); if (allowTrailingComma && this.afterTrailingComma(close)) { break } } else { first = false; } var elt = (void 0); if (allowEmpty && this.type === types$1.comma) { elt = null; } else if (this.type === types$1.ellipsis) { elt = this.parseSpread(refDestructuringErrors); if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this.start; } } else { elt = this.parseMaybeAssign(false, refDestructuringErrors); } elts.push(elt); } return elts }; pp$5.checkUnreserved = function(ref) { var start = ref.start; var end = ref.end; var name = ref.name; if (this.inGenerator && name === "yield") { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } if (this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } if (this.currentThisScope().inClassFieldInit && name === "arguments") { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } if (this.inClassStaticBlock && (name === "arguments" || name === "await")) { this.raise(start, ("Cannot use " + name + " in class static initialization block")); } if (this.keywords.test(name)) { this.raise(start, ("Unexpected keyword '" + name + "'")); } if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) { return } var re = this.strict ? this.reservedWordsStrict : this.reservedWords; if (re.test(name)) { if (!this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); } }; // Parse the next token as an identifier. If `liberal` is true (used // when parsing properties), it will also convert keywords into // identifiers. pp$5.parseIdent = function(liberal, isBinding) { var node = this.startNode(); if (this.type === types$1.name) { node.name = this.value; } else if (this.type.keyword) { node.name = this.type.keyword; // To fix path_to_url // `class` and `function` keywords push new context into this.context. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { this.context.pop(); } } else { this.unexpected(); } this.next(!!liberal); this.finishNode(node, "Identifier"); if (!liberal) { this.checkUnreserved(node); if (node.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = node.start; } } return node }; pp$5.parsePrivateIdent = function() { var node = this.startNode(); if (this.type === types$1.privateId) { node.name = this.value; } else { this.unexpected(); } this.next(); this.finishNode(node, "PrivateIdentifier"); // For validating existence if (this.privateNameStack.length === 0) { this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); } else { this.privateNameStack[this.privateNameStack.length - 1].used.push(node); } return node }; // Parses yield expression inside generator. pp$5.parseYield = function(forInit) { if (!this.yieldPos) { this.yieldPos = this.start; } var node = this.startNode(); this.next(); if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) { node.delegate = false; node.argument = null; } else { node.delegate = this.eat(types$1.star); node.argument = this.parseMaybeAssign(forInit); } return this.finishNode(node, "YieldExpression") }; pp$5.parseAwait = function(forInit) { if (!this.awaitPos) { this.awaitPos = this.start; } var node = this.startNode(); this.next(); node.argument = this.parseMaybeUnary(null, true, false, forInit); return this.finishNode(node, "AwaitExpression") }; var pp$4 = Parser.prototype; // This function is used to raise exceptions on parse errors. It // takes an offset integer (into the current `input`) to indicate // the location of the error, attaches the position to the end // of the error message, and then raises a `SyntaxError` with that // message. pp$4.raise = function(pos, message) { var loc = getLineInfo(this.input, pos); message += " (" + loc.line + ":" + loc.column + ")"; var err = new SyntaxError(message); err.pos = pos; err.loc = loc; err.raisedAt = this.pos; throw err }; pp$4.raiseRecoverable = pp$4.raise; pp$4.curPosition = function() { if (this.options.locations) { return new Position(this.curLine, this.pos - this.lineStart) } }; var pp$3 = Parser.prototype; var Scope = function Scope(flags) { this.flags = flags; // A list of var-declared names in the current lexical scope this.var = []; // A list of lexically-declared names in the current lexical scope this.lexical = []; // A list of lexically-declared FunctionDeclaration names in the current lexical scope this.functions = []; // A switch to disallow the identifier reference 'arguments' this.inClassFieldInit = false; }; // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. pp$3.enterScope = function(flags) { this.scopeStack.push(new Scope(flags)); }; pp$3.exitScope = function() { this.scopeStack.pop(); }; // The spec says: // > At the top level of a function, or script, function declarations are // > treated like var declarations rather than like lexical declarations. pp$3.treatFunctionsAsVarInScope = function(scope) { return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) }; pp$3.declareName = function(name, bindingType, pos) { var redeclared = false; if (bindingType === BIND_LEXICAL) { var scope = this.currentScope(); redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; scope.lexical.push(name); if (this.inModule && (scope.flags & SCOPE_TOP)) { delete this.undefinedExports[name]; } } else if (bindingType === BIND_SIMPLE_CATCH) { var scope$1 = this.currentScope(); scope$1.lexical.push(name); } else if (bindingType === BIND_FUNCTION) { var scope$2 = this.currentScope(); if (this.treatFunctionsAsVar) { redeclared = scope$2.lexical.indexOf(name) > -1; } else { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } scope$2.functions.push(name); } else { for (var i = this.scopeStack.length - 1; i >= 0; --i) { var scope$3 = this.scopeStack[i]; if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { redeclared = true; break } scope$3.var.push(name); if (this.inModule && (scope$3.flags & SCOPE_TOP)) { delete this.undefinedExports[name]; } if (scope$3.flags & SCOPE_VAR) { break } } } if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } }; pp$3.checkLocalExport = function(id) { // scope.functions must be empty as Module code is always strict. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) { this.undefinedExports[id.name] = id; } }; pp$3.currentScope = function() { return this.scopeStack[this.scopeStack.length - 1] }; pp$3.currentVarScope = function() { for (var i = this.scopeStack.length - 1;; i--) { var scope = this.scopeStack[i]; if (scope.flags & SCOPE_VAR) { return scope } } }; // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. pp$3.currentThisScope = function() { for (var i = this.scopeStack.length - 1;; i--) { var scope = this.scopeStack[i]; if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } } }; var Node = function Node(parser, pos, loc) { this.type = ""; this.start = pos; this.end = 0; if (parser.options.locations) { this.loc = new SourceLocation(parser, loc); } if (parser.options.directSourceFile) { this.sourceFile = parser.options.directSourceFile; } if (parser.options.ranges) { this.range = [pos, 0]; } }; // Start an AST node, attaching a start offset. var pp$2 = Parser.prototype; pp$2.startNode = function() { return new Node(this, this.start, this.startLoc) }; pp$2.startNodeAt = function(pos, loc) { return new Node(this, pos, loc) }; // Finish an AST node, adding `type` and `end` properties. function finishNodeAt(node, type, pos, loc) { node.type = type; node.end = pos; if (this.options.locations) { node.loc.end = loc; } if (this.options.ranges) { node.range[1] = pos; } return node } pp$2.finishNode = function(node, type) { return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) }; // Finish node at given position pp$2.finishNodeAt = function(node, type, pos, loc) { return finishNodeAt.call(this, node, type, pos, loc) }; pp$2.copyNode = function(node) { var newNode = new Node(this, node.start, this.startLoc); for (var prop in node) { newNode[prop] = node[prop]; } return newNode }; // This file contains Unicode properties extracted from the ECMAScript // specification. The lists are extracted like so: // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) // #table-binary-unicode-properties var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; var ecma11BinaryProperties = ecma10BinaryProperties; var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; var ecma13BinaryProperties = ecma12BinaryProperties; var unicodeBinaryProperties = { 9: ecma9BinaryProperties, 10: ecma10BinaryProperties, 11: ecma11BinaryProperties, 12: ecma12BinaryProperties, 13: ecma13BinaryProperties }; // #table-unicode-general-category-values var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; // #table-unicode-script-values var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; var unicodeScriptValues = { 9: ecma9ScriptValues, 10: ecma10ScriptValues, 11: ecma11ScriptValues, 12: ecma12ScriptValues, 13: ecma13ScriptValues }; var data = {}; function buildUnicodeData(ecmaVersion) { var d = data[ecmaVersion] = { binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), nonBinary: { General_Category: wordsRegexp(unicodeGeneralCategoryValues), Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) } }; d.nonBinary.Script_Extensions = d.nonBinary.Script; d.nonBinary.gc = d.nonBinary.General_Category; d.nonBinary.sc = d.nonBinary.Script; d.nonBinary.scx = d.nonBinary.Script_Extensions; } for (var i = 0, list = [9, 10, 11, 12, 13]; i < list.length; i += 1) { var ecmaVersion = list[i]; buildUnicodeData(ecmaVersion); } var pp$1 = Parser.prototype; var RegExpValidationState = function RegExpValidationState(parser) { this.parser = parser; this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : ""); this.unicodeProperties = data[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion]; this.source = ""; this.flags = ""; this.start = 0; this.switchU = false; this.switchN = false; this.pos = 0; this.lastIntValue = 0; this.lastStringValue = ""; this.lastAssertionIsQuantifiable = false; this.numCapturingParens = 0; this.maxBackReference = 0; this.groupNames = []; this.backReferenceNames = []; }; RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { var unicode = flags.indexOf("u") !== -1; this.start = start | 0; this.source = pattern + ""; this.flags = flags; this.switchU = unicode && this.parser.options.ecmaVersion >= 6; this.switchN = unicode && this.parser.options.ecmaVersion >= 9; }; RegExpValidationState.prototype.raise = function raise (message) { this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); }; // If u flag is given, this returns the code point at the index (it combines a surrogate pair). // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). RegExpValidationState.prototype.at = function at (i, forceU) { if ( forceU === void 0 ) forceU = false; var s = this.source; var l = s.length; if (i >= l) { return -1 } var c = s.charCodeAt(i); if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { return c } var next = s.charCodeAt(i + 1); return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c }; RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { if ( forceU === void 0 ) forceU = false; var s = this.source; var l = s.length; if (i >= l) { return l } var c = s.charCodeAt(i), next; if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { return i + 1 } return i + 2 }; RegExpValidationState.prototype.current = function current (forceU) { if ( forceU === void 0 ) forceU = false; return this.at(this.pos, forceU) }; RegExpValidationState.prototype.lookahead = function lookahead (forceU) { if ( forceU === void 0 ) forceU = false; return this.at(this.nextIndex(this.pos, forceU), forceU) }; RegExpValidationState.prototype.advance = function advance (forceU) { if ( forceU === void 0 ) forceU = false; this.pos = this.nextIndex(this.pos, forceU); }; RegExpValidationState.prototype.eat = function eat (ch, forceU) { if ( forceU === void 0 ) forceU = false; if (this.current(forceU) === ch) { this.advance(forceU); return true } return false }; /** * Validate the flags part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp$1.validateRegExpFlags = function(state) { var validFlags = state.validFlags; var flags = state.flags; for (var i = 0; i < flags.length; i++) { var flag = flags.charAt(i); if (validFlags.indexOf(flag) === -1) { this.raise(state.start, "Invalid regular expression flag"); } if (flags.indexOf(flag, i + 1) > -1) { this.raise(state.start, "Duplicate regular expression flag"); } } }; /** * Validate the pattern part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp$1.validateRegExpPattern = function(state) { this.regexp_pattern(state); // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of // parsing contains a |GroupName|, reparse with the goal symbol // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* // exception if _P_ did not conform to the grammar, if any elements of _P_ // were not matched by the parse, or if any Early Error conditions exist. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { state.switchN = true; this.regexp_pattern(state); } }; // path_to_url#prod-Pattern pp$1.regexp_pattern = function(state) { state.pos = 0; state.lastIntValue = 0; state.lastStringValue = ""; state.lastAssertionIsQuantifiable = false; state.numCapturingParens = 0; state.maxBackReference = 0; state.groupNames.length = 0; state.backReferenceNames.length = 0; this.regexp_disjunction(state); if (state.pos !== state.source.length) { // Make the same messages as V8. if (state.eat(0x29 /* ) */)) { state.raise("Unmatched ')'"); } if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { state.raise("Lone quantifier brackets"); } } if (state.maxBackReference > state.numCapturingParens) { state.raise("Invalid escape"); } for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { var name = list[i]; if (state.groupNames.indexOf(name) === -1) { state.raise("Invalid named capture referenced"); } } }; // path_to_url#prod-Disjunction pp$1.regexp_disjunction = function(state) { this.regexp_alternative(state); while (state.eat(0x7C /* | */)) { this.regexp_alternative(state); } // Make the same message as V8. if (this.regexp_eatQuantifier(state, true)) { state.raise("Nothing to repeat"); } if (state.eat(0x7B /* { */)) { state.raise("Lone quantifier brackets"); } }; // path_to_url#prod-Alternative pp$1.regexp_alternative = function(state) { while (state.pos < state.source.length && this.regexp_eatTerm(state)) { } }; // path_to_url#prod-annexB-Term pp$1.regexp_eatTerm = function(state) { if (this.regexp_eatAssertion(state)) { // Handle `QuantifiableAssertion Quantifier` alternative. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion // is a QuantifiableAssertion. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { // Make the same message as V8. if (state.switchU) { state.raise("Invalid quantifier"); } } return true } if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { this.regexp_eatQuantifier(state); return true } return false }; // path_to_url#prod-annexB-Assertion pp$1.regexp_eatAssertion = function(state) { var start = state.pos; state.lastAssertionIsQuantifiable = false; // ^, $ if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { return true } // \b \B if (state.eat(0x5C /* \ */)) { if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { return true } state.pos = start; } // Lookahead / Lookbehind if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { var lookbehind = false; if (this.options.ecmaVersion >= 9) { lookbehind = state.eat(0x3C /* < */); } if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { this.regexp_disjunction(state); if (!state.eat(0x29 /* ) */)) { state.raise("Unterminated group"); } state.lastAssertionIsQuantifiable = !lookbehind; return true } } state.pos = start; return false }; // path_to_url#prod-Quantifier pp$1.regexp_eatQuantifier = function(state, noError) { if ( noError === void 0 ) noError = false; if (this.regexp_eatQuantifierPrefix(state, noError)) { state.eat(0x3F /* ? */); return true } return false }; // path_to_url#prod-QuantifierPrefix pp$1.regexp_eatQuantifierPrefix = function(state, noError) { return ( state.eat(0x2A /* * */) || state.eat(0x2B /* + */) || state.eat(0x3F /* ? */) || this.regexp_eatBracedQuantifier(state, noError) ) }; pp$1.regexp_eatBracedQuantifier = function(state, noError) { var start = state.pos; if (state.eat(0x7B /* { */)) { var min = 0, max = -1; if (this.regexp_eatDecimalDigits(state)) { min = state.lastIntValue; if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { max = state.lastIntValue; } if (state.eat(0x7D /* } */)) { // SyntaxError in path_to_url#sec-term if (max !== -1 && max < min && !noError) { state.raise("numbers out of order in {} quantifier"); } return true } } if (state.switchU && !noError) { state.raise("Incomplete quantifier"); } state.pos = start; } return false }; // path_to_url#prod-Atom pp$1.regexp_eatAtom = function(state) { return ( this.regexp_eatPatternCharacters(state) || state.eat(0x2E /* . */) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) ) }; pp$1.regexp_eatReverseSolidusAtomEscape = function(state) { var start = state.pos; if (state.eat(0x5C /* \ */)) { if (this.regexp_eatAtomEscape(state)) { return true } state.pos = start; } return false }; pp$1.regexp_eatUncapturingGroup = function(state) { var start = state.pos; if (state.eat(0x28 /* ( */)) { if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { this.regexp_disjunction(state); if (state.eat(0x29 /* ) */)) { return true } state.raise("Unterminated group"); } state.pos = start; } return false }; pp$1.regexp_eatCapturingGroup = function(state) { if (state.eat(0x28 /* ( */)) { if (this.options.ecmaVersion >= 9) { this.regexp_groupSpecifier(state); } else if (state.current() === 0x3F /* ? */) { state.raise("Invalid group"); } this.regexp_disjunction(state); if (state.eat(0x29 /* ) */)) { state.numCapturingParens += 1; return true } state.raise("Unterminated group"); } return false }; // path_to_url#prod-annexB-ExtendedAtom pp$1.regexp_eatExtendedAtom = function(state) { return ( state.eat(0x2E /* . */) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state) ) }; // path_to_url#prod-annexB-InvalidBracedQuantifier pp$1.regexp_eatInvalidBracedQuantifier = function(state) { if (this.regexp_eatBracedQuantifier(state, true)) { state.raise("Nothing to repeat"); } return false }; // path_to_url#prod-SyntaxCharacter pp$1.regexp_eatSyntaxCharacter = function(state) { var ch = state.current(); if (isSyntaxCharacter(ch)) { state.lastIntValue = ch; state.advance(); return true } return false }; function isSyntaxCharacter(ch) { return ( ch === 0x24 /* $ */ || ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || ch === 0x2E /* . */ || ch === 0x3F /* ? */ || ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || ch >= 0x7B /* { */ && ch <= 0x7D /* } */ ) } // path_to_url#prod-PatternCharacter // But eat eager. pp$1.regexp_eatPatternCharacters = function(state) { var start = state.pos; var ch = 0; while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { state.advance(); } return state.pos !== start }; // path_to_url#prod-annexB-ExtendedPatternCharacter pp$1.regexp_eatExtendedPatternCharacter = function(state) { var ch = state.current(); if ( ch !== -1 && ch !== 0x24 /* $ */ && !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && ch !== 0x2E /* . */ && ch !== 0x3F /* ? */ && ch !== 0x5B /* [ */ && ch !== 0x5E /* ^ */ && ch !== 0x7C /* | */ ) { state.advance(); return true } return false }; // GroupSpecifier :: // [empty] // `?` GroupName pp$1.regexp_groupSpecifier = function(state) { if (state.eat(0x3F /* ? */)) { if (this.regexp_eatGroupName(state)) { if (state.groupNames.indexOf(state.lastStringValue) !== -1) { state.raise("Duplicate capture group name"); } state.groupNames.push(state.lastStringValue); return } state.raise("Invalid group"); } }; // GroupName :: // `<` RegExpIdentifierName `>` // Note: this updates `state.lastStringValue` property with the eaten name. pp$1.regexp_eatGroupName = function(state) { state.lastStringValue = ""; if (state.eat(0x3C /* < */)) { if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { return true } state.raise("Invalid capture group name"); } return false }; // RegExpIdentifierName :: // RegExpIdentifierStart // RegExpIdentifierName RegExpIdentifierPart // Note: this updates `state.lastStringValue` property with the eaten name. pp$1.regexp_eatRegExpIdentifierName = function(state) { state.lastStringValue = ""; if (this.regexp_eatRegExpIdentifierStart(state)) { state.lastStringValue += codePointToString(state.lastIntValue); while (this.regexp_eatRegExpIdentifierPart(state)) { state.lastStringValue += codePointToString(state.lastIntValue); } return true } return false }; // RegExpIdentifierStart :: // UnicodeIDStart // `$` // `_` // `\` RegExpUnicodeEscapeSequence[+U] pp$1.regexp_eatRegExpIdentifierStart = function(state) { var start = state.pos; var forceU = this.options.ecmaVersion >= 11; var ch = state.current(forceU); state.advance(forceU); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue; } if (isRegExpIdentifierStart(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierStart(ch) { return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ } // RegExpIdentifierPart :: // UnicodeIDContinue // `$` // `_` // `\` RegExpUnicodeEscapeSequence[+U] // <ZWNJ> // <ZWJ> pp$1.regexp_eatRegExpIdentifierPart = function(state) { var start = state.pos; var forceU = this.options.ecmaVersion >= 11; var ch = state.current(forceU); state.advance(forceU); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue; } if (isRegExpIdentifierPart(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierPart(ch) { return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */ } // path_to_url#prod-annexB-AtomEscape pp$1.regexp_eatAtomEscape = function(state) { if ( this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || (state.switchN && this.regexp_eatKGroupName(state)) ) { return true } if (state.switchU) { // Make the same message as V8. if (state.current() === 0x63 /* c */) { state.raise("Invalid unicode escape"); } state.raise("Invalid escape"); } return false }; pp$1.regexp_eatBackReference = function(state) { var start = state.pos; if (this.regexp_eatDecimalEscape(state)) { var n = state.lastIntValue; if (state.switchU) { // For SyntaxError in path_to_url#sec-atomescape if (n > state.maxBackReference) { state.maxBackReference = n; } return true } if (n <= state.numCapturingParens) { return true } state.pos = start; } return false }; pp$1.regexp_eatKGroupName = function(state) { if (state.eat(0x6B /* k */)) { if (this.regexp_eatGroupName(state)) { state.backReferenceNames.push(state.lastStringValue); return true } state.raise("Invalid named reference"); } return false }; // path_to_url#prod-annexB-CharacterEscape pp$1.regexp_eatCharacterEscape = function(state) { return ( this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || this.regexp_eatIdentityEscape(state) ) }; pp$1.regexp_eatCControlLetter = function(state) { var start = state.pos; if (state.eat(0x63 /* c */)) { if (this.regexp_eatControlLetter(state)) { return true } state.pos = start; } return false }; pp$1.regexp_eatZero = function(state) { if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { state.lastIntValue = 0; state.advance(); return true } return false }; // path_to_url#prod-ControlEscape pp$1.regexp_eatControlEscape = function(state) { var ch = state.current(); if (ch === 0x74 /* t */) { state.lastIntValue = 0x09; /* \t */ state.advance(); return true } if (ch === 0x6E /* n */) { state.lastIntValue = 0x0A; /* \n */ state.advance(); return true } if (ch === 0x76 /* v */) { state.lastIntValue = 0x0B; /* \v */ state.advance(); return true } if (ch === 0x66 /* f */) { state.lastIntValue = 0x0C; /* \f */ state.advance(); return true } if (ch === 0x72 /* r */) { state.lastIntValue = 0x0D; /* \r */ state.advance(); return true } return false }; // path_to_url#prod-ControlLetter pp$1.regexp_eatControlLetter = function(state) { var ch = state.current(); if (isControlLetter(ch)) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; function isControlLetter(ch) { return ( (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) ) } // path_to_url#prod-RegExpUnicodeEscapeSequence pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { if ( forceU === void 0 ) forceU = false; var start = state.pos; var switchU = forceU || state.switchU; if (state.eat(0x75 /* u */)) { if (this.regexp_eatFixedHexDigits(state, 4)) { var lead = state.lastIntValue; if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { var leadSurrogateEnd = state.pos; if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { var trail = state.lastIntValue; if (trail >= 0xDC00 && trail <= 0xDFFF) { state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; return true } } state.pos = leadSurrogateEnd; state.lastIntValue = lead; } return true } if ( switchU && state.eat(0x7B /* { */) && this.regexp_eatHexDigits(state) && state.eat(0x7D /* } */) && isValidUnicode(state.lastIntValue) ) { return true } if (switchU) { state.raise("Invalid unicode escape"); } state.pos = start; } return false }; function isValidUnicode(ch) { return ch >= 0 && ch <= 0x10FFFF } // path_to_url#prod-annexB-IdentityEscape pp$1.regexp_eatIdentityEscape = function(state) { if (state.switchU) { if (this.regexp_eatSyntaxCharacter(state)) { return true } if (state.eat(0x2F /* / */)) { state.lastIntValue = 0x2F; /* / */ return true } return false } var ch = state.current(); if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { state.lastIntValue = ch; state.advance(); return true } return false }; // path_to_url#prod-DecimalEscape pp$1.regexp_eatDecimalEscape = function(state) { state.lastIntValue = 0; var ch = state.current(); if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { do { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); state.advance(); } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) return true } return false }; // path_to_url#prod-CharacterClassEscape pp$1.regexp_eatCharacterClassEscape = function(state) { var ch = state.current(); if (isCharacterClassEscape(ch)) { state.lastIntValue = -1; state.advance(); return true } if ( state.switchU && this.options.ecmaVersion >= 9 && (ch === 0x50 /* P */ || ch === 0x70 /* p */) ) { state.lastIntValue = -1; state.advance(); if ( state.eat(0x7B /* { */) && this.regexp_eatUnicodePropertyValueExpression(state) && state.eat(0x7D /* } */) ) { return true } state.raise("Invalid property name"); } return false }; function isCharacterClassEscape(ch) { return ( ch === 0x64 /* d */ || ch === 0x44 /* D */ || ch === 0x73 /* s */ || ch === 0x53 /* S */ || ch === 0x77 /* w */ || ch === 0x57 /* W */ ) } // UnicodePropertyValueExpression :: // UnicodePropertyName `=` UnicodePropertyValue // LoneUnicodePropertyNameOrValue pp$1.regexp_eatUnicodePropertyValueExpression = function(state) { var start = state.pos; // UnicodePropertyName `=` UnicodePropertyValue if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { var name = state.lastStringValue; if (this.regexp_eatUnicodePropertyValue(state)) { var value = state.lastStringValue; this.regexp_validateUnicodePropertyNameAndValue(state, name, value); return true } } state.pos = start; // LoneUnicodePropertyNameOrValue if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { var nameOrValue = state.lastStringValue; this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); return true } return false }; pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { if (!hasOwn(state.unicodeProperties.nonBinary, name)) { state.raise("Invalid property name"); } if (!state.unicodeProperties.nonBinary[name].test(value)) { state.raise("Invalid property value"); } }; pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { if (!state.unicodeProperties.binary.test(nameOrValue)) { state.raise("Invalid property name"); } }; // UnicodePropertyName :: // UnicodePropertyNameCharacters pp$1.regexp_eatUnicodePropertyName = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyNameCharacter(ch = state.current())) { state.lastStringValue += codePointToString(ch); state.advance(); } return state.lastStringValue !== "" }; function isUnicodePropertyNameCharacter(ch) { return isControlLetter(ch) || ch === 0x5F /* _ */ } // UnicodePropertyValue :: // UnicodePropertyValueCharacters pp$1.regexp_eatUnicodePropertyValue = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyValueCharacter(ch = state.current())) { state.lastStringValue += codePointToString(ch); state.advance(); } return state.lastStringValue !== "" }; function isUnicodePropertyValueCharacter(ch) { return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) } // LoneUnicodePropertyNameOrValue :: // UnicodePropertyValueCharacters pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { return this.regexp_eatUnicodePropertyValue(state) }; // path_to_url#prod-CharacterClass pp$1.regexp_eatCharacterClass = function(state) { if (state.eat(0x5B /* [ */)) { state.eat(0x5E /* ^ */); this.regexp_classRanges(state); if (state.eat(0x5D /* ] */)) { return true } // Unreachable since it threw "unterminated regular expression" error before. state.raise("Unterminated character class"); } return false }; // path_to_url#prod-ClassRanges // path_to_url#prod-NonemptyClassRanges // path_to_url#prod-NonemptyClassRangesNoDash pp$1.regexp_classRanges = function(state) { while (this.regexp_eatClassAtom(state)) { var left = state.lastIntValue; if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { var right = state.lastIntValue; if (state.switchU && (left === -1 || right === -1)) { state.raise("Invalid character class"); } if (left !== -1 && right !== -1 && left > right) { state.raise("Range out of order in character class"); } } } }; // path_to_url#prod-ClassAtom // path_to_url#prod-ClassAtomNoDash pp$1.regexp_eatClassAtom = function(state) { var start = state.pos; if (state.eat(0x5C /* \ */)) { if (this.regexp_eatClassEscape(state)) { return true } if (state.switchU) { // Make the same message as V8. var ch$1 = state.current(); if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { state.raise("Invalid class escape"); } state.raise("Invalid escape"); } state.pos = start; } var ch = state.current(); if (ch !== 0x5D /* ] */) { state.lastIntValue = ch; state.advance(); return true } return false }; // path_to_url#prod-annexB-ClassEscape pp$1.regexp_eatClassEscape = function(state) { var start = state.pos; if (state.eat(0x62 /* b */)) { state.lastIntValue = 0x08; /* <BS> */ return true } if (state.switchU && state.eat(0x2D /* - */)) { state.lastIntValue = 0x2D; /* - */ return true } if (!state.switchU && state.eat(0x63 /* c */)) { if (this.regexp_eatClassControlLetter(state)) { return true } state.pos = start; } return ( this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) ) }; // path_to_url#prod-annexB-ClassControlLetter pp$1.regexp_eatClassControlLetter = function(state) { var ch = state.current(); if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; // path_to_url#prod-HexEscapeSequence pp$1.regexp_eatHexEscapeSequence = function(state) { var start = state.pos; if (state.eat(0x78 /* x */)) { if (this.regexp_eatFixedHexDigits(state, 2)) { return true } if (state.switchU) { state.raise("Invalid escape"); } state.pos = start; } return false }; // path_to_url#prod-DecimalDigits pp$1.regexp_eatDecimalDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isDecimalDigit(ch = state.current())) { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); state.advance(); } return state.pos !== start }; function isDecimalDigit(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ } // path_to_url#prod-HexDigits pp$1.regexp_eatHexDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isHexDigit(ch = state.current())) { state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance(); } return state.pos !== start }; function isHexDigit(ch) { return ( (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) ) } function hexToInt(ch) { if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { return 10 + (ch - 0x41 /* A */) } if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { return 10 + (ch - 0x61 /* a */) } return ch - 0x30 /* 0 */ } // path_to_url#prod-annexB-LegacyOctalEscapeSequence // Allows only 0-377(octal) i.e. 0-255(decimal). pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) { if (this.regexp_eatOctalDigit(state)) { var n1 = state.lastIntValue; if (this.regexp_eatOctalDigit(state)) { var n2 = state.lastIntValue; if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; } else { state.lastIntValue = n1 * 8 + n2; } } else { state.lastIntValue = n1; } return true } return false }; // path_to_url#prod-OctalDigit pp$1.regexp_eatOctalDigit = function(state) { var ch = state.current(); if (isOctalDigit(ch)) { state.lastIntValue = ch - 0x30; /* 0 */ state.advance(); return true } state.lastIntValue = 0; return false }; function isOctalDigit(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ } // path_to_url#prod-Hex4Digits // path_to_url#prod-HexDigit // And HexDigit HexDigit in path_to_url#prod-HexEscapeSequence pp$1.regexp_eatFixedHexDigits = function(state, length) { var start = state.pos; state.lastIntValue = 0; for (var i = 0; i < length; ++i) { var ch = state.current(); if (!isHexDigit(ch)) { state.pos = start; return false } state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance(); } return true }; // Object type used to represent tokens. Note that normally, tokens // simply exist as properties on the parser object. This is only // used for the onToken callback and the external tokenizer. var Token = function Token(p) { this.type = p.type; this.value = p.value; this.start = p.start; this.end = p.end; if (p.options.locations) { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } if (p.options.ranges) { this.range = [p.start, p.end]; } }; // ## Tokenizer var pp = Parser.prototype; // Move to the next token pp.next = function(ignoreEscapeSequenceInKeyword) { if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } if (this.options.onToken) { this.options.onToken(new Token(this)); } this.lastTokEnd = this.end; this.lastTokStart = this.start; this.lastTokEndLoc = this.endLoc; this.lastTokStartLoc = this.startLoc; this.nextToken(); }; pp.getToken = function() { this.next(); return new Token(this) }; // If we're in an ES6 environment, make parsers iterable if (typeof Symbol !== "undefined") { pp[Symbol.iterator] = function() { var this$1$1 = this; return { next: function () { var token = this$1$1.getToken(); return { done: token.type === types$1.eof, value: token } } } }; } // Toggle strict mode. Re-reads the next number or string to please // pedantic tests (`"use strict"; 010;` should fail). // Read a single token, updating the parser object's token-related // properties. pp.nextToken = function() { var curContext = this.curContext(); if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } this.start = this.pos; if (this.options.locations) { this.startLoc = this.curPosition(); } if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) } if (curContext.override) { return curContext.override(this) } else { this.readToken(this.fullCharCodeAtPos()); } }; pp.readToken = function(code) { // Identifier or keyword. '\uXXXX' sequences are allowed in // identifiers, so '\' also dispatches to that. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) { return this.readWord() } return this.getTokenFromCode(code) }; pp.fullCharCodeAtPos = function() { var code = this.input.charCodeAt(this.pos); if (code <= 0xd7ff || code >= 0xdc00) { return code } var next = this.input.charCodeAt(this.pos + 1); return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 }; pp.skipBlockComment = function() { var startLoc = this.options.onComment && this.curPosition(); var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } this.pos = end + 2; if (this.options.locations) { for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) { ++this.curLine; pos = this.lineStart = nextBreak; } } if (this.options.onComment) { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition()); } }; pp.skipLineComment = function(startSkip) { var start = this.pos; var startLoc = this.options.onComment && this.curPosition(); var ch = this.input.charCodeAt(this.pos += startSkip); while (this.pos < this.input.length && !isNewLine(ch)) { ch = this.input.charCodeAt(++this.pos); } if (this.options.onComment) { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition()); } }; // Called at the start of the parse and after every token. Skips // whitespace and comments, and. pp.skipSpace = function() { loop: while (this.pos < this.input.length) { var ch = this.input.charCodeAt(this.pos); switch (ch) { case 32: case 160: // ' ' ++this.pos; break case 13: if (this.input.charCodeAt(this.pos + 1) === 10) { ++this.pos; } case 10: case 8232: case 8233: ++this.pos; if (this.options.locations) { ++this.curLine; this.lineStart = this.pos; } break case 47: // '/' switch (this.input.charCodeAt(this.pos + 1)) { case 42: // '*' this.skipBlockComment(); break case 47: this.skipLineComment(2); break default: break loop } break default: if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { ++this.pos; } else { break loop } } } }; // Called at the end of every token. Sets `end`, `val`, and // maintains `context` and `exprAllowed`, and skips the space after // the token, so that the next one's `start` will point at the // right position. pp.finishToken = function(type, val) { this.end = this.pos; if (this.options.locations) { this.endLoc = this.curPosition(); } var prevType = this.type; this.type = type; this.value = val; this.updateContext(prevType); }; // ### Token reading // This is the function that is called to fetch the next token. It // is somewhat obscure, because it works in character codes rather // than characters, and because operator parsing has been inlined // into it. // // All in the name of speed. // pp.readToken_dot = function() { var next = this.input.charCodeAt(this.pos + 1); if (next >= 48 && next <= 57) { return this.readNumber(true) } var next2 = this.input.charCodeAt(this.pos + 2); if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' this.pos += 3; return this.finishToken(types$1.ellipsis) } else { ++this.pos; return this.finishToken(types$1.dot) } }; pp.readToken_slash = function() { // '/' var next = this.input.charCodeAt(this.pos + 1); if (this.exprAllowed) { ++this.pos; return this.readRegexp() } if (next === 61) { return this.finishOp(types$1.assign, 2) } return this.finishOp(types$1.slash, 1) }; pp.readToken_mult_modulo_exp = function(code) { // '%*' var next = this.input.charCodeAt(this.pos + 1); var size = 1; var tokentype = code === 42 ? types$1.star : types$1.modulo; // exponentiation operator ** and **= if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { ++size; tokentype = types$1.starstar; next = this.input.charCodeAt(this.pos + 2); } if (next === 61) { return this.finishOp(types$1.assign, size + 1) } return this.finishOp(tokentype, size) }; pp.readToken_pipe_amp = function(code) { // '|&' var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (this.options.ecmaVersion >= 12) { var next2 = this.input.charCodeAt(this.pos + 2); if (next2 === 61) { return this.finishOp(types$1.assign, 3) } } return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2) } if (next === 61) { return this.finishOp(types$1.assign, 2) } return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1) }; pp.readToken_caret = function() { // '^' var next = this.input.charCodeAt(this.pos + 1); if (next === 61) { return this.finishOp(types$1.assign, 2) } return this.finishOp(types$1.bitwiseXOR, 1) }; pp.readToken_plus_min = function(code) { // '+-' var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { // A `-->` line comment this.skipLineComment(3); this.skipSpace(); return this.nextToken() } return this.finishOp(types$1.incDec, 2) } if (next === 61) { return this.finishOp(types$1.assign, 2) } return this.finishOp(types$1.plusMin, 1) }; pp.readToken_lt_gt = function(code) { // '<>' var next = this.input.charCodeAt(this.pos + 1); var size = 1; if (next === code) { size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) } return this.finishOp(types$1.bitShift, size) } if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) { // `<!--`, an XML-style comment that should be interpreted as a line comment this.skipLineComment(4); this.skipSpace(); return this.nextToken() } if (next === 61) { size = 2; } return this.finishOp(types$1.relational, size) }; pp.readToken_eq_excl = function(code) { // '=!' var next = this.input.charCodeAt(this.pos + 1); if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) } if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>' this.pos += 2; return this.finishToken(types$1.arrow) } return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1) }; pp.readToken_question = function() { // '?' var ecmaVersion = this.options.ecmaVersion; if (ecmaVersion >= 11) { var next = this.input.charCodeAt(this.pos + 1); if (next === 46) { var next2 = this.input.charCodeAt(this.pos + 2); if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) } } if (next === 63) { if (ecmaVersion >= 12) { var next2$1 = this.input.charCodeAt(this.pos + 2); if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) } } return this.finishOp(types$1.coalesce, 2) } } return this.finishOp(types$1.question, 1) }; pp.readToken_numberSign = function() { // '#' var ecmaVersion = this.options.ecmaVersion; var code = 35; // '#' if (ecmaVersion >= 13) { ++this.pos; code = this.fullCharCodeAtPos(); if (isIdentifierStart(code, true) || code === 92 /* '\' */) { return this.finishToken(types$1.privateId, this.readWord1()) } } this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'"); }; pp.getTokenFromCode = function(code) { switch (code) { // The interpretation of a dot depends on whether it is followed // by a digit or another two dots. case 46: // '.' return this.readToken_dot() // Punctuation tokens. case 40: ++this.pos; return this.finishToken(types$1.parenL) case 41: ++this.pos; return this.finishToken(types$1.parenR) case 59: ++this.pos; return this.finishToken(types$1.semi) case 44: ++this.pos; return this.finishToken(types$1.comma) case 91: ++this.pos; return this.finishToken(types$1.bracketL) case 93: ++this.pos; return this.finishToken(types$1.bracketR) case 123: ++this.pos; return this.finishToken(types$1.braceL) case 125: ++this.pos; return this.finishToken(types$1.braceR) case 58: ++this.pos; return this.finishToken(types$1.colon) case 96: // '`' if (this.options.ecmaVersion < 6) { break } ++this.pos; return this.finishToken(types$1.backQuote) case 48: // '0' var next = this.input.charCodeAt(this.pos + 1); if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number if (this.options.ecmaVersion >= 6) { if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number } // Anything else beginning with a digit is an integer, octal // number, or float. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9 return this.readNumber(false) // Quotes produce strings. case 34: case 39: // '"', "'" return this.readString(code) // Operators are parsed inline in tiny state machines. '=' (61) is // often referred to. `finishOp` simply skips the amount of // characters it is given as second argument, and returns a token // of the type given by its first argument. case 47: // '/' return this.readToken_slash() case 37: case 42: // '%*' return this.readToken_mult_modulo_exp(code) case 124: case 38: // '|&' return this.readToken_pipe_amp(code) case 94: // '^' return this.readToken_caret() case 43: case 45: // '+-' return this.readToken_plus_min(code) case 60: case 62: // '<>' return this.readToken_lt_gt(code) case 61: case 33: // '=!' return this.readToken_eq_excl(code) case 63: // '?' return this.readToken_question() case 126: // '~' return this.finishOp(types$1.prefix, 1) case 35: // '#' return this.readToken_numberSign() } this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'"); }; pp.finishOp = function(type, size) { var str = this.input.slice(this.pos, this.pos + size); this.pos += size; return this.finishToken(type, str) }; pp.readRegexp = function() { var escaped, inClass, start = this.pos; for (;;) { if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); } var ch = this.input.charAt(this.pos); if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); } if (!escaped) { if (ch === "[") { inClass = true; } else if (ch === "]" && inClass) { inClass = false; } else if (ch === "/" && !inClass) { break } escaped = ch === "\\"; } else { escaped = false; } ++this.pos; } var pattern = this.input.slice(start, this.pos); ++this.pos; var flagsStart = this.pos; var flags = this.readWord1(); if (this.containsEsc) { this.unexpected(flagsStart); } // Validate pattern var state = this.regexpState || (this.regexpState = new RegExpValidationState(this)); state.reset(start, pattern, flags); this.validateRegExpFlags(state); this.validateRegExpPattern(state); // Create Literal#value property value. var value = null; try { value = new RegExp(pattern, flags); } catch (e) { // ESTree requires null if it failed to instantiate RegExp object. // path_to_url#regexpliteral } return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value}) }; // Read an integer in the given radix. Return null if zero digits // were read, the integer value otherwise. When `len` is given, this // will return `null` unless the integer has exactly `len` digits. pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) { // `len` is used for character escape sequences. In that case, disallow separators. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined; // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b) // and isn't fraction part nor exponent part. In that case, if the first digit // is zero then disallow separators. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48; var start = this.pos, total = 0, lastCode = 0; for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) { var code = this.input.charCodeAt(this.pos), val = (void 0); if (allowSeparators && code === 95) { if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); } if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); } if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); } lastCode = code; continue } if (code >= 97) { val = code - 97 + 10; } // a else if (code >= 65) { val = code - 65 + 10; } // A else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9 else { val = Infinity; } if (val >= radix) { break } lastCode = code; total = total * radix + val; } if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); } if (this.pos === start || len != null && this.pos - start !== len) { return null } return total }; function stringToNumber(str, isLegacyOctalNumericLiteral) { if (isLegacyOctalNumericLiteral) { return parseInt(str, 8) } // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value. return parseFloat(str.replace(/_/g, "")) } function stringToBigInt(str) { if (typeof BigInt !== "function") { return null } // `BigInt(value)` throws syntax error if the string contains numeric separators. return BigInt(str.replace(/_/g, "")) } pp.readRadixNumber = function(radix) { var start = this.pos; this.pos += 2; // 0x var val = this.readInt(radix); if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); } if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) { val = stringToBigInt(this.input.slice(start, this.pos)); ++this.pos; } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); } return this.finishToken(types$1.num, val) }; // Read an integer, octal integer, or floating-point number. pp.readNumber = function(startsWithDot) { var start = this.pos; if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); } var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48; if (octal && this.strict) { this.raise(start, "Invalid number"); } var next = this.input.charCodeAt(this.pos); if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) { var val$1 = stringToBigInt(this.input.slice(start, this.pos)); ++this.pos; if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); } return this.finishToken(types$1.num, val$1) } if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; } if (next === 46 && !octal) { // '.' ++this.pos; this.readInt(10); next = this.input.charCodeAt(this.pos); } if ((next === 69 || next === 101) && !octal) { // 'eE' next = this.input.charCodeAt(++this.pos); if (next === 43 || next === 45) { ++this.pos; } // '+-' if (this.readInt(10) === null) { this.raise(start, "Invalid number"); } } if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); } var val = stringToNumber(this.input.slice(start, this.pos), octal); return this.finishToken(types$1.num, val) }; // Read a string value, interpreting backslash-escapes. pp.readCodePoint = function() { var ch = this.input.charCodeAt(this.pos), code; if (ch === 123) { // '{' if (this.options.ecmaVersion < 6) { this.unexpected(); } var codePos = ++this.pos; code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos); ++this.pos; if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); } } else { code = this.readHexChar(4); } return code }; pp.readString = function(quote) { var out = "", chunkStart = ++this.pos; for (;;) { if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); } var ch = this.input.charCodeAt(this.pos); if (ch === quote) { break } if (ch === 92) { // '\' out += this.input.slice(chunkStart, this.pos); out += this.readEscapedChar(false); chunkStart = this.pos; } else if (ch === 0x2028 || ch === 0x2029) { if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); } ++this.pos; if (this.options.locations) { this.curLine++; this.lineStart = this.pos; } } else { if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); } ++this.pos; } } out += this.input.slice(chunkStart, this.pos++); return this.finishToken(types$1.string, out) }; // Reads template string tokens. var INVALID_TEMPLATE_ESCAPE_ERROR = {}; pp.tryReadTemplateToken = function() { this.inTemplateElement = true; try { this.readTmplToken(); } catch (err) { if (err === INVALID_TEMPLATE_ESCAPE_ERROR) { this.readInvalidTemplateToken(); } else { throw err } } this.inTemplateElement = false; }; pp.invalidStringToken = function(position, message) { if (this.inTemplateElement && this.options.ecmaVersion >= 9) { throw INVALID_TEMPLATE_ESCAPE_ERROR } else { this.raise(position, message); } }; pp.readTmplToken = function() { var out = "", chunkStart = this.pos; for (;;) { if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); } var ch = this.input.charCodeAt(this.pos); if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${' if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) { if (ch === 36) { this.pos += 2; return this.finishToken(types$1.dollarBraceL) } else { ++this.pos; return this.finishToken(types$1.backQuote) } } out += this.input.slice(chunkStart, this.pos); return this.finishToken(types$1.template, out) } if (ch === 92) { // '\' out += this.input.slice(chunkStart, this.pos); out += this.readEscapedChar(true); chunkStart = this.pos; } else if (isNewLine(ch)) { out += this.input.slice(chunkStart, this.pos); ++this.pos; switch (ch) { case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } case 10: out += "\n"; break default: out += String.fromCharCode(ch); break } if (this.options.locations) { ++this.curLine; this.lineStart = this.pos; } chunkStart = this.pos; } else { ++this.pos; } } }; // Reads a template token to search for the end, without validating any escape sequences pp.readInvalidTemplateToken = function() { for (; this.pos < this.input.length; this.pos++) { switch (this.input[this.pos]) { case "\\": ++this.pos; break case "$": if (this.input[this.pos + 1] !== "{") { break } // falls through case "`": return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos)) // no default } } this.raise(this.start, "Unterminated template"); }; // Used to read escaped characters pp.readEscapedChar = function(inTemplate) { var ch = this.input.charCodeAt(++this.pos); ++this.pos; switch (ch) { case 110: return "\n" // 'n' -> '\n' case 114: return "\r" // 'r' -> '\r' case 120: return String.fromCharCode(this.readHexChar(2)) // 'x' case 117: return codePointToString(this.readCodePoint()) // 'u' case 116: return "\t" // 't' -> '\t' case 98: return "\b" // 'b' -> '\b' case 118: return "\u000b" // 'v' -> '\u000b' case 102: return "\f" // 'f' -> '\f' case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n' case 10: // ' \n' if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; } return "" case 56: case 57: if (this.strict) { this.invalidStringToken( this.pos - 1, "Invalid escape sequence" ); } if (inTemplate) { var codePos = this.pos - 1; this.invalidStringToken( codePos, "Invalid escape sequence in template string" ); return null } default: if (ch >= 48 && ch <= 55) { var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0]; var octal = parseInt(octalStr, 8); if (octal > 255) { octalStr = octalStr.slice(0, -1); octal = parseInt(octalStr, 8); } this.pos += octalStr.length - 1; ch = this.input.charCodeAt(this.pos); if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) { this.invalidStringToken( this.pos - 1 - octalStr.length, inTemplate ? "Octal literal in template string" : "Octal literal in strict mode" ); } return String.fromCharCode(octal) } if (isNewLine(ch)) { // Unicode new line characters after \ get removed from output in both // template literals and strings return "" } return String.fromCharCode(ch) } }; // Used to read character escape sequences ('\x', '\u', '\U'). pp.readHexChar = function(len) { var codePos = this.pos; var n = this.readInt(16, len); if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); } return n }; // Read an identifier, and return it as a string. Sets `this.containsEsc` // to whether the word contained a '\u' escape. // // Incrementally adds only escaped chars, adding other chunks as-is // as a micro-optimization. pp.readWord1 = function() { this.containsEsc = false; var word = "", first = true, chunkStart = this.pos; var astral = this.options.ecmaVersion >= 6; while (this.pos < this.input.length) { var ch = this.fullCharCodeAtPos(); if (isIdentifierChar(ch, astral)) { this.pos += ch <= 0xffff ? 1 : 2; } else if (ch === 92) { // "\" this.containsEsc = true; word += this.input.slice(chunkStart, this.pos); var escStart = this.pos; if (this.input.charCodeAt(++this.pos) !== 117) // "u" { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); } ++this.pos; var esc = this.readCodePoint(); if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) { this.invalidStringToken(escStart, "Invalid Unicode escape"); } word += codePointToString(esc); chunkStart = this.pos; } else { break } first = false; } return word + this.input.slice(chunkStart, this.pos) }; // Read an identifier or keyword token. Will check for reserved // words when necessary. pp.readWord = function() { var word = this.readWord1(); var type = types$1.name; if (this.keywords.test(word)) { type = keywords[word]; } return this.finishToken(type, word) }; // Acorn is a tiny, fast JavaScript parser written in JavaScript. var version = "8.7.1"; Parser.acorn = { Parser: Parser, version: version, defaultOptions: defaultOptions, Position: Position, SourceLocation: SourceLocation, getLineInfo: getLineInfo, Node: Node, TokenType: TokenType, tokTypes: types$1, keywordTypes: keywords, TokContext: TokContext, tokContexts: types, isIdentifierChar: isIdentifierChar, isIdentifierStart: isIdentifierStart, Token: Token, isNewLine: isNewLine, lineBreak: lineBreak, lineBreakG: lineBreakG, nonASCIIwhitespace: nonASCIIwhitespace }; // The main exported interface (under `self.acorn` when in the // browser) is a `parse` function that takes a code string and // returns an abstract syntax tree as specified by [Mozilla parser // API][api]. // // [api]: path_to_url function parse(input, options) { return Parser.parse(input, options) } // This function tries to parse a single expression at a given // offset in a string. Useful for parsing mixed-language formats // that embed JavaScript expressions. function parseExpressionAt(input, pos, options) { return Parser.parseExpressionAt(input, pos, options) } // Acorn is organized as a tokenizer and a recursive-descent parser. // The `tokenizer` export provides an interface to the tokenizer. function tokenizer(input, options) { return Parser.tokenizer(input, options) } exports.Node = Node; exports.Parser = Parser; exports.Position = Position; exports.SourceLocation = SourceLocation; exports.TokContext = TokContext; exports.Token = Token; exports.TokenType = TokenType; exports.defaultOptions = defaultOptions; exports.getLineInfo = getLineInfo; exports.isIdentifierChar = isIdentifierChar; exports.isIdentifierStart = isIdentifierStart; exports.isNewLine = isNewLine; exports.keywordTypes = keywords; exports.lineBreak = lineBreak; exports.lineBreakG = lineBreakG; exports.nonASCIIwhitespace = nonASCIIwhitespace; exports.parse = parse; exports.parseExpressionAt = parseExpressionAt; exports.tokContexts = types; exports.tokTypes = types$1; exports.tokenizer = tokenizer; exports.version = version; Object.defineProperty(exports, '__esModule', { value: true }); })); ```
/content/code_sandbox/node_modules/vm2/node_modules/acorn/dist/acorn.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
60,612
```javascript (function(){var n=this,t=n._,r={},e=Array.prototype,u=Object.prototype,i=Function.prototype,a=e.push,o=e.slice,c=e.concat,l=u.toString,f=u.hasOwnProperty,s=e.forEach,p=e.map,h=e.reduce,v=e.reduceRight,d=e.filter,g=e.every,m=e.some,y=e.indexOf,b=e.lastIndexOf,x=Array.isArray,_=Object.keys,j=i.bind,w=function(n){return n instanceof w?n:this instanceof w?(this._wrapped=n,void 0):new w(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=w),exports._=w):n._=w,w.VERSION="1.4.4";var A=w.each=w.forEach=function(n,t,e){if(null!=n)if(s&&n.forEach===s)n.forEach(t,e);else if(n.length===+n.length){for(var u=0,i=n.length;i>u;u++)if(t.call(e,n[u],u,n)===r)return}else for(var a in n)if(w.has(n,a)&&t.call(e,n[a],a,n)===r)return};w.map=w.collect=function(n,t,r){var e=[];return null==n?e:p&&n.map===p?n.map(t,r):(A(n,function(n,u,i){e[e.length]=t.call(r,n,u,i)}),e)};var O="Reduce of empty array with no initial value";w.reduce=w.foldl=w.inject=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),h&&n.reduce===h)return e&&(t=w.bind(t,e)),u?n.reduce(t,r):n.reduce(t);if(A(n,function(n,i,a){u?r=t.call(e,r,n,i,a):(r=n,u=!0)}),!u)throw new TypeError(O);return r},w.reduceRight=w.foldr=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),v&&n.reduceRight===v)return e&&(t=w.bind(t,e)),u?n.reduceRight(t,r):n.reduceRight(t);var i=n.length;if(i!==+i){var a=w.keys(n);i=a.length}if(A(n,function(o,c,l){c=a?a[--i]:--i,u?r=t.call(e,r,n[c],c,l):(r=n[c],u=!0)}),!u)throw new TypeError(O);return r},w.find=w.detect=function(n,t,r){var e;return E(n,function(n,u,i){return t.call(r,n,u,i)?(e=n,!0):void 0}),e},w.filter=w.select=function(n,t,r){var e=[];return null==n?e:d&&n.filter===d?n.filter(t,r):(A(n,function(n,u,i){t.call(r,n,u,i)&&(e[e.length]=n)}),e)},w.reject=function(n,t,r){return w.filter(n,function(n,e,u){return!t.call(r,n,e,u)},r)},w.every=w.all=function(n,t,e){t||(t=w.identity);var u=!0;return null==n?u:g&&n.every===g?n.every(t,e):(A(n,function(n,i,a){return(u=u&&t.call(e,n,i,a))?void 0:r}),!!u)};var E=w.some=w.any=function(n,t,e){t||(t=w.identity);var u=!1;return null==n?u:m&&n.some===m?n.some(t,e):(A(n,function(n,i,a){return u||(u=t.call(e,n,i,a))?r:void 0}),!!u)};w.contains=w.include=function(n,t){return null==n?!1:y&&n.indexOf===y?n.indexOf(t)!=-1:E(n,function(n){return n===t})},w.invoke=function(n,t){var r=o.call(arguments,2),e=w.isFunction(t);return w.map(n,function(n){return(e?t:n[t]).apply(n,r)})},w.pluck=function(n,t){return w.map(n,function(n){return n[t]})},w.where=function(n,t,r){return w.isEmpty(t)?r?null:[]:w[r?"find":"filter"](n,function(n){for(var r in t)if(t[r]!==n[r])return!1;return!0})},w.findWhere=function(n,t){return w.where(n,t,!0)},w.max=function(n,t,r){if(!t&&w.isArray(n)&&n[0]===+n[0]&&65535>n.length)return Math.max.apply(Math,n);if(!t&&w.isEmpty(n))return-1/0;var e={computed:-1/0,value:-1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;a>=e.computed&&(e={value:n,computed:a})}),e.value},w.min=function(n,t,r){if(!t&&w.isArray(n)&&n[0]===+n[0]&&65535>n.length)return Math.min.apply(Math,n);if(!t&&w.isEmpty(n))return 1/0;var e={computed:1/0,value:1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;e.computed>a&&(e={value:n,computed:a})}),e.value},w.shuffle=function(n){var t,r=0,e=[];return A(n,function(n){t=w.random(r++),e[r-1]=e[t],e[t]=n}),e};var k=function(n){return w.isFunction(n)?n:function(t){return t[n]}};w.sortBy=function(n,t,r){var e=k(t);return w.pluck(w.map(n,function(n,t,u){return{value:n,index:t,criteria:e.call(r,n,t,u)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index<t.index?-1:1}),"value")};var F=function(n,t,r,e){var u={},i=k(t||w.identity);return A(n,function(t,a){var o=i.call(r,t,a,n);e(u,o,t)}),u};w.groupBy=function(n,t,r){return F(n,t,r,function(n,t,r){(w.has(n,t)?n[t]:n[t]=[]).push(r)})},w.countBy=function(n,t,r){return F(n,t,r,function(n,t){w.has(n,t)||(n[t]=0),n[t]++})},w.sortedIndex=function(n,t,r,e){r=null==r?w.identity:k(r);for(var u=r.call(e,t),i=0,a=n.length;a>i;){var o=i+a>>>1;u>r.call(e,n[o])?i=o+1:a=o}return i},w.toArray=function(n){return n?w.isArray(n)?o.call(n):n.length===+n.length?w.map(n,w.identity):w.values(n):[]},w.size=function(n){return null==n?0:n.length===+n.length?n.length:w.keys(n).length},w.first=w.head=w.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:o.call(n,0,t)},w.initial=function(n,t,r){return o.call(n,0,n.length-(null==t||r?1:t))},w.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:o.call(n,Math.max(n.length-t,0))},w.rest=w.tail=w.drop=function(n,t,r){return o.call(n,null==t||r?1:t)},w.compact=function(n){return w.filter(n,w.identity)};var R=function(n,t,r){return A(n,function(n){w.isArray(n)?t?a.apply(r,n):R(n,t,r):r.push(n)}),r};w.flatten=function(n,t){return R(n,t,[])},w.without=function(n){return w.difference(n,o.call(arguments,1))},w.uniq=w.unique=function(n,t,r,e){w.isFunction(t)&&(e=r,r=t,t=!1);var u=r?w.map(n,r,e):n,i=[],a=[];return A(u,function(r,e){(t?e&&a[a.length-1]===r:w.contains(a,r))||(a.push(r),i.push(n[e]))}),i},w.union=function(){return w.uniq(c.apply(e,arguments))},w.intersection=function(n){var t=o.call(arguments,1);return w.filter(w.uniq(n),function(n){return w.every(t,function(t){return w.indexOf(t,n)>=0})})},w.difference=function(n){var t=c.apply(e,o.call(arguments,1));return w.filter(n,function(n){return!w.contains(t,n)})},w.zip=function(){for(var n=o.call(arguments),t=w.max(w.pluck(n,"length")),r=Array(t),e=0;t>e;e++)r[e]=w.pluck(n,""+e);return r},w.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},w.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=w.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}if(y&&n.indexOf===y)return n.indexOf(t,r);for(;u>e;e++)if(n[e]===t)return e;return-1},w.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=null!=r;if(b&&n.lastIndexOf===b)return e?n.lastIndexOf(t,r):n.lastIndexOf(t);for(var u=e?r:n.length;u--;)if(n[u]===t)return u;return-1},w.range=function(n,t,r){1>=arguments.length&&(t=n||0,n=0),r=arguments[2]||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=0,i=Array(e);e>u;)i[u++]=n,n+=r;return i},w.bind=function(n,t){if(n.bind===j&&j)return j.apply(n,o.call(arguments,1));var r=o.call(arguments,2);return function(){return n.apply(t,r.concat(o.call(arguments)))}},w.partial=function(n){var t=o.call(arguments,1);return function(){return n.apply(this,t.concat(o.call(arguments)))}},w.bindAll=function(n){var t=o.call(arguments,1);return 0===t.length&&(t=w.functions(n)),A(t,function(t){n[t]=w.bind(n[t],n)}),n},w.memoize=function(n,t){var r={};return t||(t=w.identity),function(){var e=t.apply(this,arguments);return w.has(r,e)?r[e]:r[e]=n.apply(this,arguments)}},w.delay=function(n,t){var r=o.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},w.defer=function(n){return w.delay.apply(w,[n,1].concat(o.call(arguments,1)))},w.throttle=function(n,t){var r,e,u,i,a=0,o=function(){a=new Date,u=null,i=n.apply(r,e)};return function(){var c=new Date,l=t-(c-a);return r=this,e=arguments,0>=l?(clearTimeout(u),u=null,a=c,i=n.apply(r,e)):u||(u=setTimeout(o,l)),i}},w.debounce=function(n,t,r){var e,u;return function(){var i=this,a=arguments,o=function(){e=null,r||(u=n.apply(i,a))},c=r&&!e;return clearTimeout(e),e=setTimeout(o,t),c&&(u=n.apply(i,a)),u}},w.once=function(n){var t,r=!1;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}},w.wrap=function(n,t){return function(){var r=[n];return a.apply(r,arguments),t.apply(this,r)}},w.compose=function(){var n=arguments;return function(){for(var t=arguments,r=n.length-1;r>=0;r--)t=[n[r].apply(this,t)];return t[0]}},w.after=function(n,t){return 0>=n?t():function(){return 1>--n?t.apply(this,arguments):void 0}},w.keys=_||function(n){if(n!==Object(n))throw new TypeError("Invalid object");var t=[];for(var r in n)w.has(n,r)&&(t[t.length]=r);return t},w.values=function(n){var t=[];for(var r in n)w.has(n,r)&&t.push(n[r]);return t},w.pairs=function(n){var t=[];for(var r in n)w.has(n,r)&&t.push([r,n[r]]);return t},w.invert=function(n){var t={};for(var r in n)w.has(n,r)&&(t[n[r]]=r);return t},w.functions=w.methods=function(n){var t=[];for(var r in n)w.isFunction(n[r])&&t.push(r);return t.sort()},w.extend=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]=t[r]}),n},w.pick=function(n){var t={},r=c.apply(e,o.call(arguments,1));return A(r,function(r){r in n&&(t[r]=n[r])}),t},w.omit=function(n){var t={},r=c.apply(e,o.call(arguments,1));for(var u in n)w.contains(r,u)||(t[u]=n[u]);return t},w.defaults=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)null==n[r]&&(n[r]=t[r])}),n},w.clone=function(n){return w.isObject(n)?w.isArray(n)?n.slice():w.extend({},n):n},w.tap=function(n,t){return t(n),n};var I=function(n,t,r,e){if(n===t)return 0!==n||1/n==1/t;if(null==n||null==t)return n===t;n instanceof w&&(n=n._wrapped),t instanceof w&&(t=t._wrapped);var u=l.call(n);if(u!=l.call(t))return!1;switch(u){case"[object String]":return n==t+"";case"[object Number]":return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case"[object Date]":case"[object Boolean]":return+n==+t;case"[object RegExp]":return n.source==t.source&&n.global==t.global&&n.multiline==t.multiline&&n.ignoreCase==t.ignoreCase}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]==n)return e[i]==t;r.push(n),e.push(t);var a=0,o=!0;if("[object Array]"==u){if(a=n.length,o=a==t.length)for(;a--&&(o=I(n[a],t[a],r,e)););}else{var c=n.constructor,f=t.constructor;if(c!==f&&!(w.isFunction(c)&&c instanceof c&&w.isFunction(f)&&f instanceof f))return!1;for(var s in n)if(w.has(n,s)&&(a++,!(o=w.has(t,s)&&I(n[s],t[s],r,e))))break;if(o){for(s in t)if(w.has(t,s)&&!a--)break;o=!a}}return r.pop(),e.pop(),o};w.isEqual=function(n,t){return I(n,t,[],[])},w.isEmpty=function(n){if(null==n)return!0;if(w.isArray(n)||w.isString(n))return 0===n.length;for(var t in n)if(w.has(n,t))return!1;return!0},w.isElement=function(n){return!(!n||1!==n.nodeType)},w.isArray=x||function(n){return"[object Array]"==l.call(n)},w.isObject=function(n){return n===Object(n)},A(["Arguments","Function","String","Number","Date","RegExp"],function(n){w["is"+n]=function(t){return l.call(t)=="[object "+n+"]"}}),w.isArguments(arguments)||(w.isArguments=function(n){return!(!n||!w.has(n,"callee"))}),"function"!=typeof/./&&(w.isFunction=function(n){return"function"==typeof n}),w.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},w.isNaN=function(n){return w.isNumber(n)&&n!=+n},w.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"==l.call(n)},w.isNull=function(n){return null===n},w.isUndefined=function(n){return n===void 0},w.has=function(n,t){return f.call(n,t)},w.noConflict=function(){return n._=t,this},w.identity=function(n){return n},w.times=function(n,t,r){for(var e=Array(n),u=0;n>u;u++)e[u]=t.call(r,u);return e},w.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))};var M={escape:{"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"}};M.unescape=w.invert(M.escape);var S={escape:RegExp("["+w.keys(M.escape).join("")+"]","g"),unescape:RegExp("("+w.keys(M.unescape).join("|")+")","g")};w.each(["escape","unescape"],function(n){w[n]=function(t){return null==t?"":(""+t).replace(S[n],function(t){return M[n][t]})}}),w.result=function(n,t){if(null==n)return null;var r=n[t];return w.isFunction(r)?r.call(n):r},w.mixin=function(n){A(w.functions(n),function(t){var r=w[t]=n[t];w.prototype[t]=function(){var n=[this._wrapped];return a.apply(n,arguments),D.call(this,r.apply(w,n))}})};var N=0;w.uniqueId=function(n){var t=++N+"";return n?n+t:t},w.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var T=/(.)^/,q={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"},B=/\\|'|\r|\n|\t|\u2028|\u2029/g;w.template=function(n,t,r){var e;r=w.defaults({},r,w.templateSettings);var u=RegExp([(r.escape||T).source,(r.interpolate||T).source,(r.evaluate||T).source].join("|")+"|$","g"),i=0,a="__p+='";n.replace(u,function(t,r,e,u,o){return a+=n.slice(i,o).replace(B,function(n){return"\\"+q[n]}),r&&(a+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'"),e&&(a+="'+\n((__t=("+e+"))==null?'':__t)+\n'"),u&&(a+="';\n"+u+"\n__p+='"),i=o+t.length,t}),a+="';\n",r.variable||(a="with(obj||{}){\n"+a+"}\n"),a="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+a+"return __p;\n";try{e=Function(r.variable||"obj","_",a)}catch(o){throw o.source=a,o}if(t)return e(t,w);var c=function(n){return e.call(this,n,w)};return c.source="function("+(r.variable||"obj")+"){\n"+a+"}",c},w.chain=function(n){return w(n).chain()};var D=function(n){return this._chain?w(n).chain():n};w.mixin(w),A(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=e[n];w.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!=n&&"splice"!=n||0!==r.length||delete r[0],D.call(this,r)}}),A(["concat","join","slice"],function(n){var t=e[n];w.prototype[n]=function(){return D.call(this,t.apply(this._wrapped,arguments))}}),w.extend(w.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}})}).call(this); ```
/content/code_sandbox/node_modules/underscore/underscore-min.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
4,601
```javascript var Writable = require('readable-stream').Writable var inherits = require('inherits') var bufferFrom = require('buffer-from') if (typeof Uint8Array === 'undefined') { var U8 = require('typedarray').Uint8Array } else { var U8 = Uint8Array } function ConcatStream(opts, cb) { if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb) if (typeof opts === 'function') { cb = opts opts = {} } if (!opts) opts = {} var encoding = opts.encoding var shouldInferEncoding = false if (!encoding) { shouldInferEncoding = true } else { encoding = String(encoding).toLowerCase() if (encoding === 'u8' || encoding === 'uint8') { encoding = 'uint8array' } } Writable.call(this, { objectMode: true }) this.encoding = encoding this.shouldInferEncoding = shouldInferEncoding if (cb) this.on('finish', function () { cb(this.getBody()) }) this.body = [] } module.exports = ConcatStream inherits(ConcatStream, Writable) ConcatStream.prototype._write = function(chunk, enc, next) { this.body.push(chunk) next() } ConcatStream.prototype.inferEncoding = function (buff) { var firstBuffer = buff === undefined ? this.body[0] : buff; if (Buffer.isBuffer(firstBuffer)) return 'buffer' if (typeof Uint8Array !== 'undefined' && firstBuffer instanceof Uint8Array) return 'uint8array' if (Array.isArray(firstBuffer)) return 'array' if (typeof firstBuffer === 'string') return 'string' if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return 'object' return 'buffer' } ConcatStream.prototype.getBody = function () { if (!this.encoding && this.body.length === 0) return [] if (this.shouldInferEncoding) this.encoding = this.inferEncoding() if (this.encoding === 'array') return arrayConcat(this.body) if (this.encoding === 'string') return stringConcat(this.body) if (this.encoding === 'buffer') return bufferConcat(this.body) if (this.encoding === 'uint8array') return u8Concat(this.body) return this.body } var isArray = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]' } function isArrayish (arr) { return /Array\]$/.test(Object.prototype.toString.call(arr)) } function isBufferish (p) { return typeof p === 'string' || isArrayish(p) || (p && typeof p.subarray === 'function') } function stringConcat (parts) { var strings = [] var needsToString = false for (var i = 0; i < parts.length; i++) { var p = parts[i] if (typeof p === 'string') { strings.push(p) } else if (Buffer.isBuffer(p)) { strings.push(p) } else if (isBufferish(p)) { strings.push(bufferFrom(p)) } else { strings.push(bufferFrom(String(p))) } } if (Buffer.isBuffer(parts[0])) { strings = Buffer.concat(strings) strings = strings.toString('utf8') } else { strings = strings.join('') } return strings } function bufferConcat (parts) { var bufs = [] for (var i = 0; i < parts.length; i++) { var p = parts[i] if (Buffer.isBuffer(p)) { bufs.push(p) } else if (isBufferish(p)) { bufs.push(bufferFrom(p)) } else { bufs.push(bufferFrom(String(p))) } } return Buffer.concat(bufs) } function arrayConcat (parts) { var res = [] for (var i = 0; i < parts.length; i++) { res.push.apply(res, parts[i]) } return res } function u8Concat (parts) { var len = 0 for (var i = 0; i < parts.length; i++) { if (typeof parts[i] === 'string') { parts[i] = bufferFrom(parts[i]) } len += parts[i].length } var u8 = new U8(len) for (var i = 0, offset = 0; i < parts.length; i++) { var part = parts[i] for (var j = 0; j < part.length; j++) { u8[offset++] = part[j] } } return u8 } ```
/content/code_sandbox/node_modules/concat-stream/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,026
```javascript var assert = require('tap'); var t = require('./lib/util'); assert.equal(t.isArray([]), true); assert.equal(t.isArray({}), false); assert.equal(t.isBoolean(null), false); assert.equal(t.isBoolean(true), true); assert.equal(t.isBoolean(false), true); assert.equal(t.isNull(null), true); assert.equal(t.isNull(undefined), false); assert.equal(t.isNull(false), false); assert.equal(t.isNull(), false); assert.equal(t.isNullOrUndefined(null), true); assert.equal(t.isNullOrUndefined(undefined), true); assert.equal(t.isNullOrUndefined(false), false); assert.equal(t.isNullOrUndefined(), true); assert.equal(t.isNumber(null), false); assert.equal(t.isNumber('1'), false); assert.equal(t.isNumber(1), true); assert.equal(t.isString(null), false); assert.equal(t.isString('1'), true); assert.equal(t.isString(1), false); assert.equal(t.isSymbol(null), false); assert.equal(t.isSymbol('1'), false); assert.equal(t.isSymbol(1), false); assert.equal(t.isSymbol(Symbol()), true); assert.equal(t.isUndefined(null), false); assert.equal(t.isUndefined(undefined), true); assert.equal(t.isUndefined(false), false); assert.equal(t.isUndefined(), true); assert.equal(t.isRegExp(null), false); assert.equal(t.isRegExp('1'), false); assert.equal(t.isRegExp(new RegExp()), true); assert.equal(t.isObject({}), true); assert.equal(t.isObject([]), true); assert.equal(t.isObject(new RegExp()), true); assert.equal(t.isObject(new Date()), true); assert.equal(t.isDate(null), false); assert.equal(t.isDate('1'), false); assert.equal(t.isDate(new Date()), true); assert.equal(t.isError(null), false); assert.equal(t.isError({ err: true }), false); assert.equal(t.isError(new Error()), true); assert.equal(t.isFunction(null), false); assert.equal(t.isFunction({ }), false); assert.equal(t.isFunction(function() {}), true); assert.equal(t.isPrimitive(null), true); assert.equal(t.isPrimitive(''), true); assert.equal(t.isPrimitive(0), true); assert.equal(t.isPrimitive(new Date()), false); assert.equal(t.isBuffer(null), false); assert.equal(t.isBuffer({}), false); assert.equal(t.isBuffer(new Buffer(0)), true); ```
/content/code_sandbox/node_modules/core-util-is/test.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
484
```javascript // // 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. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } ```
/content/code_sandbox/node_modules/core-util-is/lib/util.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
660
```javascript 'use strict' module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount /*, ...nodes */) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 2; i < arguments.length; i++) { walker = insert(this, walker, arguments[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present require('./iterator.js')(Yallist) } catch (er) {} ```
/content/code_sandbox/node_modules/yallist/yallist.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,526
```javascript var IncomingForm = require('./incoming_form').IncomingForm; IncomingForm.IncomingForm = IncomingForm; module.exports = IncomingForm; ```
/content/code_sandbox/node_modules/formidable/lib/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
28
```javascript var Buffer = require('buffer').Buffer, s = 0, S = { PARSER_UNINITIALIZED: s++, START: s++, START_BOUNDARY: s++, HEADER_FIELD_START: s++, HEADER_FIELD: s++, HEADER_VALUE_START: s++, HEADER_VALUE: s++, HEADER_VALUE_ALMOST_DONE: s++, HEADERS_ALMOST_DONE: s++, PART_DATA_START: s++, PART_DATA: s++, PART_END: s++, END: s++ }, f = 1, F = { PART_BOUNDARY: f, LAST_BOUNDARY: f *= 2 }, LF = 10, CR = 13, SPACE = 32, HYPHEN = 45, COLON = 58, A = 97, Z = 122, lower = function(c) { return c | 0x20; }; for (s in S) { exports[s] = S[s]; } function MultipartParser() { this.boundary = null; this.boundaryChars = null; this.lookbehind = null; this.state = S.PARSER_UNINITIALIZED; this.index = null; this.flags = 0; } exports.MultipartParser = MultipartParser; MultipartParser.stateToString = function(stateNumber) { for (var state in S) { var number = S[state]; if (number === stateNumber) return state; } }; MultipartParser.prototype.initWithBoundary = function(str) { this.boundary = new Buffer(str.length+4); this.boundary.write('\r\n--', 0); this.boundary.write(str, 4); this.lookbehind = new Buffer(this.boundary.length+8); this.state = S.START; this.boundaryChars = {}; for (var i = 0; i < this.boundary.length; i++) { this.boundaryChars[this.boundary[i]] = true; } }; MultipartParser.prototype.write = function(buffer) { var self = this, i = 0, len = buffer.length, prevIndex = this.index, index = this.index, state = this.state, flags = this.flags, lookbehind = this.lookbehind, boundary = this.boundary, boundaryChars = this.boundaryChars, boundaryLength = this.boundary.length, boundaryEnd = boundaryLength - 1, bufferLength = buffer.length, c, cl, mark = function(name) { self[name+'Mark'] = i; }, clear = function(name) { delete self[name+'Mark']; }, callback = function(name, buffer, start, end) { if (start !== undefined && start === end) { return; } var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); if (callbackSymbol in self) { self[callbackSymbol](buffer, start, end); } }, dataCallback = function(name, clear) { var markSymbol = name+'Mark'; if (!(markSymbol in self)) { return; } if (!clear) { callback(name, buffer, self[markSymbol], buffer.length); self[markSymbol] = 0; } else { callback(name, buffer, self[markSymbol], i); delete self[markSymbol]; } }; for (i = 0; i < len; i++) { c = buffer[i]; switch (state) { case S.PARSER_UNINITIALIZED: return i; case S.START: index = 0; state = S.START_BOUNDARY; case S.START_BOUNDARY: if (index == boundary.length - 2) { if (c == HYPHEN) { flags |= F.LAST_BOUNDARY; } else if (c != CR) { return i; } index++; break; } else if (index - 1 == boundary.length - 2) { if (flags & F.LAST_BOUNDARY && c == HYPHEN){ callback('end'); state = S.END; flags = 0; } else if (!(flags & F.LAST_BOUNDARY) && c == LF) { index = 0; callback('partBegin'); state = S.HEADER_FIELD_START; } else { return i; } break; } if (c != boundary[index+2]) { index = -2; } if (c == boundary[index+2]) { index++; } break; case S.HEADER_FIELD_START: state = S.HEADER_FIELD; mark('headerField'); index = 0; case S.HEADER_FIELD: if (c == CR) { clear('headerField'); state = S.HEADERS_ALMOST_DONE; break; } index++; if (c == HYPHEN) { break; } if (c == COLON) { if (index == 1) { // empty header field return i; } dataCallback('headerField', true); state = S.HEADER_VALUE_START; break; } cl = lower(c); if (cl < A || cl > Z) { return i; } break; case S.HEADER_VALUE_START: if (c == SPACE) { break; } mark('headerValue'); state = S.HEADER_VALUE; case S.HEADER_VALUE: if (c == CR) { dataCallback('headerValue', true); callback('headerEnd'); state = S.HEADER_VALUE_ALMOST_DONE; } break; case S.HEADER_VALUE_ALMOST_DONE: if (c != LF) { return i; } state = S.HEADER_FIELD_START; break; case S.HEADERS_ALMOST_DONE: if (c != LF) { return i; } callback('headersEnd'); state = S.PART_DATA_START; break; case S.PART_DATA_START: state = S.PART_DATA; mark('partData'); case S.PART_DATA: prevIndex = index; if (index === 0) { // boyer-moore derrived algorithm to safely skip non-boundary data i += boundaryEnd; while (i < bufferLength && !(buffer[i] in boundaryChars)) { i += boundaryLength; } i -= boundaryEnd; c = buffer[i]; } if (index < boundary.length) { if (boundary[index] == c) { if (index === 0) { dataCallback('partData', true); } index++; } else { index = 0; } } else if (index == boundary.length) { index++; if (c == CR) { // CR = part boundary flags |= F.PART_BOUNDARY; } else if (c == HYPHEN) { // HYPHEN = end boundary flags |= F.LAST_BOUNDARY; } else { index = 0; } } else if (index - 1 == boundary.length) { if (flags & F.PART_BOUNDARY) { index = 0; if (c == LF) { // unset the PART_BOUNDARY flag flags &= ~F.PART_BOUNDARY; callback('partEnd'); callback('partBegin'); state = S.HEADER_FIELD_START; break; } } else if (flags & F.LAST_BOUNDARY) { if (c == HYPHEN) { callback('partEnd'); callback('end'); state = S.END; flags = 0; } else { index = 0; } } else { index = 0; } } if (index > 0) { // when matching a possible boundary, keep a lookbehind reference // in case it turns out to be a false lead lookbehind[index-1] = c; } else if (prevIndex > 0) { // if our boundary turned out to be rubbish, the captured lookbehind // belongs to partData callback('partData', lookbehind, 0, prevIndex); prevIndex = 0; mark('partData'); // reconsider the current character even so it interrupted the sequence // it could be the beginning of a new sequence i--; } break; case S.END: break; default: return i; } } dataCallback('headerField'); dataCallback('headerValue'); dataCallback('partData'); this.index = index; this.state = state; this.flags = flags; return len; }; MultipartParser.prototype.end = function() { var callback = function(self, name) { var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); if (callbackSymbol in self) { self[callbackSymbol](); } }; if ((this.state == S.HEADER_FIELD_START && this.index === 0) || (this.state == S.PART_DATA && this.index == this.boundary.length)) { callback(this, 'partEnd'); callback(this, 'end'); } else if (this.state != S.END) { return new Error('MultipartParser.end(): stream ended unexpectedly: ' + this.explain()); } }; MultipartParser.prototype.explain = function() { return 'state = ' + MultipartParser.stateToString(this.state); }; ```
/content/code_sandbox/node_modules/formidable/lib/multipart_parser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,131
```javascript if (global.GENTLY) require = GENTLY.hijack(require); var Buffer = require('buffer').Buffer; function JSONParser(parent) { this.parent = parent; this.chunks = []; this.bytesWritten = 0; } exports.JSONParser = JSONParser; JSONParser.prototype.write = function(buffer) { this.bytesWritten += buffer.length; this.chunks.push(buffer); return buffer.length; }; JSONParser.prototype.end = function() { try { var fields = JSON.parse(Buffer.concat(this.chunks)); for (var field in fields) { this.onField(field, fields[field]); } } catch (e) { this.parent.emit('error', e); } this.data = null; this.onEnd(); }; ```
/content/code_sandbox/node_modules/formidable/lib/json_parser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
164
```javascript var EventEmitter = require('events').EventEmitter , util = require('util'); function OctetParser(options){ if(!(this instanceof OctetParser)) return new OctetParser(options); EventEmitter.call(this); } util.inherits(OctetParser, EventEmitter); exports.OctetParser = OctetParser; OctetParser.prototype.write = function(buffer) { this.emit('data', buffer); return buffer.length; }; OctetParser.prototype.end = function() { this.emit('end'); }; ```
/content/code_sandbox/node_modules/formidable/lib/octet_parser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
104
```javascript if (global.GENTLY) require = GENTLY.hijack(require); var util = require('util'), fs = require('fs'), EventEmitter = require('events').EventEmitter, crypto = require('crypto'); function File(properties) { EventEmitter.call(this); this.size = 0; this.path = null; this.name = null; this.type = null; this.hash = null; this.lastModifiedDate = null; this._writeStream = null; for (var key in properties) { this[key] = properties[key]; } if(typeof this.hash === 'string') { this.hash = crypto.createHash(properties.hash); } else { this.hash = null; } } module.exports = File; util.inherits(File, EventEmitter); File.prototype.open = function() { this._writeStream = new fs.WriteStream(this.path); }; File.prototype.toJSON = function() { var json = { size: this.size, path: this.path, name: this.name, type: this.type, mtime: this.lastModifiedDate, length: this.length, filename: this.filename, mime: this.mime }; if (this.hash && this.hash != "") { json.hash = this.hash; } return json; }; File.prototype.write = function(buffer, cb) { var self = this; if (self.hash) { self.hash.update(buffer); } if (this._writeStream.closed) { return cb(); } this._writeStream.write(buffer, function() { self.lastModifiedDate = new Date(); self.size += buffer.length; self.emit('progress', self.size); cb(); }); }; File.prototype.end = function(cb) { var self = this; if (self.hash) { self.hash = self.hash.digest('hex'); } this._writeStream.end(function() { self.emit('end'); cb(); }); }; ```
/content/code_sandbox/node_modules/formidable/lib/file.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
422
```javascript if (global.GENTLY) require = GENTLY.hijack(require); var crypto = require('crypto'); var fs = require('fs'); var util = require('util'), path = require('path'), File = require('./file'), MultipartParser = require('./multipart_parser').MultipartParser, QuerystringParser = require('./querystring_parser').QuerystringParser, OctetParser = require('./octet_parser').OctetParser, JSONParser = require('./json_parser').JSONParser, StringDecoder = require('string_decoder').StringDecoder, EventEmitter = require('events').EventEmitter, Stream = require('stream').Stream, os = require('os'); function IncomingForm(opts) { if (!(this instanceof IncomingForm)) return new IncomingForm(opts); EventEmitter.call(this); opts=opts||{}; this.error = null; this.ended = false; this.maxFields = opts.maxFields || 1000; this.maxFieldsSize = opts.maxFieldsSize || 20 * 1024 * 1024; this.maxFileSize = opts.maxFileSize || 200 * 1024 * 1024; this.keepExtensions = opts.keepExtensions || false; this.uploadDir = opts.uploadDir || (os.tmpdir && os.tmpdir()) || os.tmpDir(); this.encoding = opts.encoding || 'utf-8'; this.headers = null; this.type = null; this.hash = opts.hash || false; this.multiples = opts.multiples || false; this.bytesReceived = null; this.bytesExpected = null; this._parser = null; this._flushing = 0; this._fieldsSize = 0; this._fileSize = 0; this.openedFiles = []; return this; } util.inherits(IncomingForm, EventEmitter); exports.IncomingForm = IncomingForm; IncomingForm.prototype.parse = function(req, cb) { this.pause = function() { try { req.pause(); } catch (err) { // the stream was destroyed if (!this.ended) { // before it was completed, crash & burn this._error(err); } return false; } return true; }; this.resume = function() { try { req.resume(); } catch (err) { // the stream was destroyed if (!this.ended) { // before it was completed, crash & burn this._error(err); } return false; } return true; }; // Setup callback first, so we don't miss anything from data events emitted // immediately. if (cb) { var fields = {}, files = {}; this .on('field', function(name, value) { fields[name] = value; }) .on('file', function(name, file) { if (this.multiples) { if (files[name]) { if (!Array.isArray(files[name])) { files[name] = [files[name]]; } files[name].push(file); } else { files[name] = file; } } else { files[name] = file; } }) .on('error', function(err) { cb(err, fields, files); }) .on('end', function() { cb(null, fields, files); }); } // Parse headers and setup the parser, ready to start listening for data. this.writeHeaders(req.headers); // Start listening for data. var self = this; req .on('error', function(err) { self._error(err); }) .on('aborted', function() { self.emit('aborted'); self._error(new Error('Request aborted')); }) .on('data', function(buffer) { self.write(buffer); }) .on('end', function() { if (self.error) { return; } var err = self._parser.end(); if (err) { self._error(err); } }); return this; }; IncomingForm.prototype.writeHeaders = function(headers) { this.headers = headers; this._parseContentLength(); this._parseContentType(); }; IncomingForm.prototype.write = function(buffer) { if (this.error) { return; } if (!this._parser) { this._error(new Error('uninitialized parser')); return; } if (typeof this._parser.write !== 'function') { this._error(new Error('did not expect data')); return; } this.bytesReceived += buffer.length; this.emit('progress', this.bytesReceived, this.bytesExpected); var bytesParsed = this._parser.write(buffer); if (bytesParsed !== buffer.length) { this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed')); } return bytesParsed; }; IncomingForm.prototype.pause = function() { // this does nothing, unless overwritten in IncomingForm.parse return false; }; IncomingForm.prototype.resume = function() { // this does nothing, unless overwritten in IncomingForm.parse return false; }; IncomingForm.prototype.onPart = function(part) { // this method can be overwritten by the user this.handlePart(part); }; IncomingForm.prototype.handlePart = function(part) { var self = this; // This MUST check exactly for undefined. You can not change it to !part.filename. if (part.filename === undefined) { var value = '' , decoder = new StringDecoder(this.encoding); part.on('data', function(buffer) { self._fieldsSize += buffer.length; if (self._fieldsSize > self.maxFieldsSize) { self._error(new Error('maxFieldsSize exceeded, received '+self._fieldsSize+' bytes of field data')); return; } value += decoder.write(buffer); }); part.on('end', function() { self.emit('field', part.name, value); }); return; } this._flushing++; var file = new File({ path: this._uploadPath(part.filename), name: part.filename, type: part.mime, hash: self.hash }); this.emit('fileBegin', part.name, file); file.open(); this.openedFiles.push(file); part.on('data', function(buffer) { self._fileSize += buffer.length; if (self._fileSize > self.maxFileSize) { self._error(new Error('maxFileSize exceeded, received '+self._fileSize+' bytes of file data')); return; } if (buffer.length == 0) { return; } self.pause(); file.write(buffer, function() { self.resume(); }); }); part.on('end', function() { file.end(function() { self._flushing--; self.emit('file', part.name, file); self._maybeEnd(); }); }); }; function dummyParser(self) { return { end: function () { self.ended = true; self._maybeEnd(); return null; } }; } IncomingForm.prototype._parseContentType = function() { if (this.bytesExpected === 0) { this._parser = dummyParser(this); return; } if (!this.headers['content-type']) { this._error(new Error('bad content-type header, no content-type')); return; } if (this.headers['content-type'].match(/octet-stream/i)) { this._initOctetStream(); return; } if (this.headers['content-type'].match(/urlencoded/i)) { this._initUrlencoded(); return; } if (this.headers['content-type'].match(/multipart/i)) { var m = this.headers['content-type'].match(/boundary=(?:"([^"]+)"|([^;]+))/i); if (m) { this._initMultipart(m[1] || m[2]); } else { this._error(new Error('bad content-type header, no multipart boundary')); } return; } if (this.headers['content-type'].match(/json/i)) { this._initJSONencoded(); return; } this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type'])); }; IncomingForm.prototype._error = function(err) { if (this.error || this.ended) { return; } this.error = err; this.emit('error', err); if (Array.isArray(this.openedFiles)) { this.openedFiles.forEach(function(file) { file._writeStream .on('error', function() {}) .destroy(); setTimeout(fs.unlink, 0, file.path, function(error) { }); }); } }; IncomingForm.prototype._parseContentLength = function() { this.bytesReceived = 0; if (this.headers['content-length']) { this.bytesExpected = parseInt(this.headers['content-length'], 10); } else if (this.headers['transfer-encoding'] === undefined) { this.bytesExpected = 0; } if (this.bytesExpected !== null) { this.emit('progress', this.bytesReceived, this.bytesExpected); } }; IncomingForm.prototype._newParser = function() { return new MultipartParser(); }; IncomingForm.prototype._initMultipart = function(boundary) { this.type = 'multipart'; var parser = new MultipartParser(), self = this, headerField, headerValue, part; parser.initWithBoundary(boundary); parser.onPartBegin = function() { part = new Stream(); part.readable = true; part.headers = {}; part.name = null; part.filename = null; part.mime = null; part.transferEncoding = 'binary'; part.transferBuffer = ''; headerField = ''; headerValue = ''; }; parser.onHeaderField = function(b, start, end) { headerField += b.toString(self.encoding, start, end); }; parser.onHeaderValue = function(b, start, end) { headerValue += b.toString(self.encoding, start, end); }; parser.onHeaderEnd = function() { headerField = headerField.toLowerCase(); part.headers[headerField] = headerValue; // matches either a quoted-string or a token (RFC 2616 section 19.5.1) var m = headerValue.match(/\bname=("([^"]*)"|([^\(\)<>@,;:\\"\/\[\]\?=\{\}\s\t/]+))/i); if (headerField == 'content-disposition') { if (m) { part.name = m[2] || m[3] || ''; } part.filename = self._fileName(headerValue); } else if (headerField == 'content-type') { part.mime = headerValue; } else if (headerField == 'content-transfer-encoding') { part.transferEncoding = headerValue.toLowerCase(); } headerField = ''; headerValue = ''; }; parser.onHeadersEnd = function() { switch(part.transferEncoding){ case 'binary': case '7bit': case '8bit': parser.onPartData = function(b, start, end) { part.emit('data', b.slice(start, end)); }; parser.onPartEnd = function() { part.emit('end'); }; break; case 'base64': parser.onPartData = function(b, start, end) { part.transferBuffer += b.slice(start, end).toString('ascii'); /* four bytes (chars) in base64 converts to three bytes in binary encoding. So we should always work with a number of bytes that can be divided by 4, it will result in a number of buytes that can be divided vy 3. */ var offset = parseInt(part.transferBuffer.length / 4, 10) * 4; part.emit('data', new Buffer(part.transferBuffer.substring(0, offset), 'base64')); part.transferBuffer = part.transferBuffer.substring(offset); }; parser.onPartEnd = function() { part.emit('data', new Buffer(part.transferBuffer, 'base64')); part.emit('end'); }; break; default: return self._error(new Error('unknown transfer-encoding')); } self.onPart(part); }; parser.onEnd = function() { self.ended = true; self._maybeEnd(); }; this._parser = parser; }; IncomingForm.prototype._fileName = function(headerValue) { // matches either a quoted-string or a token (RFC 2616 section 19.5.1) var m = headerValue.match(/\bfilename=("(.*?)"|([^\(\)<>@,;:\\"\/\[\]\?=\{\}\s\t/]+))($|;\s)/i); if (!m) return; var match = m[2] || m[3] || ''; var filename = match.substr(match.lastIndexOf('\\') + 1); filename = filename.replace(/%22/g, '"'); filename = filename.replace(/&#([\d]{4});/g, function(m, code) { return String.fromCharCode(code); }); return filename; }; IncomingForm.prototype._initUrlencoded = function() { this.type = 'urlencoded'; var parser = new QuerystringParser(this.maxFields) , self = this; parser.onField = function(key, val) { self.emit('field', key, val); }; parser.onEnd = function() { self.ended = true; self._maybeEnd(); }; this._parser = parser; }; IncomingForm.prototype._initOctetStream = function() { this.type = 'octet-stream'; var filename = this.headers['x-file-name']; var mime = this.headers['content-type']; var file = new File({ path: this._uploadPath(filename), name: filename, type: mime }); this.emit('fileBegin', filename, file); file.open(); this.openedFiles.push(file); this._flushing++; var self = this; self._parser = new OctetParser(); //Keep track of writes that haven't finished so we don't emit the file before it's done being written var outstandingWrites = 0; self._parser.on('data', function(buffer){ self.pause(); outstandingWrites++; file.write(buffer, function() { outstandingWrites--; self.resume(); if(self.ended){ self._parser.emit('doneWritingFile'); } }); }); self._parser.on('end', function(){ self._flushing--; self.ended = true; var done = function(){ file.end(function() { self.emit('file', 'file', file); self._maybeEnd(); }); }; if(outstandingWrites === 0){ done(); } else { self._parser.once('doneWritingFile', done); } }); }; IncomingForm.prototype._initJSONencoded = function() { this.type = 'json'; var parser = new JSONParser(this) , self = this; parser.onField = function(key, val) { self.emit('field', key, val); }; parser.onEnd = function() { self.ended = true; self._maybeEnd(); }; this._parser = parser; }; IncomingForm.prototype._uploadPath = function(filename) { var buf = crypto.randomBytes(16); var name = 'upload_' + buf.toString('hex'); if (this.keepExtensions) { var ext = path.extname(filename); ext = ext.replace(/(\.[a-z0-9]+).*/i, '$1'); name += ext; } return path.join(this.uploadDir, name); }; IncomingForm.prototype._maybeEnd = function() { if (!this.ended || this._flushing || this.error) { return; } this.emit('end'); }; ```
/content/code_sandbox/node_modules/formidable/lib/incoming_form.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,486
```javascript if (global.GENTLY) require = GENTLY.hijack(require); // This is a buffering parser, not quite as nice as the multipart one. // If I find time I'll rewrite this to be fully streaming as well var querystring = require('querystring'); function QuerystringParser(maxKeys) { this.maxKeys = maxKeys; this.buffer = ''; } exports.QuerystringParser = QuerystringParser; QuerystringParser.prototype.write = function(buffer) { this.buffer += buffer.toString('ascii'); return buffer.length; }; QuerystringParser.prototype.end = function() { var fields = querystring.parse(this.buffer, '&', '=', { maxKeys: this.maxKeys }); for (var field in fields) { this.onField(field, fields[field]); } this.buffer = ''; this.onEnd(); }; ```
/content/code_sandbox/node_modules/formidable/lib/querystring_parser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
176
```html <!DOCTYPE HTML> <html> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <meta http-equiv="X-UA-Compatible" content="chrome=1" /> <meta name="viewport" content="width=device-width" /> <link rel="canonical" href="path_to_url" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> <title>Underscore.js</title> <style> body { font-size: 14px; line-height: 22px; background: #f4f4f4 url(docs/images/background.png); color: #000; font-family: Helvetica Neue, Helvetica, Arial; } .interface { font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important; } div#sidebar { background: #fff; position: fixed; top: 0; left: 0; bottom: 0; width: 200px; overflow-y: auto; overflow-x: hidden; -webkit-overflow-scrolling: touch; padding: 15px 0 30px 30px; border-right: 1px solid #bbb; box-shadow: 0 0 20px #ccc; -webkit-box-shadow: 0 0 20px #ccc; -moz-box-shadow: 0 0 20px #ccc; } a.toc_title, a.toc_title:visited { display: block; color: black; font-weight: bold; margin-top: 15px; } a.toc_title:hover { text-decoration: underline; } #sidebar .version { font-size: 10px; font-weight: normal; } ul.toc_section { font-size: 11px; line-height: 14px; margin: 5px 0 0 0; padding-left: 0px; list-style-type: none; font-family: Lucida Grande; } .toc_section li { cursor: pointer; margin: 0 0 3px 0; } .toc_section li a { text-decoration: none; color: black; } .toc_section li a:hover { text-decoration: underline; } div.container { width: 550px; margin: 40px 0 50px 260px; } img#logo { width: 396px; height: 69px; } div.warning { margin-top: 15px; font: bold 11px Arial; color: #770000; } p { margin: 20px 0; width: 550px; } a, a:visited { color: #444; } a:active, a:hover { color: #000; } h1, h2, h3, h4, h5, h6 { padding-top: 20px; } h2 { font-size: 20px; } b.header { font-size: 16px; line-height: 30px; } span.alias { font-size: 14px; font-style: italic; margin-left: 20px; } table, tr, td { margin: 0; padding: 0; } td { padding: 2px 12px 2px 0; } table .rule { height: 1px; background: #ccc; margin: 5px 0; } ul { list-style-type: circle; padding: 0 0 0 20px; } li { width: 500px; margin-bottom: 10px; } code, pre, tt { font-family: Monaco, Consolas, "Lucida Console", monospace; font-size: 12px; line-height: 18px; font-style: normal; } tt { padding: 0px 3px; background: #fff; border: 1px solid #ddd; zoom: 1; } code { margin-left: 20px; } pre { font-size: 12px; padding: 2px 0 2px 15px; border-left: 5px solid #bbb; margin: 0px 0 30px; } @media only screen and (-webkit-min-device-pixel-ratio: 1.5) and (max-width: 640px), only screen and (-o-min-device-pixel-ratio: 3/2) and (max-width: 640px), only screen and (min-device-pixel-ratio: 1.5) and (max-width: 640px) { img { max-width: 100%; } div#sidebar { -webkit-overflow-scrolling: initial; position: relative; width: 90%; height: 120px; left: 0; top: -7px; padding: 10px 0 10px 30px; border: 0; } img#logo { width: auto; height: auto; } div.container { margin: 0; width: 100%; } p, div.container ul { max-width: 98%; overflow-x: scroll; } pre { overflow: scroll; } } </style> </head> <body> <div id="sidebar" class="interface"> <a class="toc_title" href="#"> Underscore.js <span class="version">(1.4.4)</span> </a> <ul class="toc_section"> <li>&raquo; <a href="path_to_url">GitHub Repository</a></li> <li>&raquo; <a href="docs/underscore.html">Annotated Source</a></li> </ul> <a class="toc_title" href="#"> Introduction </a> <a class="toc_title" href="#collections"> Collections </a> <ul class="toc_section"> <li>- <a href="#each">each</a></li> <li>- <a href="#map">map</a></li> <li>- <a href="#reduce">reduce</a></li> <li>- <a href="#reduceRight">reduceRight</a></li> <li>- <a href="#find">find</a></li> <li>- <a href="#filter">filter</a></li> <li>- <a href="#where">where</a></li> <li>- <a href="#findWhere">findWhere</a></li> <li>- <a href="#reject">reject</a></li> <li>- <a href="#every">every</a></li> <li>- <a href="#some">some</a></li> <li>- <a href="#contains">contains</a></li> <li>- <a href="#invoke">invoke</a></li> <li>- <a href="#pluck">pluck</a></li> <li>- <a href="#max">max</a></li> <li>- <a href="#min">min</a></li> <li>- <a href="#sortBy">sortBy</a></li> <li>- <a href="#groupBy">groupBy</a></li> <li>- <a href="#countBy">countBy</a></li> <li>- <a href="#shuffle">shuffle</a></li> <li>- <a href="#toArray">toArray</a></li> <li>- <a href="#size">size</a></li> </ul> <a class="toc_title" href="#arrays"> Arrays </a> <ul class="toc_section"> <li>- <a href="#first">first</a></li> <li>- <a href="#initial">initial</a></li> <li>- <a href="#last">last</a></li> <li>- <a href="#rest">rest</a></li> <li>- <a href="#compact">compact</a></li> <li>- <a href="#flatten">flatten</a></li> <li>- <a href="#without">without</a></li> <li>- <a href="#union">union</a></li> <li>- <a href="#intersection">intersection</a></li> <li>- <a href="#difference">difference</a></li> <li>- <a href="#uniq">uniq</a></li> <li>- <a href="#zip">zip</a></li> <li>- <a href="#object">object</a></li> <li>- <a href="#indexOf">indexOf</a></li> <li>- <a href="#lastIndexOf">lastIndexOf</a></li> <li>- <a href="#sortedIndex">sortedIndex</a></li> <li>- <a href="#range">range</a></li> </ul> <a class="toc_title" href="#functions"> Functions </a> <ul class="toc_section"> <li>- <a href="#bind">bind</a></li> <li>- <a href="#bindAll">bindAll</a></li> <li>- <a href="#partial">partial</a></li> <li>- <a href="#memoize">memoize</a></li> <li>- <a href="#delay">delay</a></li> <li>- <a href="#defer">defer</a></li> <li>- <a href="#throttle">throttle</a></li> <li>- <a href="#debounce">debounce</a></li> <li>- <a href="#once">once</a></li> <li>- <a href="#after">after</a></li> <li>- <a href="#wrap">wrap</a></li> <li>- <a href="#compose">compose</a></li> </ul> <a class="toc_title" href="#objects"> Objects </a> <ul class="toc_section"> <li>- <a href="#keys">keys</a></li> <li>- <a href="#values">values</a></li> <li>- <a href="#pairs">pairs</a></li> <li>- <a href="#invert">invert</a></li> <li>- <a href="#object-functions">functions</a></li> <li>- <a href="#extend">extend</a></li> <li>- <a href="#pick">pick</a></li> <li>- <a href="#omit">omit</a></li> <li>- <a href="#defaults">defaults</a></li> <li>- <a href="#clone">clone</a></li> <li>- <a href="#tap">tap</a></li> <li>- <a href="#has">has</a></li> <li>- <a href="#isEqual">isEqual</a></li> <li>- <a href="#isEmpty">isEmpty</a></li> <li>- <a href="#isElement">isElement</a></li> <li>- <a href="#isArray">isArray</a></li> <li>- <a href="#isObject">isObject</a></li> <li>- <a href="#isArguments">isArguments</a></li> <li>- <a href="#isFunction">isFunction</a></li> <li>- <a href="#isString">isString</a></li> <li>- <a href="#isNumber">isNumber</a></li> <li>- <a href="#isFinite">isFinite</a></li> <li>- <a href="#isBoolean">isBoolean</a></li> <li>- <a href="#isDate">isDate</a></li> <li>- <a href="#isRegExp">isRegExp</a></li> <li>- <a href="#isNaN">isNaN</a></li> <li>- <a href="#isNull">isNull</a></li> <li>- <a href="#isUndefined">isUndefined</a></li> </ul> <a class="toc_title" href="#utility"> Utility </a> <ul class="toc_section"> <li>- <a href="#noConflict">noConflict</a></li> <li>- <a href="#identity">identity</a></li> <li>- <a href="#times">times</a></li> <li>- <a href="#random">random</a></li> <li>- <a href="#mixin">mixin</a></li> <li>- <a href="#uniqueId">uniqueId</a></li> <li>- <a href="#escape">escape</a></li> <li>- <a href="#unescape">unescape</a></li> <li>- <a href="#result">result</a></li> <li>- <a href="#template">template</a></li> </ul> <a class="toc_title" href="#chaining"> Chaining </a> <ul class="toc_section"> <li>- <a href="#chain">chain</a></li> <li>- <a href="#value">value</a></li> </ul> <a class="toc_title" href="#links"> Links </a> <a class="toc_title" href="#changelog"> Change Log </a> </div> <div class="container"> <p id="introduction"> <img id="logo" src="docs/images/underscore.png" alt="Underscore.js" /> </p> <p> <a href="path_to_url">Underscore</a> is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in <a href="path_to_url">Prototype.js</a> (or <a href="path_to_url">Ruby</a>), but without extending any of the built-in JavaScript objects. It's the tie to go along with <a href="path_to_url">jQuery</a>'s tux, and <a href="path_to_url">Backbone.js</a>'s suspenders. </p> <p> Underscore provides 80-odd functions that support both the usual functional suspects: <b>map</b>, <b>select</b>, <b>invoke</b> &mdash; as well as more specialized helpers: function binding, javascript templating, deep equality testing, and so on. It delegates to built-in functions, if present, so modern browsers will use the native implementations of <b>forEach</b>, <b>map</b>, <b>reduce</b>, <b>filter</b>, <b>every</b>, <b>some</b> and <b>indexOf</b>. </p> <p> A complete <a href="test/">Test &amp; Benchmark Suite</a> is included for your perusal. </p> <p> You may also read through the <a href="docs/underscore.html">annotated source code</a>. </p> <p> The project is <a href="path_to_url">hosted on GitHub</a>. You can report bugs and discuss features on the <a href="path_to_url">issues page</a>, on Freenode in the <tt>#documentcloud</tt> channel, or send tweets to <a href="path_to_url">@documentcloud</a>. </p> <p> <i>Underscore is an open-source component of <a href="path_to_url">DocumentCloud</a>.</i> </p> <h2>Downloads <i style="padding-left: 12px; font-size:12px;">(Right-click, and use "Save As")</i></h2> <table> <tr> <td><a href="underscore.js">Development Version (1.4.4)</a></td> <td><i>40kb, Uncompressed with Plentiful Comments</i></td> </tr> <tr> <td><a href="underscore-min.js">Production Version (1.4.4)</a></td> <td><i>4kb, Minified and Gzipped</i></td> </tr> <tr> <td colspan="2"><div class="rule"></div></td> </tr> <tr> <td><a href="path_to_url">Edge Version</a></td> <td><i>Unreleased, current <tt>master</tt>, use at your own risk</i></td> </tr> </table> <div id="documentation"> <h2 id="collections">Collection Functions (Arrays or Objects)</h2> <p id="each"> <b class="header">each</b><code>_.each(list, iterator, [context])</code> <span class="alias">Alias: <b>forEach</b></span> <br /> Iterates over a <b>list</b> of elements, yielding each in turn to an <b>iterator</b> function. The <b>iterator</b> is bound to the <b>context</b> object, if one is passed. Each invocation of <b>iterator</b> is called with three arguments: <tt>(element, index, list)</tt>. If <b>list</b> is a JavaScript object, <b>iterator</b>'s arguments will be <tt>(value, key, list)</tt>. Delegates to the native <b>forEach</b> function if it exists. </p> <pre> _.each([1, 2, 3], alert); =&gt; alerts each number in turn... _.each({one : 1, two : 2, three : 3}, alert); =&gt; alerts each number value in turn...</pre> <p id="map"> <b class="header">map</b><code>_.map(list, iterator, [context])</code> <span class="alias">Alias: <b>collect</b></span> <br /> Produces a new array of values by mapping each value in <b>list</b> through a transformation function (<b>iterator</b>). If the native <b>map</b> method exists, it will be used instead. If <b>list</b> is a JavaScript object, <b>iterator</b>'s arguments will be <tt>(value, key, list)</tt>. </p> <pre> _.map([1, 2, 3], function(num){ return num * 3; }); =&gt; [3, 6, 9] _.map({one : 1, two : 2, three : 3}, function(num, key){ return num * 3; }); =&gt; [3, 6, 9]</pre> <p id="reduce"> <b class="header">reduce</b><code>_.reduce(list, iterator, memo, [context])</code> <span class="alias">Aliases: <b>inject, foldl</b></span> <br /> Also known as <b>inject</b> and <b>foldl</b>, <b>reduce</b> boils down a <b>list</b> of values into a single value. <b>Memo</b> is the initial state of the reduction, and each successive step of it should be returned by <b>iterator</b>. The iterator is passed four arguments: the <tt>memo</tt>, then the <tt>value</tt> and <tt>index</tt> (or key) of the iteration, and finally a reference to the entire <tt>list</tt>. </p> <pre> var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0); =&gt; 6 </pre> <p id="reduceRight"> <b class="header">reduceRight</b><code>_.reduceRight(list, iterator, memo, [context])</code> <span class="alias">Alias: <b>foldr</b></span> <br /> The right-associative version of <b>reduce</b>. Delegates to the JavaScript 1.8 version of <b>reduceRight</b>, if it exists. <b>Foldr</b> is not as useful in JavaScript as it would be in a language with lazy evaluation. </p> <pre> var list = [[0, 1], [2, 3], [4, 5]]; var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); =&gt; [4, 5, 2, 3, 0, 1] </pre> <p id="find"> <b class="header">find</b><code>_.find(list, iterator, [context])</code> <span class="alias">Alias: <b>detect</b></span> <br /> Looks through each value in the <b>list</b>, returning the first one that passes a truth test (<b>iterator</b>). The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list. </p> <pre> var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); =&gt; 2 </pre> <p id="filter"> <b class="header">filter</b><code>_.filter(list, iterator, [context])</code> <span class="alias">Alias: <b>select</b></span> <br /> Looks through each value in the <b>list</b>, returning an array of all the values that pass a truth test (<b>iterator</b>). Delegates to the native <b>filter</b> method, if it exists. </p> <pre> var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); =&gt; [2, 4, 6] </pre> <p id="where"> <b class="header">where</b><code>_.where(list, properties)</code> <br /> Looks through each value in the <b>list</b>, returning an array of all the values that contain all of the key-value pairs listed in <b>properties</b>. </p> <pre> _.where(listOfPlays, {author: "Shakespeare", year: 1611}); =&gt; [{title: "Cymbeline", author: "Shakespeare", year: 1611}, {title: "The Tempest", author: "Shakespeare", year: 1611}] </pre> <p id="findWhere"> <b class="header">findWhere</b><code>_.findWhere(list, properties)</code> <br /> Looks through the <b>list</b> and returns the <i>first</i> value that matches all of the key-value pairs listed in <b>properties</b>. </p> <pre> _.findWhere(publicServicePulitzers, {newsroom: "The New York Times"}); =&gt; {year: 1918, newsroom: "The New York Times", reason: "For its public service in publishing in full so many official reports, documents and speeches by European statesmen relating to the progress and conduct of the war."} </pre> <p id="reject"> <b class="header">reject</b><code>_.reject(list, iterator, [context])</code> <br /> Returns the values in <b>list</b> without the elements that the truth test (<b>iterator</b>) passes. The opposite of <b>filter</b>. </p> <pre> var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); =&gt; [1, 3, 5] </pre> <p id="every"> <b class="header">every</b><code>_.every(list, iterator, [context])</code> <span class="alias">Alias: <b>all</b></span> <br /> Returns <i>true</i> if all of the values in the <b>list</b> pass the <b>iterator</b> truth test. Delegates to the native method <b>every</b>, if present. </p> <pre> _.every([true, 1, null, 'yes'], _.identity); =&gt; false </pre> <p id="some"> <b class="header">some</b><code>_.some(list, [iterator], [context])</code> <span class="alias">Alias: <b>any</b></span> <br /> Returns <i>true</i> if any of the values in the <b>list</b> pass the <b>iterator</b> truth test. Short-circuits and stops traversing the list if a true element is found. Delegates to the native method <b>some</b>, if present. </p> <pre> _.some([null, 0, 'yes', false]); =&gt; true </pre> <p id="contains"> <b class="header">contains</b><code>_.contains(list, value)</code> <span class="alias">Alias: <b>include</b></span> <br /> Returns <i>true</i> if the <b>value</b> is present in the <b>list</b>. Uses <b>indexOf</b> internally, if <b>list</b> is an Array. </p> <pre> _.contains([1, 2, 3], 3); =&gt; true </pre> <p id="invoke"> <b class="header">invoke</b><code>_.invoke(list, methodName, [*arguments])</code> <br /> Calls the method named by <b>methodName</b> on each value in the <b>list</b>. Any extra arguments passed to <b>invoke</b> will be forwarded on to the method invocation. </p> <pre> _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); =&gt; [[1, 5, 7], [1, 2, 3]] </pre> <p id="pluck"> <b class="header">pluck</b><code>_.pluck(list, propertyName)</code> <br /> A convenient version of what is perhaps the most common use-case for <b>map</b>: extracting a list of property values. </p> <pre> var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}]; _.pluck(stooges, 'name'); =&gt; ["moe", "larry", "curly"] </pre> <p id="max"> <b class="header">max</b><code>_.max(list, [iterator], [context])</code> <br /> Returns the maximum value in <b>list</b>. If <b>iterator</b> is passed, it will be used on each value to generate the criterion by which the value is ranked. </p> <pre> var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}]; _.max(stooges, function(stooge){ return stooge.age; }); =&gt; {name : 'curly', age : 60}; </pre> <p id="min"> <b class="header">min</b><code>_.min(list, [iterator], [context])</code> <br /> Returns the minimum value in <b>list</b>. If <b>iterator</b> is passed, it will be used on each value to generate the criterion by which the value is ranked. </p> <pre> var numbers = [10, 5, 100, 2, 1000]; _.min(numbers); =&gt; 2 </pre> <p id="sortBy"> <b class="header">sortBy</b><code>_.sortBy(list, iterator, [context])</code> <br /> Returns a sorted copy of <b>list</b>, ranked in ascending order by the results of running each value through <b>iterator</b>. Iterator may also be the string name of the property to sort by (eg. <tt>length</tt>). </p> <pre> _.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); }); =&gt; [5, 4, 6, 3, 1, 2] </pre> <p id="groupBy"> <b class="header">groupBy</b><code>_.groupBy(list, iterator, [context])</code> <br /> Splits a collection into sets, grouped by the result of running each value through <b>iterator</b>. If <b>iterator</b> is a string instead of a function, groups by the property named by <b>iterator</b> on each of the values. </p> <pre> _.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); }); =&gt; {1: [1.3], 2: [2.1, 2.4]} _.groupBy(['one', 'two', 'three'], 'length'); =&gt; {3: ["one", "two"], 5: ["three"]} </pre> <p id="countBy"> <b class="header">countBy</b><code>_.countBy(list, iterator, [context])</code> <br /> Sorts a list into groups and returns a count for the number of objects in each group. Similar to <tt>groupBy</tt>, but instead of returning a list of values, returns a count for the number of values in that group. </p> <pre> _.countBy([1, 2, 3, 4, 5], function(num) { return num % 2 == 0 ? 'even' : 'odd'; }); =&gt; {odd: 3, even: 2} </pre> <p id="shuffle"> <b class="header">shuffle</b><code>_.shuffle(list)</code> <br /> Returns a shuffled copy of the <b>list</b>, using a version of the <a href="path_to_url">Fisher-Yates shuffle</a>. </p> <pre> _.shuffle([1, 2, 3, 4, 5, 6]); =&gt; [4, 1, 6, 3, 5, 2] </pre> <p id="toArray"> <b class="header">toArray</b><code>_.toArray(list)</code> <br /> Converts the <b>list</b> (anything that can be iterated over), into a real Array. Useful for transmuting the <b>arguments</b> object. </p> <pre> (function(){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4); =&gt; [2, 3, 4] </pre> <p id="size"> <b class="header">size</b><code>_.size(list)</code> <br /> Return the number of values in the <b>list</b>. </p> <pre> _.size({one : 1, two : 2, three : 3}); =&gt; 3 </pre> <h2 id="arrays">Array Functions</h2> <p> <i> Note: All array functions will also work on the <b>arguments</b> object. However, Underscore functions are not designed to work on "sparse" arrays. </i> </p> <p id="first"> <b class="header">first</b><code>_.first(array, [n])</code> <span class="alias">Alias: <b>head</b>, <b>take</b></span> <br /> Returns the first element of an <b>array</b>. Passing <b>n</b> will return the first <b>n</b> elements of the array. </p> <pre> _.first([5, 4, 3, 2, 1]); =&gt; 5 </pre> <p id="initial"> <b class="header">initial</b><code>_.initial(array, [n])</code> <br /> Returns everything but the last entry of the array. Especially useful on the arguments object. Pass <b>n</b> to exclude the last <b>n</b> elements from the result. </p> <pre> _.initial([5, 4, 3, 2, 1]); =&gt; [5, 4, 3, 2] </pre> <p id="last"> <b class="header">last</b><code>_.last(array, [n])</code> <br /> Returns the last element of an <b>array</b>. Passing <b>n</b> will return the last <b>n</b> elements of the array. </p> <pre> _.last([5, 4, 3, 2, 1]); =&gt; 1 </pre> <p id="rest"> <b class="header">rest</b><code>_.rest(array, [index])</code> <span class="alias">Alias: <b>tail, drop</b></span> <br /> Returns the <b>rest</b> of the elements in an array. Pass an <b>index</b> to return the values of the array from that index onward. </p> <pre> _.rest([5, 4, 3, 2, 1]); =&gt; [4, 3, 2, 1] </pre> <p id="compact"> <b class="header">compact</b><code>_.compact(array)</code> <br /> Returns a copy of the <b>array</b> with all falsy values removed. In JavaScript, <i>false</i>, <i>null</i>, <i>0</i>, <i>""</i>, <i>undefined</i> and <i>NaN</i> are all falsy. </p> <pre> _.compact([0, 1, false, 2, '', 3]); =&gt; [1, 2, 3] </pre> <p id="flatten"> <b class="header">flatten</b><code>_.flatten(array, [shallow])</code> <br /> Flattens a nested <b>array</b> (the nesting can be to any depth). If you pass <b>shallow</b>, the array will only be flattened a single level. </p> <pre> _.flatten([1, [2], [3, [[4]]]]); =&gt; [1, 2, 3, 4]; _.flatten([1, [2], [3, [[4]]]], true); =&gt; [1, 2, 3, [[4]]]; </pre> <p id="without"> <b class="header">without</b><code>_.without(array, [*values])</code> <br /> Returns a copy of the <b>array</b> with all instances of the <b>values</b> removed. </p> <pre> _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); =&gt; [2, 3, 4] </pre> <p id="union"> <b class="header">union</b><code>_.union(*arrays)</code> <br /> Computes the union of the passed-in <b>arrays</b>: the list of unique items, in order, that are present in one or more of the <b>arrays</b>. </p> <pre> _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); =&gt; [1, 2, 3, 101, 10] </pre> <p id="intersection"> <b class="header">intersection</b><code>_.intersection(*arrays)</code> <br /> Computes the list of values that are the intersection of all the <b>arrays</b>. Each value in the result is present in each of the <b>arrays</b>. </p> <pre> _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); =&gt; [1, 2] </pre> <p id="difference"> <b class="header">difference</b><code>_.difference(array, *others)</code> <br /> Similar to <b>without</b>, but returns the values from <b>array</b> that are not present in the <b>other</b> arrays. </p> <pre> _.difference([1, 2, 3, 4, 5], [5, 2, 10]); =&gt; [1, 3, 4] </pre> <p id="uniq"> <b class="header">uniq</b><code>_.uniq(array, [isSorted], [iterator])</code> <span class="alias">Alias: <b>unique</b></span> <br /> Produces a duplicate-free version of the <b>array</b>, using <i>===</i> to test object equality. If you know in advance that the <b>array</b> is sorted, passing <i>true</i> for <b>isSorted</b> will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an <b>iterator</b> function. </p> <pre> _.uniq([1, 2, 1, 3, 1, 4]); =&gt; [1, 2, 3, 4] </pre> <p id="zip"> <b class="header">zip</b><code>_.zip(*arrays)</code> <br /> Merges together the values of each of the <b>arrays</b> with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes. If you're working with a matrix of nested arrays, <b>zip.apply</b> can transpose the matrix in a similar fashion. </p> <pre> _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); =&gt; [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]] </pre> <p id="object"> <b class="header">object</b><code>_.object(list, [values])</code> <br /> Converts arrays into objects. Pass either a single list of <tt>[key, value]</tt> pairs, or a list of keys, and a list of values. </p> <pre> _.object(['moe', 'larry', 'curly'], [30, 40, 50]); =&gt; {moe: 30, larry: 40, curly: 50} _.object([['moe', 30], ['larry', 40], ['curly', 50]]); =&gt; {moe: 30, larry: 40, curly: 50} </pre> <p id="indexOf"> <b class="header">indexOf</b><code>_.indexOf(array, value, [isSorted])</code> <br /> Returns the index at which <b>value</b> can be found in the <b>array</b>, or <i>-1</i> if value is not present in the <b>array</b>. Uses the native <b>indexOf</b> function unless it's missing. If you're working with a large array, and you know that the array is already sorted, pass <tt>true</tt> for <b>isSorted</b> to use a faster binary search ... or, pass a number as the third argument in order to look for the first matching value in the array after the given index. </p> <pre> _.indexOf([1, 2, 3], 2); =&gt; 1 </pre> <p id="lastIndexOf"> <b class="header">lastIndexOf</b><code>_.lastIndexOf(array, value, [fromIndex])</code> <br /> Returns the index of the last occurrence of <b>value</b> in the <b>array</b>, or <i>-1</i> if value is not present. Uses the native <b>lastIndexOf</b> function if possible. Pass <b>fromIndex</b> to start your search at a given index. </p> <pre> _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); =&gt; 4 </pre> <p id="sortedIndex"> <b class="header">sortedIndex</b><code>_.sortedIndex(list, value, [iterator], [context])</code> <br /> Uses a binary search to determine the index at which the <b>value</b> <i>should</i> be inserted into the <b>list</b> in order to maintain the <b>list</b>'s sorted order. If an <b>iterator</b> is passed, it will be used to compute the sort ranking of each value, including the <b>value</b> you pass. </p> <pre> _.sortedIndex([10, 20, 30, 40, 50], 35); =&gt; 3 </pre> <p id="range"> <b class="header">range</b><code>_.range([start], stop, [step])</code> <br /> A function to create flexibly-numbered lists of integers, handy for <tt>each</tt> and <tt>map</tt> loops. <b>start</b>, if omitted, defaults to <i>0</i>; <b>step</b> defaults to <i>1</i>. Returns a list of integers from <b>start</b> to <b>stop</b>, incremented (or decremented) by <b>step</b>, exclusive. </p> <pre> _.range(10); =&gt; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] _.range(1, 11); =&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] _.range(0, 30, 5); =&gt; [0, 5, 10, 15, 20, 25] _.range(0, -10, -1); =&gt; [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] _.range(0); =&gt; [] </pre> <h2 id="functions">Function (uh, ahem) Functions</h2> <p id="bind"> <b class="header">bind</b><code>_.bind(function, object, [*arguments])</code> <br /> Bind a <b>function</b> to an <b>object</b>, meaning that whenever the function is called, the value of <i>this</i> will be the <b>object</b>. Optionally, pass <b>arguments</b> to the <b>function</b> to pre-fill them, also known as <b>partial application</b>. </p> <pre> var func = function(greeting){ return greeting + ': ' + this.name }; func = _.bind(func, {name : 'moe'}, 'hi'); func(); =&gt; 'hi: moe' </pre> <p id="bindAll"> <b class="header">bindAll</b><code>_.bindAll(object, [*methodNames])</code> <br /> Binds a number of methods on the <b>object</b>, specified by <b>methodNames</b>, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless <i>this</i>. If no <b>methodNames</b> are provided, all of the object's function properties will be bound to it. </p> <pre> var buttonView = { label : 'underscore', onClick : function(){ alert('clicked: ' + this.label); }, onHover : function(){ console.log('hovering: ' + this.label); } }; _.bindAll(buttonView); jQuery('#underscore_button').bind('click', buttonView.onClick); =&gt; When the button is clicked, this.label will have the correct value... </pre> <p id="partial"> <b class="header">partial</b><code>_.partial(function, [*arguments])</code> <br /> Partially apply a function by filling in any number of its arguments, <i>without</i> changing its dynamic <tt>this</tt> value. A close cousin of <a href="#bind">bind</a>. </p> <pre> var add = function(a, b) { return a + b; }; add5 = _.partial(add, 5); add5(10); =&gt; 15 </pre> <p id="memoize"> <b class="header">memoize</b><code>_.memoize(function, [hashFunction])</code> <br /> Memoizes a given <b>function</b> by caching the computed result. Useful for speeding up slow-running computations. If passed an optional <b>hashFunction</b>, it will be used to compute the hash key for storing the result, based on the arguments to the original function. The default <b>hashFunction</b> just uses the first argument to the memoized function as the key. </p> <pre> var fibonacci = _.memoize(function(n) { return n &lt; 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); }); </pre> <p id="delay"> <b class="header">delay</b><code>_.delay(function, wait, [*arguments])</code> <br /> Much like <b>setTimeout</b>, invokes <b>function</b> after <b>wait</b> milliseconds. If you pass the optional <b>arguments</b>, they will be forwarded on to the <b>function</b> when it is invoked. </p> <pre> var log = _.bind(console.log, console); _.delay(log, 1000, 'logged later'); =&gt; 'logged later' // Appears after one second. </pre> <p id="defer"> <b class="header">defer</b><code>_.defer(function, [*arguments])</code> <br /> Defers invoking the <b>function</b> until the current call stack has cleared, similar to using <b>setTimeout</b> with a delay of 0. Useful for performing expensive computations or HTML rendering in chunks without blocking the UI thread from updating. If you pass the optional <b>arguments</b>, they will be forwarded on to the <b>function</b> when it is invoked. </p> <pre> _.defer(function(){ alert('deferred'); }); // Returns from the function before the alert runs. </pre> <p id="throttle"> <b class="header">throttle</b><code>_.throttle(function, wait)</code> <br /> Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every <b>wait</b> milliseconds. Useful for rate-limiting events that occur faster than you can keep up with. </p> <pre> var throttled = _.throttle(updatePosition, 100); $(window).scroll(throttled); </pre> <p id="debounce"> <b class="header">debounce</b><code>_.debounce(function, wait, [immediate])</code> <br /> Creates and returns a new debounced version of the passed function that will postpone its execution until after <b>wait</b> milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happen <i>after</i> the input has stopped arriving. For example: rendering a preview of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on. </p> <p> Pass <tt>true</tt> for the <b>immediate</b> parameter to cause <b>debounce</b> to trigger the function on the leading instead of the trailing edge of the <b>wait</b> interval. Useful in circumstances like preventing accidental double-clicks on a "submit" button from firing a second time. </p> <pre> var lazyLayout = _.debounce(calculateLayout, 300); $(window).resize(lazyLayout); </pre> <p id="once"> <b class="header">once</b><code>_.once(function)</code> <br /> Creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and then check it later. </p> <pre> var initialize = _.once(createApplication); initialize(); initialize(); // Application is only created once. </pre> <p id="after"> <b class="header">after</b><code>_.after(count, function)</code> <br /> Creates a version of the function that will only be run after first being called <b>count</b> times. Useful for grouping asynchronous responses, where you want to be sure that all the async calls have finished, before proceeding. </p> <pre> var renderNotes = _.after(notes.length, render); _.each(notes, function(note) { note.asyncSave({success: renderNotes}); }); // renderNotes is run once, after all notes have saved. </pre> <p id="wrap"> <b class="header">wrap</b><code>_.wrap(function, wrapper)</code> <br /> Wraps the first <b>function</b> inside of the <b>wrapper</b> function, passing it as the first argument. This allows the <b>wrapper</b> to execute code before and after the <b>function</b> runs, adjust the arguments, and execute it conditionally. </p> <pre> var hello = function(name) { return "hello: " + name; }; hello = _.wrap(hello, function(func) { return "before, " + func("moe") + ", after"; }); hello(); =&gt; 'before, hello: moe, after' </pre> <p id="compose"> <b class="header">compose</b><code>_.compose(*functions)</code> <br /> Returns the composition of a list of <b>functions</b>, where each function consumes the return value of the function that follows. In math terms, composing the functions <i>f()</i>, <i>g()</i>, and <i>h()</i> produces <i>f(g(h()))</i>. </p> <pre> var greet = function(name){ return "hi: " + name; }; var exclaim = function(statement){ return statement + "!"; }; var welcome = _.compose(exclaim, greet); welcome('moe'); =&gt; 'hi: moe!' </pre> <h2 id="objects">Object Functions</h2> <p id="keys"> <b class="header">keys</b><code>_.keys(object)</code> <br /> Retrieve all the names of the <b>object</b>'s properties. </p> <pre> _.keys({one : 1, two : 2, three : 3}); =&gt; ["one", "two", "three"] </pre> <p id="values"> <b class="header">values</b><code>_.values(object)</code> <br /> Return all of the values of the <b>object</b>'s properties. </p> <pre> _.values({one : 1, two : 2, three : 3}); =&gt; [1, 2, 3] </pre> <p id="pairs"> <b class="header">pairs</b><code>_.pairs(object)</code> <br /> Convert an object into a list of <tt>[key, value]</tt> pairs. </p> <pre> _.pairs({one: 1, two: 2, three: 3}); =&gt; [["one", 1], ["two", 2], ["three", 3]] </pre> <p id="invert"> <b class="header">invert</b><code>_.invert(object)</code> <br /> Returns a copy of the <b>object</b> where the keys have become the values and the values the keys. For this to work, all of your object's values should be unique and string serializable. </p> <pre> _.invert({Moe: "Moses", Larry: "Louis", Curly: "Jerome"}); =&gt; {Moses: "Moe", Louis: "Larry", Jerome: "Curly"}; </pre> <p id="object-functions"> <b class="header">functions</b><code>_.functions(object)</code> <span class="alias">Alias: <b>methods</b></span> <br /> Returns a sorted list of the names of every method in an object &mdash; that is to say, the name of every function property of the object. </p> <pre> _.functions(_); =&gt; ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ... </pre> <p id="extend"> <b class="header">extend</b><code>_.extend(destination, *sources)</code> <br /> Copy all of the properties in the <b>source</b> objects over to the <b>destination</b> object, and return the <b>destination</b> object. It's in-order, so the last source will override properties of the same name in previous arguments. </p> <pre> _.extend({name : 'moe'}, {age : 50}); =&gt; {name : 'moe', age : 50} </pre> <p id="pick"> <b class="header">pick</b><code>_.pick(object, *keys)</code> <br /> Return a copy of the <b>object</b>, filtered to only have values for the whitelisted <b>keys</b> (or array of valid keys). </p> <pre> _.pick({name : 'moe', age: 50, userid : 'moe1'}, 'name', 'age'); =&gt; {name : 'moe', age : 50} </pre> <p id="omit"> <b class="header">omit</b><code>_.omit(object, *keys)</code> <br /> Return a copy of the <b>object</b>, filtered to omit the blacklisted <b>keys</b> (or array of keys). </p> <pre> _.omit({name : 'moe', age : 50, userid : 'moe1'}, 'userid'); =&gt; {name : 'moe', age : 50} </pre> <p id="defaults"> <b class="header">defaults</b><code>_.defaults(object, *defaults)</code> <br /> Fill in null and undefined properties in <b>object</b> with values from the <b>defaults</b> objects, and return the <b>object</b>. As soon as the property is filled, further defaults will have no effect. </p> <pre> var iceCream = {flavor : "chocolate"}; _.defaults(iceCream, {flavor : "vanilla", sprinkles : "lots"}); =&gt; {flavor : "chocolate", sprinkles : "lots"} </pre> <p id="clone"> <b class="header">clone</b><code>_.clone(object)</code> <br /> Create a shallow-copied clone of the <b>object</b>. Any nested objects or arrays will be copied by reference, not duplicated. </p> <pre> _.clone({name : 'moe'}); =&gt; {name : 'moe'}; </pre> <p id="tap"> <b class="header">tap</b><code>_.tap(object, interceptor)</code> <br /> Invokes <b>interceptor</b> with the <b>object</b>, and then returns <b>object</b>. The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain. </p> <pre> _.chain([1,2,3,200]) .filter(function(num) { return num % 2 == 0; }) .tap(alert) .map(function(num) { return num * num }) .value(); =&gt; // [2, 200] (alerted) =&gt; [4, 40000] </pre> <p id="has"> <b class="header">has</b><code>_.has(object, key)</code> <br /> Does the object contain the given key? Identical to <tt>object.hasOwnProperty(key)</tt>, but uses a safe reference to the <tt>hasOwnProperty</tt> function, in case it's been <a href="path_to_url">overridden accidentally</a>. </p> <pre> _.has({a: 1, b: 2, c: 3}, "b"); =&gt; true </pre> <p id="isEqual"> <b class="header">isEqual</b><code>_.isEqual(object, other)</code> <br /> Performs an optimized deep comparison between the two objects, to determine if they should be considered equal. </p> <pre> var moe = {name : 'moe', luckyNumbers : [13, 27, 34]}; var clone = {name : 'moe', luckyNumbers : [13, 27, 34]}; moe == clone; =&gt; false _.isEqual(moe, clone); =&gt; true </pre> <p id="isEmpty"> <b class="header">isEmpty</b><code>_.isEmpty(object)</code> <br /> Returns <i>true</i> if <b>object</b> contains no values. </p> <pre> _.isEmpty([1, 2, 3]); =&gt; false _.isEmpty({}); =&gt; true </pre> <p id="isElement"> <b class="header">isElement</b><code>_.isElement(object)</code> <br /> Returns <i>true</i> if <b>object</b> is a DOM element. </p> <pre> _.isElement(jQuery('body')[0]); =&gt; true </pre> <p id="isArray"> <b class="header">isArray</b><code>_.isArray(object)</code> <br /> Returns <i>true</i> if <b>object</b> is an Array. </p> <pre> (function(){ return _.isArray(arguments); })(); =&gt; false _.isArray([1,2,3]); =&gt; true </pre> <p id="isObject"> <b class="header">isObject</b><code>_.isObject(value)</code> <br /> Returns <i>true</i> if <b>value</b> is an Object. Note that JavaScript arrays and functions are objects, while (normal) strings and numbers are not. </p> <pre> _.isObject({}); =&gt; true _.isObject(1); =&gt; false </pre> <p id="isArguments"> <b class="header">isArguments</b><code>_.isArguments(object)</code> <br /> Returns <i>true</i> if <b>object</b> is an Arguments object. </p> <pre> (function(){ return _.isArguments(arguments); })(1, 2, 3); =&gt; true _.isArguments([1,2,3]); =&gt; false </pre> <p id="isFunction"> <b class="header">isFunction</b><code>_.isFunction(object)</code> <br /> Returns <i>true</i> if <b>object</b> is a Function. </p> <pre> _.isFunction(alert); =&gt; true </pre> <p id="isString"> <b class="header">isString</b><code>_.isString(object)</code> <br /> Returns <i>true</i> if <b>object</b> is a String. </p> <pre> _.isString("moe"); =&gt; true </pre> <p id="isNumber"> <b class="header">isNumber</b><code>_.isNumber(object)</code> <br /> Returns <i>true</i> if <b>object</b> is a Number (including <tt>NaN</tt>). </p> <pre> _.isNumber(8.4 * 5); =&gt; true </pre> <p id="isFinite"> <b class="header">isFinite</b><code>_.isFinite(object)</code> <br /> Returns <i>true</i> if <b>object</b> is a finite Number. </p> <pre> _.isFinite(-101); =&gt; true _.isFinite(-Infinity); =&gt; false </pre> <p id="isBoolean"> <b class="header">isBoolean</b><code>_.isBoolean(object)</code> <br /> Returns <i>true</i> if <b>object</b> is either <i>true</i> or <i>false</i>. </p> <pre> _.isBoolean(null); =&gt; false </pre> <p id="isDate"> <b class="header">isDate</b><code>_.isDate(object)</code> <br /> Returns <i>true</i> if <b>object</b> is a Date. </p> <pre> _.isDate(new Date()); =&gt; true </pre> <p id="isRegExp"> <b class="header">isRegExp</b><code>_.isRegExp(object)</code> <br /> Returns <i>true</i> if <b>object</b> is a RegExp. </p> <pre> _.isRegExp(/moe/); =&gt; true </pre> <p id="isNaN"> <b class="header">isNaN</b><code>_.isNaN(object)</code> <br /> Returns <i>true</i> if <b>object</b> is <i>NaN</i>.<br /> Note: this is not the same as the native <b>isNaN</b> function, which will also return true if the variable is <i>undefined</i>. </p> <pre> _.isNaN(NaN); =&gt; true isNaN(undefined); =&gt; true _.isNaN(undefined); =&gt; false </pre> <p id="isNull"> <b class="header">isNull</b><code>_.isNull(object)</code> <br /> Returns <i>true</i> if the value of <b>object</b> is <i>null</i>. </p> <pre> _.isNull(null); =&gt; true _.isNull(undefined); =&gt; false </pre> <p id="isUndefined"> <b class="header">isUndefined</b><code>_.isUndefined(value)</code> <br /> Returns <i>true</i> if <b>value</b> is <i>undefined</i>. </p> <pre> _.isUndefined(window.missingVariable); =&gt; true </pre> <h2 id="utility">Utility Functions</h2> <p id="noConflict"> <b class="header">noConflict</b><code>_.noConflict()</code> <br /> Give control of the "_" variable back to its previous owner. Returns a reference to the <b>Underscore</b> object. </p> <pre> var underscore = _.noConflict();</pre> <p id="identity"> <b class="header">identity</b><code>_.identity(value)</code> <br /> Returns the same value that is used as the argument. In math: <tt>f(x) = x</tt><br /> This function looks useless, but is used throughout Underscore as a default iterator. </p> <pre> var moe = {name : 'moe'}; moe === _.identity(moe); =&gt; true</pre> <p id="times"> <b class="header">times</b><code>_.times(n, iterator, [context])</code> <br /> Invokes the given iterator function <b>n</b> times. Each invocation of <b>iterator</b> is called with an <tt>index</tt> argument. <br /> <i>Note: this example uses the <a href="#chaining">chaining syntax</a></i>. </p> <pre> _(3).times(function(n){ genie.grantWishNumber(n); });</pre> <p id="random"> <b class="header">random</b><code>_.random(min, max)</code> <br /> Returns a random integer between <b>min</b> and <b>max</b>, inclusive. If you only pass one argument, it will return a number between <tt>0</tt> and that number. </p> <pre> _.random(0, 100); =&gt; 42</pre> <p id="mixin"> <b class="header">mixin</b><code>_.mixin(object)</code> <br /> Allows you to extend Underscore with your own utility functions. Pass a hash of <tt>{name: function}</tt> definitions to have your functions added to the Underscore object, as well as the OOP wrapper. </p> <pre> _.mixin({ capitalize : function(string) { return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase(); } }); _("fabio").capitalize(); =&gt; "Fabio" </pre> <p id="uniqueId"> <b class="header">uniqueId</b><code>_.uniqueId([prefix])</code> <br /> Generate a globally-unique id for client-side models or DOM elements that need one. If <b>prefix</b> is passed, the id will be appended to it. </p> <pre> _.uniqueId('contact_'); =&gt; 'contact_104'</pre> <p id="escape"> <b class="header">escape</b><code>_.escape(string)</code> <br /> Escapes a string for insertion into HTML, replacing <tt>&amp;</tt>, <tt>&lt;</tt>, <tt>&gt;</tt>, <tt>&quot;</tt>, <tt>&#x27;</tt>, and <tt>&#x2F;</tt> characters. </p> <pre> _.escape('Curly, Larry &amp; Moe'); =&gt; "Curly, Larry &amp;amp; Moe"</pre> <p id="unescape"> <b class="header">unescape</b><code>_.unescape(string)</code> <br /> The opposite of <a href="#escape"><b>escape</b></a>, replaces <tt>&amp;amp;</tt>, <tt>&amp;lt;</tt>, <tt>&amp;gt;</tt>, <tt>&amp;quot;</tt>, <tt>&amp;#x27;</tt>, and <tt>&amp;#x2F;</tt> with their unescaped counterparts. </p> <pre> _.unescape('Curly, Larry &amp;amp; Moe'); =&gt; "Curly, Larry &amp; Moe"</pre> <p id="result"> <b class="header">result</b><code>_.result(object, property)</code> <br /> If the value of the named property is a function then invoke it; otherwise, return it. </p> <pre> var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }}; _.result(object, 'cheese'); =&gt; "crumpets" _.result(object, 'stuff'); =&gt; "nonsense"</pre> <p id="template"> <b class="header">template</b><code>_.template(templateString, [data], [settings])</code> <br /> Compiles JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources. Template functions can both interpolate variables, using <tt>&lt;%= &hellip; %&gt;</tt>, as well as execute arbitrary JavaScript code, with <tt>&lt;% &hellip; %&gt;</tt>. If you wish to interpolate a value, and have it be HTML-escaped, use <tt>&lt;%- &hellip; %&gt;</tt> When you evaluate a template function, pass in a <b>data</b> object that has properties corresponding to the template's free variables. If you're writing a one-off, you can pass the <b>data</b> object as the second parameter to <b>template</b> in order to render immediately instead of returning a template function. The <b>settings</b> argument should be a hash containing any <tt>_.templateSettings</tt> that should be overridden. </p> <pre> var compiled = _.template("hello: &lt;%= name %&gt;"); compiled({name : 'moe'}); =&gt; "hello: moe" var list = "&lt;% _.each(people, function(name) { %&gt; &lt;li&gt;&lt;%= name %&gt;&lt;/li&gt; &lt;% }); %&gt;"; _.template(list, {people : ['moe', 'curly', 'larry']}); =&gt; "&lt;li&gt;moe&lt;/li&gt;&lt;li&gt;curly&lt;/li&gt;&lt;li&gt;larry&lt;/li&gt;" var template = _.template("&lt;b&gt;&lt;%- value %&gt;&lt;/b&gt;"); template({value : '&lt;script&gt;'}); =&gt; "&lt;b&gt;&amp;lt;script&amp;gt;&lt;/b&gt;"</pre> <p> You can also use <tt>print</tt> from within JavaScript code. This is sometimes more convenient than using <tt>&lt;%= ... %&gt;</tt>. </p> <pre> var compiled = _.template("&lt;% print('Hello ' + epithet); %&gt;"); compiled({epithet: "stooge"}); =&gt; "Hello stooge."</pre> <p> If ERB-style delimiters aren't your cup of tea, you can change Underscore's template settings to use different symbols to set off interpolated code. Define an <b>interpolate</b> regex to match expressions that should be interpolated verbatim, an <b>escape</b> regex to match expressions that should be inserted after being HTML escaped, and an <b>evaluate</b> regex to match expressions that should be evaluated without insertion into the resulting string. You may define or omit any combination of the three. For example, to perform <a href="path_to_url#readme">Mustache.js</a> style templating: </p> <pre> _.templateSettings = { interpolate : /\{\{(.+?)\}\}/g }; var template = _.template("Hello {{ name }}!"); template({name : "Mustache"}); =&gt; "Hello Mustache!"</pre> <p> By default, <b>template</b> places the values from your data in the local scope via the <tt>with</tt> statement. However, you can specify a single variable name with the <b>variable</b> setting. This can significantly improve the speed at which a template is able to render. </p> <pre> _.template("Using 'with': <%= data.answer %>", {answer: 'no'}, {variable: 'data'}); =&gt; "Using 'with': no"</pre> <p> Precompiling your templates can be a big help when debugging errors you can't reproduce. This is because precompiled templates can provide line numbers and a stack trace, something that is not possible when compiling templates on the client. The <b>source</b> property is available on the compiled template function for easy precompilation. </p> <pre>&lt;script&gt; JST.project = <%= _.template(jstText).source %>; &lt;/script&gt;</pre> <h2 id="chaining">Chaining</h2> <p> You can use Underscore in either an object-oriented or a functional style, depending on your preference. The following two lines of code are identical ways to double a list of numbers. </p> <pre> _.map([1, 2, 3], function(n){ return n * 2; }); _([1, 2, 3]).map(function(n){ return n * 2; });</pre> <p> Calling <tt>chain</tt> will cause all future method calls to return wrapped objects. When you've finished the computation, use <tt>value</tt> to retrieve the final value. Here's an example of chaining together a <b>map/flatten/reduce</b>, in order to get the word count of every word in a song. </p> <pre> var lyrics = [ {line : 1, words : "I'm a lumberjack and I'm okay"}, {line : 2, words : "I sleep all night and I work all day"}, {line : 3, words : "He's a lumberjack and he's okay"}, {line : 4, words : "He sleeps all night and he works all day"} ]; _.chain(lyrics) .map(function(line) { return line.words.split(' '); }) .flatten() .reduce(function(counts, word) { counts[word] = (counts[word] || 0) + 1; return counts; }, {}) .value(); =&gt; {lumberjack : 2, all : 4, night : 2 ... }</pre> <p> In addition, the <a href="path_to_url">Array prototype's methods</a> are proxied through the chained Underscore object, so you can slip a <tt>reverse</tt> or a <tt>push</tt> into your chain, and continue to modify the array. </p> <p id="chain"> <b class="header">chain</b><code>_.chain(obj)</code> <br /> Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until <tt>value</tt> is used. </p> <pre> var stooges = [{name : 'curly', age : 25}, {name : 'moe', age : 21}, {name : 'larry', age : 23}]; var youngest = _.chain(stooges) .sortBy(function(stooge){ return stooge.age; }) .map(function(stooge){ return stooge.name + ' is ' + stooge.age; }) .first() .value(); =&gt; "moe is 21" </pre> <p id="value"> <b class="header">value</b><code>_(obj).value()</code> <br /> Extracts the value of a wrapped object. </p> <pre> _([1, 2, 3]).value(); =&gt; [1, 2, 3] </pre> <h2 id="links">Links &amp; Suggested Reading</h2> <p> The Underscore documentation is also available in <a href="path_to_url">Simplified Chinese</a>. </p> <p> <a href="path_to_url">Underscore.lua</a>, a Lua port of the functions that are applicable in both languages. Includes OOP-wrapping and chaining. (<a href="path_to_url">source</a>) </p> <p> <a href="path_to_url">Underscore.m</a>, an Objective-C port of many of the Underscore.js functions, using a syntax that encourages chaining. (<a href="path_to_url">source</a>) </p> <p> <a href="path_to_url">_.m</a>, an alternative Objective-C port that tries to stick a little closer to the original Underscore.js API. (<a href="path_to_url">source</a>) </p> <p> <a href="path_to_url">Underscore.php</a>, a PHP port of the functions that are applicable in both languages. Includes OOP-wrapping and chaining. (<a href="path_to_url">source</a>) </p> <p> <a href="path_to_url">Underscore-perl</a>, a Perl port of many of the Underscore.js functions, aimed at on Perl hashes and arrays. (<a href="path_to_url">source</a>) </p> <p> <a href="path_to_url">Underscore.cfc</a>, a Coldfusion port of many of the Underscore.js functions. (<a href="path_to_url">source</a>) </p> <p> <a href="path_to_url">Underscore.string</a>, an Underscore extension that adds functions for string-manipulation: <tt>trim</tt>, <tt>startsWith</tt>, <tt>contains</tt>, <tt>capitalize</tt>, <tt>reverse</tt>, <tt>sprintf</tt>, and more. </p> <p> Ruby's <a href="path_to_url">Enumerable</a> module. </p> <p> <a href="path_to_url">Prototype.js</a>, which provides JavaScript with collection functions in the manner closest to Ruby's Enumerable. </p> <p> Oliver Steele's <a href="path_to_url">Functional JavaScript</a>, which includes comprehensive higher-order function support as well as string lambdas. </p> <p> Michael Aufreiter's <a href="path_to_url">Data.js</a>, a data manipulation + persistence library for JavaScript. </p> <p> Python's <a href="path_to_url">itertools</a>. </p> <h2 id="changelog">Change Log</h2> <p> <b class="header">1.4.4</b> &mdash; <small><i>Jan. 30, 2013</i></small> &mdash; <a href="path_to_url">Diff</a><br /> <ul> <li> Added <tt>_.findWhere</tt>, for finding the first element in a list that matches a particular set of keys and values. </li> <li> Added <tt>_.partial</tt>, for partially applying a function <i>without</i> changing its dynamic reference to <tt>this</tt>. </li> <li> Simplified <tt>bind</tt> by removing some edge cases involving constructor functions. In short: don't <tt>_.bind</tt> your constructors. </li> <li> A minor optimization to <tt>invoke</tt>. </li> <li> Fix bug in the minified version due to the minifier incorrectly optimizing-away <tt>isFunction</tt>. </li> </ul> </p> <p> <b class="header">1.4.3</b> &mdash; <small><i>Dec. 4, 2012</i></small> &mdash; <a href="path_to_url">Diff</a><br /> <ul> <li> Improved Underscore compatibility with Adobe's JS engine that can be used to script Illustrator, Photoshop, and friends. </li> <li> Added a default <tt>_.identity</tt> iterator to <tt>countBy</tt> and <tt>groupBy</tt>. </li> <li> The <tt>uniq</tt> function can now take <tt>array, iterator, context</tt> as the argument list. </li> <li> The <tt>times</tt> function now returns the mapped array of iterator results. </li> <li> Simplified and fixed bugs in <tt>throttle</tt>. </li> </ul> </p> <p> <b class="header">1.4.2</b> &mdash; <small><i>Oct. 1, 2012</i></small> &mdash; <a href="path_to_url">Diff</a><br /> <ul> <li> For backwards compatibility, returned to pre-1.4.0 behavior when passing <tt>null</tt> to iteration functions. They now become no-ops again. </li> </ul> </p> <p> <b class="header">1.4.1</b> &mdash; <small><i>Oct. 1, 2012</i></small> &mdash; <a href="path_to_url">Diff</a><br /> <ul> <li> Fixed a 1.4.0 regression in the <tt>lastIndexOf</tt> function. </li> </ul> </p> <p> <b class="header">1.4.0</b> &mdash; <small><i>Sept. 27, 2012</i></small> &mdash; <a href="path_to_url">Diff</a><br /> <ul> <li> Added a <tt>pairs</tt> function, for turning a JavaScript object into <tt>[key, value]</tt> pairs ... as well as an <tt>object</tt> function, for converting an array of <tt>[key, value]</tt> pairs into an object. </li> <li> Added a <tt>countBy</tt> function, for counting the number of objects in a list that match a certain criteria. </li> <li> Added an <tt>invert</tt> function, for performing a simple inversion of the keys and values in an object. </li> <li> Added a <tt>where</tt> function, for easy cases of filtering a list for objects with specific values. </li> <li> Added an <tt>omit</tt> function, for filtering an object to remove certain keys. </li> <li> Added a <tt>random</tt> function, to return a random number in a given range. </li> <li> <tt>_.debounce</tt>'d functions now return their last updated value, just like <tt>_.throttle</tt>'d functions do. </li> <li> The <tt>sortBy</tt> function now runs a stable sort algorithm. </li> <li> Added the optional <tt>fromIndex</tt> option to <tt>indexOf</tt> and <tt>lastIndexOf</tt>. </li> <li> "Sparse" arrays are no longer supported in Underscore iteration functions. Use a <tt>for</tt> loop instead (or better yet, an object). </li> <li> The <tt>min</tt> and <tt>max</tt> functions may now be called on <i>very</i> large arrays. </li> <li> Interpolation in templates now represents <tt>null</tt> and <tt>undefined</tt> as the empty string. </li> <li> <del>Underscore iteration functions no longer accept <tt>null</tt> values as a no-op argument. You'll get an early error instead.</del> </li> <li> A number of edge-cases fixes and tweaks, which you can spot in the <a href="path_to_url">diff</a>. Depending on how you're using Underscore, <b>1.4.0</b> may be more backwards-incompatible than usual &mdash; please test when you upgrade. </li> </ul> </p> <p> <b class="header">1.3.3</b> &mdash; <small><i>April 10, 2012</i></small><br /> <ul> <li> Many improvements to <tt>_.template</tt>, which now provides the <tt>source</tt> of the template function as a property, for potentially even more efficient pre-compilation on the server-side. You may now also set the <tt>variable</tt> option when creating a template, which will cause your passed-in data to be made available under the variable you named, instead of using a <tt>with</tt> statement &mdash; significantly improving the speed of rendering the template. </li> <li> Added the <tt>pick</tt> function, which allows you to filter an object literal with a whitelist of allowed property names. </li> <li> Added the <tt>result</tt> function, for convenience when working with APIs that allow either functions or raw properties. </li> <li> Added the <tt>isFinite</tt> function, because sometimes knowing that a value is a number just ain't quite enough. </li> <li> The <tt>sortBy</tt> function may now also be passed the string name of a property to use as the sort order on each object. </li> <li> Fixed <tt>uniq</tt> to work with sparse arrays. </li> <li> The <tt>difference</tt> function now performs a shallow flatten instead of a deep one when computing array differences. </li> <li> The <tt>debounce</tt> function now takes an <tt>immediate</tt> parameter, which will cause the callback to fire on the leading instead of the trailing edge. </li> </ul> </p> <p> <b class="header">1.3.1</b> &mdash; <small><i>Jan. 23, 2012</i></small><br /> <ul> <li> Added an <tt>_.has</tt> function, as a safer way to use <tt>hasOwnProperty</tt>. </li> <li> Added <tt>_.collect</tt> as an alias for <tt>_.map</tt>. Smalltalkers, rejoice. </li> <li> Reverted an old change so that <tt>_.extend</tt> will correctly copy over keys with undefined values again. </li> <li> Bugfix to stop escaping slashes within interpolations in <tt>_.template</tt>. </li> </ul> </p> <p> <b class="header">1.3.0</b> &mdash; <small><i>Jan. 11, 2012</i></small><br /> <ul> <li> Removed AMD (RequireJS) support from Underscore. If you'd like to use Underscore with RequireJS, you can load it as a normal script, wrap or patch your copy, or download a forked version. </li> </ul> </p> <p> <b class="header">1.2.4</b> &mdash; <small><i>Jan. 4, 2012</i></small><br /> <ul> <li> You now can (and probably should, as it's simpler) write <tt>_.chain(list)</tt> instead of <tt>_(list).chain()</tt>. </li> <li> Fix for escaped characters in Underscore templates, and for supporting customizations of <tt>_.templateSettings</tt> that only define one or two of the required regexes. </li> <li> Fix for passing an array as the first argument to an <tt>_.wrap</tt>'d function. </li> <li> Improved compatibility with ClojureScript, which adds a <tt>call</tt> function to <tt>String.prototype</tt>. </li> </ul> </p> <p> <b class="header">1.2.3</b> &mdash; <small><i>Dec. 7, 2011</i></small><br /> <ul> <li> Dynamic scope is now preserved for compiled <tt>_.template</tt> functions, so you can use the value of <tt>this</tt> if you like. </li> <li> Sparse array support of <tt>_.indexOf</tt>, <tt>_.lastIndexOf</tt>. </li> <li> Both <tt>_.reduce</tt> and <tt>_.reduceRight</tt> can now be passed an explicitly <tt>undefined</tt> value. (There's no reason why you'd want to do this.) </li> </ul> </p> <p> <b class="header">1.2.2</b> &mdash; <small><i>Nov. 14, 2011</i></small><br /> <ul> <li> Continued tweaks to <tt>_.isEqual</tt> semantics. Now JS primitives are considered equivalent to their wrapped versions, and arrays are compared by their numeric properties only <small>(#351)</small>. </li> <li> <tt>_.escape</tt> no longer tries to be smart about not double-escaping already-escaped HTML entities. Now it just escapes regardless <small>(#350)</small>. </li> <li> In <tt>_.template</tt>, you may now leave semicolons out of evaluated statements if you wish: <tt>&lt;% }) %&gt;</tt> <small>(#369)</small>. </li> <li> <tt>_.after(callback, 0)</tt> will now trigger the callback immediately, making "after" easier to use with asynchronous APIs <small>(#366)</small>. </li> </ul> </p> <p> <b class="header">1.2.1</b> &mdash; <small><i>Oct. 24, 2011</i></small><br /> <ul> <li> Several important bug fixes for <tt>_.isEqual</tt>, which should now do better on mutated Arrays, and on non-Array objects with <tt>length</tt> properties. <small>(#329)</small> </li> <li> <b>jrburke</b> contributed Underscore exporting for AMD module loaders, and <b>tonylukasavage</b> for Appcelerator Titanium. <small>(#335, #338)</small> </li> <li> You can now <tt>_.groupBy(list, 'property')</tt> as a shortcut for grouping values by a particular common property. </li> <li> <tt>_.throttle</tt>'d functions now fire immediately upon invocation, and are rate-limited thereafter <small>(#170, #266)</small>. </li> <li> Most of the <tt>_.is[Type]</tt> checks no longer ducktype. </li> <li> The <tt>_.bind</tt> function now also works on constructors, a-la ES5 ... but you would never want to use <tt>_.bind</tt> on a constructor function. </li> <li> <tt>_.clone</tt> no longer wraps non-object types in Objects. </li> <li> <tt>_.find</tt> and <tt>_.filter</tt> are now the preferred names for <tt>_.detect</tt> and <tt>_.select</tt>. </li> </ul> </p> <p> <b class="header">1.2.0</b> &mdash; <small><i>Oct. 5, 2011</i></small><br /> <ul> <li> The <tt>_.isEqual</tt> function now supports true deep equality comparisons, with checks for cyclic structures, thanks to Kit Cambridge. </li> <li> Underscore templates now support HTML escaping interpolations, using <tt>&lt;%- ... %&gt;</tt> syntax. </li> <li> Ryan Tenney contributed <tt>_.shuffle</tt>, which uses a modified Fisher-Yates to give you a shuffled copy of an array. </li> <li> <tt>_.uniq</tt> can now be passed an optional iterator, to determine by what criteria an object should be considered unique. </li> <li> <tt>_.last</tt> now takes an optional argument which will return the last N elements of the list. </li> <li> A new <tt>_.initial</tt> function was added, as a mirror of <tt>_.rest</tt>, which returns all the initial values of a list (except the last N). </li> </ul> </p> <p> <b class="header">1.1.7</b> &mdash; <small><i>July 13, 2011</i></small><br /> Added <tt>_.groupBy</tt>, which aggregates a collection into groups of like items. Added <tt>_.union</tt> and <tt>_.difference</tt>, to complement the (re-named) <tt>_.intersection</tt>. Various improvements for support of sparse arrays. <tt>_.toArray</tt> now returns a clone, if directly passed an array. <tt>_.functions</tt> now also returns the names of functions that are present in the prototype chain. </p> <p> <b class="header">1.1.6</b> &mdash; <small><i>April 18, 2011</i></small><br /> Added <tt>_.after</tt>, which will return a function that only runs after first being called a specified number of times. <tt>_.invoke</tt> can now take a direct function reference. <tt>_.every</tt> now requires an iterator function to be passed, which mirrors the ECMA5 API. <tt>_.extend</tt> no longer copies keys when the value is undefined. <tt>_.bind</tt> now errors when trying to bind an undefined value. </p> <p> <b class="header">1.1.5</b> &mdash; <small><i>Mar 20, 2011</i></small><br /> Added an <tt>_.defaults</tt> function, for use merging together JS objects representing default options. Added an <tt>_.once</tt> function, for manufacturing functions that should only ever execute a single time. <tt>_.bind</tt> now delegates to the native ECMAScript 5 version, where available. <tt>_.keys</tt> now throws an error when used on non-Object values, as in ECMAScript 5. Fixed a bug with <tt>_.keys</tt> when used over sparse arrays. </p> <p> <b class="header">1.1.4</b> &mdash; <small><i>Jan 9, 2011</i></small><br /> Improved compliance with ES5's Array methods when passing <tt>null</tt> as a value. <tt>_.wrap</tt> now correctly sets <tt>this</tt> for the wrapped function. <tt>_.indexOf</tt> now takes an optional flag for finding the insertion index in an array that is guaranteed to already be sorted. Avoiding the use of <tt>.callee</tt>, to allow <tt>_.isArray</tt> to work properly in ES5's strict mode. </p> <p> <b class="header">1.1.3</b> &mdash; <small><i>Dec 1, 2010</i></small><br /> In CommonJS, Underscore may now be required with just: <br /> <tt>var _ = require("underscore")</tt>. Added <tt>_.throttle</tt> and <tt>_.debounce</tt> functions. Removed <tt>_.breakLoop</tt>, in favor of an ECMA5-style un-<i>break</i>-able each implementation &mdash; this removes the try/catch, and you'll now have better stack traces for exceptions that are thrown within an Underscore iterator. Improved the <b>isType</b> family of functions for better interoperability with Internet Explorer host objects. <tt>_.template</tt> now correctly escapes backslashes in templates. Improved <tt>_.reduce</tt> compatibility with the ECMA5 version: if you don't pass an initial value, the first item in the collection is used. <tt>_.each</tt> no longer returns the iterated collection, for improved consistency with ES5's <tt>forEach</tt>. </p> <p> <b class="header">1.1.2</b><br /> Fixed <tt>_.contains</tt>, which was mistakenly pointing at <tt>_.intersect</tt> instead of <tt>_.include</tt>, like it should have been. Added <tt>_.unique</tt> as an alias for <tt>_.uniq</tt>. </p> <p> <b class="header">1.1.1</b><br /> Improved the speed of <tt>_.template</tt>, and its handling of multiline interpolations. Ryan Tenney contributed optimizations to many Underscore functions. An annotated version of the source code is now available. </p> <p> <b class="header">1.1.0</b><br /> The method signature of <tt>_.reduce</tt> has been changed to match the ECMAScript 5 signature, instead of the Ruby/Prototype.js version. This is a backwards-incompatible change. <tt>_.template</tt> may now be called with no arguments, and preserves whitespace. <tt>_.contains</tt> is a new alias for <tt>_.include</tt>. </p> <p> <b class="header">1.0.4</b><br /> <a href="path_to_url">Andri Mll</a> contributed the <tt>_.memoize</tt> function, which can be used to speed up expensive repeated computations by caching the results. </p> <p> <b class="header">1.0.3</b><br /> Patch that makes <tt>_.isEqual</tt> return <tt>false</tt> if any property of the compared object has a <tt>NaN</tt> value. Technically the correct thing to do, but of questionable semantics. Watch out for NaN comparisons. </p> <p> <b class="header">1.0.2</b><br /> Fixes <tt>_.isArguments</tt> in recent versions of Opera, which have arguments objects as real Arrays. </p> <p> <b class="header">1.0.1</b><br /> Bugfix for <tt>_.isEqual</tt>, when comparing two objects with the same number of undefined keys, but with different names. </p> <p> <b class="header">1.0.0</b><br /> Things have been stable for many months now, so Underscore is now considered to be out of beta, at <b>1.0</b>. Improvements since <b>0.6</b> include <tt>_.isBoolean</tt>, and the ability to have <tt>_.extend</tt> take multiple source objects. </p> <p> <b class="header">0.6.0</b><br /> Major release. Incorporates a number of <a href="path_to_url">Mile Frawley's</a> refactors for safer duck-typing on collection functions, and cleaner internals. A new <tt>_.mixin</tt> method that allows you to extend Underscore with utility functions of your own. Added <tt>_.times</tt>, which works the same as in Ruby or Prototype.js. Native support for ECMAScript 5's <tt>Array.isArray</tt>, and <tt>Object.keys</tt>. </p> <p> <b class="header">0.5.8</b><br /> Fixed Underscore's collection functions to work on <a href="path_to_url">NodeLists</a> and <a href="path_to_url">HTMLCollections</a> once more, thanks to <a href="path_to_url">Justin Tulloss</a>. </p> <p> <b class="header">0.5.7</b><br /> A safer implementation of <tt>_.isArguments</tt>, and a faster <tt>_.isNumber</tt>,<br />thanks to <a href="path_to_url">Jed Schmidt</a>. </p> <p> <b class="header">0.5.6</b><br /> Customizable delimiters for <tt>_.template</tt>, contributed by <a href="path_to_url">Noah Sloan</a>. </p> <p> <b class="header">0.5.5</b><br /> Fix for a bug in MobileSafari's OOP-wrapper, with the arguments object. </p> <p> <b class="header">0.5.4</b><br /> Fix for multiple single quotes within a template string for <tt>_.template</tt>. See: <a href="path_to_url">Rick Strahl's blog post</a>. </p> <p> <b class="header">0.5.2</b><br /> New implementations of <tt>isArray</tt>, <tt>isDate</tt>, <tt>isFunction</tt>, <tt>isNumber</tt>, <tt>isRegExp</tt>, and <tt>isString</tt>, thanks to a suggestion from <a href="path_to_url">Robert Kieffer</a>. Instead of doing <tt>Object#toString</tt> comparisons, they now check for expected properties, which is less safe, but more than an order of magnitude faster. Most other Underscore functions saw minor speed improvements as a result. <a href="path_to_url">Evgeniy Dolzhenko</a> contributed <tt>_.tap</tt>, <a href="path_to_url#M000191">similar to Ruby 1.9's</a>, which is handy for injecting side effects (like logging) into chained calls. </p> <p> <b class="header">0.5.1</b><br /> Added an <tt>_.isArguments</tt> function. Lots of little safety checks and optimizations contributed by <a href="path_to_url">Noah Sloan</a> and <a href="path_to_url">Andri Mll</a>. </p> <p> <b class="header">0.5.0</b><br /> <b>[API Changes]</b> <tt>_.bindAll</tt> now takes the context object as its first parameter. If no method names are passed, all of the context object's methods are bound to it, enabling chaining and easier binding. <tt>_.functions</tt> now takes a single argument and returns the names of its Function properties. Calling <tt>_.functions(_)</tt> will get you the previous behavior. Added <tt>_.isRegExp</tt> so that <tt>isEqual</tt> can now test for RegExp equality. All of the "is" functions have been shrunk down into a single definition. <a href="path_to_url">Karl Guertin</a> contributed patches. </p> <p> <b class="header">0.4.7</b><br /> Added <tt>isDate</tt>, <tt>isNaN</tt>, and <tt>isNull</tt>, for completeness. Optimizations for <tt>isEqual</tt> when checking equality between Arrays or Dates. <tt>_.keys</tt> is now <small><i><b>25%&ndash;2X</b></i></small> faster (depending on your browser) which speeds up the functions that rely on it, such as <tt>_.each</tt>. </p> <p> <b class="header">0.4.6</b><br /> Added the <tt>range</tt> function, a port of the <a href="path_to_url#range">Python function of the same name</a>, for generating flexibly-numbered lists of integers. Original patch contributed by <a href="path_to_url">Kirill Ishanov</a>. </p> <p> <b class="header">0.4.5</b><br /> Added <tt>rest</tt> for Arrays and arguments objects, and aliased <tt>first</tt> as <tt>head</tt>, and <tt>rest</tt> as <tt>tail</tt>, thanks to <a href="path_to_url">Luke Sutton</a>'s patches. Added tests ensuring that all Underscore Array functions also work on <i>arguments</i> objects. </p> <p> <b class="header">0.4.4</b><br /> Added <tt>isString</tt>, and <tt>isNumber</tt>, for consistency. Fixed <tt>_.isEqual(NaN, NaN)</tt> to return <i>true</i> (which is debatable). </p> <p> <b class="header">0.4.3</b><br /> Started using the native <tt>StopIteration</tt> object in browsers that support it. Fixed Underscore setup for CommonJS environments. </p> <p> <b class="header">0.4.2</b><br /> Renamed the unwrapping function to <tt>value</tt>, for clarity. </p> <p> <b class="header">0.4.1</b><br /> Chained Underscore objects now support the Array prototype methods, so that you can perform the full range of operations on a wrapped array without having to break your chain. Added a <tt>breakLoop</tt> method to <b>break</b> in the middle of any Underscore iteration. Added an <tt>isEmpty</tt> function that works on arrays and objects. </p> <p> <b class="header">0.4.0</b><br /> All Underscore functions can now be called in an object-oriented style, like so: <tt>_([1, 2, 3]).map(...);</tt>. Original patch provided by <a href="path_to_url">Marc-Andr Cournoyer</a>. Wrapped objects can be chained through multiple method invocations. A <a href="#object-functions"><tt>functions</tt></a> method was added, providing a sorted list of all the functions in Underscore. </p> <p> <b class="header">0.3.3</b><br /> Added the JavaScript 1.8 function <tt>reduceRight</tt>. Aliased it as <tt>foldr</tt>, and aliased <tt>reduce</tt> as <tt>foldl</tt>. </p> <p> <b class="header">0.3.2</b><br /> Now runs on stock <a href="path_to_url">Rhino</a> interpreters with: <tt>load("underscore.js")</tt>. Added <a href="#identity"><tt>identity</tt></a> as a utility function. </p> <p> <b class="header">0.3.1</b><br /> All iterators are now passed in the original collection as their third argument, the same as JavaScript 1.6's <b>forEach</b>. Iterating over objects is now called with <tt>(value, key, collection)</tt>, for details see <a href="#each"><tt>_.each</tt></a>. </p> <p> <b class="header">0.3.0</b><br /> Added <a href="path_to_url">Dmitry Baranovskiy</a>'s comprehensive optimizations, merged in <a href="path_to_url">Kris Kowal</a>'s patches to make Underscore <a href="path_to_url">CommonJS</a> and <a href="path_to_url">Narwhal</a> compliant. </p> <p> <b class="header">0.2.0</b><br /> Added <tt>compose</tt> and <tt>lastIndexOf</tt>, renamed <tt>inject</tt> to <tt>reduce</tt>, added aliases for <tt>inject</tt>, <tt>filter</tt>, <tt>every</tt>, <tt>some</tt>, and <tt>forEach</tt>. </p> <p> <b class="header">0.1.1</b><br /> Added <tt>noConflict</tt>, so that the "Underscore" object can be assigned to other variables. </p> <p> <b class="header">0.1.0</b><br /> Initial release of Underscore.js. </p> <p> <a href="path_to_url" title="A DocumentCloud Project" style="background:none;"> <img src="path_to_url" alt="A DocumentCloud Project" /> </a> </p> </div> </div> <!-- Include Underscore, so you can play with it in the console. --> <script type="text/javascript" src="underscore.js"></script> </body> </html> ```
/content/code_sandbox/node_modules/underscore/index.html
html
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
26,089
```javascript var path = require('path'); var fs = require('fs'); var _0777 = parseInt('0777', 8); module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; function mkdirP (p, opts, f, made) { if (typeof opts === 'function') { f = opts; opts = {}; } else if (!opts || typeof opts !== 'object') { opts = { mode: opts }; } var mode = opts.mode; var xfs = opts.fs || fs; if (mode === undefined) { mode = _0777 } if (!made) made = null; var cb = f || /* istanbul ignore next */ function () {}; p = path.resolve(p); xfs.mkdir(p, mode, function (er) { if (!er) { made = made || p; return cb(null, made); } switch (er.code) { case 'ENOENT': /* istanbul ignore if */ if (path.dirname(p) === p) return cb(er); mkdirP(path.dirname(p), opts, function (er, made) { /* istanbul ignore if */ if (er) cb(er, made); else mkdirP(p, opts, cb, made); }); break; // In the case of any other error, just see if there's a dir // there already. If so, then hooray! If not, then something // is borked. default: xfs.stat(p, function (er2, stat) { // if the stat fails, then that's super weird. // let the original error be the failure reason. if (er2 || !stat.isDirectory()) cb(er, made) else cb(null, made); }); break; } }); } mkdirP.sync = function sync (p, opts, made) { if (!opts || typeof opts !== 'object') { opts = { mode: opts }; } var mode = opts.mode; var xfs = opts.fs || fs; if (mode === undefined) { mode = _0777 } if (!made) made = null; p = path.resolve(p); try { xfs.mkdirSync(p, mode); made = made || p; } catch (err0) { switch (err0.code) { case 'ENOENT' : made = sync(path.dirname(p), opts, made); sync(p, opts, made); break; // In the case of any other error, just see if there's a dir // there already. If so, then hooray! If not, then something // is borked. default: var stat; try { stat = xfs.statSync(p); } catch (err1) /* istanbul ignore next */ { throw err0; } /* istanbul ignore if */ if (!stat.isDirectory()) throw err0; break; } } return made; }; ```
/content/code_sandbox/node_modules/mkdirp/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
683
```markdown # mkdirp Like `mkdir -p`, but in node.js! [![build status](path_to_url # example ## pow.js ```js var mkdirp = require('mkdirp'); mkdirp('/tmp/foo/bar/baz', function (err) { if (err) console.error(err) else console.log('pow!') }); ``` Output ``` pow! ``` And now /tmp/foo/bar/baz exists, huzzah! # methods ```js var mkdirp = require('mkdirp'); ``` ## mkdirp(dir, opts, cb) Create a new directory and any necessary subdirectories at `dir` with octal permission string `opts.mode`. If `opts` is a non-object, it will be treated as the `opts.mode`. If `opts.mode` isn't specified, it defaults to `0777`. `cb(err, made)` fires with the error or the first directory `made` that had to be created, if any. You can optionally pass in an alternate `fs` implementation by passing in `opts.fs`. Your implementation should have `opts.fs.mkdir(path, mode, cb)` and `opts.fs.stat(path, cb)`. ## mkdirp.sync(dir, opts) Synchronously create a new directory and any necessary subdirectories at `dir` with octal permission string `opts.mode`. If `opts` is a non-object, it will be treated as the `opts.mode`. If `opts.mode` isn't specified, it defaults to `0777`. Returns the first directory that had to be created, if any. You can optionally pass in an alternate `fs` implementation by passing in `opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and `opts.fs.statSync(path)`. # usage This package also ships with a `mkdirp` command. ``` usage: mkdirp [DIR1,DIR2..] {OPTIONS} Create each supplied directory including any necessary parent directories that don't yet exist. If the directory already exists, do nothing. OPTIONS are: -m, --mode If a directory needs to be created, set the mode as an octal permission string. ``` # install With [npm](path_to_url do: ``` npm install mkdirp ``` to get the library, or ``` npm install -g mkdirp ``` to get the command. # license MIT ```
/content/code_sandbox/node_modules/mkdirp/readme.markdown
markdown
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
521
```javascript /** * * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /*global exports:true*/ /** * Desugars ES6 Arrow functions to ES3 function expressions. * If the function contains `this` expression -- automatically * binds the funciton to current value of `this`. * * Single parameter, simple expression: * * [1, 2, 3].map(x => x * x); * * [1, 2, 3].map(function(x) { return x * x; }); * * Several parameters, complex block: * * this.users.forEach((user, idx) => { * return this.isActive(idx) && this.send(user); * }); * * this.users.forEach(function(user, idx) { * return this.isActive(idx) && this.send(user); * }.bind(this)); * */ var restParamVisitors = require('./es6-rest-param-visitors'); var Syntax = require('esprima-fb').Syntax; var utils = require('../src/utils'); /** * @public */ function visitArrowFunction(traverse, node, path, state) { // Prologue. utils.append('function', state); renderParams(node, state); // Skip arrow. utils.catchupWhiteSpace(node.body.range[0], state); var renderBody = node.body.type == Syntax.BlockStatement ? renderStatementBody : renderExpressionBody; path.unshift(node); renderBody(traverse, node, path, state); path.shift(); // Bind the function only if `this` value is used // inside it or inside any sub-expression. if (utils.containsChildOfType(node.body, Syntax.ThisExpression)) { utils.append('.bind(this)', state); } return false; } function renderParams(node, state) { // To preserve inline typechecking directives, we // distinguish between parens-free and paranthesized single param. if (isParensFreeSingleParam(node, state) || !node.params.length) { utils.append('(', state); } if (node.params.length !== 0) { utils.catchup(node.params[node.params.length - 1].range[1], state); } utils.append(')', state); } function isParensFreeSingleParam(node, state) { return node.params.length === 1 && state.g.source[state.g.position] !== '('; } function renderExpressionBody(traverse, node, path, state) { // Wrap simple expression bodies into a block // with explicit return statement. utils.append('{', state); if (node.rest) { utils.append( restParamVisitors.renderRestParamSetup(node), state ); } utils.append('return ', state); renderStatementBody(traverse, node, path, state); utils.append(';}', state); } function renderStatementBody(traverse, node, path, state) { traverse(node.body, path, state); utils.catchup(node.body.range[1], state); } visitArrowFunction.test = function(node, path, state) { return node.type === Syntax.ArrowFunctionExpression; }; exports.visitorList = [ visitArrowFunction ]; ```
/content/code_sandbox/node_modules/jstransform/visitors/es6-arrow-function-visitors.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
695
```javascript /** * * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /*jslint node:true*/ /** * @typechecks */ 'use strict'; var Syntax = require('esprima-fb').Syntax; var utils = require('../src/utils'); /** * path_to_url~jorendorff/es6-draft.html#sec-12.1.9 */ function visitTemplateLiteral(traverse, node, path, state) { var templateElements = node.quasis; utils.append('(', state); for (var ii = 0; ii < templateElements.length; ii++) { var templateElement = templateElements[ii]; if (templateElement.value.raw !== '') { utils.append(getCookedValue(templateElement), state); if (!templateElement.tail) { // + between element and substitution utils.append(' + ', state); } // maintain line numbers utils.move(templateElement.range[0], state); utils.catchupNewlines(templateElement.range[1], state); } utils.move(templateElement.range[1], state); if (!templateElement.tail) { var substitution = node.expressions[ii]; if (substitution.type === Syntax.Identifier || substitution.type === Syntax.MemberExpression || substitution.type === Syntax.CallExpression) { utils.catchup(substitution.range[1], state); } else { utils.append('(', state); traverse(substitution, path, state); utils.catchup(substitution.range[1], state); utils.append(')', state); } // if next templateElement isn't empty... if (templateElements[ii + 1].value.cooked !== '') { utils.append(' + ', state); } } } utils.move(node.range[1], state); utils.append(')', state); return false; } visitTemplateLiteral.test = function(node, path, state) { return node.type === Syntax.TemplateLiteral; }; /** * path_to_url~jorendorff/es6-draft.html#sec-12.2.6 */ function visitTaggedTemplateExpression(traverse, node, path, state) { var template = node.quasi; var numQuasis = template.quasis.length; // print the tag utils.move(node.tag.range[0], state); traverse(node.tag, path, state); utils.catchup(node.tag.range[1], state); // print array of template elements utils.append('(function() { var siteObj = [', state); for (var ii = 0; ii < numQuasis; ii++) { utils.append(getCookedValue(template.quasis[ii]), state); if (ii !== numQuasis - 1) { utils.append(', ', state); } } utils.append(']; siteObj.raw = [', state); for (ii = 0; ii < numQuasis; ii++) { utils.append(getRawValue(template.quasis[ii]), state); if (ii !== numQuasis - 1) { utils.append(', ', state); } } utils.append( ']; Object.freeze(siteObj.raw); Object.freeze(siteObj); return siteObj; }()', state ); // print substitutions if (numQuasis > 1) { for (ii = 0; ii < template.expressions.length; ii++) { var expression = template.expressions[ii]; utils.append(', ', state); // maintain line numbers by calling catchupWhiteSpace over the whole // previous TemplateElement utils.move(template.quasis[ii].range[0], state); utils.catchupNewlines(template.quasis[ii].range[1], state); utils.move(expression.range[0], state); traverse(expression, path, state); utils.catchup(expression.range[1], state); } } // print blank lines to push the closing ) down to account for the final // TemplateElement. utils.catchupNewlines(node.range[1], state); utils.append(')', state); return false; } visitTaggedTemplateExpression.test = function(node, path, state) { return node.type === Syntax.TaggedTemplateExpression; }; function getCookedValue(templateElement) { return JSON.stringify(templateElement.value.cooked); } function getRawValue(templateElement) { return JSON.stringify(templateElement.value.raw); } exports.visitorList = [ visitTemplateLiteral, visitTaggedTemplateExpression ]; ```
/content/code_sandbox/node_modules/jstransform/visitors/es6-template-visitors.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
975
```javascript /** * * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /*jslint node: true*/ /** * Desugars ES6 Object Literal short notations into ES3 full notation. * * // Easier return values. * function foo(x, y) { * return {x, y}; // {x: x, y: y} * }; * * // Destrucruting. * function init({port, ip, coords: {x, y}}) { ... } * */ var Syntax = require('esprima-fb').Syntax; var utils = require('../src/utils'); /** * @public */ function visitObjectLiteralShortNotation(traverse, node, path, state) { utils.catchup(node.key.range[1], state); utils.append(':' + node.key.name, state); return false; } visitObjectLiteralShortNotation.test = function(node, path, state) { return node.type === Syntax.Property && node.kind === 'init' && node.shorthand === true; }; exports.visitorList = [ visitObjectLiteralShortNotation ]; ```
/content/code_sandbox/node_modules/jstransform/visitors/es6-object-short-notation-visitors.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
258