code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
module.exports = PrivateKey; var assert = require('assert-plus'); var Buffer = require('safer-buffer').Buffer; var algs = require('sshpk/lib/algs'); var crypto = require('crypto'); var Fingerprint = require('sshpk/lib/fingerprint'); var Signature = require('sshpk/lib/signature'); var errs = require('sshpk/lib/errors'); var util = require('util'); var utils = require('sshpk/lib/utils'); var dhe = require('sshpk/lib/dhe'); var generateECDSA = dhe.generateECDSA; var generateED25519 = dhe.generateED25519; var edCompat = require('sshpk/lib/ed-compat'); var nacl = require('tweetnacl'); var Key = require('sshpk/lib/key'); var InvalidAlgorithmError = errs.InvalidAlgorithmError; var KeyParseError = errs.KeyParseError; var KeyEncryptedError = errs.KeyEncryptedError; var formats = {}; formats['auto'] = require('sshpk/lib/formats/auto'); formats['pem'] = require('sshpk/lib/formats/pem'); formats['pkcs1'] = require('sshpk/lib/formats/pkcs1'); formats['pkcs8'] = require('sshpk/lib/formats/pkcs8'); formats['rfc4253'] = require('sshpk/lib/formats/rfc4253'); formats['ssh-private'] = require('sshpk/lib/formats/ssh-private'); formats['openssh'] = formats['ssh-private']; formats['ssh'] = formats['ssh-private']; formats['dnssec'] = require('sshpk/lib/formats/dnssec'); function PrivateKey(opts) { assert.object(opts, 'options'); Key.call(this, opts); this._pubCache = undefined; } util.inherits(PrivateKey, Key); PrivateKey.formats = formats; PrivateKey.prototype.toBuffer = function (format, options) { if (format === undefined) format = 'pkcs1'; assert.string(format, 'format'); assert.object(formats[format], 'formats[format]'); assert.optionalObject(options, 'options'); return (formats[format].write(this, options)); }; PrivateKey.prototype.hash = function (algo, type) { return (this.toPublic().hash(algo, type)); }; PrivateKey.prototype.fingerprint = function (algo, type) { return (this.toPublic().fingerprint(algo, type)); }; PrivateKey.prototype.toPublic = function () { if (this._pubCache) return (this._pubCache); var algInfo = algs.info[this.type]; var pubParts = []; for (var i = 0; i < algInfo.parts.length; ++i) { var p = algInfo.parts[i]; pubParts.push(this.part[p]); } this._pubCache = new Key({ type: this.type, source: this, parts: pubParts }); if (this.comment) this._pubCache.comment = this.comment; return (this._pubCache); }; PrivateKey.prototype.derive = function (newType) { assert.string(newType, 'type'); var priv, pub, pair; if (this.type === 'ed25519' && newType === 'curve25519') { priv = this.part.k.data; if (priv[0] === 0x00) priv = priv.slice(1); pair = nacl.box.keyPair.fromSecretKey(new Uint8Array(priv)); pub = Buffer.from(pair.publicKey); return (new PrivateKey({ type: 'curve25519', parts: [ { name: 'A', data: utils.mpNormalize(pub) }, { name: 'k', data: utils.mpNormalize(priv) } ] })); } else if (this.type === 'curve25519' && newType === 'ed25519') { priv = this.part.k.data; if (priv[0] === 0x00) priv = priv.slice(1); pair = nacl.sign.keyPair.fromSeed(new Uint8Array(priv)); pub = Buffer.from(pair.publicKey); return (new PrivateKey({ type: 'ed25519', parts: [ { name: 'A', data: utils.mpNormalize(pub) }, { name: 'k', data: utils.mpNormalize(priv) } ] })); } throw (new Error('Key derivation not supported from ' + this.type + ' to ' + newType)); }; PrivateKey.prototype.createVerify = function (hashAlgo) { return (this.toPublic().createVerify(hashAlgo)); }; PrivateKey.prototype.createSign = function (hashAlgo) { if (hashAlgo === undefined) hashAlgo = this.defaultHashAlgorithm(); assert.string(hashAlgo, 'hash algorithm'); /* ED25519 is not supported by OpenSSL, use a javascript impl. */ if (this.type === 'ed25519' && edCompat !== undefined) return (new edCompat.Signer(this, hashAlgo)); if (this.type === 'curve25519') throw (new Error('Curve25519 keys are not suitable for ' + 'signing or verification')); var v, nm, err; try { nm = hashAlgo.toUpperCase(); v = crypto.createSign(nm); } catch (e) { err = e; } if (v === undefined || (err instanceof Error && err.message.match(/Unknown message digest/))) { nm = 'RSA-'; nm += hashAlgo.toUpperCase(); v = crypto.createSign(nm); } assert.ok(v, 'failed to create verifier'); var oldSign = v.sign.bind(v); var key = this.toBuffer('pkcs1'); var type = this.type; var curve = this.curve; v.sign = function () { var sig = oldSign(key); if (typeof (sig) === 'string') sig = Buffer.from(sig, 'binary'); sig = Signature.parse(sig, type, 'asn1'); sig.hashAlgorithm = hashAlgo; sig.curve = curve; return (sig); }; return (v); }; PrivateKey.parse = function (data, format, options) { if (typeof (data) !== 'string') assert.buffer(data, 'data'); if (format === undefined) format = 'auto'; assert.string(format, 'format'); if (typeof (options) === 'string') options = { filename: options }; assert.optionalObject(options, 'options'); if (options === undefined) options = {}; assert.optionalString(options.filename, 'options.filename'); if (options.filename === undefined) options.filename = '(unnamed)'; assert.object(formats[format], 'formats[format]'); try { var k = formats[format].read(data, options); assert.ok(k instanceof PrivateKey, 'key is not a private key'); if (!k.comment) k.comment = options.filename; return (k); } catch (e) { if (e.name === 'KeyEncryptedError') throw (e); throw (new KeyParseError(options.filename, format, e)); } }; PrivateKey.isPrivateKey = function (obj, ver) { return (utils.isCompatible(obj, PrivateKey, ver)); }; PrivateKey.generate = function (type, options) { if (options === undefined) options = {}; assert.object(options, 'options'); switch (type) { case 'ecdsa': if (options.curve === undefined) options.curve = 'nistp256'; assert.string(options.curve, 'options.curve'); return (generateECDSA(options.curve)); case 'ed25519': return (generateED25519()); default: throw (new Error('Key generation not supported with key ' + 'type "' + type + '"')); } }; /* * API versions for PrivateKey: * [1,0] -- initial ver * [1,1] -- added auto, pkcs[18], openssh/ssh-private formats * [1,2] -- added defaultHashAlgorithm * [1,3] -- added derive, ed, createDH * [1,4] -- first tagged version * [1,5] -- changed ed25519 part names and format * [1,6] -- type arguments for hash() and fingerprint() */ PrivateKey.prototype._sshpkApiVersion = [1, 6]; PrivateKey._oldVersionDetect = function (obj) { assert.func(obj.toPublic); assert.func(obj.createSign); if (obj.derive) return ([1, 3]); if (obj.defaultHashAlgorithm) return ([1, 2]); if (obj.formats['auto']) return ([1, 1]); return ([1, 0]); };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/private-key.js
private-key.js
module.exports = SSHBuffer; var assert = require('assert-plus'); var Buffer = require('safer-buffer').Buffer; function SSHBuffer(opts) { assert.object(opts, 'options'); if (opts.buffer !== undefined) assert.buffer(opts.buffer, 'options.buffer'); this._size = opts.buffer ? opts.buffer.length : 1024; this._buffer = opts.buffer || Buffer.alloc(this._size); this._offset = 0; } SSHBuffer.prototype.toBuffer = function () { return (this._buffer.slice(0, this._offset)); }; SSHBuffer.prototype.atEnd = function () { return (this._offset >= this._buffer.length); }; SSHBuffer.prototype.remainder = function () { return (this._buffer.slice(this._offset)); }; SSHBuffer.prototype.skip = function (n) { this._offset += n; }; SSHBuffer.prototype.expand = function () { this._size *= 2; var buf = Buffer.alloc(this._size); this._buffer.copy(buf, 0); this._buffer = buf; }; SSHBuffer.prototype.readPart = function () { return ({data: this.readBuffer()}); }; SSHBuffer.prototype.readBuffer = function () { var len = this._buffer.readUInt32BE(this._offset); this._offset += 4; assert.ok(this._offset + len <= this._buffer.length, 'length out of bounds at +0x' + this._offset.toString(16) + ' (data truncated?)'); var buf = this._buffer.slice(this._offset, this._offset + len); this._offset += len; return (buf); }; SSHBuffer.prototype.readString = function () { return (this.readBuffer().toString()); }; SSHBuffer.prototype.readCString = function () { var offset = this._offset; while (offset < this._buffer.length && this._buffer[offset] !== 0x00) offset++; assert.ok(offset < this._buffer.length, 'c string does not terminate'); var str = this._buffer.slice(this._offset, offset).toString(); this._offset = offset + 1; return (str); }; SSHBuffer.prototype.readInt = function () { var v = this._buffer.readUInt32BE(this._offset); this._offset += 4; return (v); }; SSHBuffer.prototype.readInt64 = function () { assert.ok(this._offset + 8 < this._buffer.length, 'buffer not long enough to read Int64'); var v = this._buffer.slice(this._offset, this._offset + 8); this._offset += 8; return (v); }; SSHBuffer.prototype.readChar = function () { var v = this._buffer[this._offset++]; return (v); }; SSHBuffer.prototype.writeBuffer = function (buf) { while (this._offset + 4 + buf.length > this._size) this.expand(); this._buffer.writeUInt32BE(buf.length, this._offset); this._offset += 4; buf.copy(this._buffer, this._offset); this._offset += buf.length; }; SSHBuffer.prototype.writeString = function (str) { this.writeBuffer(Buffer.from(str, 'utf8')); }; SSHBuffer.prototype.writeCString = function (str) { while (this._offset + 1 + str.length > this._size) this.expand(); this._buffer.write(str, this._offset); this._offset += str.length; this._buffer[this._offset++] = 0; }; SSHBuffer.prototype.writeInt = function (v) { while (this._offset + 4 > this._size) this.expand(); this._buffer.writeUInt32BE(v, this._offset); this._offset += 4; }; SSHBuffer.prototype.writeInt64 = function (v) { assert.buffer(v, 'value'); if (v.length > 8) { var lead = v.slice(0, v.length - 8); for (var i = 0; i < lead.length; ++i) { assert.strictEqual(lead[i], 0, 'must fit in 64 bits of precision'); } v = v.slice(v.length - 8, v.length); } while (this._offset + 8 > this._size) this.expand(); v.copy(this._buffer, this._offset); this._offset += 8; }; SSHBuffer.prototype.writeChar = function (v) { while (this._offset + 1 > this._size) this.expand(); this._buffer[this._offset++] = v; }; SSHBuffer.prototype.writePart = function (p) { this.writeBuffer(p.data); }; SSHBuffer.prototype.write = function (buf) { while (this._offset + buf.length > this._size) this.expand(); buf.copy(this._buffer, this._offset); this._offset += buf.length; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/ssh-buffer.js
ssh-buffer.js
module.exports = Certificate; var assert = require('assert-plus'); var Buffer = require('safer-buffer').Buffer; var algs = require('sshpk/lib/algs'); var crypto = require('crypto'); var Fingerprint = require('sshpk/lib/fingerprint'); var Signature = require('sshpk/lib/signature'); var errs = require('sshpk/lib/errors'); var util = require('util'); var utils = require('sshpk/lib/utils'); var Key = require('sshpk/lib/key'); var PrivateKey = require('sshpk/lib/private-key'); var Identity = require('sshpk/lib/identity'); var formats = {}; formats['openssh'] = require('sshpk/lib/formats/openssh-cert'); formats['x509'] = require('sshpk/lib/formats/x509'); formats['pem'] = require('sshpk/lib/formats/x509-pem'); var CertificateParseError = errs.CertificateParseError; var InvalidAlgorithmError = errs.InvalidAlgorithmError; function Certificate(opts) { assert.object(opts, 'options'); assert.arrayOfObject(opts.subjects, 'options.subjects'); utils.assertCompatible(opts.subjects[0], Identity, [1, 0], 'options.subjects'); utils.assertCompatible(opts.subjectKey, Key, [1, 0], 'options.subjectKey'); utils.assertCompatible(opts.issuer, Identity, [1, 0], 'options.issuer'); if (opts.issuerKey !== undefined) { utils.assertCompatible(opts.issuerKey, Key, [1, 0], 'options.issuerKey'); } assert.object(opts.signatures, 'options.signatures'); assert.buffer(opts.serial, 'options.serial'); assert.date(opts.validFrom, 'options.validFrom'); assert.date(opts.validUntil, 'optons.validUntil'); assert.optionalArrayOfString(opts.purposes, 'options.purposes'); this._hashCache = {}; this.subjects = opts.subjects; this.issuer = opts.issuer; this.subjectKey = opts.subjectKey; this.issuerKey = opts.issuerKey; this.signatures = opts.signatures; this.serial = opts.serial; this.validFrom = opts.validFrom; this.validUntil = opts.validUntil; this.purposes = opts.purposes; } Certificate.formats = formats; Certificate.prototype.toBuffer = function (format, options) { if (format === undefined) format = 'x509'; assert.string(format, 'format'); assert.object(formats[format], 'formats[format]'); assert.optionalObject(options, 'options'); return (formats[format].write(this, options)); }; Certificate.prototype.toString = function (format, options) { if (format === undefined) format = 'pem'; return (this.toBuffer(format, options).toString()); }; Certificate.prototype.fingerprint = function (algo) { if (algo === undefined) algo = 'sha256'; assert.string(algo, 'algorithm'); var opts = { type: 'certificate', hash: this.hash(algo), algorithm: algo }; return (new Fingerprint(opts)); }; Certificate.prototype.hash = function (algo) { assert.string(algo, 'algorithm'); algo = algo.toLowerCase(); if (algs.hashAlgs[algo] === undefined) throw (new InvalidAlgorithmError(algo)); if (this._hashCache[algo]) return (this._hashCache[algo]); var hash = crypto.createHash(algo). update(this.toBuffer('x509')).digest(); this._hashCache[algo] = hash; return (hash); }; Certificate.prototype.isExpired = function (when) { if (when === undefined) when = new Date(); return (!((when.getTime() >= this.validFrom.getTime()) && (when.getTime() < this.validUntil.getTime()))); }; Certificate.prototype.isSignedBy = function (issuerCert) { utils.assertCompatible(issuerCert, Certificate, [1, 0], 'issuer'); if (!this.issuer.equals(issuerCert.subjects[0])) return (false); if (this.issuer.purposes && this.issuer.purposes.length > 0 && this.issuer.purposes.indexOf('ca') === -1) { return (false); } return (this.isSignedByKey(issuerCert.subjectKey)); }; Certificate.prototype.getExtension = function (keyOrOid) { assert.string(keyOrOid, 'keyOrOid'); var ext = this.getExtensions().filter(function (maybeExt) { if (maybeExt.format === 'x509') return (maybeExt.oid === keyOrOid); if (maybeExt.format === 'openssh') return (maybeExt.name === keyOrOid); return (false); })[0]; return (ext); }; Certificate.prototype.getExtensions = function () { var exts = []; var x509 = this.signatures.x509; if (x509 && x509.extras && x509.extras.exts) { x509.extras.exts.forEach(function (ext) { ext.format = 'x509'; exts.push(ext); }); } var openssh = this.signatures.openssh; if (openssh && openssh.exts) { openssh.exts.forEach(function (ext) { ext.format = 'openssh'; exts.push(ext); }); } return (exts); }; Certificate.prototype.isSignedByKey = function (issuerKey) { utils.assertCompatible(issuerKey, Key, [1, 2], 'issuerKey'); if (this.issuerKey !== undefined) { return (this.issuerKey. fingerprint('sha512').matches(issuerKey)); } var fmt = Object.keys(this.signatures)[0]; var valid = formats[fmt].verify(this, issuerKey); if (valid) this.issuerKey = issuerKey; return (valid); }; Certificate.prototype.signWith = function (key) { utils.assertCompatible(key, PrivateKey, [1, 2], 'key'); var fmts = Object.keys(formats); var didOne = false; for (var i = 0; i < fmts.length; ++i) { if (fmts[i] !== 'pem') { var ret = formats[fmts[i]].sign(this, key); if (ret === true) didOne = true; } } if (!didOne) { throw (new Error('Failed to sign the certificate for any ' + 'available certificate formats')); } }; Certificate.createSelfSigned = function (subjectOrSubjects, key, options) { var subjects; if (Array.isArray(subjectOrSubjects)) subjects = subjectOrSubjects; else subjects = [subjectOrSubjects]; assert.arrayOfObject(subjects); subjects.forEach(function (subject) { utils.assertCompatible(subject, Identity, [1, 0], 'subject'); }); utils.assertCompatible(key, PrivateKey, [1, 2], 'private key'); assert.optionalObject(options, 'options'); if (options === undefined) options = {}; assert.optionalObject(options.validFrom, 'options.validFrom'); assert.optionalObject(options.validUntil, 'options.validUntil'); var validFrom = options.validFrom; var validUntil = options.validUntil; if (validFrom === undefined) validFrom = new Date(); if (validUntil === undefined) { assert.optionalNumber(options.lifetime, 'options.lifetime'); var lifetime = options.lifetime; if (lifetime === undefined) lifetime = 10*365*24*3600; validUntil = new Date(); validUntil.setTime(validUntil.getTime() + lifetime*1000); } assert.optionalBuffer(options.serial, 'options.serial'); var serial = options.serial; if (serial === undefined) serial = Buffer.from('0000000000000001', 'hex'); var purposes = options.purposes; if (purposes === undefined) purposes = []; if (purposes.indexOf('signature') === -1) purposes.push('signature'); /* Self-signed certs are always CAs. */ if (purposes.indexOf('ca') === -1) purposes.push('ca'); if (purposes.indexOf('crl') === -1) purposes.push('crl'); /* * If we weren't explicitly given any other purposes, do the sensible * thing and add some basic ones depending on the subject type. */ if (purposes.length <= 3) { var hostSubjects = subjects.filter(function (subject) { return (subject.type === 'host'); }); var userSubjects = subjects.filter(function (subject) { return (subject.type === 'user'); }); if (hostSubjects.length > 0) { if (purposes.indexOf('serverAuth') === -1) purposes.push('serverAuth'); } if (userSubjects.length > 0) { if (purposes.indexOf('clientAuth') === -1) purposes.push('clientAuth'); } if (userSubjects.length > 0 || hostSubjects.length > 0) { if (purposes.indexOf('keyAgreement') === -1) purposes.push('keyAgreement'); if (key.type === 'rsa' && purposes.indexOf('encryption') === -1) purposes.push('encryption'); } } var cert = new Certificate({ subjects: subjects, issuer: subjects[0], subjectKey: key.toPublic(), issuerKey: key.toPublic(), signatures: {}, serial: serial, validFrom: validFrom, validUntil: validUntil, purposes: purposes }); cert.signWith(key); return (cert); }; Certificate.create = function (subjectOrSubjects, key, issuer, issuerKey, options) { var subjects; if (Array.isArray(subjectOrSubjects)) subjects = subjectOrSubjects; else subjects = [subjectOrSubjects]; assert.arrayOfObject(subjects); subjects.forEach(function (subject) { utils.assertCompatible(subject, Identity, [1, 0], 'subject'); }); utils.assertCompatible(key, Key, [1, 0], 'key'); if (PrivateKey.isPrivateKey(key)) key = key.toPublic(); utils.assertCompatible(issuer, Identity, [1, 0], 'issuer'); utils.assertCompatible(issuerKey, PrivateKey, [1, 2], 'issuer key'); assert.optionalObject(options, 'options'); if (options === undefined) options = {}; assert.optionalObject(options.validFrom, 'options.validFrom'); assert.optionalObject(options.validUntil, 'options.validUntil'); var validFrom = options.validFrom; var validUntil = options.validUntil; if (validFrom === undefined) validFrom = new Date(); if (validUntil === undefined) { assert.optionalNumber(options.lifetime, 'options.lifetime'); var lifetime = options.lifetime; if (lifetime === undefined) lifetime = 10*365*24*3600; validUntil = new Date(); validUntil.setTime(validUntil.getTime() + lifetime*1000); } assert.optionalBuffer(options.serial, 'options.serial'); var serial = options.serial; if (serial === undefined) serial = Buffer.from('0000000000000001', 'hex'); var purposes = options.purposes; if (purposes === undefined) purposes = []; if (purposes.indexOf('signature') === -1) purposes.push('signature'); if (options.ca === true) { if (purposes.indexOf('ca') === -1) purposes.push('ca'); if (purposes.indexOf('crl') === -1) purposes.push('crl'); } var hostSubjects = subjects.filter(function (subject) { return (subject.type === 'host'); }); var userSubjects = subjects.filter(function (subject) { return (subject.type === 'user'); }); if (hostSubjects.length > 0) { if (purposes.indexOf('serverAuth') === -1) purposes.push('serverAuth'); } if (userSubjects.length > 0) { if (purposes.indexOf('clientAuth') === -1) purposes.push('clientAuth'); } if (userSubjects.length > 0 || hostSubjects.length > 0) { if (purposes.indexOf('keyAgreement') === -1) purposes.push('keyAgreement'); if (key.type === 'rsa' && purposes.indexOf('encryption') === -1) purposes.push('encryption'); } var cert = new Certificate({ subjects: subjects, issuer: issuer, subjectKey: key, issuerKey: issuerKey.toPublic(), signatures: {}, serial: serial, validFrom: validFrom, validUntil: validUntil, purposes: purposes }); cert.signWith(issuerKey); return (cert); }; Certificate.parse = function (data, format, options) { if (typeof (data) !== 'string') assert.buffer(data, 'data'); if (format === undefined) format = 'auto'; assert.string(format, 'format'); if (typeof (options) === 'string') options = { filename: options }; assert.optionalObject(options, 'options'); if (options === undefined) options = {}; assert.optionalString(options.filename, 'options.filename'); if (options.filename === undefined) options.filename = '(unnamed)'; assert.object(formats[format], 'formats[format]'); try { var k = formats[format].read(data, options); return (k); } catch (e) { throw (new CertificateParseError(options.filename, format, e)); } }; Certificate.isCertificate = function (obj, ver) { return (utils.isCompatible(obj, Certificate, ver)); }; /* * API versions for Certificate: * [1,0] -- initial ver * [1,1] -- openssh format now unpacks extensions */ Certificate.prototype._sshpkApiVersion = [1, 1]; Certificate._oldVersionDetect = function (obj) { return ([1, 0]); };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/certificate.js
certificate.js
module.exports = Key; var assert = require('assert-plus'); var algs = require('sshpk/lib/algs'); var crypto = require('crypto'); var Fingerprint = require('sshpk/lib/fingerprint'); var Signature = require('sshpk/lib/signature'); var DiffieHellman = require('sshpk/lib/dhe').DiffieHellman; var errs = require('sshpk/lib/errors'); var utils = require('sshpk/lib/utils'); var PrivateKey = require('sshpk/lib/private-key'); var edCompat; try { edCompat = require('sshpk/lib/ed-compat'); } catch (e) { /* Just continue through, and bail out if we try to use it. */ } var InvalidAlgorithmError = errs.InvalidAlgorithmError; var KeyParseError = errs.KeyParseError; var formats = {}; formats['auto'] = require('sshpk/lib/formats/auto'); formats['pem'] = require('sshpk/lib/formats/pem'); formats['pkcs1'] = require('sshpk/lib/formats/pkcs1'); formats['pkcs8'] = require('sshpk/lib/formats/pkcs8'); formats['rfc4253'] = require('sshpk/lib/formats/rfc4253'); formats['ssh'] = require('sshpk/lib/formats/ssh'); formats['ssh-private'] = require('sshpk/lib/formats/ssh-private'); formats['openssh'] = formats['ssh-private']; formats['dnssec'] = require('sshpk/lib/formats/dnssec'); formats['putty'] = require('sshpk/lib/formats/putty'); formats['ppk'] = formats['putty']; function Key(opts) { assert.object(opts, 'options'); assert.arrayOfObject(opts.parts, 'options.parts'); assert.string(opts.type, 'options.type'); assert.optionalString(opts.comment, 'options.comment'); var algInfo = algs.info[opts.type]; if (typeof (algInfo) !== 'object') throw (new InvalidAlgorithmError(opts.type)); var partLookup = {}; for (var i = 0; i < opts.parts.length; ++i) { var part = opts.parts[i]; partLookup[part.name] = part; } this.type = opts.type; this.parts = opts.parts; this.part = partLookup; this.comment = undefined; this.source = opts.source; /* for speeding up hashing/fingerprint operations */ this._rfc4253Cache = opts._rfc4253Cache; this._hashCache = {}; var sz; this.curve = undefined; if (this.type === 'ecdsa') { var curve = this.part.curve.data.toString(); this.curve = curve; sz = algs.curves[curve].size; } else if (this.type === 'ed25519' || this.type === 'curve25519') { sz = 256; this.curve = 'curve25519'; } else { var szPart = this.part[algInfo.sizePart]; sz = szPart.data.length; sz = sz * 8 - utils.countZeros(szPart.data); } this.size = sz; } Key.formats = formats; Key.prototype.toBuffer = function (format, options) { if (format === undefined) format = 'ssh'; assert.string(format, 'format'); assert.object(formats[format], 'formats[format]'); assert.optionalObject(options, 'options'); if (format === 'rfc4253') { if (this._rfc4253Cache === undefined) this._rfc4253Cache = formats['rfc4253'].write(this); return (this._rfc4253Cache); } return (formats[format].write(this, options)); }; Key.prototype.toString = function (format, options) { return (this.toBuffer(format, options).toString()); }; Key.prototype.hash = function (algo, type) { assert.string(algo, 'algorithm'); assert.optionalString(type, 'type'); if (type === undefined) type = 'ssh'; algo = algo.toLowerCase(); if (algs.hashAlgs[algo] === undefined) throw (new InvalidAlgorithmError(algo)); var cacheKey = algo + '||' + type; if (this._hashCache[cacheKey]) return (this._hashCache[cacheKey]); var buf; if (type === 'ssh') { buf = this.toBuffer('rfc4253'); } else if (type === 'spki') { buf = formats.pkcs8.pkcs8ToBuffer(this); } else { throw (new Error('Hash type ' + type + ' not supported')); } var hash = crypto.createHash(algo).update(buf).digest(); this._hashCache[cacheKey] = hash; return (hash); }; Key.prototype.fingerprint = function (algo, type) { if (algo === undefined) algo = 'sha256'; if (type === undefined) type = 'ssh'; assert.string(algo, 'algorithm'); assert.string(type, 'type'); var opts = { type: 'key', hash: this.hash(algo, type), algorithm: algo, hashType: type }; return (new Fingerprint(opts)); }; Key.prototype.defaultHashAlgorithm = function () { var hashAlgo = 'sha1'; if (this.type === 'rsa') hashAlgo = 'sha256'; if (this.type === 'dsa' && this.size > 1024) hashAlgo = 'sha256'; if (this.type === 'ed25519') hashAlgo = 'sha512'; if (this.type === 'ecdsa') { if (this.size <= 256) hashAlgo = 'sha256'; else if (this.size <= 384) hashAlgo = 'sha384'; else hashAlgo = 'sha512'; } return (hashAlgo); }; Key.prototype.createVerify = function (hashAlgo) { if (hashAlgo === undefined) hashAlgo = this.defaultHashAlgorithm(); assert.string(hashAlgo, 'hash algorithm'); /* ED25519 is not supported by OpenSSL, use a javascript impl. */ if (this.type === 'ed25519' && edCompat !== undefined) return (new edCompat.Verifier(this, hashAlgo)); if (this.type === 'curve25519') throw (new Error('Curve25519 keys are not suitable for ' + 'signing or verification')); var v, nm, err; try { nm = hashAlgo.toUpperCase(); v = crypto.createVerify(nm); } catch (e) { err = e; } if (v === undefined || (err instanceof Error && err.message.match(/Unknown message digest/))) { nm = 'RSA-'; nm += hashAlgo.toUpperCase(); v = crypto.createVerify(nm); } assert.ok(v, 'failed to create verifier'); var oldVerify = v.verify.bind(v); var key = this.toBuffer('pkcs8'); var curve = this.curve; var self = this; v.verify = function (signature, fmt) { if (Signature.isSignature(signature, [2, 0])) { if (signature.type !== self.type) return (false); if (signature.hashAlgorithm && signature.hashAlgorithm !== hashAlgo) return (false); if (signature.curve && self.type === 'ecdsa' && signature.curve !== curve) return (false); return (oldVerify(key, signature.toBuffer('asn1'))); } else if (typeof (signature) === 'string' || Buffer.isBuffer(signature)) { return (oldVerify(key, signature, fmt)); /* * Avoid doing this on valid arguments, walking the prototype * chain can be quite slow. */ } else if (Signature.isSignature(signature, [1, 0])) { throw (new Error('signature was created by too old ' + 'a version of sshpk and cannot be verified')); } else { throw (new TypeError('signature must be a string, ' + 'Buffer, or Signature object')); } }; return (v); }; Key.prototype.createDiffieHellman = function () { if (this.type === 'rsa') throw (new Error('RSA keys do not support Diffie-Hellman')); return (new DiffieHellman(this)); }; Key.prototype.createDH = Key.prototype.createDiffieHellman; Key.parse = function (data, format, options) { if (typeof (data) !== 'string') assert.buffer(data, 'data'); if (format === undefined) format = 'auto'; assert.string(format, 'format'); if (typeof (options) === 'string') options = { filename: options }; assert.optionalObject(options, 'options'); if (options === undefined) options = {}; assert.optionalString(options.filename, 'options.filename'); if (options.filename === undefined) options.filename = '(unnamed)'; assert.object(formats[format], 'formats[format]'); try { var k = formats[format].read(data, options); if (k instanceof PrivateKey) k = k.toPublic(); if (!k.comment) k.comment = options.filename; return (k); } catch (e) { if (e.name === 'KeyEncryptedError') throw (e); throw (new KeyParseError(options.filename, format, e)); } }; Key.isKey = function (obj, ver) { return (utils.isCompatible(obj, Key, ver)); }; /* * API versions for Key: * [1,0] -- initial ver, may take Signature for createVerify or may not * [1,1] -- added pkcs1, pkcs8 formats * [1,2] -- added auto, ssh-private, openssh formats * [1,3] -- added defaultHashAlgorithm * [1,4] -- added ed support, createDH * [1,5] -- first explicitly tagged version * [1,6] -- changed ed25519 part names * [1,7] -- spki hash types */ Key.prototype._sshpkApiVersion = [1, 7]; Key._oldVersionDetect = function (obj) { assert.func(obj.toBuffer); assert.func(obj.fingerprint); if (obj.createDH) return ([1, 4]); if (obj.defaultHashAlgorithm) return ([1, 3]); if (obj.formats['auto']) return ([1, 2]); if (obj.formats['pkcs1']) return ([1, 1]); return ([1, 0]); };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/key.js
key.js
module.exports = { read: read, readPkcs1: readPkcs1, write: write, writePkcs1: writePkcs1 }; var assert = require('assert-plus'); var asn1 = require('asn1'); var Buffer = require('safer-buffer').Buffer; var algs = require('sshpk/lib/algs'); var utils = require('sshpk/lib/utils'); var Key = require('sshpk/lib/key'); var PrivateKey = require('sshpk/lib/private-key'); var pem = require('sshpk/lib/formats/pem'); var pkcs8 = require('sshpk/lib/formats/pkcs8'); var readECDSACurve = pkcs8.readECDSACurve; function read(buf, options) { return (pem.read(buf, options, 'pkcs1')); } function write(key, options) { return (pem.write(key, options, 'pkcs1')); } /* Helper to read in a single mpint */ function readMPInt(der, nm) { assert.strictEqual(der.peek(), asn1.Ber.Integer, nm + ' is not an Integer'); return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); } function readPkcs1(alg, type, der) { switch (alg) { case 'RSA': if (type === 'public') return (readPkcs1RSAPublic(der)); else if (type === 'private') return (readPkcs1RSAPrivate(der)); throw (new Error('Unknown key type: ' + type)); case 'DSA': if (type === 'public') return (readPkcs1DSAPublic(der)); else if (type === 'private') return (readPkcs1DSAPrivate(der)); throw (new Error('Unknown key type: ' + type)); case 'EC': case 'ECDSA': if (type === 'private') return (readPkcs1ECDSAPrivate(der)); else if (type === 'public') return (readPkcs1ECDSAPublic(der)); throw (new Error('Unknown key type: ' + type)); case 'EDDSA': case 'EdDSA': if (type === 'private') return (readPkcs1EdDSAPrivate(der)); throw (new Error(type + ' keys not supported with EdDSA')); default: throw (new Error('Unknown key algo: ' + alg)); } } function readPkcs1RSAPublic(der) { // modulus and exponent var n = readMPInt(der, 'modulus'); var e = readMPInt(der, 'exponent'); // now, make the key var key = { type: 'rsa', parts: [ { name: 'e', data: e }, { name: 'n', data: n } ] }; return (new Key(key)); } function readPkcs1RSAPrivate(der) { var version = readMPInt(der, 'version'); assert.strictEqual(version[0], 0); // modulus then public exponent var n = readMPInt(der, 'modulus'); var e = readMPInt(der, 'public exponent'); var d = readMPInt(der, 'private exponent'); var p = readMPInt(der, 'prime1'); var q = readMPInt(der, 'prime2'); var dmodp = readMPInt(der, 'exponent1'); var dmodq = readMPInt(der, 'exponent2'); var iqmp = readMPInt(der, 'iqmp'); // now, make the key var key = { type: 'rsa', parts: [ { name: 'n', data: n }, { name: 'e', data: e }, { name: 'd', data: d }, { name: 'iqmp', data: iqmp }, { name: 'p', data: p }, { name: 'q', data: q }, { name: 'dmodp', data: dmodp }, { name: 'dmodq', data: dmodq } ] }; return (new PrivateKey(key)); } function readPkcs1DSAPrivate(der) { var version = readMPInt(der, 'version'); assert.strictEqual(version.readUInt8(0), 0); var p = readMPInt(der, 'p'); var q = readMPInt(der, 'q'); var g = readMPInt(der, 'g'); var y = readMPInt(der, 'y'); var x = readMPInt(der, 'x'); // now, make the key var key = { type: 'dsa', parts: [ { name: 'p', data: p }, { name: 'q', data: q }, { name: 'g', data: g }, { name: 'y', data: y }, { name: 'x', data: x } ] }; return (new PrivateKey(key)); } function readPkcs1EdDSAPrivate(der) { var version = readMPInt(der, 'version'); assert.strictEqual(version.readUInt8(0), 1); // private key var k = der.readString(asn1.Ber.OctetString, true); der.readSequence(0xa0); var oid = der.readOID(); assert.strictEqual(oid, '1.3.101.112', 'the ed25519 curve identifier'); der.readSequence(0xa1); var A = utils.readBitString(der); var key = { type: 'ed25519', parts: [ { name: 'A', data: utils.zeroPadToLength(A, 32) }, { name: 'k', data: k } ] }; return (new PrivateKey(key)); } function readPkcs1DSAPublic(der) { var y = readMPInt(der, 'y'); var p = readMPInt(der, 'p'); var q = readMPInt(der, 'q'); var g = readMPInt(der, 'g'); var key = { type: 'dsa', parts: [ { name: 'y', data: y }, { name: 'p', data: p }, { name: 'q', data: q }, { name: 'g', data: g } ] }; return (new Key(key)); } function readPkcs1ECDSAPublic(der) { der.readSequence(); var oid = der.readOID(); assert.strictEqual(oid, '1.2.840.10045.2.1', 'must be ecPublicKey'); var curveOid = der.readOID(); var curve; var curves = Object.keys(algs.curves); for (var j = 0; j < curves.length; ++j) { var c = curves[j]; var cd = algs.curves[c]; if (cd.pkcs8oid === curveOid) { curve = c; break; } } assert.string(curve, 'a known ECDSA named curve'); var Q = der.readString(asn1.Ber.BitString, true); Q = utils.ecNormalize(Q); var key = { type: 'ecdsa', parts: [ { name: 'curve', data: Buffer.from(curve) }, { name: 'Q', data: Q } ] }; return (new Key(key)); } function readPkcs1ECDSAPrivate(der) { var version = readMPInt(der, 'version'); assert.strictEqual(version.readUInt8(0), 1); // private key var d = der.readString(asn1.Ber.OctetString, true); der.readSequence(0xa0); var curve = readECDSACurve(der); assert.string(curve, 'a known elliptic curve'); der.readSequence(0xa1); var Q = der.readString(asn1.Ber.BitString, true); Q = utils.ecNormalize(Q); var key = { type: 'ecdsa', parts: [ { name: 'curve', data: Buffer.from(curve) }, { name: 'Q', data: Q }, { name: 'd', data: d } ] }; return (new PrivateKey(key)); } function writePkcs1(der, key) { der.startSequence(); switch (key.type) { case 'rsa': if (PrivateKey.isPrivateKey(key)) writePkcs1RSAPrivate(der, key); else writePkcs1RSAPublic(der, key); break; case 'dsa': if (PrivateKey.isPrivateKey(key)) writePkcs1DSAPrivate(der, key); else writePkcs1DSAPublic(der, key); break; case 'ecdsa': if (PrivateKey.isPrivateKey(key)) writePkcs1ECDSAPrivate(der, key); else writePkcs1ECDSAPublic(der, key); break; case 'ed25519': if (PrivateKey.isPrivateKey(key)) writePkcs1EdDSAPrivate(der, key); else writePkcs1EdDSAPublic(der, key); break; default: throw (new Error('Unknown key algo: ' + key.type)); } der.endSequence(); } function writePkcs1RSAPublic(der, key) { der.writeBuffer(key.part.n.data, asn1.Ber.Integer); der.writeBuffer(key.part.e.data, asn1.Ber.Integer); } function writePkcs1RSAPrivate(der, key) { var ver = Buffer.from([0]); der.writeBuffer(ver, asn1.Ber.Integer); der.writeBuffer(key.part.n.data, asn1.Ber.Integer); der.writeBuffer(key.part.e.data, asn1.Ber.Integer); der.writeBuffer(key.part.d.data, asn1.Ber.Integer); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); if (!key.part.dmodp || !key.part.dmodq) utils.addRSAMissing(key); der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer); der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer); der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer); } function writePkcs1DSAPrivate(der, key) { var ver = Buffer.from([0]); der.writeBuffer(ver, asn1.Ber.Integer); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); der.writeBuffer(key.part.g.data, asn1.Ber.Integer); der.writeBuffer(key.part.y.data, asn1.Ber.Integer); der.writeBuffer(key.part.x.data, asn1.Ber.Integer); } function writePkcs1DSAPublic(der, key) { der.writeBuffer(key.part.y.data, asn1.Ber.Integer); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); der.writeBuffer(key.part.g.data, asn1.Ber.Integer); } function writePkcs1ECDSAPublic(der, key) { der.startSequence(); der.writeOID('1.2.840.10045.2.1'); /* ecPublicKey */ var curve = key.part.curve.data.toString(); var curveOid = algs.curves[curve].pkcs8oid; assert.string(curveOid, 'a known ECDSA named curve'); der.writeOID(curveOid); der.endSequence(); var Q = utils.ecNormalize(key.part.Q.data, true); der.writeBuffer(Q, asn1.Ber.BitString); } function writePkcs1ECDSAPrivate(der, key) { var ver = Buffer.from([1]); der.writeBuffer(ver, asn1.Ber.Integer); der.writeBuffer(key.part.d.data, asn1.Ber.OctetString); der.startSequence(0xa0); var curve = key.part.curve.data.toString(); var curveOid = algs.curves[curve].pkcs8oid; assert.string(curveOid, 'a known ECDSA named curve'); der.writeOID(curveOid); der.endSequence(); der.startSequence(0xa1); var Q = utils.ecNormalize(key.part.Q.data, true); der.writeBuffer(Q, asn1.Ber.BitString); der.endSequence(); } function writePkcs1EdDSAPrivate(der, key) { var ver = Buffer.from([1]); der.writeBuffer(ver, asn1.Ber.Integer); der.writeBuffer(key.part.k.data, asn1.Ber.OctetString); der.startSequence(0xa0); der.writeOID('1.3.101.112'); der.endSequence(); der.startSequence(0xa1); utils.writeBitString(der, key.part.A.data); der.endSequence(); } function writePkcs1EdDSAPublic(der, key) { throw (new Error('Public keys are not supported for EdDSA PKCS#1')); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/formats/pkcs1.js
pkcs1.js
var x509 = require('sshpk/lib/formats/x509'); module.exports = { read: read, verify: x509.verify, sign: x509.sign, write: write }; var assert = require('assert-plus'); var asn1 = require('asn1'); var Buffer = require('safer-buffer').Buffer; var algs = require('sshpk/lib/algs'); var utils = require('sshpk/lib/utils'); var Key = require('sshpk/lib/key'); var PrivateKey = require('sshpk/lib/private-key'); var pem = require('sshpk/lib/formats/pem'); var Identity = require('sshpk/lib/identity'); var Signature = require('sshpk/lib/signature'); var Certificate = require('sshpk/lib/certificate'); function read(buf, options) { if (typeof (buf) !== 'string') { assert.buffer(buf, 'buf'); buf = buf.toString('ascii'); } var lines = buf.trim().split(/[\r\n]+/g); var m; var si = -1; while (!m && si < lines.length) { m = lines[++si].match(/*JSSTYLED*/ /[-]+[ ]*BEGIN CERTIFICATE[ ]*[-]+/); } assert.ok(m, 'invalid PEM header'); var m2; var ei = lines.length; while (!m2 && ei > 0) { m2 = lines[--ei].match(/*JSSTYLED*/ /[-]+[ ]*END CERTIFICATE[ ]*[-]+/); } assert.ok(m2, 'invalid PEM footer'); lines = lines.slice(si, ei + 1); var headers = {}; while (true) { lines = lines.slice(1); m = lines[0].match(/*JSSTYLED*/ /^([A-Za-z0-9-]+): (.+)$/); if (!m) break; headers[m[1].toLowerCase()] = m[2]; } /* Chop off the first and last lines */ lines = lines.slice(0, -1).join(''); buf = Buffer.from(lines, 'base64'); return (x509.read(buf, options)); } function write(cert, options) { var dbuf = x509.write(cert, options); var header = 'CERTIFICATE'; var tmp = dbuf.toString('base64'); var len = tmp.length + (tmp.length / 64) + 18 + 16 + header.length*2 + 10; var buf = Buffer.alloc(len); var o = 0; o += buf.write('-----BEGIN ' + header + '-----\n', o); for (var i = 0; i < tmp.length; ) { var limit = i + 64; if (limit > tmp.length) limit = tmp.length; o += buf.write(tmp.slice(i, limit), o); buf[o++] = 10; i = limit; } o += buf.write('-----END ' + header + '-----\n', o); return (buf.slice(0, o)); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/formats/x509-pem.js
x509-pem.js
module.exports = { read: read, write: write }; var assert = require('assert-plus'); var Buffer = require('safer-buffer').Buffer; var rfc4253 = require('sshpk/lib/formats/rfc4253'); var utils = require('sshpk/lib/utils'); var Key = require('sshpk/lib/key'); var PrivateKey = require('sshpk/lib/private-key'); var sshpriv = require('sshpk/lib/formats/ssh-private'); /*JSSTYLED*/ var SSHKEY_RE = /^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/]+[=]*)([ \t]+([^ \t][^\n]*[\n]*)?)?$/; /*JSSTYLED*/ var SSHKEY_RE2 = /^([a-z0-9-]+)[ \t\n]+([a-zA-Z0-9+\/][a-zA-Z0-9+\/ \t\n=]*)([^a-zA-Z0-9+\/ \t\n=].*)?$/; function read(buf, options) { if (typeof (buf) !== 'string') { assert.buffer(buf, 'buf'); buf = buf.toString('ascii'); } var trimmed = buf.trim().replace(/[\\\r]/g, ''); var m = trimmed.match(SSHKEY_RE); if (!m) m = trimmed.match(SSHKEY_RE2); assert.ok(m, 'key must match regex'); var type = rfc4253.algToKeyType(m[1]); var kbuf = Buffer.from(m[2], 'base64'); /* * This is a bit tricky. If we managed to parse the key and locate the * key comment with the regex, then do a non-partial read and assert * that we have consumed all bytes. If we couldn't locate the key * comment, though, there may be whitespace shenanigans going on that * have conjoined the comment to the rest of the key. We do a partial * read in this case to try to make the best out of a sorry situation. */ var key; var ret = {}; if (m[4]) { try { key = rfc4253.read(kbuf); } catch (e) { m = trimmed.match(SSHKEY_RE2); assert.ok(m, 'key must match regex'); kbuf = Buffer.from(m[2], 'base64'); key = rfc4253.readInternal(ret, 'public', kbuf); } } else { key = rfc4253.readInternal(ret, 'public', kbuf); } assert.strictEqual(type, key.type); if (m[4] && m[4].length > 0) { key.comment = m[4]; } else if (ret.consumed) { /* * Now the magic: trying to recover the key comment when it's * gotten conjoined to the key or otherwise shenanigan'd. * * Work out how much base64 we used, then drop all non-base64 * chars from the beginning up to this point in the the string. * Then offset in this and try to make up for missing = chars. */ var data = m[2] + (m[3] ? m[3] : ''); var realOffset = Math.ceil(ret.consumed / 3) * 4; data = data.slice(0, realOffset - 2). /*JSSTYLED*/ replace(/[^a-zA-Z0-9+\/=]/g, '') + data.slice(realOffset - 2); var padding = ret.consumed % 3; if (padding > 0 && data.slice(realOffset - 1, realOffset) !== '=') realOffset--; while (data.slice(realOffset, realOffset + 1) === '=') realOffset++; /* Finally, grab what we think is the comment & clean it up. */ var trailer = data.slice(realOffset); trailer = trailer.replace(/[\r\n]/g, ' '). replace(/^\s+/, ''); if (trailer.match(/^[a-zA-Z0-9]/)) key.comment = trailer; } return (key); } function write(key, options) { assert.object(key); if (!Key.isKey(key)) throw (new Error('Must be a public key')); var parts = []; var alg = rfc4253.keyTypeToAlg(key); parts.push(alg); var buf = rfc4253.write(key); parts.push(buf.toString('base64')); if (key.comment) parts.push(key.comment); return (Buffer.from(parts.join(' '))); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/formats/ssh.js
ssh.js
module.exports = { read: read, verify: verify, sign: sign, signAsync: signAsync, write: write, /* Internal private API */ fromBuffer: fromBuffer, toBuffer: toBuffer }; var assert = require('assert-plus'); var SSHBuffer = require('sshpk/lib/ssh-buffer'); var crypto = require('crypto'); var Buffer = require('safer-buffer').Buffer; var algs = require('sshpk/lib/algs'); var Key = require('sshpk/lib/key'); var PrivateKey = require('sshpk/lib/private-key'); var Identity = require('sshpk/lib/identity'); var rfc4253 = require('sshpk/lib/formats/rfc4253'); var Signature = require('sshpk/lib/signature'); var utils = require('sshpk/lib/utils'); var Certificate = require('sshpk/lib/certificate'); function verify(cert, key) { /* * We always give an issuerKey, so if our verify() is being called then * there was no signature. Return false. */ return (false); } var TYPES = { 'user': 1, 'host': 2 }; Object.keys(TYPES).forEach(function (k) { TYPES[TYPES[k]] = k; }); var ECDSA_ALGO = /^ecdsa-sha2-([^@-]+)[email protected]$/; function read(buf, options) { if (Buffer.isBuffer(buf)) buf = buf.toString('ascii'); var parts = buf.trim().split(/[ \t\n]+/g); if (parts.length < 2 || parts.length > 3) throw (new Error('Not a valid SSH certificate line')); var algo = parts[0]; var data = parts[1]; data = Buffer.from(data, 'base64'); return (fromBuffer(data, algo)); } function fromBuffer(data, algo, partial) { var sshbuf = new SSHBuffer({ buffer: data }); var innerAlgo = sshbuf.readString(); if (algo !== undefined && innerAlgo !== algo) throw (new Error('SSH certificate algorithm mismatch')); if (algo === undefined) algo = innerAlgo; var cert = {}; cert.signatures = {}; cert.signatures.openssh = {}; cert.signatures.openssh.nonce = sshbuf.readBuffer(); var key = {}; var parts = (key.parts = []); key.type = getAlg(algo); var partCount = algs.info[key.type].parts.length; while (parts.length < partCount) parts.push(sshbuf.readPart()); assert.ok(parts.length >= 1, 'key must have at least one part'); var algInfo = algs.info[key.type]; if (key.type === 'ecdsa') { var res = ECDSA_ALGO.exec(algo); assert.ok(res !== null); assert.strictEqual(res[1], parts[0].data.toString()); } for (var i = 0; i < algInfo.parts.length; ++i) { parts[i].name = algInfo.parts[i]; if (parts[i].name !== 'curve' && algInfo.normalize !== false) { var p = parts[i]; p.data = utils.mpNormalize(p.data); } } cert.subjectKey = new Key(key); cert.serial = sshbuf.readInt64(); var type = TYPES[sshbuf.readInt()]; assert.string(type, 'valid cert type'); cert.signatures.openssh.keyId = sshbuf.readString(); var principals = []; var pbuf = sshbuf.readBuffer(); var psshbuf = new SSHBuffer({ buffer: pbuf }); while (!psshbuf.atEnd()) principals.push(psshbuf.readString()); if (principals.length === 0) principals = ['*']; cert.subjects = principals.map(function (pr) { if (type === 'user') return (Identity.forUser(pr)); else if (type === 'host') return (Identity.forHost(pr)); throw (new Error('Unknown identity type ' + type)); }); cert.validFrom = int64ToDate(sshbuf.readInt64()); cert.validUntil = int64ToDate(sshbuf.readInt64()); var exts = []; var extbuf = new SSHBuffer({ buffer: sshbuf.readBuffer() }); var ext; while (!extbuf.atEnd()) { ext = { critical: true }; ext.name = extbuf.readString(); ext.data = extbuf.readBuffer(); exts.push(ext); } extbuf = new SSHBuffer({ buffer: sshbuf.readBuffer() }); while (!extbuf.atEnd()) { ext = { critical: false }; ext.name = extbuf.readString(); ext.data = extbuf.readBuffer(); exts.push(ext); } cert.signatures.openssh.exts = exts; /* reserved */ sshbuf.readBuffer(); var signingKeyBuf = sshbuf.readBuffer(); cert.issuerKey = rfc4253.read(signingKeyBuf); /* * OpenSSH certs don't give the identity of the issuer, just their * public key. So, we use an Identity that matches anything. The * isSignedBy() function will later tell you if the key matches. */ cert.issuer = Identity.forHost('**'); var sigBuf = sshbuf.readBuffer(); cert.signatures.openssh.signature = Signature.parse(sigBuf, cert.issuerKey.type, 'ssh'); if (partial !== undefined) { partial.remainder = sshbuf.remainder(); partial.consumed = sshbuf._offset; } return (new Certificate(cert)); } function int64ToDate(buf) { var i = buf.readUInt32BE(0) * 4294967296; i += buf.readUInt32BE(4); var d = new Date(); d.setTime(i * 1000); d.sourceInt64 = buf; return (d); } function dateToInt64(date) { if (date.sourceInt64 !== undefined) return (date.sourceInt64); var i = Math.round(date.getTime() / 1000); var upper = Math.floor(i / 4294967296); var lower = Math.floor(i % 4294967296); var buf = Buffer.alloc(8); buf.writeUInt32BE(upper, 0); buf.writeUInt32BE(lower, 4); return (buf); } function sign(cert, key) { if (cert.signatures.openssh === undefined) cert.signatures.openssh = {}; try { var blob = toBuffer(cert, true); } catch (e) { delete (cert.signatures.openssh); return (false); } var sig = cert.signatures.openssh; var hashAlgo = undefined; if (key.type === 'rsa' || key.type === 'dsa') hashAlgo = 'sha1'; var signer = key.createSign(hashAlgo); signer.write(blob); sig.signature = signer.sign(); return (true); } function signAsync(cert, signer, done) { if (cert.signatures.openssh === undefined) cert.signatures.openssh = {}; try { var blob = toBuffer(cert, true); } catch (e) { delete (cert.signatures.openssh); done(e); return; } var sig = cert.signatures.openssh; signer(blob, function (err, signature) { if (err) { done(err); return; } try { /* * This will throw if the signature isn't of a * type/algo that can be used for SSH. */ signature.toBuffer('ssh'); } catch (e) { done(e); return; } sig.signature = signature; done(); }); } function write(cert, options) { if (options === undefined) options = {}; var blob = toBuffer(cert); var out = getCertType(cert.subjectKey) + ' ' + blob.toString('base64'); if (options.comment) out = out + ' ' + options.comment; return (out); } function toBuffer(cert, noSig) { assert.object(cert.signatures.openssh, 'signature for openssh format'); var sig = cert.signatures.openssh; if (sig.nonce === undefined) sig.nonce = crypto.randomBytes(16); var buf = new SSHBuffer({}); buf.writeString(getCertType(cert.subjectKey)); buf.writeBuffer(sig.nonce); var key = cert.subjectKey; var algInfo = algs.info[key.type]; algInfo.parts.forEach(function (part) { buf.writePart(key.part[part]); }); buf.writeInt64(cert.serial); var type = cert.subjects[0].type; assert.notStrictEqual(type, 'unknown'); cert.subjects.forEach(function (id) { assert.strictEqual(id.type, type); }); type = TYPES[type]; buf.writeInt(type); if (sig.keyId === undefined) { sig.keyId = cert.subjects[0].type + '_' + (cert.subjects[0].uid || cert.subjects[0].hostname); } buf.writeString(sig.keyId); var sub = new SSHBuffer({}); cert.subjects.forEach(function (id) { if (type === TYPES.host) sub.writeString(id.hostname); else if (type === TYPES.user) sub.writeString(id.uid); }); buf.writeBuffer(sub.toBuffer()); buf.writeInt64(dateToInt64(cert.validFrom)); buf.writeInt64(dateToInt64(cert.validUntil)); var exts = sig.exts; if (exts === undefined) exts = []; var extbuf = new SSHBuffer({}); exts.forEach(function (ext) { if (ext.critical !== true) return; extbuf.writeString(ext.name); extbuf.writeBuffer(ext.data); }); buf.writeBuffer(extbuf.toBuffer()); extbuf = new SSHBuffer({}); exts.forEach(function (ext) { if (ext.critical === true) return; extbuf.writeString(ext.name); extbuf.writeBuffer(ext.data); }); buf.writeBuffer(extbuf.toBuffer()); /* reserved */ buf.writeBuffer(Buffer.alloc(0)); sub = rfc4253.write(cert.issuerKey); buf.writeBuffer(sub); if (!noSig) buf.writeBuffer(sig.signature.toBuffer('ssh')); return (buf.toBuffer()); } function getAlg(certType) { if (certType === '[email protected]') return ('rsa'); if (certType === '[email protected]') return ('dsa'); if (certType.match(ECDSA_ALGO)) return ('ecdsa'); if (certType === '[email protected]') return ('ed25519'); throw (new Error('Unsupported cert type ' + certType)); } function getCertType(key) { if (key.type === 'rsa') return ('[email protected]'); if (key.type === 'dsa') return ('[email protected]'); if (key.type === 'ecdsa') return ('ecdsa-sha2-' + key.curve + '[email protected]'); if (key.type === 'ed25519') return ('[email protected]'); throw (new Error('Unsupported key type ' + key.type)); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/formats/openssh-cert.js
openssh-cert.js
module.exports = { read: read, readPkcs8: readPkcs8, write: write, writePkcs8: writePkcs8, pkcs8ToBuffer: pkcs8ToBuffer, readECDSACurve: readECDSACurve, writeECDSACurve: writeECDSACurve }; var assert = require('assert-plus'); var asn1 = require('asn1'); var Buffer = require('safer-buffer').Buffer; var algs = require('sshpk/lib/algs'); var utils = require('sshpk/lib/utils'); var Key = require('sshpk/lib/key'); var PrivateKey = require('sshpk/lib/private-key'); var pem = require('sshpk/lib/formats/pem'); function read(buf, options) { return (pem.read(buf, options, 'pkcs8')); } function write(key, options) { return (pem.write(key, options, 'pkcs8')); } /* Helper to read in a single mpint */ function readMPInt(der, nm) { assert.strictEqual(der.peek(), asn1.Ber.Integer, nm + ' is not an Integer'); return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); } function readPkcs8(alg, type, der) { /* Private keys in pkcs#8 format have a weird extra int */ if (der.peek() === asn1.Ber.Integer) { assert.strictEqual(type, 'private', 'unexpected Integer at start of public key'); der.readString(asn1.Ber.Integer, true); } der.readSequence(); var next = der.offset + der.length; var oid = der.readOID(); switch (oid) { case '1.2.840.113549.1.1.1': der._offset = next; if (type === 'public') return (readPkcs8RSAPublic(der)); else return (readPkcs8RSAPrivate(der)); case '1.2.840.10040.4.1': if (type === 'public') return (readPkcs8DSAPublic(der)); else return (readPkcs8DSAPrivate(der)); case '1.2.840.10045.2.1': if (type === 'public') return (readPkcs8ECDSAPublic(der)); else return (readPkcs8ECDSAPrivate(der)); case '1.3.101.112': if (type === 'public') { return (readPkcs8EdDSAPublic(der)); } else { return (readPkcs8EdDSAPrivate(der)); } case '1.3.101.110': if (type === 'public') { return (readPkcs8X25519Public(der)); } else { return (readPkcs8X25519Private(der)); } default: throw (new Error('Unknown key type OID ' + oid)); } } function readPkcs8RSAPublic(der) { // bit string sequence der.readSequence(asn1.Ber.BitString); der.readByte(); der.readSequence(); // modulus var n = readMPInt(der, 'modulus'); var e = readMPInt(der, 'exponent'); // now, make the key var key = { type: 'rsa', source: der.originalInput, parts: [ { name: 'e', data: e }, { name: 'n', data: n } ] }; return (new Key(key)); } function readPkcs8RSAPrivate(der) { der.readSequence(asn1.Ber.OctetString); der.readSequence(); var ver = readMPInt(der, 'version'); assert.equal(ver[0], 0x0, 'unknown RSA private key version'); // modulus then public exponent var n = readMPInt(der, 'modulus'); var e = readMPInt(der, 'public exponent'); var d = readMPInt(der, 'private exponent'); var p = readMPInt(der, 'prime1'); var q = readMPInt(der, 'prime2'); var dmodp = readMPInt(der, 'exponent1'); var dmodq = readMPInt(der, 'exponent2'); var iqmp = readMPInt(der, 'iqmp'); // now, make the key var key = { type: 'rsa', parts: [ { name: 'n', data: n }, { name: 'e', data: e }, { name: 'd', data: d }, { name: 'iqmp', data: iqmp }, { name: 'p', data: p }, { name: 'q', data: q }, { name: 'dmodp', data: dmodp }, { name: 'dmodq', data: dmodq } ] }; return (new PrivateKey(key)); } function readPkcs8DSAPublic(der) { der.readSequence(); var p = readMPInt(der, 'p'); var q = readMPInt(der, 'q'); var g = readMPInt(der, 'g'); // bit string sequence der.readSequence(asn1.Ber.BitString); der.readByte(); var y = readMPInt(der, 'y'); // now, make the key var key = { type: 'dsa', parts: [ { name: 'p', data: p }, { name: 'q', data: q }, { name: 'g', data: g }, { name: 'y', data: y } ] }; return (new Key(key)); } function readPkcs8DSAPrivate(der) { der.readSequence(); var p = readMPInt(der, 'p'); var q = readMPInt(der, 'q'); var g = readMPInt(der, 'g'); der.readSequence(asn1.Ber.OctetString); var x = readMPInt(der, 'x'); /* The pkcs#8 format does not include the public key */ var y = utils.calculateDSAPublic(g, p, x); var key = { type: 'dsa', parts: [ { name: 'p', data: p }, { name: 'q', data: q }, { name: 'g', data: g }, { name: 'y', data: y }, { name: 'x', data: x } ] }; return (new PrivateKey(key)); } function readECDSACurve(der) { var curveName, curveNames; var j, c, cd; if (der.peek() === asn1.Ber.OID) { var oid = der.readOID(); curveNames = Object.keys(algs.curves); for (j = 0; j < curveNames.length; ++j) { c = curveNames[j]; cd = algs.curves[c]; if (cd.pkcs8oid === oid) { curveName = c; break; } } } else { // ECParameters sequence der.readSequence(); var version = der.readString(asn1.Ber.Integer, true); assert.strictEqual(version[0], 1, 'ECDSA key not version 1'); var curve = {}; // FieldID sequence der.readSequence(); var fieldTypeOid = der.readOID(); assert.strictEqual(fieldTypeOid, '1.2.840.10045.1.1', 'ECDSA key is not from a prime-field'); var p = curve.p = utils.mpNormalize( der.readString(asn1.Ber.Integer, true)); /* * p always starts with a 1 bit, so count the zeros to get its * real size. */ curve.size = p.length * 8 - utils.countZeros(p); // Curve sequence der.readSequence(); curve.a = utils.mpNormalize( der.readString(asn1.Ber.OctetString, true)); curve.b = utils.mpNormalize( der.readString(asn1.Ber.OctetString, true)); if (der.peek() === asn1.Ber.BitString) curve.s = der.readString(asn1.Ber.BitString, true); // Combined Gx and Gy curve.G = der.readString(asn1.Ber.OctetString, true); assert.strictEqual(curve.G[0], 0x4, 'uncompressed G is required'); curve.n = utils.mpNormalize( der.readString(asn1.Ber.Integer, true)); curve.h = utils.mpNormalize( der.readString(asn1.Ber.Integer, true)); assert.strictEqual(curve.h[0], 0x1, 'a cofactor=1 curve is ' + 'required'); curveNames = Object.keys(algs.curves); var ks = Object.keys(curve); for (j = 0; j < curveNames.length; ++j) { c = curveNames[j]; cd = algs.curves[c]; var equal = true; for (var i = 0; i < ks.length; ++i) { var k = ks[i]; if (cd[k] === undefined) continue; if (typeof (cd[k]) === 'object' && cd[k].equals !== undefined) { if (!cd[k].equals(curve[k])) { equal = false; break; } } else if (Buffer.isBuffer(cd[k])) { if (cd[k].toString('binary') !== curve[k].toString('binary')) { equal = false; break; } } else { if (cd[k] !== curve[k]) { equal = false; break; } } } if (equal) { curveName = c; break; } } } return (curveName); } function readPkcs8ECDSAPrivate(der) { var curveName = readECDSACurve(der); assert.string(curveName, 'a known elliptic curve'); der.readSequence(asn1.Ber.OctetString); der.readSequence(); var version = readMPInt(der, 'version'); assert.equal(version[0], 1, 'unknown version of ECDSA key'); var d = der.readString(asn1.Ber.OctetString, true); var Q; if (der.peek() == 0xa0) { der.readSequence(0xa0); der._offset += der.length; } if (der.peek() == 0xa1) { der.readSequence(0xa1); Q = der.readString(asn1.Ber.BitString, true); Q = utils.ecNormalize(Q); } if (Q === undefined) { var pub = utils.publicFromPrivateECDSA(curveName, d); Q = pub.part.Q.data; } var key = { type: 'ecdsa', parts: [ { name: 'curve', data: Buffer.from(curveName) }, { name: 'Q', data: Q }, { name: 'd', data: d } ] }; return (new PrivateKey(key)); } function readPkcs8ECDSAPublic(der) { var curveName = readECDSACurve(der); assert.string(curveName, 'a known elliptic curve'); var Q = der.readString(asn1.Ber.BitString, true); Q = utils.ecNormalize(Q); var key = { type: 'ecdsa', parts: [ { name: 'curve', data: Buffer.from(curveName) }, { name: 'Q', data: Q } ] }; return (new Key(key)); } function readPkcs8EdDSAPublic(der) { if (der.peek() === 0x00) der.readByte(); var A = utils.readBitString(der); var key = { type: 'ed25519', parts: [ { name: 'A', data: utils.zeroPadToLength(A, 32) } ] }; return (new Key(key)); } function readPkcs8X25519Public(der) { var A = utils.readBitString(der); var key = { type: 'curve25519', parts: [ { name: 'A', data: utils.zeroPadToLength(A, 32) } ] }; return (new Key(key)); } function readPkcs8EdDSAPrivate(der) { if (der.peek() === 0x00) der.readByte(); der.readSequence(asn1.Ber.OctetString); var k = der.readString(asn1.Ber.OctetString, true); k = utils.zeroPadToLength(k, 32); var A; if (der.peek() === asn1.Ber.BitString) { A = utils.readBitString(der); A = utils.zeroPadToLength(A, 32); } else { A = utils.calculateED25519Public(k); } var key = { type: 'ed25519', parts: [ { name: 'A', data: utils.zeroPadToLength(A, 32) }, { name: 'k', data: utils.zeroPadToLength(k, 32) } ] }; return (new PrivateKey(key)); } function readPkcs8X25519Private(der) { if (der.peek() === 0x00) der.readByte(); der.readSequence(asn1.Ber.OctetString); var k = der.readString(asn1.Ber.OctetString, true); k = utils.zeroPadToLength(k, 32); var A = utils.calculateX25519Public(k); var key = { type: 'curve25519', parts: [ { name: 'A', data: utils.zeroPadToLength(A, 32) }, { name: 'k', data: utils.zeroPadToLength(k, 32) } ] }; return (new PrivateKey(key)); } function pkcs8ToBuffer(key) { var der = new asn1.BerWriter(); writePkcs8(der, key); return (der.buffer); } function writePkcs8(der, key) { der.startSequence(); if (PrivateKey.isPrivateKey(key)) { var sillyInt = Buffer.from([0]); der.writeBuffer(sillyInt, asn1.Ber.Integer); } der.startSequence(); switch (key.type) { case 'rsa': der.writeOID('1.2.840.113549.1.1.1'); if (PrivateKey.isPrivateKey(key)) writePkcs8RSAPrivate(key, der); else writePkcs8RSAPublic(key, der); break; case 'dsa': der.writeOID('1.2.840.10040.4.1'); if (PrivateKey.isPrivateKey(key)) writePkcs8DSAPrivate(key, der); else writePkcs8DSAPublic(key, der); break; case 'ecdsa': der.writeOID('1.2.840.10045.2.1'); if (PrivateKey.isPrivateKey(key)) writePkcs8ECDSAPrivate(key, der); else writePkcs8ECDSAPublic(key, der); break; case 'ed25519': der.writeOID('1.3.101.112'); if (PrivateKey.isPrivateKey(key)) throw (new Error('Ed25519 private keys in pkcs8 ' + 'format are not supported')); writePkcs8EdDSAPublic(key, der); break; default: throw (new Error('Unsupported key type: ' + key.type)); } der.endSequence(); } function writePkcs8RSAPrivate(key, der) { der.writeNull(); der.endSequence(); der.startSequence(asn1.Ber.OctetString); der.startSequence(); var version = Buffer.from([0]); der.writeBuffer(version, asn1.Ber.Integer); der.writeBuffer(key.part.n.data, asn1.Ber.Integer); der.writeBuffer(key.part.e.data, asn1.Ber.Integer); der.writeBuffer(key.part.d.data, asn1.Ber.Integer); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); if (!key.part.dmodp || !key.part.dmodq) utils.addRSAMissing(key); der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer); der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer); der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer); der.endSequence(); der.endSequence(); } function writePkcs8RSAPublic(key, der) { der.writeNull(); der.endSequence(); der.startSequence(asn1.Ber.BitString); der.writeByte(0x00); der.startSequence(); der.writeBuffer(key.part.n.data, asn1.Ber.Integer); der.writeBuffer(key.part.e.data, asn1.Ber.Integer); der.endSequence(); der.endSequence(); } function writePkcs8DSAPrivate(key, der) { der.startSequence(); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); der.writeBuffer(key.part.g.data, asn1.Ber.Integer); der.endSequence(); der.endSequence(); der.startSequence(asn1.Ber.OctetString); der.writeBuffer(key.part.x.data, asn1.Ber.Integer); der.endSequence(); } function writePkcs8DSAPublic(key, der) { der.startSequence(); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); der.writeBuffer(key.part.g.data, asn1.Ber.Integer); der.endSequence(); der.endSequence(); der.startSequence(asn1.Ber.BitString); der.writeByte(0x00); der.writeBuffer(key.part.y.data, asn1.Ber.Integer); der.endSequence(); } function writeECDSACurve(key, der) { var curve = algs.curves[key.curve]; if (curve.pkcs8oid) { /* This one has a name in pkcs#8, so just write the oid */ der.writeOID(curve.pkcs8oid); } else { // ECParameters sequence der.startSequence(); var version = Buffer.from([1]); der.writeBuffer(version, asn1.Ber.Integer); // FieldID sequence der.startSequence(); der.writeOID('1.2.840.10045.1.1'); // prime-field der.writeBuffer(curve.p, asn1.Ber.Integer); der.endSequence(); // Curve sequence der.startSequence(); var a = curve.p; if (a[0] === 0x0) a = a.slice(1); der.writeBuffer(a, asn1.Ber.OctetString); der.writeBuffer(curve.b, asn1.Ber.OctetString); der.writeBuffer(curve.s, asn1.Ber.BitString); der.endSequence(); der.writeBuffer(curve.G, asn1.Ber.OctetString); der.writeBuffer(curve.n, asn1.Ber.Integer); var h = curve.h; if (!h) { h = Buffer.from([1]); } der.writeBuffer(h, asn1.Ber.Integer); // ECParameters der.endSequence(); } } function writePkcs8ECDSAPublic(key, der) { writeECDSACurve(key, der); der.endSequence(); var Q = utils.ecNormalize(key.part.Q.data, true); der.writeBuffer(Q, asn1.Ber.BitString); } function writePkcs8ECDSAPrivate(key, der) { writeECDSACurve(key, der); der.endSequence(); der.startSequence(asn1.Ber.OctetString); der.startSequence(); var version = Buffer.from([1]); der.writeBuffer(version, asn1.Ber.Integer); der.writeBuffer(key.part.d.data, asn1.Ber.OctetString); der.startSequence(0xa1); var Q = utils.ecNormalize(key.part.Q.data, true); der.writeBuffer(Q, asn1.Ber.BitString); der.endSequence(); der.endSequence(); der.endSequence(); } function writePkcs8EdDSAPublic(key, der) { der.endSequence(); utils.writeBitString(der, key.part.A.data); } function writePkcs8EdDSAPrivate(key, der) { der.endSequence(); var k = utils.mpNormalize(key.part.k.data, true); der.startSequence(asn1.Ber.OctetString); der.writeBuffer(k, asn1.Ber.OctetString); der.endSequence(); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/formats/pkcs8.js
pkcs8.js
module.exports = { read: read.bind(undefined, false, undefined), readType: read.bind(undefined, false), write: write, /* semi-private api, used by sshpk-agent */ readPartial: read.bind(undefined, true), /* shared with ssh format */ readInternal: read, keyTypeToAlg: keyTypeToAlg, algToKeyType: algToKeyType }; var assert = require('assert-plus'); var Buffer = require('safer-buffer').Buffer; var algs = require('sshpk/lib/algs'); var utils = require('sshpk/lib/utils'); var Key = require('sshpk/lib/key'); var PrivateKey = require('sshpk/lib/private-key'); var SSHBuffer = require('sshpk/lib/ssh-buffer'); function algToKeyType(alg) { assert.string(alg); if (alg === 'ssh-dss') return ('dsa'); else if (alg === 'ssh-rsa') return ('rsa'); else if (alg === 'ssh-ed25519') return ('ed25519'); else if (alg === 'ssh-curve25519') return ('curve25519'); else if (alg.match(/^ecdsa-sha2-/)) return ('ecdsa'); else throw (new Error('Unknown algorithm ' + alg)); } function keyTypeToAlg(key) { assert.object(key); if (key.type === 'dsa') return ('ssh-dss'); else if (key.type === 'rsa') return ('ssh-rsa'); else if (key.type === 'ed25519') return ('ssh-ed25519'); else if (key.type === 'curve25519') return ('ssh-curve25519'); else if (key.type === 'ecdsa') return ('ecdsa-sha2-' + key.part.curve.data.toString()); else throw (new Error('Unknown key type ' + key.type)); } function read(partial, type, buf, options) { if (typeof (buf) === 'string') buf = Buffer.from(buf); assert.buffer(buf, 'buf'); var key = {}; var parts = key.parts = []; var sshbuf = new SSHBuffer({buffer: buf}); var alg = sshbuf.readString(); assert.ok(!sshbuf.atEnd(), 'key must have at least one part'); key.type = algToKeyType(alg); var partCount = algs.info[key.type].parts.length; if (type && type === 'private') partCount = algs.privInfo[key.type].parts.length; while (!sshbuf.atEnd() && parts.length < partCount) parts.push(sshbuf.readPart()); while (!partial && !sshbuf.atEnd()) parts.push(sshbuf.readPart()); assert.ok(parts.length >= 1, 'key must have at least one part'); assert.ok(partial || sshbuf.atEnd(), 'leftover bytes at end of key'); var Constructor = Key; var algInfo = algs.info[key.type]; if (type === 'private' || algInfo.parts.length !== parts.length) { algInfo = algs.privInfo[key.type]; Constructor = PrivateKey; } assert.strictEqual(algInfo.parts.length, parts.length); if (key.type === 'ecdsa') { var res = /^ecdsa-sha2-(.+)$/.exec(alg); assert.ok(res !== null); assert.strictEqual(res[1], parts[0].data.toString()); } var normalized = true; for (var i = 0; i < algInfo.parts.length; ++i) { var p = parts[i]; p.name = algInfo.parts[i]; /* * OpenSSH stores ed25519 "private" keys as seed + public key * concat'd together (k followed by A). We want to keep them * separate for other formats that don't do this. */ if (key.type === 'ed25519' && p.name === 'k') p.data = p.data.slice(0, 32); if (p.name !== 'curve' && algInfo.normalize !== false) { var nd; if (key.type === 'ed25519') { nd = utils.zeroPadToLength(p.data, 32); } else { nd = utils.mpNormalize(p.data); } if (nd.toString('binary') !== p.data.toString('binary')) { p.data = nd; normalized = false; } } } if (normalized) key._rfc4253Cache = sshbuf.toBuffer(); if (partial && typeof (partial) === 'object') { partial.remainder = sshbuf.remainder(); partial.consumed = sshbuf._offset; } return (new Constructor(key)); } function write(key, options) { assert.object(key); var alg = keyTypeToAlg(key); var i; var algInfo = algs.info[key.type]; if (PrivateKey.isPrivateKey(key)) algInfo = algs.privInfo[key.type]; var parts = algInfo.parts; var buf = new SSHBuffer({}); buf.writeString(alg); for (i = 0; i < parts.length; ++i) { var data = key.part[parts[i]].data; if (algInfo.normalize !== false) { if (key.type === 'ed25519') data = utils.zeroPadToLength(data, 32); else data = utils.mpNormalize(data); } if (key.type === 'ed25519' && parts[i] === 'k') data = Buffer.concat([data, key.part.A.data]); buf.writeBuffer(data); } return (buf.toBuffer()); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/formats/rfc4253.js
rfc4253.js
module.exports = { read: read, write: write }; var assert = require('assert-plus'); var Buffer = require('safer-buffer').Buffer; var Key = require('sshpk/lib/key'); var PrivateKey = require('sshpk/lib/private-key'); var utils = require('sshpk/lib/utils'); var SSHBuffer = require('sshpk/lib/ssh-buffer'); var Dhe = require('sshpk/lib/dhe'); var supportedAlgos = { 'rsa-sha1' : 5, 'rsa-sha256' : 8, 'rsa-sha512' : 10, 'ecdsa-p256-sha256' : 13, 'ecdsa-p384-sha384' : 14 /* * ed25519 is hypothetically supported with id 15 * but the common tools available don't appear to be * capable of generating/using ed25519 keys */ }; var supportedAlgosById = {}; Object.keys(supportedAlgos).forEach(function (k) { supportedAlgosById[supportedAlgos[k]] = k.toUpperCase(); }); function read(buf, options) { if (typeof (buf) !== 'string') { assert.buffer(buf, 'buf'); buf = buf.toString('ascii'); } var lines = buf.split('\n'); if (lines[0].match(/^Private-key-format\: v1/)) { var algElems = lines[1].split(' '); var algoNum = parseInt(algElems[1], 10); var algoName = algElems[2]; if (!supportedAlgosById[algoNum]) throw (new Error('Unsupported algorithm: ' + algoName)); return (readDNSSECPrivateKey(algoNum, lines.slice(2))); } // skip any comment-lines var line = 0; /* JSSTYLED */ while (lines[line].match(/^\;/)) line++; // we should now have *one single* line left with our KEY on it. if ((lines[line].match(/\. IN KEY /) || lines[line].match(/\. IN DNSKEY /)) && lines[line+1].length === 0) { return (readRFC3110(lines[line])); } throw (new Error('Cannot parse dnssec key')); } function readRFC3110(keyString) { var elems = keyString.split(' '); //unused var flags = parseInt(elems[3], 10); //unused var protocol = parseInt(elems[4], 10); var algorithm = parseInt(elems[5], 10); if (!supportedAlgosById[algorithm]) throw (new Error('Unsupported algorithm: ' + algorithm)); var base64key = elems.slice(6, elems.length).join(); var keyBuffer = Buffer.from(base64key, 'base64'); if (supportedAlgosById[algorithm].match(/^RSA-/)) { // join the rest of the body into a single base64-blob var publicExponentLen = keyBuffer.readUInt8(0); if (publicExponentLen != 3 && publicExponentLen != 1) throw (new Error('Cannot parse dnssec key: ' + 'unsupported exponent length')); var publicExponent = keyBuffer.slice(1, publicExponentLen+1); publicExponent = utils.mpNormalize(publicExponent); var modulus = keyBuffer.slice(1+publicExponentLen); modulus = utils.mpNormalize(modulus); // now, make the key var rsaKey = { type: 'rsa', parts: [] }; rsaKey.parts.push({ name: 'e', data: publicExponent}); rsaKey.parts.push({ name: 'n', data: modulus}); return (new Key(rsaKey)); } if (supportedAlgosById[algorithm] === 'ECDSA-P384-SHA384' || supportedAlgosById[algorithm] === 'ECDSA-P256-SHA256') { var curve = 'nistp384'; var size = 384; if (supportedAlgosById[algorithm].match(/^ECDSA-P256-SHA256/)) { curve = 'nistp256'; size = 256; } var ecdsaKey = { type: 'ecdsa', curve: curve, size: size, parts: [ {name: 'curve', data: Buffer.from(curve) }, {name: 'Q', data: utils.ecNormalize(keyBuffer) } ] }; return (new Key(ecdsaKey)); } throw (new Error('Unsupported algorithm: ' + supportedAlgosById[algorithm])); } function elementToBuf(e) { return (Buffer.from(e.split(' ')[1], 'base64')); } function readDNSSECRSAPrivateKey(elements) { var rsaParams = {}; elements.forEach(function (element) { if (element.split(' ')[0] === 'Modulus:') rsaParams['n'] = elementToBuf(element); else if (element.split(' ')[0] === 'PublicExponent:') rsaParams['e'] = elementToBuf(element); else if (element.split(' ')[0] === 'PrivateExponent:') rsaParams['d'] = elementToBuf(element); else if (element.split(' ')[0] === 'Prime1:') rsaParams['p'] = elementToBuf(element); else if (element.split(' ')[0] === 'Prime2:') rsaParams['q'] = elementToBuf(element); else if (element.split(' ')[0] === 'Exponent1:') rsaParams['dmodp'] = elementToBuf(element); else if (element.split(' ')[0] === 'Exponent2:') rsaParams['dmodq'] = elementToBuf(element); else if (element.split(' ')[0] === 'Coefficient:') rsaParams['iqmp'] = elementToBuf(element); }); // now, make the key var key = { type: 'rsa', parts: [ { name: 'e', data: utils.mpNormalize(rsaParams['e'])}, { name: 'n', data: utils.mpNormalize(rsaParams['n'])}, { name: 'd', data: utils.mpNormalize(rsaParams['d'])}, { name: 'p', data: utils.mpNormalize(rsaParams['p'])}, { name: 'q', data: utils.mpNormalize(rsaParams['q'])}, { name: 'dmodp', data: utils.mpNormalize(rsaParams['dmodp'])}, { name: 'dmodq', data: utils.mpNormalize(rsaParams['dmodq'])}, { name: 'iqmp', data: utils.mpNormalize(rsaParams['iqmp'])} ] }; return (new PrivateKey(key)); } function readDNSSECPrivateKey(alg, elements) { if (supportedAlgosById[alg].match(/^RSA-/)) { return (readDNSSECRSAPrivateKey(elements)); } if (supportedAlgosById[alg] === 'ECDSA-P384-SHA384' || supportedAlgosById[alg] === 'ECDSA-P256-SHA256') { var d = Buffer.from(elements[0].split(' ')[1], 'base64'); var curve = 'nistp384'; var size = 384; if (supportedAlgosById[alg] === 'ECDSA-P256-SHA256') { curve = 'nistp256'; size = 256; } // DNSSEC generates the public-key on the fly (go calculate it) var publicKey = utils.publicFromPrivateECDSA(curve, d); var Q = publicKey.part['Q'].data; var ecdsaKey = { type: 'ecdsa', curve: curve, size: size, parts: [ {name: 'curve', data: Buffer.from(curve) }, {name: 'd', data: d }, {name: 'Q', data: Q } ] }; return (new PrivateKey(ecdsaKey)); } throw (new Error('Unsupported algorithm: ' + supportedAlgosById[alg])); } function dnssecTimestamp(date) { var year = date.getFullYear() + ''; //stringify var month = (date.getMonth() + 1); var timestampStr = year + month + date.getUTCDate(); timestampStr += '' + date.getUTCHours() + date.getUTCMinutes(); timestampStr += date.getUTCSeconds(); return (timestampStr); } function rsaAlgFromOptions(opts) { if (!opts || !opts.hashAlgo || opts.hashAlgo === 'sha1') return ('5 (RSASHA1)'); else if (opts.hashAlgo === 'sha256') return ('8 (RSASHA256)'); else if (opts.hashAlgo === 'sha512') return ('10 (RSASHA512)'); else throw (new Error('Unknown or unsupported hash: ' + opts.hashAlgo)); } function writeRSA(key, options) { // if we're missing parts, add them. if (!key.part.dmodp || !key.part.dmodq) { utils.addRSAMissing(key); } var out = ''; out += 'Private-key-format: v1.3\n'; out += 'Algorithm: ' + rsaAlgFromOptions(options) + '\n'; var n = utils.mpDenormalize(key.part['n'].data); out += 'Modulus: ' + n.toString('base64') + '\n'; var e = utils.mpDenormalize(key.part['e'].data); out += 'PublicExponent: ' + e.toString('base64') + '\n'; var d = utils.mpDenormalize(key.part['d'].data); out += 'PrivateExponent: ' + d.toString('base64') + '\n'; var p = utils.mpDenormalize(key.part['p'].data); out += 'Prime1: ' + p.toString('base64') + '\n'; var q = utils.mpDenormalize(key.part['q'].data); out += 'Prime2: ' + q.toString('base64') + '\n'; var dmodp = utils.mpDenormalize(key.part['dmodp'].data); out += 'Exponent1: ' + dmodp.toString('base64') + '\n'; var dmodq = utils.mpDenormalize(key.part['dmodq'].data); out += 'Exponent2: ' + dmodq.toString('base64') + '\n'; var iqmp = utils.mpDenormalize(key.part['iqmp'].data); out += 'Coefficient: ' + iqmp.toString('base64') + '\n'; // Assume that we're valid as-of now var timestamp = new Date(); out += 'Created: ' + dnssecTimestamp(timestamp) + '\n'; out += 'Publish: ' + dnssecTimestamp(timestamp) + '\n'; out += 'Activate: ' + dnssecTimestamp(timestamp) + '\n'; return (Buffer.from(out, 'ascii')); } function writeECDSA(key, options) { var out = ''; out += 'Private-key-format: v1.3\n'; if (key.curve === 'nistp256') { out += 'Algorithm: 13 (ECDSAP256SHA256)\n'; } else if (key.curve === 'nistp384') { out += 'Algorithm: 14 (ECDSAP384SHA384)\n'; } else { throw (new Error('Unsupported curve')); } var base64Key = key.part['d'].data.toString('base64'); out += 'PrivateKey: ' + base64Key + '\n'; // Assume that we're valid as-of now var timestamp = new Date(); out += 'Created: ' + dnssecTimestamp(timestamp) + '\n'; out += 'Publish: ' + dnssecTimestamp(timestamp) + '\n'; out += 'Activate: ' + dnssecTimestamp(timestamp) + '\n'; return (Buffer.from(out, 'ascii')); } function write(key, options) { if (PrivateKey.isPrivateKey(key)) { if (key.type === 'rsa') { return (writeRSA(key, options)); } else if (key.type === 'ecdsa') { return (writeECDSA(key, options)); } else { throw (new Error('Unsupported algorithm: ' + key.type)); } } else if (Key.isKey(key)) { /* * RFC3110 requires a keyname, and a keytype, which we * don't really have a mechanism for specifying such * additional metadata. */ throw (new Error('Format "dnssec" only supports ' + 'writing private keys')); } else { throw (new Error('key is not a Key or PrivateKey')); } }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/formats/dnssec.js
dnssec.js
module.exports = { read: read, write: write }; var assert = require('assert-plus'); var Buffer = require('safer-buffer').Buffer; var utils = require('sshpk/lib/utils'); var Key = require('sshpk/lib/key'); var PrivateKey = require('sshpk/lib/private-key'); var pem = require('sshpk/lib/formats/pem'); var ssh = require('sshpk/lib/formats/ssh'); var rfc4253 = require('sshpk/lib/formats/rfc4253'); var dnssec = require('sshpk/lib/formats/dnssec'); var putty = require('sshpk/lib/formats/putty'); var DNSSEC_PRIVKEY_HEADER_PREFIX = 'Private-key-format: v1'; function read(buf, options) { if (typeof (buf) === 'string') { if (buf.trim().match(/^[-]+[ ]*BEGIN/)) return (pem.read(buf, options)); if (buf.match(/^\s*ssh-[a-z]/)) return (ssh.read(buf, options)); if (buf.match(/^\s*ecdsa-/)) return (ssh.read(buf, options)); if (buf.match(/^putty-user-key-file-2:/i)) return (putty.read(buf, options)); if (findDNSSECHeader(buf)) return (dnssec.read(buf, options)); buf = Buffer.from(buf, 'binary'); } else { assert.buffer(buf); if (findPEMHeader(buf)) return (pem.read(buf, options)); if (findSSHHeader(buf)) return (ssh.read(buf, options)); if (findPuTTYHeader(buf)) return (putty.read(buf, options)); if (findDNSSECHeader(buf)) return (dnssec.read(buf, options)); } if (buf.readUInt32BE(0) < buf.length) return (rfc4253.read(buf, options)); throw (new Error('Failed to auto-detect format of key')); } function findPuTTYHeader(buf) { var offset = 0; while (offset < buf.length && (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9)) ++offset; if (offset + 22 <= buf.length && buf.slice(offset, offset + 22).toString('ascii').toLowerCase() === 'putty-user-key-file-2:') return (true); return (false); } function findSSHHeader(buf) { var offset = 0; while (offset < buf.length && (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9)) ++offset; if (offset + 4 <= buf.length && buf.slice(offset, offset + 4).toString('ascii') === 'ssh-') return (true); if (offset + 6 <= buf.length && buf.slice(offset, offset + 6).toString('ascii') === 'ecdsa-') return (true); return (false); } function findPEMHeader(buf) { var offset = 0; while (offset < buf.length && (buf[offset] === 32 || buf[offset] === 10)) ++offset; if (buf[offset] !== 45) return (false); while (offset < buf.length && (buf[offset] === 45)) ++offset; while (offset < buf.length && (buf[offset] === 32)) ++offset; if (offset + 5 > buf.length || buf.slice(offset, offset + 5).toString('ascii') !== 'BEGIN') return (false); return (true); } function findDNSSECHeader(buf) { // private case first if (buf.length <= DNSSEC_PRIVKEY_HEADER_PREFIX.length) return (false); var headerCheck = buf.slice(0, DNSSEC_PRIVKEY_HEADER_PREFIX.length); if (headerCheck.toString('ascii') === DNSSEC_PRIVKEY_HEADER_PREFIX) return (true); // public-key RFC3110 ? // 'domain.com. IN KEY ...' or 'domain.com. IN DNSKEY ...' // skip any comment-lines if (typeof (buf) !== 'string') { buf = buf.toString('ascii'); } var lines = buf.split('\n'); var line = 0; /* JSSTYLED */ while (lines[line].match(/^\;/)) line++; if (lines[line].toString('ascii').match(/\. IN KEY /)) return (true); if (lines[line].toString('ascii').match(/\. IN DNSKEY /)) return (true); return (false); } function write(key, options) { throw (new Error('"auto" format cannot be used for writing')); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/formats/auto.js
auto.js
module.exports = { read: read, readSSHPrivate: readSSHPrivate, write: write }; var assert = require('assert-plus'); var asn1 = require('asn1'); var Buffer = require('safer-buffer').Buffer; var algs = require('sshpk/lib/algs'); var utils = require('sshpk/lib/utils'); var crypto = require('crypto'); var Key = require('sshpk/lib/key'); var PrivateKey = require('sshpk/lib/private-key'); var pem = require('sshpk/lib/formats/pem'); var rfc4253 = require('sshpk/lib/formats/rfc4253'); var SSHBuffer = require('sshpk/lib/ssh-buffer'); var errors = require('sshpk/lib/errors'); var bcrypt; function read(buf, options) { return (pem.read(buf, options)); } var MAGIC = 'openssh-key-v1'; function readSSHPrivate(type, buf, options) { buf = new SSHBuffer({buffer: buf}); var magic = buf.readCString(); assert.strictEqual(magic, MAGIC, 'bad magic string'); var cipher = buf.readString(); var kdf = buf.readString(); var kdfOpts = buf.readBuffer(); var nkeys = buf.readInt(); if (nkeys !== 1) { throw (new Error('OpenSSH-format key file contains ' + 'multiple keys: this is unsupported.')); } var pubKey = buf.readBuffer(); if (type === 'public') { assert.ok(buf.atEnd(), 'excess bytes left after key'); return (rfc4253.read(pubKey)); } var privKeyBlob = buf.readBuffer(); assert.ok(buf.atEnd(), 'excess bytes left after key'); var kdfOptsBuf = new SSHBuffer({ buffer: kdfOpts }); switch (kdf) { case 'none': if (cipher !== 'none') { throw (new Error('OpenSSH-format key uses KDF "none" ' + 'but specifies a cipher other than "none"')); } break; case 'bcrypt': var salt = kdfOptsBuf.readBuffer(); var rounds = kdfOptsBuf.readInt(); var cinf = utils.opensshCipherInfo(cipher); if (bcrypt === undefined) { bcrypt = require('bcrypt-pbkdf'); } if (typeof (options.passphrase) === 'string') { options.passphrase = Buffer.from(options.passphrase, 'utf-8'); } if (!Buffer.isBuffer(options.passphrase)) { throw (new errors.KeyEncryptedError( options.filename, 'OpenSSH')); } var pass = new Uint8Array(options.passphrase); var salti = new Uint8Array(salt); /* Use the pbkdf to derive both the key and the IV. */ var out = new Uint8Array(cinf.keySize + cinf.blockSize); var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length, out, out.length, rounds); if (res !== 0) { throw (new Error('bcrypt_pbkdf function returned ' + 'failure, parameters invalid')); } out = Buffer.from(out); var ckey = out.slice(0, cinf.keySize); var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize); var cipherStream = crypto.createDecipheriv(cinf.opensslName, ckey, iv); cipherStream.setAutoPadding(false); var chunk, chunks = []; cipherStream.once('error', function (e) { if (e.toString().indexOf('bad decrypt') !== -1) { throw (new Error('Incorrect passphrase ' + 'supplied, could not decrypt key')); } throw (e); }); cipherStream.write(privKeyBlob); cipherStream.end(); while ((chunk = cipherStream.read()) !== null) chunks.push(chunk); privKeyBlob = Buffer.concat(chunks); break; default: throw (new Error( 'OpenSSH-format key uses unknown KDF "' + kdf + '"')); } buf = new SSHBuffer({buffer: privKeyBlob}); var checkInt1 = buf.readInt(); var checkInt2 = buf.readInt(); if (checkInt1 !== checkInt2) { throw (new Error('Incorrect passphrase supplied, could not ' + 'decrypt key')); } var ret = {}; var key = rfc4253.readInternal(ret, 'private', buf.remainder()); buf.skip(ret.consumed); var comment = buf.readString(); key.comment = comment; return (key); } function write(key, options) { var pubKey; if (PrivateKey.isPrivateKey(key)) pubKey = key.toPublic(); else pubKey = key; var cipher = 'none'; var kdf = 'none'; var kdfopts = Buffer.alloc(0); var cinf = { blockSize: 8 }; var passphrase; if (options !== undefined) { passphrase = options.passphrase; if (typeof (passphrase) === 'string') passphrase = Buffer.from(passphrase, 'utf-8'); if (passphrase !== undefined) { assert.buffer(passphrase, 'options.passphrase'); assert.optionalString(options.cipher, 'options.cipher'); cipher = options.cipher; if (cipher === undefined) cipher = 'aes128-ctr'; cinf = utils.opensshCipherInfo(cipher); kdf = 'bcrypt'; } } var privBuf; if (PrivateKey.isPrivateKey(key)) { privBuf = new SSHBuffer({}); var checkInt = crypto.randomBytes(4).readUInt32BE(0); privBuf.writeInt(checkInt); privBuf.writeInt(checkInt); privBuf.write(key.toBuffer('rfc4253')); privBuf.writeString(key.comment || ''); var n = 1; while (privBuf._offset % cinf.blockSize !== 0) privBuf.writeChar(n++); privBuf = privBuf.toBuffer(); } switch (kdf) { case 'none': break; case 'bcrypt': var salt = crypto.randomBytes(16); var rounds = 16; var kdfssh = new SSHBuffer({}); kdfssh.writeBuffer(salt); kdfssh.writeInt(rounds); kdfopts = kdfssh.toBuffer(); if (bcrypt === undefined) { bcrypt = require('bcrypt-pbkdf'); } var pass = new Uint8Array(passphrase); var salti = new Uint8Array(salt); /* Use the pbkdf to derive both the key and the IV. */ var out = new Uint8Array(cinf.keySize + cinf.blockSize); var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length, out, out.length, rounds); if (res !== 0) { throw (new Error('bcrypt_pbkdf function returned ' + 'failure, parameters invalid')); } out = Buffer.from(out); var ckey = out.slice(0, cinf.keySize); var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize); var cipherStream = crypto.createCipheriv(cinf.opensslName, ckey, iv); cipherStream.setAutoPadding(false); var chunk, chunks = []; cipherStream.once('error', function (e) { throw (e); }); cipherStream.write(privBuf); cipherStream.end(); while ((chunk = cipherStream.read()) !== null) chunks.push(chunk); privBuf = Buffer.concat(chunks); break; default: throw (new Error('Unsupported kdf ' + kdf)); } var buf = new SSHBuffer({}); buf.writeCString(MAGIC); buf.writeString(cipher); /* cipher */ buf.writeString(kdf); /* kdf */ buf.writeBuffer(kdfopts); /* kdfoptions */ buf.writeInt(1); /* nkeys */ buf.writeBuffer(pubKey.toBuffer('rfc4253')); if (privBuf) buf.writeBuffer(privBuf); buf = buf.toBuffer(); var header; if (PrivateKey.isPrivateKey(key)) header = 'OPENSSH PRIVATE KEY'; else header = 'OPENSSH PUBLIC KEY'; var tmp = buf.toString('base64'); var len = tmp.length + (tmp.length / 70) + 18 + 16 + header.length*2 + 10; buf = Buffer.alloc(len); var o = 0; o += buf.write('-----BEGIN ' + header + '-----\n', o); for (var i = 0; i < tmp.length; ) { var limit = i + 70; if (limit > tmp.length) limit = tmp.length; o += buf.write(tmp.slice(i, limit), o); buf[o++] = 10; i = limit; } o += buf.write('-----END ' + header + '-----\n', o); return (buf.slice(0, o)); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/formats/ssh-private.js
ssh-private.js
module.exports = { read: read, write: write }; var assert = require('assert-plus'); var Buffer = require('safer-buffer').Buffer; var rfc4253 = require('sshpk/lib/formats/rfc4253'); var Key = require('sshpk/lib/key'); var errors = require('sshpk/lib/errors'); function read(buf, options) { var lines = buf.toString('ascii').split(/[\r\n]+/); var found = false; var parts; var si = 0; while (si < lines.length) { parts = splitHeader(lines[si++]); if (parts && parts[0].toLowerCase() === 'putty-user-key-file-2') { found = true; break; } } if (!found) { throw (new Error('No PuTTY format first line found')); } var alg = parts[1]; parts = splitHeader(lines[si++]); assert.equal(parts[0].toLowerCase(), 'encryption'); parts = splitHeader(lines[si++]); assert.equal(parts[0].toLowerCase(), 'comment'); var comment = parts[1]; parts = splitHeader(lines[si++]); assert.equal(parts[0].toLowerCase(), 'public-lines'); var publicLines = parseInt(parts[1], 10); if (!isFinite(publicLines) || publicLines < 0 || publicLines > lines.length) { throw (new Error('Invalid public-lines count')); } var publicBuf = Buffer.from( lines.slice(si, si + publicLines).join(''), 'base64'); var keyType = rfc4253.algToKeyType(alg); var key = rfc4253.read(publicBuf); if (key.type !== keyType) { throw (new Error('Outer key algorithm mismatch')); } key.comment = comment; return (key); } function splitHeader(line) { var idx = line.indexOf(':'); if (idx === -1) return (null); var header = line.slice(0, idx); ++idx; while (line[idx] === ' ') ++idx; var rest = line.slice(idx); return ([header, rest]); } function write(key, options) { assert.object(key); if (!Key.isKey(key)) throw (new Error('Must be a public key')); var alg = rfc4253.keyTypeToAlg(key); var buf = rfc4253.write(key); var comment = key.comment || ''; var b64 = buf.toString('base64'); var lines = wrap(b64, 64); lines.unshift('Public-Lines: ' + lines.length); lines.unshift('Comment: ' + comment); lines.unshift('Encryption: none'); lines.unshift('PuTTY-User-Key-File-2: ' + alg); return (Buffer.from(lines.join('\n') + '\n')); } function wrap(txt, len) { var lines = []; var pos = 0; while (pos < txt.length) { lines.push(txt.slice(pos, pos + 64)); pos += 64; } return (lines); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/formats/putty.js
putty.js
module.exports = { read: read, write: write }; var assert = require('assert-plus'); var asn1 = require('asn1'); var crypto = require('crypto'); var Buffer = require('safer-buffer').Buffer; var algs = require('sshpk/lib/algs'); var utils = require('sshpk/lib/utils'); var Key = require('sshpk/lib/key'); var PrivateKey = require('sshpk/lib/private-key'); var pkcs1 = require('sshpk/lib/formats/pkcs1'); var pkcs8 = require('sshpk/lib/formats/pkcs8'); var sshpriv = require('sshpk/lib/formats/ssh-private'); var rfc4253 = require('sshpk/lib/formats/rfc4253'); var errors = require('sshpk/lib/errors'); var OID_PBES2 = '1.2.840.113549.1.5.13'; var OID_PBKDF2 = '1.2.840.113549.1.5.12'; var OID_TO_CIPHER = { '1.2.840.113549.3.7': '3des-cbc', '2.16.840.1.101.3.4.1.2': 'aes128-cbc', '2.16.840.1.101.3.4.1.42': 'aes256-cbc' }; var CIPHER_TO_OID = {}; Object.keys(OID_TO_CIPHER).forEach(function (k) { CIPHER_TO_OID[OID_TO_CIPHER[k]] = k; }); var OID_TO_HASH = { '1.2.840.113549.2.7': 'sha1', '1.2.840.113549.2.9': 'sha256', '1.2.840.113549.2.11': 'sha512' }; var HASH_TO_OID = {}; Object.keys(OID_TO_HASH).forEach(function (k) { HASH_TO_OID[OID_TO_HASH[k]] = k; }); /* * For reading we support both PKCS#1 and PKCS#8. If we find a private key, * we just take the public component of it and use that. */ function read(buf, options, forceType) { var input = buf; if (typeof (buf) !== 'string') { assert.buffer(buf, 'buf'); buf = buf.toString('ascii'); } var lines = buf.trim().split(/[\r\n]+/g); var m; var si = -1; while (!m && si < lines.length) { m = lines[++si].match(/*JSSTYLED*/ /[-]+[ ]*BEGIN ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/); } assert.ok(m, 'invalid PEM header'); var m2; var ei = lines.length; while (!m2 && ei > 0) { m2 = lines[--ei].match(/*JSSTYLED*/ /[-]+[ ]*END ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/); } assert.ok(m2, 'invalid PEM footer'); /* Begin and end banners must match key type */ assert.equal(m[2], m2[2]); var type = m[2].toLowerCase(); var alg; if (m[1]) { /* They also must match algorithms, if given */ assert.equal(m[1], m2[1], 'PEM header and footer mismatch'); alg = m[1].trim(); } lines = lines.slice(si, ei + 1); var headers = {}; while (true) { lines = lines.slice(1); m = lines[0].match(/*JSSTYLED*/ /^([A-Za-z0-9-]+): (.+)$/); if (!m) break; headers[m[1].toLowerCase()] = m[2]; } /* Chop off the first and last lines */ lines = lines.slice(0, -1).join(''); buf = Buffer.from(lines, 'base64'); var cipher, key, iv; if (headers['proc-type']) { var parts = headers['proc-type'].split(','); if (parts[0] === '4' && parts[1] === 'ENCRYPTED') { if (typeof (options.passphrase) === 'string') { options.passphrase = Buffer.from( options.passphrase, 'utf-8'); } if (!Buffer.isBuffer(options.passphrase)) { throw (new errors.KeyEncryptedError( options.filename, 'PEM')); } else { parts = headers['dek-info'].split(','); assert.ok(parts.length === 2); cipher = parts[0].toLowerCase(); iv = Buffer.from(parts[1], 'hex'); key = utils.opensslKeyDeriv(cipher, iv, options.passphrase, 1).key; } } } if (alg && alg.toLowerCase() === 'encrypted') { var eder = new asn1.BerReader(buf); var pbesEnd; eder.readSequence(); eder.readSequence(); pbesEnd = eder.offset + eder.length; var method = eder.readOID(); if (method !== OID_PBES2) { throw (new Error('Unsupported PEM/PKCS8 encryption ' + 'scheme: ' + method)); } eder.readSequence(); /* PBES2-params */ eder.readSequence(); /* keyDerivationFunc */ var kdfEnd = eder.offset + eder.length; var kdfOid = eder.readOID(); if (kdfOid !== OID_PBKDF2) throw (new Error('Unsupported PBES2 KDF: ' + kdfOid)); eder.readSequence(); var salt = eder.readString(asn1.Ber.OctetString, true); var iterations = eder.readInt(); var hashAlg = 'sha1'; if (eder.offset < kdfEnd) { eder.readSequence(); var hashAlgOid = eder.readOID(); hashAlg = OID_TO_HASH[hashAlgOid]; if (hashAlg === undefined) { throw (new Error('Unsupported PBKDF2 hash: ' + hashAlgOid)); } } eder._offset = kdfEnd; eder.readSequence(); /* encryptionScheme */ var cipherOid = eder.readOID(); cipher = OID_TO_CIPHER[cipherOid]; if (cipher === undefined) { throw (new Error('Unsupported PBES2 cipher: ' + cipherOid)); } iv = eder.readString(asn1.Ber.OctetString, true); eder._offset = pbesEnd; buf = eder.readString(asn1.Ber.OctetString, true); if (typeof (options.passphrase) === 'string') { options.passphrase = Buffer.from( options.passphrase, 'utf-8'); } if (!Buffer.isBuffer(options.passphrase)) { throw (new errors.KeyEncryptedError( options.filename, 'PEM')); } var cinfo = utils.opensshCipherInfo(cipher); cipher = cinfo.opensslName; key = utils.pbkdf2(hashAlg, salt, iterations, cinfo.keySize, options.passphrase); alg = undefined; } if (cipher && key && iv) { var cipherStream = crypto.createDecipheriv(cipher, key, iv); var chunk, chunks = []; cipherStream.once('error', function (e) { if (e.toString().indexOf('bad decrypt') !== -1) { throw (new Error('Incorrect passphrase ' + 'supplied, could not decrypt key')); } throw (e); }); cipherStream.write(buf); cipherStream.end(); while ((chunk = cipherStream.read()) !== null) chunks.push(chunk); buf = Buffer.concat(chunks); } /* The new OpenSSH internal format abuses PEM headers */ if (alg && alg.toLowerCase() === 'openssh') return (sshpriv.readSSHPrivate(type, buf, options)); if (alg && alg.toLowerCase() === 'ssh2') return (rfc4253.readType(type, buf, options)); var der = new asn1.BerReader(buf); der.originalInput = input; /* * All of the PEM file types start with a sequence tag, so chop it * off here */ der.readSequence(); /* PKCS#1 type keys name an algorithm in the banner explicitly */ if (alg) { if (forceType) assert.strictEqual(forceType, 'pkcs1'); return (pkcs1.readPkcs1(alg, type, der)); } else { if (forceType) assert.strictEqual(forceType, 'pkcs8'); return (pkcs8.readPkcs8(alg, type, der)); } } function write(key, options, type) { assert.object(key); var alg = { 'ecdsa': 'EC', 'rsa': 'RSA', 'dsa': 'DSA', 'ed25519': 'EdDSA' }[key.type]; var header; var der = new asn1.BerWriter(); if (PrivateKey.isPrivateKey(key)) { if (type && type === 'pkcs8') { header = 'PRIVATE KEY'; pkcs8.writePkcs8(der, key); } else { if (type) assert.strictEqual(type, 'pkcs1'); header = alg + ' PRIVATE KEY'; pkcs1.writePkcs1(der, key); } } else if (Key.isKey(key)) { if (type && type === 'pkcs1') { header = alg + ' PUBLIC KEY'; pkcs1.writePkcs1(der, key); } else { if (type) assert.strictEqual(type, 'pkcs8'); header = 'PUBLIC KEY'; pkcs8.writePkcs8(der, key); } } else { throw (new Error('key is not a Key or PrivateKey')); } var tmp = der.buffer.toString('base64'); var len = tmp.length + (tmp.length / 64) + 18 + 16 + header.length*2 + 10; var buf = Buffer.alloc(len); var o = 0; o += buf.write('-----BEGIN ' + header + '-----\n', o); for (var i = 0; i < tmp.length; ) { var limit = i + 64; if (limit > tmp.length) limit = tmp.length; o += buf.write(tmp.slice(i, limit), o); buf[o++] = 10; i = limit; } o += buf.write('-----END ' + header + '-----\n', o); return (buf.slice(0, o)); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/formats/pem.js
pem.js
module.exports = { read: read, verify: verify, sign: sign, signAsync: signAsync, write: write }; var assert = require('assert-plus'); var asn1 = require('asn1'); var Buffer = require('safer-buffer').Buffer; var algs = require('sshpk/lib/algs'); var utils = require('sshpk/lib/utils'); var Key = require('sshpk/lib/key'); var PrivateKey = require('sshpk/lib/private-key'); var pem = require('sshpk/lib/formats/pem'); var Identity = require('sshpk/lib/identity'); var Signature = require('sshpk/lib/signature'); var Certificate = require('sshpk/lib/certificate'); var pkcs8 = require('sshpk/lib/formats/pkcs8'); /* * This file is based on RFC5280 (X.509). */ /* Helper to read in a single mpint */ function readMPInt(der, nm) { assert.strictEqual(der.peek(), asn1.Ber.Integer, nm + ' is not an Integer'); return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); } function verify(cert, key) { var sig = cert.signatures.x509; assert.object(sig, 'x509 signature'); var algParts = sig.algo.split('-'); if (algParts[0] !== key.type) return (false); var blob = sig.cache; if (blob === undefined) { var der = new asn1.BerWriter(); writeTBSCert(cert, der); blob = der.buffer; } var verifier = key.createVerify(algParts[1]); verifier.write(blob); return (verifier.verify(sig.signature)); } function Local(i) { return (asn1.Ber.Context | asn1.Ber.Constructor | i); } function Context(i) { return (asn1.Ber.Context | i); } var SIGN_ALGS = { 'rsa-md5': '1.2.840.113549.1.1.4', 'rsa-sha1': '1.2.840.113549.1.1.5', 'rsa-sha256': '1.2.840.113549.1.1.11', 'rsa-sha384': '1.2.840.113549.1.1.12', 'rsa-sha512': '1.2.840.113549.1.1.13', 'dsa-sha1': '1.2.840.10040.4.3', 'dsa-sha256': '2.16.840.1.101.3.4.3.2', 'ecdsa-sha1': '1.2.840.10045.4.1', 'ecdsa-sha256': '1.2.840.10045.4.3.2', 'ecdsa-sha384': '1.2.840.10045.4.3.3', 'ecdsa-sha512': '1.2.840.10045.4.3.4', 'ed25519-sha512': '1.3.101.112' }; Object.keys(SIGN_ALGS).forEach(function (k) { SIGN_ALGS[SIGN_ALGS[k]] = k; }); SIGN_ALGS['1.3.14.3.2.3'] = 'rsa-md5'; SIGN_ALGS['1.3.14.3.2.29'] = 'rsa-sha1'; var EXTS = { 'issuerKeyId': '2.5.29.35', 'altName': '2.5.29.17', 'basicConstraints': '2.5.29.19', 'keyUsage': '2.5.29.15', 'extKeyUsage': '2.5.29.37' }; function read(buf, options) { if (typeof (buf) === 'string') { buf = Buffer.from(buf, 'binary'); } assert.buffer(buf, 'buf'); var der = new asn1.BerReader(buf); der.readSequence(); if (Math.abs(der.length - der.remain) > 1) { throw (new Error('DER sequence does not contain whole byte ' + 'stream')); } var tbsStart = der.offset; der.readSequence(); var sigOffset = der.offset + der.length; var tbsEnd = sigOffset; if (der.peek() === Local(0)) { der.readSequence(Local(0)); var version = der.readInt(); assert.ok(version <= 3, 'only x.509 versions up to v3 supported'); } var cert = {}; cert.signatures = {}; var sig = (cert.signatures.x509 = {}); sig.extras = {}; cert.serial = readMPInt(der, 'serial'); der.readSequence(); var after = der.offset + der.length; var certAlgOid = der.readOID(); var certAlg = SIGN_ALGS[certAlgOid]; if (certAlg === undefined) throw (new Error('unknown signature algorithm ' + certAlgOid)); der._offset = after; cert.issuer = Identity.parseAsn1(der); der.readSequence(); cert.validFrom = readDate(der); cert.validUntil = readDate(der); cert.subjects = [Identity.parseAsn1(der)]; der.readSequence(); after = der.offset + der.length; cert.subjectKey = pkcs8.readPkcs8(undefined, 'public', der); der._offset = after; /* issuerUniqueID */ if (der.peek() === Local(1)) { der.readSequence(Local(1)); sig.extras.issuerUniqueID = buf.slice(der.offset, der.offset + der.length); der._offset += der.length; } /* subjectUniqueID */ if (der.peek() === Local(2)) { der.readSequence(Local(2)); sig.extras.subjectUniqueID = buf.slice(der.offset, der.offset + der.length); der._offset += der.length; } /* extensions */ if (der.peek() === Local(3)) { der.readSequence(Local(3)); var extEnd = der.offset + der.length; der.readSequence(); while (der.offset < extEnd) readExtension(cert, buf, der); assert.strictEqual(der.offset, extEnd); } assert.strictEqual(der.offset, sigOffset); der.readSequence(); after = der.offset + der.length; var sigAlgOid = der.readOID(); var sigAlg = SIGN_ALGS[sigAlgOid]; if (sigAlg === undefined) throw (new Error('unknown signature algorithm ' + sigAlgOid)); der._offset = after; var sigData = der.readString(asn1.Ber.BitString, true); if (sigData[0] === 0) sigData = sigData.slice(1); var algParts = sigAlg.split('-'); sig.signature = Signature.parse(sigData, algParts[0], 'asn1'); sig.signature.hashAlgorithm = algParts[1]; sig.algo = sigAlg; sig.cache = buf.slice(tbsStart, tbsEnd); return (new Certificate(cert)); } function readDate(der) { if (der.peek() === asn1.Ber.UTCTime) { return (utcTimeToDate(der.readString(asn1.Ber.UTCTime))); } else if (der.peek() === asn1.Ber.GeneralizedTime) { return (gTimeToDate(der.readString(asn1.Ber.GeneralizedTime))); } else { throw (new Error('Unsupported date format')); } } function writeDate(der, date) { if (date.getUTCFullYear() >= 2050 || date.getUTCFullYear() < 1950) { der.writeString(dateToGTime(date), asn1.Ber.GeneralizedTime); } else { der.writeString(dateToUTCTime(date), asn1.Ber.UTCTime); } } /* RFC5280, section 4.2.1.6 (GeneralName type) */ var ALTNAME = { OtherName: Local(0), RFC822Name: Context(1), DNSName: Context(2), X400Address: Local(3), DirectoryName: Local(4), EDIPartyName: Local(5), URI: Context(6), IPAddress: Context(7), OID: Context(8) }; /* RFC5280, section 4.2.1.12 (KeyPurposeId) */ var EXTPURPOSE = { 'serverAuth': '1.3.6.1.5.5.7.3.1', 'clientAuth': '1.3.6.1.5.5.7.3.2', 'codeSigning': '1.3.6.1.5.5.7.3.3', /* See https://github.com/joyent/oid-docs/blob/master/root.md */ 'joyentDocker': '1.3.6.1.4.1.38678.1.4.1', 'joyentCmon': '1.3.6.1.4.1.38678.1.4.2' }; var EXTPURPOSE_REV = {}; Object.keys(EXTPURPOSE).forEach(function (k) { EXTPURPOSE_REV[EXTPURPOSE[k]] = k; }); var KEYUSEBITS = [ 'signature', 'identity', 'keyEncryption', 'encryption', 'keyAgreement', 'ca', 'crl' ]; function readExtension(cert, buf, der) { der.readSequence(); var after = der.offset + der.length; var extId = der.readOID(); var id; var sig = cert.signatures.x509; if (!sig.extras.exts) sig.extras.exts = []; var critical; if (der.peek() === asn1.Ber.Boolean) critical = der.readBoolean(); switch (extId) { case (EXTS.basicConstraints): der.readSequence(asn1.Ber.OctetString); der.readSequence(); var bcEnd = der.offset + der.length; var ca = false; if (der.peek() === asn1.Ber.Boolean) ca = der.readBoolean(); if (cert.purposes === undefined) cert.purposes = []; if (ca === true) cert.purposes.push('ca'); var bc = { oid: extId, critical: critical }; if (der.offset < bcEnd && der.peek() === asn1.Ber.Integer) bc.pathLen = der.readInt(); sig.extras.exts.push(bc); break; case (EXTS.extKeyUsage): der.readSequence(asn1.Ber.OctetString); der.readSequence(); if (cert.purposes === undefined) cert.purposes = []; var ekEnd = der.offset + der.length; while (der.offset < ekEnd) { var oid = der.readOID(); cert.purposes.push(EXTPURPOSE_REV[oid] || oid); } /* * This is a bit of a hack: in the case where we have a cert * that's only allowed to do serverAuth or clientAuth (and not * the other), we want to make sure all our Subjects are of * the right type. But we already parsed our Subjects and * decided if they were hosts or users earlier (since it appears * first in the cert). * * So we go through and mutate them into the right kind here if * it doesn't match. This might not be hugely beneficial, as it * seems that single-purpose certs are not often seen in the * wild. */ if (cert.purposes.indexOf('serverAuth') !== -1 && cert.purposes.indexOf('clientAuth') === -1) { cert.subjects.forEach(function (ide) { if (ide.type !== 'host') { ide.type = 'host'; ide.hostname = ide.uid || ide.email || ide.components[0].value; } }); } else if (cert.purposes.indexOf('clientAuth') !== -1 && cert.purposes.indexOf('serverAuth') === -1) { cert.subjects.forEach(function (ide) { if (ide.type !== 'user') { ide.type = 'user'; ide.uid = ide.hostname || ide.email || ide.components[0].value; } }); } sig.extras.exts.push({ oid: extId, critical: critical }); break; case (EXTS.keyUsage): der.readSequence(asn1.Ber.OctetString); var bits = der.readString(asn1.Ber.BitString, true); var setBits = readBitField(bits, KEYUSEBITS); setBits.forEach(function (bit) { if (cert.purposes === undefined) cert.purposes = []; if (cert.purposes.indexOf(bit) === -1) cert.purposes.push(bit); }); sig.extras.exts.push({ oid: extId, critical: critical, bits: bits }); break; case (EXTS.altName): der.readSequence(asn1.Ber.OctetString); der.readSequence(); var aeEnd = der.offset + der.length; while (der.offset < aeEnd) { switch (der.peek()) { case ALTNAME.OtherName: case ALTNAME.EDIPartyName: der.readSequence(); der._offset += der.length; break; case ALTNAME.OID: der.readOID(ALTNAME.OID); break; case ALTNAME.RFC822Name: /* RFC822 specifies email addresses */ var email = der.readString(ALTNAME.RFC822Name); id = Identity.forEmail(email); if (!cert.subjects[0].equals(id)) cert.subjects.push(id); break; case ALTNAME.DirectoryName: der.readSequence(ALTNAME.DirectoryName); id = Identity.parseAsn1(der); if (!cert.subjects[0].equals(id)) cert.subjects.push(id); break; case ALTNAME.DNSName: var host = der.readString( ALTNAME.DNSName); id = Identity.forHost(host); if (!cert.subjects[0].equals(id)) cert.subjects.push(id); break; default: der.readString(der.peek()); break; } } sig.extras.exts.push({ oid: extId, critical: critical }); break; default: sig.extras.exts.push({ oid: extId, critical: critical, data: der.readString(asn1.Ber.OctetString, true) }); break; } der._offset = after; } var UTCTIME_RE = /^([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/; function utcTimeToDate(t) { var m = t.match(UTCTIME_RE); assert.ok(m, 'timestamps must be in UTC'); var d = new Date(); var thisYear = d.getUTCFullYear(); var century = Math.floor(thisYear / 100) * 100; var year = parseInt(m[1], 10); if (thisYear % 100 < 50 && year >= 60) year += (century - 1); else year += century; d.setUTCFullYear(year, parseInt(m[2], 10) - 1, parseInt(m[3], 10)); d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10)); if (m[6] && m[6].length > 0) d.setUTCSeconds(parseInt(m[6], 10)); return (d); } var GTIME_RE = /^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/; function gTimeToDate(t) { var m = t.match(GTIME_RE); assert.ok(m); var d = new Date(); d.setUTCFullYear(parseInt(m[1], 10), parseInt(m[2], 10) - 1, parseInt(m[3], 10)); d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10)); if (m[6] && m[6].length > 0) d.setUTCSeconds(parseInt(m[6], 10)); return (d); } function zeroPad(n, m) { if (m === undefined) m = 2; var s = '' + n; while (s.length < m) s = '0' + s; return (s); } function dateToUTCTime(d) { var s = ''; s += zeroPad(d.getUTCFullYear() % 100); s += zeroPad(d.getUTCMonth() + 1); s += zeroPad(d.getUTCDate()); s += zeroPad(d.getUTCHours()); s += zeroPad(d.getUTCMinutes()); s += zeroPad(d.getUTCSeconds()); s += 'Z'; return (s); } function dateToGTime(d) { var s = ''; s += zeroPad(d.getUTCFullYear(), 4); s += zeroPad(d.getUTCMonth() + 1); s += zeroPad(d.getUTCDate()); s += zeroPad(d.getUTCHours()); s += zeroPad(d.getUTCMinutes()); s += zeroPad(d.getUTCSeconds()); s += 'Z'; return (s); } function sign(cert, key) { if (cert.signatures.x509 === undefined) cert.signatures.x509 = {}; var sig = cert.signatures.x509; sig.algo = key.type + '-' + key.defaultHashAlgorithm(); if (SIGN_ALGS[sig.algo] === undefined) return (false); var der = new asn1.BerWriter(); writeTBSCert(cert, der); var blob = der.buffer; sig.cache = blob; var signer = key.createSign(); signer.write(blob); cert.signatures.x509.signature = signer.sign(); return (true); } function signAsync(cert, signer, done) { if (cert.signatures.x509 === undefined) cert.signatures.x509 = {}; var sig = cert.signatures.x509; var der = new asn1.BerWriter(); writeTBSCert(cert, der); var blob = der.buffer; sig.cache = blob; signer(blob, function (err, signature) { if (err) { done(err); return; } sig.algo = signature.type + '-' + signature.hashAlgorithm; if (SIGN_ALGS[sig.algo] === undefined) { done(new Error('Invalid signing algorithm "' + sig.algo + '"')); return; } sig.signature = signature; done(); }); } function write(cert, options) { var sig = cert.signatures.x509; assert.object(sig, 'x509 signature'); var der = new asn1.BerWriter(); der.startSequence(); if (sig.cache) { der._ensure(sig.cache.length); sig.cache.copy(der._buf, der._offset); der._offset += sig.cache.length; } else { writeTBSCert(cert, der); } der.startSequence(); der.writeOID(SIGN_ALGS[sig.algo]); if (sig.algo.match(/^rsa-/)) der.writeNull(); der.endSequence(); var sigData = sig.signature.toBuffer('asn1'); var data = Buffer.alloc(sigData.length + 1); data[0] = 0; sigData.copy(data, 1); der.writeBuffer(data, asn1.Ber.BitString); der.endSequence(); return (der.buffer); } function writeTBSCert(cert, der) { var sig = cert.signatures.x509; assert.object(sig, 'x509 signature'); der.startSequence(); der.startSequence(Local(0)); der.writeInt(2); der.endSequence(); der.writeBuffer(utils.mpNormalize(cert.serial), asn1.Ber.Integer); der.startSequence(); der.writeOID(SIGN_ALGS[sig.algo]); if (sig.algo.match(/^rsa-/)) der.writeNull(); der.endSequence(); cert.issuer.toAsn1(der); der.startSequence(); writeDate(der, cert.validFrom); writeDate(der, cert.validUntil); der.endSequence(); var subject = cert.subjects[0]; var altNames = cert.subjects.slice(1); subject.toAsn1(der); pkcs8.writePkcs8(der, cert.subjectKey); if (sig.extras && sig.extras.issuerUniqueID) { der.writeBuffer(sig.extras.issuerUniqueID, Local(1)); } if (sig.extras && sig.extras.subjectUniqueID) { der.writeBuffer(sig.extras.subjectUniqueID, Local(2)); } if (altNames.length > 0 || subject.type === 'host' || (cert.purposes !== undefined && cert.purposes.length > 0) || (sig.extras && sig.extras.exts)) { der.startSequence(Local(3)); der.startSequence(); var exts = []; if (cert.purposes !== undefined && cert.purposes.length > 0) { exts.push({ oid: EXTS.basicConstraints, critical: true }); exts.push({ oid: EXTS.keyUsage, critical: true }); exts.push({ oid: EXTS.extKeyUsage, critical: true }); } exts.push({ oid: EXTS.altName }); if (sig.extras && sig.extras.exts) exts = sig.extras.exts; for (var i = 0; i < exts.length; ++i) { der.startSequence(); der.writeOID(exts[i].oid); if (exts[i].critical !== undefined) der.writeBoolean(exts[i].critical); if (exts[i].oid === EXTS.altName) { der.startSequence(asn1.Ber.OctetString); der.startSequence(); if (subject.type === 'host') { der.writeString(subject.hostname, Context(2)); } for (var j = 0; j < altNames.length; ++j) { if (altNames[j].type === 'host') { der.writeString( altNames[j].hostname, ALTNAME.DNSName); } else if (altNames[j].type === 'email') { der.writeString( altNames[j].email, ALTNAME.RFC822Name); } else { /* * Encode anything else as a * DN style name for now. */ der.startSequence( ALTNAME.DirectoryName); altNames[j].toAsn1(der); der.endSequence(); } } der.endSequence(); der.endSequence(); } else if (exts[i].oid === EXTS.basicConstraints) { der.startSequence(asn1.Ber.OctetString); der.startSequence(); var ca = (cert.purposes.indexOf('ca') !== -1); var pathLen = exts[i].pathLen; der.writeBoolean(ca); if (pathLen !== undefined) der.writeInt(pathLen); der.endSequence(); der.endSequence(); } else if (exts[i].oid === EXTS.extKeyUsage) { der.startSequence(asn1.Ber.OctetString); der.startSequence(); cert.purposes.forEach(function (purpose) { if (purpose === 'ca') return; if (KEYUSEBITS.indexOf(purpose) !== -1) return; var oid = purpose; if (EXTPURPOSE[purpose] !== undefined) oid = EXTPURPOSE[purpose]; der.writeOID(oid); }); der.endSequence(); der.endSequence(); } else if (exts[i].oid === EXTS.keyUsage) { der.startSequence(asn1.Ber.OctetString); /* * If we parsed this certificate from a byte * stream (i.e. we didn't generate it in sshpk) * then we'll have a ".bits" property on the * ext with the original raw byte contents. * * If we have this, use it here instead of * regenerating it. This guarantees we output * the same data we parsed, so signatures still * validate. */ if (exts[i].bits !== undefined) { der.writeBuffer(exts[i].bits, asn1.Ber.BitString); } else { var bits = writeBitField(cert.purposes, KEYUSEBITS); der.writeBuffer(bits, asn1.Ber.BitString); } der.endSequence(); } else { der.writeBuffer(exts[i].data, asn1.Ber.OctetString); } der.endSequence(); } der.endSequence(); der.endSequence(); } der.endSequence(); } /* * Reads an ASN.1 BER bitfield out of the Buffer produced by doing * `BerReader#readString(asn1.Ber.BitString)`. That function gives us the raw * contents of the BitString tag, which is a count of unused bits followed by * the bits as a right-padded byte string. * * `bits` is the Buffer, `bitIndex` should contain an array of string names * for the bits in the string, ordered starting with bit #0 in the ASN.1 spec. * * Returns an array of Strings, the names of the bits that were set to 1. */ function readBitField(bits, bitIndex) { var bitLen = 8 * (bits.length - 1) - bits[0]; var setBits = {}; for (var i = 0; i < bitLen; ++i) { var byteN = 1 + Math.floor(i / 8); var bit = 7 - (i % 8); var mask = 1 << bit; var bitVal = ((bits[byteN] & mask) !== 0); var name = bitIndex[i]; if (bitVal && typeof (name) === 'string') { setBits[name] = true; } } return (Object.keys(setBits)); } /* * `setBits` is an array of strings, containing the names for each bit that * sould be set to 1. `bitIndex` is same as in `readBitField()`. * * Returns a Buffer, ready to be written out with `BerWriter#writeString()`. */ function writeBitField(setBits, bitIndex) { var bitLen = bitIndex.length; var blen = Math.ceil(bitLen / 8); var unused = blen * 8 - bitLen; var bits = Buffer.alloc(1 + blen); // zero-filled bits[0] = unused; for (var i = 0; i < bitLen; ++i) { var byteN = 1 + Math.floor(i / 8); var bit = 7 - (i % 8); var mask = 1 << bit; var name = bitIndex[i]; if (name === undefined) continue; var bitVal = (setBits.indexOf(name) !== -1); if (bitVal) { bits[byteN] |= mask; } } return (bits); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/sshpk/lib/formats/x509.js
x509.js
# Acorn AST walker An abstract syntax tree walker for the [ESTree](https://github.com/estree/estree) format. ## Community Acorn is open source software released under an [MIT license](https://github.com/acornjs/acorn/blob/master/acorn-walk/LICENSE). You are welcome to [report bugs](https://github.com/acornjs/acorn/issues) or create pull requests on [github](https://github.com/acornjs/acorn). For questions and discussion, please use the [Tern discussion forum](https://discuss.ternjs.net). ## Installation The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): ```sh npm install acorn-walk ``` Alternately, you can download the source and build acorn yourself: ```sh git clone https://github.com/acornjs/acorn.git cd acorn npm install ``` ## Interface An algorithm for recursing through a syntax tree is stored as an object, with a property for each tree node type holding a function that will recurse through such a node. There are several ways to run such a walker. **simple**`(node, visitors, base, state)` does a 'simple' walk over a tree. `node` should be the AST node to walk, and `visitors` an object with properties whose names correspond to node types in the [ESTree spec](https://github.com/estree/estree). The properties should contain functions that will be called with the node object and, if applicable the state at that point. The last two arguments are optional. `base` is a walker algorithm, and `state` is a start state. The default walker will simply visit all statements and expressions and not produce a meaningful state. (An example of a use of state is to track scope at each point in the tree.) ```js const acorn = require("acorn") const walk = require("acorn-walk") walk.simple(acorn.parse("let x = 10"), { Literal(node) { console.log(`Found a literal: ${node.value}`) } }) ``` **ancestor**`(node, visitors, base, state)` does a 'simple' walk over a tree, building up an array of ancestor nodes (including the current node) and passing the array to the callbacks as a third parameter. ```js const acorn = require("acorn") const walk = require("acorn-walk") walk.ancestor(acorn.parse("foo('hi')"), { Literal(_, ancestors) { console.log("This literal's ancestors are:", ancestors.map(n => n.type)) } }) ``` **recursive**`(node, state, functions, base)` does a 'recursive' walk, where the walker functions are responsible for continuing the walk on the child nodes of their target node. `state` is the start state, and `functions` should contain an object that maps node types to walker functions. Such functions are called with `(node, state, c)` arguments, and can cause the walk to continue on a sub-node by calling the `c` argument on it with `(node, state)` arguments. The optional `base` argument provides the fallback walker functions for node types that aren't handled in the `functions` object. If not given, the default walkers will be used. **make**`(functions, base)` builds a new walker object by using the walker functions in `functions` and filling in the missing ones by taking defaults from `base`. **full**`(node, callback, base, state)` does a 'full' walk over a tree, calling the callback with the arguments (node, state, type) for each node **fullAncestor**`(node, callback, base, state)` does a 'full' walk over a tree, building up an array of ancestor nodes (including the current node) and passing the array to the callbacks as a third parameter. ```js const acorn = require("acorn") const walk = require("acorn-walk") walk.full(acorn.parse("1 + 1"), node => { console.log(`There's a ${node.type} node at ${node.ch}`) }) ``` **findNodeAt**`(node, start, end, test, base, state)` tries to locate a node in a tree at the given start and/or end offsets, which satisfies the predicate `test`. `start` and `end` can be either `null` (as wildcard) or a number. `test` may be a string (indicating a node type) or a function that takes `(nodeType, node)` arguments and returns a boolean indicating whether this node is interesting. `base` and `state` are optional, and can be used to specify a custom walker. Nodes are tested from inner to outer, so if two nodes match the boundaries, the inner one will be preferred. **findNodeAround**`(node, pos, test, base, state)` is a lot like `findNodeAt`, but will match any node that exists 'around' (spanning) the given position. **findNodeAfter**`(node, pos, test, base, state)` is similar to `findNodeAround`, but will match all nodes *after* the given position (testing outer nodes before inner nodes).
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/acorn-walk/README.md
README.md
## 7.2.0 (2020-06-17) ### New features Support optional chaining and nullish coalescing. Support `import.meta`. Add support for `export * as ns from "source"`. ## 7.1.1 (2020-02-13) ### Bug fixes Clean up the type definitions to actually work well with the main parser. ## 7.1.0 (2020-02-11) ### New features Add a TypeScript definition file for the library. ## 7.0.0 (2017-08-12) ### New features Support walking `ImportExpression` nodes. ## 6.2.0 (2017-07-04) ### New features Add support for `Import` nodes. ## 6.1.0 (2018-09-28) ### New features The walker now walks `TemplateElement` nodes. ## 6.0.1 (2018-09-14) ### Bug fixes Fix bad "main" field in package.json. ## 6.0.0 (2018-09-14) ### Breaking changes This is now a separate package, `acorn-walk`, rather than part of the main `acorn` package. The `ScopeBody` and `ScopeExpression` meta-node-types are no longer supported. ## 5.7.1 (2018-06-15) ### Bug fixes Make sure the walker and bin files are rebuilt on release (the previous release didn't get the up-to-date versions). ## 5.7.0 (2018-06-15) ### Bug fixes Fix crash in walker when walking a binding-less catch node. ## 5.6.2 (2018-06-05) ### Bug fixes In the walker, go back to allowing the `baseVisitor` argument to be null to default to the default base everywhere. ## 5.6.1 (2018-06-01) ### Bug fixes Fix regression when passing `null` as fourth argument to `walk.recursive`. ## 5.6.0 (2018-05-31) ### Bug fixes Fix a bug in the walker that caused a crash when walking an object pattern spread. ## 5.5.1 (2018-03-06) ### Bug fixes Fix regression in walker causing property values in object patterns to be walked as expressions. ## 5.5.0 (2018-02-27) ### Bug fixes Support object spread in the AST walker. ## 5.4.1 (2018-02-02) ### Bug fixes 5.4.0 somehow accidentally included an old version of walk.js. ## 5.2.0 (2017-10-30) ### Bug fixes The `full` and `fullAncestor` walkers no longer visit nodes multiple times. ## 5.1.0 (2017-07-05) ### New features New walker functions `full` and `fullAncestor`. ## 3.2.0 (2016-06-07) ### New features Make it possible to use `visit.ancestor` with a walk state. ## 3.1.0 (2016-04-18) ### New features The walker now allows defining handlers for `CatchClause` nodes. ## 2.5.2 (2015-10-27) ### Fixes Fix bug where the walker walked an exported `let` statement as an expression.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/acorn-walk/CHANGELOG.md
CHANGELOG.md
import {Node} from 'acorn'; declare module "acorn-walk" { type FullWalkerCallback<TState> = ( node: Node, state: TState, type: string ) => void; type FullAncestorWalkerCallback<TState> = ( node: Node, state: TState | Node[], ancestors: Node[], type: string ) => void; type WalkerCallback<TState> = (node: Node, state: TState) => void; type SimpleWalkerFn<TState> = ( node: Node, state: TState ) => void; type AncestorWalkerFn<TState> = ( node: Node, state: TState| Node[], ancestors: Node[] ) => void; type RecursiveWalkerFn<TState> = ( node: Node, state: TState, callback: WalkerCallback<TState> ) => void; type SimpleVisitors<TState> = { [type: string]: SimpleWalkerFn<TState> }; type AncestorVisitors<TState> = { [type: string]: AncestorWalkerFn<TState> }; type RecursiveVisitors<TState> = { [type: string]: RecursiveWalkerFn<TState> }; type FindPredicate = (type: string, node: Node) => boolean; interface Found<TState> { node: Node, state: TState } export function simple<TState>( node: Node, visitors: SimpleVisitors<TState>, base?: RecursiveVisitors<TState>, state?: TState ): void; export function ancestor<TState>( node: Node, visitors: AncestorVisitors<TState>, base?: RecursiveVisitors<TState>, state?: TState ): void; export function recursive<TState>( node: Node, state: TState, functions: RecursiveVisitors<TState>, base?: RecursiveVisitors<TState> ): void; export function full<TState>( node: Node, callback: FullWalkerCallback<TState>, base?: RecursiveVisitors<TState>, state?: TState ): void; export function fullAncestor<TState>( node: Node, callback: FullAncestorWalkerCallback<TState>, base?: RecursiveVisitors<TState>, state?: TState ): void; export function make<TState>( functions: RecursiveVisitors<TState>, base?: RecursiveVisitors<TState> ): RecursiveVisitors<TState>; export function findNodeAt<TState>( node: Node, start: number | undefined, end?: number | undefined, type?: FindPredicate | string, base?: RecursiveVisitors<TState>, state?: TState ): Found<TState> | undefined; export function findNodeAround<TState>( node: Node, start: number | undefined, type?: FindPredicate | string, base?: RecursiveVisitors<TState>, state?: TState ): Found<TState> | undefined; export const findNodeAfter: typeof findNodeAround; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/acorn-walk/dist/walk.d.ts
walk.d.ts
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory((global.acorn = global.acorn || {}, global.acorn.walk = {}))); }(this, (function (exports) { 'use strict'; // AST walker module for Mozilla Parser API compatible trees // A simple walk is one where you simply specify callbacks to be // called on specific nodes. The last two arguments are optional. A // simple use would be // // walk.simple(myTree, { // Expression: function(node) { ... } // }); // // to do something with all expressions. All Parser API node types // can be used to identify node types, as well as Expression and // Statement, which denote categories of nodes. // // The base argument can be used to pass a custom (recursive) // walker, and state can be used to give this walked an initial // state. function simple(node, visitors, baseVisitor, state, override) { if (!baseVisitor) { baseVisitor = base ; }(function c(node, st, override) { var type = override || node.type, found = visitors[type]; baseVisitor[type](node, st, c); if (found) { found(node, st); } })(node, state, override); } // An ancestor walk keeps an array of ancestor nodes (including the // current node) and passes them to the callback as third parameter // (and also as state parameter when no other state is present). function ancestor(node, visitors, baseVisitor, state, override) { var ancestors = []; if (!baseVisitor) { baseVisitor = base ; }(function c(node, st, override) { var type = override || node.type, found = visitors[type]; var isNew = node !== ancestors[ancestors.length - 1]; if (isNew) { ancestors.push(node); } baseVisitor[type](node, st, c); if (found) { found(node, st || ancestors, ancestors); } if (isNew) { ancestors.pop(); } })(node, state, override); } // A recursive walk is one where your functions override the default // walkers. They can modify and replace the state parameter that's // threaded through the walk, and can opt how and whether to walk // their child nodes (by calling their third argument on these // nodes). function recursive(node, state, funcs, baseVisitor, override) { var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor ;(function c(node, st, override) { visitor[override || node.type](node, st, c); })(node, state, override); } function makeTest(test) { if (typeof test === "string") { return function (type) { return type === test; } } else if (!test) { return function () { return true; } } else { return test } } var Found = function Found(node, state) { this.node = node; this.state = state; }; // A full walk triggers the callback on each node function full(node, callback, baseVisitor, state, override) { if (!baseVisitor) { baseVisitor = base ; }(function c(node, st, override) { var type = override || node.type; baseVisitor[type](node, st, c); if (!override) { callback(node, st, type); } })(node, state, override); } // An fullAncestor walk is like an ancestor walk, but triggers // the callback on each node function fullAncestor(node, callback, baseVisitor, state) { if (!baseVisitor) { baseVisitor = base; } var ancestors = [] ;(function c(node, st, override) { var type = override || node.type; var isNew = node !== ancestors[ancestors.length - 1]; if (isNew) { ancestors.push(node); } baseVisitor[type](node, st, c); if (!override) { callback(node, st || ancestors, ancestors, type); } if (isNew) { ancestors.pop(); } })(node, state); } // Find a node with a given start, end, and type (all are optional, // null can be used as wildcard). Returns a {node, state} object, or // undefined when it doesn't find a matching node. function findNodeAt(node, start, end, test, baseVisitor, state) { if (!baseVisitor) { baseVisitor = base; } test = makeTest(test); try { (function c(node, st, override) { var type = override || node.type; if ((start == null || node.start <= start) && (end == null || node.end >= end)) { baseVisitor[type](node, st, c); } if ((start == null || node.start === start) && (end == null || node.end === end) && test(type, node)) { throw new Found(node, st) } })(node, state); } catch (e) { if (e instanceof Found) { return e } throw e } } // Find the innermost node of a given type that contains the given // position. Interface similar to findNodeAt. function findNodeAround(node, pos, test, baseVisitor, state) { test = makeTest(test); if (!baseVisitor) { baseVisitor = base; } try { (function c(node, st, override) { var type = override || node.type; if (node.start > pos || node.end < pos) { return } baseVisitor[type](node, st, c); if (test(type, node)) { throw new Found(node, st) } })(node, state); } catch (e) { if (e instanceof Found) { return e } throw e } } // Find the outermost matching node after a given position. function findNodeAfter(node, pos, test, baseVisitor, state) { test = makeTest(test); if (!baseVisitor) { baseVisitor = base; } try { (function c(node, st, override) { if (node.end < pos) { return } var type = override || node.type; if (node.start >= pos && test(type, node)) { throw new Found(node, st) } baseVisitor[type](node, st, c); })(node, state); } catch (e) { if (e instanceof Found) { return e } throw e } } // Find the outermost matching node before a given position. function findNodeBefore(node, pos, test, baseVisitor, state) { test = makeTest(test); if (!baseVisitor) { baseVisitor = base; } var max ;(function c(node, st, override) { if (node.start > pos) { return } var type = override || node.type; if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node)) { max = new Found(node, st); } baseVisitor[type](node, st, c); })(node, state); return max } // Fallback to an Object.create polyfill for older environments. var create = Object.create || function(proto) { function Ctor() {} Ctor.prototype = proto; return new Ctor }; // Used to create a custom walker. Will fill in all missing node // type properties with the defaults. function make(funcs, baseVisitor) { var visitor = create(baseVisitor || base); for (var type in funcs) { visitor[type] = funcs[type]; } return visitor } function skipThrough(node, st, c) { c(node, st); } function ignore(_node, _st, _c) {} // Node walkers. var base = {}; base.Program = base.BlockStatement = function (node, st, c) { for (var i = 0, list = node.body; i < list.length; i += 1) { var stmt = list[i]; c(stmt, st, "Statement"); } }; base.Statement = skipThrough; base.EmptyStatement = ignore; base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = function (node, st, c) { return c(node.expression, st, "Expression"); }; base.IfStatement = function (node, st, c) { c(node.test, st, "Expression"); c(node.consequent, st, "Statement"); if (node.alternate) { c(node.alternate, st, "Statement"); } }; base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); }; base.BreakStatement = base.ContinueStatement = ignore; base.WithStatement = function (node, st, c) { c(node.object, st, "Expression"); c(node.body, st, "Statement"); }; base.SwitchStatement = function (node, st, c) { c(node.discriminant, st, "Expression"); for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) { var cs = list$1[i$1]; if (cs.test) { c(cs.test, st, "Expression"); } for (var i = 0, list = cs.consequent; i < list.length; i += 1) { var cons = list[i]; c(cons, st, "Statement"); } } }; base.SwitchCase = function (node, st, c) { if (node.test) { c(node.test, st, "Expression"); } for (var i = 0, list = node.consequent; i < list.length; i += 1) { var cons = list[i]; c(cons, st, "Statement"); } }; base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) { if (node.argument) { c(node.argument, st, "Expression"); } }; base.ThrowStatement = base.SpreadElement = function (node, st, c) { return c(node.argument, st, "Expression"); }; base.TryStatement = function (node, st, c) { c(node.block, st, "Statement"); if (node.handler) { c(node.handler, st); } if (node.finalizer) { c(node.finalizer, st, "Statement"); } }; base.CatchClause = function (node, st, c) { if (node.param) { c(node.param, st, "Pattern"); } c(node.body, st, "Statement"); }; base.WhileStatement = base.DoWhileStatement = function (node, st, c) { c(node.test, st, "Expression"); c(node.body, st, "Statement"); }; base.ForStatement = function (node, st, c) { if (node.init) { c(node.init, st, "ForInit"); } if (node.test) { c(node.test, st, "Expression"); } if (node.update) { c(node.update, st, "Expression"); } c(node.body, st, "Statement"); }; base.ForInStatement = base.ForOfStatement = function (node, st, c) { c(node.left, st, "ForInit"); c(node.right, st, "Expression"); c(node.body, st, "Statement"); }; base.ForInit = function (node, st, c) { if (node.type === "VariableDeclaration") { c(node, st); } else { c(node, st, "Expression"); } }; base.DebuggerStatement = ignore; base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); }; base.VariableDeclaration = function (node, st, c) { for (var i = 0, list = node.declarations; i < list.length; i += 1) { var decl = list[i]; c(decl, st); } }; base.VariableDeclarator = function (node, st, c) { c(node.id, st, "Pattern"); if (node.init) { c(node.init, st, "Expression"); } }; base.Function = function (node, st, c) { if (node.id) { c(node.id, st, "Pattern"); } for (var i = 0, list = node.params; i < list.length; i += 1) { var param = list[i]; c(param, st, "Pattern"); } c(node.body, st, node.expression ? "Expression" : "Statement"); }; base.Pattern = function (node, st, c) { if (node.type === "Identifier") { c(node, st, "VariablePattern"); } else if (node.type === "MemberExpression") { c(node, st, "MemberPattern"); } else { c(node, st); } }; base.VariablePattern = ignore; base.MemberPattern = skipThrough; base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); }; base.ArrayPattern = function (node, st, c) { for (var i = 0, list = node.elements; i < list.length; i += 1) { var elt = list[i]; if (elt) { c(elt, st, "Pattern"); } } }; base.ObjectPattern = function (node, st, c) { for (var i = 0, list = node.properties; i < list.length; i += 1) { var prop = list[i]; if (prop.type === "Property") { if (prop.computed) { c(prop.key, st, "Expression"); } c(prop.value, st, "Pattern"); } else if (prop.type === "RestElement") { c(prop.argument, st, "Pattern"); } } }; base.Expression = skipThrough; base.ThisExpression = base.Super = base.MetaProperty = ignore; base.ArrayExpression = function (node, st, c) { for (var i = 0, list = node.elements; i < list.length; i += 1) { var elt = list[i]; if (elt) { c(elt, st, "Expression"); } } }; base.ObjectExpression = function (node, st, c) { for (var i = 0, list = node.properties; i < list.length; i += 1) { var prop = list[i]; c(prop, st); } }; base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; base.SequenceExpression = function (node, st, c) { for (var i = 0, list = node.expressions; i < list.length; i += 1) { var expr = list[i]; c(expr, st, "Expression"); } }; base.TemplateLiteral = function (node, st, c) { for (var i = 0, list = node.quasis; i < list.length; i += 1) { var quasi = list[i]; c(quasi, st); } for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1) { var expr = list$1[i$1]; c(expr, st, "Expression"); } }; base.TemplateElement = ignore; base.UnaryExpression = base.UpdateExpression = function (node, st, c) { c(node.argument, st, "Expression"); }; base.BinaryExpression = base.LogicalExpression = function (node, st, c) { c(node.left, st, "Expression"); c(node.right, st, "Expression"); }; base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) { c(node.left, st, "Pattern"); c(node.right, st, "Expression"); }; base.ConditionalExpression = function (node, st, c) { c(node.test, st, "Expression"); c(node.consequent, st, "Expression"); c(node.alternate, st, "Expression"); }; base.NewExpression = base.CallExpression = function (node, st, c) { c(node.callee, st, "Expression"); if (node.arguments) { for (var i = 0, list = node.arguments; i < list.length; i += 1) { var arg = list[i]; c(arg, st, "Expression"); } } }; base.MemberExpression = function (node, st, c) { c(node.object, st, "Expression"); if (node.computed) { c(node.property, st, "Expression"); } }; base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) { if (node.declaration) { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); } if (node.source) { c(node.source, st, "Expression"); } }; base.ExportAllDeclaration = function (node, st, c) { if (node.exported) { c(node.exported, st); } c(node.source, st, "Expression"); }; base.ImportDeclaration = function (node, st, c) { for (var i = 0, list = node.specifiers; i < list.length; i += 1) { var spec = list[i]; c(spec, st); } c(node.source, st, "Expression"); }; base.ImportExpression = function (node, st, c) { c(node.source, st, "Expression"); }; base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore; base.TaggedTemplateExpression = function (node, st, c) { c(node.tag, st, "Expression"); c(node.quasi, st, "Expression"); }; base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); }; base.Class = function (node, st, c) { if (node.id) { c(node.id, st, "Pattern"); } if (node.superClass) { c(node.superClass, st, "Expression"); } c(node.body, st); }; base.ClassBody = function (node, st, c) { for (var i = 0, list = node.body; i < list.length; i += 1) { var elt = list[i]; c(elt, st); } }; base.MethodDefinition = base.Property = function (node, st, c) { if (node.computed) { c(node.key, st, "Expression"); } c(node.value, st, "Expression"); }; exports.ancestor = ancestor; exports.base = base; exports.findNodeAfter = findNodeAfter; exports.findNodeAround = findNodeAround; exports.findNodeAt = findNodeAt; exports.findNodeBefore = findNodeBefore; exports.full = full; exports.fullAncestor = fullAncestor; exports.make = make; exports.recursive = recursive; exports.simple = simple; Object.defineProperty(exports, '__esModule', { value: true }); })));
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/acorn-walk/dist/walk.js
walk.js
node-asn1 is a library for encoding and decoding ASN.1 datatypes in pure JS. Currently BER encoding is supported; at some point I'll likely have to do DER. ## Usage Mostly, if you're *actually* needing to read and write ASN.1, you probably don't need this readme to explain what and why. If you have no idea what ASN.1 is, see this: ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc The source is pretty much self-explanatory, and has read/write methods for the common types out there. ### Decoding The following reads an ASN.1 sequence with a boolean. var Ber = require('asn1').Ber; var reader = new Ber.Reader(Buffer.from([0x30, 0x03, 0x01, 0x01, 0xff])); reader.readSequence(); console.log('Sequence len: ' + reader.length); if (reader.peek() === Ber.Boolean) console.log(reader.readBoolean()); ### Encoding The following generates the same payload as above. var Ber = require('asn1').Ber; var writer = new Ber.Writer(); writer.startSequence(); writer.writeBoolean(true); writer.endSequence(); console.log(writer.buffer); ## Installation npm install asn1 ## License MIT. ## Bugs See <https://github.com/joyent/node-asn1/issues>.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/asn1/README.md
README.md
var assert = require('assert'); var Buffer = require('safer-buffer').Buffer; var ASN1 = require('asn1/lib/ber/types'); var errors = require('asn1/lib/ber/errors'); // --- Globals var newInvalidAsn1Error = errors.newInvalidAsn1Error; // --- API function Reader(data) { if (!data || !Buffer.isBuffer(data)) throw new TypeError('data must be a node Buffer'); this._buf = data; this._size = data.length; // These hold the "current" state this._len = 0; this._offset = 0; } Object.defineProperty(Reader.prototype, 'length', { enumerable: true, get: function () { return (this._len); } }); Object.defineProperty(Reader.prototype, 'offset', { enumerable: true, get: function () { return (this._offset); } }); Object.defineProperty(Reader.prototype, 'remain', { get: function () { return (this._size - this._offset); } }); Object.defineProperty(Reader.prototype, 'buffer', { get: function () { return (this._buf.slice(this._offset)); } }); /** * Reads a single byte and advances offset; you can pass in `true` to make this * a "peek" operation (i.e., get the byte, but don't advance the offset). * * @param {Boolean} peek true means don't move offset. * @return {Number} the next byte, null if not enough data. */ Reader.prototype.readByte = function (peek) { if (this._size - this._offset < 1) return null; var b = this._buf[this._offset] & 0xff; if (!peek) this._offset += 1; return b; }; Reader.prototype.peek = function () { return this.readByte(true); }; /** * Reads a (potentially) variable length off the BER buffer. This call is * not really meant to be called directly, as callers have to manipulate * the internal buffer afterwards. * * As a result of this call, you can call `Reader.length`, until the * next thing called that does a readLength. * * @return {Number} the amount of offset to advance the buffer. * @throws {InvalidAsn1Error} on bad ASN.1 */ Reader.prototype.readLength = function (offset) { if (offset === undefined) offset = this._offset; if (offset >= this._size) return null; var lenB = this._buf[offset++] & 0xff; if (lenB === null) return null; if ((lenB & 0x80) === 0x80) { lenB &= 0x7f; if (lenB === 0) throw newInvalidAsn1Error('Indefinite length not supported'); if (lenB > 4) throw newInvalidAsn1Error('encoding too long'); if (this._size - offset < lenB) return null; this._len = 0; for (var i = 0; i < lenB; i++) this._len = (this._len << 8) + (this._buf[offset++] & 0xff); } else { // Wasn't a variable length this._len = lenB; } return offset; }; /** * Parses the next sequence in this BER buffer. * * To get the length of the sequence, call `Reader.length`. * * @return {Number} the sequence's tag. */ Reader.prototype.readSequence = function (tag) { var seq = this.peek(); if (seq === null) return null; if (tag !== undefined && tag !== seq) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + seq.toString(16)); var o = this.readLength(this._offset + 1); // stored in `length` if (o === null) return null; this._offset = o; return seq; }; Reader.prototype.readInt = function () { return this._readTag(ASN1.Integer); }; Reader.prototype.readBoolean = function () { return (this._readTag(ASN1.Boolean) === 0 ? false : true); }; Reader.prototype.readEnumeration = function () { return this._readTag(ASN1.Enumeration); }; Reader.prototype.readString = function (tag, retbuf) { if (!tag) tag = ASN1.OctetString; var b = this.peek(); if (b === null) return null; if (b !== tag) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + b.toString(16)); var o = this.readLength(this._offset + 1); // stored in `length` if (o === null) return null; if (this.length > this._size - o) return null; this._offset = o; if (this.length === 0) return retbuf ? Buffer.alloc(0) : ''; var str = this._buf.slice(this._offset, this._offset + this.length); this._offset += this.length; return retbuf ? str : str.toString('utf8'); }; Reader.prototype.readOID = function (tag) { if (!tag) tag = ASN1.OID; var b = this.readString(tag, true); if (b === null) return null; var values = []; var value = 0; for (var i = 0; i < b.length; i++) { var byte = b[i] & 0xff; value <<= 7; value += byte & 0x7f; if ((byte & 0x80) === 0) { values.push(value); value = 0; } } value = values.shift(); values.unshift(value % 40); values.unshift((value / 40) >> 0); return values.join('.'); }; Reader.prototype._readTag = function (tag) { assert.ok(tag !== undefined); var b = this.peek(); if (b === null) return null; if (b !== tag) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + b.toString(16)); var o = this.readLength(this._offset + 1); // stored in `length` if (o === null) return null; if (this.length > 4) throw newInvalidAsn1Error('Integer too long: ' + this.length); if (this.length > this._size - o) return null; this._offset = o; var fb = this._buf[this._offset]; var value = 0; for (var i = 0; i < this.length; i++) { value <<= 8; value |= (this._buf[this._offset++] & 0xff); } if ((fb & 0x80) === 0x80 && i !== 4) value -= (1 << (i * 8)); return value >> 0; }; // --- Exported API module.exports = Reader;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/asn1/lib/ber/reader.js
reader.js
var assert = require('assert'); var Buffer = require('safer-buffer').Buffer; var ASN1 = require('asn1/lib/ber/types'); var errors = require('asn1/lib/ber/errors'); // --- Globals var newInvalidAsn1Error = errors.newInvalidAsn1Error; var DEFAULT_OPTS = { size: 1024, growthFactor: 8 }; // --- Helpers function merge(from, to) { assert.ok(from); assert.equal(typeof (from), 'object'); assert.ok(to); assert.equal(typeof (to), 'object'); var keys = Object.getOwnPropertyNames(from); keys.forEach(function (key) { if (to[key]) return; var value = Object.getOwnPropertyDescriptor(from, key); Object.defineProperty(to, key, value); }); return to; } // --- API function Writer(options) { options = merge(DEFAULT_OPTS, options || {}); this._buf = Buffer.alloc(options.size || 1024); this._size = this._buf.length; this._offset = 0; this._options = options; // A list of offsets in the buffer where we need to insert // sequence tag/len pairs. this._seq = []; } Object.defineProperty(Writer.prototype, 'buffer', { get: function () { if (this._seq.length) throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); return (this._buf.slice(0, this._offset)); } }); Writer.prototype.writeByte = function (b) { if (typeof (b) !== 'number') throw new TypeError('argument must be a Number'); this._ensure(1); this._buf[this._offset++] = b; }; Writer.prototype.writeInt = function (i, tag) { if (typeof (i) !== 'number') throw new TypeError('argument must be a Number'); if (typeof (tag) !== 'number') tag = ASN1.Integer; var sz = 4; while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && (sz > 1)) { sz--; i <<= 8; } if (sz > 4) throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); this._ensure(2 + sz); this._buf[this._offset++] = tag; this._buf[this._offset++] = sz; while (sz-- > 0) { this._buf[this._offset++] = ((i & 0xff000000) >>> 24); i <<= 8; } }; Writer.prototype.writeNull = function () { this.writeByte(ASN1.Null); this.writeByte(0x00); }; Writer.prototype.writeEnumeration = function (i, tag) { if (typeof (i) !== 'number') throw new TypeError('argument must be a Number'); if (typeof (tag) !== 'number') tag = ASN1.Enumeration; return this.writeInt(i, tag); }; Writer.prototype.writeBoolean = function (b, tag) { if (typeof (b) !== 'boolean') throw new TypeError('argument must be a Boolean'); if (typeof (tag) !== 'number') tag = ASN1.Boolean; this._ensure(3); this._buf[this._offset++] = tag; this._buf[this._offset++] = 0x01; this._buf[this._offset++] = b ? 0xff : 0x00; }; Writer.prototype.writeString = function (s, tag) { if (typeof (s) !== 'string') throw new TypeError('argument must be a string (was: ' + typeof (s) + ')'); if (typeof (tag) !== 'number') tag = ASN1.OctetString; var len = Buffer.byteLength(s); this.writeByte(tag); this.writeLength(len); if (len) { this._ensure(len); this._buf.write(s, this._offset); this._offset += len; } }; Writer.prototype.writeBuffer = function (buf, tag) { if (typeof (tag) !== 'number') throw new TypeError('tag must be a number'); if (!Buffer.isBuffer(buf)) throw new TypeError('argument must be a buffer'); this.writeByte(tag); this.writeLength(buf.length); this._ensure(buf.length); buf.copy(this._buf, this._offset, 0, buf.length); this._offset += buf.length; }; Writer.prototype.writeStringArray = function (strings) { if ((!strings instanceof Array)) throw new TypeError('argument must be an Array[String]'); var self = this; strings.forEach(function (s) { self.writeString(s); }); }; // This is really to solve DER cases, but whatever for now Writer.prototype.writeOID = function (s, tag) { if (typeof (s) !== 'string') throw new TypeError('argument must be a string'); if (typeof (tag) !== 'number') tag = ASN1.OID; if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) throw new Error('argument is not a valid OID string'); function encodeOctet(bytes, octet) { if (octet < 128) { bytes.push(octet); } else if (octet < 16384) { bytes.push((octet >>> 7) | 0x80); bytes.push(octet & 0x7F); } else if (octet < 2097152) { bytes.push((octet >>> 14) | 0x80); bytes.push(((octet >>> 7) | 0x80) & 0xFF); bytes.push(octet & 0x7F); } else if (octet < 268435456) { bytes.push((octet >>> 21) | 0x80); bytes.push(((octet >>> 14) | 0x80) & 0xFF); bytes.push(((octet >>> 7) | 0x80) & 0xFF); bytes.push(octet & 0x7F); } else { bytes.push(((octet >>> 28) | 0x80) & 0xFF); bytes.push(((octet >>> 21) | 0x80) & 0xFF); bytes.push(((octet >>> 14) | 0x80) & 0xFF); bytes.push(((octet >>> 7) | 0x80) & 0xFF); bytes.push(octet & 0x7F); } } var tmp = s.split('.'); var bytes = []; bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); tmp.slice(2).forEach(function (b) { encodeOctet(bytes, parseInt(b, 10)); }); var self = this; this._ensure(2 + bytes.length); this.writeByte(tag); this.writeLength(bytes.length); bytes.forEach(function (b) { self.writeByte(b); }); }; Writer.prototype.writeLength = function (len) { if (typeof (len) !== 'number') throw new TypeError('argument must be a Number'); this._ensure(4); if (len <= 0x7f) { this._buf[this._offset++] = len; } else if (len <= 0xff) { this._buf[this._offset++] = 0x81; this._buf[this._offset++] = len; } else if (len <= 0xffff) { this._buf[this._offset++] = 0x82; this._buf[this._offset++] = len >> 8; this._buf[this._offset++] = len; } else if (len <= 0xffffff) { this._buf[this._offset++] = 0x83; this._buf[this._offset++] = len >> 16; this._buf[this._offset++] = len >> 8; this._buf[this._offset++] = len; } else { throw newInvalidAsn1Error('Length too long (> 4 bytes)'); } }; Writer.prototype.startSequence = function (tag) { if (typeof (tag) !== 'number') tag = ASN1.Sequence | ASN1.Constructor; this.writeByte(tag); this._seq.push(this._offset); this._ensure(3); this._offset += 3; }; Writer.prototype.endSequence = function () { var seq = this._seq.pop(); var start = seq + 3; var len = this._offset - start; if (len <= 0x7f) { this._shift(start, len, -2); this._buf[seq] = len; } else if (len <= 0xff) { this._shift(start, len, -1); this._buf[seq] = 0x81; this._buf[seq + 1] = len; } else if (len <= 0xffff) { this._buf[seq] = 0x82; this._buf[seq + 1] = len >> 8; this._buf[seq + 2] = len; } else if (len <= 0xffffff) { this._shift(start, len, 1); this._buf[seq] = 0x83; this._buf[seq + 1] = len >> 16; this._buf[seq + 2] = len >> 8; this._buf[seq + 3] = len; } else { throw newInvalidAsn1Error('Sequence too long'); } }; Writer.prototype._shift = function (start, len, shift) { assert.ok(start !== undefined); assert.ok(len !== undefined); assert.ok(shift); this._buf.copy(this._buf, start + shift, start, start + len); this._offset += shift; }; Writer.prototype._ensure = function (len) { assert.ok(len); if (this._size - this._offset < len) { var sz = this._size * this._options.growthFactor; if (sz - this._offset < len) sz += len; var buf = Buffer.alloc(sz); this._buf.copy(buf, 0, 0, this._offset); this._buf = buf; this._size = sz; } }; // --- Exported API module.exports = Writer;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/asn1/lib/ber/writer.js
writer.js
<h1 align="center"> <img width="100" height="100" src="logo.svg" alt=""><br> jsdom </h1> jsdom is a pure-JavaScript implementation of many web standards, notably the WHATWG [DOM](https://dom.spec.whatwg.org/) and [HTML](https://html.spec.whatwg.org/multipage/) Standards, for use with Node.js. In general, the goal of the project is to emulate enough of a subset of a web browser to be useful for testing and scraping real-world web applications. The latest versions of jsdom require Node.js v10 or newer. (Versions of jsdom below v16 still work with previous Node.js versions, but are unsupported.) ## Basic usage ```js const jsdom = require("jsdom"); const { JSDOM } = jsdom; ``` To use jsdom, you will primarily use the `JSDOM` constructor, which is a named export of the jsdom main module. Pass the constructor a string. You will get back a `JSDOM` object, which has a number of useful properties, notably `window`: ```js const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`); console.log(dom.window.document.querySelector("p").textContent); // "Hello world" ``` (Note that jsdom will parse the HTML you pass it just like a browser does, including implied `<html>`, `<head>`, and `<body>` tags.) The resulting object is an instance of the `JSDOM` class, which contains a number of useful properties and methods besides `window`. In general, it can be used to act on the jsdom from the "outside," doing things that are not possible with the normal DOM APIs. For simple cases, where you don't need any of this functionality, we recommend a coding pattern like ```js const { window } = new JSDOM(`...`); // or even const { document } = (new JSDOM(`...`)).window; ``` Full documentation on everything you can do with the `JSDOM` class is below, in the section "`JSDOM` Object API". ## Customizing jsdom The `JSDOM` constructor accepts a second parameter which can be used to customize your jsdom in the following ways. ### Simple options ```js const dom = new JSDOM(``, { url: "https://example.org/", referrer: "https://example.com/", contentType: "text/html", includeNodeLocations: true, storageQuota: 10000000 }); ``` - `url` sets the value returned by `window.location`, `document.URL`, and `document.documentURI`, and affects things like resolution of relative URLs within the document and the same-origin restrictions and referrer used while fetching subresources. It defaults to `"about:blank"`. - `referrer` just affects the value read from `document.referrer`. It defaults to no referrer (which reflects as the empty string). - `contentType` affects the value read from `document.contentType`, as well as how the document is parsed: as HTML or as XML. Values that are not a [HTML mime type](https://mimesniff.spec.whatwg.org/#html-mime-type) or an [XML mime type](https://mimesniff.spec.whatwg.org/#xml-mime-type) will throw. It defaults to `"text/html"`. If a `charset` parameter is present, it can affect [binary data processing](#encoding-sniffing). - `includeNodeLocations` preserves the location info produced by the HTML parser, allowing you to retrieve it with the `nodeLocation()` method (described below). It also ensures that line numbers reported in exception stack traces for code running inside `<script>` elements are correct. It defaults to `false` to give the best performance, and cannot be used with an XML content type since our XML parser does not support location info. - `storageQuota` is the maximum size in code units for the separate storage areas used by `localStorage` and `sessionStorage`. Attempts to store data larger than this limit will cause a `DOMException` to be thrown. By default, it is set to 5,000,000 code units per origin, as inspired by the HTML specification. Note that both `url` and `referrer` are canonicalized before they're used, so e.g. if you pass in `"https:example.com"`, jsdom will interpret that as if you had given `"https://example.com/"`. If you pass an unparseable URL, the call will throw. (URLs are parsed and serialized according to the [URL Standard](http://url.spec.whatwg.org/).) ### Executing scripts jsdom's most powerful ability is that it can execute scripts inside the jsdom. These scripts can modify the content of the page and access all the web platform APIs jsdom implements. However, this is also highly dangerous when dealing with untrusted content. The jsdom sandbox is not foolproof, and code running inside the DOM's `<script>`s can, if it tries hard enough, get access to the Node.js environment, and thus to your machine. As such, the ability to execute scripts embedded in the HTML is disabled by default: ```js const dom = new JSDOM(`<body> <script>document.body.appendChild(document.createElement("hr"));</script> </body>`); // The script will not be executed, by default: dom.window.document.body.children.length === 1; ``` To enable executing scripts inside the page, you can use the `runScripts: "dangerously"` option: ```js const dom = new JSDOM(`<body> <script>document.body.appendChild(document.createElement("hr"));</script> </body>`, { runScripts: "dangerously" }); // The script will be executed and modify the DOM: dom.window.document.body.children.length === 2; ``` Again we emphasize to only use this when feeding jsdom code you know is safe. If you use it on arbitrary user-supplied code, or code from the Internet, you are effectively running untrusted Node.js code, and your machine could be compromised. If you want to execute _external_ scripts, included via `<script src="">`, you'll also need to ensure that they load them. To do this, add the option `resources: "usable"` [as described below](#loading-subresources). (You'll likely also want to set the `url` option, for the reasons discussed there.) Event handler attributes, like `<div onclick="">`, are also governed by this setting; they will not function unless `runScripts` is set to `"dangerously"`. (However, event handler _properties_, like `div.onclick = ...`, will function regardless of `runScripts`.) If you are simply trying to execute script "from the outside", instead of letting `<script>` elements and event handlers attributes run "from the inside", you can use the `runScripts: "outside-only"` option, which enables fresh copies of all the JavaScript spec-provided globals to be installed on `window`. This includes things like `window.Array`, `window.Promise`, etc. It also, notably, includes `window.eval`, which allows running scripts, but with the jsdom `window` as the global: ```js const { window } = new JSDOM(``, { runScripts: "outside-only" }); window.eval(`document.body.innerHTML = "<p>Hello, world!</p>";`); window.document.body.children.length === 1; ``` This is turned off by default for performance reasons, but is safe to enable. (Note that in the default configuration, without setting `runScripts`, the values of `window.Array`, `window.eval`, etc. will be the same as those provided by the outer Node.js environment. That is, `window.eval === eval` will hold, so `window.eval` will not run scripts in a useful way.) We strongly advise against trying to "execute scripts" by mashing together the jsdom and Node global environments (e.g. by doing `global.window = dom.window`), and then executing scripts or test code inside the Node global environment. Instead, you should treat jsdom like you would a browser, and run all scripts and tests that need access to a DOM inside the jsdom environment, using `window.eval` or `runScripts: "dangerously"`. This might require, for example, creating a browserify bundle to execute as a `<script>` element—just like you would in a browser. Finally, for advanced use cases you can use the `dom.getInternalVMContext()` method, documented below. ### Pretending to be a visual browser jsdom does not have the capability to render visual content, and will act like a headless browser by default. It provides hints to web pages through APIs such as `document.hidden` that their content is not visible. When the `pretendToBeVisual` option is set to `true`, jsdom will pretend that it is rendering and displaying content. It does this by: * Changing `document.hidden` to return `false` instead of `true` * Changing `document.visibilityState` to return `"visible"` instead of `"prerender"` * Enabling `window.requestAnimationFrame()` and `window.cancelAnimationFrame()` methods, which otherwise do not exist ```js const window = (new JSDOM(``, { pretendToBeVisual: true })).window; window.requestAnimationFrame(timestamp => { console.log(timestamp > 0); }); ``` Note that jsdom still [does not do any layout or rendering](#unimplemented-parts-of-the-web-platform), so this is really just about _pretending_ to be visual, not about implementing the parts of the platform a real, visual web browser would implement. ### Loading subresources #### Basic options By default, jsdom will not load any subresources such as scripts, stylesheets, images, or iframes. If you'd like jsdom to load such resources, you can pass the `resources: "usable"` option, which will load all usable resources. Those are: * Frames and iframes, via `<frame>` and `<iframe>` * Stylesheets, via `<link rel="stylesheet">` * Scripts, via `<script>`, but only if `runScripts: "dangerously"` is also set * Images, via `<img>`, but only if the `canvas` npm package is also installed (see "[Canvas Support](#canvas-support)" below) When attempting to load resources, recall that the default value for the `url` option is `"about:blank"`, which means that any resources included via relative URLs will fail to load. (The result of trying to parse the URL `/something` against the URL `about:blank` is an error.) So, you'll likely want to set a non-default value for the `url` option in those cases, or use one of the [convenience APIs](#convenience-apis) that do so automatically. #### Advanced configuration _This resource loader system is new as of jsdom v12.0.0, and we'd love your feedback on whether it meets your needs and how easy it is to use. Please file an issue to discuss!_ To more fully customize jsdom's resource-loading behavior, you can pass an instance of the `ResourceLoader` class as the `resources` option value: ```js const resourceLoader = new jsdom.ResourceLoader({ proxy: "http://127.0.0.1:9001", strictSSL: false, userAgent: "Mellblomenator/9000", }); const dom = new JSDOM(``, { resources: resourceLoader }); ``` The three options to the `ResourceLoader` constructor are: - `proxy` is the address of an HTTP proxy to be used. - `strictSSL` can be set to false to disable the requirement that SSL certificates be valid. - `userAgent` affects the `User-Agent` header sent, and thus the resulting value for `navigator.userAgent`. It defaults to <code>\`Mozilla/5.0 (${process.platform || "unknown OS"}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}\`</code>. You can further customize resource fetching by subclassing `ResourceLoader` and overriding the `fetch()` method. For example, here is a version that only returns results for requests to a trusted origin: ```js class CustomResourceLoader extends jsdom.ResourceLoader { fetch(url, options) { // Override the contents of this script to do something unusual. if (url === "https://example.com/some-specific-script.js") { return Promise.resolve(Buffer.from("window.someGlobal = 5;")); } return super.fetch(url, options); } } ``` jsdom will call your custom resource loader's `fetch()` method whenever it encounters a "usable" resource, per the above section. The method takes a URL string, as well as a few options which you should pass through unmodified if calling `super.fetch()`. It must return a promise for a Node.js `Buffer` object, or return `null` if the resource is intentionally not to be loaded. In general, most cases will want to delegate to `super.fetch()`, as shown. One of the options you will receive in `fetch()` will be the element (if applicable) that is fetching a resource. ```js class CustomResourceLoader extends jsdom.ResourceLoader { fetch(url, options) { if (options.element) { console.log(`Element ${options.element.localName} is requesting the url ${url}`); } return super.fetch(url, options); } } ``` ### Virtual consoles Like web browsers, jsdom has the concept of a "console". This records both information directly sent from the page, via scripts executing inside the document, as well as information from the jsdom implementation itself. We call the user-controllable console a "virtual console", to distinguish it from the Node.js `console` API and from the inside-the-page `window.console` API. By default, the `JSDOM` constructor will return an instance with a virtual console that forwards all its output to the Node.js console. To create your own virtual console and pass it to jsdom, you can override this default by doing ```js const virtualConsole = new jsdom.VirtualConsole(); const dom = new JSDOM(``, { virtualConsole }); ``` Code like this will create a virtual console with no behavior. You can give it behavior by adding event listeners for all the possible console methods: ```js virtualConsole.on("error", () => { ... }); virtualConsole.on("warn", () => { ... }); virtualConsole.on("info", () => { ... }); virtualConsole.on("dir", () => { ... }); // ... etc. See https://console.spec.whatwg.org/#logging ``` (Note that it is probably best to set up these event listeners *before* calling `new JSDOM()`, since errors or console-invoking script might occur during parsing.) If you simply want to redirect the virtual console output to another console, like the default Node.js one, you can do ```js virtualConsole.sendTo(console); ``` There is also a special event, `"jsdomError"`, which will fire with error objects to report errors from jsdom itself. This is similar to how error messages often show up in web browser consoles, even if they are not initiated by `console.error`. So far, the following errors are output this way: - Errors loading or parsing subresources (scripts, stylesheets, frames, and iframes) - Script execution errors that are not handled by a window `onerror` event handler that returns `true` or calls `event.preventDefault()` - Not-implemented errors resulting from calls to methods, like `window.alert`, which jsdom does not implement, but installs anyway for web compatibility If you're using `sendTo(c)` to send errors to `c`, by default it will call `c.error(errorStack[, errorDetail])` with information from `"jsdomError"` events. If you'd prefer to maintain a strict one-to-one mapping of events to method calls, and perhaps handle `"jsdomError"`s yourself, then you can do ```js virtualConsole.sendTo(c, { omitJSDOMErrors: true }); ``` ### Cookie jars Like web browsers, jsdom has the concept of a cookie jar, storing HTTP cookies. Cookies that have a URL on the same domain as the document, and are not marked HTTP-only, are accessible via the `document.cookie` API. Additionally, all cookies in the cookie jar will impact the fetching of subresources. By default, the `JSDOM` constructor will return an instance with an empty cookie jar. To create your own cookie jar and pass it to jsdom, you can override this default by doing ```js const cookieJar = new jsdom.CookieJar(store, options); const dom = new JSDOM(``, { cookieJar }); ``` This is mostly useful if you want to share the same cookie jar among multiple jsdoms, or prime the cookie jar with certain values ahead of time. Cookie jars are provided by the [tough-cookie](https://www.npmjs.com/package/tough-cookie) package. The `jsdom.CookieJar` constructor is a subclass of the tough-cookie cookie jar which by default sets the `looseMode: true` option, since that [matches better how browsers behave](https://github.com/whatwg/html/issues/804). If you want to use tough-cookie's utilities and classes yourself, you can use the `jsdom.toughCookie` module export to get access to the tough-cookie module instance packaged with jsdom. ### Intervening before parsing jsdom allows you to intervene in the creation of a jsdom very early: after the `Window` and `Document` objects are created, but before any HTML is parsed to populate the document with nodes: ```js const dom = new JSDOM(`<p>Hello</p>`, { beforeParse(window) { window.document.childNodes.length === 0; window.someCoolAPI = () => { /* ... */ }; } }); ``` This is especially useful if you are wanting to modify the environment in some way, for example adding shims for web platform APIs jsdom does not support. ## `JSDOM` object API Once you have constructed a `JSDOM` object, it will have the following useful capabilities: ### Properties The property `window` retrieves the `Window` object that was created for you. The properties `virtualConsole` and `cookieJar` reflect the options you pass in, or the defaults created for you if nothing was passed in for those options. ### Serializing the document with `serialize()` The `serialize()` method will return the [HTML serialization](https://html.spec.whatwg.org/#html-fragment-serialisation-algorithm) of the document, including the doctype: ```js const dom = new JSDOM(`<!DOCTYPE html>hello`); dom.serialize() === "<!DOCTYPE html><html><head></head><body>hello</body></html>"; // Contrast with: dom.window.document.documentElement.outerHTML === "<html><head></head><body>hello</body></html>"; ``` ### Getting the source location of a node with `nodeLocation(node)` The `nodeLocation()` method will find where a DOM node is within the source document, returning the [parse5 location info](https://www.npmjs.com/package/parse5#options-locationinfo) for the node: ```js const dom = new JSDOM( `<p>Hello <img src="foo.jpg"> </p>`, { includeNodeLocations: true } ); const document = dom.window.document; const bodyEl = document.body; // implicitly created const pEl = document.querySelector("p"); const textNode = pEl.firstChild; const imgEl = document.querySelector("img"); console.log(dom.nodeLocation(bodyEl)); // null; it's not in the source console.log(dom.nodeLocation(pEl)); // { startOffset: 0, endOffset: 39, startTag: ..., endTag: ... } console.log(dom.nodeLocation(textNode)); // { startOffset: 3, endOffset: 13 } console.log(dom.nodeLocation(imgEl)); // { startOffset: 13, endOffset: 32 } ``` Note that this feature only works if you have set the `includeNodeLocations` option; node locations are off by default for performance reasons. ### Interfacing with the Node.js `vm` module using `getInternalVMContext()` The built-in [`vm`](https://nodejs.org/api/vm.html) module of Node.js is what underpins jsdom's script-running magic. Some advanced use cases, like pre-compiling a script and then running it multiple times, benefit from using the `vm` module directly with a jsdom-created `Window`. To get access to the [contextified global object](https://nodejs.org/api/vm.html#vm_what_does_it_mean_to_contextify_an_object), suitable for use with the `vm` APIs, you can use the `getInternalVMContext()` method: ```js const { Script } = require("vm"); const dom = new JSDOM(``, { runScripts: "outside-only" }); const script = new Script(` if (!this.ran) { this.ran = 0; } ++this.ran; `); const vmContext = dom.getInternalVMContext(); script.runInContext(vmContext); script.runInContext(vmContext); script.runInContext(vmContext); console.assert(dom.window.ran === 3); ``` This is somewhat-advanced functionality, and we advise sticking to normal DOM APIs (such as `window.eval()` or `document.createElement("script")`) unless you have very specific needs. Note that this method will throw an exception if the `JSDOM` instance was created without `runScripts` set, or if you are [using jsdom in a web browser](#running-jsdom-inside-a-web-browser). ### Reconfiguring the jsdom with `reconfigure(settings)` The `top` property on `window` is marked `[Unforgeable]` in the spec, meaning it is a non-configurable own property and thus cannot be overridden or shadowed by normal code running inside the jsdom, even using `Object.defineProperty`. Similarly, at present jsdom does not handle navigation (such as setting `window.location.href = "https://example.com/"`); doing so will cause the virtual console to emit a `"jsdomError"` explaining that this feature is not implemented, and nothing will change: there will be no new `Window` or `Document` object, and the existing `window`'s `location` object will still have all the same property values. However, if you're acting from outside the window, e.g. in some test framework that creates jsdoms, you can override one or both of these using the special `reconfigure()` method: ```js const dom = new JSDOM(); dom.window.top === dom.window; dom.window.location.href === "about:blank"; dom.reconfigure({ windowTop: myFakeTopForTesting, url: "https://example.com/" }); dom.window.top === myFakeTopForTesting; dom.window.location.href === "https://example.com/"; ``` Note that changing the jsdom's URL will impact all APIs that return the current document URL, such as `window.location`, `document.URL`, and `document.documentURI`, as well as the resolution of relative URLs within the document, and the same-origin checks and referrer used while fetching subresources. It will not, however, perform navigation to the contents of that URL; the contents of the DOM will remain unchanged, and no new instances of `Window`, `Document`, etc. will be created. ## Convenience APIs ### `fromURL()` In addition to the `JSDOM` constructor itself, jsdom provides a promise-returning factory method for constructing a jsdom from a URL: ```js JSDOM.fromURL("https://example.com/", options).then(dom => { console.log(dom.serialize()); }); ``` The returned promise will fulfill with a `JSDOM` instance if the URL is valid and the request is successful. Any redirects will be followed to their ultimate destination. The options provided to `fromURL()` are similar to those provided to the `JSDOM` constructor, with the following additional restrictions and consequences: - The `url` and `contentType` options cannot be provided. - The `referrer` option is used as the HTTP `Referer` request header of the initial request. - The `resources` option also affects the initial request; this is useful if you want to, for example, configure a proxy (see above). - The resulting jsdom's URL, content type, and referrer are determined from the response. - Any cookies set via HTTP `Set-Cookie` response headers are stored in the jsdom's cookie jar. Similarly, any cookies already in a supplied cookie jar are sent as HTTP `Cookie` request headers. ### `fromFile()` Similar to `fromURL()`, jsdom also provides a `fromFile()` factory method for constructing a jsdom from a filename: ```js JSDOM.fromFile("stuff.html", options).then(dom => { console.log(dom.serialize()); }); ``` The returned promise will fulfill with a `JSDOM` instance if the given file can be opened. As usual in Node.js APIs, the filename is given relative to the current working directory. The options provided to `fromFile()` are similar to those provided to the `JSDOM` constructor, with the following additional defaults: - The `url` option will default to a file URL corresponding to the given filename, instead of to `"about:blank"`. - The `contentType` option will default to `"application/xhtml+xml"` if the given filename ends in `.xht`, `.xhtml`, or `.xml`; otherwise it will continue to default to `"text/html"`. ### `fragment()` For the very simplest of cases, you might not need a whole `JSDOM` instance with all its associated power. You might not even need a `Window` or `Document`! Instead, you just need to parse some HTML, and get a DOM object you can manipulate. For that, we have `fragment()`, which creates a `DocumentFragment` from a given string: ```js const frag = JSDOM.fragment(`<p>Hello</p><p><strong>Hi!</strong>`); frag.childNodes.length === 2; frag.querySelector("strong").textContent === "Hi!"; // etc. ``` Here `frag` is a [`DocumentFragment`](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment) instance, whose contents are created by parsing the provided string. The parsing is done using a `<template>` element, so you can include any element there (including ones with weird parsing rules like `<td>`). It's also important to note that the resulting `DocumentFragment` will not have [an associated browsing context](https://html.spec.whatwg.org/multipage/#concept-document-bc): that is, elements' `ownerDocument` will have a null `defaultView` property, resources will not load, etc. All invocations of the `fragment()` factory result in `DocumentFragment`s that share the same template owner `Document`. This allows many calls to `fragment()` with no extra overhead. But it also means that calls to `fragment()` cannot be customized with any options. Note that serialization is not as easy with `DocumentFragment`s as it is with full `JSDOM` objects. If you need to serialize your DOM, you should probably use the `JSDOM` constructor more directly. But for the special case of a fragment containing a single element, it's pretty easy to do through normal means: ```js const frag = JSDOM.fragment(`<p>Hello</p>`); console.log(frag.firstChild.outerHTML); // logs "<p>Hello</p>" ``` ## Other noteworthy features ### Canvas support jsdom includes support for using the [`canvas`](https://www.npmjs.com/package/canvas) package to extend any `<canvas>` elements with the canvas API. To make this work, you need to include `canvas` as a dependency in your project, as a peer of `jsdom`. If jsdom can find the `canvas` package, it will use it, but if it's not present, then `<canvas>` elements will behave like `<div>`s. Since jsdom v13, version 2.x of `canvas` is required; version 1.x is no longer supported. ### Encoding sniffing In addition to supplying a string, the `JSDOM` constructor can also be supplied binary data, in the form of a Node.js [`Buffer`](https://nodejs.org/docs/latest/api/buffer.html) or a standard JavaScript binary data type like `ArrayBuffer`, `Uint8Array`, `DataView`, etc. When this is done, jsdom will [sniff the encoding](https://html.spec.whatwg.org/multipage/syntax.html#encoding-sniffing-algorithm) from the supplied bytes, scanning for `<meta charset>` tags just like a browser does. If the supplied `contentType` option contains a `charset` parameter, that encoding will override the sniffed encoding—unless a UTF-8 or UTF-16 BOM is present, in which case those take precedence. (Again, this is just like a browser.) This encoding sniffing also applies to `JSDOM.fromFile()` and `JSDOM.fromURL()`. In the latter case, any `Content-Type` headers sent with the response will take priority, in the same fashion as the constructor's `contentType` option. Note that in many cases supplying bytes in this fashion can be better than supplying a string. For example, if you attempt to use Node.js's `buffer.toString("utf-8")` API, Node.js will not strip any leading BOMs. If you then give this string to jsdom, it will interpret it verbatim, leaving the BOM intact. But jsdom's binary data decoding code will strip leading BOMs, just like a browser; in such cases, supplying `buffer` directly will give the desired result. ### Closing down a jsdom Timers in the jsdom (set by `window.setTimeout()` or `window.setInterval()`) will, by definition, execute code in the future in the context of the window. Since there is no way to execute code in the future without keeping the process alive, outstanding jsdom timers will keep your Node.js process alive. Similarly, since there is no way to execute code in the context of an object without keeping that object alive, outstanding jsdom timers will prevent garbage collection of the window on which they are scheduled. If you want to be sure to shut down a jsdom window, use `window.close()`, which will terminate all running timers (and also remove any event listeners on the window and document). ### Running jsdom inside a web browser jsdom has some support for being run inside a web browser, using [browserify](https://browserify.org/). That is, inside a web browser, you can use a browserified jsdom to create an entirely self-contained set of plain JavaScript objects which look and act much like the browser's existing DOM objects, while being entirely independent of them. "Virtual DOM", indeed! jsdom's primary target is still Node.js, and so we use language features that are only present in recent Node.js versions (namely, Node.js v8+). Thus, older browsers will likely not work. (Even transpilation will not help: we use `Proxy`s extensively throughout the jsdom codebase.) Notably, jsdom works well inside a web worker. The original contributor, [@lawnsea](https://github.com/lawnsea/), who made this possible, has [published a paper](https://pdfs.semanticscholar.org/47f0/6bb6607a975500a30e9e52d7c9fbc0034e27.pdf) about his project which uses this capability. Not everything works perfectly when running jsdom inside a web browser. Sometimes that is because of fundamental limitations (such as not having filesystem access), but sometimes it is simply because we haven't spent enough time making the appropriate small tweaks. Bug reports are certainly welcome. ### Debugging the DOM using Chrome Devtools As of Node.js v6 you can debug programs using Chrome Devtools. See the [official documentation](https://nodejs.org/en/docs/inspector/) for how to get started. By default jsdom elements are formatted as plain old JS objects in the console. To make it easier to debug, you can use [jsdom-devtools-formatter](https://github.com/viddo/jsdom-devtools-formatter), which lets you inspect them like real DOM elements. ## Caveats ### Asynchronous script loading People often have trouble with asynchronous script loading when using jsdom. Many pages load scripts asynchronously, but there is no way to tell when they're done doing so, and thus when it's a good time to run your code and inspect the resulting DOM structure. This is a fundamental limitation; we cannot predict what scripts on the web page will do, and so cannot tell you when they are done loading more scripts. This can be worked around in a few ways. The best way, if you control the page in question, is to use whatever mechanisms are given by the script loader to detect when loading is done. For example, if you're using a module loader like RequireJS, the code could look like: ```js // On the Node.js side: const window = (new JSDOM(...)).window; window.onModulesLoaded = () => { console.log("ready to roll!"); }; ``` ```html <!-- Inside the HTML you supply to jsdom --> <script> requirejs(["entry-module"], () => { window.onModulesLoaded(); }); </script> ``` If you do not control the page, you could try workarounds such as polling for the presence of a specific element. For more details, see the discussion in [#640](https://github.com/jsdom/jsdom/issues/640), especially [@matthewkastor](https://github.com/matthewkastor)'s [insightful comment](https://github.com/jsdom/jsdom/issues/640#issuecomment-22216965). ### Unimplemented parts of the web platform Although we enjoy adding new features to jsdom and keeping it up to date with the latest web specs, it has many missing APIs. Please feel free to file an issue for anything missing, but we're a small and busy team, so a pull request might work even better. Beyond just features that we haven't gotten to yet, there are two major features that are currently outside the scope of jsdom. These are: - **Navigation**: the ability to change the global object, and all other objects, when clicking a link or assigning `location.href` or similar. - **Layout**: the ability to calculate where elements will be visually laid out as a result of CSS, which impacts methods like `getBoundingClientRects()` or properties like `offsetTop`. Currently jsdom has dummy behaviors for some aspects of these features, such as sending a "not implemented" `"jsdomError"` to the virtual console for navigation, or returning zeros for many layout-related properties. Often you can work around these limitations in your code, e.g. by creating new `JSDOM` instances for each page you "navigate" to during a crawl, or using `Object.defineProperty()` to change what various layout-related getters and methods return. Note that other tools in the same space, such as PhantomJS, do support these features. On the wiki, we have a more complete writeup about [jsdom vs. PhantomJS](https://github.com/jsdom/jsdom/wiki/jsdom-vs.-PhantomJS). ## Supporting jsdom jsdom is a community-driven project maintained by a team of [volunteers](https://github.com/orgs/jsdom/people). You could support jsdom by: - [Getting professional support for jsdom](https://tidelift.com/subscription/pkg/npm-jsdom?utm_source=npm-jsdom&utm_medium=referral&utm_campaign=readme) as part of a Tidelift subscription. Tidelift helps making open source sustainable for us while giving teams assurances for maintenance, licensing, and security. - [Contributing](https://github.com/jsdom/jsdom/blob/master/Contributing.md) directly to the project. ## Getting help If you need help with jsdom, please feel free to use any of the following venues: - The [mailing list](http://groups.google.com/group/jsdom) (best for "how do I" questions) - The [issue tracker](https://github.com/jsdom/jsdom/issues) (best for bug reports) - The IRC channel: [#jsdom on freenode](irc://irc.freenode.net/jsdom)
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/README.md
README.md
# jsdom Changelog <!-- Style guide: * Use past tense verbs to start the sentence, e.g. "Fixed", "Added", "Removed", ... * Each bullet point is a sentence (or more), and so ends with a period. * Package names are in `code`, sometimes [`linked`](). * Prefer referring to methods and properties via `someInstance.prop`, instead of `ClassName.prototype.prop`. (Never use `ClassName.prop` except for statics.) * Refer to attributes via `attr=""`. * Refer to elements via `<element>`. * Refer to events via `eventname`. * Refer to CSS properties via `'propname'`. * Never use the IDL terms "interface", "attribute", or "operation". * URL schemes are in `code`, e.g. `data:`. * Except in the headings, all version numbers get a "v" prefix, e.g. v12.2.0. * Follow the bullet point with parenthetical GitHub usernames when contributed by a non-core team member, e.g. "Fixed foo. (person)" Other guidelines: * Commit messages are primarily for jsdom developers. Changelog entries are primarily for users. Usually you cannot reuse the commit message. * Sometimes a single commit may expand to multiple changelog entries. * Do not include commits that have no user-facing impact, e.g. test rolls, refactorings, benchmark additions, etc. * For regression fixes, note the version in which something regressed. * Breaking changes get their own section. * Group in the order "Added", "Removed", "Changed", "Fixed". * Roughly order changes within those groupings by impact. --> ## 16.3.0 * Added firing of `focusin` and `focusout` when using `el.focus()` and `el.blur()`. (trueadm) * Fixed elements with the `contenteditable=""` attribute to be considered as focusable. (jamieliu386) * Fixed `window.NodeFilter` to be per-`Window`, instead of shared across all `Window`s. (ExE-Boss) * Fixed edge-case behavior involving use of objects with `handleEvent` properties as event listeners. (ExE-Boss) * Fixed a second failing image load sometimes firing a `load` event instead of an `error` event, when the `canvas` package is installed. (strager) * Fixed drawing an empty canvas into another canvas. (zjffun) ## 16.2.2 * Updated `StyleSheetList` for better spec compliance; notably it no longer inherits from `Array.prototype`. (ExE-Boss) * Fixed `requestAnimationFrame()` from preventing process exit. This likely regressed in v16.1.0. * Fixed `setTimeout()` to no longer leak the closures passed in to it. This likely regressed in v16.1.0. (AviVahl) * Fixed infinite recursion that could occur when calling `click()` on a `<label>` element, or one of its descendants. * Fixed `getComputedStyle()` to consider inline `style=""` attributes. (eps1lon) * Fixed several issues with `<input type="number">`'s `stepUp()` and `stepDown()` functions to be properly decimal-based, instead of floating point-based. * Fixed various issues where updating `selectEl.value` would not invalidate properties such as `selectEl.selectedOptions`. (ExE-Boss) * Fixed `<input>`'s `src` property, and `<ins>`/`<del>`'s `cite` property, to properly reflect as URLs. * Fixed `window.addEventLister`, `window.removeEventListener`, and `window.dispatchEvent` to properly be inherited from `EventTarget`, instead of being distinct functions. (ExE-Boss) * Fixed errors that would occur if attempting to use a DOM object, such as a custom element, as an argument to `addEventListener`. * Fixed errors that would occur when closing a window with outstanding requests to `data:` URLs. * Fixed sporadic issues with the value of `<input type="month">` that could occur in some time zones and for some times. * Fixed `document.implementation.createDocument()` to return an `XMLDocument`, instead of a `Document`. (ExE-Boss) * Fixed running jsdom in a browser to detect globals more reliably. (ExE-Boss) ## 16.2.1 * Updated `saxes`, to bring in some BOM-related fixes. * Updated Acorn-related packages to squelch `npm audit` warnings. ## 16.2.0 * Added support for custom elements! Congratulations and thanks to [@pmdartus](https://github.com/jsdom/jsdom/commits?author=pmdartus) for making this happen, after ten months of hard work and lots of effort poured into the complex architectural prerequisites in jsdom and supporting packages. * Fixed some issues when trying to use `Attr` as a `Node`, e.g. by checking its `baseURI` property or calling `attr.cloneNode()`. * Fixed a memory leak during parsing that was introduced in v14.0.0. * Fixed edge cases in number/string conversion used for certain element properties that reflected integer attributes. ## 16.1.0 * Added `console.timeLog()`. * Changed `Attr` to extend `Node`, to align with specifications. (ExE-Boss) * Changed `<noscript>` children to be parsed as nodes, instead of as text, when `runScripts` is left as the default of `undefined`. (ACHP) * Upgraded `cssstyle` to v2.1.0, which brings along fixes to handling of `rgba()` and `hsl()` colors. (kraynel) * Fixed some selection-related issues when manipulating the value of `<input>`s and `<textarea>`s. (Matthew-Goldberg) * Fixed various issues with `setTimeout()`, `setInterval()`, and `requestAnimationFrame()`, particularly around window closing and recursive calls. ## 16.0.1 * Fixed Node v10 and v11 support when `runScripts` was set. * Fixed the behavior when changing an `<input>`'s `type=""` attribute. * Fixed input validation behavior for `<input type="range">` when `max=""` is less than `min=""`. ## 16.0.0 For this release we'd like to welcome [@pmdartus](https://github.com/jsdom/jsdom/commits?author=pmdartus) to the core team. Among other work, he's driven the heroic effort of constructor prototype and reform in jsdom and its dependencies over the last few months, to allow us to move away from shared constructors and prototypes, and set the groundwork for custom elements support ([coming soon](https://github.com/jsdom/jsdom/pull/2548)!). Breaking changes: * Node v10 is now the minimum supported version. * The `dom.runVMScript()` API has been replaced with the more general `dom.getInternalVMContext()` API. * Each jsdom `Window` now creates new instances of all the web platform globals. That is, our old [shared constructor and prototypes](https://github.com/jsdom/jsdom/blob/35894a6703ed1f4de98942780bd99244ac27f600/README.md#shared-constructors-and-prototypes) caveat is no longer in play. * Each jsdom `Window` now exposes all JavaScript-spec-defined globals uniformly. When `runScripts` is disabled, it exposes them as aliases of the ones from the outer Node.js environment. Whereas when `runScripts` is enabled, it exposes fresh copies of each global from the new scripting environment. (Previously, a few typed array classes would always be aliased, and with `runScripts` disabled, the other classes would not be exposed at all.) Other changes: * Added the `AbstractRange`, `Range`, `StaticRange`, `Selection`, and `window.getSelection()` APIs. * Added working constructors for `Comment`, `Text`, and `DocumentFragment`. * Added `valueAsDate`, `valueAsNumber`, `stepUp()` and `stepDown()` to `<input>` elements. (kraynel) * Added `window.origin`. * Removed `document.origin`. * Fixed `<template>` to work correctly inside XML documents. * Fixed some bugs which would cause jsdom to choose the wrong character encoding because it was failing to detect `<meta charset>` or `<meta http-equiv="charset">` elements. * Fixed `input.type` to default to `"text"`. (connormeredith) * Fixed incorrect validation errors for `<input>` with fractional values for their `step=""` attribute. (kontomondo) * Fixed incorrect validation errors on readonly `<input>` elements. * Fixed `<input type="email" multiple pattern="...">` validation. * Fixed `fileReader.readAsDataURL()` to always base64-encode the result. (ytetsuro) * Fixed inserting `<img>` elements into documents without a browsing context to no longer crash when the `canvas` package is installed. * Fixed a memory leak when using `window.setTimeout()` or `window.setInterval()`. * Improved the performance of `getComputedStyle()`. (eps1lon) ## 15.2.1 * Fixed `JSDOM.fromURL()` handling of URLs with hashes in them, to no longer send the hash to the server and append an extra copy of it when constructing the `Document`. (rchl) * Fixed focusing an already-focused element to correctly do nothing, instead of firing additional `focus` events. (eps1lon) * Fixed typo in the not-implemented message for `mediaElement.addTextTrack()`. (mtsmfm) * Upgraded `nwsapi` minimum version to 2.2.0, which fixes issues with `::-webkit-` prefixed pseudo-elements and namespaced attribute selectors. ## 15.2.0 * Added basic style inheritance in `getComputedStyle()` for the `'visibility'` property. This sets the foundation for further work on inheritance, cascading, and specificity. (eps1lon) * Added `shadowRoot.activeElement`. * Added `readystatechange` events during document loading. * Added a stub for `form.requestSubmit()`, to match our existing stub for `form.submit()`. * Changed `el.tabIndex`'s default value, when no `tabindex=""` attribute was set, to reflect the updated specification. * Changed the exception thrown by `el.attachShadow()` on something that's already a shadow host, to reflect the updated specification. * Fixed the validation logic for `<input type="range">`. * Fixed `selectEl.value` when no `<option>` is selected to return the empty string, instead of the value of the first option. (tgohn) * Fixed various correctness issues with `new FormData(formElement)`. (brendo) * Fixed error messages when parsing XML to include the filename, instead of using `"undefined"`. (papandreou) * Fixed the logic for reflected properties to not be affected by overwriting of `el.getAttributeNS()` or `el.setAttributeNS()`. * Set `canvas` as an optional ``peerDependency`, which apparently helps with Yarn PnP support. ## 15.1.1 * Moved the `nonce` property from `HTMLScriptElement` and `HTMLStyleElement` to `HTMLElement`. Note that it is still just a simple reflection of the attribute, and has not been updated for the rest of the changes in [whatwg/html#2373](https://github.com/whatwg/html/pull/2373). * Fixed the `style` and `on<event>` properties to properly track their related attributes for SVG elements. (kbruneel) * Fixed `XMLHttpRequest` merging preflight and response headers. (thiagohirata) * Fixed `XMLHttpRequest` reserializing `content-type` request headers unnecessarily. See [whatwg/mimesniff#84](https://github.com/whatwg/mimesniff/issues/84) for more details. (thiagohirata) * Fixed `element.tagName` to be the ASCII uppercase of the element's qualified name, instead of the Unicode uppercase. ## 15.1.0 * Added the `Headers` class from the Fetch standard. * Added the `element.translate` getter and setter. * Fixed synchronous `XMLHttpRequest` on the newly-released Node.js v12. * Fixed `form.elements` to exclude `<input type="image">` elements. * Fixed event path iteration in shadow DOM cases, following spec fixes at [whatwg/dom#686](https://github.com/whatwg/dom/pull/686) and [whatwg/dom#750](https://github.com/whatwg/dom/pull/750). * Fixed `pattern=""` form control validation to apply the given regular expression to the whole string. (kontomondo) ## 15.0.0 Several potentially-breaking changes, each of them fairly unlikely to actually break anything: * `JSDOM.fromFile()` now treats `.xht` files as `application/xhtml+xml`, the same as it does for `.xhtml` and `.xml`. Previously, it would treat them as `text/html`. * If the `JSDOM` constructor's `contentType` option has a `charset` parameter, and the first argument to the constructor is a binary data type (e.g. `Buffer` or `ArrayBuffer`), then the `charset` will override any sniffed encoding in the same way as a `Content-Type` header would in browser scenarios. Previously, the `charset` parameter was ignored. * When using the `Blob` or `File` constructor with the `endings: "native"` option, jsdom will now convert line endings to `\n` on all operating systems, for consistency. Previously, on Windows, it would convert line endings to `\r\n`. ## 14.1.0 * Added activation behavior for `<a>` and `<area>` elements whose `href=""` points to a `javascript:` URL or fragment. * Added the `<datalist>` element's `options` property. * Added the `<input>` element's `list` property. * Added `PageTransitionEvent`, and the firing of `pageshow` events during loading. * Exposed the `External` class as a property of `window`. * Fixed HTML fragment parsing (via `innerHTML` and `outerHTML`) to be spec-compliant. (pmdartus) * Fixed HTML serialization (e.g. via `innerHTML`) breaking after setting certain properties to non-string values. * Fixed how disabling an element would cause its activation behavior to forever be null, even if it were re-enabled. * Fixed all access to attributes to ignore attributes with namespaces, per the spec. * Fixed `<style>`s to no longer apply to documents without a browsing context. This includes fixing a crash that would occur with such styles if they had an `@import` rule. * Fixed `<option>`'s `label` and `value` properties to return correct values in various edge cases. * Fixed the `load` event during document loading to target the `Document`, not the `Window`. * Fixed the `pretendToBeVisual` option to propagate to child subframes, as well as the main `Window`. (pyrho) * Updated the minimum [`nwsapi`](https://www.npmjs.com/package/nwsapi) version from v2.1.1 to v2.1.3, bringing along a few fixes in our selector engine. ## 14.0.0 Breaking changes: * `JSDOM.fragment()` now creates fragments whose document has no [browsing context](https://html.spec.whatwg.org/multipage/#concept-document-bc), i.e. no associated `Window`. This means the `defaultView` property will be null, resources will not load, etc. * `JSDOM.fragment()`, called with no arguments, now creates a `DocumentFragment` with no children, instead of with a single child text node whose data was `"undefined"`. Other changes: * Fixed a regression in v13.2.0 when calling `element.blur()` on a focused element. * Fixed inserting `<link>` elements into documents with no browsing context to no longer crash if the originating `JSDOM` was configured to fetch the resource. Now, per spec, `<link>` elements only attempt to fetch if they are browsing-context connected. * Fixed `<template>` elements to have the correct semantics, of using a separate browsing-context-less document to store its contents. In particular this means resources will not be fetched for elements inside the `<template>`, as per spec. ## 13.2.0 * Added support for `MutationObserver`s! (pmdartus) * Added support for XML documents loaded in frames and iframes; previously this would error. * Added the `<progress>` element's `value`, `max`, and `position` properties. * Added `navigator.plugins` and `navigator.mimeTypes`. (But, they are always empty.) * Fixed `<summary>` elements respond to `click` events by toggling their parent `<details>`. * Fixed `<summary>` elements to be focusable. * Fixed XML document DOCTYPE parsing to preserve any custom name values. * Fixed XML documents to default to UTF-8, not windows-1252 like HTML documents do. * Fixed all events fired by jsdom to have `isTrusted` set to `true`. * Fixed `DOMParser`-created documents to have their `readyState` set to `"complete"`. * Fixed how nested `<fieldset>`s get disabled. * Fixed `getComputedStyle()` to throw a sensible exception when passed the wrong argument, instead of one that exposes jsdom internals. * Upgraded our [`saxes`](https://github.com/lddubeau/saxes) dependency, so that it now correctly errors on XML fragments like `<foo bar:="1"/>`. ## 13.1.0 * Added `el.insertAdjacentElement()` and `el.insertAdjacentText()`. * Added the firing of a cancelable `reset` event to `form.reset()`. (epfremmer) * Added the `type`, `value`, and `defaultValue` properties to `<output>` elements, including their form reset behavior. (epfremmer) * Added the `outputEl.htmlFor` property. * Fixed the performance of parsing large text nodes, particularly noticeable for large inline `<style>` or `<script>` elements. This regressed in v11.6.0. To learn more, see [V8 issue #6730](https://bugs.chromium.org/p/v8/issues/detail?id=6730#c4). * Fixed the `style` property on `<a>` and `<area>` elements. This regressed in v13.0.0. * Fixed `node.isConnected` to not always return false for nodes inside a shadow tree. (pmdartus) * Fixed `<button type="reset">` and `<input type="reset">` elements to actually perform a form reset when clicked, instead of doing nothing. (epfremmer) * Fixed `el.setCustomValidity()` for `<output>` and `<fieldset>`. * Fixed activation behavior when dispatching bubbling `click` events, so that for example calling `el.click()` on the child of a submit button element will submit the form. * Fixed our XML parsing code to ignore text outside the root element, instead of treating it as an error. (lddubeau) * Fixed XML serialization when elements had an unknown prefix. * Fixed radio button group name matching to be case-sensitive, per [a spec update](https://github.com/whatwg/html/commit/6acdb2122298d2bb7bb839c0a61b4e1f9b0f9bc9). * Fixed `focus`/`blur` events to be composed. * Fixed `mediaElement.duration` to default to `NaN`. * Fixed `olEl.start` to default to `1`. * Fixed using `XMLHttpRequest` against non-existant `file:` URLs to treat that as a network error, instead of crashing. (pascalbayer) Note that in the future we may completely disable `XMLHttpRequest` usage against `file:` URLs to follow the browser security model. * Fixed `document.title` in SVG documents. * Fixed `titleElement.text` to return the child text content, instead of being the same as `titleElement.innerHTML`. * Fixed `<textarea>`s to properly account for child CDATA section nodes changing. * Fixed the value of `Element.prototype[Symbol.unscopables]`. ## 13.0.0 Breaking change: * Removed support for v1.x of the [`canvas`](https://github.com/Automattic/node-canvas) package, in favor of v2.x. This also removes support for `canvas-prebuilt`, since `canvas` v2.x has a built-in prebuilt version. Other changes: * Added proper XML serialization, based on the [`w3c-xmlserializer`](https://github.com/jsdom/w3c-xmlserializer) package. Previously we were just using the HTML serialization, even in XML documents. * Added the `storageEvent.initStorageEvent()` method. * Added support for the `passive` option to `addEventListener()`. * Added the `relList` property to `<a>`, `<area>`, and `<link>` elements. * Fixed our implementation of the node tree modification constraints (for example the [ensure pre-insertion validity](https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity) algorithm). It is no longer possible to add, remove, or move nodes to create impossible DOM trees. (pmdartus) ## 12.2.0 * Added support for shadow DOM! This includes shadow roots, slots, composed events, and more. (pmdartus) * Added the `element.toggleAttribute()` method. * Fixed `XMLHttpRequest` sometimes sending an empty request body after a preflight request. (andreasf) * Fixed the `formElement.form` property to use an algorithm that also checks the `form=""` attribute, instead of always looking for the closest ancestor `<form>` element. (jamietre) * Stopped swallowing errors when the `canvas` or `canvas-prebuilt` packages were installed, but failed to load. (joscha) ## 12.1.0 * Dramatically upgraded our XML parser, from the unmaintained [`sax`](https://github.com/isaacs/sax-js) package to the well-maintained [`saxes`](https://github.com/lddubeau/saxes) replacement. This increases our specification conformance, including rejecting certain ill-formed XML documents that were previously accepted, and properly handling other constructs like empty comments, CDATA sections, and `<script>` elements. (lddubeau) * Added `fieldsetEl.elements` and `fieldsetEl.type` properties. * Added the `options` parameter to `dom.runVMScript()`. (SimenB) * Added the ability for custom resource loader `fetch()` implementations to see what element initiated the fetch. (sarvaje) * Fixed `input` and `change` events for `<input>` elements to be trusted and uncancelable. * "Fixed" `<script>`s with the `async` attribute to not execute before sync `<script>`s that precede them. We still do not, in general, have proper execution of scripts during the initial parsing of a document, so this fix is more of a reduction of badness than an alignment with the specification. This behavior regressed in v12.0.0. (sarvaje) ## 12.0.0 This major release brings along our [new resource loader API](https://github.com/jsdom/jsdom#loading-subresources), finally bringing all the capabilities from jsdom v9 to the new (jsdom v10+) API. Thanks very much to [@sarvaje](https://github.com/sarvaje) for his work to make this possible! Breaking changes: * jsdom now requires Node.js v8. * Removed the old jsdom API, as the new API now has all the capabilities you need. * Updated our [`parse5`](https://github.com/inikulin/parse5/) dependency to v5, which changes the format of the node locations returned by `dom.nodeLocation()`. * Updated our [`whatwg-url`](https://github.com/jsdom/whatwg-url) dependency to v7, which changes the origin of `file:` URLs to be an opaque origin (and thus `file:` URLs are no longer same origin to each other). Other changes: * Added `countReset()`, `dir()` and `dirxml()` methods to `console`. * Added the `InputEvent` class. * Added `window.status`. * Added `htmlElement.draggable`. * Fixed `window.frameElement` to correctly return an actual `HTMLElement` instance, instead of a jsdom internal class. * Fixed cloning of `textarea` elements to preserve their values. * Fixed `select.selectedOptions` sometimes returning outdated results. * Fixed CSS selection APIs sometimes returning outdated results, especially for state pseudo-class selectors like `:checked`. * Fixed CSS selection APIs to throw an error for invalid selectors even when used on empty nodes. * Fixed `window.name` to default to the empty string, per spec, instead of `"nodejs"`. * Fixed the default User-Agent to say "unknown OS" instead of "undefined" when jsdom is used in web browsers. ## 11.12.0 * Added `window.localStorage`, `window.sessionStorage`, and `StorageEvent` support. These are currently only stored in-memory; file an issue if you need persistent (on-disk) storage capability so we can discuss adding that. This feature includes the new `storageQuota` option for controlling how much can be stored. * Added `element.closest()`. (caub) * Changed `hashchange` and `popstate` events to no longer bubble, per a specification update. * Fixed the old API in Node.js v10 to not throw, when given input that is not a valid file path (such as a typical HTML string). * Upgraded `cssstyle` to v1.0.0, bringing along various fixes to our CSS parser and object model. (eddies) * Upgraded `nwsapi` to v2.0.7, bringing along various fixes to our selector engine. ## 11.11.0 * Added `node.getRootNode()`. (FrecksterGIT) * Added `label.control`. (FrecksterGIT) * Added `el.labels` for form control elements. (FrecksterGIT) * Fixed the `contentType` of `Document`s created through `<iframe>`s. * Fixed the `contentType` and `origin` of `Document`s created through `document.implementation.createDocument()`. * Fixed `sourceEl.srcset` to return the value of the `srcset=""` attribute, instead of the `cite=""` attribute. * Fixed `node.normalize()` to not modify non-`Text` nodes. (lddubeau) * Upgraded `cssstyle` to v0.3.1, bringing along various fixes to our CSS parser and object model. (jsakas) * Upgraded `whatwg-url` to v6.4.1, fixing the interaction of `URL`'s `href` and `searchParams` properties. * Upgraded our selector matching engine from `nwsmatcher` to `nwsapi`, bringing along extensive fixes, performance improvements, and additional selector support. ## 11.10.0 * Added `event.srcElement` and `event.returnValue`. * Fixed `XMLHttpRequest` to correctly set the User-Agent header, and set it on CORS preflight requests. (BehindTheMath) ## 11.9.0 * Added `node.lookupPrefix()`, `node.lookupNamespaceURI()` and `node.isDefaultNamespace()`. * Fixed the cloning of `Document`s; previously it would not clone all of the appropriate state, and would sometimes add an extra document type node. * Fixed various edge cases in the `textContent` and `nodeValue` properties. * Fixed `canvas.toBlob()` to properly pass through the JPEG quality argument, instead of always passing zero to `node-canvas`. (challakoushik) ## 11.8.0 * Added the full constraint validation API, i.e. `willValidate`, `validity`, `validationMessage`, `checkValidity()`, `reportValidity()`, and `setCustomValidity()`, on `HTMLButtonElement`, `HTMLFieldSetElement`, `HTMLFormElement`, `HTMLInputElement`, `HTMLObjectElement`, `HTMLOutputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. (kontomondo) * Added `getElementById()` to `DocumentFragment`. ## 11.7.0 * Added the boolean return value to `DOMTokenList`'s `replace()` method, per the recent spec addition. * Added `FileReader`'s `readAsBinaryString()` method, as it has been added back to the specification. * Fixed event handlers to be own properties of each `Window`, instead of on `Window.prototype`. (Fetz) * Fixed an exception that would sometimes get raised when removing an `<img>` element's `src=""` attribute. (atsikov) * Fixed `abort` events on `AbortSignal`s to have their `isTrusted` set to true. * Fixed some argument conversions in `XMLHttpRequest`'s `open()` method. * Improved MIME type and `data:` URL parsing throughout jsdom, by using the new [`whatwg-mimetype`](https://www.npmjs.com/package/whatwg-mimetype) and [`data-urls`](https://www.npmjs.com/package/data-urls) packages. * Removed some unnecessary `.webidl` files that were included in the npm package. ## 11.6.2 * Fixed another regression (since v11.6.0) in `<style>` elements, where they would omit a series of parsing `jsdomError` events for any style sheet text containing spaces. * Generally improved the spec-conformance of when `<style>` and `<script>` elements are evaluated; for example, `<script>` elements inserted by `innerHTML` are no longer evaluated. ## 11.6.1 * Fixed one regression (since v11.6.0) in `<style>` elements, where their `sheet` property would sometimes be `null` when it should not be. * Fixed a case where a `<style>` element's `sheet` property would be left as a `CSSStyleSheet` despite it not being in the document. Another regression remains where we are emitting spurious CSS-parsing `jsdomError` events; see [#2123](https://github.com/jsdom/jsdom/issues/2123). We also discovered a large amount of preexisting brokenness around `<style>`, `<link>`, and `@import`; see [#2124](https://github.com/jsdom/jsdom/issues/2124) for more details. We'll try to fix these soon, especially the regression. ## 11.6.0 * Added a fully-functioning `WebSocket` implementation! * Added a `window.performance` implementation, including the basics of the [High Resolution Time](https://w3c.github.io/hr-time/) specification: `performance.now()`, `performance.timeOrigin`, and `performance.toJSON()`. * Added support for all of the public API of `HTMLMeterElement`, except for `meterEl.labels`. * Added the `locationbar`, `menubar`, `personalbar`, `scrollbars`, `statusbar`, and `toolbar` properties to `Window`. * Added more properties to `window.screen`: `availWidth`, `availHeight`, `colorDepth`, and `pixelDepth`. All of its properties are now getters as well. * Added `window.devicePixelRatio`. * Added `getModifierState()` to `MouseEvent` and `KeyboardEvent`. * Added a setter for `HTMLInputElement`'s `files` property. * Added support for the `endings` option to the `Blob` constructor. * Fixed firing various event firings to have the correct default values, e.g. the properties of `MouseEvent` when using `element.click()`. * Fixed the firing of `popstate` and `hashchange` events during fragment navigation to make them trusted events. * Fixed `data:` URL parsing to not include the fragment portions. * Fixed all URL-accepting properties to properly perform [scalar value string conversion](https://infra.spec.whatwg.org/#javascript-string-convert) and URL resolution. * Fixed many other small edge-case conformance issues in the API surface of various web APIs; see [#2053](https://github.com/jsdom/jsdom/pull/2053) and [#2081](https://github.com/jsdom/jsdom/pull/2081) for more information. * Fixed various APIs to use ASCII lowercasing, instead of Unicode lowercasing, for element and attribute names. * Fixed the encoding of a document created via `new Document()` to be UTF-8. * Fixed event handler properties behavior when given non-callable objects. * Increased the performance of parsing HTML documents with large numbers of sibling elements. * Removed `probablySupportsContext()` and `setContext()` from `HTMLCanvasElement`, per spec updates. * Removed the nonstandard `window.scrollLeft` and `window.scrollTop` properties, and the `window.createPopup()` method. ## 11.5.1 (This should have been a minor release; oops.) * Added `AbortSignal` and `AbortController`. * Fixed validation for file `<input>`s and implemented validation for more input types. ## 11.4.0 For this release we'd like to welcome [@Zirro](https://github.com/jsdom/jsdom/commits?author=Zirro) to the core team; his contributions over the course of this year have enhanced jsdom immensely. * Added a rudimentary set of SVG element classes, namely `SVGElement`, `SVGGraphicsElement`, `SVGSVGElement`, `SVGTests`, `SVGAnimatedString`, `SVGNumber`, and `SVGStringList`. The main impact here is that SVG elements are now instances of `SVGElement`, instead of being simply `Element` (as they were in v11.3.0) or `HTMLUnknownElement` (as they were in v11.2.0 and previously). The only concrete subclass that is implemented is `SVGSVGElement`, for `<svg>` itself; other tags will not map to their correct classes, because those classes are not yet implemented. * Added the new `pretendToBeVisual` option, which controls the presence of the new `requestAnimationFrame()` and `cancelAnimationFrame()` methods, and the new values of `document.hidden`/`document.visibilityState`. [See the README](https://github.com/jsdom/jsdom#pretending-to-be-a-visual-browser) for more information. (SimenB) * Added the `append()` and `prepend()` methods to `Document`, `DocumentFragment`, and `Element`. (caub) * Added the `before()`, `after()`, and `replaceWith()` methods to `DocumentType`, `Element`, and `CharacterData`. (caub) * Added `node.isConnected`. * Added `node.isSameNode()`. * Added support for parsing CDATA sections in XML documents, including in `domParser.parseFromString()`. (myabc) * Added appropriate `input.value` getter/setter logic for `<input type="file">`. * Significantly improved the spec-compliance of `NamedNodeMap`, i.e. of `element.attributes`, such that retrieving named or indexed properties will now always work properly. * Fixed `domParser.parseFromString()` to not parse HTML character entities in XML documents. (myabc) * Fixed `xhr.abort()` to clear any set headers. * Fixed `XMLHttpRequest` to always decoded responses as UTF-8 when `responseType` is set to `"json"`. * Fixed `XMLHttpRequest` CORS header handling, especially with regard to preflights and Access-Control-Allow-Headers. (ScottAlbertine) * Fixed the behavior of `radioButton.click()` to fire appropriate `input` and `change` events. (liqwid) * Fixed `querySelector()`/`querySelectorAll()` behavior for SVG elements inside `<template>` contents `DocumentFragment`s, including those created by `JSDOM.fragment()`. (caub) * Fixed the line number reporting in exception stack traces when using `<script>` elements, when `includeNodeLocations` is set. * Removed the `<applet>` element, [following the spec](https://github.com/whatwg/html/pull/1399). ## 11.3.0 For this release we'd like to formally welcome [@TimothyGu](https://github.com/jsdom/jsdom/commits?author=TimothyGu) to the core team, as a prolific contributor. He will join the illustrious ranks of those who do so much work on jsdom that we no longer note their names in the changelog. * Added `table.tHead`, `table.tFoot`, and `table.caption` setters, and the `table.createTBody()` method. * Added `CompositionEvent` and `WheelEvent` classes. * Added a `<details>` element implementation. (Zirro) * Added stub `<marquee>` and `<picture>` element implementations. (Zirro) * Updated `uiEvent.initUIEvent()`, `keyboardEvent.initKeyboardEvent()`, and `mouseEvent.initiMouseEvent()` to match the latest specifications. * Converted `DOMTokenList` (used by, e.g., `element.classList`) to use proxies for improved specification compliance and "liveness". * Fixed the `DOMException` class to be spec-compliant, including its constructor signature. * Fixed some subtle interactions between inline event handlers and other event listeners. * Fixed the element interface used when creating many of the more obscure elements. * Fixed the behavior of the `table.rows` getter, and the `table.createCaption()` and `table.deleteRow()` methods. * Fixed incorrect sharing of methods between interfaces that used mixins (e.g. previously `document.querySelector === documentFragment.querySelector`, incorrectly). * Fixed `FocusEvent` creation, which regressed in v11.2.0. * Fixed `UIEvent` to only allow initializing with `Window` objects for its `view` property. * Fixed the behavior of `tr.rowIndex` and `tr.deleteCall()`. * Fixed the element interface for `<td>` and `<th>` to be simply `HTMLTableCellElement`, and improved that class's spec compliance. * Fixed calling `label.click()` to not trigger the labeled control's activation behavior when the control is disabled. (schreifels) * Fixed `document.getElementsByName()` to return a `NodeList` instead of a `HTMLCollection`. (Zirro) * Significantly sped up synchronous `XMLHttpRequest`. (Zirro) ## 11.2.0 This release brings with it a much-awaited infrastructure change, as part of [webidl2js v7.3.0](https://github.com/jsdom/webidl2js/releases/tag/v7.3.0) by the ever-amazing TimothyGu: jsdom can now generate spec-compliant versions of classes that have "`Proxy`-like" behavior, i.e. allow getting or setting keys in unusual ways. This enables a number of improvements, also by TimothyGu: * Significantly improved the spec-compliance and "liveness" of both `NodeList` and `HTMLCollection`, such that retrieving properties via indices or (in `HTMLCollection`'s case) `id`/`name` values will always work correctly. * Added `element.dataset` support. * Added indexed and named access to `<select>` elements, as well as the corresponding `item()` and `namedItem()` methods. * Added suport for `FileList` indexed properties, i.e. `fileList[i]`. * Made `select.options` an instance of the newly-implemented `HTMLOptionsCollection`, instead of just a `HTMLCollection`. This infrastructure will allow us to improve and implement many other similar behaviors; that work is being tracked in [#1129](https://github.com/jsdom/jsdom/issues/1129). In addition to these improvements to the object model, we have more work to share: * Added no-op APIs `document.clear()`, `document.captureEvents()`, `document.releaseEvents()`, `window.external.AddSearchProvider()`, and `window.external.IsSearchProviderInstalled()`. (Zirro) * Added active checks to prevent reentrancy in `TreeWalker` and `NodeIterator`. * Updated the interaction between a `<textarea>`'s `value`, `defaultValue`, and `textContent` per [a recent spec change](https://github.com/whatwg/html/commit/5afbba1cf62ee01bc6af3fd220d01f3f7591a0fc) * Fixed elements with `id="undefined"` shadowing the `undefined` property of the global object. (TimothyGu) * Fixed matching in `getElementsByClassName()` to be ASCII case-insensitive, instead of using JavaScript's `toLowerCase()`. * Improved some behaviors around navigating to fragments. (ForbesLindesay) * Improved `XMLHttpRequest` and `FileReader` behavior, mainly around event handlers, `abort()`, and network errors. * Improved edge-case spec compliance of `NodeIterator`. ## 11.1.0 * Added `javascript:` URL "navigation" via `window.location`, at least by evaluating the side effects. It still doesn't actually navigate anywhere. (ForbesLindesay) * Updated `whatwg-url` to v6.1.0, bringing along origin serialization changes and `URLSearchParams` among various other fixes. (ForbesLindesay) * Fixed `javascript:` URL loading for iframes to do proper percent-decoding and error reporting. * Fixed corrupted `XMLHttpRequest` responses when they were over 1 MiB. * Fixed timers to not start after a window is `close()`d, which could cause strange errors since most objects are unusable at that point. (Enverbalalic) ## 11.0.0 Breaking changes: * Custom parsers, via the `parser` option to the old API, can no longer be specified. They were never tested, often broken, and a maintenance burden. The defaults, of [parse5](https://www.npmjs.com/package/parse5) for HTML and [sax](https://www.npmjs.com/package/sax) for XML, now always apply. * Due to a parse5 upgrade, the location info objects returned by `dom.nodeLocation()` or the old API's `jsdom.nodeLocation()` now have a different structure. * Fixed how `runScripts` applies to event handler attributes; now they will no longer be converted into event handler functions unless `runScripts: "dangerously"` is set. However, event handler _properties_ will now work with any `runScripts` option value, instead of being blocked. Other changes: * Overhauled how event handler properties and attributes work to follow the spec. In particular, this adds various `oneventname` properties to various prototypes, ensures the correct order when interleaving event handlers and other event listeners, and ensures that event handlers are evaluated with the correct values in scope. * Upgraded parse5 from v1 to v3, bringing along several correctness improvements to HTML parsing. (Zirro) * Updated `Location` properties to be on the instance, instead of the prototype, and to be non-configurable. * Significantly improved the performance of `HTMLCollection`, and thus of parsing large documents. (Zirro) * Significantly improved the performance of `getComputedStyle()` by removing unsupported selectors from the default style sheet. (flaviut) * Fixed all web platform methods that accepted web platform objects to perform proper type checks on them, throwing a `TypeError` when given invalid values. (TimothyGu) * Fixed the `Symbol.toStringTag` properties to be non-writable and non-enumerable. (TimothyGu) * Fixed `tokenList.remove()` when the `DOMTokenList` corresponded to a non-existant attribute. (Zirro) * Fixed `fileReader.abort()` to terminate ongoing reads properly. * Fixed `xhr.send()` to support array buffer views, not just `ArrayBuffer`s. (ondras) * Fixed non-`GET` requests to `data:` URLs using `XMLHttpRequest`. (Zirro) * Fixed form submission to no longer happen for disconnected forms. * Fixed body event handler attributes to be treated like all others in terms of how they interact with `runScripts`. * Many updates per recent spec changes: (Zirro) * Updated `tokenList.replace()` edge-case behavior. * Invalid qualified names now throw `"InvalidCharacterError"` `DOMException`s, instead of `"NamespaceError"` `DOMException`s. * Changed `input.select()` to no longer throw on types where selection does not apply. * Updated `event.initEvent()` and various related methods to have additional defaults. * Stopped lowercasing headers in `XMLHttpRequest` responses. * Started lowercasing headers in `xhr.getAllResponseHeaders()`, and separating the header values with a comma-space (not just a comma). * Allow a redirect after a CORS preflight when using `XMLHttpRequest`. * Tweaked username/password CORS treatment when using `XMLHttpRequest`. * Changed `xhr.overrideMimeType()` to no longer throw for invalid input. * Removed `blob.close()` and `blob.isClosed()`. * Removed some remaining not-per-spec `toString()` methods on various prototypes, which were made redundant in v10.1.0 but we forgot to remove. ## 10.1.0 * Added the value sanitization algorithm for password, search, tel, text, color, email, and url input types. (Zirro) * Added `Symbol.toStringTag` to all web platform classes, so that now `Object.prototype.toString.call()` works as expected on jsdom objects. * Added the `select.selectedOptions` property. * Removed the `toString()` methods on various prototypes that returned `"[object ClassName]"` in an attempt to fake the `Symbol.toStringTag` behavior. * Changed `XMLHttpRequest` to pre-allocate a 1 MiB buffer, which it grows exponentially as needed, in order to avoid frequent buffer allocation and concatenation. (skygon) * Fixed a variety of properties that were meant to always return the same object, to actually do so. (Zirro) * Fixed inheritance of the `runScripts` and `resources` options into iframes. * Fixed an uncaught exception that occurred if you called `xhr.abort()` during a `readystatechange` event. ## 10.0.0 This release includes a complete overhaul of jsdom's API for creating and manipulating jsdoms. The new API is meant to be much more intuitive and have better defaults, with complete documentation in the newly-overhauled README. We hope you like it! As discussed in the new README, the old API is still available and supported via `require("jsdom/lib/old-api.js")`, at least until we have ported all of its features over to the new API. It will, however, not be gaining any new features, and we suggest you try the new API unless you really need the customizable resource loading the old API provides. Apart from the new API, the following changes were made, with breaking changes bolded: * **Removed support for Node.js v4 and v5**, as we have started using new JavaScript features only supported in Node.js v6 onwards. * **Changed the `omitJsdomErrors` option to `omitJSDOMErrors`**, for consistency [with web platform APIs](https://w3ctag.github.io/design-principles/#casing-rules). * Added `document.dir`. (Zirro) * Updated the `<a>` and `<area>` APIs to the latest specification, and fixed a few bugs with them. (makana) * Fixed `<img>` elements to no longer fire `load` events unless their image data is actually loaded (which generally only occurs when the `canvas` package is installed). * Fixed `XMLHttpRequest` preflights to forward approved preflight headers to the actual request. (mbroadst) * Fixed `htmlElement.dir` to properly restrict its values to `"ltr"`, `"rtl"`, or `"auto"`. (Zirro) * Fixed setting `innerHTML` to the empty string to no longer be a no-op. (Zirro) * Fixed the origin-checking logic in `window.postMessage()`, so that now you don't always have to pass an origin of `"*"`. (jmlopez-rod) * Improved the `xhr.open()` error message when there are not enough arguments. (lencioni) ## 9.12.0 * Added the `Option` named constructor. (NAlexPear) * Added support for the `canvas-prebuilt` npm package as an alternative to `canvas`. (asturur) * Fixed `setTimeout()` and `setInterval()` to always return a positive integer, instead of returning `0` the first time were called. (yefremov) * Fixed `jsdom.env()` to preserve URL fragments across redirects. (josephfrazier) * Fixed `optionEl.text` and `optionEl.value` to be more spec-compliant. * Fixed `event.stopImmediatePropagation()` to actually stop immediate propagation, not just propagation. * Fixed `clearTimeout()` and `clearInterval()` to work correctly when using jsdom browserified. ## 9.11.0 * Added dummy properties `offsetTop`, `offsetLeft`, `offsetWidth`, and `offsetHeight` that always return `0`, and `offsetParent` which always returns `null`, for all HTML elements. (yefremov) * Fixed various edge cases in our type conversions applied to method arguments and setters throughout the web platform APIs implemented by jsdom. ## 9.10.0 * Added `forEach`, `keys`, `values`, and `entries` methods to `NodeList`. * Added `event.cancelBubble`. * Added dummy properties `scrollWidth`, `scrollHeight`, `clientTop`, `clientLeft`, `clientWidth`, and `clientHeight` that always return `0` to all elements. (alistairjcbrown) * Updated many aspects of `Blob`, `File`, and `FileReader` to better match the File API specification. (TimothyGu) * Fixed the progress and readystatechange events fired by `XMLHttpRequest` to match recent specification changes and test updates. * Fixed `element.getClientRects()` to return an empty array, instead of an array containing a dummy bounding box. (alistairjcbrown) * Changed `navigator.vendor` to return `"Apple Computer, Inc."` instead of `"Google Inc."`, since we have chosen the WebKit [navigator compatibility mode](https://html.spec.whatwg.org/multipage/webappapis.html#concept-navigator-compatibility-mode). ## 9.9.1 * Removed the use of `array.includes` to fix a compatibility issue with Node.js v4. ## 9.9.0 * Added `CDATASection` nodes, including `document.createCDATASection`. (snuggs) * Added `node.wholeText`. (jdanyow) * Added a setter for `document.body`. * Added `document.embeds`, `document.plugsin`, and `document.scripts`. These were supposed to be added in 9.5.0 but were mistakenly omitted. * Fixed `element.insertAdjacentHTML` to work when the element has null or the document as its parent node, as long as the insertion position is `"afterbegin"` or `"beforeend"`. * Fixed form submission to only hit the "not implemented" virtual console message when form submission is _not_ canceled, instead of when it is. * Fixed an issue where the event listener was not being correctly removed when using the `{ once: true }` option to `addEventListener`. (i8-pi) * Fixed an error that was thrown when using `XHTMLHttpRequest` and POSTing JSON contents to an endpoint that requires CORS while using an `Authorization` header. (dunnock) * Fixed `document.body` and `document.title` to act more correctly in various edge cases. * Fixed `HTMLCollection` named access to return the first element encountered, not the last. ## 9.8.3 * Fixed syntax errors in Node.js v4. ## 9.8.2 * Fixed `DOMTokenList` and `getElementsByClassName` to only split on ASCII whitespace, not all Unicode whitespace. ## 9.8.1 * Fixed an error that occurred when passing no class names to `getElementsByClassName`, e.g. `getElementsByClassName("")` or `getElementsByClassName(" ")`. ## 9.8.0 * Added the `blob.isClosed` property. (TimothyGu) * Fixed the `file.lastModified` property to be on `File` instead of on `Blob`. (TimothyGu) * Fixed the `file.lastModified` property to default to the time of the `File` object's creation, not the time that the property is accessed. (TimothyGu) * Fixed a minor edge-case regression where non-HTML elements with the name `"iframe"` became focusable in v9.7.0. ## 9.7.1 * Fixed a performance regression introduced in 9.5.0 for modifying the DOM. It was particularly noticable during initial parsing of a document with many elements; for example, one test showed parsing ten thousand elements taking 36.4 seconds, whereas after this fix it is back to a more reasonable 0.4 seconds. ## 9.7.0 * Added `EventListenerOptions` support to `addEventListener` and `removeEventListener`, including both the `once` and `capture` options. (GianlucaGuarini) * Added `document.hasFocus()` (acusti) * Fixed the focus management to ensure that focusing something inside an `iframe` will also focus the `iframe` itself. (acusti) ## 9.6.0 * Added `HTMLCollection.prototype[Symbol.iterator]`, so you can use `for`-`of` loops over `HTMLCollection`s now. (i8-pi) * Fixed `file.lastModified` to return the current time as the default, instead of `0`. * Fixed cloning of `Attr`s to properly clone the namespace prefix. * Tweaked `XMLHttpRequest` progress event ordering slightly to better match the spec and browsers. * Tweaked the behavior of calling `event.stopPropagation` and `event.stopImmediatePropagation` on already-dispatched events, per [the latest changes to the DOM Standard](https://github.com/whatwg/dom/commit/806d4aab584f6fc38c21f8e088b51b8ba3e27e20). ## 9.5.0 * Added `document.scripts`, `document.embeds`, and `document.plugins`. * Fixed `document.getElementsByTagName` and `document.getElementsByTagNameNS` to return `HTMLCollection`s instead of `NodeList`s, and to follow the spec algorithms more exactly. * Fixed various `HTMLCollection`-returning getters such as `document.applets` or `table.cells` to be more spec-compliant. * Fixed the resource loader to respect the `agent` and `agentClass` options, not just the `agentOptions` one. * Fixed `console.groupCollapse` to be `console.groupCollapsed` (and changed the virtual console accordingly). ## 9.4.5 * Fixed `error` events from failed resource loads going missing since v9.4.3. I really should have tested that release better. ## 9.4.4 * Fixed a leftover `console.log` introduced in the error handling path in v9.4.3. ## 9.4.3 * Fixed spurious `"jsdomError"`s occuring when closing a window, due to aborted resource loads. ## 9.4.2 * Fixed what would happen when inline event handlers (such as `element.onclick`) would return non-boolean values (such as `undefined`); it would previously erroneously cancel the event, in many cases. (dmethvin) * Upgraded the minimum tough-cookie version to ensure all installations are protected against [a security advisory](https://nodesecurity.io/advisories/130). ## 9.4.1 * Implemented the cloning steps for `<input>` elements, so that cloned inputs properly copy over their value, checkedness, dirty value flag, and dirty checkedness flag. (matthewp) ## 9.4.0 * Added the `DOMParser` API. It is spec-compliant, including producing `<parsererror>` elements, except that the produced documents do not have the same URL as the creating document (they instead always have `"about:blank"`). * Added strict XML parsing when using `parsingMode: "xml"`. Creating documents will now fail, just like in a browser, when ill-formed XHTML markup is used. * Added some rudimentary application of XML `<!ENTITY` declarations. * Added `window.frameElement`, although without appropriate cross-origin security checks. * Added the `jsdom.evalVMScript` public API. * Added more custom request agent support: you can now pass `agent` and `agentClass` in addition to `agentOptions`. (frarees) * Updated our elements-being-disabled semantics to more closely match the spec, in particular with regard to being descendants of `<fieldset disabled>`. * Updated `FormData` for [recent spec fixes](https://github.com/whatwg/xhr/commit/1a75845e67792418a7721d516266ad01a90f2062): blobs, files, and filenames should now all work like you'd expect. * Updated the `FormData` constructor to use the proper, rather-complex, [constructing the form data set](https://html.spec.whatwg.org/multipage/forms.html#constructing-form-data-set) algorithm. * Fixed all constructors that appears as globals on the jsdom `window` object to be non-enumerable. * Fixed `<script>` elements to load when they gain a `src` attribute while in a document. * Fixed `<link rel="stylesheet">` elements to load when their `href` attributes change while in a document. * Fixed the loading of external `<img>`s (when the `canvas` npm package is installed) that were specified via relative URL; this regressed in 9.2.1. * Fixed `<iframe>` documents to have the correct `referrer` value (viz. the URL of their parent). * Fixed the value of `input.checked` inside `click` events on checkboxes. * Fixed the window object's named properties to correctly return the `<iframe>` element or the `<iframe>`'s window in appropriate scenarios involving `name` vs. `id` attributes on the `<iframe>`. (matthewp) ## 9.3.0 * Added the `Audio` named constructor. * Fixed the `Image` named constructor to follow the spec more closely (e.g. `Image.prototype` is now equal to `HTMLImageElement.prototype`). * Fixed the `tabIndex` setter, which regressed in 9.1.0, to no longer cause errors. * Made submit buttons and labels respond to click event cancelation correctly, preventing form submission and re-dispatching to the relevant form control. (marcandre) * Fixed unhandled errors thrown in XHR event handlers being swallowed; they now properly are redirected to the virtual console. ## 9.2.1 * Fixed `<input>`'s `selectionStart`, `selectionEnd`, and `selectionDirection` getters to return null, instead of throwing, for elements that do not allow selection, per [a recent spec change](https://github.com/whatwg/html/pull/1006). * Fixed `<base>`'s `href` getter logic to return the attribute value instead of the empty string for unparseable URLs, per [a recent spec change](https://github.com/whatwg/html/pull/1064). * Fixed the referrer sent when retrieving external resources to be the document's URL, not the document's base URL. * Fixed suppression of all `error` events on `window` beyond the first one. * Fixed `new URL` to correctly throw for unparseable URLs, and all of `URL`'s setters to correctly ignore invalid input instead of throwing. * Fixed `StyleSheetList.prototype.item` to return `null` instead of `undefined` for out-of-bounds indices. (Ginden) * Updated `cssstyle` minimum version to ensure all jsdom installs (not just fresh ones) get the benefit of `cssstyle`'s recently-better `background` and `width` setters. ## 9.2.0 * Added `jsdom.changeURL(window, newURL)` for allowing you to override a window's existing URL. (mummybot) * Fixed the `proxy` option to be applied to all requests; previously it was not always passed through. (nicolashenry) * Fixed `XMLHttpRequest` response header filtering for cross-origin requests; this also fixes `ProgressEvent`s fired from such XHRs. (nicolashenry) ## 9.1.0 * Added a somewhat-reasonable implementation of focus and focus events. Although the full complexity of focus is not implemented, the following improvements have been made: - Only elements which are focusable can be focused. - Added the `FocusEvent` class, and now `focus` and `blur` events are fired appropriately. - `tabIndex` now returns `0` by default for focusable elements. * Reimplemented `navigator` to be to-spec: - Added `appCodeName`, `product`, `productSub`, `vendor`, and `vendorSub`; also changes `userAgent`, `appName`, `platform`, and `version` to be more browser-like instead of based on various Node.js information. - Added `language` and `languages`. - Added `onLine`. - Added `javaEnabled()`. - Removed `noUI`. * Fixed `formEl.action` to return a value resolved relative to the document URL, or to return the document URL if the corresponding attribute is missing or empty. * Sped up XPath execution. (vsemozhetbyt) * Fixed `window.close()` not correctly clearing event listeners on the document. (Ojek) * Fixed a regression introduced in v9.0.0 where invalid CSS would cause a crash while attempting to parse it. Instead, a `"jsdomError"` will now be emitted to the virtual console. ## 9.0.0 This major release removes jsdom's support for mutation events. Mutation events were never well-specified, and the modern DOM Standard omits them in the hopes that they can be removed from browsers (although this has not yet happened in major browser engines). We had hoped to implement their modern alternative, mutation observers, before performing this removal, to give jsdom users the same capabilities. However, recent performance investigations revealed that mutation events were the major bottleneck in most jsdom operations; tools like [ecmarkup](https://github.com/bterlson/ecmarkup) which make heavy use of jsdom had their running time halved by removing mutation events, which add serious overhead to every DOM mutation. As such, we are doing a major release with them removed, so that jsdom users can benefit from this massive performance gain. Mutation observer support is [in progress](https://github.com/jsdom/jsdom/issues/639); please use the GitHub reactions feature to vote on that issue if you are impacted by this removal and are hoping for mutation observer support to replace it. Your normal change log follows: * **Removed mutation events**, as discussed above. * Added the `DOMTokenList.prototype.replace` method. (nicolashenry) * Updated `DOMTokenList.prototype.contains` to no longer validate its arguments, as per the latest spec. (nicolashenry) * Made various improvements to XMLHttpRequest (nicolashenry): - Added the `responseURL` property. - Updated methods, headers, and header values to use the `ByteString` algorithm. - Fixed the default `statusText` to be `""` instead of `"OK"`. * Fixed the `Blob` constructor's `type` validation. (nicolashenry) ## 8.5.0 * Added encoding handling (nicolashenry) - `jsdom.env`, when given a URL or file, will decode the resulting bytes using signals like the `Content-Type` header, `<meta charset>` declaration, or presence of a BOM, in the same manner as web browsers. - Fetching external resources, via mechanisms such as XMLHttpRequest or `<script>`/`<link>`/`<iframe>` tags, will also account for such signals. - `jsdom.jsdom()`, which takes a string, still sets a "UTF-8" encoding by default, since there are no bytes or headers for it to sniff an encoding from. * Removed `iframe.sandbox` property, since it was not implemented and simply crashed when used. * Removed `element.sourceIndex` property, since it was nonstandard (Internet Explorer only). * Fixed setting proxied inline event handlers, such as `doc.body`'s `onload=""` attribute, for documents that do not have a browsing context. ## 8.4.1 * Fixed an issue where setting `selected` on an multi-select would clear all other selectedness. ## 8.4.0 * Added an implementation of the `TreeWalker` class (and `document.createTreeWalker`). (garycourt) * Fixed a few minor bugs in URL parsing and the `URL` API, by upgrading to `whatwg-url` v2.0.1. * Fixed a few issues with generated files in the published package, which seem to have impacted webpack users. ## 8.3.1 * Fixed an issue where if you modified `Object.prototype`, spurious attributes would show up on your jsdom nodes. (deckar01) ## 8.3.0 * Added image loading and decoding, when the `canvas` npm package is installed (lehni). In practice, this means that if you enable fetching `"img"` external resources, then: * `img.naturalWidth`, `img.naturalHeight`, `img.width`, `img.height`, `img.complete`, and `img.currentSrc` will update themselves correctly as the image loads * `load` and `error` events will fire on the `<img>` element, according to how well image decoding goes. * You can draw images onto canvases, using the newly-enabled `canvasContext.drawImage` API. * Added `canvasContext.createPattern` and `canvasContext.toBlob`, when the `canvas` npm package is installed. (lehni) * Added a basic implementation of the [Page Visibility API](https://w3c.github.io/page-visibility/), in particular a `document.hidden` property that always returns `true`, and a `document.visibilityState` property that always returns `"prerender"`. This is a more standard alternative to our proprietary `navigator.noUI`, which will be removed whenever we release v9.0.0. (kapouer) ## 8.2.0 * Added correct click behavior for inputs (jeffcarp): - `change` and `input` events now fire appropriately - The "click in progress" flag is implemented, so you cannot click while a click is in progress - Canceling a click event appropriately resets radio buttons and checkboxes * Updated our XMLHttpRequest implementation with a variety of fixes and features, including preliminary CORS support. (nicolashenry) * Added a `strictSSL` top-level option to govern all requests jsdom makes. (nicolashenry) * XHTML frames and iframes are now parsed as XML instead of HTML. (nicolashenry) * Added `document.origin` and `document.lastModified`. (nicolashenry) * Fixed the `scriptEl.text` getter and setter to follow the spec. * Fixed script execution to check against the canonical list of JavaScript MIME types and only execute those scripts as JavaScript. ## 8.1.1 * Fixed input selection methods and properties to properly differentiate between inputs that can be selected outright vs. textual inputs which allow variable-length selection. (yaycmyk) ## 8.1.0 * Added `attr.nodeName`, which was [recently re-added to the spec](https://github.com/whatwg/dom/issues/171). * Added click-proxying behavior from `<label>`s to their labeled form elements. (yaycmyk) * Added a setter for `element.classList` per recent spec changes (it forwards to `element.classList.value`). * Updated our attributes implementation in a few ways for recent spec changes and to fix discovered bugs: - Added `element.getAttributeNames()`. ([spec addition](https://github.com/whatwg/dom/issues/115)) - `setAttributeNode` and `setAttributeNodeNS` can now replace an attribute node, instead of removing the old one and adding a new one; this avoids changing the order in the attribute list. ([spec change](https://github.com/whatwg/dom/issues/116)) - `NamedNodeMap` named properties are now lowercase (except in edge cases involving XML documents or non-HTML elements). ([spec change](https://github.com/whatwg/dom/issues/141)) - `NamedNodeMap` named properties are now non-enumerable. - The `"DOMAttrModified"` mutation event's `relatedNode` is now the new `Attr` object, not the `Node`, as per spec. * Updated `DOMTokenList` to have a `value` property per [recent spec changes](https://github.com/whatwg/dom/issues/119); its `toString` serialization also changed slightly. * Updated `tc.headers` to be a `DOMTokenList` that simply reflects the `headers` attribute; previously it was a string, with its computation doing some weird stuff. * Fixed `document.implementation.createDocument()` to create a document with its parsing mode set to XML, which affects a variety of DOM APIs in small ways. * Fixed `EventTarget.prototype.constructor` to be correct; it was previously `Window`. * Fixed `option.index` for `<option>`s not inside a `<select>` to no longer error. * Fixed `tc.cellIndex` for `<td>`s and `<th>`s not inside a `<tr>` to no longer error. * Fixed `tr.sectionRowIndex` for `<tr>`s not inside a `<table>`, `<tbody>`, `<thead>`, or `<tfoot>` to no longer error. * Removed the `"keyevents"` alias for `"keyboardevent"` when using `document.createEvent`, [per recent spec changes](https://github.com/whatwg/dom/issues/148). ## 8.0.4 * Fixed the `this` value when you pass a `{ handleEvent() { ... } }` object to `addEventListener`. (thetalecrafter) ## 8.0.3 * Fixed `HTMLOptionElement.prototype.label`; a typo was causing it to not work at all. (karlhorky) * Updated `cssstyle` minimum version to ensure all jsdom installs (not just fresh ones) get the benefit of `cssstyle`'s recently-better `padding` and `margin` parsing/CSSOM. ## 8.0.2 * Fixed an issue where custom user agents would not propagate to `navigator.userAgent` in frames and iframes. * Improved our `document.activeElement` implementation to be a bit smarter; we still don't have full focus/blur/active element semantics, but at least now it falls back to the `<body>` element when the active element is removed from the document or when no element has been focused yet. ## 8.0.1 * Fixed an issue where the `this` inside event handler callbacks was not equal to the event's current target. (Surprisingly there were no tests for this!) ## 8.0.0 This major release includes a large rewrite of most of the DOM and HTML classes exposed in jsdom. A lot of their behavior is generated from their specs' IDL syntax, taking care of many type conversions, attribute/property reflections, and much more. Many properties that were previously not present are now available, and almost everything behaves in a more spec-compliant way. Additionally, for these classes all of their implementation details are no longer available as underscore-prefixed properties, but instead are hidden behind a single symbol. Although normally jsdom does not mark a new major release for changes that simply update us to the latest specs or hide internal implementation details better, the magnitude of the changes is so extensive that we want to bump the major version in order to ensure that consumers perform adequate testing before upgrading. But, you should definitely upgrade! The new stuff is really awesome! * Reimplemented `Location`, `History`, and `HTMLHyperlinkElementUtils` (used by both `HTMLAnchorElement` and `HTMLAreaElement`) according to the latest specs, and using the latest [whatwg-url](https://github.com/jsdom/whatwg-url) package. This greatly improves our correctness on URL resolution and navigation (to the extent we support navigation, i.e. `pushState` and changing the hash). It should also improve parsing speed as we no longer parse and resolve URLs during parsing. * Added `Element.prototype.insertAdjacentHTML`. (kasperisager) * Added `Node.prototype.adoptNode`, and adopt nodes during insertion instead of throwing `"WrongDocumentError"`s. (dmethvin) * Added a stub `Element.prototype.getClientRects` to match our stub `getBoundingClientRect`. * Fixed `setTimeout` and `setInterval` to return numeric IDs, instead of objects. (alvarorahul) * Fixed `setTimeout` and `setInterval` to accept string arguments to eval, and to pass along extra arguments after the first two. * Fixed certain style shorthand properties not updating their component properties or parsing correctly. (dpvc) * Fixed `Event` object creation to always initialize the event objects, unless using `document.createEvent`, even for events with name `""`. * Fixed iframes to go through the custom resource loader. (chrmarti) * Removed ["DOM Load and Save"](http://www.w3.org/TR/2003/CR-DOM-Level-3-LS-20031107/load-save.html) stub implementation. That spec was never implemented in browsers, and jsdom only contained stubs. * Removed other minor unimplemented, stub, or no-longer-standard APIs from "DOM Level 3", like the user-data API, `DOMError`, `DOMConfiguration`, and `DOMStringList`. ## 7.2.2 * Fixed `canvasEl.toDataURL()`, with the `canvas` npm package installed; a recent update to the `canvas` package broke how we were passing arguments to do. * Fixed `data:` URL parsing to allow empty contents, e.g. `data:text/css;base64,`. (sebmck) ## 7.2.1 * Fixed a regression in XML parsing of attributes with a namespace URL but no prefix (e.g. `<math xmlns="http://www.w3.org/1998/Math/MathML">`). ## 7.2.0 * Added support for text selection APIs on `<input>` and `<textarea>`! (sjelin and yaycmyk) * Replaced our default XML parser with [sax](https://www.npmjs.com/package/sax), thus fixing many (but not all) issues with XML and XHTML parsing. To get a flavor of the issues fixed, check out these now-closed bugs: [#393](https://github.com/jsdom/jsdom/issues/393), [#651](https://github.com/jsdom/jsdom/issues/651), [#415](https://github.com/jsdom/jsdom/issues/415), [#1276](https://github.com/jsdom/jsdom/issues/1276). * Fixed the `<canvas>` tag to reset its contents when its width or height changed, including the change from the default 300 × 150 canvas. (Applies only when using the `canvas` npm package.) * Fixed an issue where `HTMLCollection`s would get confused when they contained elements with numeric `id`s or `name`s. * Fixed an issue with doctype parsing confusing the system ID and public ID. * Made the task posted by `postMessage` use the inside-jsdom timer queue, instead of the Node.js one. This allows easier mocking. (cpojer) ## 7.1.1 * When `<iframe>`s have unresolvable URLs, jsdom will no longer crash, but will instead just load `about:blank` into them. (This is the spec behavior.) * Fixed `document.writeln` to correctly handle multiple arguments; previously it ignored all after the first. * Fixed `FileList` objects to no longer have a property named `"undefined"`. (jfremy) ## 7.1.0 This is a rather large release bringing with it several important re-implementations of DOM and HTML APIs. * Our `EventTarget` implementation has been rewritten from scratch to follow the spec exactly. This should improve any edge case misbehaviors. * Our `Event` class hierarchy has been rewritten and fleshed out, fixing many gaps in functionality. - Previously missing classes `KeyboardEvent` and `TouchEvent` are now implemented. - Almost all supported `Event` subclasses now have constructors. (`TouchEvent` does not yet, and `MutationEvent` is specified to not have one.) - All classes now have correct public APIs, e.g. getters instead of data properties, missing properties added, and constructors that correctly allow setting all the supported properties. - `document.createEvent("customevent", ...)` now correctly creates a `CustomEvent` instead of an `Event`, and `CustomEvent.prototype.initProgressEvent` has been replaced with `CustomEvent.prototype.initCustomEvent`. * The `Attr` class and related attribute-manipulating methods has been rewritten to follow the latest specification. In particular, `Attr` is no longer a subclass of `Node`, and no longer has child text nodes. * The `<template>` element implementation has been greatly improved, now passing most web platform tests. Its `.content` property no longer has an extra intermediate document fragment; it no longer has child nodes; and related parts of the parser and serializer have been fixed, including `innerHTML` and `outerHTML`, to now work as specified. * `querySelector`, `querySelectorAll`, and `matches` now correctly throw `"SyntaxError"` `DOMException`s for invalid selectors, instead of just `Error` instances. * `Node.prototype`'s `insertBefore`, `replaceChild`, and `appendChild` methods now check their arguments more correctly. * The browser builds now have regained the ability to fetch URLs for content and the like; this had been broken due to an issue with the browser-request package, which is no longer necessary anyway. ## 7.0.2 * Fixed an issue where inside jsdom `<script>` code, `/regexpliteral/ instanceof RegExp` would be `false`. ## 7.0.1 * Fixed two bugs with `Node.prototype.isEqualNode`: - It would previously always return `true` for comparing any two doctypes. - It would throw an error when trying to compare two elements that had attributes. * Enforced that `document.implementation.createDocumentType` requires all three of its arguments. ## 7.0.0 This major release has as its headlining feature a completely re-written `XMLHttpRequest` implementation, in a heroic effort by [@nicolashenry](https://github.com/nicolashenry). It includes a number of other smaller improvements and fixes. The breaking changes are highlighted in bold below. * **Node.js 4.0 onward is now required**, as we have begun using ES2015 features only present there. * Completely re-implemented `XMLHttpRequest` and related classes (nicolashenry): - Includes support for `Blob`, `File`, `FileList`, `FileReader`, `FormData`, `ProgressEvent`, and the supporting `XMLHttpRequestUpload`, and `XMLHttpRequestEventTarget` interfaces. - Includes support for synchronous XHRs. - Adds some new request-management abilities, documented in the readme. In short, the `pool`, `agentOptions`, and `userAgent` options are new, and resource loads can now be aborted. - These implementations are extremely complete and standards-compliant, passing 136 newly-introduced web platform tests. * Added `document.charset`, an alias for `document.characterSet`. * Added `HTMLTemplateElement.prototype.content`, for getting the contents of a `<template>` element as a document fragment. (rickychien) * Implemented "loose" cookie parsing, giving correct execution of code like `document.cookie = "foo"`. * Several fixes related to event dispatching and creation, including the addition of `Event.prototype.stopImmediatePropagation` and the constants `NONE`, `CAPTURING_PHASE`, `AT_TARGET`, and `BUBBLING_PHASE`. This accounted for another 15 newly-passing web platform tests. (nicolashenry) * Fixed `document.styleSheets` to correctly track the removal of stylesheets from the document. (AVGP) * Fixed the `created` jsdom lifecycle callback receiving a different `window` object than the `loaded` or `done` callbacks when scripting was enabled. * **Invalid URLs are no longer allowed when creating a jsdom document**; the URL must be parseable, or an error will be thrown. * **The `{ omitJsdomErrors }` option of the virtual console has moved**; it is no longer provided when creating the virtual console, but instead when calling `sendTo`. ## 6.5.1 * Fixed an issue where with `jsdom.jsdom`, you had to pass `referrer` and `cookie` options as top-level, whereas with `jsdom.env`, you had to nest them under a `document` option. This was unnecessarily confusing. Now both possibilities are allowed for both functions. (The readme only documents the top-level version, though.) ## 6.5.0 * Added `NodeList.prototype[Symbol.iterator]`, so you can now use `for`-`of` loops with `NodeList`s. ## 6.4.0 * Added `jsdom.nodeLocation(node)` to get the location within the source text of a given node. * Added `jsdom.reconfigureWindow(window, { top })` to allow changing the value of a window's `top` property. * Added the `element` argument to the custom resource loader, so you can customize resource loads depending on which element loaded them. * Updated `getElementsByClassName` to match the spec. It now correctly splits on whitespace to try to find elements with all the given classes; it returns a `HTMLCollection` instead of a `NodeList`; and it memoizes the result. * Updated `NodeList` and `HTMLCollection` to match the spec. The most noticable change is that `HTMLCollection` no longer inherits from `NodeList`. ## 6.3.0 * Added a fully spec-compliant implementation of `window.atob` and `window.btoa`. (jeffcarp) * Fixed many issues with our `<canvas>` implementation: - With the `canvas` npm package installed, `<canvas>` elements are now properly `instanceof HTMLCanvasElement` and `instanceof HTMLElement`. - `<canvas>` elements now present the same uniform spec-compliant API both with and without the `canvas` npm package installed. If the package is not installed, some of the methods will cause not-implemented `jsdomError` events to be emitted on the virtual console. - The `width` and `height` properties now correctly reflect the `width` and `height` attributes, and have the appropriate default values of `300` and `150`. - With the `canvas` npm package installed, `<canvas>` elements now generally play better with other parts of jsdom, e.g., `document.getElementById` actually works with them. * Introduced and upated many of our element classes, so that at least every tag name/element class pair is now correct, even if some of the classes are stubs. In particular: - Complete implementations were added for `HTMLDataElement`, `HTMLSpanElement`, and `HTMLTimeElement`. - Stubs were added for `HTMLDataListElement`, `HTMLDialogElement`, `HTMLEmbedElement`, `HTMLMeterElement`, `HTMLOutputElement`, `HTMLProgressElement`, `HTMLSourceElement`, `HTMLTemplateElement`, and `HTMLTrackElement`. - `HTMLAudioElement` was implemented in full, although its `HTMLMediaElement` base, where most of its functionality is, is still largely a stub. - `HTMLTableSectionElement`, `HTMLTableRowElement`, `HTMLTableCellElement`, `HTMLTableDataCellElement`, and `HTMLTableHeaderCellElement` were updated to the latest spec. - `HTMLIsIndexElement` was removed; it has never been produced by the parser since 1.0.0-pre.1, and so it has been just a vestigial global property. - Appropriate constants were added to `HTMLMediaElement`. * Updated everything having to do with base URLs to be per-spec: - Added `Node.prototype.baseURI` property to get the node's owner document's base URL. - `HTMLBaseElement`'s `href` getter now contains appropriate fallbacks and always returns an absolute URL, per spec. - If there are no `base` elements in an `"about:blank"` iframe document, the base URL correctly falls back to the parent window's base URL. * When you provide a `url: ...` option to `jsdom.jsdom()` or `jsdom.env()`, the given string is now attempted to be resolved as a URL before it is installed as `document.URL`. - So for example, providing `url: "http://example.com"` will mean `document.URL` returns `"http://example.com/"`, with a trailing slash. - In a future major release, we will start throwing if strings that cannot be parsed as valid absolute URL are provided for this option. ## 6.2.0 * Added a full-featured, spec-compliant `Element.prototype.classList`, closing out a three-year old issue! (wacii) * Made `virtualConsole.sendTo(console)` forward `"jsdomError"`s to `console` by calling `console.error`. This can be turned off by doing `virtualConsole.sendTo(console, { omitJsdomErrors: true })`. * Fixed errors when trying to parse invalid doctype declarations, like `<!DOCTYPE>`. * Fixed spurious `"jsdomError"`s that were emitted after calling `window.close()`. * Fixed the `DOMSubtreeModified` event to fire in more cases. Note that our mutation events implementation remains incomplete, and will eventually be removed (in a major release) once we implement mutation observers. (selam) ## 6.1.0 * Added basic implementations of `HTMLMediaElement` and `HTMLVideoElement`, back-ported from Facebook's Jest project. (cpojer) ## 6.0.1 * Fixed `XMLHttpRequest.prototype.getAllResponseHeaders` to not crash when used with `file:` URLs. (justinmchase) * Fixed `XMLHttpRequest.prototype.response` to correctly return the response text even when `responseType` was unset. (justinmchase) ## 6.0.0 This major release is focused on massive improvements in speed, URL parsing, and error handling. The potential breaking changes are highlighted in bold below; the largest ones are around the `jsdom.env` error-handling paradigm. This release also welcomes [long-time contributer](https://github.com/jsdom/jsdom/commits/master?author=Joris-van-der-Wel) [@Joris-van-der-Wel](https://github.com/Joris-van-der-Wel/) to the core team. You may recognize him from earlier changelogs. We're very happy to have his help in making jsdom awesome! * **io.js 2.0 onward is now required**, as we have begun using ES2015 features only present there. * Improved performance dramatically, by ~10000x in some cases, due to the following changes: - Overhauled the named properties tracker to not walk the entire tree, thus greatly speeding up the setting of `id` and `name` attributes (including during parsing). - Overhauled everything dealing with tree traversal to use a new library, [symbol-tree](https://github.com/jsdom/js-symbol-tree), to turn many operations that were previously O(n^2) or O(n) into O(n) or O(1). - Sped up `node.compareDocumentPosition` and anything that used it (like `node.contains`) by doing more intelligent tree traversal instead of directly implementing the specced algorithm. * Overhauled how error handling works in jsdom: - `window.onerror` (or `window.addEventListener("error", ...)`) now work, and will catch all script errors, similar to in browsers. This also introduces the `ErrorEvent` class, incidentally. - The virtual console is now the destination for several types of errors from jsdom, using [the new event `"jsdomError"`](https://github.com/jsdom/jsdom#virtual-console-jsdomerror-error-reporting). This includes: errors loading external resources; script execution errors unhandled by `window.onerror`; and not-implemented warnings resulting from calling methods like `window.alert` which jsdom explicitly does not support. - Since script errors are now handled by `window.onerror` and the virtual console, they are no longer included in the initialization process. This results in two changes to `jsdom.env` and the initialization lifecycle: + **The `load(errors, window)` callback was changed to `onload(window)`**, to reflect that it is now just sugar for setting a `window.onload` handler. + **The `done(errors, window)` callback (i.e., the default callback for `jsdom.env`) has become `done(error, window)`**, and like every other io.js callback now simply gives you a single error object, instead of an array of them. - Nodes no longer have a nonstandard `errors` array, or a `raise` method used to put things in that array. * URL parsing and resolution was entirely overhauled to follow [the URL standard](http://url.spec.whatwg.org/)! - This fixes several long-standing bugs and hacks in the jsdom URL parser, which already had a mess of gross patches on top of the built-in io.js parser to be more web-compatible. - The new [`URL` class](https://url.spec.whatwg.org/#url) has been added to `window` - The interfaces for `HTMLAnchorElement.prototype` and `document.location` (as well as `URL`, of course) are now uniformized to follow the [`URLUtils` API](https://url.spec.whatwg.org/#api) (minus `searchParams` for now). - **As part of this change, you may need to start passing in `file:` URLs to `jsdom.env` where previously you were able to get away with passing in filenames.** * Added the `XMLHttpRequest.prototype.response` getter. * Fixed `StyleSheetList.prototype.item` to actually work. (chad3814) * Fixed the browser `vm` shim to properly add the built-in global properties (`Object`, `Array`, etc.) to the sandbox. If you were running jsdom inside a web worker and most of your scripts were broken, this should fix that. * Fixed the `hashchange` event to correctly fire `HashChangeEvent` instances, with correct properties `newURL` and `oldURL` (instead of the incorrect `newUrl` and `oldUrl` used previously). * Removed usage of the setimmediate library, as it required `eval` and thus did not work in CSP scenarios. Finally, if you're a loyal jsdom fan whose made it this far into the changelog, I'd urge you to come join us in [#1139](https://github.com/jsdom/jsdom/issues/1139), where we are brainstorming a modernized jsdom API that could get rid of many of the warts in the current one. ## 5.6.1 * Fixed an accidentally-created global `attribute` variable if you ever called `createAttributeNS`. * Dependency upgrades fixed a couple of bugs, although you would have gotten these anyway with a clean jsdom v5.6.0 install: - Parsing of CSS properties that use `url("quoted string")` now works correctly, as of `cssstyle` v0.2.29. - Selectors for the empty string, like `div[title=""]`, now work correctly, as of `nwmatcher` v1.3.6. ## 5.6.0 * `virtualConsole.sendTo` now returns `this`, allowing for [a nice shorthand](https://github.com/jsdom/jsdom/tree/60ccb9b318d0bae8fe37e19af5af444b9c98ddac#forward-a-windows-console-output-to-the-iojs-console). (jeffcarp) ## 5.5.0 * Added `postMessage` support, for communicating between parent windows, iframes, and combinations thereof. It's missing a few semantics, especially around origins, as well as MessageEvent source. Objects are not yet structured cloned, but instead passed by reference. But it's working, and awesome! (jeffcarp) * Rewrote cloning code (underlying `cloneNode` and `importNode`), fixing a number of issues: - Elements with weird tag names, of the type that only the parser can normally create, can now be cloned ([#1142](https://github.com/jsdom/jsdom/issues/1142)) - Doctypes can now be cloned, per the latest spec. - Attrs cannot be cloned, per the latest spec (although they still have a `cloneNode` method for now due to legacy). - Document clones now correctly copy over the URL and content-type. * Fixed any virtual console output from iframes to be proxied to the parent window's virtual console. (jeffcarp) * Fixed the `type` property of `<button>` elements to correctly default to `submit`, and to stay within the allowed range. * Fixed clicking on submit `<button>`s to submit their containing form; previously only `<input type="submit">` worked. (rxgx) * Fixed `document.open()` to return `this`, per spec. (ryanseddon) Additionally, Joris-van-der-Wel added [a benchmarking framework](https://github.com/jsdom/jsdom/blob/master/Contributing.md#running-the-benchmarks), and a number of benchmarks, which should help us avoid performance regressions going forward, and also make targeted performance fixes. We're already investigating [some real-world issues](https://github.com/jsdom/jsdom/issues/1156) using this framework. Very exciting! ## 5.4.3 * Incorporated upstream fix for setting `el.style.cssText` to an invalid value, which should be ignored instead of causing an error to be thrown. This same bug has also caused an error while setting the style attribute to an invalid value, ever since 5.4.0. (Joris-van-der-Wel; chad3814 upstream) ## 5.4.2 * Fixed license metadata to conform to latest npm standards. ## 5.4.1 * Fixed to work with browserify again (regression introduced in v5.4.0). ## 5.4.0 This is a pretty exciting release! It includes a couple features I never really anticipated jsdom being awesome enough to have, but our wonderful contributors powered through and made them happen anyway: * Added support for the default HTML stylesheet when using `window.getComputedStyle`! (akhaku) - Notably, this makes jQuery's `show()` and `hide()` methods now work correctly; see [#994](https://github.com/jsdom/jsdom/issues/994). * Added support for named properties on `window`: any elements with an `id` attribute, or certain elements with a `name` attribute, will cause properties to show up on the `window`, and thus as global variables within the jsdom. (Joris-van-der-Wel) - Although this is fairly unfortunate browser behavior, it's standardized and supported everywhere, so the fact that jsdom now supports this too means we can run a lot of scripts that would previously fail. - Previously, we only supported this for `<iframe>`s, and our implementation was quite buggy: e.g., `<iframe name="addEventListener">` would override `window.addEventListener`. - Now that we have the infrastructure in place, we anticipate expanding our support so that this works on e.g. `HTMLFormElement`s as well in the future. We also have a bunch more fixes and additions: * Implemented the [`NonDocumentTypeChildNode`](https://dom.spec.whatwg.org/#nondocumenttypechildnode) mixin. Practically, this means adding `nextElementSibling` and `previousElementSibling` to `Element` and the various types of `CharacterData`. (brandon-bethke-neudesic) * Updated `StyleSheetList` to inherit from `Array`, as per the latest CSSOM spec. * Overhauled the handling of attributes throughout the DOM, to follow the spec more exactly. - Our `NamedNodeMap` implementation is up to date, as are the various `Element` methods; other places in the code that deal with attributes now all go through a spec-compliant set of helpers. - Some weirdnesses around the `style` attribute were fixed along the way; see e.g. [#1109](https://github.com/jsdom/jsdom/issues/1109). - However, `Attr` objects themselves are not yet spec-compliant (e.g., they still inherit from `Node`). That's coming soon. * Fixed an unfortunate bug where `getElementById` would fail to work correctly on `<img>` elements whose `id` attributes were modified. (Joris-van-der-Wel) * Fixed the `virtualConsole` option to work with `jsdom.env`, not just `jsdom.jsdom`. (jeffcarp) * Removed a few functions that were erroneously added to `window`: `mapper`, `mapDOMNodes`, and `visitTree`. (Joris-van-der-Wel) ## 5.3.0 * Added a `virtualConsole` option to the document creation methods, along with the `jsdom.createVirtualConsole` factory. (See [examples in the readme](https://github.com/jsdom/jsdom/blob/dbf88666d1152576237ed1c741263f5516bb4005/README.md#capturing-console-output).) With this option you can install a virtual console before the document is even created, thus allowing you to catch any virtual console events that occur during initialization. (jeffcarp) ## 5.2.0 * Implemented much of the [`ParentNode`](https://dom.spec.whatwg.org/#interface-parentnode) mixin (Joris-van-der-Wel): - Moved `children` from `Node` to `ParentNode`, i.e., made it available on `Document`, `DocumentFragment`, and `Element`, but not other types of nodes. - Made `children` a `HTMLCollection` instead of a `NodeList`. - Implemented `firstElementChild`, `lastElementChild`, and `childElementCount`. * Implemented the `outerHTML` setter. (Joris-van-der-Wel) * Fixed the `outerHTML` getter for `<select>` and `<form>`. (Joris-van-der-Wel) * Fixed various issues with window-less documents, so that they no longer give incorrect results or blow up in strange ways. You can create such documents with e.g. `document.implementation.createHTMLDocument()`. (Joris-van-der-Wel) * Fixed relative stylesheet resolution when using `@import`. (dbo) ## 5.1.0 * Added support for the `NodeIterator` class from the DOM Standard. (Joris-van-der-Wel) * Fixed an issue with the initial request where it was not sharing its cookie jar with the subsequent requests, sometimes leading to a "possible EventEmitter memory leak detected" warning. (inikulin) * Updated tough-cookie to 0.13.0, bringing along many spec compliance fixes. (inikulin) * Added a fast failure in Node.js™ with a clear error message, so that people don't get confused by syntax errors. ## 5.0.1 * Fixed `document.cookie` setter to no longer ignore `null`; instead it correctly sets a cookie of `"null"`. (Chrome is not compliant to the spec in this regard.) * Fixed documents created with `parsingMode: "xml"` to no longer get `"<html><head></head><body></body></html>"` automatically inserted when calling `jsdom.jsdom()` with no arguments. * Fixed the `innerHTML` setter to no longer ignore `undefined`; instead it correctly sets the innerHTML to `"undefined"`. * Fixed `document.write` to throw for XML documents as per the spec. * Fixed `document.write` to accept more than one argument (they get concatenated). * Fixed `document.write("")` to no longer try to write `"<html><head></head><body></body></html>"`. ## 5.0.0 This release overhauls how cookies are handled in jsdom to be less fiddly and more like-a-browser. The work for this was done by [@inikulin](https://github.com/inikulin), who is also our beloved parse5 maintainer. You should only need to worry about upgrading to this release if you use jsdom's cookie handling capabilities beyond the basics of reading and writing to `document.cookie`. If that describes you, here's what changed: * Removed `options.jar` and `options.document.cookieDomain` from the configuration for creating jsdom documents. * Instead, there is now a new option, `options.cookieJar`, which accepts cookie jars created by the new `jsdom.createCookieJar()` API. You should use this if you intend to share cookie jars among multiple jsdom documents. * Within a given cookie jar, cookie access is now automatically handled on a domain basis, as the browser does, with the domain calculated from the document's URL (supplied as `options.url` when creating a document). This supplants the former `options.document.cookieDomain`. In addition to these changes to the public API, the following new cookie-related features came along for the ride: * Implemented automatic cookie-jar sharing with descendant `<iframe>`s. (So, if the iframe is same-domain, it can automatically access the appropriate cookies.) * Let `options.document.cookie` accept arrays, instead of just strings, for if you want to set multiple cookies at once. Finally, it's worth noting that we now delegate our cookie handling in general to the [tough-cookie](https://www.npmjs.com/package/tough-cookie) package, which should hopefully mean that it now captures many of the behaviors that were previously missing (for example [#1027](https://github.com/jsdom/jsdom/issues/1027)). @inikulin is working on [a large pull request to fix tough-cookie to be more spec compliant](https://github.com/goinstant/tough-cookie/pull/30), which should automatically be picked up by jsdom installs once it is merged. ## 4.5.1 * Removed unnecessary browserify dependency that was erroneously included in 4.5.0. ## 4.5.0 * Added `document.currentScript`. (jeffcarp) ## 4.4.0 * All resources are now loaded with the [request](https://www.npmjs.com/package/request) package, which means that e.g. GZIPped resources will be properly uncompressed, redirects will be followed, and more. This was previously the case only for URLs passed directly to `jsdom.env`, and not for sub-resources inside the resulting page. (ssesha) ## 4.3.0 * Made the click behavior for radio buttons and checkboxes work when doing `el.dispatchEvent(clickEvent)`, not just when doing `el.click()`. (brandon-bethke-neudesic) * Added `defaultPrevented` property to `Event` instances, reflecting whether `ev.preventDefault()` has been called. (brandon-bethke-neudesic) * Moved the `click()` method from `HTMLInputElement.prototype` to `HTMLElement.prototype`, per the latest spec. * Made the `click()` method trigger a `MouseEvent` instead of just an `Event`. ## 4.2.0 * Added a second parameter to `UIEvent`, `MouseEvent`, and `MutationEvent`, which for now just behaves the same as that for `Event`. (Rich-Harris) ## 4.1.0 * Added a second parameter to the `Event` constructor, which allows you to set the `bubbles` and `cancelable` properties. (brandon-bethke-neudesic) ## 4.0.5 * Added `HTMLUnknownElement` and fix the parser/`document.createElement` to create those instead of `HTMLElement` for unknown elements. * Fixed issues with named and indexed properties on `window`, as well as `window.length`, with regard to `<frame>`s/`<iframe>`s being added and removed from the document. _Note:_ this probably should have been a minor version number increment (i.e. 4.1.0 instead of 4.0.5), since it added `HTMLUnknownElement`. We apologize for the deviation from semver. ## 4.0.4 * Fixed parsing of doctypes by relying on the information provided by the html parser if possible. ## 4.0.3 * Fixed events fired from `EventTarget`s to execute their handlers in FIFO order, as per the spec. * Fixed a case where `childNodes` would not be correctly up to date in some cases. (medikoo) * Sped up window creation with `jsdom.env` by ~600%, for the special case when no scripts are to be executed. ## 4.0.2 * `EventTarget` is now correctly in the prototype chain of `Window`. * `EventTarget` argument validation is now correct according to the DOM Standard. * `DOMException` now behaves more like it should per Web IDL. In particular it has a more comprehensive set of constants, and instances now have `name` properties. * `new Event("click")` can now be dispatched. (lovebear) * `document.createEvent` now behaves more like it should according to the DOM Standard: it accepts a wider range of arguments, but will throw if an invalid one is given. (lovebear) * Fixed a regression in our browser support that required Chrome 41 as of 4.0.1; now Chrome 40 will work, as well as (in theory, although less well-tested) the latest stable versions of Firefox and IE. ## 4.0.1 * Fixed: `Node.prototype.contains` to always return a boolean. This was a regression in 3.1.1. (Joris-van-der-Wel) * Fixed: `Document.prototype` no longer contains its own `ownerDocument` getter, instead correctly delegating to `Node.prototype`. * Fixed: some edge cases regarding running `<script>`s in browserified jsdom. * A couple fixes from updated dependencies (although you would have gotten these anyway with a fresh install, due to floating version specifiers): - csstyle minimum version bumped from 0.2.21 to 0.2.23, fixing handling of `0` when setting numeric CSS properties and parsing of shorthand `font` declarations. - parse5 minimum version bumped from 1.3.1 to 1.3.2 to, fixing the parsing of `<form>` elements inside `<template>` elements. ## 4.0.0 This release relies on the newly-overhauled `vm` module of io.js to eliminate the Contextify native module dependency. jsdom should now be much easier to use and install, without requiring a C++ compiler toolchain! Note that as of this release, jsdom no longer works with Node.js™, and instead requires io.js. You are still welcome to install a release in [the 3.x series](https://github.com/jsdom/jsdom/tree/3.x) if you are stuck on legacy technology like Node.js™. In the process of rewriting parts of jsdom to use `vm`, a number of related fixes were made regarding the `Window` object: * In some cases, state was implicitly shared between `Window` instances—especially parser- and serializer-related state. This is no longer the case, thankfully. * A number of properties of `Window` were updated for spec compliance: some data properties became accessors, and all methods moved from the prototype to the instance. * The non-standard `document.parentWindow` was removed, in favor of the standard `document.defaultView`. Our apologies for encouraging use of `parentWindow` in our README, tests, and examples. ## 3.1.2 * Some fixes to the `NOT_IMPLEMENTED` internal helper, which should eliminate the cases where calling e.g. `window.alert` crashes your application. * Fixed a global variable leak when triggering `NOT_IMPLEMENTED` methods, like `window.location.reload`. * Fixed the URL resolution algorithm to handle `about:blank` properly on all systems (previously it only worked on Windows). This is especially important since as of 3.0.0 the default URL is `about:blank`. * Fixed, at least partially, the ability to run `<script>`s inside a browserified jsdom instance. This is done by dynamically rewriting the source code so that global variable references become explicit references to `window.variableName`, so it is not foolproof. ## 3.1.1 * Updated `Node.prototype.isEqualNode` to the algorithm of the DOM Standard, fixing a bug where it would throw an error along the way. * Removed `Node.prototype.isSameNode`, which is not present in the DOM Standard (and was just a verbose `===` check anyway). * Fixed a couple small issues while browserifying, mainly around `jsdom.env`. However, while doing so discovered that `<script>`s in general don't work too well in a browserified jsdom; see [#1023](https://github.com/jsdom/jsdom/issues/1023). ## 3.1.0 * Added support for [custom external resource loading](https://github.com/jsdom/jsdom#custom-external-resource-loader). (tobie) ## 3.0.3 * Fixed some stray byte-order marks in a couple files, which incidentally [break Browserify](https://github.com/substack/node-browserify/issues/1095). (sterpe) ## 3.0.2 * Fixed another edge case where unchecking a radio button would incorrectly uncheck radio buttons outside the containing form. (zpao) ## 3.0.1 * Fixed errors when serializing text nodes (possibly only occurred when inside `<template>`). * Handle null bytes being passed to `jsdom.env`'s autodetecting capabilities. (fluffybunnies) * Handle empty HTML strings being passed to `jsdom.env`'s `html` option. (fluffybunnies) ## 3.0.0 This release updates large swathes of the DOM APIs to conform to the standard, mostly by removing old stuff. It also fixes a few bugs, introduces a couple new features, and changes some defaults. 3.0.x will be the last release of jsdom to support Node.js. All future releases (starting with 4.0.0) will require [io.js](https://iojs.org/), whose [new `vm` module](https://github.com/iojs/io.js/blob/v1.x/CHANGELOG.md#vm) will allow us to remove our contextify native-module dependency. (Given that I submitted the relevant patch to joyent/node [1.5 years ago](https://github.com/joyent/node/commit/7afdba6e0bc3b69c2bf5fdbd59f938ac8f7a64c5), I'm very excited that we can finally use it!) * By default documents now use `about:blank` as their URL, instead of trying to infer some type of file URL from the call site (in Node.js) or using `location.href` (in browsers). * Introduced a new "virtual console" abstraction for capturing console output from inside the page. [See the readme for more information.](https://github.com/jsdom/jsdom#capturing-console-output) Note that `console.error` will no longer contribute to the (non-standard, and likely dying in the future) `window.errors` array. (jeffcarp) * Added the named `new Image(width, height)` constructor. (vinothkr) * Fixed an exception when using `querySelector` with selectors like `div:last-child > span[title]`. * Removed all traces of entities, entity types, notations, default attributes, and CDATA sections. * Differentiated between XML and HTML documents better, for example in how they handle the casing of tag names and attributes. * Updated `DOMImplementation` to mostly work per-spec, including removing `addFeature` and `removeFeature` methods, the `ownerDocument` property, and making `hasFeature` always return `true`. * Re-did the `CharacterData` implementation to follow the algorithms in the DOM Standard; this notably removes a few exceptions that were previously thrown. * Re-did `Comment`, `Text`, and `ProcessingInstruction` to follow the DOM Standard and derive from `CharacterData`. * Re-did `DocumentType` to follow the DOM Standard and be much simpler, notably removing notations, entities, and default attributes. * Fixed a variety of accessors on `Node`, `Element`, `Attr`, and `Document`; some were removed that were nonstandard (especially setters); others were updated to reflect the spec; etc. * Re-did name/qname validation, which is done by various APIs, to work with the xml-name-validator package and some centralized algorithms. * Made the XML parser at least somewhat aware of processing instructions. * Cleaned up doctype parsing and association between doctypes and documents. More exotic doctypes should parse better now. * `document.contentType` now is generally inferred from the parsing mode of the document. * Moved some properties to `Document.prototype` and `Window.prototype` instead of setting them as own properties during the document/window creation. This should improve memory usage (as well as spec compliance). ## 2.0.0 This release is largely a refactoring release to remove the defunct concept of "levels" from jsdom, in favor of the [living standard model](https://wiki.whatwg.org/wiki/FAQ#What_does_.22Living_Standard.22_mean.3F) that browsers follow. Although the code is still organized that way, that's now [noted as a historical artifact](https://github.com/jsdom/jsdom/blob/2ff5747488ad4b518fcef97a026c82eab42a0a14/lib/README.md). The public API changes while doing so were fairly minimal, but this sets the stage for a cleaner jsdom code structure going forward. * Removed: `jsdom.level`, and the `level` option from `jsdom.jsdom`. * Change: the nonstandard `Element.prototype.matchesSelector` method was replaced with the standard `Element.prototype.matches`. (KenPowers) * Fix: `querySelector` correctly coerces its argument to a string (1.2.2 previously fixed this for `querySelectorAll`). ## 1.5.0 * Add: missing `window.console` methods, viz. `assert`, `clear`, `count`, `debug`, `group`, `groupCollapse`, `groupEnd`, `table`, `time`, `timeEnd`, and `trace`. All except `assert` do nothing for now, but see [#979](https://github.com/jsdom/jsdom/issues/979) for future plans. (jeffcarp) * Tweak: make `childNodes`, and the many places in jsdom that use it, much faster. (Joris-van-der-Wel) ## 1.4.1 * Tweak: faster implementation of `NodeList.prototype.length`, which should speed up common operations like `appendChild` and similar. (Joris-van-der-Wel) ## 1.4.0 * Fix: `HTMLInputElement.prototype.checked` and `defaultChecked` now behave per the spec. (Joris-van-der-Wel) * Fix: `HTMLOptionElement.prototype.selected` now behaves per the spec. (Joris-van-der-Wel) * Fix: `HTMLInputElement.prototype.value` now behaves per the spec. (Joris-van-der-Wel) * Fix: `HTMLTextAreaElement.prototype.value` and `defaultValue` now behave per the spec. (Joris-van-der-Wel) * Add: `HTMLTextAreaElement.prototype.defaultValue` now has a setter, and `HTMLTextAreaElement.prototype.textLength` now exists. (Joris-van-der-Wel) * Fix: resetting a `<form>` now behaves per spec for all different types of form elements. (Joris-van-der-Wel) * Fix: radio buttons reset other radio buttons correctly now per the spec. (Joris-van-der-Wel) * Fix: `document.cloneNode` now works. (AVGP) * Fix: `hasAttribute` is now case-insensitive, as it should be. (AVGP) * Fix: `div.toString()` now returns `[object HTMLDivElement]`. (AVGP) ## 1.3.2 * Fix: check if `module.parent` exists before using it to construct a document's initial URL. Apparently some testing frameworks like Jest do not correctly emulate the module environment; this compensates. (SegFaultx64) ## 1.3.1 * Fix: changing attributes on `<option>` elements will now have the correct consequences. For example changing the `id` attribute now interacts correctly with `document.getElementById`. (Joris-van-der-Wel) ## 1.3.0 * Add: moved `focus` and `blur` methods to `HTMLElement.prototype`, instead of having them only be present on certain element prototypes. Our focus story is still not very spec-compliant, but this is a step in the right direction. (vincentsiao) ## 1.2.3 * Tweak: improve performance of `Node.prototype.insertBefore`, `Node.prototype.removeChild`, and several `AttributeList` methods. (Joris-van-der-Wel) ## 1.2.2 * Fix: `querySelectorAll` correctly coerces its argument to a string; notably this allows you to pass arrays. (jeffcarp) * Fix: the `data` setter on text nodes correctly coerces the new value to a string. (medikoo) * Fix: `document.toString()` now returns `[object HTMLDocument]`. (jeffcarp) ## 1.2.1 * Fix: handling of `<template>` element parsing and serialization, now that it is supported by parse5. (inikulin) ## 1.2.0 * Add: `NodeFilter`, in particular its constants. (fhemberger) * Fix: initial `history.length` should be `1`, not `0`. (rgrove) * Fix: `history.pushState` and `history.replaceState` should not fire the `popstate` event. (rgrove) ## 1.1.0 * Add: `document.implementation.createHTMLDocument()`. (fhemberger) * Fix: `localName` was sometimes `null` for elements when it should not be. (fhemberger) ## 1.0.3 * Update: no longer requiring separate `cssstyle` and `cssstyle-browserify` dependencies; now `cssstyle` can be used directly. This also un-pins the `cssstyle` dependency so that future fixes arrive as they appear upstream. ## 1.0.2 * Fix: temporarily pin `cssstyle` dependency to at most 0.2.18 until [chad3814/CSSStyleDeclaration#20](https://github.com/chad3814/CSSStyleDeclaration/issues/20) is fixed. * Fix: browserifying jsdom should work better now that the required packages are included as `dependencies` instead of `devDependencies`. (Sebmaster) * Fix: using `jsdom.env` in a browser environment now correctly defaults `options.url` to `location.href` instead of trying to infer a reasonable `fil://` URL using techniques that fail in the browser. (rattrayalex) ## 1.0.1 * Fix: the return value of `EventTarget.prototype.dispatchEvent` should be `true` when the default is *not* prevented; previously it was the opposite. (eventualbuddha) ## 1.0.0 For a consolidated list of changes from 0.11.1 to 1.0.0, see [this wiki page](https://github.com/jsdom/jsdom/wiki/Changes-from-0.11.1-to-1.0.0). * Remove: nonstandard `EventTarget.getListeners`; `EventTarget.forwardIterator`; `EventTarget.backwardIterator`; `EventTarget.singleIterator`. * Remove: nonstandard `document.innerHTML`. (jorendorff) * Fix: `value` and `defaultValue` properties of a `HTMLInputElement` are now correctly synced to the `value=""` attribute. (Sebmaster) ## 1.0.0-pre.7 * Remove: support for old, untested HTML and XML parsers, namely davglass/node-htmlparser and isaacs/sax-js. In the future we plan to work toward a standardized parsing interface that other parsers can implement, instead of adding custom code to jsdom for various parsers. This interface still is being decided though, as it needs to support complex things like pausing the parse stream (for `document.write`) and parsing disconnected fragments (for `document.innerHTML`). (Sebmaster) * Add: new `parsingMode` configuration, to allow you to manually specify XML or HTML. (Sebmaster) * Change: jsdom will no longer use the presence of `<?xml` or similar to attempt to auto-detect XHTML documents. Instead, it will by default treat them the same as browsers do, with the `<?xml` declaration just being a bogus comment. If you need your document interpreted as XHTML instead of HTML, use the `parsingMode` option. (Sebmaster) * Tweak: memoize various DOM-querying functions (e.g. `getElementsByTagName`, `querySelector`, etc.) to improve performance. (ccarpita) ## 1.0.0-pre.6 * Fix: another parsing issues with void elements and `innerHTML`, this time related to disconnected nodes. This was a regression between 0.11.1 and 1.0.0-pre.1. (paton) * Fix: same-named radio inputs should not be mutually exclusive unless they are in the same form. (stof) ## 1.0.0-pre.5 * Fix: sometimes calling `window.close()` would cause a segfault. (paton) ## 1.0.0-pre.4 * Fix: attributes and elements now have their `prefix`, `localName`, and `namespaceURI` properties set correctly in all cases. (Excepting `application/xhtml+xml` mode, which jsdom does not support yet.) (Sebmaster) ## 1.0.0-pre.3 * Fix: void elements no longer parsed correctly when using `innerHTML`. This was a regression between 0.11.1 and 1.0.0-pre.1. (Sebmaster) ## 1.0.0-pre.2 * Fix: parsing and serialization of attributes in the form `x:y`, e.g. `xmlns:xlink` or `xlink:href`. This was a regression between 0.11.1 and 1.0.0-pre.1. (Sebmaster) ## 1.0.0-pre.1 This is a prerelease of jsdom's first major version. It incorporates several great additions, as well as a general cleanup of the API surface, which make it more backward-incompatible than usual. Starting with the 1.0.0 release, we will be following semantic versioning, so that you can depend on stability within major version ranges. But we still have [a few more issues](https://github.com/jsdom/jsdom/issues?q=is%3Aopen+is%3Aissue+milestone%3A1.0) before we can get there, so I don't want to do 1.0.0 quite yet. This release owes a special thanks to [@Sebmaster](https://github.com/Sebmaster), for his amazing work taking on some of the hardest problems in jsdom and solving them with gusto. ### Major changes * jsdom now can be browserified into a bundle that works in web workers! This is highly experimental, but also highly exciting! (lawnsea) * An overhaul of the [initialization lifecycle](https://github.com/jsdom/jsdom#initialization-lifecycle), to bring more control and address common use cases. (Sebmaster) * The excellent [parse5](https://npmjs.org/package/parse5) HTML parser is now the default parser, fixing many parsing bugs and giving us full, official-test-suite-passing HTML parsing support. This especially impacts documents that didn't include optional tags like `<html>`, `<head>`, or `<body>` in their source. We also use parse5 for serialization, fixing many bugs there. (Sebmaster) * As part of the new parser story, we are not supporting XML for now. It might work if you switch to a different parser (e.g. htmlparser2), but in the end, HTML and XML are very different, and we are not attempting to be an XML DOM. That said, we eventually want to support XML to the same extent browsers do (i.e., support XHTML and SVG, with an appropriate MIME type switch); this is being planned in [#820](https://github.com/jsdom/jsdom/issues/820). ### Removed jsdom APIs * `jsdom.createWindow`: use `document.parentWindow` after creating a document * `jsdom.html`: use `jsdom.jsdom` * `jsdom.version`: use `require("jsdom/package.json").version` * `jsdom.level`: levels are deprecated and will probably be removed in 2.0.0 * `jsdom.dom` * `jsdom.browserAugmentation` * `jsdom.windowAugmentation` ### Changed jsdom APIs * `jsdom.jsdom` no longer takes a level as its second argument. * `jsdom.jQueryify` now requires a jQuery URL, since [always picking the latest was a bad idea](http://blog.jquery.com/2014/07/03/dont-use-jquery-latest-js/). ### Removed non-standard DOM APIs * `document.createWindow`: use `document.parentWindow` * `document.innerHTML` and `document.outerHTML`: use the new `jsdom.serializeDocument` to include the DOCTYPE, or use `document.documentElement.outerHTML` to omit it. ### Other fixes * Allow empty strings to be passed to `jsdom.env`. (michaelmior) * Fix for a memory leak in `EventTarget.prototype.dispatchEvent`. (Joris-van-der-Wel) * Make event listeners in the capture phase also fire on the event target. (Joris-van-der-Wel) * Correctly reset `eventPhase` and `currentTarget` on events, before and after a dispatch. (Joris-van-der-Wel) * Fix `document.cookie = null` to not throw, but instead just do nothing. (kapouer) ## 0.11.1 * Add: `Node.prototype.parentElement`. (lukasbuenger) * Fix: attributes that are reflected as properties should be `''` when not present, instead of `null`. (Note that `getAttribute` still returns `null` for them). (thejameskyle) * Fix: `textContent` now works for nodes that do not have children, like text nodes for example. (hayes) * Fix: `jsdom.jQueryify` was using the wrong URL for jQuery by default. (lukasbuenger) ## 0.11.0 * Add: new default level, `living`, reflecting our focus on the [DOM Living Standard](http://dom.spec.whatwg.org/) and the [HTML Living Standard](http://www.whatwg.org/specs/web-apps/current-work/multipage/), which are what browsers actually implement. This should open the door for more features of the modern DOM and HTML specs to be implemented in jsdom. (robotlovesyou) * Add: `Node.prototype.contains` now implemented. (robotlovesyou) * Add: `navigator.cookieEnabled` now implemented; it always returns `true`. (Sebmaster) * Change: DOCTYPEs no longer have their `name` property uppercased during parsing, and appear in the output of `document.innerHTML`. * Fix: `Node.prototype.compareDocumentPosition` implemented correctly; various document position constants added to the `Node` constructor. (robotlovesyou) * Fix: `DocumentType.prototype.parentNode` now returns the document node, not `null`. (robotlovesyou) * Fix: various `navigator` properties are now getters, not data properties. (Sebmaster) * Fix: a bug involving invalid script paths and `jsdom.jQueryify`. (Sebmaster) ## 0.10.6 * Add: remaining URL properties to `window.location` and `HTMLAnchorElement`. * Fix: the presence of `String.prototype.normalize`, which is available by default in Node 0.11.13 onwards, caused reflected attributes to break. (brock8503) * Fix: iframes now correctly load `about:blank` when the `src` attribute is empty or missing. (mcmathja) * Fix: documents containing only whitespace now correctly generate wrapper documents, just like blank documents do. (nikolas) * Tweak: lazy-load the request module, to improve overall jsdom loading time. (tantaman) ## 0.10.5 * Fix: the list of void elements has been updated to match the latest HTML spec. * Fix: when serializing void elements, don't include a ` /`: i.e. the result is now `<br>` instead of `<br />`. ## 0.10.4 * Fix: another case was found where jQuery 1.11's `show()` method would cause errors. * Add: `querySelector` and `querySelectorAll` methods to `DocumentFragment`s. (Joris-van-der-Wel) ## 0.10.3 * Fix: various defaults on `HTMLAnchorElement` and `window.location` should not be `null`; they should usually be the empty string. ## 0.10.2 * Fix: Using jQuery 1.11's `show()` method would cause an error to be thrown. * Fix: `window.location` properties were not updating correctly after using `pushState` or `replaceState`. (toomanydaves) ## 0.10.1 * Fix: `window.location.port` should default to `""`, not `null`. (bpeacock) ## 0.10.0 * Add: a more complete `document.cookie` implementation, that supports multiple cookies. Note that options like `path`, `max-age`, etc. are still ignored. (dai-shi) ## 0.9.0 * Add: implement attribute ordering semantics from WHATWG DOM spec, and in general overhaul attribute storage implementation to be much more awesome and accurate. (lddubeau) * Add: `port` and `protocol` to `HTMLAnchorElement`. (sporchia) * Fix: make `HTMLInputElement` not have a `type` *attribute* by default. It still has a default value for the `type` *property*, viz. `"text"`. (aredridel) * Fix: treat empty namespace URI as meaning "no namespace" with the `getAttributeNS`, `hasAttributeNS`, and `setAttributeNS` functions. (lddubeau) * Fix: reference typed arrays in a way that doesn't immediately break on Node 0.6. Node 0.6 isn't supported in general, though. (kangax) ## 0.8.11 * Add: store and use cookies between requests; customizable cookie jars also possible. (stockholmux) * Fix: attributes named the same as prototype properties of `NamedNodeMap` no longer break jsdom. (papandreou) * Fix: `removeAttributeNS` should not throw on missing attributes. (lddubeau) * Change: remove `__proto__`, `__defineGetter__`, and `__defineSetter__` usage, as part of a project to make jsdom work better across multiple environments. (lawnsea) ## 0.8.10 * Add: `hash` property to `HTMLAnchorElement`. (fr0z3nk0) ## 0.8.9 * Upgrade: `cssom` to 0.3.0, adding support for `@-moz-document` and fixing a few other issues. * Upgrade: `cssstyle` to 0.2.6, adding support for many shorthand properties and better unit handling. ## 0.8.8 * Fix: avoid repeated `NodeList.prototype.length` calculation, for a speed improvement. (peller) ## 0.8.7 * Add: `host` property to `HTMLAnchorElement`. (sporchia) ## 0.8.6 * Fix: stop accidentally modifying `Error.prototype`. (mitar) * Add: a dummy `getBoundingClientRect` method, that returns `0` for all properties of the rectangle, is now implemented. (F1LT3R) ## 0.8.5 * Add: `href` property on `CSSStyleSheet` instances for external CSS files. (FrozenCow) ## 0.8.4 * Add: typed array constructors on the `window`. (nlacasse) * Fix: `querySelector` and `querySelectorAll` should be on the prototypes of `Element` and `Document`, not own-properties. (mbostock) ## 0.8.3 * Fix: when auto-detecting whether the first parameter to `jsdom.env` is a HTML string or a filename, deal with long strings correctly instead of erroring. (baryshev) ## 0.8.2 * Add: basic `window.history` support, including `back`, `forward`, `go`, `pushState`, and `replaceState`. (ralphholzmann) * Add: if an `<?xml?>` declaration starts the document, will try to parse as XML, e.g. not lowercasing the tags. (robdodson) * Fix: tag names passed to `createElement` are coerced to strings before evaluating. ## 0.8.1 (hotfix) * Fix: a casing issue that prevented jsdom from loading on Unix and Solaris systems. (dai-shi) * Fix: `window.location.replace` was broken. (dai-shi) * Fix: update minimum htmlparser2 version, to ensure you get the latest parsing-related bugfixes. ## 0.8.0 * Add: working `XMLHttpRequest` support, including cookie passing! (dai-shi) * Add: there is now a `window.navigator.noUI` property that evaluates to true, if you want to specifically distinguish jsdom in your tests. ## 0.7.0 * Change: the logic when passing `jsdom.env` a string is more accurate, and you can be explicit by using the `html`, `url`, or `file` properties. This is a breaking change in the behavior of `html`, which used to do the same auto-detection logic as the string-only version. * Fix: errors raised in scripts are now passed to `jsdom.env`'s callback. (airportyh) * Fix: set `window.location.href` correctly when using `jsdom.env` to construct a window from a URL, when that URL causes a redirect. (fegs) * Add: a more complete and accurate `window.location` object, which includes firing `hashchange` events when the hash is changed. (dai-shi) * Add: when using a non-implemented feature, mention exactly what it was that is not implemented in the error message. (papandreou) ## 0.6.5 * Fix: custom attributes whose names were the same as properties of `Object.prototype`, e.g. `"constructor"`, would confuse jsdom massively. ## 0.6.4 * Fix: CSS selectors which contain commas inside quotes are no longer misinterpreted. (chad3814) * Add: `<img>` elements now fire `load` events when their `src` attributes are changed. (kapouer) ## 0.6.3 * Fix: better automatic detection of URLs vs. HTML fragments when using `jsdom.env`. (jden) ## 0.6.2 * Fix: URL resolution to be amazing and extremely browser-compatible, including the interplay between the document's original URL, any `<base>` tags that were set, and any relative `href`s. This impacts many parts of jsdom having to do with external resources or accurate `href` and `src` attributes. (deitch) * Add: access to frames and iframes via named properties. (adrianlang) * Fix: node-canvas integration, which had been broken since 0.5.7. ## 0.6.1 * Make the code parseable with Esprima. (squarooticus) * Use the correct `package.json` field `"repository"` instead of `"repositories"` to prevent npm warnings. (jonathanong) ## 0.6.0 Integrated a new HTML parser, [htmlparser2](https://npmjs.org/package/htmlparser2), from fb55. This is an actively maintained and much less buggy parser, fixing many of our parsing issues, including: * Parsing elements with optional closing tags, like `<p>` or `<td>`. * The `innerHTML` of `<script>` tags no longer cuts off the first character. * Empty attributes now have `""` as their value instead of the attribute name. * Multiline attributes no longer get horribly mangled. * Attribute names can now be any value allowed by HTML5, including crazy things like `^`. * Attribute values can now contain any value allowed by HTML5, including e.g. `>` and `<`. ## 0.5.7 * Fix: make event handlers attached via `on<event>` more spec-compatible, supporting `return false` and passing the `event` argument. (adrianlang) * Fix: make the getter for `textContent` more accurate, e.g. in cases involving comment nodes or processing instruction nodes. (adrianlang) * Fix: make `<canvas>` behave like a `<div>` when the `node-canvas` package isn't available, instead of crashing. (stepheneb) ## 0.5.6 * Fix: `on<event>` properties are correctly updated when using `setAttributeNode`, `attributeNode.value =`, `removeAttribute`, and `removeAttributeNode`; before it only worked with `setAttribute`. (adrianlang) * Fix: `HTMLCollection`s now have named properties based on their members' `id` and `name` attributes, e.g. `form.elements.inputId` is now present. (adrianlang) ## 0.5.5 * Fix: `readOnly` and `selected` properties were not correct when their attribute values were falsy, e.g. `<option selected="">`. (adrianlang) ## 0.5.4 This release, and all future releases, require at least Node.js 0.8. * Add: parser can now be set via `jsdom.env` configuration. (xavi-) * Fix: accessing `rowIndex` for table rows that are not part of a table would throw. (medikoo) * Fix: several places in the code accidentally created global variables, or referenced nonexistant values. (xavi-) * Fix: `<img>` elements' `src` properties now evaluate relative to `location.href`, just like `<a>` elements' `href` properties. (brianmaissy) ## 0.5.3 This release is compatible with Node.js 0.6, whereas all future releases will require at least Node.js 0.8. * Fix: `getAttributeNS` now returns `null` for attributes that are not present, just like `getAttribute`. (mbostock) * Change: `"request"` dependency pinned to version 2.14 for Node.js 0.6 compatibility. ## 0.5.2 * Fix: stylesheets with `@-webkit-keyframes` rules were crashing calls to `getComputedStyle`. * Fix: handling of `features` option to `jsdom.env`. * Change: retain the value of the `style` attribute until the element's `style` property is touched. (papandreou) ## 0.5.1 * Fix: `selectedIndex` now changes correctly in response to `<option>` elements being selected. This makes `<select>` elements actually work like you would want, especially with jQuery. (xcoderzach) * Fix: `checked` works correctly on radio buttons, i.e. only one can be checked and clicking on one does not uncheck it. Previously they worked just like checkboxes. (xcoderzach) * Fix: `click()` on `<input>` elements now fires a click event. (xcoderzach) ## 0.5.0 * Fix: Make `contextify` a non-optional dependency. jsdom never worked without it, really, so this just caused confusion. ## 0.4.2 * Fix: `selected` now returns true for the first `<option>` in a `<select>` if nothing is explicitly set. * Fix: tweaks to accuracy and speed of the `querySelectorAll` implementation. ## 0.4.1 (hotfix) * Fix: crashes when loading HTML files with `<a>` tags with no `href` attribute. (eleith) ## 0.4.0 * Fix: `getAttribute` now returns `null` for attributes that are not present, as per DOM4 (but in contradiction to DOM1 through DOM3). * Fix: static `NodeList`-returning methods (such as `querySelectorAll`) now return a real `NodeList` instance. * Change: `NodeList`s no longer expose nonstandard properties to the world, like `toArray`, without first prefixing them with an underscore. * Change: `NodeList`s no longer inconsistently have array methods. Previously, live node lists would have `indexOf`, while static node lists would have them all. Now, they have no array methods at all, as is correct per the specification. ## 0.3.4 * Fix: stylesheets with `@media` rules were crashing calls to `getComputedStyle`, e.g. those in jQuery's initialization. ## 0.3.3 * Fix: make `document.write` calls insert new elements correctly. (johanoverip, kblomquist). * Fix: `<input>` tags with no `type` attribute now return a default value of `"text"` when calling `inputEl.getAttribute("type")`. ## 0.3.2 * Fix: stylesheets with "joining" rules (i.e. those containing comma-separated selectors) now apply when using `getComputedStyle`. (chad3814, godmar) * Add: support for running the tests using @aredridel's [html5](https://npmjs.org/package/html5) parser, as a prelude toward maybe eventually making this the default and fixing various parsing bugs. ## 0.3.1 (hotfix) * Fix: crashes when invalid selectors were present in stylesheets. ## 0.3.0 * Fix: a real `querySelector` implementation, courtesy of the nwmatcher project, solves many outstanding `querySelector` bugs. * Add: `matchesSelector`, again via nwmatcher. * Add: support for styles coming from `<style>` and `<link rel="stylesheet">` elements being applied to the results of `window.getComputedStyle`. (chad3814) * Add: basic implementation of `focus()` and `blur()` methods on appropriate elements. More work remains. * Fix: script filenames containing spaces will now work when passed to `jsdom.env`. (TomNomNom) * Fix: elements with IDs `toString`, `hasOwnProperty`, etc. could cause lots of problems. * Change: A window's `load` event always fires asynchronously now, even if no external resources are necessary. * Change: turning off mutation events is not supported, since doing so breaks external-resource fetching. ## 0.2.19 * Fix: URL resolution was broken on pages that included `href`-less `<base>` tags. * Fix: avoid putting `attr` in the global scope when using node-canvas. (starsquare) * Add: New `SkipExternalResources` feature accepts a regular expression. (fgalassi) ## 0.2.18 * Un-revert: cssstyle has fixed its memory problems, so we get back accurate `cssText` and `style` properties again. ## 0.2.17 (hotfix) * Revert: had to revert the use of the cssstyle package. `cssText` and `style` properties are no longer as accurate. * Fix: cssstyle was causing out-of-memory errors on some larger real-world pages, e.g. reddit.com. ## 0.2.16 * Update: Sizzle version updated to circa September 2012. * Fix: when setting a text node's value to a falsy value, convert it to a string instead of coercing it to `""`. * Fix: Use the cssstyle package for `CSSStyleDeclaration`, giving much more accurate `cssText` and `style` properties on all elements. (chad3814) * Fix: the `checked` property on checkboxes and radiobuttons now reflects the attribute correctly. * Fix: `HTMLOptionElement`'s `text` property should return the option's text, not its value. * Fix: make the `name` property only exist on certain specific tags, and accurately reflect the corresponding `name` attribute. * Fix: don't format `outerHTML` (especially important for `<pre>` elements). * Fix: remove the `value` property from `Text` instances (e.g. text nodes). * Fix: don't break in the presence of a `String.prototype.normalize` method, like that of sugar.js. * Fix: include level3/xpath correctly. * Fix: many more tests passing, especially related to file:/// URLs on Windows. Tests can now be run with `npm test`. ## 0.2.15 * Fix: make sure that doctypes don't get set as the documentElement (Aria Stewart) * Add: HTTP proxy support for jsdom.env (Eugene Ware) * Add: .hostname and .pathname properties to Anchor elements to comply with WHATWG standard (Avi Deitcher) * Fix: Only decode HTML entities in text when not inside a `<script>` or `<style>` tag. (Andreas Lind Petersen) * Fix: HTMLSelectElement single selection implemented its type incorrectly as 'select' instead of 'select-one' (John Roberts) ## 0.2.14 * Fix: when serializing single tags use ' />' instead of '/>' (kapouer) * Fix: support for contextify simulation using vm.runInContext (trodrigues) * Fix: allow jsdom.env's config.html to handle file paths which contain spaces (shinuza) * Fix: Isolate QuerySelector from prototype (Nao Iizuka) * Add: setting textContent to '' or clears children (Jason Davies) * Fix: jsdom.env swallows exceptions that occur in the callback (Xavi) ## 0.2.13 * Fix: remove unused style property which was causing explosions in 0.2.12 and node 0.4.7 ## 0.2.12 * Fix: do not include gmon.out/v8.log/tests in npm distribution ## 0.2.11 * Add: allow non-unique element ids (Avi Deitcher) * Fix: make contexify an optional dependency (Isaac Schlueter) * Add: scripts injected by jsdom are now marked with a 'jsdom' class for serialization's sake (Peter Lyons) * Fix: definition for ldquo entity (Andrew Morton) * Fix: access NamedNodeMap items via property (Brian McDaniel) * Add: upgrade sizzle from 1.0 to [fe2f6181](https://github.com/jquery/sizzle/commit/fe2f618106bb76857b229113d6d11653707d0b22) which is roughly 1.5.1 * Add: documentation now includes `jsdom.level(x, 'feature')` * Fix: make `toArray` and `item` on `NodeList` objects non-enumerable properties * Add: a reference to `window.close` in the readme * Fix: Major performance boost (Felix Gnass) * Fix: Using querySelector `:not()` throws a `ReferenceError` (Felix Gnass) ## 0.2.10 * Fix: problems with lax dependency versions * Fix: CSSOM constructors are hung off of the dom (Brian McDaniel) * Fix: move away from deprecated 'sys' module * Fix: attribute event handlers on bubbling path aren't called (Brian McDaniel) * Fix: setting textarea.value to markup should not be parsed (Andreas Lind Petersen) * Fix: content of script tags should not be escaped (Ken Sternberg) * Fix: DocumentFeatures for iframes with no src attribute. (Brian McDaniel) Closes #355 * Fix: 'trigger' to 'raise' to be a bit more descriptive * Fix: When `ProcessExternalResources['script']` is disabled, do _not_ run inline event handlers. #355 * Add: verbose flag to test runner (to show tests as they are running and finishing) ## 0.2.9 * Fix: ensure features are properly reset after a jsdom.env invocation. Closes #239 * Fix: ReferenceError in the scanForImportRules helper function * Fix: bug in appendHtmlToElement with HTML5 parser (Brian McDaniel) * Add: jsonp support (lheiskan) * Fix: for setting script element's text property (Brian McDaniel) * Fix: for jsdom.env src bug * Add: test for jsdom.env src bug (multiple done calls) * Fix: NodeList properties should enumerate like arrays (Felix Gnass) * Fix: when downloading a file, include the url.search in file path * Add: test for making a jsonp request with jquery from jsdom window * Add: test case for issue #338 * Fix: double load behavior when mixing jsdom.env's `scripts` and `src` properties (cjroebuck) ## 0.2.8 (hotfix) * Fix: inline event handlers are ignored by everything except for the javascript context ## 0.2.7 (hotfix) * Fix stylesheet loading ## 0.2.6 * Add: support for window.location.search and document.cookie (Derek Lindahl) * Add: jsdom.env now has a document configuation option which allows users to change the referer of the document (Derek Lindahl) * Fix: allow users to use different jsdom levels in the same process (sinegar) * Fix: removeAttributeNS no longer has a return value (Jason Davies) * Add: support for encoding/decoding all html entities from html4/5 (papandreou) * Add: jsdom.env() accepts the same features object seen in jsdom.jsdom and friends ## 0.2.5 * Fix: serialize special characters in Element.innerHTML/Element.attributes like a grade A browser (Jason Priestley) * Fix: ensure Element.getElementById only returns elements that are attached to the document * Fix: ensure an Element's id is updated when changing the nodeValue of the 'id' attribute (Felix Gnass) * Add: stacktrace to error reporter (Josh Marshall) * Fix: events now bubble up to the window (Jason Davies) * Add: initial window.location.hash support (Josh Marshall) * Add: Node#insertBefore should do nothing when both params are the same node (Jason Davies) * Add: fixes for DOMAttrModified mutation events (Felix Gnass) ## 0.2.4 * Fix: adding script to invalid/incomplete dom (document.documentElement) now catches the error and passes it in the `.env` callback (Gregory Tomlinson) * Cleanup: trigger and html tests * Add: support for inline event handlers (ie: `<div onclick='some.horrible.string()'>`) (Brian McDaniel) * Fix: script loading over https (Brian McDaniel) #280 * Add: using style.setProperty updates the style attribute (Jimmy Mabey). * Add: invalid markup is reported as an error and attached to the associated element and document * Fix: crash when setChild() failes to create new DOM element (John Hurliman) * Added test for issue #287. * Added support for inline event handlers. * Moved frame tests to test/window/frame.js and cleaned up formatting. * Moved script execution tests to test/window/script.js. * Fix a crash when setChild() fails to create a new DOM element * Override CSSOM to update style attribute ## 0.2.3 * Fix: segfault due to window being garbage collected prematurely NOTE: you must manually close the window to free memory (window.close()) ## 0.2.2 * Switch to Contextify to manage the window's script execution. * Fix: allow nodelists to have a length of 0 and toArray to return an empty array * Fix: style serialization; issues #230 and #259 * Fix: Incomplete DOCTYPE causes JavaScript error * Fix: indentation, removed outdated debug code and trailing whitespace. * Prevent JavaScript error when parsing incomplete `<!DOCTYPE>`. Closes #259. * Adding a test from brianmcd that ensures that setTimeout callbacks execute in the context of the window * Fixes issue 250: make `document.parentWindow === window` work * Added test to ensure that timer callbacks execute in the window context. * Fixes 2 issues in ResourceQueue * Make frame/iframe load/process scripts if the parent has the features enabled ## 0.2.1 * Javascript execution fixes [#248, #163, #179] * XPath (Yonathan and Daniel Cassidy) * Start of cssom integration (Yonathan) * Conversion of tests to nodeunit! (Martin Davis) * Added sizzle tests, only failing 3/15 * Set the title node's textContent rather than its innerHTML #242. (Andreas Lind Petersen) * The textContent getter now walks the DOM and extract the text properly. (Andreas Lind Petersen) * Empty scripts won't cause jsdom.env to hang #172 (Karuna Sagar) * Every document has either a body or a frameset #82. (Karuna Sagar) * Added the ability to grab a level by string + feature. ie: jsdom.level(2, 'html') (Aria Stewart) * Cleaned up htmlencoding and fixed character (de)entification #147, #177 (Andreas Lind Petersen) * htmlencoding.HTMLDecode: Fixed decoding of `&lt;`, `&gt;`, `&amp;`, and `&apos;`. Closes #147 and #177. * Require dom level as a string or object. (Aria Stewart) * JS errors ar triggered on the script element, not document. (Yonathan) * Added configuration property 'headers' for HTTP request headers. (antonj) * Attr.specified is readonly - Karuna Sagar * Removed return value from setAttributeNS() #207 (Karuna Sagar) * Pass the correct script filename to runInContext. (robin) * Add http referrer support for the download() function. (Robin) * First attempt at fixing the horrible memory leak via window.stopTimers() (d-ash) * Use vm instead of evals binding (d-ash) * Add a way to set the encoding of the jsdom.env html request. * Fixed various typos/lint problems (d-ash) * The first parameter download is now the object returned by URL.parse(). (Robin) * Fixed serialization of elements with a style attribute. * Added src config option to jsdom.env() (Jerry Sievert) * Removed dead code from getNamedItemNS() (Karuna Sagar) * Changes to language/javascript so jsdom would work on v0.5.0-pre (Gord Tanner) * Correct spelling of "Hierarchy request error" (Daniel Cassidy) * Node and Exception type constants are available in all levels. (Daniel Cassidy) * Use \n instead of \r\n during serialization * Fixed auto-insertion of body/html tags (Adrian Makowski) * Adopt unowned nodes when added to the tree. (Aria Stewart) * Fix the selected and defaultSelected fields of `option` element. - Yonathan * Fix: EventTarget.getListeners() now returns a shallow copy so that listeners can be safely removed while an event is being dispatched. (Felix Gnass) * Added removeEventListener() to DOMWindow (Felix Gnass) * Added the ability to pre-load scripts for jsdom.env() (Jerry Sievert) * Mutation event tests/fixes (Felix Gnass) * Changed HTML serialization code to (optionally) pretty print while traversing the tree instead of doing a regexp-based postprocessing. (Andreas Lind Petersen) * Relative and absolute urls now work as expected * setNamedItem no longer sets Node.parentNode #153 (Karuna Sagar) * Added missing semicolon after entity name - Felix Gnass * Added NodeList#indexOf implementation/tests (Karuna Sagar) * resourceLoader.download now works correctly with https and redirects (waslogic) * Scheme-less URLs default to the current protocol #87 (Alexander Flatter) * Simplification the prevSibling(), appendChild(), insertBefore() and replaceChild() code (Karuna Sagar) * Javascript errors use core.Node.trigger (Alexander Flatter) * Add core.Document.trigger in level1/core and level2/events; Make DOMWindow.console use it (Alexander Flatter) * Resource resolver fixes (Alexander Flatter) * Fix serialization of doctypes with new lines #148 (Karuna Sagar) * Child nodes are calculated immediately instead of after .length is called #169, #171, #176 (Karuna Sagar)
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/Changelog.md
Changelog.md
"use strict"; // https://heycam.github.io/webidl/#idl-named-properties const IS_NAMED_PROPERTY = Symbol("is named property"); const TRACKER = Symbol("named property tracker"); /** * Create a new NamedPropertiesTracker for the given `object`. * * Named properties are used in DOM to let you lookup (for example) a Node by accessing a property on another object. * For example `window.foo` might resolve to an image element with id "foo". * * This tracker is a workaround because the ES6 Proxy feature is not yet available. * * @param {Object} object Object used to write properties to * @param {Object} objectProxy Object used to check if a property is already defined * @param {Function} resolverFunc Each time a property is accessed, this function is called to determine the value of * the property. The function is passed 3 arguments: (object, name, values). * `object` is identical to the `object` parameter of this `create` function. * `name` is the name of the property. * `values` is a function that returns a Set with all the tracked values for this name. The order of these * values is undefined. * * @returns {NamedPropertiesTracker} */ exports.create = function (object, objectProxy, resolverFunc) { if (object[TRACKER]) { throw Error("A NamedPropertiesTracker has already been created for this object"); } const tracker = new NamedPropertiesTracker(object, objectProxy, resolverFunc); object[TRACKER] = tracker; return tracker; }; exports.get = function (object) { if (!object) { return null; } return object[TRACKER] || null; }; function NamedPropertiesTracker(object, objectProxy, resolverFunc) { this.object = object; this.objectProxy = objectProxy; this.resolverFunc = resolverFunc; this.trackedValues = new Map(); // Map<Set<value>> } function newPropertyDescriptor(tracker, name) { const emptySet = new Set(); function getValues() { return tracker.trackedValues.get(name) || emptySet; } const descriptor = { enumerable: true, configurable: true, get() { return tracker.resolverFunc(tracker.object, name, getValues); }, set(value) { Object.defineProperty(tracker.object, name, { enumerable: true, configurable: true, writable: true, value }); } }; descriptor.get[IS_NAMED_PROPERTY] = true; descriptor.set[IS_NAMED_PROPERTY] = true; return descriptor; } /** * Track a value (e.g. a Node) for a specified name. * * Values can be tracked eagerly, which means that not all tracked values *have* to appear in the output. The resolver * function that was passed to the output may filter the value. * * Tracking the same `name` and `value` pair multiple times has no effect * * @param {String} name * @param {*} value */ NamedPropertiesTracker.prototype.track = function (name, value) { if (name === undefined || name === null || name === "") { return; } let valueSet = this.trackedValues.get(name); if (!valueSet) { valueSet = new Set(); this.trackedValues.set(name, valueSet); } valueSet.add(value); if (name in this.objectProxy) { // already added our getter or it is not a named property (e.g. "addEventListener") return; } const descriptor = newPropertyDescriptor(this, name); Object.defineProperty(this.object, name, descriptor); }; /** * Stop tracking a previously tracked `name` & `value` pair, see track(). * * Untracking the same `name` and `value` pair multiple times has no effect * * @param {String} name * @param {*} value */ NamedPropertiesTracker.prototype.untrack = function (name, value) { if (name === undefined || name === null || name === "") { return; } const valueSet = this.trackedValues.get(name); if (!valueSet) { // the value is not present return; } if (!valueSet.delete(value)) { // the value was not present return; } if (valueSet.size === 0) { this.trackedValues.delete(name); } if (valueSet.size > 0) { // other values for this name are still present return; } // at this point there are no more values, delete the property const descriptor = Object.getOwnPropertyDescriptor(this.object, name); if (!descriptor || !descriptor.get || descriptor.get[IS_NAMED_PROPERTY] !== true) { // Not defined by NamedPropertyTracker return; } // note: delete puts the object in dictionary mode. // if this turns out to be a performance issue, maybe add: // https://github.com/petkaantonov/bluebird/blob/3e36fc861ac5795193ba37935333eb6ef3716390/src/util.js#L177 delete this.object[name]; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/named-properties-tracker.js
named-properties-tracker.js
"use strict"; const path = require("path"); const whatwgURL = require("whatwg-url"); const { domSymbolTree } = require("jsdom/lib/jsdom/living/helpers/internal-constants"); const SYMBOL_TREE_POSITION = require("symbol-tree").TreePosition; exports.toFileUrl = function (fileName) { // Beyond just the `path.resolve`, this is mostly for the benefit of Windows, // where we need to convert "\" to "/" and add an extra "/" prefix before the // drive letter. let pathname = path.resolve(process.cwd(), fileName).replace(/\\/g, "/"); if (pathname[0] !== "/") { pathname = "/" + pathname; } // path might contain spaces, so convert those to %20 return "file://" + encodeURI(pathname); }; /** * Define a set of properties on an object, by copying the property descriptors * from the original object. * * - `object` {Object} the target object * - `properties` {Object} the source from which to copy property descriptors */ exports.define = function define(object, properties) { for (const name of Object.getOwnPropertyNames(properties)) { const propDesc = Object.getOwnPropertyDescriptor(properties, name); Object.defineProperty(object, name, propDesc); } }; /** * Define a list of constants on a constructor and its .prototype * * - `Constructor` {Function} the constructor to define the constants on * - `propertyMap` {Object} key/value map of properties to define */ exports.addConstants = function addConstants(Constructor, propertyMap) { for (const property in propertyMap) { const value = propertyMap[property]; addConstant(Constructor, property, value); addConstant(Constructor.prototype, property, value); } }; function addConstant(object, property, value) { Object.defineProperty(object, property, { configurable: false, enumerable: true, writable: false, value }); } exports.mixin = (target, source) => { const keys = Reflect.ownKeys(source); for (let i = 0; i < keys.length; ++i) { if (keys[i] in target) { continue; } Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); } }; let memoizeQueryTypeCounter = 0; /** * Returns a version of a method that memoizes specific types of calls on the object * * - `fn` {Function} the method to be memozied */ exports.memoizeQuery = function memoizeQuery(fn) { // Only memoize query functions with arity <= 2 if (fn.length > 2) { return fn; } const type = memoizeQueryTypeCounter++; return function () { if (!this._memoizedQueries) { return fn.apply(this, arguments); } if (!this._memoizedQueries[type]) { this._memoizedQueries[type] = Object.create(null); } let key; if (arguments.length === 1 && typeof arguments[0] === "string") { key = arguments[0]; } else if (arguments.length === 2 && typeof arguments[0] === "string" && typeof arguments[1] === "string") { key = arguments[0] + "::" + arguments[1]; } else { return fn.apply(this, arguments); } if (!(key in this._memoizedQueries[type])) { this._memoizedQueries[type][key] = fn.apply(this, arguments); } return this._memoizedQueries[type][key]; }; }; function isValidAbsoluteURL(str) { return whatwgURL.parseURL(str) !== null; } exports.isValidTargetOrigin = function (str) { return str === "*" || str === "/" || isValidAbsoluteURL(str); }; exports.simultaneousIterators = function* (first, second) { for (;;) { const firstResult = first.next(); const secondResult = second.next(); if (firstResult.done && secondResult.done) { return; } yield [ firstResult.done ? null : firstResult.value, secondResult.done ? null : secondResult.value ]; } }; exports.treeOrderSorter = function (a, b) { const compare = domSymbolTree.compareTreePosition(a, b); if (compare & SYMBOL_TREE_POSITION.PRECEDING) { // b is preceding a return 1; } if (compare & SYMBOL_TREE_POSITION.FOLLOWING) { return -1; } // disconnected or equal: return 0; }; /* eslint-disable global-require */ exports.Canvas = null; let canvasInstalled = false; try { require.resolve("canvas"); canvasInstalled = true; } catch (e) { // canvas is not installed } if (canvasInstalled) { const Canvas = require("canvas"); if (typeof Canvas.createCanvas === "function") { // In browserify, the require will succeed but return an empty object exports.Canvas = Canvas; } }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/utils.js
utils.js
"use strict"; /* eslint-disable no-new-func */ const acorn = require("acorn"); const findGlobals = require("acorn-globals"); const escodegen = require("escodegen"); const jsGlobals = require("jsdom/lib/jsdom/browser/js-globals.json"); // We can't use the default browserify vm shim because it doesn't work in a web worker. // "eval" is skipped because it's set to a function that calls `runInContext`: const jsGlobalEntriesToInstall = Object.entries(jsGlobals).filter(([name]) => name !== "eval" && name in global); exports.createContext = function (sandbox) { // TODO: This should probably use a symbol Object.defineProperty(sandbox, "__isVMShimContext", { value: true, writable: true, configurable: true, enumerable: false }); for (const [globalName, globalPropDesc] of jsGlobalEntriesToInstall) { const propDesc = { ...globalPropDesc, value: global[globalName] }; Object.defineProperty(sandbox, globalName, propDesc); } Object.defineProperty(sandbox, "eval", { value(code) { return exports.runInContext(code, sandbox); }, writable: true, configurable: true, enumerable: false }); }; exports.isContext = function (sandbox) { return sandbox.__isVMShimContext; }; exports.runInContext = function (code, contextifiedSandbox, options) { if (code === "this") { // Special case for during window creation. return contextifiedSandbox; } if (options === undefined) { options = {}; } const comments = []; const tokens = []; const ast = acorn.parse(code, { allowReturnOutsideFunction: true, ranges: true, // collect comments in Esprima's format onComment: comments, // collect token ranges onToken: tokens }); // make sure we keep comments escodegen.attachComments(ast, comments, tokens); const globals = findGlobals(ast); for (let i = 0; i < globals.length; ++i) { if (globals[i].name === "window" || globals[i].name === "this") { continue; } const { nodes } = globals[i]; for (let j = 0; j < nodes.length; ++j) { const { type, name } = nodes[j]; nodes[j].type = "MemberExpression"; nodes[j].property = { name, type }; nodes[j].computed = false; nodes[j].object = { name: "window", type: "Identifier" }; } } const lastNode = ast.body[ast.body.length - 1]; if (lastNode.type === "ExpressionStatement") { lastNode.type = "ReturnStatement"; lastNode.argument = lastNode.expression; delete lastNode.expression; } const rewrittenCode = escodegen.generate(ast, { comment: true }); const suffix = options.filename !== undefined ? "\n//# sourceURL=" + options.filename : ""; return Function("window", rewrittenCode + suffix).bind(contextifiedSandbox)(contextifiedSandbox); }; exports.Script = class VMShimScript { constructor(code, options) { this._code = code; this._options = options; } runInContext(sandbox, options) { return exports.runInContext(this._code, sandbox, Object.assign({}, this._options, options)); } };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/vm-shim.js
vm-shim.js
"use strict"; const DOMException = require("domexception/webidl2js-wrapper"); const { HTML_NS } = require("jsdom/lib/jsdom/living/helpers/namespaces"); const { asciiLowercase } = require("jsdom/lib/jsdom/living/helpers/strings"); const { queueAttributeMutationRecord } = require("jsdom/lib/jsdom/living/helpers/mutation-observers"); const { enqueueCECallbackReaction } = require("jsdom/lib/jsdom/living/helpers/custom-elements"); // The following three are for https://dom.spec.whatwg.org/#concept-element-attribute-has. We don't just have a // predicate tester since removing that kind of flexibility gives us the potential for better future optimizations. /* eslint-disable no-restricted-properties */ exports.hasAttribute = function (element, A) { return element._attributeList.includes(A); }; exports.hasAttributeByName = function (element, name) { return element._attributesByNameMap.has(name); }; exports.hasAttributeByNameNS = function (element, namespace, localName) { return element._attributeList.some(attribute => { return attribute._localName === localName && attribute._namespace === namespace; }); }; // https://dom.spec.whatwg.org/#concept-element-attributes-change exports.changeAttribute = (element, attribute, value) => { const { _localName, _namespace, _value } = attribute; queueAttributeMutationRecord(element, _localName, _namespace, _value); if (element._ceState === "custom") { enqueueCECallbackReaction(element, "attributeChangedCallback", [ _localName, _value, value, _namespace ]); } attribute._value = value; // Run jsdom hooks; roughly correspond to spec's "An attribute is set and an attribute is changed." element._attrModified(attribute._qualifiedName, value, _value); }; // https://dom.spec.whatwg.org/#concept-element-attributes-append exports.appendAttribute = function (element, attribute) { const { _localName, _namespace, _value } = attribute; queueAttributeMutationRecord(element, _localName, _namespace, null); if (element._ceState === "custom") { enqueueCECallbackReaction(element, "attributeChangedCallback", [ _localName, null, _value, _namespace ]); } const attributeList = element._attributeList; attributeList.push(attribute); attribute._element = element; // Sync name cache const name = attribute._qualifiedName; const cache = element._attributesByNameMap; let entry = cache.get(name); if (!entry) { entry = []; cache.set(name, entry); } entry.push(attribute); // Run jsdom hooks; roughly correspond to spec's "An attribute is set and an attribute is added." element._attrModified(name, _value, null); }; exports.removeAttribute = function (element, attribute) { // https://dom.spec.whatwg.org/#concept-element-attributes-remove const { _localName, _namespace, _value } = attribute; queueAttributeMutationRecord(element, _localName, _namespace, _value); if (element._ceState === "custom") { enqueueCECallbackReaction(element, "attributeChangedCallback", [ _localName, _value, null, _namespace ]); } const attributeList = element._attributeList; for (let i = 0; i < attributeList.length; ++i) { if (attributeList[i] === attribute) { attributeList.splice(i, 1); attribute._element = null; // Sync name cache const name = attribute._qualifiedName; const cache = element._attributesByNameMap; const entry = cache.get(name); entry.splice(entry.indexOf(attribute), 1); if (entry.length === 0) { cache.delete(name); } // Run jsdom hooks; roughly correspond to spec's "An attribute is removed." element._attrModified(name, null, attribute._value); return; } } }; exports.replaceAttribute = function (element, oldAttr, newAttr) { // https://dom.spec.whatwg.org/#concept-element-attributes-replace const { _localName, _namespace, _value } = oldAttr; queueAttributeMutationRecord(element, _localName, _namespace, _value); if (element._ceState === "custom") { enqueueCECallbackReaction(element, "attributeChangedCallback", [ _localName, _value, newAttr._value, _namespace ]); } const attributeList = element._attributeList; for (let i = 0; i < attributeList.length; ++i) { if (attributeList[i] === oldAttr) { attributeList.splice(i, 1, newAttr); oldAttr._element = null; newAttr._element = element; // Sync name cache const name = newAttr._qualifiedName; const cache = element._attributesByNameMap; let entry = cache.get(name); if (!entry) { entry = []; cache.set(name, entry); } entry.splice(entry.indexOf(oldAttr), 1, newAttr); // Run jsdom hooks; roughly correspond to spec's "An attribute is set and an attribute is changed." element._attrModified(name, newAttr._value, oldAttr._value); return; } } }; exports.getAttributeByName = function (element, name) { // https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name if (element._namespaceURI === HTML_NS && element._ownerDocument._parsingMode === "html") { name = asciiLowercase(name); } const cache = element._attributesByNameMap; const entry = cache.get(name); if (!entry) { return null; } return entry[0]; }; exports.getAttributeByNameNS = function (element, namespace, localName) { // https://dom.spec.whatwg.org/#concept-element-attributes-get-by-namespace if (namespace === "") { namespace = null; } const attributeList = element._attributeList; for (let i = 0; i < attributeList.length; ++i) { const attr = attributeList[i]; if (attr._namespace === namespace && attr._localName === localName) { return attr; } } return null; }; // Both of the following functions implement https://dom.spec.whatwg.org/#concept-element-attributes-get-value. // Separated them into two to keep symmetry with other functions. exports.getAttributeValue = function (element, localName) { const attr = exports.getAttributeByNameNS(element, null, localName); if (!attr) { return ""; } return attr._value; }; exports.getAttributeValueNS = function (element, namespace, localName) { const attr = exports.getAttributeByNameNS(element, namespace, localName); if (!attr) { return ""; } return attr._value; }; exports.setAttribute = function (element, attr) { // https://dom.spec.whatwg.org/#concept-element-attributes-set if (attr._element !== null && attr._element !== element) { throw DOMException.create(element._globalObject, ["The attribute is in use.", "InUseAttributeError"]); } const oldAttr = exports.getAttributeByNameNS(element, attr._namespace, attr._localName); if (oldAttr === attr) { return attr; } if (oldAttr !== null) { exports.replaceAttribute(element, oldAttr, attr); } else { exports.appendAttribute(element, attr); } return oldAttr; }; exports.setAttributeValue = function (element, localName, value, prefix, namespace) { // https://dom.spec.whatwg.org/#concept-element-attributes-set-value if (prefix === undefined) { prefix = null; } if (namespace === undefined) { namespace = null; } const attribute = exports.getAttributeByNameNS(element, namespace, localName); if (attribute === null) { const newAttribute = element._ownerDocument._createAttribute({ namespace, namespacePrefix: prefix, localName, value }); exports.appendAttribute(element, newAttribute); return; } exports.changeAttribute(element, attribute, value); }; // https://dom.spec.whatwg.org/#set-an-existing-attribute-value exports.setAnExistingAttributeValue = (attribute, value) => { const element = attribute._element; if (element === null) { attribute._value = value; } else { exports.changeAttribute(element, attribute, value); } }; exports.removeAttributeByName = function (element, name) { // https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-name const attr = exports.getAttributeByName(element, name); if (attr !== null) { exports.removeAttribute(element, attr); } return attr; }; exports.removeAttributeByNameNS = function (element, namespace, localName) { // https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-namespace const attr = exports.getAttributeByNameNS(element, namespace, localName); if (attr !== null) { exports.removeAttribute(element, attr); } return attr; }; exports.attributeNames = function (element) { // Needed by https://dom.spec.whatwg.org/#dom-element-getattributenames return element._attributeList.map(a => a._qualifiedName); }; exports.hasAttributes = function (element) { // Needed by https://dom.spec.whatwg.org/#dom-element-hasattributes return element._attributeList.length > 0; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/attributes.js
attributes.js
"use strict"; const { appendAttribute } = require("jsdom/lib/jsdom/living/attributes"); const NODE_TYPE = require("jsdom/lib/jsdom/living/node-type"); const orderedSetParse = require("jsdom/lib/jsdom/living/helpers/ordered-set").parse; const { createElement } = require("jsdom/lib/jsdom/living/helpers/create-element"); const { HTML_NS, XMLNS_NS } = require("jsdom/lib/jsdom/living/helpers/namespaces"); const { cloningSteps, domSymbolTree } = require("jsdom/lib/jsdom/living/helpers/internal-constants"); const { asciiCaseInsensitiveMatch, asciiLowercase } = require("jsdom/lib/jsdom/living/helpers/strings"); const HTMLCollection = require("jsdom/lib/jsdom/living/generated/HTMLCollection"); exports.clone = (node, document, cloneChildren) => { if (document === undefined) { document = node._ownerDocument; } let copy; switch (node.nodeType) { case NODE_TYPE.DOCUMENT_NODE: // Can't use a simple `Document.createImpl` because of circular dependency issues :-/ copy = node._cloneDocument(); break; case NODE_TYPE.DOCUMENT_TYPE_NODE: copy = document.implementation.createDocumentType(node.name, node.publicId, node.systemId); break; case NODE_TYPE.ELEMENT_NODE: copy = createElement( document, node._localName, node._namespaceURI, node._prefix, node._isValue, false ); for (const attribute of node._attributeList) { appendAttribute(copy, exports.clone(attribute, document)); } break; case NODE_TYPE.ATTRIBUTE_NODE: copy = document._createAttribute({ namespace: node._namespace, namespacePrefix: node._namespacePrefix, localName: node._localName, value: node._value }); break; case NODE_TYPE.TEXT_NODE: copy = document.createTextNode(node._data); break; case NODE_TYPE.CDATA_SECTION_NODE: copy = document.createCDATASection(node._data); break; case NODE_TYPE.COMMENT_NODE: copy = document.createComment(node._data); break; case NODE_TYPE.PROCESSING_INSTRUCTION_NODE: copy = document.createProcessingInstruction(node.target, node._data); break; case NODE_TYPE.DOCUMENT_FRAGMENT_NODE: copy = document.createDocumentFragment(); break; } if (node[cloningSteps]) { node[cloningSteps](copy, node, document, cloneChildren); } if (cloneChildren) { for (const child of domSymbolTree.childrenIterator(node)) { const childCopy = exports.clone(child, document, true); copy._append(childCopy); } } return copy; }; // For the following, memoization is not applied here since the memoized results are stored on `this`. exports.listOfElementsWithClassNames = (classNames, root) => { // https://dom.spec.whatwg.org/#concept-getElementsByClassName const classes = orderedSetParse(classNames); if (classes.size === 0) { return HTMLCollection.createImpl(root._globalObject, [], { element: root, query: () => [] }); } return HTMLCollection.createImpl(root._globalObject, [], { element: root, query: () => { const isQuirksMode = root._ownerDocument.compatMode === "BackCompat"; return domSymbolTree.treeToArray(root, { filter(node) { if (node.nodeType !== NODE_TYPE.ELEMENT_NODE || node === root) { return false; } const { classList } = node; if (isQuirksMode) { for (const className of classes) { if (!classList.tokenSet.some(cur => asciiCaseInsensitiveMatch(cur, className))) { return false; } } } else { for (const className of classes) { if (!classList.tokenSet.contains(className)) { return false; } } } return true; } }); } }); }; exports.listOfElementsWithQualifiedName = (qualifiedName, root) => { // https://dom.spec.whatwg.org/#concept-getelementsbytagname if (qualifiedName === "*") { return HTMLCollection.createImpl(root._globalObject, [], { element: root, query: () => domSymbolTree.treeToArray(root, { filter: node => node.nodeType === NODE_TYPE.ELEMENT_NODE && node !== root }) }); } if (root._ownerDocument._parsingMode === "html") { const lowerQualifiedName = asciiLowercase(qualifiedName); return HTMLCollection.createImpl(root._globalObject, [], { element: root, query: () => domSymbolTree.treeToArray(root, { filter(node) { if (node.nodeType !== NODE_TYPE.ELEMENT_NODE || node === root) { return false; } if (node._namespaceURI === HTML_NS) { return node._qualifiedName === lowerQualifiedName; } return node._qualifiedName === qualifiedName; } }) }); } return HTMLCollection.createImpl(root._globalObject, [], { element: root, query: () => domSymbolTree.treeToArray(root, { filter(node) { if (node.nodeType !== NODE_TYPE.ELEMENT_NODE || node === root) { return false; } return node._qualifiedName === qualifiedName; } }) }); }; exports.listOfElementsWithNamespaceAndLocalName = (namespace, localName, root) => { // https://dom.spec.whatwg.org/#concept-getelementsbytagnamens if (namespace === "") { namespace = null; } if (namespace === "*" && localName === "*") { return HTMLCollection.createImpl(root._globalObject, [], { element: root, query: () => domSymbolTree.treeToArray(root, { filter: node => node.nodeType === NODE_TYPE.ELEMENT_NODE && node !== root }) }); } if (namespace === "*") { return HTMLCollection.createImpl(root._globalObject, [], { element: root, query: () => domSymbolTree.treeToArray(root, { filter(node) { if (node.nodeType !== NODE_TYPE.ELEMENT_NODE || node === root) { return false; } return node._localName === localName; } }) }); } if (localName === "*") { return HTMLCollection.createImpl(root._globalObject, [], { element: root, query: () => domSymbolTree.treeToArray(root, { filter(node) { if (node.nodeType !== NODE_TYPE.ELEMENT_NODE || node === root) { return false; } return node._namespaceURI === namespace; } }) }); } return HTMLCollection.createImpl(root._globalObject, [], { element: root, query: () => domSymbolTree.treeToArray(root, { filter(node) { if (node.nodeType !== NODE_TYPE.ELEMENT_NODE || node === root) { return false; } return node._localName === localName && node._namespaceURI === namespace; } }) }); }; // https://dom.spec.whatwg.org/#converting-nodes-into-a-node // create a fragment (or just return a node for one item) exports.convertNodesIntoNode = (document, nodes) => { if (nodes.length === 1) { // note: I'd prefer to check instanceof Node rather than string return typeof nodes[0] === "string" ? document.createTextNode(nodes[0]) : nodes[0]; } const fragment = document.createDocumentFragment(); for (let i = 0; i < nodes.length; i++) { fragment._append(typeof nodes[i] === "string" ? document.createTextNode(nodes[i]) : nodes[i]); } return fragment; }; // https://dom.spec.whatwg.org/#locate-a-namespace-prefix exports.locateNamespacePrefix = (element, namespace) => { if (element._namespaceURI === namespace && element._prefix !== null) { return element._prefix; } for (const attribute of element._attributeList) { if (attribute._namespacePrefix === "xmlns" && attribute._value === namespace) { return attribute._localName; } } if (element.parentElement !== null) { return exports.locateNamespacePrefix(element.parentElement, namespace); } return null; }; // https://dom.spec.whatwg.org/#locate-a-namespace exports.locateNamespace = (node, prefix) => { switch (node.nodeType) { case NODE_TYPE.ELEMENT_NODE: { if (node._namespaceURI !== null && node._prefix === prefix) { return node._namespaceURI; } if (prefix === null) { for (const attribute of node._attributeList) { if (attribute._namespace === XMLNS_NS && attribute._namespacePrefix === null && attribute._localName === "xmlns") { return attribute._value !== "" ? attribute._value : null; } } } else { for (const attribute of node._attributeList) { if (attribute._namespace === XMLNS_NS && attribute._namespacePrefix === "xmlns" && attribute._localName === prefix) { return attribute._value !== "" ? attribute._value : null; } } } if (node.parentElement === null) { return null; } return exports.locateNamespace(node.parentElement, prefix); } case NODE_TYPE.DOCUMENT_NODE: { if (node.documentElement === null) { return null; } return exports.locateNamespace(node.documentElement, prefix); } case NODE_TYPE.DOCUMENT_TYPE_NODE: case NODE_TYPE.DOCUMENT_FRAGMENT_NODE: { return null; } case NODE_TYPE.ATTRIBUTE_NODE: { if (node._element === null) { return null; } return exports.locateNamespace(node._element, prefix); } default: { if (node.parentElement === null) { return null; } return exports.locateNamespace(node.parentElement, prefix); } } };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/node.js
node.js
"use strict"; // https://infra.spec.whatwg.org/#ascii-whitespace const asciiWhitespaceRe = /^[\t\n\f\r ]$/; exports.asciiWhitespaceRe = asciiWhitespaceRe; // https://infra.spec.whatwg.org/#ascii-lowercase exports.asciiLowercase = s => { return s.replace(/[A-Z]/g, l => l.toLowerCase()); }; // https://infra.spec.whatwg.org/#ascii-uppercase exports.asciiUppercase = s => { return s.replace(/[a-z]/g, l => l.toUpperCase()); }; // https://infra.spec.whatwg.org/#strip-newlines exports.stripNewlines = s => { return s.replace(/[\n\r]+/g, ""); }; // https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace exports.stripLeadingAndTrailingASCIIWhitespace = s => { return s.replace(/^[ \t\n\f\r]+/, "").replace(/[ \t\n\f\r]+$/, ""); }; // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace exports.stripAndCollapseASCIIWhitespace = s => { return s.replace(/[ \t\n\f\r]+/g, " ").replace(/^[ \t\n\f\r]+/, "").replace(/[ \t\n\f\r]+$/, ""); }; // https://html.spec.whatwg.org/multipage/infrastructure.html#valid-simple-colour exports.isValidSimpleColor = s => { return /^#[a-fA-F\d]{6}$/.test(s); }; // https://infra.spec.whatwg.org/#ascii-case-insensitive exports.asciiCaseInsensitiveMatch = (a, b) => { if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; ++i) { if ((a.charCodeAt(i) | 32) !== (b.charCodeAt(i) | 32)) { return false; } } return true; }; // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#rules-for-parsing-integers // Error is represented as null. const parseInteger = exports.parseInteger = input => { // The implementation here is slightly different from the spec's. We want to use parseInt(), but parseInt() trims // Unicode whitespace in addition to just ASCII ones, so we make sure that the trimmed prefix contains only ASCII // whitespace ourselves. const numWhitespace = input.length - input.trimStart().length; if (/[^\t\n\f\r ]/.test(input.slice(0, numWhitespace))) { return null; } // We don't allow hexadecimal numbers here. // eslint-disable-next-line radix const value = parseInt(input, 10); if (Number.isNaN(value)) { return null; } // parseInt() returns -0 for "-0". Normalize that here. return value === 0 ? 0 : value; }; // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#rules-for-parsing-non-negative-integers // Error is represented as null. exports.parseNonNegativeInteger = input => { const value = parseInteger(input); if (value === null) { return null; } if (value < 0) { return null; } return value; }; // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-floating-point-number const floatingPointNumRe = /^-?(?:\d+|\d*\.\d+)(?:[eE][-+]?\d+)?$/; exports.isValidFloatingPointNumber = str => floatingPointNumRe.test(str); // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#rules-for-parsing-floating-point-number-values // Error is represented as null. exports.parseFloatingPointNumber = str => { // The implementation here is slightly different from the spec's. We need to use parseFloat() in order to retain // accuracy, but parseFloat() trims Unicode whitespace in addition to just ASCII ones, so we make sure that the // trimmed prefix contains only ASCII whitespace ourselves. const numWhitespace = str.length - str.trimStart().length; if (/[^\t\n\f\r ]/.test(str.slice(0, numWhitespace))) { return null; } const parsed = parseFloat(str); return isFinite(parsed) ? parsed : null; }; // https://infra.spec.whatwg.org/#split-on-ascii-whitespace exports.splitOnASCIIWhitespace = str => { let position = 0; const tokens = []; while (position < str.length && asciiWhitespaceRe.test(str[position])) { position++; } if (position === str.length) { return tokens; } while (position < str.length) { const start = position; while (position < str.length && !asciiWhitespaceRe.test(str[position])) { position++; } tokens.push(str.slice(start, position)); while (position < str.length && asciiWhitespaceRe.test(str[position])) { position++; } } return tokens; }; // https://infra.spec.whatwg.org/#split-on-commas exports.splitOnCommas = str => { let position = 0; const tokens = []; while (position < str.length) { let start = position; while (position < str.length && str[position] !== ",") { position++; } let end = position; while (start < str.length && asciiWhitespaceRe.test(str[start])) { start++; } while (end > start && asciiWhitespaceRe.test(str[end - 1])) { end--; } tokens.push(str.slice(start, end)); if (position < str.length) { position++; } } return tokens; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/helpers/strings.js
strings.js
"use strict"; const xnv = require("xml-name-validator"); const DOMException = require("domexception/webidl2js-wrapper"); const { XML_NS, XMLNS_NS } = require("jsdom/lib/jsdom/living/helpers/namespaces"); // https://dom.spec.whatwg.org/#validate exports.name = function (globalObject, name) { const result = xnv.name(name); if (!result.success) { throw DOMException.create(globalObject, [ "\"" + name + "\" did not match the Name production: " + result.error, "InvalidCharacterError" ]); } }; exports.qname = function (globalObject, qname) { exports.name(globalObject, qname); const result = xnv.qname(qname); if (!result.success) { throw DOMException.create(globalObject, [ "\"" + qname + "\" did not match the QName production: " + result.error, "InvalidCharacterError" ]); } }; exports.validateAndExtract = function (globalObject, namespace, qualifiedName) { if (namespace === "") { namespace = null; } exports.qname(globalObject, qualifiedName); let prefix = null; let localName = qualifiedName; const colonIndex = qualifiedName.indexOf(":"); if (colonIndex !== -1) { prefix = qualifiedName.substring(0, colonIndex); localName = qualifiedName.substring(colonIndex + 1); } if (prefix !== null && namespace === null) { throw DOMException.create(globalObject, [ "A namespace was given but a prefix was also extracted from the qualifiedName", "NamespaceError" ]); } if (prefix === "xml" && namespace !== XML_NS) { throw DOMException.create(globalObject, [ "A prefix of \"xml\" was given but the namespace was not the XML namespace", "NamespaceError" ]); } if ((qualifiedName === "xmlns" || prefix === "xmlns") && namespace !== XMLNS_NS) { throw DOMException.create(globalObject, [ "A prefix or qualifiedName of \"xmlns\" was given but the namespace was not the XMLNS namespace", "NamespaceError" ]); } if (namespace === XMLNS_NS && qualifiedName !== "xmlns" && prefix !== "xmlns") { throw DOMException.create(globalObject, [ "The XMLNS namespace was given but neither the prefix nor qualifiedName was \"xmlns\"", "NamespaceError" ]); } return { namespace, prefix, localName }; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/helpers/validate-names.js
validate-names.js
"use strict"; const cssom = require("cssom"); const defaultStyleSheet = require("jsdom/lib/jsdom/browser/default-stylesheet"); const { matchesDontThrow } = require("jsdom/lib/jsdom/living/helpers/selectors"); const { forEach, indexOf } = Array.prototype; let parsedDefaultStyleSheet; // Properties for which getResolvedValue is implemented. This is less than // every supported property. // https://drafts.csswg.org/indexes/#properties exports.propertiesWithResolvedValueImplemented = { __proto__: null, // https://drafts.csswg.org/css2/visufx.html#visibility visibility: { inherited: true, initial: "visible", computedValue: "as-specified" } }; exports.forEachMatchingSheetRuleOfElement = (elementImpl, handleRule) => { function handleSheet(sheet) { forEach.call(sheet.cssRules, rule => { if (rule.media) { if (indexOf.call(rule.media, "screen") !== -1) { forEach.call(rule.cssRules, innerRule => { if (matches(innerRule, elementImpl)) { handleRule(innerRule); } }); } } else if (matches(rule, elementImpl)) { handleRule(rule); } }); } if (!parsedDefaultStyleSheet) { parsedDefaultStyleSheet = cssom.parse(defaultStyleSheet); } handleSheet(parsedDefaultStyleSheet); forEach.call(elementImpl._ownerDocument.styleSheets._list, handleSheet); }; function matches(rule, element) { return matchesDontThrow(element, rule.selectorText); } // Naive implementation of https://drafts.csswg.org/css-cascade-4/#cascading // based on the previous jsdom implementation of getComputedStyle. // Does not implement https://drafts.csswg.org/css-cascade-4/#cascade-specificity, // or rather specificity is only implemented by the order in which the matching // rules appear. The last rule is the most specific while the first rule is // the least specific. function getCascadedPropertyValue(element, property) { let value = ""; exports.forEachMatchingSheetRuleOfElement(element, rule => { value = rule.style.getPropertyValue(property); }); const inlineValue = element.style.getPropertyValue(property); if (inlineValue !== "" && inlineValue !== null) { value = inlineValue; } return value; } // https://drafts.csswg.org/css-cascade-4/#specified-value function getSpecifiedValue(element, property) { const cascade = getCascadedPropertyValue(element, property); if (cascade !== "") { return cascade; } // Defaulting const { initial, inherited } = exports.propertiesWithResolvedValueImplemented[property]; if (inherited && element.parentElement !== null) { return getComputedValue(element.parentElement, property); } // root element without parent element or inherited property return initial; } // https://drafts.csswg.org/css-cascade-4/#computed-value function getComputedValue(element, property) { const { computedValue } = exports.propertiesWithResolvedValueImplemented[property]; if (computedValue === "as-specified") { return getSpecifiedValue(element, property); } throw new TypeError(`Internal error: unrecognized computed value instruction '${computedValue}'`); } // https://drafts.csswg.org/cssom/#resolved-value // Only implements `visibility` exports.getResolvedValue = (element, property) => { // Determined for special case properties, none of which are implemented here. // So we skip to "any other property: The resolved value is the computed value." return getComputedValue(element, property); };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/helpers/style-rules.js
style-rules.js
"use strict"; const { parseFloatingPointNumber } = require("jsdom/lib/jsdom/living/helpers/strings"); const { parseDateString, parseLocalDateAndTimeString, parseMonthString, parseTimeString, parseWeekString, serializeDate, serializeMonth, serializeNormalizedDateAndTime, serializeTime, serializeWeek, parseDateAsWeek } = require("jsdom/lib/jsdom/living/helpers/dates-and-times"); // Necessary because Date.UTC() treats year within [0, 99] as [1900, 1999]. function getUTCMs(year, month = 1, day = 1, hour = 0, minute = 0, second = 0, millisecond = 0) { if (year > 99 || year < 0) { return Date.UTC(year, month - 1, day, hour, minute, second, millisecond); } const d = new Date(0); d.setUTCFullYear(year); d.setUTCMonth(month - 1); d.setUTCDate(day); d.setUTCHours(hour); d.setUTCMinutes(minute); d.setUTCSeconds(second, millisecond); return d.valueOf(); } const dayOfWeekRelMondayLUT = [-1, 0, 1, 2, 3, -3, -2]; exports.convertStringToNumberByType = { // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):concept-input-value-string-number date(input) { const date = parseDateString(input); if (date === null) { return null; } return getUTCMs(date.year, date.month, date.day); }, // https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month):concept-input-value-string-number month(input) { const date = parseMonthString(input); if (date === null) { return null; } return (date.year - 1970) * 12 + (date.month - 1); }, // https://html.spec.whatwg.org/multipage/input.html#week-state-(type=week):concept-input-value-string-number week(input) { const date = parseWeekString(input); if (date === null) { return null; } const dateObj = new Date(getUTCMs(date.year)); // An HTML week starts on Monday, while 0 represents Sunday. Account for such. const dayOfWeekRelMonday = dayOfWeekRelMondayLUT[dateObj.getUTCDay()]; return dateObj.setUTCDate(1 + 7 * (date.week - 1) - dayOfWeekRelMonday); }, // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):concept-input-value-string-number time(input) { const time = parseTimeString(input); if (time === null) { return null; } return ((time.hour * 60 + time.minute) * 60 + time.second) * 1000 + time.millisecond; }, // https://html.spec.whatwg.org/multipage/input.html#local-date-and-time-state-(type=datetime-local):concept-input-value-string-number "datetime-local"(input) { const dateAndTime = parseLocalDateAndTimeString(input); if (dateAndTime === null) { return null; } const { date: { year, month, day }, time: { hour, minute, second, millisecond } } = dateAndTime; // Doesn't quite matter whether or not UTC is used, since the offset from 1970-01-01 local time is returned. return getUTCMs(year, month, day, hour, minute, second, millisecond); }, // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-value-string-number number: parseFloatingPointNumber, // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-value-string-number range: parseFloatingPointNumber }; exports.convertStringToDateByType = { date(input) { const parsedInput = exports.convertStringToNumberByType.date(input); return parsedInput === null ? null : new Date(parsedInput); }, // https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month):concept-input-value-string-number month(input) { const parsedMonthString = parseMonthString(input); if (parsedMonthString === null) { return null; } const date = new Date(0); date.setUTCFullYear(parsedMonthString.year); date.setUTCMonth(parsedMonthString.month - 1); return date; }, week(input) { const parsedInput = exports.convertStringToNumberByType.week(input); return parsedInput === null ? null : new Date(parsedInput); }, time(input) { const parsedInput = exports.convertStringToNumberByType.time(input); return parsedInput === null ? null : new Date(parsedInput); }, "datetime-local"(input) { const parsedInput = exports.convertStringToNumberByType["datetime-local"](input); return parsedInput === null ? null : new Date(parsedInput); } }; exports.serializeDateByType = { date(input) { return serializeDate({ year: input.getUTCFullYear(), month: input.getUTCMonth() + 1, day: input.getUTCDate() }); }, month(input) { return serializeMonth({ year: input.getUTCFullYear(), month: input.getUTCMonth() + 1 }); }, week(input) { return serializeWeek(parseDateAsWeek(input)); }, time(input) { return serializeTime({ hour: input.getUTCHours(), minute: input.getUTCMinutes(), second: input.getUTCSeconds(), millisecond: input.getUTCMilliseconds() }); }, "datetime-local"(input) { return serializeNormalizedDateAndTime({ date: { year: input.getUTCFullYear(), month: input.getUTCMonth() + 1, day: input.getUTCDate() }, time: { hour: input.getUTCHours(), minute: input.getUTCMinutes(), second: input.getUTCSeconds(), millisecond: input.getUTCMilliseconds() } }); } }; exports.convertNumberToStringByType = { // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):concept-input-value-string-number date(input) { return exports.serializeDateByType.date(new Date(input)); }, // https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month):concept-input-value-string-date month(input) { const year = 1970 + Math.floor(input / 12); const month = input % 12; const date = new Date(0); date.setUTCFullYear(year); date.setUTCMonth(month); return exports.serializeDateByType.month(date); }, // https://html.spec.whatwg.org/multipage/input.html#week-state-(type=week):concept-input-value-string-date week(input) { return exports.serializeDateByType.week(new Date(input)); }, // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):concept-input-value-string-date time(input) { return exports.serializeDateByType.time(new Date(input)); }, // https://html.spec.whatwg.org/multipage/input.html#local-date-and-time-state-(type=datetime-local):concept-input-value-number-string "datetime-local"(input) { return exports.serializeDateByType["datetime-local"](new Date(input)); }, // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-value-number-string number(input) { return input.toString(); }, // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-value-number-string range(input) { return input.toString(); } };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/helpers/number-and-date-inputs.js
number-and-date-inputs.js
"use strict"; const { domSymbolTree } = require("jsdom/lib/jsdom/living/helpers/internal-constants"); const { HTML_NS } = require("jsdom/lib/jsdom/living/helpers/namespaces"); // All these operate on and return impls, not wrappers! exports.closest = (e, localName, namespace = HTML_NS) => { while (e) { if (e.localName === localName && e.namespaceURI === namespace) { return e; } e = domSymbolTree.parent(e); } return null; }; exports.childrenByLocalName = (parent, localName, namespace = HTML_NS) => { return domSymbolTree.childrenToArray(parent, { filter(node) { return node._localName === localName && node._namespaceURI === namespace; } }); }; exports.descendantsByLocalName = (parent, localName, namespace = HTML_NS) => { return domSymbolTree.treeToArray(parent, { filter(node) { return node._localName === localName && node._namespaceURI === namespace && node !== parent; } }); }; exports.childrenByLocalNames = (parent, localNamesSet, namespace = HTML_NS) => { return domSymbolTree.childrenToArray(parent, { filter(node) { return localNamesSet.has(node._localName) && node._namespaceURI === namespace; } }); }; exports.descendantsByLocalNames = (parent, localNamesSet, namespace = HTML_NS) => { return domSymbolTree.treeToArray(parent, { filter(node) { return localNamesSet.has(node._localName) && node._namespaceURI === namespace && node !== parent; } }); }; exports.firstChildWithLocalName = (parent, localName, namespace = HTML_NS) => { const iterator = domSymbolTree.childrenIterator(parent); for (const child of iterator) { if (child._localName === localName && child._namespaceURI === namespace) { return child; } } return null; }; exports.firstChildWithLocalNames = (parent, localNamesSet, namespace = HTML_NS) => { const iterator = domSymbolTree.childrenIterator(parent); for (const child of iterator) { if (localNamesSet.has(child._localName) && child._namespaceURI === namespace) { return child; } } return null; }; exports.firstDescendantWithLocalName = (parent, localName, namespace = HTML_NS) => { const iterator = domSymbolTree.treeIterator(parent); for (const descendant of iterator) { if (descendant._localName === localName && descendant._namespaceURI === namespace) { return descendant; } } return null; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/helpers/traversal.js
traversal.js
"use strict"; // https://infra.spec.whatwg.org/#sets // // Only use this class if a Set cannot be used, e.g. when "replace" operation is needed, since there's no way to replace // an element while keep the relative order using a Set, only remove and then add something at the end. module.exports = class OrderedSet { constructor() { this._items = []; } append(item) { if (!this.contains(item)) { this._items.push(item); } } prepend(item) { if (!this.contains(item)) { this._items.unshift(item); } } replace(item, replacement) { let seen = false; for (let i = 0; i < this._items.length;) { const isInstance = this._items[i] === item || this._items[i] === replacement; if (seen && isInstance) { this._items.splice(i, 1); } else { if (isInstance) { this._items[i] = replacement; seen = true; } i++; } } } remove(...items) { this.removePredicate(item => items.includes(item)); } removePredicate(predicate) { for (let i = 0; i < this._items.length;) { if (predicate(this._items[i])) { this._items.splice(i, 1); } else { i++; } } } empty() { this._items.length = 0; } contains(item) { return this._items.includes(item); } get size() { return this._items.length; } isEmpty() { return this._items.length === 0; } // Useful for other parts of jsdom [Symbol.iterator]() { return this._items[Symbol.iterator](); } keys() { return this._items.keys(); } get(index) { return this._items[index]; } some(func) { return this._items.some(func); } // https://dom.spec.whatwg.org/#concept-ordered-set-parser static parse(input) { const tokens = new OrderedSet(); for (const token of input.split(/[\t\n\f\r ]+/)) { if (token) { tokens.append(token); } } return tokens; } // https://dom.spec.whatwg.org/#concept-ordered-set-serializer serialize() { return this._items.join(" "); } };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/helpers/ordered-set.js
ordered-set.js
"use strict"; const { isValidFloatingPointNumber, isValidSimpleColor, parseFloatingPointNumber, stripLeadingAndTrailingASCIIWhitespace, stripNewlines, splitOnCommas } = require("jsdom/lib/jsdom/living/helpers/strings"); const { isValidDateString, isValidMonthString, isValidTimeString, isValidWeekString, parseLocalDateAndTimeString, serializeNormalizedDateAndTime } = require("jsdom/lib/jsdom/living/helpers/dates-and-times"); const whatwgURL = require("whatwg-url"); const NodeList = require("jsdom/lib/jsdom/living/generated/NodeList"); const { domSymbolTree } = require("jsdom/lib/jsdom/living/helpers/internal-constants"); const { closest, firstChildWithLocalName } = require("jsdom/lib/jsdom/living/helpers/traversal"); const NODE_TYPE = require("jsdom/lib/jsdom/living/node-type"); const { HTML_NS } = require("jsdom/lib/jsdom/living/helpers/namespaces"); // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#concept-fe-disabled exports.isDisabled = formControl => { if (formControl.localName === "button" || formControl.localName === "input" || formControl.localName === "select" || formControl.localName === "textarea") { if (formControl.hasAttributeNS(null, "disabled")) { return true; } } let e = formControl.parentNode; while (e) { if (e.localName === "fieldset" && e.hasAttributeNS(null, "disabled")) { const firstLegendElementChild = firstChildWithLocalName(e, "legend"); if (!firstLegendElementChild || !firstLegendElementChild.contains(formControl)) { return true; } } e = e.parentNode; } return false; }; // https://html.spec.whatwg.org/multipage/forms.html#category-listed const listedElements = new Set(["button", "fieldset", "input", "object", "output", "select", "textarea"]); exports.isListed = formControl => listedElements.has(formControl._localName) && formControl.namespaceURI === HTML_NS; // https://html.spec.whatwg.org/multipage/forms.html#category-submit const submittableElements = new Set(["button", "input", "object", "select", "textarea"]); exports.isSubmittable = formControl => { return submittableElements.has(formControl._localName) && formControl.namespaceURI === HTML_NS; }; // https://html.spec.whatwg.org/multipage/forms.html#concept-submit-button const submitButtonInputTypes = new Set(["submit", "image"]); exports.isSubmitButton = formControl => { return ((formControl._localName === "input" && submitButtonInputTypes.has(formControl.type)) || (formControl._localName === "button" && formControl.type === "submit")) && formControl.namespaceURI === HTML_NS; }; // https://html.spec.whatwg.org/multipage/forms.html#concept-button const buttonInputTypes = new Set([...submitButtonInputTypes, "reset", "button"]); exports.isButton = formControl => { return ((formControl._localName === "input" && buttonInputTypes.has(formControl.type)) || formControl._localName === "button") && formControl.namespaceURI === HTML_NS; }; exports.normalizeToCRLF = string => { return string.replace(/\r([^\n])/g, "\r\n$1") .replace(/\r$/, "\r\n") .replace(/([^\r])\n/g, "$1\r\n") .replace(/^\n/, "\r\n"); }; // https://html.spec.whatwg.org/multipage/dom.html#interactive-content-2 exports.isInteractiveContent = node => { if (node.nodeType !== NODE_TYPE.ELEMENT_NODE) { return false; } if (node.namespaceURI !== HTML_NS) { return false; } if (node.hasAttributeNS(null, "tabindex")) { return true; } switch (node.localName) { case "a": return node.hasAttributeNS(null, "href"); case "audio": case "video": return node.hasAttributeNS(null, "controls"); case "img": case "object": return node.hasAttributeNS(null, "usemap"); case "input": return node.type !== "hidden"; case "button": case "details": case "embed": case "iframe": case "label": case "select": case "textarea": return true; } return false; }; // https://html.spec.whatwg.org/multipage/forms.html#category-label exports.isLabelable = node => { if (node.nodeType !== NODE_TYPE.ELEMENT_NODE) { return false; } if (node.namespaceURI !== HTML_NS) { return false; } switch (node.localName) { case "button": case "meter": case "output": case "progress": case "select": case "textarea": return true; case "input": return node.type !== "hidden"; } return false; }; exports.getLabelsForLabelable = labelable => { if (!exports.isLabelable(labelable)) { return null; } if (!labelable._labels) { const root = labelable.getRootNode({}); labelable._labels = NodeList.create(root._globalObject, [], { element: root, query: () => { const nodes = []; for (const descendant of domSymbolTree.treeIterator(root)) { if (descendant.control === labelable) { nodes.push(descendant); } } return nodes; } }); } return labelable._labels; }; // https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address exports.isValidEmailAddress = (emailAddress, multiple = false) => { const emailAddressRegExp = new RegExp("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9]" + "(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}" + "[a-zA-Z0-9])?)*$"); // A valid e-mail address list is a set of comma-separated tokens, where each token is itself // a valid e - mail address.To obtain the list of tokens from a valid e - mail address list, // an implementation must split the string on commas. if (multiple) { return splitOnCommas(emailAddress).every(value => emailAddressRegExp.test(value)); } return emailAddressRegExp.test(emailAddress); }; exports.isValidAbsoluteURL = url => { return whatwgURL.parseURL(url) !== null; }; exports.sanitizeValueByType = (input, val) => { switch (input.type.toLowerCase()) { case "password": case "search": case "tel": case "text": val = stripNewlines(val); break; case "color": // https://html.spec.whatwg.org/multipage/forms.html#color-state-(type=color):value-sanitization-algorithm val = isValidSimpleColor(val) ? val.toLowerCase() : "#000000"; break; case "date": // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):value-sanitization-algorithm if (!isValidDateString(val)) { val = ""; } break; case "datetime-local": { // https://html.spec.whatwg.org/multipage/input.html#local-date-and-time-state-(type=datetime-local):value-sanitization-algorithm const dateAndTime = parseLocalDateAndTimeString(val); val = dateAndTime !== null ? serializeNormalizedDateAndTime(dateAndTime) : ""; break; } case "email": // https://html.spec.whatwg.org/multipage/forms.html#e-mail-state-(type=email):value-sanitization-algorithm // https://html.spec.whatwg.org/multipage/forms.html#e-mail-state-(type=email):value-sanitization-algorithm-2 if (input.hasAttributeNS(null, "multiple")) { val = val.split(",").map(token => stripLeadingAndTrailingASCIIWhitespace(token)).join(","); } else { val = stripNewlines(val); val = stripLeadingAndTrailingASCIIWhitespace(val); } break; case "month": // https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month):value-sanitization-algorithm if (!isValidMonthString(val)) { val = ""; } break; case "number": // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):value-sanitization-algorithm // TODO: using parseFloatingPointNumber in addition to isValidFloatingPointNumber to pass number.html WPT. // Possible spec bug. if (!isValidFloatingPointNumber(val) || parseFloatingPointNumber(val) === null) { val = ""; } break; case "range": // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):value-sanitization-algorithm // TODO: using parseFloatingPointNumber in addition to isValidFloatingPointNumber to pass number.html WPT. // Possible spec bug. if (!isValidFloatingPointNumber(val) || parseFloatingPointNumber(val) === null) { const minimum = input._minimum; const maximum = input._maximum; const defaultValue = maximum < minimum ? minimum : (minimum + maximum) / 2; val = `${defaultValue}`; } else if (val < input._minimum) { val = `${input._minimum}`; } else if (val > input._maximum) { val = `${input._maximum}`; } break; case "time": // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):value-sanitization-algorithm if (!isValidTimeString(val)) { val = ""; } break; case "url": // https://html.spec.whatwg.org/multipage/forms.html#url-state-(type=url):value-sanitization-algorithm val = stripNewlines(val); val = stripLeadingAndTrailingASCIIWhitespace(val); break; case "week": // https://html.spec.whatwg.org/multipage/input.html#week-state-(type=week):value-sanitization-algorithm if (!isValidWeekString(val)) { val = ""; } } return val; }; // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#form-owner // TODO: The spec describes an imperative process for assigning/resetting an element's form // owner based on activities involving form-associated elements. This simpler implementation // instead calculates the current form owner only when the property is accessed. This is not // sufficient to pass all the web platform tests, but is good enough for most purposes. We // should eventually update it to use the correct version, though. See // https://github.com/whatwg/html/issues/4050 for some discussion. exports.formOwner = formControl => { const formAttr = formControl.getAttributeNS(null, "form"); if (formAttr === "") { return null; } if (formAttr === null) { return closest(formControl, "form"); } const root = formControl.getRootNode({}); let firstElementWithId; for (const descendant of domSymbolTree.treeIterator(root)) { if (descendant.nodeType === NODE_TYPE.ELEMENT_NODE && descendant.getAttributeNS(null, "id") === formAttr) { firstElementWithId = descendant; break; } } if (firstElementWithId && firstElementWithId.namespaceURI === HTML_NS && firstElementWithId.localName === "form") { return firstElementWithId; } return null; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/helpers/form-controls.js
form-controls.js
"use strict"; function isLeapYear(year) { return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0); } // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#number-of-days-in-month-month-of-year-year const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; function numberOfDaysInMonthOfYear(month, year) { if (month === 2 && isLeapYear(year)) { return 29; } return daysInMonth[month - 1]; } const monthRe = /^([0-9]{4,})-([0-9]{2})$/; // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#parse-a-month-string function parseMonthString(str) { const matches = monthRe.exec(str); if (!matches) { return null; } const year = Number(matches[1]); if (year <= 0) { return null; } const month = Number(matches[2]); if (month < 1 || month > 12) { return null; } return { year, month }; } // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-month-string function isValidMonthString(str) { return parseMonthString(str) !== null; } function serializeMonth({ year, month }) { const yearStr = `${year}`.padStart(4, "0"); const monthStr = `${month}`.padStart(2, "0"); return `${yearStr}-${monthStr}`; } const dateRe = /^([0-9]{4,})-([0-9]{2})-([0-9]{2})$/; // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#parse-a-date-string function parseDateString(str) { const matches = dateRe.exec(str); if (!matches) { return null; } const year = Number(matches[1]); if (year <= 0) { return null; } const month = Number(matches[2]); if (month < 1 || month > 12) { return null; } const day = Number(matches[3]); if (day < 1 || day > numberOfDaysInMonthOfYear(month, year)) { return null; } return { year, month, day }; } // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-date-string function isValidDateString(str) { return parseDateString(str) !== null; } function serializeDate(date) { const dayStr = `${date.day}`.padStart(2, "0"); return `${serializeMonth(date)}-${dayStr}`; } const yearlessDateRe = /^(?:--)?([0-9]{2})-([0-9]{2})$/; // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#parse-a-yearless-date-string function parseYearlessDateString(str) { const matches = yearlessDateRe.exec(str); if (!matches) { return null; } const month = Number(matches[1]); if (month < 1 || month > 12) { return null; } const day = Number(matches[2]); if (day < 1 || day > numberOfDaysInMonthOfYear(month, 4)) { return null; } return { month, day }; } // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-yearless-date-string function isValidYearlessDateString(str) { return parseYearlessDateString(str) !== null; } function serializeYearlessDate({ month, day }) { const monthStr = `${month}`.padStart(2, "0"); const dayStr = `${day}`.padStart(2, "0"); return `${monthStr}-${dayStr}`; } const timeRe = /^([0-9]{2}):([0-9]{2})(?::([0-9]{2}(?:\.([0-9]{1,3}))?))?$/; // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#parse-a-time-string function parseTimeString(str) { const matches = timeRe.exec(str); if (!matches) { return null; } const hour = Number(matches[1]); if (hour < 0 || hour > 23) { return null; } const minute = Number(matches[2]); if (minute < 0 || minute > 59) { return null; } const second = matches[3] !== undefined ? Math.trunc(Number(matches[3])) : 0; if (second < 0 || second >= 60) { return null; } const millisecond = matches[4] !== undefined ? Number(matches[4]) : 0; return { hour, minute, second, millisecond }; } // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-time-string function isValidTimeString(str) { return parseTimeString(str) !== null; } function serializeTime({ hour, minute, second, millisecond }) { const hourStr = `${hour}`.padStart(2, "0"); const minuteStr = `${minute}`.padStart(2, "0"); if (second === 0 && millisecond === 0) { return `${hourStr}:${minuteStr}`; } const secondStr = `${second}`.padStart(2, "0"); const millisecondStr = `${millisecond}`.padStart(3, "0"); return `${hourStr}:${minuteStr}:${secondStr}.${millisecondStr}`; } // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#parse-a-local-date-and-time-string function parseLocalDateAndTimeString(str, normalized = false) { let separatorIdx = str.indexOf("T"); if (separatorIdx < 0 && !normalized) { separatorIdx = str.indexOf(" "); } if (separatorIdx < 0) { return null; } const date = parseDateString(str.slice(0, separatorIdx)); if (date === null) { return null; } const time = parseTimeString(str.slice(separatorIdx + 1)); if (time === null) { return null; } return { date, time }; } // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-local-date-and-time-string function isValidLocalDateAndTimeString(str) { return parseLocalDateAndTimeString(str) !== null; } // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-normalised-local-date-and-time-string function isValidNormalizedLocalDateAndTimeString(str) { return parseLocalDateAndTimeString(str, true) !== null; } function serializeNormalizedDateAndTime({ date, time }) { return `${serializeDate(date)}T${serializeTime(time)}`; } // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#week-number-of-the-last-day // https://stackoverflow.com/a/18538272/1937836 function weekNumberOfLastDay(year) { const jan1 = new Date(year, 0); return jan1.getDay() === 4 || (isLeapYear(year) && jan1.getDay() === 3) ? 53 : 52; } const weekRe = /^([0-9]{4,5})-W([0-9]{2})$/; // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#parse-a-week-string function parseWeekString(str) { const matches = weekRe.exec(str); if (!matches) { return null; } const year = Number(matches[1]); if (year <= 0) { return null; } const week = Number(matches[2]); if (week < 1 || week > weekNumberOfLastDay(year)) { return null; } return { year, week }; } // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-week-string function isValidWeekString(str) { return parseWeekString(str) !== null; } function serializeWeek({ year, week }) { const yearStr = `${year}`.padStart(4, "0"); const weekStr = `${week}`.padStart(2, "0"); return `${yearStr}-W${weekStr}`; } // https://stackoverflow.com/a/6117889 function parseDateAsWeek(originalDate) { const dayInSeconds = 86400000; // Copy date so don't modify original const date = new Date(Date.UTC(originalDate.getUTCFullYear(), originalDate.getUTCMonth(), originalDate.getUTCDate())); // Set to nearest Thursday: current date + 4 - current day number // Make Sunday's day number 7 date.setUTCDate(date.getUTCDate() + 4 - (date.getUTCDay() || 7)); // Get first day of year const yearStart = new Date(Date.UTC(date.getUTCFullYear(), 0, 1)); // Calculate full weeks to nearest Thursday const week = Math.ceil((((date - yearStart) / dayInSeconds) + 1) / 7); return { year: date.getUTCFullYear(), week }; } function isDate(obj) { try { Date.prototype.valueOf.call(obj); return true; } catch { return false; } } module.exports = { isDate, numberOfDaysInMonthOfYear, parseMonthString, isValidMonthString, serializeMonth, parseDateString, isValidDateString, serializeDate, parseYearlessDateString, isValidYearlessDateString, serializeYearlessDate, parseTimeString, isValidTimeString, serializeTime, parseLocalDateAndTimeString, isValidLocalDateAndTimeString, isValidNormalizedLocalDateAndTimeString, serializeNormalizedDateAndTime, parseDateAsWeek, weekNumberOfLastDay, parseWeekString, isValidWeekString, serializeWeek };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/helpers/dates-and-times.js
dates-and-times.js
"use strict"; const DOMException = require("domexception/webidl2js-wrapper"); const isPotentialCustomElementName = require("is-potential-custom-element-name"); const NODE_TYPE = require("jsdom/lib/jsdom/living/node-type"); const { HTML_NS } = require("jsdom/lib/jsdom/living/helpers/namespaces"); const { shadowIncludingRoot } = require("jsdom/lib/jsdom/living/helpers/shadow-dom"); const reportException = require("jsdom/lib/jsdom/living/helpers/runtime-script-errors"); const { implForWrapper, wrapperForImpl } = require("jsdom/lib/jsdom/living/generated/utils"); // https://html.spec.whatwg.org/multipage/custom-elements.html#custom-element-reactions-stack class CEReactionsStack { constructor() { this._stack = []; // https://html.spec.whatwg.org/multipage/custom-elements.html#backup-element-queue this.backupElementQueue = []; // https://html.spec.whatwg.org/multipage/custom-elements.html#processing-the-backup-element-queue this.processingBackupElementQueue = false; } push(elementQueue) { this._stack.push(elementQueue); } pop() { return this._stack.pop(); } get currentElementQueue() { const { _stack } = this; return _stack[_stack.length - 1]; } isEmpty() { return this._stack.length === 0; } } // In theory separate cross-origin Windows created by separate JSDOM instances could have separate stacks. But, we would // need to implement the whole agent architecture. Which is kind of questionable given that we don't run our Windows in // their own separate threads, which is what agents are meant to represent. const customElementReactionsStack = new CEReactionsStack(); // https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions function ceReactionsPreSteps() { customElementReactionsStack.push([]); } function ceReactionsPostSteps() { const queue = customElementReactionsStack.pop(); invokeCEReactions(queue); } const RESTRICTED_CUSTOM_ELEMENT_NAME = new Set([ "annotation-xml", "color-profile", "font-face", "font-face-src", "font-face-uri", "font-face-format", "font-face-name", "missing-glyph" ]); // https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name function isValidCustomElementName(name) { if (RESTRICTED_CUSTOM_ELEMENT_NAME.has(name)) { return false; } return isPotentialCustomElementName(name); } // https://html.spec.whatwg.org/multipage/custom-elements.html#concept-upgrade-an-element function upgradeElement(definition, element) { if (element._ceState !== "undefined" || element._ceState === "uncustomized") { return; } element._ceDefinition = definition; element._ceState = "failed"; for (const attribute of element._attributeList) { const { _localName, _namespace, _value } = attribute; enqueueCECallbackReaction(element, "attributeChangedCallback", [_localName, null, _value, _namespace]); } if (shadowIncludingRoot(element).nodeType === NODE_TYPE.DOCUMENT_NODE) { enqueueCECallbackReaction(element, "connectedCallback", []); } definition.constructionStack.push(element); const { constructionStack, ctor: C } = definition; let constructionError; try { if (definition.disableShadow === true && element._shadowRoot !== null) { throw DOMException.create(element._globalObject, [ "Can't upgrade a custom element with a shadow root if shadow is disabled", "NotSupportedError" ]); } const constructionResult = new C(); const constructionResultImpl = implForWrapper(constructionResult); if (constructionResultImpl !== element) { throw new TypeError("Invalid custom element constructor return value"); } } catch (error) { constructionError = error; } constructionStack.pop(); if (constructionError !== undefined) { element._ceDefinition = null; element._ceReactionQueue = []; throw constructionError; } element._ceState = "custom"; } // https://html.spec.whatwg.org/#concept-try-upgrade function tryUpgradeElement(element) { const { _ownerDocument, _namespaceURI, _localName, _isValue } = element; const definition = lookupCEDefinition(_ownerDocument, _namespaceURI, _localName, _isValue); if (definition !== null) { enqueueCEUpgradeReaction(element, definition); } } // https://html.spec.whatwg.org/#look-up-a-custom-element-definition function lookupCEDefinition(document, namespace, localName, isValue) { const definition = null; if (namespace !== HTML_NS) { return definition; } if (!document._defaultView) { return definition; } const registry = implForWrapper(document._globalObject.customElements); const definitionByName = registry._customElementDefinitions.find(def => { return def.name === def.localName && def.localName === localName; }); if (definitionByName !== undefined) { return definitionByName; } const definitionByIs = registry._customElementDefinitions.find(def => { return def.name === isValue && def.localName === localName; }); if (definitionByIs !== undefined) { return definitionByIs; } return definition; } // https://html.spec.whatwg.org/multipage/custom-elements.html#invoke-custom-element-reactions function invokeCEReactions(elementQueue) { for (const element of elementQueue) { const reactions = element._ceReactionQueue; try { while (reactions.length > 0) { const reaction = reactions.shift(); switch (reaction.type) { case "upgrade": upgradeElement(reaction.definition, element); break; case "callback": reaction.callback.apply(wrapperForImpl(element), reaction.args); break; } } } catch (error) { reportException(element._globalObject, error); } } } // https://html.spec.whatwg.org/multipage/custom-elements.html#enqueue-an-element-on-the-appropriate-element-queue function enqueueElementOnAppropriateElementQueue(element) { if (customElementReactionsStack.isEmpty()) { customElementReactionsStack.backupElementQueue.push(element); if (customElementReactionsStack.processingBackupElementQueue) { return; } customElementReactionsStack.processingBackupElementQueue = true; Promise.resolve().then(() => { const elementQueue = customElementReactionsStack.backupElementQueue; invokeCEReactions(elementQueue); customElementReactionsStack.processingBackupElementQueue = false; }); } else { customElementReactionsStack.currentElementQueue.push(element); } } // https://html.spec.whatwg.org/multipage/custom-elements.html#enqueue-a-custom-element-callback-reaction function enqueueCECallbackReaction(element, callbackName, args) { const { _ceDefinition: { lifecycleCallbacks, observedAttributes } } = element; const callback = lifecycleCallbacks[callbackName]; if (callback === null) { return; } if (callbackName === "attributeChangedCallback") { const attributeName = args[0]; if (!observedAttributes.includes(attributeName)) { return; } } element._ceReactionQueue.push({ type: "callback", callback, args }); enqueueElementOnAppropriateElementQueue(element); } // https://html.spec.whatwg.org/#enqueue-a-custom-element-upgrade-reaction function enqueueCEUpgradeReaction(element, definition) { element._ceReactionQueue.push({ type: "upgrade", definition }); enqueueElementOnAppropriateElementQueue(element); } module.exports = { customElementReactionsStack, ceReactionsPreSteps, ceReactionsPostSteps, isValidCustomElementName, upgradeElement, tryUpgradeElement, lookupCEDefinition, enqueueCEUpgradeReaction, enqueueCECallbackReaction, invokeCEReactions };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/helpers/custom-elements.js
custom-elements.js
"use strict"; const NODE_TYPE = require("jsdom/lib/jsdom/living/node-type"); const { nodeRoot } = require("jsdom/lib/jsdom/living/helpers/node"); const { HTML_NS } = require("jsdom/lib/jsdom/living/helpers/namespaces"); const { domSymbolTree } = require("jsdom/lib/jsdom/living/helpers/internal-constants"); const { signalSlotList, queueMutationObserverMicrotask } = require("jsdom/lib/jsdom/living/helpers/mutation-observers"); // Valid host element for ShadowRoot. // Defined in: https://dom.spec.whatwg.org/#dom-element-attachshadow const VALID_HOST_ELEMENT_NAME = new Set([ "article", "aside", "blockquote", "body", "div", "footer", "h1", "h2", "h3", "h4", "h5", "h6", "header", "main", "nav", "p", "section", "span" ]); function isValidHostElementName(name) { return VALID_HOST_ELEMENT_NAME.has(name); } // Use an approximation by checking the presence of nodeType instead of instead of using the isImpl from // "../generated/Node" to avoid introduction of circular dependencies. function isNode(nodeImpl) { return Boolean(nodeImpl && "nodeType" in nodeImpl); } // Use an approximation by checking the value of nodeType and presence of nodeType host instead of instead // of using the isImpl from "../generated/ShadowRoot" to avoid introduction of circular dependencies. function isShadowRoot(nodeImpl) { return Boolean(nodeImpl && nodeImpl.nodeType === NODE_TYPE.DOCUMENT_FRAGMENT_NODE && "host" in nodeImpl); } // https://dom.spec.whatwg.org/#concept-slotable function isSlotable(nodeImpl) { return nodeImpl && (nodeImpl.nodeType === NODE_TYPE.ELEMENT_NODE || nodeImpl.nodeType === NODE_TYPE.TEXT_NODE); } function isSlot(nodeImpl) { return nodeImpl && nodeImpl.localName === "slot" && nodeImpl._namespaceURI === HTML_NS; } // https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-ancestor function isShadowInclusiveAncestor(ancestor, node) { while (isNode(node)) { if (node === ancestor) { return true; } if (isShadowRoot(node)) { node = node.host; } else { node = domSymbolTree.parent(node); } } return false; } // https://dom.spec.whatwg.org/#retarget function retarget(a, b) { while (true) { if (!isNode(a)) { return a; } const aRoot = nodeRoot(a); if ( !isShadowRoot(aRoot) || (isNode(b) && isShadowInclusiveAncestor(aRoot, b)) ) { return a; } a = nodeRoot(a).host; } } // https://dom.spec.whatwg.org/#get-the-parent function getEventTargetParent(eventTarget, event) { // _getTheParent will be missing for Window, since it doesn't have an impl class and we don't want to pollute the // user-visible global scope with a _getTheParent value. TODO: remove this entire function and use _getTheParent // directly, once Window gets split into impl/wrapper. return eventTarget._getTheParent ? eventTarget._getTheParent(event) : null; } // https://dom.spec.whatwg.org/#concept-shadow-including-root function shadowIncludingRoot(node) { const root = nodeRoot(node); return isShadowRoot(root) ? shadowIncludingRoot(root.host) : root; } // https://dom.spec.whatwg.org/#assign-a-slot function assignSlot(slotable) { const slot = findSlot(slotable); if (slot) { assignSlotable(slot); } } // https://dom.spec.whatwg.org/#assign-slotables function assignSlotable(slot) { const slotables = findSlotable(slot); let shouldFireSlotChange = false; if (slotables.length !== slot._assignedNodes.length) { shouldFireSlotChange = true; } else { for (let i = 0; i < slotables.length; i++) { if (slotables[i] !== slot._assignedNodes[i]) { shouldFireSlotChange = true; break; } } } if (shouldFireSlotChange) { signalSlotChange(slot); } slot._assignedNodes = slotables; for (const slotable of slotables) { slotable._assignedSlot = slot; } } // https://dom.spec.whatwg.org/#assign-slotables-for-a-tree function assignSlotableForTree(root) { for (const slot of domSymbolTree.treeIterator(root)) { if (isSlot(slot)) { assignSlotable(slot); } } } // https://dom.spec.whatwg.org/#find-slotables function findSlotable(slot) { const result = []; const root = nodeRoot(slot); if (!isShadowRoot(root)) { return result; } for (const slotable of domSymbolTree.treeIterator(root.host)) { const foundSlot = findSlot(slotable); if (foundSlot === slot) { result.push(slotable); } } return result; } // https://dom.spec.whatwg.org/#find-flattened-slotables function findFlattenedSlotables(slot) { const result = []; const root = nodeRoot(slot); if (!isShadowRoot(root)) { return result; } const slotables = findSlotable(slot); if (slotables.length === 0) { for (const child of domSymbolTree.childrenIterator(slot)) { if (isSlotable(child)) { slotables.push(child); } } } for (const node of slotables) { if (isSlot(node) && isShadowRoot(nodeRoot(node))) { const temporaryResult = findFlattenedSlotables(node); result.push(...temporaryResult); } else { result.push(node); } } return result; } // https://dom.spec.whatwg.org/#find-a-slot function findSlot(slotable, openFlag) { const { parentNode: parent } = slotable; if (!parent) { return null; } const shadow = parent._shadowRoot; if (!shadow || (openFlag && shadow.mode !== "open")) { return null; } for (const child of domSymbolTree.treeIterator(shadow)) { if (isSlot(child) && child.name === slotable._slotableName) { return child; } } return null; } // https://dom.spec.whatwg.org/#signal-a-slot-change function signalSlotChange(slot) { if (!signalSlotList.some(entry => entry === slot)) { signalSlotList.push(slot); } queueMutationObserverMicrotask(); } // https://dom.spec.whatwg.org/#concept-shadow-including-descendant function* shadowIncludingInclusiveDescendantsIterator(node) { yield node; if (node._shadowRoot) { yield* shadowIncludingInclusiveDescendantsIterator(node._shadowRoot); } for (const child of domSymbolTree.childrenIterator(node)) { yield* shadowIncludingInclusiveDescendantsIterator(child); } } // https://dom.spec.whatwg.org/#concept-shadow-including-descendant function* shadowIncludingDescendantsIterator(node) { if (node._shadowRoot) { yield* shadowIncludingInclusiveDescendantsIterator(node._shadowRoot); } for (const child of domSymbolTree.childrenIterator(node)) { yield* shadowIncludingInclusiveDescendantsIterator(child); } } module.exports = { isValidHostElementName, isNode, isSlotable, isSlot, isShadowRoot, isShadowInclusiveAncestor, retarget, getEventTargetParent, shadowIncludingRoot, assignSlot, assignSlotable, assignSlotableForTree, findSlot, findFlattenedSlotables, signalSlotChange, shadowIncludingInclusiveDescendantsIterator, shadowIncludingDescendantsIterator };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/helpers/shadow-dom.js
shadow-dom.js
"use strict"; const cssom = require("cssom"); const whatwgEncoding = require("whatwg-encoding"); const whatwgURL = require("whatwg-url"); // TODO: this should really implement https://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet // It (and the things it calls) is nowhere close right now. exports.fetchStylesheet = (elementImpl, urlString) => { const parsedURL = whatwgURL.parseURL(urlString); return fetchStylesheetInternal(elementImpl, urlString, parsedURL); }; // https://drafts.csswg.org/cssom/#remove-a-css-style-sheet exports.removeStylesheet = (sheet, elementImpl) => { const { styleSheets } = elementImpl._ownerDocument; styleSheets._remove(sheet); // Remove the association explicitly; in the spec it's implicit so this step doesn't exist. elementImpl.sheet = null; // TODO: "Set the CSS style sheet’s parent CSS style sheet, owner node and owner CSS rule to null." // Probably when we have a real CSSOM implementation. }; // https://drafts.csswg.org/cssom/#create-a-css-style-sheet kinda: // - Parsing failures are not handled gracefully like they should be // - The import rules stuff seems out of place, and probably should affect the load event... exports.createStylesheet = (sheetText, elementImpl, baseURL) => { let sheet; try { sheet = cssom.parse(sheetText); } catch (e) { if (elementImpl._ownerDocument._defaultView) { const error = new Error("Could not parse CSS stylesheet"); error.detail = sheetText; error.type = "css parsing"; elementImpl._ownerDocument._defaultView._virtualConsole.emit("jsdomError", error); } return; } scanForImportRules(elementImpl, sheet.cssRules, baseURL); addStylesheet(sheet, elementImpl); }; // https://drafts.csswg.org/cssom/#add-a-css-style-sheet function addStylesheet(sheet, elementImpl) { elementImpl._ownerDocument.styleSheets._add(sheet); // Set the association explicitly; in the spec it's implicit. elementImpl.sheet = sheet; // TODO: title and disabled stuff } function fetchStylesheetInternal(elementImpl, urlString, parsedURL) { const document = elementImpl._ownerDocument; let defaultEncoding = document._encoding; const resourceLoader = document._resourceLoader; if (elementImpl.localName === "link" && elementImpl.hasAttributeNS(null, "charset")) { defaultEncoding = whatwgEncoding.labelToName(elementImpl.getAttributeNS(null, "charset")); } function onStylesheetLoad(data) { const css = whatwgEncoding.decode(data, defaultEncoding); // TODO: MIME type checking? if (elementImpl.sheet) { exports.removeStylesheet(elementImpl.sheet, elementImpl); } exports.createStylesheet(css, elementImpl, parsedURL); } resourceLoader.fetch(urlString, { element: elementImpl, onLoad: onStylesheetLoad }); } // TODO this is actually really messed up and overwrites the sheet on elementImpl // Tracking in https://github.com/jsdom/jsdom/issues/2124 function scanForImportRules(elementImpl, cssRules, baseURL) { if (!cssRules) { return; } for (let i = 0; i < cssRules.length; ++i) { if (cssRules[i].cssRules) { // @media rule: keep searching inside it. scanForImportRules(elementImpl, cssRules[i].cssRules, baseURL); } else if (cssRules[i].href) { // @import rule: fetch the resource and evaluate it. // See http://dev.w3.org/csswg/cssom/#css-import-rule // If loading of the style sheet fails its cssRules list is simply // empty. I.e. an @import rule always has an associated style sheet. const parsed = whatwgURL.parseURL(cssRules[i].href, { baseURL }); if (parsed === null) { const window = elementImpl._ownerDocument._defaultView; if (window) { const error = new Error(`Could not parse CSS @import URL ${cssRules[i].href} relative to base URL ` + `"${whatwgURL.serializeURL(baseURL)}"`); error.type = "css @import URL parsing"; window._virtualConsole.emit("jsdomError", error); } } else { fetchStylesheetInternal(elementImpl, whatwgURL.serializeURL(parsed), parsed); } } } }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/helpers/stylesheets.js
stylesheets.js
"use strict"; const webIDLConversions = require("webidl-conversions"); const DOMException = require("domexception/webidl2js-wrapper"); const NODE_TYPE = require("jsdom/lib/jsdom/living/node-type"); const { HTML_NS } = require("jsdom/lib/jsdom/living/helpers/namespaces"); const { getHTMLElementInterface } = require("jsdom/lib/jsdom/living/helpers/create-element"); const { shadowIncludingInclusiveDescendantsIterator } = require("jsdom/lib/jsdom/living/helpers/shadow-dom"); const { isValidCustomElementName, tryUpgradeElement, enqueueCEUpgradeReaction } = require("jsdom/lib/jsdom/living/helpers/custom-elements"); const idlUtils = require("jsdom/lib/jsdom/living/generated/utils"); const HTMLUnknownElement = require("jsdom/lib/jsdom/living/generated/HTMLUnknownElement"); const LIFECYCLE_CALLBACKS = [ "connectedCallback", "disconnectedCallback", "adoptedCallback", "attributeChangedCallback" ]; function convertToSequenceDOMString(obj) { if (!obj || !obj[Symbol.iterator]) { throw new TypeError("Invalid Sequence"); } return Array.from(obj).map(webIDLConversions.DOMString); } // Returns true is the passed value is a valid constructor. // Borrowed from: https://stackoverflow.com/a/39336206/3832710 function isConstructor(value) { if (typeof value !== "function") { return false; } try { const P = new Proxy(value, { construct() { return {}; } }); // eslint-disable-next-line no-new new P(); return true; } catch { return false; } } // https://html.spec.whatwg.org/#customelementregistry class CustomElementRegistryImpl { constructor(globalObject) { this._customElementDefinitions = []; this._elementDefinitionIsRunning = false; this._whenDefinedPromiseMap = Object.create(null); this._globalObject = globalObject; } // https://html.spec.whatwg.org/#dom-customelementregistry-define define(name, ctor, options) { const { _globalObject } = this; if (!isConstructor(ctor)) { throw new TypeError("Constructor argument is not a constructor."); } if (!isValidCustomElementName(name)) { throw DOMException.create(_globalObject, ["Name argument is not a valid custom element name.", "SyntaxError"]); } const nameAlreadyRegistered = this._customElementDefinitions.some(entry => entry.name === name); if (nameAlreadyRegistered) { throw DOMException.create(_globalObject, [ "This name has already been registered in the registry.", "NotSupportedError" ]); } const ctorAlreadyRegistered = this._customElementDefinitions.some(entry => entry.ctor === ctor); if (ctorAlreadyRegistered) { throw DOMException.create(_globalObject, [ "This constructor has already been registered in the registry.", "NotSupportedError" ]); } let localName = name; let extendsOption = null; if (options !== undefined && options.extends) { extendsOption = options.extends; } if (extendsOption !== null) { if (isValidCustomElementName(extendsOption)) { throw DOMException.create(_globalObject, [ "Option extends value can't be a valid custom element name.", "NotSupportedError" ]); } const extendsInterface = getHTMLElementInterface(extendsOption); if (extendsInterface === HTMLUnknownElement) { throw DOMException.create(_globalObject, [ `${extendsOption} is an HTMLUnknownElement.`, "NotSupportedError" ]); } localName = extendsOption; } if (this._elementDefinitionIsRunning) { throw DOMException.create(_globalObject, [ "Invalid nested custom element definition.", "NotSupportedError" ]); } this._elementDefinitionIsRunning = true; let disableShadow = false; let observedAttributes = []; const lifecycleCallbacks = { connectedCallback: null, disconnectedCallback: null, adoptedCallback: null, attributeChangedCallback: null }; let caughtError; try { const { prototype } = ctor; if (typeof prototype !== "object") { throw new TypeError("Invalid constructor prototype."); } for (const callbackName of LIFECYCLE_CALLBACKS) { const callbackValue = prototype[callbackName]; if (callbackValue !== undefined) { lifecycleCallbacks[callbackName] = webIDLConversions.Function(callbackValue); } } if (lifecycleCallbacks.attributeChangedCallback !== null) { const observedAttributesIterable = ctor.observedAttributes; if (observedAttributesIterable !== undefined) { observedAttributes = convertToSequenceDOMString(observedAttributesIterable); } } let disabledFeatures = []; const disabledFeaturesIterable = ctor.disabledFeatures; if (disabledFeaturesIterable) { disabledFeatures = convertToSequenceDOMString(disabledFeaturesIterable); } disableShadow = disabledFeatures.includes("shadow"); } catch (err) { caughtError = err; } finally { this._elementDefinitionIsRunning = false; } if (caughtError !== undefined) { throw caughtError; } const definition = { name, localName, ctor, observedAttributes, lifecycleCallbacks, disableShadow, constructionStack: [] }; this._customElementDefinitions.push(definition); const document = idlUtils.implForWrapper(this._globalObject._document); const upgradeCandidates = []; for (const candidate of shadowIncludingInclusiveDescendantsIterator(document)) { if ( (candidate._namespaceURI === HTML_NS && candidate._localName === localName) && (extendsOption === null || candidate._isValue === name) ) { upgradeCandidates.push(candidate); } } for (const upgradeCandidate of upgradeCandidates) { enqueueCEUpgradeReaction(upgradeCandidate, definition); } if (this._whenDefinedPromiseMap[name] !== undefined) { this._whenDefinedPromiseMap[name].resolve(undefined); delete this._whenDefinedPromiseMap[name]; } } // https://html.spec.whatwg.org/#dom-customelementregistry-get get(name) { const definition = this._customElementDefinitions.find(entry => entry.name === name); return definition && definition.ctor; } // https://html.spec.whatwg.org/#dom-customelementregistry-whendefined whenDefined(name) { if (!isValidCustomElementName(name)) { return Promise.reject(DOMException.create( this._globalObject, ["Name argument is not a valid custom element name.", "SyntaxError"] )); } const alreadyRegistered = this._customElementDefinitions.some(entry => entry.name === name); if (alreadyRegistered) { return Promise.resolve(); } if (this._whenDefinedPromiseMap[name] === undefined) { let resolve; const promise = new Promise(r => { resolve = r; }); // Store the pending Promise along with the extracted resolve callback to actually resolve the returned Promise, // once the custom element is registered. this._whenDefinedPromiseMap[name] = { promise, resolve }; } return this._whenDefinedPromiseMap[name].promise; } // https://html.spec.whatwg.org/#dom-customelementregistry-upgrade upgrade(root) { for (const candidate of shadowIncludingInclusiveDescendantsIterator(root)) { if (candidate.nodeType === NODE_TYPE.ELEMENT_NODE) { tryUpgradeElement(candidate); } } } } module.exports = { implementation: CustomElementRegistryImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/custom-elements/CustomElementRegistry-impl.js
CustomElementRegistry-impl.js
"use strict"; const DOMException = require("domexception/webidl2js-wrapper"); const HTMLElementImpl = require("jsdom/lib/jsdom/living/nodes/HTMLElement-impl").implementation; const notImplemented = require("jsdom/lib/jsdom/browser/not-implemented"); const { fireAnEvent } = require("jsdom/lib/jsdom/living/helpers/events"); function getTimeRangeDummy() { return { length: 0, start() { return 0; }, end() { return 0; } }; } class HTMLMediaElementImpl extends HTMLElementImpl { constructor(globalObject, args, privateData) { super(globalObject, args, privateData); this._muted = false; this._volume = 1.0; this.readyState = 0; this.networkState = 0; this.currentTime = 0; this.currentSrc = ""; this.buffered = getTimeRangeDummy(); this.seeking = false; this.duration = NaN; this.paused = true; this.played = getTimeRangeDummy(); this.seekable = getTimeRangeDummy(); this.ended = false; this.audioTracks = []; this.videoTracks = []; this.textTracks = []; } // Implemented accoring to W3C Draft 22 August 2012 set defaultPlaybackRate(v) { if (v === 0.0) { throw DOMException.create(this._globalObject, ["The operation is not supported.", "NotSupportedError"]); } if (this._defaultPlaybackRate !== v) { this._defaultPlaybackRate = v; this._dispatchRateChange(); } } _dispatchRateChange() { fireAnEvent("ratechange", this); } get defaultPlaybackRate() { if (this._defaultPlaybackRate === undefined) { return 1.0; } return this._defaultPlaybackRate; } get playbackRate() { if (this._playbackRate === undefined) { return 1.0; } return this._playbackRate; } set playbackRate(v) { if (v !== this._playbackRate) { this._playbackRate = v; this._dispatchRateChange(); } } get muted() { return this._muted; } _dispatchVolumeChange() { fireAnEvent("volumechange", this); } set muted(v) { if (v !== this._muted) { this._muted = v; this._dispatchVolumeChange(); } } get defaultMuted() { return this.getAttributeNS(null, "muted") !== null; } set defaultMuted(v) { if (v) { this.setAttributeNS(null, "muted", v); } else { this.removeAttributeNS(null, "muted"); } } get volume() { return this._volume; } set volume(v) { if (v < 0 || v > 1) { throw DOMException.create(this._globalObject, ["The index is not in the allowed range.", "IndexSizeError"]); } if (this._volume !== v) { this._volume = v; this._dispatchVolumeChange(); } } // Not (yet) implemented according to spec // Should return sane default values load() { notImplemented("HTMLMediaElement.prototype.load", this._ownerDocument._defaultView); } canPlayType() { return ""; } play() { notImplemented("HTMLMediaElement.prototype.play", this._ownerDocument._defaultView); } pause() { notImplemented("HTMLMediaElement.prototype.pause", this._ownerDocument._defaultView); } addTextTrack() { notImplemented("HTMLMediaElement.prototype.addTextTrack", this._ownerDocument._defaultView); } } module.exports = { implementation: HTMLMediaElementImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/HTMLMediaElement-impl.js
HTMLMediaElement-impl.js
"use strict"; const { appendHandler, createEventAccessor } = require("jsdom/lib/jsdom/living/helpers/create-event-accessor"); const events = new Set([ "abort", "autocomplete", "autocompleteerror", "blur", "cancel", "canplay", "canplaythrough", "change", "click", "close", "contextmenu", "cuechange", "dblclick", "drag", "dragend", "dragenter", "dragexit", "dragleave", "dragover", "dragstart", "drop", "durationchange", "emptied", "ended", "error", "focus", "input", "invalid", "keydown", "keypress", "keyup", "load", "loadeddata", "loadedmetadata", "loadstart", "mousedown", "mouseenter", "mouseleave", "mousemove", "mouseout", "mouseover", "mouseup", "wheel", "pause", "play", "playing", "progress", "ratechange", "reset", "resize", "scroll", "securitypolicyviolation", "seeked", "seeking", "select", "sort", "stalled", "submit", "suspend", "timeupdate", "toggle", "volumechange", "waiting" ]); class GlobalEventHandlersImpl { _initGlobalEvents() { this._registeredHandlers = new Set(); this._eventHandlers = Object.create(null); } _getEventHandlerTarget() { return this; } _getEventHandlerFor(event) { const target = this._getEventHandlerTarget(event); if (!target) { return null; } return target._eventHandlers[event]; } _setEventHandlerFor(event, handler) { const target = this._getEventHandlerTarget(event); if (!target) { return; } if (!target._registeredHandlers.has(event) && handler !== null) { target._registeredHandlers.add(event); appendHandler(target, event); } target._eventHandlers[event] = handler; } _globalEventChanged(event) { const propName = "on" + event; if (!(propName in this)) { return; } // Only translate attribute changes into properties when runScripts: "dangerously" is set. // Documents without a browsing context (i.e. without a _defaultView) never run scripts. const runScripts = "_runScripts" in this ? this._runScripts : (this._ownerDocument._defaultView || {})._runScripts; if (runScripts !== "dangerously") { return; } const val = this.getAttributeNS(null, propName); const handler = val === null ? null : { body: val }; this._setEventHandlerFor(event, handler); } } for (const event of events) { createEventAccessor(GlobalEventHandlersImpl.prototype, event); } module.exports = { implementation: GlobalEventHandlersImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/GlobalEventHandlers-impl.js
GlobalEventHandlers-impl.js
"use strict"; const HTMLElementImpl = require("jsdom/lib/jsdom/living/nodes/HTMLElement-impl").implementation; const { stripAndCollapseASCIIWhitespace } = require("jsdom/lib/jsdom/living/helpers/strings"); const { domSymbolTree } = require("jsdom/lib/jsdom/living/helpers/internal-constants"); const { closest } = require("jsdom/lib/jsdom/living/helpers/traversal"); const { formOwner } = require("jsdom/lib/jsdom/living/helpers/form-controls"); class HTMLOptionElementImpl extends HTMLElementImpl { constructor(globalObject, args, privateData) { super(globalObject, args, privateData); // whenever selectedness is set to true, make sure all // other options set selectedness to false this._selectedness = false; this._dirtyness = false; } _removeOtherSelectedness() { // Remove the selectedness flag from all other options in this select const select = this._selectNode; if (select && !select.hasAttributeNS(null, "multiple")) { for (const option of select.options) { if (option !== this) { option._selectedness = false; } } } } _askForAReset() { const select = this._selectNode; if (select) { select._askedForAReset(); } } _attrModified(name) { if (!this._dirtyness && name === "selected") { this._selectedness = this.hasAttributeNS(null, "selected"); if (this._selectedness) { this._removeOtherSelectedness(); } this._askForAReset(); } super._attrModified.apply(this, arguments); } get _selectNode() { let select = domSymbolTree.parent(this); if (!select) { return null; } if (select.nodeName.toUpperCase() !== "SELECT") { select = domSymbolTree.parent(select); if (!select || select.nodeName.toUpperCase() !== "SELECT") { return null; } } return select; } get form() { return formOwner(this); } get text() { // TODO is not correctly excluding script and SVG script descendants return stripAndCollapseASCIIWhitespace(this.textContent); } set text(value) { this.textContent = value; } // https://html.spec.whatwg.org/multipage/form-elements.html#concept-option-value _getValue() { if (this.hasAttributeNS(null, "value")) { return this.getAttributeNS(null, "value"); } return this.text; } get value() { return this._getValue(); } set value(value) { this.setAttributeNS(null, "value", value); } get index() { const select = closest(this, "select"); if (select === null) { return 0; } return select.options.indexOf(this); } get selected() { return this._selectedness; } set selected(s) { this._dirtyness = true; this._selectedness = Boolean(s); if (this._selectedness) { this._removeOtherSelectedness(); } this._askForAReset(); this._modified(); } get label() { if (this.hasAttributeNS(null, "label")) { return this.getAttributeNS(null, "label"); } return this.text; } set label(value) { this.setAttributeNS(null, "label", value); } } module.exports = { implementation: HTMLOptionElementImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/HTMLOptionElement-impl.js
HTMLOptionElement-impl.js
"use strict"; const conversions = require("webidl-conversions"); const { serializeURL } = require("whatwg-url"); const HTMLElementImpl = require("jsdom/lib/jsdom/living/nodes/HTMLElement-impl").implementation; const { Canvas } = require("jsdom/lib/jsdom/utils"); const { parseURLToResultingURLRecord } = require("jsdom/lib/jsdom/living/helpers/document-base-url"); class HTMLImageElementImpl extends HTMLElementImpl { _attrModified(name, value, oldVal) { // TODO: handle crossorigin if (name === "src" || ((name === "srcset" || name === "width" || name === "sizes") && value !== oldVal)) { this._updateTheImageData(); } super._attrModified(name, value, oldVal); } get _accept() { return "image/png,image/*;q=0.8,*/*;q=0.5"; } get height() { // Just like on browsers, if no width / height is defined, we fall back on the // dimensions of the internal image data. return this.hasAttributeNS(null, "height") ? conversions["unsigned long"](this.getAttributeNS(null, "height")) : this.naturalHeight; } set height(V) { this.setAttributeNS(null, "height", String(V)); } get width() { return this.hasAttributeNS(null, "width") ? conversions["unsigned long"](this.getAttributeNS(null, "width")) : this.naturalWidth; } set width(V) { this.setAttributeNS(null, "width", String(V)); } get naturalHeight() { return this._image ? this._image.naturalHeight : 0; } get naturalWidth() { return this._image ? this._image.naturalWidth : 0; } get complete() { return Boolean(this._image && this._image.complete); } get currentSrc() { return this._currentSrc || ""; } // https://html.spec.whatwg.org/multipage/images.html#updating-the-image-data _updateTheImageData() { const document = this._ownerDocument; if (!document._defaultView) { return; } if (!Canvas) { return; } if (!this._image) { this._image = new Canvas.Image(); } this._currentSrc = null; const srcAttributeValue = this.getAttributeNS(null, "src"); let urlString = null; if (srcAttributeValue !== null && srcAttributeValue !== "") { const urlRecord = parseURLToResultingURLRecord(srcAttributeValue, this._ownerDocument); if (urlRecord === null) { return; } urlString = serializeURL(urlRecord); } if (urlString !== null) { const resourceLoader = document._resourceLoader; let request; const onLoadImage = data => { const { response } = request; if (response && response.statusCode !== undefined && response.statusCode !== 200) { throw new Error("Status code: " + response.statusCode); } let error = null; this._image.onerror = function (err) { error = err; }; this._image.src = data; if (error) { throw new Error(error); } this._currentSrc = srcAttributeValue; }; request = resourceLoader.fetch(urlString, { element: this, onLoad: onLoadImage }); } else { this._image.src = ""; } } } module.exports = { implementation: HTMLImageElementImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/HTMLImageElement-impl.js
HTMLImageElement-impl.js
"use strict"; const HTMLElementImpl = require("jsdom/lib/jsdom/living/nodes/HTMLElement-impl").implementation; const { parseFloatingPointNumber } = require("jsdom/lib/jsdom/living/helpers/strings"); const { getLabelsForLabelable } = require("jsdom/lib/jsdom/living/helpers/form-controls"); class HTMLMeterElementImpl extends HTMLElementImpl { constructor(globalObject, args, privateData) { super(globalObject, args, privateData); this._labels = null; } // https://html.spec.whatwg.org/multipage/form-elements.html#concept-meter-minimum get _minimumValue() { const min = this.getAttributeNS(null, "min"); if (min !== null) { const parsed = parseFloatingPointNumber(min); if (parsed !== null) { return parsed; } } return 0; } // https://html.spec.whatwg.org/multipage/form-elements.html#concept-meter-maximum get _maximumValue() { let candidate = 1.0; const max = this.getAttributeNS(null, "max"); if (max !== null) { const parsed = parseFloatingPointNumber(max); if (parsed !== null) { candidate = parsed; } } const minimumValue = this._minimumValue; return candidate >= minimumValue ? candidate : minimumValue; } // https://html.spec.whatwg.org/multipage/form-elements.html#concept-meter-actual get _actualValue() { let candidate = 0; const value = this.getAttributeNS(null, "value"); if (value !== null) { const parsed = parseFloatingPointNumber(value); if (parsed !== null) { candidate = parsed; } } const minimumValue = this._minimumValue; if (candidate < minimumValue) { return minimumValue; } const maximumValue = this._maximumValue; return candidate > maximumValue ? maximumValue : candidate; } // https://html.spec.whatwg.org/multipage/form-elements.html#concept-meter-low get _lowBoundary() { const minimumValue = this._minimumValue; let candidate = minimumValue; const low = this.getAttributeNS(null, "low"); if (low !== null) { const parsed = parseFloatingPointNumber(low); if (parsed !== null) { candidate = parsed; } } if (candidate < minimumValue) { return minimumValue; } const maximumValue = this._maximumValue; return candidate > maximumValue ? maximumValue : candidate; } // https://html.spec.whatwg.org/multipage/form-elements.html#concept-meter-high get _highBoundary() { const maximumValue = this._maximumValue; let candidate = maximumValue; const high = this.getAttributeNS(null, "high"); if (high !== null) { const parsed = parseFloatingPointNumber(high); if (parsed !== null) { candidate = parsed; } } const lowBoundary = this._lowBoundary; if (candidate < lowBoundary) { return lowBoundary; } return candidate > maximumValue ? maximumValue : candidate; } // https://html.spec.whatwg.org/multipage/form-elements.html#concept-meter-optimum get _optimumPoint() { const minimumValue = this._minimumValue; const maximumValue = this._maximumValue; let candidate = (minimumValue + maximumValue) / 2; const optimum = this.getAttributeNS(null, "optimum"); if (optimum !== null) { const parsed = parseFloatingPointNumber(optimum); if (parsed !== null) { candidate = parsed; } } if (candidate < minimumValue) { return minimumValue; } return candidate > maximumValue ? maximumValue : candidate; } get labels() { return getLabelsForLabelable(this); } get value() { return this._actualValue; } set value(val) { this.setAttributeNS(null, "value", String(val)); } get min() { return this._minimumValue; } set min(val) { this.setAttributeNS(null, "min", String(val)); } get max() { return this._maximumValue; } set max(val) { this.setAttributeNS(null, "max", String(val)); } get low() { return this._lowBoundary; } set low(val) { this.setAttributeNS(null, "low", String(val)); } get high() { return this._highBoundary; } set high(val) { this.setAttributeNS(null, "high", String(val)); } get optimum() { return this._optimumPoint; } set optimum(val) { this.setAttributeNS(null, "optimum", String(val)); } } module.exports = { implementation: HTMLMeterElementImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/HTMLMeterElement-impl.js
HTMLMeterElement-impl.js
"use strict"; const DOMException = require("domexception/webidl2js-wrapper"); const EventTargetImpl = require("jsdom/lib/jsdom/living/events/EventTarget-impl").implementation; const { simultaneousIterators } = require("jsdom/lib/jsdom/utils"); const NODE_TYPE = require("jsdom/lib/jsdom/living/node-type"); const NODE_DOCUMENT_POSITION = require("jsdom/lib/jsdom/living/node-document-position"); const { clone, locateNamespacePrefix, locateNamespace } = require("jsdom/lib/jsdom/living/node"); const { setAnExistingAttributeValue } = require("jsdom/lib/jsdom/living/attributes"); const NodeList = require("jsdom/lib/jsdom/living/generated/NodeList"); const { nodeRoot, nodeLength } = require("jsdom/lib/jsdom/living/helpers/node"); const { domSymbolTree } = require("jsdom/lib/jsdom/living/helpers/internal-constants"); const { documentBaseURLSerialized } = require("jsdom/lib/jsdom/living/helpers/document-base-url"); const { queueTreeMutationRecord } = require("jsdom/lib/jsdom/living/helpers/mutation-observers"); const { enqueueCECallbackReaction, tryUpgradeElement } = require("jsdom/lib/jsdom/living/helpers/custom-elements"); const { isShadowRoot, shadowIncludingRoot, assignSlot, assignSlotableForTree, assignSlotable, signalSlotChange, isSlot, shadowIncludingInclusiveDescendantsIterator, shadowIncludingDescendantsIterator } = require("jsdom/lib/jsdom/living/helpers/shadow-dom"); function isObsoleteNodeType(node) { return node.nodeType === NODE_TYPE.ENTITY_NODE || node.nodeType === NODE_TYPE.ENTITY_REFERENCE_NODE || node.nodeType === NODE_TYPE.NOTATION_NODE || node.nodeType === NODE_TYPE.CDATA_SECTION_NODE; } function nodeEquals(a, b) { if (a.nodeType !== b.nodeType) { return false; } switch (a.nodeType) { case NODE_TYPE.DOCUMENT_TYPE_NODE: if (a.name !== b.name || a.publicId !== b.publicId || a.systemId !== b.systemId) { return false; } break; case NODE_TYPE.ELEMENT_NODE: if (a._namespaceURI !== b._namespaceURI || a._prefix !== b._prefix || a._localName !== b._localName || a._attributes.length !== b._attributes.length) { return false; } break; case NODE_TYPE.ATTRIBUTE_NODE: if (a._namespace !== b._namespace || a._localName !== b._localName || a._value !== b._value) { return false; } break; case NODE_TYPE.PROCESSING_INSTRUCTION_NODE: if (a._target !== b._target || a._data !== b._data) { return false; } break; case NODE_TYPE.TEXT_NODE: case NODE_TYPE.COMMENT_NODE: if (a._data !== b._data) { return false; } break; } if (a.nodeType === NODE_TYPE.ELEMENT_NODE && !attributeListsEqual(a, b)) { return false; } for (const nodes of simultaneousIterators(domSymbolTree.childrenIterator(a), domSymbolTree.childrenIterator(b))) { if (!nodes[0] || !nodes[1]) { // mismatch in the amount of childNodes return false; } if (!nodeEquals(nodes[0], nodes[1])) { return false; } } return true; } // Needed by https://dom.spec.whatwg.org/#concept-node-equals function attributeListsEqual(elementA, elementB) { const listA = elementA._attributeList; const listB = elementB._attributeList; const lengthA = listA.length; const lengthB = listB.length; if (lengthA !== lengthB) { return false; } for (let i = 0; i < lengthA; ++i) { const attrA = listA[i]; if (!listB.some(attrB => nodeEquals(attrA, attrB))) { return false; } } return true; } // https://dom.spec.whatwg.org/#concept-tree-host-including-inclusive-ancestor function isHostInclusiveAncestor(nodeImplA, nodeImplB) { for (const ancestor of domSymbolTree.ancestorsIterator(nodeImplB)) { if (ancestor === nodeImplA) { return true; } } const rootImplB = nodeRoot(nodeImplB); if (rootImplB._host) { return isHostInclusiveAncestor(nodeImplA, rootImplB._host); } return false; } class NodeImpl extends EventTargetImpl { constructor(globalObject, args, privateData) { super(globalObject, args, privateData); domSymbolTree.initialize(this); this._ownerDocument = privateData.ownerDocument; this._childNodesList = null; this._childrenList = null; this._version = 0; this._memoizedQueries = {}; this._registeredObserverList = []; this._referencedRanges = new Set(); } _getTheParent() { if (this._assignedSlot) { return this._assignedSlot; } return domSymbolTree.parent(this); } get parentNode() { return domSymbolTree.parent(this); } getRootNode(options) { return options.composed ? shadowIncludingRoot(this) : nodeRoot(this); } get nodeName() { switch (this.nodeType) { case NODE_TYPE.ELEMENT_NODE: return this.tagName; case NODE_TYPE.ATTRIBUTE_NODE: return this._qualifiedName; case NODE_TYPE.TEXT_NODE: return "#text"; case NODE_TYPE.CDATA_SECTION_NODE: return "#cdata-section"; case NODE_TYPE.PROCESSING_INSTRUCTION_NODE: return this.target; case NODE_TYPE.COMMENT_NODE: return "#comment"; case NODE_TYPE.DOCUMENT_NODE: return "#document"; case NODE_TYPE.DOCUMENT_TYPE_NODE: return this.name; case NODE_TYPE.DOCUMENT_FRAGMENT_NODE: return "#document-fragment"; } // should never happen return null; } get firstChild() { return domSymbolTree.firstChild(this); } // https://dom.spec.whatwg.org/#connected // https://dom.spec.whatwg.org/#dom-node-isconnected get isConnected() { const root = shadowIncludingRoot(this); return root && root.nodeType === NODE_TYPE.DOCUMENT_NODE; } get ownerDocument() { return this.nodeType === NODE_TYPE.DOCUMENT_NODE ? null : this._ownerDocument; } get lastChild() { return domSymbolTree.lastChild(this); } get childNodes() { if (!this._childNodesList) { this._childNodesList = NodeList.createImpl(this._globalObject, [], { element: this, query: () => domSymbolTree.childrenToArray(this) }); } else { this._childNodesList._update(); } return this._childNodesList; } get nextSibling() { return domSymbolTree.nextSibling(this); } get previousSibling() { return domSymbolTree.previousSibling(this); } _modified() { this._version++; for (const ancestor of domSymbolTree.ancestorsIterator(this)) { ancestor._version++; } if (this._childrenList) { this._childrenList._update(); } if (this._childNodesList) { this._childNodesList._update(); } this._clearMemoizedQueries(); } _childTextContentChangeSteps() { // Default: do nothing } _clearMemoizedQueries() { this._memoizedQueries = {}; const myParent = domSymbolTree.parent(this); if (myParent) { myParent._clearMemoizedQueries(); } } _descendantRemoved(parent, child) { const myParent = domSymbolTree.parent(this); if (myParent) { myParent._descendantRemoved(parent, child); } } _descendantAdded(parent, child) { const myParent = domSymbolTree.parent(this); if (myParent) { myParent._descendantAdded(parent, child); } } _attach() { this._attached = true; for (const child of domSymbolTree.childrenIterator(this)) { if (child._attach) { child._attach(); } } } _detach() { this._attached = false; if (this._ownerDocument && this._ownerDocument._lastFocusedElement === this) { this._ownerDocument._lastFocusedElement = null; } for (const child of domSymbolTree.childrenIterator(this)) { if (child._detach) { child._detach(); } } } hasChildNodes() { return domSymbolTree.hasChildren(this); } // https://dom.spec.whatwg.org/#dom-node-normalize normalize() { // It is important to use a treeToArray instead of a treeToIterator here, because the // treeToIterator doesn't support tree mutation in the middle of the traversal. for (const node of domSymbolTree.treeToArray(this)) { const parentNode = domSymbolTree.parent(node); if (parentNode === null || node.nodeType !== NODE_TYPE.TEXT_NODE) { continue; } let length = nodeLength(node); if (length === 0) { parentNode._remove(node); continue; } const continuousExclusiveTextNodes = []; for (const currentNode of domSymbolTree.previousSiblingsIterator(node)) { if (currentNode.nodeType !== NODE_TYPE.TEXT_NODE) { break; } continuousExclusiveTextNodes.unshift(currentNode); } for (const currentNode of domSymbolTree.nextSiblingsIterator(node)) { if (currentNode.nodeType !== NODE_TYPE.TEXT_NODE) { break; } continuousExclusiveTextNodes.push(currentNode); } const data = continuousExclusiveTextNodes.reduce((d, n) => d + n._data, ""); node.replaceData(length, 0, data); let currentNode = domSymbolTree.nextSibling(node); while (currentNode && currentNode.nodeType !== NODE_TYPE.TEXT_NODE) { const currentNodeParent = domSymbolTree.parent(currentNode); const currentNodeIndex = domSymbolTree.index(currentNode); for (const range of node._referencedRanges) { const { _start, _end } = range; if (_start.node === currentNode) { range._setLiveRangeStart(node, _start.offset + length); } if (_end.node === currentNode) { range._setLiveRangeEnd(node, _end.offset + length); } if (_start.node === currentNodeParent && _start.offset === currentNodeIndex) { range._setLiveRangeStart(node, length); } if (_end.node === currentNodeParent && _end.offset === currentNodeIndex) { range._setLiveRangeStart(node, length); } } length += nodeLength(currentNode); currentNode = domSymbolTree.nextSibling(currentNode); } for (const continuousExclusiveTextNode of continuousExclusiveTextNodes) { parentNode._remove(continuousExclusiveTextNode); } } } get parentElement() { const parentNode = domSymbolTree.parent(this); return parentNode !== null && parentNode.nodeType === NODE_TYPE.ELEMENT_NODE ? parentNode : null; } get baseURI() { return documentBaseURLSerialized(this._ownerDocument); } compareDocumentPosition(other) { // Let node1 be other and node2 be the context object. let node1 = other; let node2 = this; if (isObsoleteNodeType(node2) || isObsoleteNodeType(node1)) { throw new Error("Obsolete node type"); } let attr1 = null; let attr2 = null; if (node1.nodeType === NODE_TYPE.ATTRIBUTE_NODE) { attr1 = node1; node1 = attr1._element; } if (node2.nodeType === NODE_TYPE.ATTRIBUTE_NODE) { attr2 = node2; node2 = attr2._element; if (attr1 !== null && node1 !== null && node2 === node1) { for (const attr of node2._attributeList) { if (nodeEquals(attr, attr1)) { return NODE_DOCUMENT_POSITION.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | NODE_DOCUMENT_POSITION.DOCUMENT_POSITION_PRECEDING; } if (nodeEquals(attr, attr2)) { return NODE_DOCUMENT_POSITION.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | NODE_DOCUMENT_POSITION.DOCUMENT_POSITION_FOLLOWING; } } } } const result = domSymbolTree.compareTreePosition(node2, node1); // “If other and reference are not in the same tree, return the result of adding DOCUMENT_POSITION_DISCONNECTED, // DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, and either DOCUMENT_POSITION_PRECEDING or // DOCUMENT_POSITION_FOLLOWING, with the constraint that this is to be consistent, together.” if (result === NODE_DOCUMENT_POSITION.DOCUMENT_POSITION_DISCONNECTED) { // symbol-tree does not add these bits required by the spec: return NODE_DOCUMENT_POSITION.DOCUMENT_POSITION_DISCONNECTED | NODE_DOCUMENT_POSITION.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | NODE_DOCUMENT_POSITION.DOCUMENT_POSITION_FOLLOWING; } return result; } lookupPrefix(namespace) { if (namespace === null || namespace === "") { return null; } switch (this.nodeType) { case NODE_TYPE.ELEMENT_NODE: { return locateNamespacePrefix(this, namespace); } case NODE_TYPE.DOCUMENT_NODE: { return this.documentElement !== null ? locateNamespacePrefix(this.documentElement, namespace) : null; } case NODE_TYPE.DOCUMENT_TYPE_NODE: case NODE_TYPE.DOCUMENT_FRAGMENT_NODE: { return null; } case NODE_TYPE.ATTRIBUTE_NODE: { return this._element !== null ? locateNamespacePrefix(this._element, namespace) : null; } default: { return this.parentElement !== null ? locateNamespacePrefix(this.parentElement, namespace) : null; } } } lookupNamespaceURI(prefix) { if (prefix === "") { prefix = null; } return locateNamespace(this, prefix); } isDefaultNamespace(namespace) { if (namespace === "") { namespace = null; } const defaultNamespace = locateNamespace(this, null); return defaultNamespace === namespace; } contains(other) { if (other === null) { return false; } else if (this === other) { return true; } return Boolean(this.compareDocumentPosition(other) & NODE_DOCUMENT_POSITION.DOCUMENT_POSITION_CONTAINED_BY); } isEqualNode(node) { if (node === null) { return false; } // Fast-path, not in the spec if (this === node) { return true; } return nodeEquals(this, node); } isSameNode(node) { if (this === node) { return true; } return false; } cloneNode(deep) { if (isShadowRoot(this)) { throw DOMException.create(this._globalObject, ["ShadowRoot nodes are not clonable.", "NotSupportedError"]); } deep = Boolean(deep); return clone(this, undefined, deep); } get nodeValue() { switch (this.nodeType) { case NODE_TYPE.ATTRIBUTE_NODE: { return this._value; } case NODE_TYPE.TEXT_NODE: case NODE_TYPE.CDATA_SECTION_NODE: // CDATASection is a subclass of Text case NODE_TYPE.PROCESSING_INSTRUCTION_NODE: case NODE_TYPE.COMMENT_NODE: { return this._data; } default: { return null; } } } set nodeValue(value) { if (value === null) { value = ""; } switch (this.nodeType) { case NODE_TYPE.ATTRIBUTE_NODE: { setAnExistingAttributeValue(this, value); break; } case NODE_TYPE.TEXT_NODE: case NODE_TYPE.CDATA_SECTION_NODE: // CDATASection is a subclass of Text case NODE_TYPE.PROCESSING_INSTRUCTION_NODE: case NODE_TYPE.COMMENT_NODE: { this.replaceData(0, this.length, value); break; } } } // https://dom.spec.whatwg.org/#dom-node-textcontent get textContent() { switch (this.nodeType) { case NODE_TYPE.DOCUMENT_FRAGMENT_NODE: case NODE_TYPE.ELEMENT_NODE: { let text = ""; for (const child of domSymbolTree.treeIterator(this)) { if (child.nodeType === NODE_TYPE.TEXT_NODE || child.nodeType === NODE_TYPE.CDATA_SECTION_NODE) { text += child.nodeValue; } } return text; } case NODE_TYPE.ATTRIBUTE_NODE: { return this._value; } case NODE_TYPE.TEXT_NODE: case NODE_TYPE.CDATA_SECTION_NODE: // CDATASection is a subclass of Text case NODE_TYPE.PROCESSING_INSTRUCTION_NODE: case NODE_TYPE.COMMENT_NODE: { return this._data; } default: { return null; } } } set textContent(value) { if (value === null) { value = ""; } switch (this.nodeType) { case NODE_TYPE.DOCUMENT_FRAGMENT_NODE: case NODE_TYPE.ELEMENT_NODE: { // https://dom.spec.whatwg.org/#string-replace-all let nodeImpl = null; if (value !== "") { nodeImpl = this._ownerDocument.createTextNode(value); } this._replaceAll(nodeImpl); break; } case NODE_TYPE.ATTRIBUTE_NODE: { setAnExistingAttributeValue(this, value); break; } case NODE_TYPE.TEXT_NODE: case NODE_TYPE.CDATA_SECTION_NODE: // CDATASection is a subclass of Text case NODE_TYPE.PROCESSING_INSTRUCTION_NODE: case NODE_TYPE.COMMENT_NODE: { this.replaceData(0, this.length, value); break; } } } // https://dom.spec.whatwg.org/#dom-node-insertbefore insertBefore(nodeImpl, childImpl) { return this._preInsert(nodeImpl, childImpl); } // https://dom.spec.whatwg.org/#dom-node-appendchild appendChild(nodeImpl) { return this._append(nodeImpl); } // https://dom.spec.whatwg.org/#dom-node-replacechild replaceChild(nodeImpl, childImpl) { return this._replace(nodeImpl, childImpl); } // https://dom.spec.whatwg.org/#dom-node-removechild removeChild(oldChildImpl) { return this._preRemove(oldChildImpl); } // https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity _preInsertValidity(nodeImpl, childImpl) { const { nodeType, nodeName } = nodeImpl; const { nodeType: parentType, nodeName: parentName } = this; if ( parentType !== NODE_TYPE.DOCUMENT_NODE && parentType !== NODE_TYPE.DOCUMENT_FRAGMENT_NODE && parentType !== NODE_TYPE.ELEMENT_NODE ) { throw DOMException.create(this._globalObject, [ `Node can't be inserted in a ${parentName} parent.`, "HierarchyRequestError" ]); } if (isHostInclusiveAncestor(nodeImpl, this)) { throw DOMException.create(this._globalObject, [ "The operation would yield an incorrect node tree.", "HierarchyRequestError" ]); } if (childImpl && domSymbolTree.parent(childImpl) !== this) { throw DOMException.create(this._globalObject, [ "The child can not be found in the parent.", "NotFoundError" ]); } if ( nodeType !== NODE_TYPE.DOCUMENT_FRAGMENT_NODE && nodeType !== NODE_TYPE.DOCUMENT_TYPE_NODE && nodeType !== NODE_TYPE.ELEMENT_NODE && nodeType !== NODE_TYPE.TEXT_NODE && nodeType !== NODE_TYPE.CDATA_SECTION_NODE && // CData section extends from Text nodeType !== NODE_TYPE.PROCESSING_INSTRUCTION_NODE && nodeType !== NODE_TYPE.COMMENT_NODE ) { throw DOMException.create(this._globalObject, [ `${nodeName} node can't be inserted in parent node.`, "HierarchyRequestError" ]); } if ( (nodeType === NODE_TYPE.TEXT_NODE && parentType === NODE_TYPE.DOCUMENT_NODE) || (nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE && parentType !== NODE_TYPE.DOCUMENT_NODE) ) { throw DOMException.create(this._globalObject, [ `${nodeName} node can't be inserted in ${parentName} parent.`, "HierarchyRequestError" ]); } if (parentType === NODE_TYPE.DOCUMENT_NODE) { const nodeChildren = domSymbolTree.childrenToArray(nodeImpl); const parentChildren = domSymbolTree.childrenToArray(this); switch (nodeType) { case NODE_TYPE.DOCUMENT_FRAGMENT_NODE: { const nodeChildrenElements = nodeChildren.filter(child => child.nodeType === NODE_TYPE.ELEMENT_NODE); if (nodeChildrenElements.length > 1) { throw DOMException.create(this._globalObject, [ `Invalid insertion of ${nodeName} node in ${parentName} node.`, "HierarchyRequestError" ]); } const hasNodeTextChildren = nodeChildren.some(child => child.nodeType === NODE_TYPE.TEXT_NODE); if (hasNodeTextChildren) { throw DOMException.create(this._globalObject, [ `Invalid insertion of ${nodeName} node in ${parentName} node.`, "HierarchyRequestError" ]); } if ( nodeChildrenElements.length === 1 && ( parentChildren.some(child => child.nodeType === NODE_TYPE.ELEMENT_NODE) || (childImpl && childImpl.nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE) || ( childImpl && domSymbolTree.nextSibling(childImpl) && domSymbolTree.nextSibling(childImpl).nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE ) ) ) { throw DOMException.create(this._globalObject, [ `Invalid insertion of ${nodeName} node in ${parentName} node.`, "HierarchyRequestError" ]); } break; } case NODE_TYPE.ELEMENT_NODE: if ( parentChildren.some(child => child.nodeType === NODE_TYPE.ELEMENT_NODE) || (childImpl && childImpl.nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE) || ( childImpl && domSymbolTree.nextSibling(childImpl) && domSymbolTree.nextSibling(childImpl).nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE ) ) { throw DOMException.create(this._globalObject, [ `Invalid insertion of ${nodeName} node in ${parentName} node.`, "HierarchyRequestError" ]); } break; case NODE_TYPE.DOCUMENT_TYPE_NODE: if ( parentChildren.some(child => child.nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE) || ( childImpl && domSymbolTree.previousSibling(childImpl) && domSymbolTree.previousSibling(childImpl).nodeType === NODE_TYPE.ELEMENT_NODE ) || (!childImpl && parentChildren.some(child => child.nodeType === NODE_TYPE.ELEMENT_NODE)) ) { throw DOMException.create(this._globalObject, [ `Invalid insertion of ${nodeName} node in ${parentName} node.`, "HierarchyRequestError" ]); } break; } } } // https://dom.spec.whatwg.org/#concept-node-pre-insert _preInsert(nodeImpl, childImpl) { this._preInsertValidity(nodeImpl, childImpl); let referenceChildImpl = childImpl; if (referenceChildImpl === nodeImpl) { referenceChildImpl = domSymbolTree.nextSibling(nodeImpl); } this._ownerDocument._adoptNode(nodeImpl); this._insert(nodeImpl, referenceChildImpl); return nodeImpl; } // https://dom.spec.whatwg.org/#concept-node-insert _insert(nodeImpl, childImpl, suppressObservers) { const count = nodeImpl.nodeType === NODE_TYPE.DOCUMENT_FRAGMENT_NODE ? domSymbolTree.childrenCount(nodeImpl) : 1; if (childImpl) { const childIndex = domSymbolTree.index(childImpl); for (const range of this._referencedRanges) { const { _start, _end } = range; if (_start.offset > childIndex) { range._setLiveRangeStart(this, _start.offset + count); } if (_end.offset > childIndex) { range._setLiveRangeEnd(this, _end.offset + count); } } } const nodesImpl = nodeImpl.nodeType === NODE_TYPE.DOCUMENT_FRAGMENT_NODE ? domSymbolTree.childrenToArray(nodeImpl) : [nodeImpl]; if (nodeImpl.nodeType === NODE_TYPE.DOCUMENT_FRAGMENT_NODE) { let grandChildImpl; while ((grandChildImpl = domSymbolTree.firstChild(nodeImpl))) { nodeImpl._remove(grandChildImpl, true); } } if (nodeImpl.nodeType === NODE_TYPE.DOCUMENT_FRAGMENT_NODE) { queueTreeMutationRecord(nodeImpl, [], nodesImpl, null, null); } const previousChildImpl = childImpl ? domSymbolTree.previousSibling(childImpl) : domSymbolTree.lastChild(this); for (const node of nodesImpl) { if (!childImpl) { domSymbolTree.appendChild(this, node); } else { domSymbolTree.insertBefore(childImpl, node); } if ( (this.nodeType === NODE_TYPE.ELEMENT_NODE && this._shadowRoot !== null) && (node.nodeType === NODE_TYPE.ELEMENT_NODE || node.nodeType === NODE_TYPE.TEXT_NODE) ) { assignSlot(node); } this._modified(); if (node.nodeType === NODE_TYPE.TEXT_NODE || node.nodeType === NODE_TYPE.CDATA_SECTION_NODE) { this._childTextContentChangeSteps(); } if (isSlot(this) && this._assignedNodes.length === 0 && isShadowRoot(nodeRoot(this))) { signalSlotChange(this); } const root = nodeRoot(node); if (isShadowRoot(root)) { assignSlotableForTree(root); } if (this._attached && nodeImpl._attach) { node._attach(); } this._descendantAdded(this, node); for (const inclusiveDescendant of shadowIncludingInclusiveDescendantsIterator(node)) { if (inclusiveDescendant.isConnected) { if (inclusiveDescendant._ceState === "custom") { enqueueCECallbackReaction(inclusiveDescendant, "connectedCallback", []); } else { tryUpgradeElement(inclusiveDescendant); } } } } if (!suppressObservers) { queueTreeMutationRecord(this, nodesImpl, [], previousChildImpl, childImpl); } } // https://dom.spec.whatwg.org/#concept-node-append _append(nodeImpl) { return this._preInsert(nodeImpl, null); } // https://dom.spec.whatwg.org/#concept-node-replace _replace(nodeImpl, childImpl) { const { nodeType, nodeName } = nodeImpl; const { nodeType: parentType, nodeName: parentName } = this; // Note: This section differs from the pre-insert validation algorithm. if ( parentType !== NODE_TYPE.DOCUMENT_NODE && parentType !== NODE_TYPE.DOCUMENT_FRAGMENT_NODE && parentType !== NODE_TYPE.ELEMENT_NODE ) { throw DOMException.create(this._globalObject, [ `Node can't be inserted in a ${parentName} parent.`, "HierarchyRequestError" ]); } if (isHostInclusiveAncestor(nodeImpl, this)) { throw DOMException.create(this._globalObject, [ "The operation would yield an incorrect node tree.", "HierarchyRequestError" ]); } if (childImpl && domSymbolTree.parent(childImpl) !== this) { throw DOMException.create(this._globalObject, [ "The child can not be found in the parent.", "NotFoundError" ]); } if ( nodeType !== NODE_TYPE.DOCUMENT_FRAGMENT_NODE && nodeType !== NODE_TYPE.DOCUMENT_TYPE_NODE && nodeType !== NODE_TYPE.ELEMENT_NODE && nodeType !== NODE_TYPE.TEXT_NODE && nodeType !== NODE_TYPE.CDATA_SECTION_NODE && // CData section extends from Text nodeType !== NODE_TYPE.PROCESSING_INSTRUCTION_NODE && nodeType !== NODE_TYPE.COMMENT_NODE ) { throw DOMException.create(this._globalObject, [ `${nodeName} node can't be inserted in parent node.`, "HierarchyRequestError" ]); } if ( (nodeType === NODE_TYPE.TEXT_NODE && parentType === NODE_TYPE.DOCUMENT_NODE) || (nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE && parentType !== NODE_TYPE.DOCUMENT_NODE) ) { throw DOMException.create(this._globalObject, [ `${nodeName} node can't be inserted in ${parentName} parent.`, "HierarchyRequestError" ]); } if (parentType === NODE_TYPE.DOCUMENT_NODE) { const nodeChildren = domSymbolTree.childrenToArray(nodeImpl); const parentChildren = domSymbolTree.childrenToArray(this); switch (nodeType) { case NODE_TYPE.DOCUMENT_FRAGMENT_NODE: { const nodeChildrenElements = nodeChildren.filter(child => child.nodeType === NODE_TYPE.ELEMENT_NODE); if (nodeChildrenElements.length > 1) { throw DOMException.create(this._globalObject, [ `Invalid insertion of ${nodeName} node in ${parentName} node.`, "HierarchyRequestError" ]); } const hasNodeTextChildren = nodeChildren.some(child => child.nodeType === NODE_TYPE.TEXT_NODE); if (hasNodeTextChildren) { throw DOMException.create(this._globalObject, [ `Invalid insertion of ${nodeName} node in ${parentName} node.`, "HierarchyRequestError" ]); } const parentChildElements = parentChildren.filter(child => child.nodeType === NODE_TYPE.ELEMENT_NODE); if ( nodeChildrenElements.length === 1 && ( (parentChildElements.length === 1 && parentChildElements[0] !== childImpl) || ( childImpl && domSymbolTree.nextSibling(childImpl) && domSymbolTree.nextSibling(childImpl).nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE ) ) ) { throw DOMException.create(this._globalObject, [ `Invalid insertion of ${nodeName} node in ${parentName} node.`, "HierarchyRequestError" ]); } break; } case NODE_TYPE.ELEMENT_NODE: if ( parentChildren.some(child => child.nodeType === NODE_TYPE.ELEMENT_NODE && child !== childImpl) || ( childImpl && domSymbolTree.nextSibling(childImpl) && domSymbolTree.nextSibling(childImpl).nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE ) ) { throw DOMException.create(this._globalObject, [ `Invalid insertion of ${nodeName} node in ${parentName} node.`, "HierarchyRequestError" ]); } break; case NODE_TYPE.DOCUMENT_TYPE_NODE: if ( parentChildren.some(child => child.nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE && child !== childImpl) || ( childImpl && domSymbolTree.previousSibling(childImpl) && domSymbolTree.previousSibling(childImpl).nodeType === NODE_TYPE.ELEMENT_NODE ) ) { throw DOMException.create(this._globalObject, [ `Invalid insertion of ${nodeName} node in ${parentName} node.`, "HierarchyRequestError" ]); } break; } } let referenceChildImpl = domSymbolTree.nextSibling(childImpl); if (referenceChildImpl === nodeImpl) { referenceChildImpl = domSymbolTree.nextSibling(nodeImpl); } const previousSiblingImpl = domSymbolTree.previousSibling(childImpl); this._ownerDocument._adoptNode(nodeImpl); let removedNodesImpl = []; if (domSymbolTree.parent(childImpl)) { removedNodesImpl = [childImpl]; this._remove(childImpl, true); } const nodesImpl = nodeImpl.nodeType === NODE_TYPE.DOCUMENT_FRAGMENT_NODE ? domSymbolTree.childrenToArray(nodeImpl) : [nodeImpl]; this._insert(nodeImpl, referenceChildImpl, true); queueTreeMutationRecord(this, nodesImpl, removedNodesImpl, previousSiblingImpl, referenceChildImpl); return childImpl; } // https://dom.spec.whatwg.org/#concept-node-replace-all _replaceAll(nodeImpl) { if (nodeImpl !== null) { this._ownerDocument._adoptNode(nodeImpl); } const removedNodesImpl = domSymbolTree.childrenToArray(this); let addedNodesImpl; if (nodeImpl === null) { addedNodesImpl = []; } else if (nodeImpl.nodeType === NODE_TYPE.DOCUMENT_FRAGMENT_NODE) { addedNodesImpl = domSymbolTree.childrenToArray(nodeImpl); } else { addedNodesImpl = [nodeImpl]; } for (const childImpl of domSymbolTree.childrenIterator(this)) { this._remove(childImpl, true); } if (nodeImpl !== null) { this._insert(nodeImpl, null, true); } if (addedNodesImpl.length > 0 || removedNodesImpl.length > 0) { queueTreeMutationRecord(this, addedNodesImpl, removedNodesImpl, null, null); } } // https://dom.spec.whatwg.org/#concept-node-pre-remove _preRemove(childImpl) { if (domSymbolTree.parent(childImpl) !== this) { throw DOMException.create(this._globalObject, [ "The node to be removed is not a child of this node.", "NotFoundError" ]); } this._remove(childImpl); return childImpl; } // https://dom.spec.whatwg.org/#concept-node-remove _remove(nodeImpl, suppressObservers) { const index = domSymbolTree.index(nodeImpl); for (const descendant of domSymbolTree.treeIterator(nodeImpl)) { for (const range of descendant._referencedRanges) { const { _start, _end } = range; if (_start.node === descendant) { range._setLiveRangeStart(this, index); } if (_end.node === descendant) { range._setLiveRangeEnd(this, index); } } } for (const range of this._referencedRanges) { const { _start, _end } = range; if (_start.node === this && _start.offset > index) { range._setLiveRangeStart(this, _start.offset - 1); } if (_end.node === this && _end.offset > index) { range._setLiveRangeEnd(this, _end.offset - 1); } } if (this._ownerDocument) { this._ownerDocument._runPreRemovingSteps(nodeImpl); } const oldPreviousSiblingImpl = domSymbolTree.previousSibling(nodeImpl); const oldNextSiblingImpl = domSymbolTree.nextSibling(nodeImpl); domSymbolTree.remove(nodeImpl); if (nodeImpl._assignedSlot) { assignSlotable(nodeImpl._assignedSlot); } if (isSlot(this) && this._assignedNodes.length === 0 && isShadowRoot(nodeRoot(this))) { signalSlotChange(this); } let hasSlotDescendant = isSlot(nodeImpl); if (!hasSlotDescendant) { for (const child of domSymbolTree.treeIterator(nodeImpl)) { if (isSlot(child)) { hasSlotDescendant = true; break; } } } if (hasSlotDescendant) { assignSlotableForTree(nodeRoot(this)); assignSlotableForTree(nodeImpl); } this._modified(); nodeImpl._detach(); this._descendantRemoved(this, nodeImpl); if (this.isConnected) { if (nodeImpl._ceState === "custom") { enqueueCECallbackReaction(nodeImpl, "disconnectedCallback", []); } for (const descendantImpl of shadowIncludingDescendantsIterator(nodeImpl)) { if (descendantImpl._ceState === "custom") { enqueueCECallbackReaction(descendantImpl, "disconnectedCallback", []); } } } if (!suppressObservers) { queueTreeMutationRecord(this, [], [nodeImpl], oldPreviousSiblingImpl, oldNextSiblingImpl); } if (nodeImpl.nodeType === NODE_TYPE.TEXT_NODE) { this._childTextContentChangeSteps(); } } } module.exports = { implementation: NodeImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/Node-impl.js
Node-impl.js
"use strict"; const whatwgURL = require("whatwg-url"); const { parseURLToResultingURLRecord } = require("jsdom/lib/jsdom/living/helpers/document-base-url"); const { asciiCaseInsensitiveMatch } = require("jsdom/lib/jsdom/living/helpers/strings"); const { navigate } = require("jsdom/lib/jsdom/living/window/navigation"); exports.implementation = class HTMLHyperlinkElementUtilsImpl { _htmlHyperlinkElementUtilsSetup() { this.url = null; } // https://html.spec.whatwg.org/multipage/links.html#cannot-navigate _cannotNavigate() { // TODO: Correctly check if the document is fully active return this._localName !== "a" && !this.isConnected; } // https://html.spec.whatwg.org/multipage/semantics.html#get-an-element's-target _getAnElementsTarget() { if (this.hasAttributeNS(null, "target")) { return this.getAttributeNS(null, "target"); } const baseEl = this._ownerDocument.querySelector("base[target]"); if (baseEl) { return baseEl.getAttributeNS(null, "target"); } return ""; } // https://html.spec.whatwg.org/multipage/browsers.html#the-rules-for-choosing-a-browsing-context-given-a-browsing-context-name _chooseABrowsingContext(name, current) { let chosen = null; if (name === "" || asciiCaseInsensitiveMatch(name, "_self")) { chosen = current; } else if (asciiCaseInsensitiveMatch(name, "_parent")) { chosen = current.parent; } else if (asciiCaseInsensitiveMatch(name, "_top")) { chosen = current.top; } else if (!asciiCaseInsensitiveMatch(name, "_blank")) { // https://github.com/whatwg/html/issues/1440 } // TODO: Create new browsing context, handle noopener return chosen; } // https://html.spec.whatwg.org/multipage/links.html#following-hyperlinks-2 _followAHyperlink() { if (this._cannotNavigate()) { return; } const source = this._ownerDocument._defaultView; let targetAttributeValue = ""; if (this._localName === "a" || this._localName === "area") { targetAttributeValue = this._getAnElementsTarget(); } const noopener = this.relList.contains("noreferrer") || this.relList.contains("noopener"); const target = this._chooseABrowsingContext(targetAttributeValue, source, noopener); if (target === null) { return; } const url = parseURLToResultingURLRecord(this.href, this._ownerDocument); if (url === null) { return; } // TODO: Handle hyperlink suffix and referrerpolicy setTimeout(() => { navigate(target, url, {}); }, 0); } toString() { return this.href; } get href() { reinitializeURL(this); const { url } = this; if (url === null) { const href = this.getAttributeNS(null, "href"); return href === null ? "" : href; } return whatwgURL.serializeURL(url); } set href(v) { this.setAttributeNS(null, "href", v); } get origin() { reinitializeURL(this); if (this.url === null) { return ""; } return whatwgURL.serializeURLOrigin(this.url); } get protocol() { reinitializeURL(this); if (this.url === null) { return ":"; } return this.url.scheme + ":"; } set protocol(v) { reinitializeURL(this); if (this.url === null) { return; } whatwgURL.basicURLParse(v + ":", { url: this.url, stateOverride: "scheme start" }); updateHref(this); } get username() { reinitializeURL(this); if (this.url === null) { return ""; } return this.url.username; } set username(v) { reinitializeURL(this); const { url } = this; if (url === null || url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file") { return; } whatwgURL.setTheUsername(url, v); updateHref(this); } get password() { reinitializeURL(this); const { url } = this; if (url === null) { return ""; } return url.password; } set password(v) { reinitializeURL(this); const { url } = this; if (url === null || url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file") { return; } whatwgURL.setThePassword(url, v); updateHref(this); } get host() { reinitializeURL(this); const { url } = this; if (url === null || url.host === null) { return ""; } if (url.port === null) { return whatwgURL.serializeHost(url.host); } return whatwgURL.serializeHost(url.host) + ":" + whatwgURL.serializeInteger(url.port); } set host(v) { reinitializeURL(this); const { url } = this; if (url === null || url.cannotBeABaseURL) { return; } whatwgURL.basicURLParse(v, { url, stateOverride: "host" }); updateHref(this); } get hostname() { reinitializeURL(this); const { url } = this; if (url === null || url.host === null) { return ""; } return whatwgURL.serializeHost(url.host); } set hostname(v) { reinitializeURL(this); const { url } = this; if (url === null || url.cannotBeABaseURL) { return; } whatwgURL.basicURLParse(v, { url, stateOverride: "hostname" }); updateHref(this); } get port() { reinitializeURL(this); const { url } = this; if (url === null || url.port === null) { return ""; } return whatwgURL.serializeInteger(url.port); } set port(v) { reinitializeURL(this); const { url } = this; if (url === null || url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file") { return; } if (v === "") { url.port = null; } else { whatwgURL.basicURLParse(v, { url, stateOverride: "port" }); } updateHref(this); } get pathname() { reinitializeURL(this); const { url } = this; if (url === null) { return ""; } if (url.cannotBeABaseURL) { return url.path[0]; } return "/" + url.path.join("/"); } set pathname(v) { reinitializeURL(this); const { url } = this; if (url === null || url.cannotBeABaseURL) { return; } url.path = []; whatwgURL.basicURLParse(v, { url, stateOverride: "path start" }); updateHref(this); } get search() { reinitializeURL(this); const { url } = this; if (url === null || url.query === null || url.query === "") { return ""; } return "?" + url.query; } set search(v) { reinitializeURL(this); const { url } = this; if (url === null) { return; } if (v === "") { url.query = null; } else { const input = v[0] === "?" ? v.substring(1) : v; url.query = ""; whatwgURL.basicURLParse(input, { url, stateOverride: "query", encodingOverride: this._ownerDocument.charset }); } updateHref(this); } get hash() { reinitializeURL(this); const { url } = this; if (url === null || url.fragment === null || url.fragment === "") { return ""; } return "#" + url.fragment; } set hash(v) { reinitializeURL(this); const { url } = this; if (url === null) { return; } if (v === "") { url.fragment = null; } else { const input = v[0] === "#" ? v.substring(1) : v; url.fragment = ""; whatwgURL.basicURLParse(input, { url, stateOverride: "fragment" }); } updateHref(this); } }; function reinitializeURL(hheu) { if (hheu.url !== null && hheu.url.scheme === "blob" && hheu.url.cannotBeABaseURL) { return; } setTheURL(hheu); } function setTheURL(hheu) { const href = hheu.getAttributeNS(null, "href"); if (href === null) { hheu.url = null; return; } const parsed = parseURLToResultingURLRecord(href, hheu._ownerDocument); hheu.url = parsed === null ? null : parsed; } function updateHref(hheu) { hheu.setAttributeNS(null, "href", whatwgURL.serializeURL(hheu.url)); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/HTMLHyperlinkElementUtils-impl.js
HTMLHyperlinkElementUtils-impl.js
"use strict"; const SlotableMixinImpl = require("jsdom/lib/jsdom/living/nodes/Slotable-impl").implementation; const CharacterDataImpl = require("jsdom/lib/jsdom/living/nodes/CharacterData-impl").implementation; const { domSymbolTree } = require("jsdom/lib/jsdom/living/helpers/internal-constants"); const DOMException = require("domexception/webidl2js-wrapper"); const NODE_TYPE = require("jsdom/lib/jsdom/living/node-type"); const { mixin } = require("jsdom/lib/jsdom/utils"); // https://dom.spec.whatwg.org/#text class TextImpl extends CharacterDataImpl { constructor(globalObject, args, privateData) { super(globalObject, args, { data: args[0], ...privateData }); this._initSlotableMixin(); this.nodeType = NODE_TYPE.TEXT_NODE; } // https://dom.spec.whatwg.org/#dom-text-splittext // https://dom.spec.whatwg.org/#concept-text-split splitText(offset) { const { length } = this; if (offset > length) { throw DOMException.create(this._globalObject, ["The index is not in the allowed range.", "IndexSizeError"]); } const count = length - offset; const newData = this.substringData(offset, count); const newNode = this._ownerDocument.createTextNode(newData); const parent = domSymbolTree.parent(this); if (parent !== null) { parent._insert(newNode, this.nextSibling); for (const range of this._referencedRanges) { const { _start, _end } = range; if (_start.node === this && _start.offset > offset) { range._setLiveRangeStart(newNode, _start.offset - offset); } if (_end.node === this && _end.offset > offset) { range._setLiveRangeEnd(newNode, _end.offset - offset); } } const nodeIndex = domSymbolTree.index(this); for (const range of parent._referencedRanges) { const { _start, _end } = range; if (_start.node === parent && _start.offset === nodeIndex + 1) { range._setLiveRangeStart(parent, _start.offset + 1); } if (_end.node === parent && _end.offset === nodeIndex + 1) { range._setLiveRangeEnd(parent, _end.offset + 1); } } } this.replaceData(offset, count, ""); return newNode; } // https://dom.spec.whatwg.org/#dom-text-wholetext get wholeText() { let wholeText = this.textContent; let next; let current = this; while ((next = domSymbolTree.previousSibling(current)) && next.nodeType === NODE_TYPE.TEXT_NODE) { wholeText = next.textContent + wholeText; current = next; } current = this; while ((next = domSymbolTree.nextSibling(current)) && next.nodeType === NODE_TYPE.TEXT_NODE) { wholeText += next.textContent; current = next; } return wholeText; } } mixin(TextImpl.prototype, SlotableMixinImpl.prototype); module.exports = { implementation: TextImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/Text-impl.js
Text-impl.js
"use strict"; const HTMLElementImpl = require("jsdom/lib/jsdom/living/nodes/HTMLElement-impl").implementation; const { removeStylesheet, createStylesheet } = require("jsdom/lib/jsdom/living/helpers/stylesheets"); const { documentBaseURL } = require("jsdom/lib/jsdom/living/helpers/document-base-url"); const { childTextContent } = require("jsdom/lib/jsdom/living/helpers/text"); const { asciiCaseInsensitiveMatch } = require("jsdom/lib/jsdom/living/helpers/strings"); class HTMLStyleElementImpl extends HTMLElementImpl { constructor(globalObject, args, privateData) { super(globalObject, args, privateData); this.sheet = null; this._isOnStackOfOpenElements = false; } _attach() { super._attach(); if (!this._isOnStackOfOpenElements) { this._updateAStyleBlock(); } } _detach() { super._detach(); if (!this._isOnStackOfOpenElements) { this._updateAStyleBlock(); } } _childTextContentChangeSteps() { super._childTextContentChangeSteps(); // This guard is not required by the spec, but should be unobservable (since you can't run script during the middle // of parsing a <style> element) and saves a bunch of unnecessary work. if (!this._isOnStackOfOpenElements) { this._updateAStyleBlock(); } } _poppedOffStackOfOpenElements() { this._isOnStackOfOpenElements = false; this._updateAStyleBlock(); } _pushedOnStackOfOpenElements() { this._isOnStackOfOpenElements = true; } _updateAStyleBlock() { if (this.sheet) { removeStylesheet(this.sheet, this); } // Browsing-context connected, per https://github.com/whatwg/html/issues/4547 if (!this.isConnected || !this._ownerDocument._defaultView) { return; } const type = this.getAttributeNS(null, "type"); if (type !== null && type !== "" && !asciiCaseInsensitiveMatch(type, "text/css")) { return; } // Not implemented: CSP const content = childTextContent(this); // Not implemented: a bunch of other state, e.g. title/media attributes createStylesheet(content, this, documentBaseURL(this._ownerDocument)); } } module.exports = { implementation: HTMLStyleElementImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/HTMLStyleElement-impl.js
HTMLStyleElement-impl.js
"use strict"; const HTMLElementImpl = require("jsdom/lib/jsdom/living/nodes/HTMLElement-impl").implementation; const { isDisabled, formOwner } = require("jsdom/lib/jsdom/living/helpers/form-controls"); const DefaultConstraintValidationImpl = require("jsdom/lib/jsdom/living/constraint-validation/DefaultConstraintValidation-impl").implementation; const { mixin } = require("jsdom/lib/jsdom/utils"); const { getLabelsForLabelable } = require("jsdom/lib/jsdom/living/helpers/form-controls"); class HTMLButtonElementImpl extends HTMLElementImpl { constructor(globalObject, args, privateData) { super(globalObject, args, privateData); this._customValidityErrorMessage = ""; this._labels = null; this._hasActivationBehavior = true; } _activationBehavior() { const { form } = this; if (form && !isDisabled(this)) { if (this.type === "submit") { form._doSubmit(); } if (this.type === "reset") { form._doReset(); } } } _getValue() { const valueAttr = this.getAttributeNS(null, "value"); return valueAttr === null ? "" : valueAttr; } get labels() { return getLabelsForLabelable(this); } get form() { return formOwner(this); } get type() { const typeAttr = (this.getAttributeNS(null, "type") || "").toLowerCase(); switch (typeAttr) { case "submit": case "reset": case "button": return typeAttr; default: return "submit"; } } set type(v) { v = String(v).toLowerCase(); switch (v) { case "submit": case "reset": case "button": this.setAttributeNS(null, "type", v); break; default: this.setAttributeNS(null, "type", "submit"); break; } } _barredFromConstraintValidationSpecialization() { return this.type === "reset" || this.type === "button"; } } mixin(HTMLButtonElementImpl.prototype, DefaultConstraintValidationImpl.prototype); module.exports = { implementation: HTMLButtonElementImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/HTMLButtonElement-impl.js
HTMLButtonElement-impl.js
"use strict"; const vm = require("vm"); const whatwgEncoding = require("whatwg-encoding"); const MIMEType = require("whatwg-mimetype"); const { serializeURL } = require("whatwg-url"); const HTMLElementImpl = require("jsdom/lib/jsdom/living/nodes/HTMLElement-impl").implementation; const reportException = require("jsdom/lib/jsdom/living/helpers/runtime-script-errors"); const { domSymbolTree, cloningSteps } = require("jsdom/lib/jsdom/living/helpers/internal-constants"); const { asciiLowercase } = require("jsdom/lib/jsdom/living/helpers/strings"); const { childTextContent } = require("jsdom/lib/jsdom/living/helpers/text"); const { fireAnEvent } = require("jsdom/lib/jsdom/living/helpers/events"); const { parseURLToResultingURLRecord } = require("jsdom/lib/jsdom/living/helpers/document-base-url"); const nodeTypes = require("jsdom/lib/jsdom/living/node-type"); const jsMIMETypes = new Set([ "application/ecmascript", "application/javascript", "application/x-ecmascript", "application/x-javascript", "text/ecmascript", "text/javascript", "text/javascript1.0", "text/javascript1.1", "text/javascript1.2", "text/javascript1.3", "text/javascript1.4", "text/javascript1.5", "text/jscript", "text/livescript", "text/x-ecmascript", "text/x-javascript" ]); class HTMLScriptElementImpl extends HTMLElementImpl { constructor(globalObject, args, privateData) { super(globalObject, args, privateData); this._alreadyStarted = false; this._parserInserted = false; // set by the parser } _attach() { super._attach(); // In our current terribly-hacky document.write() implementation, we parse in a div them move elements into the main // document. Thus _eval() will bail early when it gets in _poppedOffStackOfOpenElements(), since we're not attached // then. Instead, we'll let it eval here. if (!this._parserInserted || this._isMovingDueToDocumentWrite) { this._eval(); } } _canRunScript() { const document = this._ownerDocument; // Equivalent to the spec's "scripting is disabled" check. if (!document._defaultView || document._defaultView._runScripts !== "dangerously" || document._scriptingDisabled) { return false; } return true; } _fetchExternalScript() { const document = this._ownerDocument; const resourceLoader = document._resourceLoader; const defaultEncoding = whatwgEncoding.labelToName(this.getAttributeNS(null, "charset")) || document._encoding; let request; if (!this._canRunScript()) { return; } const src = this.getAttributeNS(null, "src"); const url = parseURLToResultingURLRecord(src, this._ownerDocument); if (url === null) { return; } const urlString = serializeURL(url); const onLoadExternalScript = data => { const { response } = request; let contentType; if (response && response.statusCode !== undefined && response.statusCode >= 400) { throw new Error("Status code: " + response.statusCode); } if (response) { contentType = MIMEType.parse(response.headers["content-type"]) || new MIMEType("text/plain"); } const encoding = whatwgEncoding.getBOMEncoding(data) || (contentType && whatwgEncoding.labelToName(contentType.parameters.get("charset"))) || defaultEncoding; const script = whatwgEncoding.decode(data, encoding); this._innerEval(script, urlString); }; request = resourceLoader.fetch(urlString, { element: this, onLoad: onLoadExternalScript }); } _fetchInternalScript() { const document = this._ownerDocument; if (!this._canRunScript()) { return; } document._queue.push(null, () => { this._innerEval(this.text, document.URL); fireAnEvent("load", this); }, null, false, this); } _attrModified(name, value, oldValue) { super._attrModified(name, value, oldValue); if (this._attached && !this._startedEval && name === "src" && oldValue === null && value !== null) { this._fetchExternalScript(); } } _poppedOffStackOfOpenElements() { // This seems to roughly correspond to // https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-incdata:prepare-a-script, although we certainly // don't implement the full semantics. this._eval(); } // Vaguely similar to https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script, but we have a long way // to go before it's aligned. _eval() { if (this._alreadyStarted) { return; } // TODO: this text check doesn't seem completely the same as the spec, which e.g. will try to execute scripts with // child element nodes. Spec bug? https://github.com/whatwg/html/issues/3419 if (!this.hasAttributeNS(null, "src") && this.text.length === 0) { return; } if (!this._attached) { return; } const scriptBlocksTypeString = this._getTypeString(); const type = getType(scriptBlocksTypeString); if (type !== "classic") { // TODO: implement modules, and then change the check to `type === null`. return; } this._alreadyStarted = true; // TODO: implement nomodule here, **but only after we support modules**. // At this point we completely depart from the spec. if (this.hasAttributeNS(null, "src")) { this._fetchExternalScript(); } else { this._fetchInternalScript(); } } _innerEval(text, filename) { this._ownerDocument._writeAfterElement = this; processJavaScript(this, text, filename); delete this._ownerDocument._writeAfterElement; } _getTypeString() { const typeAttr = this.getAttributeNS(null, "type"); const langAttr = this.getAttributeNS(null, "language"); if (typeAttr === "") { return "text/javascript"; } if (typeAttr === null && langAttr === "") { return "text/javascript"; } if (typeAttr === null && langAttr === null) { return "text/javascript"; } if (typeAttr !== null) { return typeAttr.trim(); } if (langAttr !== null) { return "text/" + langAttr; } return null; } get text() { return childTextContent(this); } set text(text) { this.textContent = text; } // https://html.spec.whatwg.org/multipage/scripting.html#script-processing-model [cloningSteps](copy, node) { copy._alreadyStarted = node._alreadyStarted; } } function processJavaScript(element, code, filename) { const document = element.ownerDocument; const window = document && document._global; if (window) { document._currentScript = element; let lineOffset = 0; if (!element.hasAttributeNS(null, "src")) { for (const child of domSymbolTree.childrenIterator(element)) { if (child.nodeType === nodeTypes.TEXT_NODE) { if (child.sourceCodeLocation) { lineOffset = child.sourceCodeLocation.startLine - 1; } break; } } } try { vm.runInContext(code, window, { filename, lineOffset, displayErrors: false }); } catch (e) { reportException(window, e, filename); } finally { document._currentScript = null; } } } function getType(typeString) { const lowercased = asciiLowercase(typeString); // Cannot use whatwg-mimetype parsing because that strips whitespace. The spec demands a strict string comparison. // That is, the type="" attribute is not really related to MIME types at all. if (jsMIMETypes.has(lowercased)) { return "classic"; } if (lowercased === "module") { return "module"; } return null; } module.exports = { implementation: HTMLScriptElementImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/HTMLScriptElement-impl.js
HTMLScriptElement-impl.js
"use strict"; const DOMException = require("domexception/webidl2js-wrapper"); const { mixin } = require("jsdom/lib/jsdom/utils"); const NodeImpl = require("jsdom/lib/jsdom/living/nodes/Node-impl").implementation; const ChildNodeImpl = require("jsdom/lib/jsdom/living/nodes/ChildNode-impl").implementation; const NonDocumentTypeChildNodeImpl = require("jsdom/lib/jsdom/living/nodes/NonDocumentTypeChildNode-impl").implementation; const { TEXT_NODE } = require("jsdom/lib/jsdom/living/node-type"); const { MUTATION_TYPE, queueMutationRecord } = require("jsdom/lib/jsdom/living/helpers/mutation-observers"); // https://dom.spec.whatwg.org/#characterdata class CharacterDataImpl extends NodeImpl { constructor(globalObject, args, privateData) { super(globalObject, args, privateData); this._data = privateData.data; } // https://dom.spec.whatwg.org/#dom-characterdata-data get data() { return this._data; } set data(data) { this.replaceData(0, this.length, data); } // https://dom.spec.whatwg.org/#dom-characterdata-length get length() { return this._data.length; } // https://dom.spec.whatwg.org/#dom-characterdata-substringdata // https://dom.spec.whatwg.org/#concept-cd-substring substringData(offset, count) { const { length } = this; if (offset > length) { throw DOMException.create(this._globalObject, ["The index is not in the allowed range.", "IndexSizeError"]); } if (offset + count > length) { return this._data.slice(offset); } return this._data.slice(offset, offset + count); } // https://dom.spec.whatwg.org/#dom-characterdata-appenddata appendData(data) { this.replaceData(this.length, 0, data); } // https://dom.spec.whatwg.org/#dom-characterdata-insertdata insertData(offset, data) { this.replaceData(offset, 0, data); } // https://dom.spec.whatwg.org/#dom-characterdata-deletedata deleteData(offset, count) { this.replaceData(offset, count, ""); } // https://dom.spec.whatwg.org/#dom-characterdata-replacedata // https://dom.spec.whatwg.org/#concept-cd-replace replaceData(offset, count, data) { const { length } = this; if (offset > length) { throw DOMException.create(this._globalObject, [ "The index is not in the allowed range.", "IndexSizeError" ]); } if (offset + count > length) { count = length - offset; } queueMutationRecord(MUTATION_TYPE.CHARACTER_DATA, this, null, null, this._data, [], [], null, null); const start = this._data.slice(0, offset); const end = this._data.slice(offset + count); this._data = start + data + end; for (const range of this._referencedRanges) { const { _start, _end } = range; if (_start.offset > offset && _start.offset <= offset + count) { range._setLiveRangeStart(this, offset); } if (_end.offset > offset && _end.offset <= offset + count) { range._setLiveRangeEnd(this, offset); } if (_start.offset > offset + count) { range._setLiveRangeStart(this, _start.offset + data.length - count); } if (_end.offset > offset + count) { range._setLiveRangeEnd(this, _end.offset + data.length - count); } } if (this.nodeType === TEXT_NODE && this.parentNode) { this.parentNode._childTextContentChangeSteps(); } } } mixin(CharacterDataImpl.prototype, NonDocumentTypeChildNodeImpl.prototype); mixin(CharacterDataImpl.prototype, ChildNodeImpl.prototype); module.exports = { implementation: CharacterDataImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/CharacterData-impl.js
CharacterData-impl.js
"use strict"; const MIMEType = require("whatwg-mimetype"); const whatwgEncoding = require("whatwg-encoding"); const { parseURL, serializeURL } = require("whatwg-url"); const sniffHTMLEncoding = require("html-encoding-sniffer"); const window = require("jsdom/lib/jsdom/browser/Window"); const HTMLElementImpl = require("jsdom/lib/jsdom/living/nodes/HTMLElement-impl").implementation; const { evaluateJavaScriptURL } = require("jsdom/lib/jsdom/living/window/navigation"); const { parseIntoDocument } = require("jsdom/lib/jsdom/browser/parser"); const { documentBaseURL } = require("jsdom/lib/jsdom/living/helpers/document-base-url"); const { fireAnEvent } = require("jsdom/lib/jsdom/living/helpers/events"); const { getAttributeValue } = require("jsdom/lib/jsdom/living/attributes"); const idlUtils = require("jsdom/lib/jsdom/living/generated/utils"); function fireLoadEvent(document, frame, attaching) { if (attaching) { fireAnEvent("load", frame); return; } const dummyPromise = Promise.resolve(); function onLoad() { fireAnEvent("load", frame); } document._queue.push(dummyPromise, onLoad); } function fetchFrame(serializedURL, frame, document, contentDoc) { const resourceLoader = document._resourceLoader; let request; function onFrameLoaded(data) { const sniffOptions = { defaultEncoding: document._encoding }; if (request.response) { const contentType = MIMEType.parse(request.response.headers["content-type"]) || new MIMEType("text/plain"); sniffOptions.transportLayerEncodingLabel = contentType.parameters.get("charset"); if (contentType) { if (contentType.isXML()) { contentDoc._parsingMode = "xml"; } contentDoc.contentType = contentType.essence; } } const encoding = sniffHTMLEncoding(data, sniffOptions); contentDoc._encoding = encoding; const html = whatwgEncoding.decode(data, contentDoc._encoding); try { parseIntoDocument(html, contentDoc); } catch (error) { const { DOMException } = contentDoc._globalObject; if ( error.constructor.name === "DOMException" && error.code === DOMException.SYNTAX_ERR && contentDoc._parsingMode === "xml" ) { // As defined (https://html.spec.whatwg.org/#read-xml) parsing error in XML document may be reported inline by // mutating the document. const element = contentDoc.createElementNS("http://www.mozilla.org/newlayout/xml/parsererror.xml", "parsererror"); element.textContent = error.message; while (contentDoc.childNodes.length > 0) { contentDoc.removeChild(contentDoc.lastChild); } contentDoc.appendChild(element); } else { throw error; } } contentDoc.close(); return new Promise((resolve, reject) => { contentDoc.addEventListener("load", resolve); contentDoc.addEventListener("error", reject); }); } request = resourceLoader.fetch(serializedURL, { element: frame, onLoad: onFrameLoaded }); } function canDispatchEvents(frame, attaching) { if (!attaching) { return false; } return Object.keys(frame._eventListeners).length === 0; } function loadFrame(frame, attaching) { if (frame._contentDocument) { if (frame._contentDocument._defaultView) { // close calls delete on its document. frame._contentDocument._defaultView.close(); } else { delete frame._contentDocument; } } const parentDoc = frame._ownerDocument; // https://html.spec.whatwg.org/#process-the-iframe-attributes let url; const srcAttribute = getAttributeValue(frame, "src"); if (srcAttribute === "") { url = parseURL("about:blank"); } else { url = parseURL(srcAttribute, { baseURL: documentBaseURL(parentDoc) || undefined }) || parseURL("about:blank"); } const serializedURL = serializeURL(url); const wnd = window.createWindow({ parsingMode: "html", url: url.scheme === "javascript" || serializedURL === "about:blank" ? parentDoc.URL : serializedURL, resourceLoader: parentDoc._defaultView._resourceLoader, referrer: parentDoc.URL, cookieJar: parentDoc._cookieJar, pool: parentDoc._pool, encoding: parentDoc._encoding, runScripts: parentDoc._defaultView._runScripts, commonForOrigin: parentDoc._defaultView._commonForOrigin, pretendToBeVisual: parentDoc._defaultView._pretendToBeVisual }); const contentDoc = frame._contentDocument = idlUtils.implForWrapper(wnd._document); const parent = parentDoc._defaultView; const contentWindow = contentDoc._defaultView; contentWindow._parent = parent; contentWindow._top = parent.top; contentWindow._frameElement = frame; contentWindow._virtualConsole = parent._virtualConsole; if (parentDoc._origin === contentDoc._origin) { contentWindow._currentOriginData.windowsInSameOrigin.push(contentWindow); } const noQueue = canDispatchEvents(frame, attaching); // Handle about:blank with a simulated load of an empty document. if (serializedURL === "about:blank") { // Cannot be done inside the enqueued callback; the documentElement etc. need to be immediately available. parseIntoDocument("<html><head></head><body></body></html>", contentDoc); contentDoc.close(noQueue); if (noQueue) { fireLoadEvent(parentDoc, frame, noQueue); } else { contentDoc.addEventListener("load", () => { fireLoadEvent(parentDoc, frame); }); } } else if (url.scheme === "javascript") { // Cannot be done inside the enqueued callback; the documentElement etc. need to be immediately available. parseIntoDocument("<html><head></head><body></body></html>", contentDoc); contentDoc.close(noQueue); const result = evaluateJavaScriptURL(contentWindow, url); if (typeof result === "string") { contentDoc.body.textContent = result; } if (noQueue) { fireLoadEvent(parentDoc, frame, noQueue); } else { contentDoc.addEventListener("load", () => { fireLoadEvent(parentDoc, frame); }); } } else { fetchFrame(serializedURL, frame, parentDoc, contentDoc); } } function refreshAccessors(document) { const { _defaultView } = document; if (!_defaultView) { return; } const frames = document.querySelectorAll("iframe,frame"); // delete accessors for all frames for (let i = 0; i < _defaultView._length; ++i) { delete _defaultView[i]; } _defaultView._length = frames.length; Array.prototype.forEach.call(frames, (frame, i) => { Object.defineProperty(_defaultView, i, { configurable: true, enumerable: true, get() { return frame.contentWindow; } }); }); } class HTMLFrameElementImpl extends HTMLElementImpl { constructor(globalObject, args, privateData) { super(globalObject, args, privateData); this._contentDocument = null; } _attrModified(name, value, oldVal) { super._attrModified(name, value, oldVal); if (name === "src") { // iframe should never load in a document without a Window // (e.g. implementation.createHTMLDocument) if (this._attached && this._ownerDocument._defaultView) { loadFrame(this); } } } _detach() { super._detach(); if (this.contentWindow) { this.contentWindow.close(); } refreshAccessors(this._ownerDocument); } _attach() { super._attach(); if (this._ownerDocument._defaultView) { loadFrame(this, true); } refreshAccessors(this._ownerDocument); } get contentDocument() { return this._contentDocument; } get contentWindow() { return this.contentDocument ? this.contentDocument._defaultView : null; } } module.exports = { implementation: HTMLFrameElementImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/HTMLFrameElement-impl.js
HTMLFrameElement-impl.js
"use strict"; const DOMException = require("domexception/webidl2js-wrapper"); const HTMLElementImpl = require("jsdom/lib/jsdom/living/nodes/HTMLElement-impl").implementation; const { HTML_NS } = require("jsdom/lib/jsdom/living/helpers/namespaces"); const { domSymbolTree } = require("jsdom/lib/jsdom/living/helpers/internal-constants"); const { firstChildWithLocalName, childrenByLocalName } = require("jsdom/lib/jsdom/living/helpers/traversal"); const HTMLCollection = require("jsdom/lib/jsdom/living/generated/HTMLCollection"); const NODE_TYPE = require("jsdom/lib/jsdom/living/node-type"); function tHeadInsertionPoint(table) { const iterator = domSymbolTree.childrenIterator(table); for (const child of iterator) { if (child.nodeType !== NODE_TYPE.ELEMENT_NODE) { continue; } if (child._namespaceURI !== HTML_NS || (child._localName !== "caption" && child._localName !== "colgroup")) { return child; } } return null; } class HTMLTableElementImpl extends HTMLElementImpl { get caption() { return firstChildWithLocalName(this, "caption"); } set caption(value) { const currentCaption = this.caption; if (currentCaption !== null) { this.removeChild(currentCaption); } if (value !== null) { const insertionPoint = this.firstChild; this.insertBefore(value, insertionPoint); } return value; } get tHead() { return firstChildWithLocalName(this, "thead"); } set tHead(value) { if (value !== null && value._localName !== "thead") { throw DOMException.create(this._globalObject, [ "Cannot set a non-thead element as a table header", "HierarchyRequestError" ]); } const currentHead = this.tHead; if (currentHead !== null) { this.removeChild(currentHead); } if (value !== null) { const insertionPoint = tHeadInsertionPoint(this); this.insertBefore(value, insertionPoint); } } get tFoot() { return firstChildWithLocalName(this, "tfoot"); } set tFoot(value) { if (value !== null && value._localName !== "tfoot") { throw DOMException.create(this._globalObject, [ "Cannot set a non-tfoot element as a table footer", "HierarchyRequestError" ]); } const currentFoot = this.tFoot; if (currentFoot !== null) { this.removeChild(currentFoot); } if (value !== null) { this.appendChild(value); } } get rows() { if (!this._rows) { this._rows = HTMLCollection.createImpl(this._globalObject, [], { element: this, query: () => { const headerRows = []; const bodyRows = []; const footerRows = []; const iterator = domSymbolTree.childrenIterator(this); for (const child of iterator) { if (child.nodeType !== NODE_TYPE.ELEMENT_NODE || child._namespaceURI !== HTML_NS) { continue; } if (child._localName === "thead") { headerRows.push(...childrenByLocalName(child, "tr")); } else if (child._localName === "tbody") { bodyRows.push(...childrenByLocalName(child, "tr")); } else if (child._localName === "tfoot") { footerRows.push(...childrenByLocalName(child, "tr")); } else if (child._localName === "tr") { bodyRows.push(child); } } return [...headerRows, ...bodyRows, ...footerRows]; } }); } return this._rows; } get tBodies() { if (!this._tBodies) { this._tBodies = HTMLCollection.createImpl(this._globalObject, [], { element: this, query: () => childrenByLocalName(this, "tbody") }); } return this._tBodies; } createTBody() { const el = this._ownerDocument.createElement("TBODY"); const tbodies = childrenByLocalName(this, "tbody"); const insertionPoint = tbodies[tbodies.length - 1]; if (insertionPoint) { this.insertBefore(el, insertionPoint.nextSibling); } else { this.appendChild(el); } return el; } createTHead() { let el = this.tHead; if (!el) { el = this.tHead = this._ownerDocument.createElement("THEAD"); } return el; } deleteTHead() { this.tHead = null; } createTFoot() { let el = this.tFoot; if (!el) { el = this.tFoot = this._ownerDocument.createElement("TFOOT"); } return el; } deleteTFoot() { this.tFoot = null; } createCaption() { let el = this.caption; if (!el) { el = this.caption = this._ownerDocument.createElement("CAPTION"); } return el; } deleteCaption() { const c = this.caption; if (c) { c.parentNode.removeChild(c); } } insertRow(index) { if (index < -1 || index > this.rows.length) { throw DOMException.create(this._globalObject, [ "Cannot insert a row at an index that is less than -1 or greater than the number of existing rows", "IndexSizeError" ]); } const tr = this._ownerDocument.createElement("tr"); if (this.rows.length === 0 && this.tBodies.length === 0) { const tBody = this._ownerDocument.createElement("tbody"); tBody.appendChild(tr); this.appendChild(tBody); } else if (this.rows.length === 0) { const tBody = this.tBodies.item(this.tBodies.length - 1); tBody.appendChild(tr); } else if (index === -1 || index === this.rows.length) { const tSection = this.rows.item(this.rows.length - 1).parentNode; tSection.appendChild(tr); } else { const beforeTR = this.rows.item(index); const tSection = beforeTR.parentNode; tSection.insertBefore(tr, beforeTR); } return tr; } deleteRow(index) { const rowLength = this.rows.length; if (index < -1 || index >= rowLength) { throw DOMException.create(this._globalObject, [ `Cannot delete a row at index ${index}, where no row exists`, "IndexSizeError" ]); } if (index === -1) { if (rowLength === 0) { return; } index = rowLength - 1; } const tr = this.rows.item(index); tr.parentNode.removeChild(tr); } } module.exports = { implementation: HTMLTableElementImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/HTMLTableElement-impl.js
HTMLTableElement-impl.js
"use strict"; const DOMException = require("domexception/webidl2js-wrapper"); const { serializeURL } = require("whatwg-url"); const HTMLElementImpl = require("jsdom/lib/jsdom/living/nodes/HTMLElement-impl").implementation; const { domSymbolTree } = require("jsdom/lib/jsdom/living/helpers/internal-constants"); const { fireAnEvent } = require("jsdom/lib/jsdom/living/helpers/events"); const { isListed, isSubmittable, isSubmitButton } = require("jsdom/lib/jsdom/living/helpers/form-controls"); const HTMLCollection = require("jsdom/lib/jsdom/living/generated/HTMLCollection"); const notImplemented = require("jsdom/lib/jsdom/browser/not-implemented"); const { parseURLToResultingURLRecord } = require("jsdom/lib/jsdom/living/helpers/document-base-url"); const encTypes = new Set([ "application/x-www-form-urlencoded", "multipart/form-data", "text/plain" ]); const methods = new Set([ "get", "post", "dialog" ]); const constraintValidationPositiveResult = Symbol("positive"); const constraintValidationNegativeResult = Symbol("negative"); class HTMLFormElementImpl extends HTMLElementImpl { _descendantAdded(parent, child) { const form = this; for (const el of domSymbolTree.treeIterator(child)) { if (typeof el._changedFormOwner === "function") { el._changedFormOwner(form); } } super._descendantAdded.apply(this, arguments); } _descendantRemoved(parent, child) { for (const el of domSymbolTree.treeIterator(child)) { if (typeof el._changedFormOwner === "function") { el._changedFormOwner(null); } } super._descendantRemoved.apply(this, arguments); } // https://html.spec.whatwg.org/multipage/forms.html#dom-form-elements get elements() { // TODO: Return a HTMLFormControlsCollection return HTMLCollection.createImpl(this._globalObject, [], { element: this, query: () => domSymbolTree.treeToArray(this, { filter: node => isListed(node) && (node._localName !== "input" || node.type !== "image") }) }); } get length() { return this.elements.length; } _doSubmit() { if (!this.isConnected) { return; } this.submit(); } submit() { if (!fireAnEvent("submit", this, undefined, { bubbles: true, cancelable: true })) { return; } notImplemented("HTMLFormElement.prototype.submit", this._ownerDocument._defaultView); } requestSubmit(submitter = undefined) { if (submitter !== undefined) { if (!isSubmitButton(submitter)) { throw new TypeError("The specified element is not a submit button"); } if (submitter.form !== this) { throw DOMException.create(this._globalObject, [ "The specified element is not owned by this form element", "NotFoundError" ]); } } if (!fireAnEvent("submit", this, undefined, { bubbles: true, cancelable: true })) { return; } notImplemented("HTMLFormElement.prototype.requestSubmit", this._ownerDocument._defaultView); } _doReset() { if (!this.isConnected) { return; } this.reset(); } reset() { if (!fireAnEvent("reset", this, undefined, { bubbles: true, cancelable: true })) { return; } for (const el of this.elements) { if (typeof el._formReset === "function") { el._formReset(); } } } get method() { let method = this.getAttributeNS(null, "method"); if (method) { method = method.toLowerCase(); } if (methods.has(method)) { return method; } return "get"; } set method(V) { this.setAttributeNS(null, "method", V); } get enctype() { let type = this.getAttributeNS(null, "enctype"); if (type) { type = type.toLowerCase(); } if (encTypes.has(type)) { return type; } return "application/x-www-form-urlencoded"; } set enctype(V) { this.setAttributeNS(null, "enctype", V); } get action() { const attributeValue = this.getAttributeNS(null, "action"); if (attributeValue === null || attributeValue === "") { return this._ownerDocument.URL; } const urlRecord = parseURLToResultingURLRecord(attributeValue, this._ownerDocument); if (urlRecord === null) { return attributeValue; } return serializeURL(urlRecord); } set action(V) { this.setAttributeNS(null, "action", V); } // If the checkValidity() method is invoked, the user agent must statically validate the // constraints of the form element, and return true if the constraint validation returned // a positive result, and false if it returned a negative result. checkValidity() { return this._staticallyValidateConstraints().result === constraintValidationPositiveResult; } // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#interactively-validate-the-constraints reportValidity() { return this.checkValidity(); } // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#statically-validate-the-constraints _staticallyValidateConstraints() { const controls = []; for (const el of domSymbolTree.treeIterator(this)) { if (el.form === this && isSubmittable(el)) { controls.push(el); } } const invalidControls = []; for (const control of controls) { if (control._isCandidateForConstraintValidation() && !control._satisfiesConstraints()) { invalidControls.push(control); } } if (invalidControls.length === 0) { return { result: constraintValidationPositiveResult }; } const unhandledInvalidControls = []; for (const invalidControl of invalidControls) { const notCancelled = fireAnEvent("invalid", invalidControl, undefined, { cancelable: true }); if (notCancelled) { unhandledInvalidControls.push(invalidControl); } } return { result: constraintValidationNegativeResult, unhandledInvalidControls }; } } module.exports = { implementation: HTMLFormElementImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/HTMLFormElement-impl.js
HTMLFormElement-impl.js
"use strict"; const { convertNodesIntoNode } = require("jsdom/lib/jsdom/living/node"); class ChildNodeImpl { remove() { if (!this.parentNode) { return; } this.parentNode._remove(this); } after(...nodes) { const parent = this.parentNode; if (parent) { let viableNextSibling = this.nextSibling; let idx = viableNextSibling ? nodes.indexOf(viableNextSibling) : -1; while (idx !== -1) { viableNextSibling = viableNextSibling.nextSibling; if (!viableNextSibling) { break; } idx = nodes.indexOf(viableNextSibling); } parent._preInsert(convertNodesIntoNode(this._ownerDocument, nodes), viableNextSibling); } } before(...nodes) { const parent = this.parentNode; if (parent) { let viablePreviousSibling = this.previousSibling; let idx = viablePreviousSibling ? nodes.indexOf(viablePreviousSibling) : -1; while (idx !== -1) { viablePreviousSibling = viablePreviousSibling.previousSibling; if (!viablePreviousSibling) { break; } idx = nodes.indexOf(viablePreviousSibling); } parent._preInsert( convertNodesIntoNode(this._ownerDocument, nodes), viablePreviousSibling ? viablePreviousSibling.nextSibling : parent.firstChild ); } } replaceWith(...nodes) { const parent = this.parentNode; if (parent) { let viableNextSibling = this.nextSibling; let idx = viableNextSibling ? nodes.indexOf(viableNextSibling) : -1; while (idx !== -1) { viableNextSibling = viableNextSibling.nextSibling; if (!viableNextSibling) { break; } idx = nodes.indexOf(viableNextSibling); } const node = convertNodesIntoNode(this._ownerDocument, nodes); if (this.parentNode === parent) { parent._replace(node, this); } else { parent._preInsert(node, viableNextSibling); } } } } module.exports = { implementation: ChildNodeImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/nodes/ChildNode-impl.js
ChildNode-impl.js
"use strict"; const whatwgURL = require("whatwg-url"); const DOMException = require("domexception/webidl2js-wrapper"); const { documentBaseURL, parseURLToResultingURLRecord } = require("jsdom/lib/jsdom/living/helpers/document-base-url"); const { navigate } = require("jsdom/lib/jsdom/living/window/navigation"); // Not implemented: use of entry settings object's API base URL in href setter, assign, and replace. Instead we just // use the document base URL. The difference matters in the case of cross-frame calls. exports.implementation = class LocationImpl { constructor(globalObject, args, privateData) { this._relevantDocument = privateData.relevantDocument; this.url = null; this._globalObject = globalObject; } get _url() { return this._relevantDocument._URL; } _locationObjectSetterNavigate(url) { // Not implemented: extra steps here to determine replacement flag. return this._locationObjectNavigate(url); } _locationObjectNavigate(url, { replacement = false } = {}) { // Not implemented: the setup for calling navigate, which doesn't apply to our stub navigate anyway. navigate(this._relevantDocument._defaultView, url, { replacement, exceptionsEnabled: true }); } toString() { return this.href; } get href() { return whatwgURL.serializeURL(this._url); } set href(v) { const newURL = whatwgURL.parseURL(v, { baseURL: documentBaseURL(this._relevantDocument) }); if (newURL === null) { throw new TypeError(`Could not parse "${v}" as a URL`); } this._locationObjectSetterNavigate(newURL); } get origin() { return whatwgURL.serializeURLOrigin(this._url); } get protocol() { return this._url.scheme + ":"; } set protocol(v) { const copyURL = Object.assign({}, this._url); const possibleFailure = whatwgURL.basicURLParse(v + ":", { url: copyURL, stateOverride: "scheme start" }); if (possibleFailure === null) { throw new TypeError(`Could not parse the URL after setting the procol to "${v}"`); } if (copyURL.scheme !== "http" && copyURL.scheme !== "https") { return; } this._locationObjectSetterNavigate(copyURL); } get host() { const url = this._url; if (url.host === null) { return ""; } if (url.port === null) { return whatwgURL.serializeHost(url.host); } return whatwgURL.serializeHost(url.host) + ":" + whatwgURL.serializeInteger(url.port); } set host(v) { const copyURL = Object.assign({}, this._url); if (copyURL.cannotBeABaseURL) { return; } whatwgURL.basicURLParse(v, { url: copyURL, stateOverride: "host" }); this._locationObjectSetterNavigate(copyURL); } get hostname() { if (this._url.host === null) { return ""; } return whatwgURL.serializeHost(this._url.host); } set hostname(v) { const copyURL = Object.assign({}, this._url); if (copyURL.cannotBeABaseURL) { return; } whatwgURL.basicURLParse(v, { url: copyURL, stateOverride: "hostname" }); this._locationObjectSetterNavigate(copyURL); } get port() { if (this._url.port === null) { return ""; } return whatwgURL.serializeInteger(this._url.port); } set port(v) { const copyURL = Object.assign({}, this._url); if (copyURL.host === null || copyURL.cannotBeABaseURL || copyURL.scheme === "file") { return; } whatwgURL.basicURLParse(v, { url: copyURL, stateOverride: "port" }); this._locationObjectSetterNavigate(copyURL); } get pathname() { const url = this._url; if (url.cannotBeABaseURL) { return url.path[0]; } return "/" + url.path.join("/"); } set pathname(v) { const copyURL = Object.assign({}, this._url); if (copyURL.cannotBeABaseURL) { return; } copyURL.path = []; whatwgURL.basicURLParse(v, { url: copyURL, stateOverride: "path start" }); this._locationObjectSetterNavigate(copyURL); } get search() { if (this._url.query === null || this._url.query === "") { return ""; } return "?" + this._url.query; } set search(v) { const copyURL = Object.assign({}, this._url); if (v === "") { copyURL.query = null; } else { const input = v[0] === "?" ? v.substring(1) : v; copyURL.query = ""; whatwgURL.basicURLParse(input, { url: copyURL, stateOverride: "query", encodingOverride: this._relevantDocument.charset }); } this._locationObjectSetterNavigate(copyURL); } get hash() { if (this._url.fragment === null || this._url.fragment === "") { return ""; } return "#" + this._url.fragment; } set hash(v) { const copyURL = Object.assign({}, this._url); if (copyURL.scheme === "javascript") { return; } if (v === "") { copyURL.fragment = null; } else { const input = v[0] === "#" ? v.substring(1) : v; copyURL.fragment = ""; whatwgURL.basicURLParse(input, { url: copyURL, stateOverride: "fragment" }); } this._locationObjectSetterNavigate(copyURL); } assign(url) { // Should be entry settings object; oh well const parsedURL = parseURLToResultingURLRecord(url, this._relevantDocument); if (parsedURL === null) { throw DOMException.create(this._globalObject, [ `Could not resolve the given string "${url}" relative to the base URL "${this._relevantDocument.URL}"`, "SyntaxError" ]); } this._locationObjectNavigate(parsedURL); } replace(url) { // Should be entry settings object; oh well const parsedURL = parseURLToResultingURLRecord(url, this._relevantDocument); if (parsedURL === null) { throw DOMException.create(this._globalObject, [ `Could not resolve the given string "${url}" relative to the base URL "${this._relevantDocument.URL}"`, "SyntaxError" ]); } this._locationObjectNavigate(parsedURL, { replacement: true }); } reload() { const flags = { replace: true, reloadTriggered: true, exceptionsEnabled: true }; navigate(this._relevantDocument._defaultView, this._url, flags); } };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/window/Location-impl.js
Location-impl.js
"use strict"; const DOMException = require("domexception/webidl2js-wrapper"); const { documentBaseURLSerialized, parseURLToResultingURLRecord } = require("jsdom/lib/jsdom/living/helpers/document-base-url.js"); // https://html.spec.whatwg.org/#history-3 exports.implementation = class HistoryImpl { constructor(globalObject, args, privateData) { this._window = privateData.window; this._document = privateData.document; this._actAsIfLocationReloadCalled = privateData.actAsIfLocationReloadCalled; this._state = null; this._globalObject = globalObject; } _guardAgainstInactiveDocuments() { if (!this._window) { throw DOMException.create(this._globalObject, [ "History object is associated with a document that is not fully active.", "SecurityError" ]); } } get length() { this._guardAgainstInactiveDocuments(); return this._window._sessionHistory.length; } get state() { this._guardAgainstInactiveDocuments(); return this._state; } go(delta) { this._guardAgainstInactiveDocuments(); if (delta === 0) { // When the go(delta) method is invoked, if delta is zero, the user agent must act as // if the location.reload() method was called instead. this._actAsIfLocationReloadCalled(); } else { // Otherwise, the user agent must traverse the history by a delta whose value is delta this._window._sessionHistory.traverseByDelta(delta); } } back() { this.go(-1); } forward() { this.go(+1); } pushState(data, title, url) { this._sharedPushAndReplaceState(data, title, url, "pushState"); } replaceState(data, title, url) { this._sharedPushAndReplaceState(data, title, url, "replaceState"); } // https://html.spec.whatwg.org/#dom-history-pushstate _sharedPushAndReplaceState(data, title, url, methodName) { this._guardAgainstInactiveDocuments(); // TODO structured clone data let newURL; if (url !== null) { // Not implemented: use of entry settings object's API base URL. Instead we just use the document base URL. The // difference matters in the case of cross-frame calls. newURL = parseURLToResultingURLRecord(url, this._document); if (newURL === null) { throw DOMException.create(this._globalObject, [ `Could not parse url argument "${url}" to ${methodName} against base URL ` + `"${documentBaseURLSerialized(this._document)}".`, "SecurityError" ]); } if (newURL.scheme !== this._document._URL.scheme || newURL.username !== this._document._URL.username || newURL.password !== this._document._URL.password || newURL.host !== this._document._URL.host || newURL.port !== this._document._URL.port || newURL.cannotBeABaseURL !== this._document._URL.cannotBeABaseURL) { throw DOMException.create(this._globalObject, [ `${methodName} cannot update history to a URL which differs in components other than in ` + `path, query, or fragment.`, "SecurityError" ]); } // Not implemented: origin check (seems to only apply to documents with weird origins, e.g. sandboxed ones) } else { newURL = this._window._sessionHistory.currentEntry.url; } if (methodName === "pushState") { this._window._sessionHistory.removeAllEntriesAfterCurrentEntry(); this._window._sessionHistory.clearHistoryTraversalTasks(); const newEntry = { document: this._document, stateObject: data, title, url: newURL }; this._window._sessionHistory.addEntryAfterCurrentEntry(newEntry); this._window._sessionHistory.updateCurrentEntry(newEntry); } else { const { currentEntry } = this._window._sessionHistory; currentEntry.stateObject = data; currentEntry.title = title; currentEntry.url = newURL; } // TODO: If the current entry in the session history represents a non-GET request // (e.g. it was the result of a POST submission) then update it to instead represent // a GET request. this._document._URL = newURL; // arguably it's a bit odd that the state and latestEntry do not belong to the SessionHistory // but the spec gives them to "History" and "Document" respecively. this._state = data; // TODO clone again!! O_o this._document._latestEntry = this._window._sessionHistory.currentEntry; } };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/window/History-impl.js
History-impl.js
"use strict"; const DOMException = require("domexception/webidl2js-wrapper"); const NODE_TYPE = require("jsdom/lib/jsdom/living/node-type"); const { nodeLength, nodeRoot } = require("jsdom/lib/jsdom/living/helpers/node"); const { domSymbolTree } = require("jsdom/lib/jsdom/living/helpers/internal-constants"); const { compareBoundaryPointsPosition } = require("jsdom/lib/jsdom/living/range/boundary-point"); const { setBoundaryPointStart, setBoundaryPointEnd } = require("jsdom/lib/jsdom/living/range/Range-impl"); const Range = require("jsdom/lib/jsdom/living/generated/Range"); const { implForWrapper } = require("jsdom/lib/jsdom/living/generated/utils"); // https://w3c.github.io/selection-api/#dfn-direction const SELECTION_DIRECTION = { FORWARDS: 1, BACKWARDS: -1, DIRECTIONLESS: 0 }; // https://w3c.github.io/selection-api/#dom-selection class SelectionImpl { constructor(globalObject) { this._range = null; this._direction = SELECTION_DIRECTION.DIRECTIONLESS; this._globalObject = globalObject; } // https://w3c.github.io/selection-api/#dom-selection-anchornode get anchorNode() { const anchor = this._anchor; return anchor ? anchor.node : null; } // https://w3c.github.io/selection-api/#dom-selection-anchoroffset get anchorOffset() { const anchor = this._anchor; return anchor ? anchor.offset : 0; } // https://w3c.github.io/selection-api/#dom-selection-focusnode get focusNode() { const focus = this._focus; return focus ? focus.node : null; } // https://w3c.github.io/selection-api/#dom-selection-focusoffset get focusOffset() { const focus = this._focus; return focus ? focus.offset : 0; } // https://w3c.github.io/selection-api/#dom-selection-iscollapsed get isCollapsed() { return this._range === null || this._range.collapsed; } // https://w3c.github.io/selection-api/#dom-selection-rangecount get rangeCount() { return this._isEmpty() ? 0 : 1; } // https://w3c.github.io/selection-api/#dom-selection-type get type() { if (this._isEmpty()) { return "None"; } else if (this._range.collapsed) { return "Caret"; } return "Range"; } // https://w3c.github.io/selection-api/#dom-selection-getrangeat getRangeAt(index) { if (index !== 0 || this._isEmpty()) { throw DOMException.create(this._globalObject, ["Invalid range index.", "IndexSizeError"]); } return this._range; } // https://w3c.github.io/selection-api/#dom-selection-addrange addRange(range) { if (range._root === implForWrapper(this._globalObject._document) && this.rangeCount === 0) { this._associateRange(range); } } // https://w3c.github.io/selection-api/#dom-selection-removerange removeRange(range) { if (range !== this._range) { throw DOMException.create(this._globalObject, ["Invalid range.", "NotFoundError"]); } this._associateRange(null); } // https://w3c.github.io/selection-api/#dom-selection-removeallranges removeAllRanges() { this._associateRange(null); } // https://w3c.github.io/selection-api/#dom-selection-empty empty() { this.removeAllRanges(); } // https://w3c.github.io/selection-api/#dom-selection-collapse collapse(node, offset) { if (node === null) { this.removeAllRanges(); return; } if (node.nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE) { throw DOMException.create(this._globalObject, [ "DocumentType Node can't be used as boundary point.", "InvalidNodeTypeError" ]); } if (offset > nodeLength(node)) { throw DOMException.create(this._globalObject, ["Invalid range index.", "IndexSizeError"]); } if (nodeRoot(node) !== implForWrapper(this._globalObject._document)) { return; } const newRange = Range.createImpl(this._globalObject, [], { start: { node, offset: 0 }, end: { node, offset: 0 } }); setBoundaryPointStart(newRange, node, offset); setBoundaryPointEnd(newRange, node, offset); this._associateRange(newRange); } // https://w3c.github.io/selection-api/#dom-selection-setposition setPosition(node, offset) { this.collapse(node, offset); } // https://w3c.github.io/selection-api/#dom-selection-collapsetostart collapseToStart() { if (this._isEmpty()) { throw DOMException.create(this._globalObject, ["There is no selection to collapse.", "InvalidStateError"]); } const { node, offset } = this._range._start; const newRange = Range.createImpl(this._globalObject, [], { start: { node, offset }, end: { node, offset } }); this._associateRange(newRange); } // https://w3c.github.io/selection-api/#dom-selection-collapsetoend collapseToEnd() { if (this._isEmpty()) { throw DOMException.create(this._globalObject, ["There is no selection to collapse.", "InvalidStateError"]); } const { node, offset } = this._range._end; const newRange = Range.createImpl(this._globalObject, [], { start: { node, offset }, end: { node, offset } }); this._associateRange(newRange); } // https://w3c.github.io/selection-api/#dom-selection-extend extend(node, offset) { if (nodeRoot(node) !== implForWrapper(this._globalObject._document)) { return; } if (this._isEmpty()) { throw DOMException.create(this._globalObject, ["There is no selection to extend.", "InvalidStateError"]); } const { _anchor: oldAnchor } = this; const newFocus = { node, offset }; const newRange = Range.createImpl(this._globalObject, [], { start: { node, offset: 0 }, end: { node, offset: 0 } }); if (nodeRoot(node) !== this._range._root) { setBoundaryPointStart(newRange, newFocus.node, newFocus.offset); setBoundaryPointEnd(newRange, newFocus.node, newFocus.offset); } else if (compareBoundaryPointsPosition(oldAnchor, newFocus) <= 0) { setBoundaryPointStart(newRange, oldAnchor.node, oldAnchor.offset); setBoundaryPointEnd(newRange, newFocus.node, newFocus.offset); } else { setBoundaryPointStart(newRange, newFocus.node, newFocus.offset); setBoundaryPointEnd(newRange, oldAnchor.node, oldAnchor.offset); } this._associateRange(newRange); this._direction = compareBoundaryPointsPosition(newFocus, oldAnchor) === -1 ? SELECTION_DIRECTION.BACKWARDS : SELECTION_DIRECTION.FORWARDS; } // https://w3c.github.io/selection-api/#dom-selection-setbaseandextent setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset) { if (anchorOffset > nodeLength(anchorNode) || focusOffset > nodeLength(focusNode)) { throw DOMException.create(this._globalObject, ["Invalid anchor or focus offset.", "IndexSizeError"]); } const document = implForWrapper(this._globalObject._document); if (document !== nodeRoot(anchorNode) || document !== nodeRoot(focusNode)) { return; } const anchor = { node: anchorNode, offset: anchorOffset }; const focus = { node: focusNode, offset: focusOffset }; let newRange; if (compareBoundaryPointsPosition(anchor, focus) === -1) { newRange = Range.createImpl(this._globalObject, [], { start: { node: anchor.node, offset: anchor.offset }, end: { node: focus.node, offset: focus.offset } }); } else { newRange = Range.createImpl(this._globalObject, [], { start: { node: focus.node, offset: focus.offset }, end: { node: anchor.node, offset: anchor.offset } }); } this._associateRange(newRange); this._direction = compareBoundaryPointsPosition(focus, anchor) === -1 ? SELECTION_DIRECTION.BACKWARDS : SELECTION_DIRECTION.FORWARDS; } // https://w3c.github.io/selection-api/#dom-selection-selectallchildren selectAllChildren(node) { if (node.nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE) { throw DOMException.create(this._globalObject, [ "DocumentType Node can't be used as boundary point.", "InvalidNodeTypeError" ]); } const document = implForWrapper(this._globalObject._document); if (document !== nodeRoot(node)) { return; } const length = domSymbolTree.childrenCount(node); const newRange = Range.createImpl(this._globalObject, [], { start: { node, offset: 0 }, end: { node, offset: 0 } }); setBoundaryPointStart(newRange, node, 0); setBoundaryPointEnd(newRange, node, length); this._associateRange(newRange); } // https://w3c.github.io/selection-api/#dom-selection-deletefromdocument deleteFromDocument() { if (!this._isEmpty()) { this._range.deleteContents(); } } // https://w3c.github.io/selection-api/#dom-selection-containsnode containsNode(node, allowPartialContainment) { if (this._isEmpty() || nodeRoot(node) !== implForWrapper(this._globalObject._document)) { return false; } const { _start, _end } = this._range; const startIsBeforeNode = compareBoundaryPointsPosition(_start, { node, offset: 0 }) === -1; const endIsAfterNode = compareBoundaryPointsPosition(_end, { node, offset: nodeLength(node) }) === 1; return allowPartialContainment ? startIsBeforeNode || endIsAfterNode : startIsBeforeNode && endIsAfterNode; } // https://w3c.github.io/selection-api/#dom-selection-stringifier toString() { return this._range ? this._range.toString() : ""; } // https://w3c.github.io/selection-api/#dfn-empty _isEmpty() { return this._range === null; } // https://w3c.github.io/selection-api/#dfn-anchor get _anchor() { if (!this._range) { return null; } return this._direction === SELECTION_DIRECTION.FORWARDS ? this._range._start : this._range._end; } // https://w3c.github.io/selection-api/#dfn-focus get _focus() { if (!this._range) { return null; } return this._direction === SELECTION_DIRECTION.FORWARDS ? this._range._end : this._range._start; } _associateRange(newRange) { this._range = newRange; this._direction = newRange === null ? SELECTION_DIRECTION.DIRECTIONLESS : SELECTION_DIRECTION.FORWARDS; // TODO: Emit "selectionchange" event. At this time, there is currently no test in WPT covering this. // https://w3c.github.io/selection-api/#selectionchange-event } } module.exports = { implementation: SelectionImpl };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/selection/Selection-impl.js
Selection-impl.js
"use strict"; const DOMException = require("domexception/webidl2js-wrapper"); const { filter, FILTER_ACCEPT, FILTER_REJECT, FILTER_SKIP } = require("jsdom/lib/jsdom/living/traversal/helpers"); const FIRST = false; const LAST = true; const NEXT = false; const PREVIOUS = true; exports.implementation = class TreeWalkerImpl { constructor(globalObject, args, privateData) { this._active = false; this.root = privateData.root; this.currentNode = this.root; this.whatToShow = privateData.whatToShow; this.filter = privateData.filter; this._globalObject = globalObject; } get currentNode() { return this._currentNode; } set currentNode(node) { if (node === null) { throw DOMException.create(this._globalObject, ["Cannot set currentNode to null", "NotSupportedError"]); } this._currentNode = node; } parentNode() { let node = this._currentNode; while (node !== null && node !== this.root) { node = node.parentNode; if (node !== null && filter(this, node) === FILTER_ACCEPT) { return (this._currentNode = node); } } return null; } firstChild() { return this._traverseChildren(FIRST); } lastChild() { return this._traverseChildren(LAST); } previousSibling() { return this._traverseSiblings(PREVIOUS); } nextSibling() { return this._traverseSiblings(NEXT); } previousNode() { let node = this._currentNode; while (node !== this.root) { let sibling = node.previousSibling; while (sibling !== null) { node = sibling; let result = filter(this, node); while (result !== FILTER_REJECT && node.hasChildNodes()) { node = node.lastChild; result = filter(this, node); } if (result === FILTER_ACCEPT) { return (this._currentNode = node); } sibling = node.previousSibling; } if (node === this.root || node.parentNode === null) { return null; } node = node.parentNode; if (filter(this, node) === FILTER_ACCEPT) { return (this._currentNode = node); } } return null; } nextNode() { let node = this._currentNode; let result = FILTER_ACCEPT; for (;;) { while (result !== FILTER_REJECT && node.hasChildNodes()) { node = node.firstChild; result = filter(this, node); if (result === FILTER_ACCEPT) { return (this._currentNode = node); } } do { if (node === this.root) { return null; } const sibling = node.nextSibling; if (sibling !== null) { node = sibling; break; } node = node.parentNode; } while (node !== null); if (node === null) { return null; } result = filter(this, node); if (result === FILTER_ACCEPT) { return (this._currentNode = node); } } } _traverseChildren(type) { let node = this._currentNode; node = type === FIRST ? node.firstChild : node.lastChild; if (node === null) { return null; } main: for (;;) { const result = filter(this, node); if (result === FILTER_ACCEPT) { return (this._currentNode = node); } if (result === FILTER_SKIP) { const child = type === FIRST ? node.firstChild : node.lastChild; if (child !== null) { node = child; continue; } } for (;;) { const sibling = type === FIRST ? node.nextSibling : node.previousSibling; if (sibling !== null) { node = sibling; continue main; } const parent = node.parentNode; if (parent === null || parent === this.root || parent === this._currentNode) { return null; } node = parent; } } } _traverseSiblings(type) { let node = this._currentNode; if (node === this.root) { return null; } for (;;) { let sibling = type === NEXT ? node.nextSibling : node.previousSibling; while (sibling !== null) { node = sibling; const result = filter(this, node); if (result === FILTER_ACCEPT) { return (this._currentNode = node); } sibling = type === NEXT ? node.firstChild : node.lastChild; if (result === FILTER_REJECT || sibling === null) { sibling = type === NEXT ? node.nextSibling : node.previousSibling; } } node = node.parentNode; if (node === null || node === this.root) { return null; } if (filter(this, node) === FILTER_ACCEPT) { return null; } } } };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/traversal/TreeWalker-impl.js
TreeWalker-impl.js
"use strict"; const { domSymbolTree } = require("jsdom/lib/jsdom/living/helpers/internal-constants"); const { filter, FILTER_ACCEPT } = require("jsdom/lib/jsdom/living/traversal/helpers"); exports.implementation = class NodeIteratorImpl { constructor(globalObject, args, privateData) { this._active = false; this.root = privateData.root; this.whatToShow = privateData.whatToShow; this.filter = privateData.filter; this._referenceNode = this.root; this._pointerBeforeReferenceNode = true; // This is used to deactive the NodeIterator if there are too many working in a Document at the same time. // Without weak references, a JS implementation of NodeIterator will leak, since we can't know when to clean it up. // This ensures we force a clean up of those beyond some maximum (specified by the Document). this._working = true; this._workingNodeIteratorsMax = privateData.workingNodeIteratorsMax; this._globalObject = globalObject; } get referenceNode() { this._throwIfNotWorking(); return this._referenceNode; } get pointerBeforeReferenceNode() { this._throwIfNotWorking(); return this._pointerBeforeReferenceNode; } nextNode() { this._throwIfNotWorking(); return this._traverse("next"); } previousNode() { this._throwIfNotWorking(); return this._traverse("previous"); } detach() { // Intentionally do nothing, per spec. } // Called by Documents. _preRemovingSteps(toBeRemovedNode) { // Second clause is https://github.com/whatwg/dom/issues/496 if (!toBeRemovedNode.contains(this._referenceNode) || toBeRemovedNode === this.root) { return; } if (this._pointerBeforeReferenceNode) { let next = null; let candidateForNext = domSymbolTree.following(toBeRemovedNode, { skipChildren: true }); while (candidateForNext !== null) { if (this.root.contains(candidateForNext)) { next = candidateForNext; break; } candidateForNext = domSymbolTree.following(candidateForNext, { skipChildren: true }); } if (next !== null) { this._referenceNode = next; return; } this._pointerBeforeReferenceNode = false; } const { previousSibling } = toBeRemovedNode; this._referenceNode = previousSibling === null ? toBeRemovedNode.parentNode : domSymbolTree.lastInclusiveDescendant(toBeRemovedNode.previousSibling); } // Only called by getters and methods that are affected by the pre-removing steps _throwIfNotWorking() { if (!this._working) { throw Error(`This NodeIterator is no longer working. More than ${this._workingNodeIteratorsMax} iterators are ` + `being used concurrently. You can increase the 'concurrentNodeIterators' option to make this error go away.`); } } _traverse(direction) { let node = this._referenceNode; let beforeNode = this._pointerBeforeReferenceNode; while (true) { if (direction === "next") { if (!beforeNode) { node = domSymbolTree.following(node, { root: this.root }); if (!node) { return null; } } beforeNode = false; } else if (direction === "previous") { if (beforeNode) { node = domSymbolTree.preceding(node, { root: this.root }); if (!node) { return null; } } beforeNode = true; } const result = filter(this, node); if (result === FILTER_ACCEPT) { break; } } this._referenceNode = node; this._pointerBeforeReferenceNode = beforeNode; return node; } };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/traversal/NodeIterator-impl.js
NodeIterator-impl.js
"use strict"; // Returns "Type(value) is Object" in ES terminology. function isObject(value) { return typeof value === "object" && value !== null || typeof value === "function"; } const hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty); const wrapperSymbol = Symbol("wrapper"); const implSymbol = Symbol("impl"); const sameObjectCaches = Symbol("SameObject caches"); const ctorRegistrySymbol = Symbol.for("[webidl2js] constructor registry"); function getSameObject(wrapper, prop, creator) { if (!wrapper[sameObjectCaches]) { wrapper[sameObjectCaches] = Object.create(null); } if (prop in wrapper[sameObjectCaches]) { return wrapper[sameObjectCaches][prop]; } wrapper[sameObjectCaches][prop] = creator(); return wrapper[sameObjectCaches][prop]; } function wrapperForImpl(impl) { return impl ? impl[wrapperSymbol] : null; } function implForWrapper(wrapper) { return wrapper ? wrapper[implSymbol] : null; } function tryWrapperForImpl(impl) { const wrapper = wrapperForImpl(impl); return wrapper ? wrapper : impl; } function tryImplForWrapper(wrapper) { const impl = implForWrapper(wrapper); return impl ? impl : wrapper; } const iterInternalSymbol = Symbol("internal"); const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())); function isArrayIndexPropName(P) { if (typeof P !== "string") { return false; } const i = P >>> 0; if (i === Math.pow(2, 32) - 1) { return false; } const s = `${i}`; if (P !== s) { return false; } return true; } const byteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; function isArrayBuffer(value) { try { byteLengthGetter.call(value); return true; } catch (e) { return false; } } const supportsPropertyIndex = Symbol("supports property index"); const supportedPropertyIndices = Symbol("supported property indices"); const supportsPropertyName = Symbol("supports property name"); const supportedPropertyNames = Symbol("supported property names"); const indexedGet = Symbol("indexed property get"); const indexedSetNew = Symbol("indexed property set new"); const indexedSetExisting = Symbol("indexed property set existing"); const namedGet = Symbol("named property get"); const namedSetNew = Symbol("named property set new"); const namedSetExisting = Symbol("named property set existing"); const namedDelete = Symbol("named property delete"); module.exports = exports = { isObject, hasOwn, wrapperSymbol, implSymbol, getSameObject, ctorRegistrySymbol, wrapperForImpl, implForWrapper, tryWrapperForImpl, tryImplForWrapper, iterInternalSymbol, IteratorPrototype, isArrayBuffer, isArrayIndexPropName, supportsPropertyIndex, supportedPropertyIndices, supportsPropertyName, supportedPropertyNames, indexedGet, indexedSetNew, indexedSetExisting, namedGet, namedSetNew, namedSetExisting, namedDelete };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/generated/utils.js
utils.js
"use strict"; const { isForbidden, isForbiddenResponse, isPrivilegedNoCORSRequest, isNoCORSSafelistedRequest, isCORSWhitelisted } = require("jsdom/lib/jsdom/living/fetch/header-types"); const HeaderList = require("jsdom/lib/jsdom/living/fetch/header-list"); function assertName(name) { if (!name.match(/^[!#$%&'*+\-.^`|~\w]+$/)) { throw new TypeError("name is invalid"); } } function assertValue(value) { if (value.match(/[\0\r\n]/)) { throw new TypeError("value is invalid"); } } class HeadersImpl { constructor(globalObject, args) { this.guard = "none"; this.headersList = new HeaderList(); if (args[0]) { this._fill(args[0]); } } _fill(init) { if (Array.isArray(init)) { for (const header of init) { if (header.length !== 2) { throw new TypeError("init is invalid"); } this.append(header[0], header[1]); } } else { for (const key of Object.keys(init)) { this.append(key, init[key]); } } } has(name) { assertName(name); return this.headersList.contains(name); } get(name) { assertName(name); return this.headersList.get(name); } _removePrivilegedNoCORSHeaders() { this.headersList.delete("range"); } append(name, value) { value = value.trim(); assertName(name); assertValue(value); switch (this.guard) { case "immutable": throw new TypeError("Headers is immutable"); case "request": if (isForbidden(name)) { return; } break; case "request-no-cors": { let temporaryValue = this.get(name); if (temporaryValue === null) { temporaryValue = value; } else { temporaryValue += `, ${value}`; } if (!isCORSWhitelisted(name, value)) { return; } break; } case "response": if (isForbiddenResponse(name)) { return; } break; } this.headersList.append(name, value); this._removePrivilegedNoCORSHeaders(); } set(name, value) { value = value.trim(); assertName(name); assertValue(value); switch (this.guard) { case "immutable": throw new TypeError("Headers is immutable"); case "request": if (isForbidden(name)) { return; } break; case "request-no-cors": { if (!isCORSWhitelisted(name, value)) { return; } break; } case "response": if (isForbiddenResponse(name)) { return; } break; } this.headersList.set(name, value); this._removePrivilegedNoCORSHeaders(); } delete(name) { assertName(name); switch (this.guard) { case "immutable": throw new TypeError("Headers is immutable"); case "request": if (isForbidden(name)) { return; } break; case "request-no-cors": { if ( !isNoCORSSafelistedRequest(name) && !isPrivilegedNoCORSRequest(name) ) { return; } break; } case "response": if (isForbiddenResponse(name)) { return; } break; } this.headersList.delete(name); this._removePrivilegedNoCORSHeaders(); } * [Symbol.iterator]() { for (const header of this.headersList.sortAndCombine()) { yield header; } } } exports.implementation = HeadersImpl;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/fetch/Headers-impl.js
Headers-impl.js
"use strict"; const MIMEType = require("whatwg-mimetype"); const PRIVILEGED_NO_CORS_REQUEST = new Set(["range"]); function isPrivilegedNoCORSRequest(name) { return PRIVILEGED_NO_CORS_REQUEST.has(name.toLowerCase()); } const NO_CORS_SAFELISTED_REQUEST = new Set([ `accept`, `accept-language`, `content-language`, `content-type` ]); function isNoCORSSafelistedRequest(name) { return NO_CORS_SAFELISTED_REQUEST.has(name.toLowerCase()); } const FORBIDDEN = new Set([ `accept-charset`, `accept-encoding`, `access-control-request-headers`, `access-control-request-method`, `connection`, `content-length`, `cookie`, `cookie2`, `date`, `dnt`, `expect`, `host`, `keep-alive`, `origin`, `referer`, `te`, `trailer`, `transfer-encoding`, `upgrade`, `via` ]); function isForbidden(name) { name = name.toLowerCase(); return ( FORBIDDEN.has(name) || name.startsWith("proxy-") || name.startsWith("sec-") ); } const FORBIDDEN_RESPONSE = new Set(["set-cookie", "set-cookie2"]); function isForbiddenResponse(name) { return FORBIDDEN_RESPONSE.has(name.toLowerCase()); } const CORS_UNSAFE_BYTE = /[\x00-\x08\x0A-\x1F"():<>?@[\\\]{}\x7F]/; function isCORSWhitelisted(name, value) { name = name.toLowerCase(); switch (name) { case "accept": if (value.match(CORS_UNSAFE_BYTE)) { return false; } break; case "accept-language": case "content-language": if (value.match(/[^\x30-\x39\x41-\x5A\x61-\x7A *,\-.;=]/)) { return false; } break; case "content-type": { if (value.match(CORS_UNSAFE_BYTE)) { return false; } const mimeType = MIMEType.parse(value); if (mimeType === null) { return false; } if ( ![ "application/x-www-form-urlencoded", "multipart/form-data", "text/plain" ].includes(mimeType.essence) ) { return false; } break; } default: return false; } if (Buffer.from(value).length > 128) { return false; } return true; } module.exports = { isPrivilegedNoCORSRequest, isNoCORSSafelistedRequest, isForbidden, isForbiddenResponse, isCORSWhitelisted };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/fetch/header-types.js
header-types.js
"use strict"; const HTTP_STATUS_CODES = require("http").STATUS_CODES; const { spawnSync } = require("child_process"); const { URL } = require("whatwg-url"); const whatwgEncoding = require("whatwg-encoding"); const tough = require("tough-cookie"); const MIMEType = require("whatwg-mimetype"); const xhrUtils = require("jsdom/lib/jsdom/living/xhr/xhr-utils"); const DOMException = require("domexception/webidl2js-wrapper"); const { documentBaseURLSerialized } = require("jsdom/lib/jsdom/living/helpers/document-base-url"); const { asciiCaseInsensitiveMatch } = require("jsdom/lib/jsdom/living/helpers/strings"); const idlUtils = require("jsdom/lib/jsdom/living/generated/utils"); const Document = require("jsdom/lib/jsdom/living/generated/Document"); const Blob = require("jsdom/lib/jsdom/living/generated/Blob"); const FormData = require("jsdom/lib/jsdom/living/generated/FormData"); const XMLHttpRequestEventTargetImpl = require("jsdom/lib/jsdom/living/xhr/XMLHttpRequestEventTarget-impl").implementation; const XMLHttpRequestUpload = require("jsdom/lib/jsdom/living/generated/XMLHttpRequestUpload"); const ProgressEvent = require("jsdom/lib/jsdom/living/generated/ProgressEvent"); const { isArrayBuffer } = require("jsdom/lib/jsdom/living/generated/utils"); const { parseIntoDocument } = require("jsdom/lib/jsdom/browser/parser"); const { fragmentSerialization } = require("jsdom/lib/jsdom/living/domparsing/serialization"); const { setupForSimpleEventAccessors } = require("jsdom/lib/jsdom/living/helpers/create-event-accessor"); const { parseJSONFromBytes } = require("jsdom/lib/jsdom/living/helpers/json"); const { fireAnEvent } = require("jsdom/lib/jsdom/living/helpers/events"); const { copyToArrayBufferInNewRealm } = require("jsdom/lib/jsdom/living/helpers/binary-data"); const { READY_STATES } = xhrUtils; const syncWorkerFile = require.resolve ? require.resolve("./xhr-sync-worker.js") : null; const tokenRegexp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; const fieldValueRegexp = /^[ \t]*(?:[\x21-\x7E\x80-\xFF](?:[ \t][\x21-\x7E\x80-\xFF])?)*[ \t]*$/; const forbiddenRequestHeaders = new Set([ "accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "date", "dnt", "expect", "host", "keep-alive", "origin", "referer", "te", "trailer", "transfer-encoding", "upgrade", "via" ]); const forbiddenResponseHeaders = new Set([ "set-cookie", "set-cookie2" ]); const uniqueResponseHeaders = new Set([ "content-type", "content-length", "user-agent", "referer", "host", "authorization", "proxy-authorization", "if-modified-since", "if-unmodified-since", "from", "location", "max-forwards" ]); const corsSafeResponseHeaders = new Set([ "cache-control", "content-language", "content-type", "expires", "last-modified", "pragma" ]); const allowedRequestMethods = new Set(["OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE"]); const forbiddenRequestMethods = new Set(["TRACK", "TRACE", "CONNECT"]); class XMLHttpRequestImpl extends XMLHttpRequestEventTargetImpl { constructor(window) { super(window); // Avoid running `_ownerDocument` getter multiple times in the constructor: const { _ownerDocument } = this; this.upload = XMLHttpRequestUpload.createImpl(window); this.readyState = READY_STATES.UNSENT; this.responseURL = ""; this.status = 0; this.statusText = ""; this.flag = { synchronous: false, withCredentials: false, mimeType: null, auth: null, method: undefined, responseType: "", requestHeaders: {}, referrer: _ownerDocument.URL, uri: "", timeout: 0, body: undefined, formData: false, preflight: false, requestManager: _ownerDocument._requestManager, strictSSL: window._resourceLoader._strictSSL, proxy: window._resourceLoader._proxy, cookieJar: _ownerDocument._cookieJar, encoding: _ownerDocument._encoding, origin: window._origin, userAgent: window.navigator.userAgent }; this.properties = { beforeSend: false, send: false, client: null, timeoutStart: 0, timeoutId: 0, timeoutFn: null, responseBuffer: null, responseCache: null, responseTextCache: null, responseXMLCache: null, responseHeaders: {}, filteredResponseHeaders: [], error: "", uploadComplete: false, uploadListener: false, // Signifies that we're calling abort() from xhr-utils.js because of a window shutdown. // In that case the termination reason is "fatal", not "end-user abort". abortError: false, cookieJar: _ownerDocument._cookieJar, bufferStepSize: 1 * 1024 * 1024, // pre-allocate buffer increase step size. init value is 1MB totalReceivedChunkSize: 0 }; } get responseType() { return this.flag.responseType; } set responseType(responseType) { const { flag } = this; if (this.readyState === READY_STATES.LOADING || this.readyState === READY_STATES.DONE) { throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]); } if (this.readyState === READY_STATES.OPENED && flag.synchronous) { throw DOMException.create(this._globalObject, [ "The object does not support the operation or argument.", "InvalidAccessError" ]); } flag.responseType = responseType; } get response() { const { properties } = this; if (properties.responseCache) { // Needed because of: https://github.com/jsdom/webidl2js/issues/149 return idlUtils.tryWrapperForImpl(properties.responseCache); } let res; const responseBuffer = properties.responseBuffer ? properties.responseBuffer.slice(0, properties.totalReceivedChunkSize) : null; switch (this.responseType) { case "": case "text": { res = this.responseText; break; } case "arraybuffer": { if (!responseBuffer) { return null; } res = copyToArrayBufferInNewRealm(responseBuffer, this._globalObject); break; } case "blob": { if (!responseBuffer) { return null; } const contentType = finalMIMEType(this); res = Blob.createImpl(this._globalObject, [ [new Uint8Array(responseBuffer)], { type: contentType || "" } ]); break; } case "document": { res = this.responseXML; break; } case "json": { if (this.readyState !== READY_STATES.DONE || !responseBuffer) { res = null; } try { res = parseJSONFromBytes(responseBuffer); } catch (e) { res = null; } break; } } properties.responseCache = res; // Needed because of: https://github.com/jsdom/webidl2js/issues/149 return idlUtils.tryWrapperForImpl(res); } get responseText() { const { properties } = this; if (this.responseType !== "" && this.responseType !== "text") { throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]); } if (this.readyState !== READY_STATES.LOADING && this.readyState !== READY_STATES.DONE) { return ""; } if (properties.responseTextCache) { return properties.responseTextCache; } const responseBuffer = properties.responseBuffer ? properties.responseBuffer.slice(0, properties.totalReceivedChunkSize) : null; if (!responseBuffer) { return ""; } const fallbackEncoding = finalCharset(this) || whatwgEncoding.getBOMEncoding(responseBuffer) || "UTF-8"; const res = whatwgEncoding.decode(responseBuffer, fallbackEncoding); properties.responseTextCache = res; return res; } get responseXML() { const { flag, properties } = this; if (this.responseType !== "" && this.responseType !== "document") { throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]); } if (this.readyState !== READY_STATES.DONE) { return null; } if (properties.responseXMLCache) { return properties.responseXMLCache; } const responseBuffer = properties.responseBuffer ? properties.responseBuffer.slice(0, properties.totalReceivedChunkSize) : null; if (!responseBuffer) { return null; } const contentType = finalMIMEType(this); let isHTML = false; let isXML = false; const parsed = MIMEType.parse(contentType); if (parsed) { isHTML = parsed.isHTML(); isXML = parsed.isXML(); if (!isXML && !isHTML) { return null; } } if (this.responseType === "" && isHTML) { return null; } const encoding = finalCharset(this) || whatwgEncoding.getBOMEncoding(responseBuffer) || "UTF-8"; const resText = whatwgEncoding.decode(responseBuffer, encoding); if (!resText) { return null; } const res = Document.createImpl(this._globalObject, [], { options: { url: flag.uri, lastModified: new Date(getResponseHeader(this, "last-modified")), parsingMode: isHTML ? "html" : "xml", cookieJar: { setCookieSync: () => undefined, getCookieStringSync: () => "" }, encoding, parseOptions: this._ownerDocument._parseOptions } }); try { parseIntoDocument(resText, res); } catch (e) { properties.responseXMLCache = null; return null; } res.close(); properties.responseXMLCache = res; return res; } get timeout() { return this.flag.timeout; } set timeout(val) { const { flag, properties } = this; if (flag.synchronous) { throw DOMException.create(this._globalObject, [ "The object does not support the operation or argument.", "InvalidAccessError" ]); } flag.timeout = val; clearTimeout(properties.timeoutId); if (val > 0 && properties.timeoutFn) { properties.timeoutId = setTimeout( properties.timeoutFn, Math.max(0, val - ((new Date()).getTime() - properties.timeoutStart)) ); } else { properties.timeoutFn = null; properties.timeoutStart = 0; } } get withCredentials() { return this.flag.withCredentials; } set withCredentials(val) { const { flag, properties } = this; if (!(this.readyState === READY_STATES.UNSENT || this.readyState === READY_STATES.OPENED)) { throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]); } if (properties.send) { throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]); } flag.withCredentials = val; } abort() { const { properties } = this; // Terminate the request clearTimeout(properties.timeoutId); properties.timeoutFn = null; properties.timeoutStart = 0; const { client } = properties; if (client) { client.abort(); properties.client = null; } if (properties.abortError) { // Special case that ideally shouldn't be going through the public API at all. // Run the https://xhr.spec.whatwg.org/#handle-errors "fatal" steps. this.readyState = READY_STATES.DONE; properties.send = false; xhrUtils.setResponseToNetworkError(this); return; } if ((this.readyState === READY_STATES.OPENED && properties.send) || this.readyState === READY_STATES.HEADERS_RECEIVED || this.readyState === READY_STATES.LOADING) { xhrUtils.requestErrorSteps(this, "abort"); } if (this.readyState === READY_STATES.DONE) { this.readyState = READY_STATES.UNSENT; xhrUtils.setResponseToNetworkError(this); } } getAllResponseHeaders() { const { properties, readyState } = this; if (readyState === READY_STATES.UNSENT || readyState === READY_STATES.OPENED) { return ""; } return Object.keys(properties.responseHeaders) .filter(key => properties.filteredResponseHeaders.indexOf(key) === -1) .map(key => [key.toLowerCase(), properties.responseHeaders[key]].join(": ")) .join("\r\n"); } getResponseHeader(header) { const { properties, readyState } = this; if (readyState === READY_STATES.UNSENT || readyState === READY_STATES.OPENED) { return null; } const lcHeader = header.toLowerCase(); if (properties.filteredResponseHeaders.find(filtered => lcHeader === filtered.toLowerCase())) { return null; } return getResponseHeader(this, lcHeader); } open(method, uri, asynchronous, user, password) { const { flag, properties, _ownerDocument } = this; if (!_ownerDocument) { throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]); } if (!tokenRegexp.test(method)) { throw DOMException.create(this._globalObject, [ "The string did not match the expected pattern.", "SyntaxError" ]); } const upperCaseMethod = method.toUpperCase(); if (forbiddenRequestMethods.has(upperCaseMethod)) { throw DOMException.create(this._globalObject, ["The operation is insecure.", "SecurityError"]); } const { client } = properties; if (client && typeof client.abort === "function") { client.abort(); } if (allowedRequestMethods.has(upperCaseMethod)) { method = upperCaseMethod; } if (typeof asynchronous !== "undefined") { flag.synchronous = !asynchronous; } else { flag.synchronous = false; } if (flag.responseType && flag.synchronous) { throw DOMException.create(this._globalObject, [ "The object does not support the operation or argument.", "InvalidAccessError" ]); } if (flag.synchronous && flag.timeout) { throw DOMException.create(this._globalObject, [ "The object does not support the operation or argument.", "InvalidAccessError" ]); } flag.method = method; let urlObj; try { urlObj = new URL(uri, documentBaseURLSerialized(_ownerDocument)); } catch (e) { throw DOMException.create(this._globalObject, [ "The string did not match the expected pattern.", "SyntaxError" ]); } if (user || (password && !urlObj.username)) { flag.auth = { user, pass: password }; urlObj.username = ""; urlObj.password = ""; } flag.uri = urlObj.href; flag.requestHeaders = {}; flag.preflight = false; properties.send = false; properties.uploadListener = false; properties.abortError = false; this.responseURL = ""; readyStateChange(this, READY_STATES.OPENED); } overrideMimeType(mime) { const { readyState } = this; if (readyState === READY_STATES.LOADING || readyState === READY_STATES.DONE) { throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]); } this.flag.overrideMIMEType = "application/octet-stream"; // Waiting for better spec: https://github.com/whatwg/xhr/issues/157 const parsed = MIMEType.parse(mime); if (parsed) { this.flag.overrideMIMEType = parsed.essence; const charset = parsed.parameters.get("charset"); if (charset) { this.flag.overrideCharset = whatwgEncoding.labelToName(charset); } } } // TODO: Add support for URLSearchParams and ReadableStream send(body) { const { flag, properties, upload, _ownerDocument } = this; // Not per spec, but per tests: https://github.com/whatwg/xhr/issues/65 if (!_ownerDocument) { throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]); } if (this.readyState !== READY_STATES.OPENED || properties.send) { throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]); } properties.beforeSend = true; try { if (flag.method === "GET" || flag.method === "HEAD") { body = null; } if (body !== null) { let encoding = null; let mimeType = null; if (Document.isImpl(body)) { encoding = "UTF-8"; mimeType = (body._parsingMode === "html" ? "text/html" : "application/xml") + ";charset=UTF-8"; flag.body = fragmentSerialization(body, { requireWellFormed: false }); } else { if (typeof body === "string") { encoding = "UTF-8"; } const { buffer, formData, contentType } = extractBody(body); mimeType = contentType; flag.body = buffer || formData; flag.formData = Boolean(formData); } const existingContentType = xhrUtils.getRequestHeader(flag.requestHeaders, "content-type"); if (mimeType !== null && existingContentType === null) { flag.requestHeaders["Content-Type"] = mimeType; } else if (existingContentType !== null && encoding !== null) { // Waiting for better spec: https://github.com/whatwg/xhr/issues/188. This seems like a good guess at what // the spec will be, in the meantime. const parsed = MIMEType.parse(existingContentType); if (parsed) { const charset = parsed.parameters.get("charset"); if (charset && !asciiCaseInsensitiveMatch(charset, encoding) && encoding !== null) { parsed.parameters.set("charset", encoding); xhrUtils.updateRequestHeader(flag.requestHeaders, "content-type", parsed.toString()); } } } } } finally { if (properties.beforeSend) { properties.beforeSend = false; } else { throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]); } } if (Object.keys(upload._eventListeners).length > 0) { properties.uploadListener = true; } // request doesn't like zero-length bodies if (flag.body && flag.body.byteLength === 0) { flag.body = null; } if (flag.synchronous) { const flagStr = JSON.stringify(flag, function (k, v) { if (this === flag && k === "requestManager") { return null; } if (this === flag && k === "pool" && v) { return { maxSockets: v.maxSockets }; } return v; }); const res = spawnSync( process.execPath, [syncWorkerFile], { input: flagStr, maxBuffer: Infinity } ); if (res.status !== 0) { throw new Error(res.stderr.toString()); } if (res.error) { if (typeof res.error === "string") { res.error = new Error(res.error); } throw res.error; } const response = JSON.parse(res.stdout.toString()); const resProp = response.properties; if (resProp.responseBuffer && resProp.responseBuffer.data) { resProp.responseBuffer = Buffer.from(resProp.responseBuffer.data); } if (resProp.cookieJar) { resProp.cookieJar = tough.CookieJar.deserializeSync( resProp.cookieJar, _ownerDocument._cookieJar.store ); } this.readyState = READY_STATES.LOADING; this.status = response.status; this.statusText = response.statusText; this.responseURL = response.responseURL; Object.assign(this.properties, response.properties); if (resProp.error) { xhrUtils.dispatchError(this); throw DOMException.create(this._globalObject, [resProp.error, "NetworkError"]); } else { const { responseBuffer } = properties; const contentLength = getResponseHeader(this, "content-length") || "0"; const bufferLength = parseInt(contentLength) || responseBuffer.length; const progressObj = { lengthComputable: false }; if (bufferLength !== 0) { progressObj.total = bufferLength; progressObj.loaded = bufferLength; progressObj.lengthComputable = true; } fireAnEvent("progress", this, ProgressEvent, progressObj); readyStateChange(this, READY_STATES.DONE); fireAnEvent("load", this, ProgressEvent, progressObj); fireAnEvent("loadend", this, ProgressEvent, progressObj); } } else { properties.send = true; fireAnEvent("loadstart", this, ProgressEvent); const client = xhrUtils.createClient(this); properties.client = client; // For new client, reset totalReceivedChunkSize and bufferStepSize properties.totalReceivedChunkSize = 0; properties.bufferStepSize = 1 * 1024 * 1024; properties.origin = flag.origin; client.on("error", err => { client.removeAllListeners(); properties.error = err; xhrUtils.dispatchError(this); }); client.on("response", res => receiveResponse(this, res)); client.on("redirect", () => { const { response } = client; const destUrlObj = new URL(response.request.headers.Referer); const urlObj = new URL(response.request.uri.href); if (destUrlObj.origin !== urlObj.origin && destUrlObj.origin !== flag.origin) { properties.origin = "null"; } response.request.headers.Origin = properties.origin; if (flag.origin !== destUrlObj.origin && destUrlObj.protocol !== "data:") { if (!xhrUtils.validCORSHeaders(this, response, flag, properties, flag.origin)) { return; } if (urlObj.username || urlObj.password) { properties.error = "Userinfo forbidden in cors redirect"; xhrUtils.dispatchError(this); } } }); if (body !== null && body !== "") { properties.uploadComplete = false; setDispatchProgressEvents(this); } else { properties.uploadComplete = true; } if (this.timeout > 0) { properties.timeoutStart = (new Date()).getTime(); properties.timeoutFn = () => { client.abort(); if (!(this.readyState === READY_STATES.UNSENT || (this.readyState === READY_STATES.OPENED && !properties.send) || this.readyState === READY_STATES.DONE)) { properties.send = false; let stateChanged = false; if (!properties.uploadComplete) { fireAnEvent("progress", upload, ProgressEvent); readyStateChange(this, READY_STATES.DONE); fireAnEvent("timeout", upload, ProgressEvent); fireAnEvent("loadend", upload, ProgressEvent); stateChanged = true; } fireAnEvent("progress", this, ProgressEvent); if (!stateChanged) { readyStateChange(this, READY_STATES.DONE); } fireAnEvent("timeout", this, ProgressEvent); fireAnEvent("loadend", this, ProgressEvent); } this.readyState = READY_STATES.UNSENT; }; properties.timeoutId = setTimeout(properties.timeoutFn, this.timeout); } } } setRequestHeader(header, value) { const { flag, properties } = this; if (this.readyState !== READY_STATES.OPENED || properties.send) { throw DOMException.create(this._globalObject, ["The object is in an invalid state.", "InvalidStateError"]); } value = normalizeHeaderValue(value); if (!tokenRegexp.test(header) || !fieldValueRegexp.test(value)) { throw DOMException.create(this._globalObject, [ "The string did not match the expected pattern.", "SyntaxError" ]); } const lcHeader = header.toLowerCase(); if (forbiddenRequestHeaders.has(lcHeader) || lcHeader.startsWith("sec-") || lcHeader.startsWith("proxy-")) { return; } const keys = Object.keys(flag.requestHeaders); let n = keys.length; while (n--) { const key = keys[n]; if (key.toLowerCase() === lcHeader) { flag.requestHeaders[key] += ", " + value; return; } } flag.requestHeaders[header] = value; } } setupForSimpleEventAccessors(XMLHttpRequestImpl.prototype, ["readystatechange"]); function readyStateChange(xhr, readyState) { if (xhr.readyState === readyState) { return; } xhr.readyState = readyState; fireAnEvent("readystatechange", xhr); } function receiveResponse(xhr, response) { const { flag, properties } = xhr; const { statusCode } = response; let byteOffset = 0; const headers = {}; const filteredResponseHeaders = []; const headerMap = {}; const { rawHeaders } = response; const n = Number(rawHeaders.length); for (let i = 0; i < n; i += 2) { const k = rawHeaders[i]; const kl = k.toLowerCase(); const v = rawHeaders[i + 1]; if (uniqueResponseHeaders.has(kl)) { if (headerMap[kl] !== undefined) { delete headers[headerMap[kl]]; } headers[k] = v; } else if (headerMap[kl] !== undefined) { headers[headerMap[kl]] += ", " + v; } else { headers[k] = v; } headerMap[kl] = k; } const destUrlObj = new URL(response.request.uri.href); if (properties.origin !== destUrlObj.origin && destUrlObj.protocol !== "data:") { if (!xhrUtils.validCORSHeaders(xhr, response, flag, properties, properties.origin)) { return; } const acehStr = response.headers["access-control-expose-headers"]; const aceh = new Set(acehStr ? acehStr.trim().toLowerCase().split(xhrUtils.headerListSeparatorRegexp) : []); for (const header in headers) { const lcHeader = header.toLowerCase(); if (!corsSafeResponseHeaders.has(lcHeader) && !aceh.has(lcHeader)) { filteredResponseHeaders.push(header); } } } for (const header in headers) { const lcHeader = header.toLowerCase(); if (forbiddenResponseHeaders.has(lcHeader)) { filteredResponseHeaders.push(header); } } xhr.responseURL = destUrlObj.href; xhr.status = statusCode; xhr.statusText = response.statusMessage || HTTP_STATUS_CODES[statusCode] || ""; properties.responseHeaders = headers; properties.filteredResponseHeaders = filteredResponseHeaders; const contentLength = getResponseHeader(xhr, "content-length") || "0"; const bufferLength = parseInt(contentLength) || 0; const progressObj = { lengthComputable: false }; let lastProgressReported; if (bufferLength !== 0) { progressObj.total = bufferLength; progressObj.loaded = 0; progressObj.lengthComputable = true; } // pre-allocate buffer. properties.responseBuffer = Buffer.alloc(properties.bufferStepSize); properties.responseCache = null; properties.responseTextCache = null; properties.responseXMLCache = null; readyStateChange(xhr, READY_STATES.HEADERS_RECEIVED); if (!properties.client) { // The request was aborted in reaction to the readystatechange event. return; } // Can't use the client since the client gets the post-ungzipping bytes (which can be greater than the // Content-Length). response.on("data", chunk => { byteOffset += chunk.length; progressObj.loaded = byteOffset; }); properties.client.on("data", chunk => { properties.totalReceivedChunkSize += chunk.length; if (properties.totalReceivedChunkSize >= properties.bufferStepSize) { properties.bufferStepSize *= 2; while (properties.totalReceivedChunkSize >= properties.bufferStepSize) { properties.bufferStepSize *= 2; } const tmpBuf = Buffer.alloc(properties.bufferStepSize); properties.responseBuffer.copy(tmpBuf, 0, 0, properties.responseBuffer.length); properties.responseBuffer = tmpBuf; } chunk.copy(properties.responseBuffer, properties.totalReceivedChunkSize - chunk.length, 0, chunk.length); properties.responseCache = null; properties.responseTextCache = null; properties.responseXMLCache = null; if (xhr.readyState === READY_STATES.HEADERS_RECEIVED) { xhr.readyState = READY_STATES.LOADING; } fireAnEvent("readystatechange", xhr); if (progressObj.total !== progressObj.loaded || properties.totalReceivedChunkSize === byteOffset) { if (lastProgressReported !== progressObj.loaded) { // This is a necessary check in the gzip case where we can be getting new data from the client, as it // un-gzips, but no new data has been gotten from the response, so we should not fire a progress event. lastProgressReported = progressObj.loaded; fireAnEvent("progress", xhr, ProgressEvent, progressObj); } } }); properties.client.on("end", () => { clearTimeout(properties.timeoutId); properties.timeoutFn = null; properties.timeoutStart = 0; properties.client = null; fireAnEvent("progress", xhr, ProgressEvent, progressObj); readyStateChange(xhr, READY_STATES.DONE); fireAnEvent("load", xhr, ProgressEvent, progressObj); fireAnEvent("loadend", xhr, ProgressEvent, progressObj); }); } function setDispatchProgressEvents(xhr) { const { properties, upload } = xhr; const { client } = properties; let total = 0; let lengthComputable = false; const length = client.headers && parseInt(xhrUtils.getRequestHeader(client.headers, "content-length")); if (length) { total = length; lengthComputable = true; } const initProgress = { lengthComputable, total, loaded: 0 }; if (properties.uploadListener) { fireAnEvent("loadstart", upload, ProgressEvent, initProgress); } client.on("request", req => { req.on("response", () => { properties.uploadComplete = true; if (!properties.uploadListener) { return; } const progress = { lengthComputable, total, loaded: total }; fireAnEvent("progress", upload, ProgressEvent, progress); fireAnEvent("load", upload, ProgressEvent, progress); fireAnEvent("loadend", upload, ProgressEvent, progress); }); }); } function finalMIMEType(xhr) { const { flag } = xhr; return flag.overrideMIMEType || getResponseHeader(xhr, "content-type"); } function finalCharset(xhr) { const { flag } = xhr; if (flag.overrideCharset) { return flag.overrideCharset; } const parsedContentType = MIMEType.parse(getResponseHeader(xhr, "content-type")); if (parsedContentType) { return whatwgEncoding.labelToName(parsedContentType.parameters.get("charset")); } return null; } function getResponseHeader(xhr, lcHeader) { const { properties } = xhr; const keys = Object.keys(properties.responseHeaders); let n = keys.length; while (n--) { const key = keys[n]; if (key.toLowerCase() === lcHeader) { return properties.responseHeaders[key]; } } return null; } function normalizeHeaderValue(value) { return value.replace(/^[\x09\x0A\x0D\x20]+/, "").replace(/[\x09\x0A\x0D\x20]+$/, ""); } function extractBody(bodyInit) { // https://fetch.spec.whatwg.org/#concept-bodyinit-extract // except we represent the body as a Node.js Buffer instead, // or a special case for FormData since we want request to handle that. Probably it would be // cleaner (and allow a future without request) if we did the form encoding ourself. if (Blob.isImpl(bodyInit)) { return { buffer: bodyInit._buffer, contentType: bodyInit.type === "" ? null : bodyInit.type }; } else if (isArrayBuffer(bodyInit)) { return { buffer: Buffer.from(bodyInit), contentType: null }; } else if (ArrayBuffer.isView(bodyInit)) { return { buffer: Buffer.from(bodyInit.buffer, bodyInit.byteOffset, bodyInit.byteLength), contentType: null }; } else if (FormData.isImpl(bodyInit)) { const formData = []; for (const entry of bodyInit._entries) { let val; if (Blob.isImpl(entry.value)) { const blob = entry.value; val = { name: entry.name, value: blob._buffer, options: { filename: blob.name, contentType: blob.type, knownLength: blob.size } }; } else { val = entry; } formData.push(val); } return { formData }; } // Must be a string return { buffer: Buffer.from(bodyInit, "utf-8"), contentType: "text/plain;charset=UTF-8" }; } exports.implementation = XMLHttpRequestImpl;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/xhr/XMLHttpRequest-impl.js
XMLHttpRequest-impl.js
"use strict"; const DOMException = require("domexception/webidl2js-wrapper"); const { clone } = require("jsdom/lib/jsdom/living/node"); const NODE_TYPE = require("jsdom/lib/jsdom/living/node-type"); const { parseFragment } = require("jsdom/lib/jsdom/browser/parser"); const { HTML_NS } = require("jsdom/lib/jsdom/living/helpers/namespaces"); const { domSymbolTree } = require("jsdom/lib/jsdom/living/helpers/internal-constants"); const { compareBoundaryPointsPosition } = require("jsdom/lib/jsdom/living/range/boundary-point"); const { nodeRoot, nodeLength, isInclusiveAncestor } = require("jsdom/lib/jsdom/living/helpers/node"); const { createElement } = require("jsdom/lib/jsdom/living/helpers/create-element"); const AbstractRangeImpl = require("jsdom/lib/jsdom/living/range/AbstractRange-impl").implementation; const Range = require("jsdom/lib/jsdom/living/generated/Range"); const DocumentFragment = require("jsdom/lib/jsdom/living/generated/DocumentFragment"); const { implForWrapper } = require("jsdom/lib/jsdom/living/generated/utils"); const RANGE_COMPARISON_TYPE = { START_TO_START: 0, START_TO_END: 1, END_TO_END: 2, END_TO_START: 3 }; class RangeImpl extends AbstractRangeImpl { constructor(globalObject, args, privateData) { super(globalObject, args, privateData); const defaultBoundaryPoint = { node: implForWrapper(globalObject._document), offset: 0 }; const { start = defaultBoundaryPoint, end = defaultBoundaryPoint } = privateData; this._setLiveRangeStart(start.node, start.offset); this._setLiveRangeEnd(end.node, end.offset); } // https://dom.spec.whatwg.org/#dom-range-commonancestorcontainer get commonAncestorContainer() { const { _start, _end } = this; for (const container of domSymbolTree.ancestorsIterator(_start.node)) { if (isInclusiveAncestor(container, _end.node)) { return container; } } return null; } // https://dom.spec.whatwg.org/#dom-range-setstart setStart(node, offset) { setBoundaryPointStart(this, node, offset); } // https://dom.spec.whatwg.org/#dom-range-setend setEnd(node, offset) { setBoundaryPointEnd(this, node, offset); } // https://dom.spec.whatwg.org/#dom-range-setstartbefore setStartBefore(node) { const parent = domSymbolTree.parent(node); if (!parent) { throw DOMException.create(this._globalObject, ["The given Node has no parent.", "InvalidNodeTypeError"]); } setBoundaryPointStart(this, parent, domSymbolTree.index(node)); } // https://dom.spec.whatwg.org/#dom-range-setstartafter setStartAfter(node) { const parent = domSymbolTree.parent(node); if (!parent) { throw DOMException.create(this._globalObject, ["The given Node has no parent.", "InvalidNodeTypeError"]); } setBoundaryPointStart(this, parent, domSymbolTree.index(node) + 1); } // https://dom.spec.whatwg.org/#dom-range-setendbefore setEndBefore(node) { const parent = domSymbolTree.parent(node); if (!parent) { throw DOMException.create(this._globalObject, ["The given Node has no parent.", "InvalidNodeTypeError"]); } setBoundaryPointEnd(this, parent, domSymbolTree.index(node)); } // https://dom.spec.whatwg.org/#dom-range-setendafter setEndAfter(node) { const parent = domSymbolTree.parent(node); if (!parent) { throw DOMException.create(this._globalObject, ["The given Node has no parent.", "InvalidNodeTypeError"]); } setBoundaryPointEnd(this, parent, domSymbolTree.index(node) + 1); } // https://dom.spec.whatwg.org/#dom-range-collapse collapse(toStart) { if (toStart) { this._setLiveRangeEnd(this._start.node, this._start.offset); } else { this._setLiveRangeStart(this._end.node, this._end.offset); } } // https://dom.spec.whatwg.org/#dom-range-selectnode selectNode(node) { selectNodeWithinRange(node, this); } // https://dom.spec.whatwg.org/#dom-range-selectnodecontents selectNodeContents(node) { if (node.nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE) { throw DOMException.create(this._globalObject, [ "DocumentType Node can't be used as boundary point.", "InvalidNodeTypeError" ]); } const length = nodeLength(node); this._setLiveRangeStart(node, 0); this._setLiveRangeEnd(node, length); } // https://dom.spec.whatwg.org/#dom-range-compareboundarypoints compareBoundaryPoints(how, sourceRange) { if ( how !== RANGE_COMPARISON_TYPE.START_TO_START && how !== RANGE_COMPARISON_TYPE.START_TO_END && how !== RANGE_COMPARISON_TYPE.END_TO_END && how !== RANGE_COMPARISON_TYPE.END_TO_START ) { const message = "The comparison method provided must be one of 'START_TO_START', 'START_TO_END', 'END_TO_END', " + "or 'END_TO_START'."; throw DOMException.create(this._globalObject, [message, "NotSupportedError"]); } if (this._root !== sourceRange._root) { throw DOMException.create(this._globalObject, ["The two Ranges are not in the same tree.", "WrongDocumentError"]); } let thisPoint; let otherPoint; if (how === RANGE_COMPARISON_TYPE.START_TO_START) { thisPoint = this._start; otherPoint = sourceRange._start; } else if (how === RANGE_COMPARISON_TYPE.START_TO_END) { thisPoint = this._end; otherPoint = sourceRange._start; } else if (how === RANGE_COMPARISON_TYPE.END_TO_END) { thisPoint = this._end; otherPoint = sourceRange._end; } else { thisPoint = this._start; otherPoint = sourceRange._end; } return compareBoundaryPointsPosition(thisPoint, otherPoint); } // https://dom.spec.whatwg.org/#dom-range-deletecontents deleteContents() { if (this.collapsed) { return; } const { _start: originalStart, _end: originalEnd } = this; if ( originalStart.node === originalEnd.node && ( originalStart.node.nodeType === NODE_TYPE.TEXT_NODE || originalStart.node.nodeType === NODE_TYPE.PROCESSING_INSTRUCTION_NODE || originalStart.node.nodeType === NODE_TYPE.COMMENT_NODE ) ) { originalStart.node.replaceData(originalStart.offset, originalEnd.offset - originalStart.offset, ""); return; } const nodesToRemove = []; let currentNode = this._start.node; const endNode = nextNodeDescendant(this._end.node); while (currentNode && currentNode !== endNode) { if ( isContained(currentNode, this) && !isContained(domSymbolTree.parent(currentNode), this) ) { nodesToRemove.push(currentNode); } currentNode = domSymbolTree.following(currentNode); } let newNode; let newOffset; if (isInclusiveAncestor(originalStart.node, originalEnd.node)) { newNode = originalStart.node; newOffset = originalStart.offset; } else { let referenceNode = originalStart.node; while ( referenceNode && !isInclusiveAncestor(domSymbolTree.parent(referenceNode), originalEnd.node) ) { referenceNode = domSymbolTree.parent(referenceNode); } newNode = domSymbolTree.parent(referenceNode); newOffset = domSymbolTree.index(referenceNode) + 1; } if ( originalStart.node.nodeType === NODE_TYPE.TEXT_NODE || originalStart.node.nodeType === NODE_TYPE.PROCESSING_INSTRUCTION_NODE || originalStart.node.nodeType === NODE_TYPE.COMMENT_NODE ) { originalStart.node.replaceData(originalStart.offset, nodeLength(originalStart.node) - originalStart.offset, ""); } for (const node of nodesToRemove) { const parent = domSymbolTree.parent(node); parent.removeChild(node); } if ( originalEnd.node.nodeType === NODE_TYPE.TEXT_NODE || originalEnd.node.nodeType === NODE_TYPE.PROCESSING_INSTRUCTION_NODE || originalEnd.node.nodeType === NODE_TYPE.COMMENT_NODE ) { originalEnd.node.replaceData(0, originalEnd.offset, ""); } this._setLiveRangeStart(newNode, newOffset); this._setLiveRangeEnd(newNode, newOffset); } // https://dom.spec.whatwg.org/#dom-range-extractcontents extractContents() { return extractRange(this); } // https://dom.spec.whatwg.org/#dom-range-clonecontents cloneContents() { return cloneRange(this); } // https://dom.spec.whatwg.org/#dom-range-insertnode insertNode(node) { insertNodeInRange(node, this); } // https://dom.spec.whatwg.org/#dom-range-surroundcontents surroundContents(newParent) { let node = this.commonAncestorContainer; const endNode = nextNodeDescendant(node); while (node !== endNode) { if (node.nodeType !== NODE_TYPE.TEXT_NODE && isPartiallyContained(node, this)) { throw DOMException.create(this._globalObject, [ "The Range has partially contains a non-Text node.", "InvalidStateError" ]); } node = domSymbolTree.following(node); } if ( newParent.nodeType === NODE_TYPE.DOCUMENT_NODE || newParent.nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE || newParent.nodeType === NODE_TYPE.DOCUMENT_FRAGMENT_NODE ) { throw DOMException.create(this._globalObject, ["Invalid element type.", "InvalidNodeTypeError"]); } const fragment = extractRange(this); while (domSymbolTree.firstChild(newParent)) { newParent.removeChild(domSymbolTree.firstChild(newParent)); } insertNodeInRange(newParent, this); newParent.appendChild(fragment); selectNodeWithinRange(newParent, this); } // https://dom.spec.whatwg.org/#dom-range-clonerange cloneRange() { const { _start, _end, _globalObject } = this; return Range.createImpl(_globalObject, [], { start: { node: _start.node, offset: _start.offset }, end: { node: _end.node, offset: _end.offset } }); } // https://dom.spec.whatwg.org/#dom-range-detach detach() { // Do nothing by spec! } // https://dom.spec.whatwg.org/#dom-range-ispointinrange isPointInRange(node, offset) { if (nodeRoot(node) !== this._root) { return false; } validateSetBoundaryPoint(node, offset); const bp = { node, offset }; if ( compareBoundaryPointsPosition(bp, this._start) === -1 || compareBoundaryPointsPosition(bp, this._end) === 1 ) { return false; } return true; } // https://dom.spec.whatwg.org/#dom-range-comparepoint comparePoint(node, offset) { if (nodeRoot(node) !== this._root) { throw DOMException.create(this._globalObject, [ "The given Node and the Range are not in the same tree.", "WrongDocumentError" ]); } validateSetBoundaryPoint(node, offset); const bp = { node, offset }; if (compareBoundaryPointsPosition(bp, this._start) === -1) { return -1; } else if (compareBoundaryPointsPosition(bp, this._end) === 1) { return 1; } return 0; } // https://dom.spec.whatwg.org/#dom-range-intersectsnode intersectsNode(node) { if (nodeRoot(node) !== this._root) { return false; } const parent = domSymbolTree.parent(node); if (!parent) { return true; } const offset = domSymbolTree.index(node); return ( compareBoundaryPointsPosition({ node: parent, offset }, this._end) === -1 && compareBoundaryPointsPosition({ node: parent, offset: offset + 1 }, this._start) === 1 ); } // https://dom.spec.whatwg.org/#dom-range-stringifier toString() { let s = ""; const { _start, _end } = this; if (_start.node === _end.node && _start.node.nodeType === NODE_TYPE.TEXT_NODE) { return _start.node.data.slice(_start.offset, _end.offset); } if (_start.node.nodeType === NODE_TYPE.TEXT_NODE) { s += _start.node.data.slice(_start.offset); } let currentNode = _start.node; const endNode = nextNodeDescendant(_end.node); while (currentNode && currentNode !== endNode) { if (currentNode.nodeType === NODE_TYPE.TEXT_NODE && isContained(currentNode, this)) { s += currentNode.data; } currentNode = domSymbolTree.following(currentNode); } if (_end.node.nodeType === NODE_TYPE.TEXT_NODE) { s += _end.node.data.slice(0, _end.offset); } return s; } // https://w3c.github.io/DOM-Parsing/#dom-range-createcontextualfragment createContextualFragment(fragment) { const { node } = this._start; let element; switch (node.nodeType) { case NODE_TYPE.DOCUMENT_NODE: case NODE_TYPE.DOCUMENT_FRAGMENT_NODE: element = null; break; case NODE_TYPE.ELEMENT_NODE: element = node; break; case NODE_TYPE.TEXT_NODE: case NODE_TYPE.COMMENT_NODE: element = node.parentElement; break; default: throw new Error("Internal error: Invalid range start node"); } if ( element === null || ( element._ownerDocument._parsingMode === "html" && element._localName === "html" && element._namespaceURI === HTML_NS ) ) { element = createElement(node._ownerDocument, "body", HTML_NS); } return parseFragment(fragment, element); } // https://dom.spec.whatwg.org/#concept-range-root get _root() { return nodeRoot(this._start.node); } _setLiveRangeStart(node, offset) { if (this._start && this._start.node !== node) { this._start.node._referencedRanges.delete(this); } if (!node._referencedRanges.has(this)) { node._referencedRanges.add(this); } this._start = { node, offset }; } _setLiveRangeEnd(node, offset) { if (this._end && this._end.node !== node) { this._end.node._referencedRanges.delete(this); } if (!node._referencedRanges.has(this)) { node._referencedRanges.add(this); } this._end = { node, offset }; } } function nextNodeDescendant(node) { while (node && !domSymbolTree.nextSibling(node)) { node = domSymbolTree.parent(node); } if (!node) { return null; } return domSymbolTree.nextSibling(node); } // https://dom.spec.whatwg.org/#concept-range-bp-set function validateSetBoundaryPoint(node, offset) { if (node.nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE) { throw DOMException.create(node._globalObject, [ "DocumentType Node can't be used as boundary point.", "InvalidNodeTypeError" ]); } if (offset > nodeLength(node)) { throw DOMException.create(node._globalObject, ["Offset out of bound.", "IndexSizeError"]); } } function setBoundaryPointStart(range, node, offset) { validateSetBoundaryPoint(node, offset); const bp = { node, offset }; if ( nodeRoot(node) !== range._root || compareBoundaryPointsPosition(bp, range._end) === 1 ) { range._setLiveRangeEnd(node, offset); } range._setLiveRangeStart(node, offset); } function setBoundaryPointEnd(range, node, offset) { validateSetBoundaryPoint(node, offset); const bp = { node, offset }; if ( nodeRoot(node) !== range._root || compareBoundaryPointsPosition(bp, range._start) === -1 ) { range._setLiveRangeStart(node, offset); } range._setLiveRangeEnd(node, offset); } // https://dom.spec.whatwg.org/#concept-range-select function selectNodeWithinRange(node, range) { const parent = domSymbolTree.parent(node); if (!parent) { throw DOMException.create(node._globalObject, ["The given Node has no parent.", "InvalidNodeTypeError"]); } const index = domSymbolTree.index(node); range._setLiveRangeStart(parent, index); range._setLiveRangeEnd(parent, index + 1); } // https://dom.spec.whatwg.org/#contained function isContained(node, range) { const { _start, _end } = range; return ( compareBoundaryPointsPosition({ node, offset: 0 }, _start) === 1 && compareBoundaryPointsPosition({ node, offset: nodeLength(node) }, _end) === -1 ); } // https://dom.spec.whatwg.org/#partially-contained function isPartiallyContained(node, range) { const { _start, _end } = range; return ( (isInclusiveAncestor(node, _start.node) && !isInclusiveAncestor(node, _end.node)) || (!isInclusiveAncestor(node, _start.node) && isInclusiveAncestor(node, _end.node)) ); } // https://dom.spec.whatwg.org/#concept-range-insert function insertNodeInRange(node, range) { const { node: startNode, offset: startOffset } = range._start; if ( startNode.nodeType === NODE_TYPE.PROCESSING_INSTRUCTION_NODE || startNode.nodeType === NODE_TYPE.COMMENT_NODE || (startNode.nodeType === NODE_TYPE.TEXT_NODE && !domSymbolTree.parent(startNode)) || node === startNode ) { throw DOMException.create(node._globalObject, ["Invalid start node.", "HierarchyRequestError"]); } let referenceNode = startNode.nodeType === NODE_TYPE.TEXT_NODE ? startNode : domSymbolTree.childrenToArray(startNode)[startOffset] || null; const parent = !referenceNode ? startNode : domSymbolTree.parent(referenceNode); parent._preInsertValidity(node, referenceNode); if (startNode.nodeType === NODE_TYPE.TEXT_NODE) { referenceNode = startNode.splitText(startOffset); } if (node === referenceNode) { referenceNode = domSymbolTree.nextSibling(referenceNode); } const nodeParent = domSymbolTree.parent(node); if (nodeParent) { nodeParent.removeChild(node); } let newOffset = !referenceNode ? nodeLength(parent) : domSymbolTree.index(referenceNode); newOffset += node.nodeType === NODE_TYPE.DOCUMENT_FRAGMENT_NODE ? nodeLength(node) : 1; parent.insertBefore(node, referenceNode); if (range.collapsed) { range._setLiveRangeEnd(parent, newOffset); } } // https://dom.spec.whatwg.org/#concept-range-clone function cloneRange(range) { const { _start: originalStart, _end: originalEnd, _globalObject } = range; const fragment = DocumentFragment.createImpl(_globalObject, [], { ownerDocument: originalStart.node._ownerDocument }); if (range.collapsed) { return fragment; } if ( originalStart.node === originalEnd.node && ( originalStart.node.nodeType === NODE_TYPE.TEXT_NODE || originalStart.node.nodeType === NODE_TYPE.PROCESSING_INSTRUCTION_NODE || originalStart.node.nodeType === NODE_TYPE.COMMENT_NODE ) ) { const cloned = clone(originalStart.node); cloned._data = cloned.substringData(originalStart.offset, originalEnd.offset - originalStart.offset); fragment.appendChild(cloned); return fragment; } let commonAncestor = originalStart.node; while (!isInclusiveAncestor(commonAncestor, originalEnd.node)) { commonAncestor = domSymbolTree.parent(commonAncestor); } let firstPartialContainedChild = null; if (!isInclusiveAncestor(originalStart.node, originalEnd.node)) { let candidate = domSymbolTree.firstChild(commonAncestor); while (!firstPartialContainedChild) { if (isPartiallyContained(candidate, range)) { firstPartialContainedChild = candidate; } candidate = domSymbolTree.nextSibling(candidate); } } let lastPartiallyContainedChild = null; if (!isInclusiveAncestor(originalEnd.node, originalStart.node)) { let candidate = domSymbolTree.lastChild(commonAncestor); while (!lastPartiallyContainedChild) { if (isPartiallyContained(candidate, range)) { lastPartiallyContainedChild = candidate; } candidate = domSymbolTree.previousSibling(candidate); } } const containedChildren = domSymbolTree.childrenToArray(commonAncestor) .filter(node => isContained(node, range)); const hasDoctypeChildren = containedChildren.some(node => node.nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE); if (hasDoctypeChildren) { throw DOMException.create(range._globalObject, ["Invalid document type element.", "HierarchyRequestError"]); } if ( firstPartialContainedChild !== null && ( firstPartialContainedChild.nodeType === NODE_TYPE.TEXT_NODE || firstPartialContainedChild.nodeType === NODE_TYPE.PROCESSING_INSTRUCTION_NODE || firstPartialContainedChild.nodeType === NODE_TYPE.COMMENT_NODE ) ) { const cloned = clone(originalStart.node); cloned._data = cloned.substringData(originalStart.offset, nodeLength(originalStart.node) - originalStart.offset); fragment.appendChild(cloned); } else if (firstPartialContainedChild !== null) { const cloned = clone(firstPartialContainedChild); fragment.appendChild(cloned); const subrange = Range.createImpl(_globalObject, [], { start: { node: originalStart.node, offset: originalStart.offset }, end: { node: firstPartialContainedChild, offset: nodeLength(firstPartialContainedChild) } }); const subfragment = cloneRange(subrange); cloned.appendChild(subfragment); } for (const containedChild of containedChildren) { const cloned = clone(containedChild, undefined, true); fragment.appendChild(cloned); } if ( lastPartiallyContainedChild !== null && ( lastPartiallyContainedChild.nodeType === NODE_TYPE.TEXT_NODE || lastPartiallyContainedChild.nodeType === NODE_TYPE.PROCESSING_INSTRUCTION_NODE || lastPartiallyContainedChild.nodeType === NODE_TYPE.COMMENT_NODE ) ) { const cloned = clone(originalEnd.node); cloned._data = cloned.substringData(0, originalEnd.offset); fragment.appendChild(cloned); } else if (lastPartiallyContainedChild !== null) { const cloned = clone(lastPartiallyContainedChild); fragment.appendChild(cloned); const subrange = Range.createImpl(_globalObject, [], { start: { node: lastPartiallyContainedChild, offset: 0 }, end: { node: originalEnd.node, offset: originalEnd.offset } }); const subfragment = cloneRange(subrange); cloned.appendChild(subfragment); } return fragment; } // https://dom.spec.whatwg.org/#concept-range-extract function extractRange(range) { const { _start: originalStart, _end: originalEnd, _globalObject } = range; const fragment = DocumentFragment.createImpl(_globalObject, [], { ownerDocument: originalStart.node._ownerDocument }); if (range.collapsed) { return fragment; } if ( originalStart.node === originalEnd.node && ( originalStart.node.nodeType === NODE_TYPE.TEXT_NODE || originalStart.node.nodeType === NODE_TYPE.PROCESSING_INSTRUCTION_NODE || originalStart.node.nodeType === NODE_TYPE.COMMENT_NODE ) ) { const cloned = clone(originalStart.node); cloned._data = cloned.substringData(originalStart.offset, originalEnd.offset - originalStart.offset); fragment.appendChild(cloned); originalStart.node.replaceData(originalStart.offset, originalEnd.offset - originalStart.offset, ""); return fragment; } let commonAncestor = originalStart.node; while (!isInclusiveAncestor(commonAncestor, originalEnd.node)) { commonAncestor = domSymbolTree.parent(commonAncestor); } let firstPartialContainedChild = null; if (!isInclusiveAncestor(originalStart.node, originalEnd.node)) { let candidate = domSymbolTree.firstChild(commonAncestor); while (!firstPartialContainedChild) { if (isPartiallyContained(candidate, range)) { firstPartialContainedChild = candidate; } candidate = domSymbolTree.nextSibling(candidate); } } let lastPartiallyContainedChild = null; if (!isInclusiveAncestor(originalEnd.node, originalStart.node)) { let candidate = domSymbolTree.lastChild(commonAncestor); while (!lastPartiallyContainedChild) { if (isPartiallyContained(candidate, range)) { lastPartiallyContainedChild = candidate; } candidate = domSymbolTree.previousSibling(candidate); } } const containedChildren = domSymbolTree.childrenToArray(commonAncestor) .filter(node => isContained(node, range)); const hasDoctypeChildren = containedChildren.some(node => node.nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE); if (hasDoctypeChildren) { throw DOMException.create(range._globalObject, ["Invalid document type element.", "HierarchyRequestError"]); } let newNode; let newOffset; if (isInclusiveAncestor(originalStart.node, originalEnd.node)) { newNode = originalStart.node; newOffset = originalStart.offset; } else { let referenceNode = originalStart.node; while ( referenceNode && !isInclusiveAncestor(domSymbolTree.parent(referenceNode), originalEnd.node) ) { referenceNode = domSymbolTree.parent(referenceNode); } newNode = domSymbolTree.parent(referenceNode); newOffset = domSymbolTree.index(referenceNode) + 1; } if ( firstPartialContainedChild !== null && ( firstPartialContainedChild.nodeType === NODE_TYPE.TEXT_NODE || firstPartialContainedChild.nodeType === NODE_TYPE.PROCESSING_INSTRUCTION_NODE || firstPartialContainedChild.nodeType === NODE_TYPE.COMMENT_NODE ) ) { const cloned = clone(originalStart.node); cloned._data = cloned.substringData(originalStart.offset, nodeLength(originalStart.node) - originalStart.offset); fragment.appendChild(cloned); originalStart.node.replaceData(originalStart.offset, nodeLength(originalStart.node) - originalStart.offset, ""); } else if (firstPartialContainedChild !== null) { const cloned = clone(firstPartialContainedChild); fragment.appendChild(cloned); const subrange = Range.createImpl(_globalObject, [], { start: { node: originalStart.node, offset: originalStart.offset }, end: { node: firstPartialContainedChild, offset: nodeLength(firstPartialContainedChild) } }); const subfragment = extractRange(subrange); cloned.appendChild(subfragment); } for (const containedChild of containedChildren) { fragment.appendChild(containedChild); } if ( lastPartiallyContainedChild !== null && ( lastPartiallyContainedChild.nodeType === NODE_TYPE.TEXT_NODE || lastPartiallyContainedChild.nodeType === NODE_TYPE.PROCESSING_INSTRUCTION_NODE || lastPartiallyContainedChild.nodeType === NODE_TYPE.COMMENT_NODE ) ) { const cloned = clone(originalEnd.node); cloned._data = cloned.substringData(0, originalEnd.offset); fragment.appendChild(cloned); originalEnd.node.replaceData(0, originalEnd.offset, ""); } else if (lastPartiallyContainedChild !== null) { const cloned = clone(lastPartiallyContainedChild); fragment.appendChild(cloned); const subrange = Range.createImpl(_globalObject, [], { start: { node: lastPartiallyContainedChild, offset: 0 }, end: { node: originalEnd.node, offset: originalEnd.offset } }); const subfragment = extractRange(subrange); cloned.appendChild(subfragment); } range._setLiveRangeStart(newNode, newOffset); range._setLiveRangeEnd(newNode, newOffset); return fragment; } module.exports = { implementation: RangeImpl, setBoundaryPointStart, setBoundaryPointEnd };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/living/range/Range-impl.js
Range-impl.js
// We use a .js file because otherwise we can't browserify this. (brfs is unusable due to lack of ES2015 support) module.exports = ` /* * The default style sheet used to render HTML. * * Copyright (C) 2000 Lars Knoll ([email protected]) * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ @namespace "http://www.w3.org/1999/xhtml"; html { display: block } :root { scroll-blocks-on: start-touch wheel-event } /* children of the <head> element all have display:none */ head { display: none } meta { display: none } title { display: none } link { display: none } style { display: none } script { display: none } /* generic block-level elements */ body { display: block; margin: 8px } p { display: block; -webkit-margin-before: 1__qem; -webkit-margin-after: 1__qem; -webkit-margin-start: 0; -webkit-margin-end: 0; } div { display: block } layer { display: block } article, aside, footer, header, hgroup, main, nav, section { display: block } marquee { display: inline-block; } address { display: block } blockquote { display: block; -webkit-margin-before: 1__qem; -webkit-margin-after: 1em; -webkit-margin-start: 40px; -webkit-margin-end: 40px; } figcaption { display: block } figure { display: block; -webkit-margin-before: 1em; -webkit-margin-after: 1em; -webkit-margin-start: 40px; -webkit-margin-end: 40px; } q { display: inline } /* nwmatcher does not support ::before and ::after, so we can't render q correctly: https://html.spec.whatwg.org/multipage/rendering.html#phrasing-content-3 TODO: add q::before and q::after selectors */ center { display: block; /* special centering to be able to emulate the html4/netscape behaviour */ text-align: -webkit-center } hr { display: block; -webkit-margin-before: 0.5em; -webkit-margin-after: 0.5em; -webkit-margin-start: auto; -webkit-margin-end: auto; border-style: inset; border-width: 1px; box-sizing: border-box } map { display: inline } video { object-fit: contain; } /* heading elements */ h1 { display: block; font-size: 2em; -webkit-margin-before: 0.67__qem; -webkit-margin-after: 0.67em; -webkit-margin-start: 0; -webkit-margin-end: 0; font-weight: bold } article h1, aside h1, nav h1, section h1 { font-size: 1.5em; -webkit-margin-before: 0.83__qem; -webkit-margin-after: 0.83em; } article article h1, article aside h1, article nav h1, article section h1, aside article h1, aside aside h1, aside nav h1, aside section h1, nav article h1, nav aside h1, nav nav h1, nav section h1, section article h1, section aside h1, section nav h1, section section h1 { font-size: 1.17em; -webkit-margin-before: 1__qem; -webkit-margin-after: 1em; } /* Remaining selectors are deleted because nwmatcher does not support :matches() and expanding the selectors manually would be far too verbose. Also see https://html.spec.whatwg.org/multipage/rendering.html#sections-and-headings TODO: rewrite to use :matches() when nwmatcher supports it. */ h2 { display: block; font-size: 1.5em; -webkit-margin-before: 0.83__qem; -webkit-margin-after: 0.83em; -webkit-margin-start: 0; -webkit-margin-end: 0; font-weight: bold } h3 { display: block; font-size: 1.17em; -webkit-margin-before: 1__qem; -webkit-margin-after: 1em; -webkit-margin-start: 0; -webkit-margin-end: 0; font-weight: bold } h4 { display: block; -webkit-margin-before: 1.33__qem; -webkit-margin-after: 1.33em; -webkit-margin-start: 0; -webkit-margin-end: 0; font-weight: bold } h5 { display: block; font-size: .83em; -webkit-margin-before: 1.67__qem; -webkit-margin-after: 1.67em; -webkit-margin-start: 0; -webkit-margin-end: 0; font-weight: bold } h6 { display: block; font-size: .67em; -webkit-margin-before: 2.33__qem; -webkit-margin-after: 2.33em; -webkit-margin-start: 0; -webkit-margin-end: 0; font-weight: bold } /* tables */ table { display: table; border-collapse: separate; border-spacing: 2px; border-color: gray } thead { display: table-header-group; vertical-align: middle; border-color: inherit } tbody { display: table-row-group; vertical-align: middle; border-color: inherit } tfoot { display: table-footer-group; vertical-align: middle; border-color: inherit } /* for tables without table section elements (can happen with XHTML or dynamically created tables) */ table > tr { vertical-align: middle; } col { display: table-column } colgroup { display: table-column-group } tr { display: table-row; vertical-align: inherit; border-color: inherit } td, th { display: table-cell; vertical-align: inherit } th { font-weight: bold } caption { display: table-caption; text-align: -webkit-center } /* lists */ ul, menu, dir { display: block; list-style-type: disc; -webkit-margin-before: 1__qem; -webkit-margin-after: 1em; -webkit-margin-start: 0; -webkit-margin-end: 0; -webkit-padding-start: 40px } ol { display: block; list-style-type: decimal; -webkit-margin-before: 1__qem; -webkit-margin-after: 1em; -webkit-margin-start: 0; -webkit-margin-end: 0; -webkit-padding-start: 40px } li { display: list-item; text-align: -webkit-match-parent; } ul ul, ol ul { list-style-type: circle } ol ol ul, ol ul ul, ul ol ul, ul ul ul { list-style-type: square } dd { display: block; -webkit-margin-start: 40px } dl { display: block; -webkit-margin-before: 1__qem; -webkit-margin-after: 1em; -webkit-margin-start: 0; -webkit-margin-end: 0; } dt { display: block } ol ul, ul ol, ul ul, ol ol { -webkit-margin-before: 0; -webkit-margin-after: 0 } /* form elements */ form { display: block; margin-top: 0__qem; } label { cursor: default; } legend { display: block; -webkit-padding-start: 2px; -webkit-padding-end: 2px; border: none } fieldset { display: block; -webkit-margin-start: 2px; -webkit-margin-end: 2px; -webkit-padding-before: 0.35em; -webkit-padding-start: 0.75em; -webkit-padding-end: 0.75em; -webkit-padding-after: 0.625em; border: 2px groove ThreeDFace; min-width: -webkit-min-content; } button { -webkit-appearance: button; } /* Form controls don't go vertical. */ input, textarea, select, button, meter, progress { -webkit-writing-mode: horizontal-tb !important; } input, textarea, select, button { margin: 0__qem; font: -webkit-small-control; text-rendering: auto; /* FIXME: Remove when tabs work with optimizeLegibility. */ color: initial; letter-spacing: normal; word-spacing: normal; line-height: normal; text-transform: none; text-indent: 0; text-shadow: none; display: inline-block; text-align: start; } /* TODO: Add " i" to attribute matchers to support case-insensitive matching */ input[type="hidden"] { display: none } input { -webkit-appearance: textfield; padding: 1px; background-color: white; border: 2px inset; -webkit-rtl-ordering: logical; -webkit-user-select: text; cursor: auto; } input[type="search"] { -webkit-appearance: searchfield; box-sizing: border-box; } select { border-radius: 5px; } textarea { -webkit-appearance: textarea; background-color: white; border: 1px solid; -webkit-rtl-ordering: logical; -webkit-user-select: text; flex-direction: column; resize: auto; cursor: auto; padding: 2px; white-space: pre-wrap; word-wrap: break-word; } input[type="password"] { -webkit-text-security: disc !important; } input[type="hidden"], input[type="image"], input[type="file"] { -webkit-appearance: initial; padding: initial; background-color: initial; border: initial; } input[type="file"] { align-items: baseline; color: inherit; text-align: start !important; } input[type="radio"], input[type="checkbox"] { margin: 3px 0.5ex; padding: initial; background-color: initial; border: initial; } input[type="button"], input[type="submit"], input[type="reset"] { -webkit-appearance: push-button; -webkit-user-select: none; white-space: pre } input[type="button"], input[type="submit"], input[type="reset"], button { align-items: flex-start; text-align: center; cursor: default; color: ButtonText; padding: 2px 6px 3px 6px; border: 2px outset ButtonFace; background-color: ButtonFace; box-sizing: border-box } input[type="range"] { -webkit-appearance: slider-horizontal; padding: initial; border: initial; margin: 2px; color: #909090; } input[type="button"]:disabled, input[type="submit"]:disabled, input[type="reset"]:disabled, button:disabled, select:disabled, optgroup:disabled, option:disabled, select[disabled]>option { color: GrayText } input[type="button"]:active, input[type="submit"]:active, input[type="reset"]:active, button:active { border-style: inset } input[type="button"]:active:disabled, input[type="submit"]:active:disabled, input[type="reset"]:active:disabled, button:active:disabled { border-style: outset } datalist { display: none } area { display: inline; cursor: pointer; } param { display: none } input[type="checkbox"] { -webkit-appearance: checkbox; box-sizing: border-box; } input[type="radio"] { -webkit-appearance: radio; box-sizing: border-box; } input[type="color"] { -webkit-appearance: square-button; width: 44px; height: 23px; background-color: ButtonFace; /* Same as native_theme_base. */ border: 1px #a9a9a9 solid; padding: 1px 2px; } input[type="color"][list] { -webkit-appearance: menulist; width: 88px; height: 23px } select { -webkit-appearance: menulist; box-sizing: border-box; align-items: center; border: 1px solid; white-space: pre; -webkit-rtl-ordering: logical; color: black; background-color: white; cursor: default; } optgroup { font-weight: bolder; display: block; } option { font-weight: normal; display: block; padding: 0 2px 1px 2px; white-space: pre; min-height: 1.2em; } output { display: inline; } /* meter */ meter { -webkit-appearance: meter; box-sizing: border-box; display: inline-block; height: 1em; width: 5em; vertical-align: -0.2em; } /* progress */ progress { -webkit-appearance: progress-bar; box-sizing: border-box; display: inline-block; height: 1em; width: 10em; vertical-align: -0.2em; } /* inline elements */ u, ins { text-decoration: underline } strong, b { font-weight: bold } i, cite, em, var, address, dfn { font-style: italic } tt, code, kbd, samp { font-family: monospace } pre, xmp, plaintext, listing { display: block; font-family: monospace; white-space: pre; margin: 1__qem 0 } mark { background-color: yellow; color: black } big { font-size: larger } small { font-size: smaller } s, strike, del { text-decoration: line-through } sub { vertical-align: sub; font-size: smaller } sup { vertical-align: super; font-size: smaller } nobr { white-space: nowrap } /* states */ :focus { outline: auto 5px -webkit-focus-ring-color } /* Read-only text fields do not show a focus ring but do still receive focus */ html:focus, body:focus, input[readonly]:focus { outline: none } embed:focus, iframe:focus, object:focus { outline: none } input:focus, textarea:focus, select:focus { outline-offset: -2px } input[type="button"]:focus, input[type="checkbox"]:focus, input[type="file"]:focus, input[type="hidden"]:focus, input[type="image"]:focus, input[type="radio"]:focus, input[type="reset"]:focus, input[type="search"]:focus, input[type="submit"]:focus { outline-offset: 0 } /* HTML5 ruby elements */ ruby, rt { text-indent: 0; /* blocks used for ruby rendering should not trigger this */ } rt { line-height: normal; -webkit-text-emphasis: none; } ruby > rt { display: block; font-size: 50%; text-align: start; } ruby > rp { display: none; } /* other elements */ noframes { display: none } frameset, frame { display: block } frameset { border-color: inherit } iframe { border: 2px inset } details { display: block } summary { display: block } template { display: none } bdi, output { unicode-bidi: -webkit-isolate; } bdo { unicode-bidi: bidi-override; } textarea[dir=auto] { unicode-bidi: -webkit-plaintext; } dialog:not([open]) { display: none } dialog { position: absolute; left: 0; right: 0; width: -webkit-fit-content; height: -webkit-fit-content; margin: auto; border: solid; padding: 1em; background: white; color: black } /* noscript is handled internally, as it depends on settings. */ `;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/browser/default-stylesheet.js
default-stylesheet.js
"use strict"; const fs = require("fs"); const { parseURL } = require("whatwg-url"); const dataURLFromRecord = require("data-urls").fromURLRecord; const request = require("request-promise-native"); const wrapCookieJarForRequest = require("jsdom/lib/jsdom/living/helpers/wrap-cookie-jar-for-request"); const packageVersion = require("jsdom/package.json").version; const IS_BROWSER = Object.prototype.toString.call(process) !== "[object process]"; module.exports = class ResourceLoader { constructor({ strictSSL = true, proxy = undefined, userAgent = `Mozilla/5.0 (${process.platform || "unknown OS"}) AppleWebKit/537.36 ` + `(KHTML, like Gecko) jsdom/${packageVersion}` } = {}) { this._strictSSL = strictSSL; this._proxy = proxy; this._userAgent = userAgent; } _readDataURL(urlRecord) { const dataURL = dataURLFromRecord(urlRecord); let timeoutId; const promise = new Promise(resolve => { timeoutId = setTimeout(resolve, 0, dataURL.body); }); promise.abort = () => { if (timeoutId !== undefined) { clearTimeout(timeoutId); } }; return promise; } _readFile(filePath) { let readableStream; let abort; // Native Promises doesn't have an "abort" method. /* * Creating a promise for two reason: * 1. fetch always return a promise. * 2. We need to add an abort handler. */ const promise = new Promise((resolve, reject) => { readableStream = fs.createReadStream(filePath); let data = Buffer.alloc(0); abort = reject; readableStream.on("error", reject); readableStream.on("data", chunk => { data = Buffer.concat([data, chunk]); }); readableStream.on("end", () => { resolve(data); }); }); promise.abort = () => { readableStream.destroy(); const error = new Error("request canceled by user"); error.isAbortError = true; abort(error); }; return promise; } _getRequestOptions({ cookieJar, referrer, accept = "*/*" }) { const requestOptions = { encoding: null, gzip: true, jar: wrapCookieJarForRequest(cookieJar), strictSSL: this._strictSSL, proxy: this._proxy, forever: true, headers: { "User-Agent": this._userAgent, "Accept-Language": "en", Accept: accept } }; if (referrer && !IS_BROWSER) { requestOptions.headers.referer = referrer; } return requestOptions; } fetch(urlString, options = {}) { const url = parseURL(urlString); if (!url) { return Promise.reject(new Error(`Tried to fetch invalid URL ${urlString}`)); } switch (url.scheme) { case "data": { return this._readDataURL(url); } case "http": case "https": { const requestOptions = this._getRequestOptions(options); return request(urlString, requestOptions); } case "file": { // TODO: Improve the URL => file algorithm. See https://github.com/jsdom/jsdom/pull/2279#discussion_r199977987 const filePath = urlString .replace(/^file:\/\//, "") .replace(/^\/([a-z]):\//i, "$1:/") .replace(/%20/g, " "); return this._readFile(filePath); } default: { return Promise.reject(new Error(`Tried to fetch URL ${urlString} with invalid scheme ${url.scheme}`)); } } } };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/browser/resources/resource-loader.js
resource-loader.js
"use strict"; /** * Queue for all the resources to be download except async scripts. * Async scripts have their own queue AsyncResourceQueue. */ module.exports = class ResourceQueue { constructor({ paused, asyncQueue } = {}) { this.paused = Boolean(paused); this._asyncQueue = asyncQueue; } getLastScript() { let head = this.tail; while (head) { if (head.isScript) { return head; } head = head.prev; } return null; } _moreScripts() { let found = false; let head = this.tail; while (head && !found) { found = head.isScript; head = head.prev; } return found; } _notify() { if (this._listener) { this._listener(); } } setListener(listener) { this._listener = listener; } push(request, onLoad, onError, keepLast, element) { const isScript = element ? element.localName === "script" : false; if (!request) { if (isScript && !this._moreScripts()) { return onLoad(); } request = new Promise(resolve => resolve()); } const q = this; const item = { isScript, err: null, element, fired: false, data: null, keepLast, prev: q.tail, check() { if (!q.paused && !this.prev && this.fired) { let promise; if (this.err && onError) { promise = onError(this.err); } if (!this.err && onLoad) { promise = onLoad(this.data); } Promise.resolve(promise) .then(() => { if (this.next) { this.next.prev = null; this.next.check(); } else { // q.tail===this q.tail = null; q._notify(); } this.finished = true; if (q._asyncQueue) { q._asyncQueue.notifyItem(this); } }); } } }; if (q.tail) { if (q.tail.keepLast) { // if the tail is the load event in document and we receive a new element to load // we should add this new request before the load event. if (q.tail.prev) { q.tail.prev.next = item; } item.prev = q.tail.prev; q.tail.prev = item; item.next = q.tail; } else { q.tail.next = item; q.tail = item; } } else { q.tail = item; } return request .then(data => { item.fired = 1; item.data = data; item.check(); }) .catch(err => { item.fired = true; item.err = err; item.check(); }); } resume() { if (!this.paused) { return; } this.paused = false; let head = this.tail; while (head && head.prev) { head = head.prev; } if (head) { head.check(); } } };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/browser/resources/resource-queue.js
resource-queue.js
"use strict"; class QueueItem { constructor(onLoad, onError, dependentItem) { this.onLoad = onLoad; this.onError = onError; this.data = null; this.error = null; this.dependentItem = dependentItem; } } /** * AsyncResourceQueue is the queue in charge of run the async scripts * and notify when they finish. */ module.exports = class AsyncResourceQueue { constructor() { this.items = new Set(); this.dependentItems = new Set(); } count() { return this.items.size + this.dependentItems.size; } _notify() { if (this._listener) { this._listener(); } } _check(item) { let promise; if (item.onError && item.error) { promise = item.onError(item.error); } else if (item.onLoad && item.data) { promise = item.onLoad(item.data); } promise .then(() => { this.items.delete(item); this.dependentItems.delete(item); if (this.count() === 0) { this._notify(); } }); } setListener(listener) { this._listener = listener; } push(request, onLoad, onError, dependentItem) { const q = this; const item = new QueueItem(onLoad, onError, dependentItem); q.items.add(item); return request .then(data => { item.data = data; if (dependentItem && !dependentItem.finished) { q.dependentItems.add(item); return q.items.delete(item); } if (onLoad) { return q._check(item); } q.items.delete(item); if (q.count() === 0) { q._notify(); } return null; }) .catch(err => { item.error = err; if (dependentItem && !dependentItem.finished) { q.dependentItems.add(item); return q.items.delete(item); } if (onError) { return q._check(item); } q.items.delete(item); if (q.count() === 0) { q._notify(); } return null; }); } notifyItem(syncItem) { for (const item of this.dependentItems) { if (item.dependentItem === syncItem) { this._check(item); } } } };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/browser/resources/async-resource-queue.js
async-resource-queue.js
module.exports = core => { var xpath = {}; // Helper function to deal with the migration of Attr to no longer have a nodeName property despite this codebase // assuming it does. function getNodeName(nodeOrAttr) { return nodeOrAttr.constructor.name === 'Attr' ? nodeOrAttr.name : nodeOrAttr.nodeName; } /*************************************************************************** * Tokenization * ***************************************************************************/ /** * The XPath lexer is basically a single regular expression, along with * some helper functions to pop different types. */ var Stream = xpath.Stream = function Stream(str) { this.original = this.str = str; this.peeked = null; // TODO: not really needed, but supposedly tokenizer also disambiguates // a * b vs. node test * this.prev = null; // for debugging this.prevprev = null; } Stream.prototype = { peek: function() { if (this.peeked) return this.peeked; var m = this.re.exec(this.str); if (!m) return null; this.str = this.str.substr(m[0].length); return this.peeked = m[1]; }, /** Peek 2 tokens ahead. */ peek2: function() { this.peek(); // make sure this.peeked is set var m = this.re.exec(this.str); if (!m) return null; return m[1]; }, pop: function() { var r = this.peek(); this.peeked = null; this.prevprev = this.prev; this.prev = r; return r; }, trypop: function(tokens) { var tok = this.peek(); if (tok === tokens) return this.pop(); if (Array.isArray(tokens)) { for (var i = 0; i < tokens.length; ++i) { var t = tokens[i]; if (t == tok) return this.pop();; } } }, trypopfuncname: function() { var tok = this.peek(); if (!this.isQnameRe.test(tok)) return null; switch (tok) { case 'comment': case 'text': case 'processing-instruction': case 'node': return null; } if ('(' != this.peek2()) return null; return this.pop(); }, trypopaxisname: function() { var tok = this.peek(); switch (tok) { case 'ancestor': case 'ancestor-or-self': case 'attribute': case 'child': case 'descendant': case 'descendant-or-self': case 'following': case 'following-sibling': case 'namespace': case 'parent': case 'preceding': case 'preceding-sibling': case 'self': if ('::' == this.peek2()) return this.pop(); } return null; }, trypopnametest: function() { var tok = this.peek(); if ('*' === tok || this.startsWithNcNameRe.test(tok)) return this.pop(); return null; }, trypopliteral: function() { var tok = this.peek(); if (null == tok) return null; var first = tok.charAt(0); var last = tok.charAt(tok.length - 1); if ('"' === first && '"' === last || "'" === first && "'" === last) { this.pop(); return tok.substr(1, tok.length - 2); } }, trypopnumber: function() { var tok = this.peek(); if (this.isNumberRe.test(tok)) return parseFloat(this.pop()); else return null; }, trypopvarref: function() { var tok = this.peek(); if (null == tok) return null; if ('$' === tok.charAt(0)) return this.pop().substr(1); else return null; }, position: function() { return this.original.length - this.str.length; } }; (function() { // http://www.w3.org/TR/REC-xml-names/#NT-NCName var nameStartCharsExceptColon = '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'; // JS doesn't support [#x10000-#xEFFFF] var nameCharExceptColon = nameStartCharsExceptColon + '\\-\\.0-9\xb7\u0300-\u036F\u203F-\u2040'; var ncNameChars = '[' + nameStartCharsExceptColon + '][' + nameCharExceptColon + ']*' // http://www.w3.org/TR/REC-xml-names/#NT-QName var qNameChars = ncNameChars + '(?::' + ncNameChars + ')?'; var otherChars = '\\.\\.|[\\(\\)\\[\\].@,]|::'; // .. must come before [.] var operatorChars = 'and|or|mod|div|' + '//|!=|<=|>=|[*/|+\\-=<>]'; // //, !=, <=, >= before individual ones. var literal = '"[^"]*"|' + "'[^']*'"; var numberChars = '[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+'; var variableReference = '\\$' + qNameChars; var nameTestChars = '\\*|' + ncNameChars + ':\\*|' + qNameChars; var optionalSpace = '[ \t\r\n]*'; // stricter than regexp \s. var nodeType = 'comment|text|processing-instruction|node'; var re = new RegExp( // numberChars before otherChars so that leading-decimal doesn't become . '^' + optionalSpace + '(' + numberChars + '|' + otherChars + '|' + nameTestChars + '|' + operatorChars + '|' + literal + '|' + variableReference + ')' // operatorName | nodeType | functionName | axisName are lumped into // qName for now; we'll check them on pop. ); Stream.prototype.re = re; Stream.prototype.startsWithNcNameRe = new RegExp('^' + ncNameChars); Stream.prototype.isQnameRe = new RegExp('^' + qNameChars + '$'); Stream.prototype.isNumberRe = new RegExp('^' + numberChars + '$'); })(); /*************************************************************************** * Parsing * ***************************************************************************/ var parse = xpath.parse = function parse(stream, a) { var r = orExpr(stream,a); var x, unparsed = []; while (x = stream.pop()) { unparsed.push(x); } if (unparsed.length) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Unparsed tokens: ' + unparsed.join(' ')); return r; } /** * binaryL ::= subExpr * | binaryL op subExpr * so a op b op c becomes ((a op b) op c) */ function binaryL(subExpr, stream, a, ops) { var lhs = subExpr(stream, a); if (lhs == null) return null; var op; while (op = stream.trypop(ops)) { var rhs = subExpr(stream, a); if (rhs == null) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected something after ' + op); lhs = a.node(op, lhs, rhs); } return lhs; } /** * Too bad this is never used. If they made a ** operator (raise to power), ( we would use it. * binaryR ::= subExpr * | subExpr op binaryR * so a op b op c becomes (a op (b op c)) */ function binaryR(subExpr, stream, a, ops) { var lhs = subExpr(stream, a); if (lhs == null) return null; var op = stream.trypop(ops); if (op) { var rhs = binaryR(stream, a); if (rhs == null) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected something after ' + op); return a.node(op, lhs, rhs); } else { return lhs;// TODO } } /** [1] LocationPath::= RelativeLocationPath | AbsoluteLocationPath * e.g. a, a/b, //a/b */ function locationPath(stream, a) { return absoluteLocationPath(stream, a) || relativeLocationPath(null, stream, a); } /** [2] AbsoluteLocationPath::= '/' RelativeLocationPath? | AbbreviatedAbsoluteLocationPath * [10] AbbreviatedAbsoluteLocationPath::= '//' RelativeLocationPath */ function absoluteLocationPath(stream, a) { var op = stream.peek(); if ('/' === op || '//' === op) { var lhs = a.node('Root'); return relativeLocationPath(lhs, stream, a, true); } else { return null; } } /** [3] RelativeLocationPath::= Step | RelativeLocationPath '/' Step | * | AbbreviatedRelativeLocationPath * [11] AbbreviatedRelativeLocationPath::= RelativeLocationPath '//' Step * e.g. p/a, etc. */ function relativeLocationPath(lhs, stream, a, isOnlyRootOk) { if (null == lhs) { lhs = step(stream, a); if (null == lhs) return lhs; } var op; while (op = stream.trypop(['/', '//'])) { if ('//' === op) { lhs = a.node('/', lhs, a.node('Axis', 'descendant-or-self', 'node', undefined)); } var rhs = step(stream, a); if (null == rhs && '/' === op && isOnlyRootOk) return lhs; else isOnlyRootOk = false; if (null == rhs) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected step after ' + op); lhs = a.node('/', lhs, rhs); } return lhs; } /** [4] Step::= AxisSpecifier NodeTest Predicate* | AbbreviatedStep * [12] AbbreviatedStep::= '.' | '..' * e.g. @href, self::p, p, a[@href], ., .. */ function step(stream, a) { var abbrStep = stream.trypop(['.', '..']); if ('.' === abbrStep) // A location step of . is short for self::node(). return a.node('Axis', 'self', 'node'); if ('..' === abbrStep) // A location step of .. is short for parent::node() return a.node('Axis', 'parent', 'node'); var axis = axisSpecifier(stream, a); var nodeType = nodeTypeTest(stream, a); var nodeName; if (null == nodeType) nodeName = nodeNameTest(stream, a); if (null == axis && null == nodeType && null == nodeName) return null; if (null == nodeType && null == nodeName) throw new XPathException( XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected nodeTest after axisSpecifier ' + axis); if (null == axis) axis = 'child'; if (null == nodeType) { // When there's only a node name, then the node type is forced to be the // principal node type of the axis. // see http://www.w3.org/TR/xpath/#dt-principal-node-type if ('attribute' === axis) nodeType = 'attribute'; else if ('namespace' === axis) nodeType = 'namespace'; else nodeType = 'element'; } var lhs = a.node('Axis', axis, nodeType, nodeName); var pred; while (null != (pred = predicate(lhs, stream, a))) { lhs = pred; } return lhs; } /** [5] AxisSpecifier::= AxisName '::' | AbbreviatedAxisSpecifier * [6] AxisName::= 'ancestor' | 'ancestor-or-self' | 'attribute' | 'child' * | 'descendant' | 'descendant-or-self' | 'following' * | 'following-sibling' | 'namespace' | 'parent' | * | 'preceding' | 'preceding-sibling' | 'self' * [13] AbbreviatedAxisSpecifier::= '@'? */ function axisSpecifier(stream, a) { var attr = stream.trypop('@'); if (null != attr) return 'attribute'; var axisName = stream.trypopaxisname(); if (null != axisName) { var coloncolon = stream.trypop('::'); if (null == coloncolon) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Should not happen. Should be ::.'); return axisName; } } /** [7] NodeTest::= NameTest | NodeType '(' ')' | 'processing-instruction' '(' Literal ')' * [38] NodeType::= 'comment' | 'text' | 'processing-instruction' | 'node' * I've split nodeTypeTest from nodeNameTest for convenience. */ function nodeTypeTest(stream, a) { if ('(' !== stream.peek2()) { return null; } var type = stream.trypop(['comment', 'text', 'processing-instruction', 'node']); if (null != type) { if (null == stream.trypop('(')) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Should not happen.'); var param = undefined; if (type == 'processing-instruction') { param = stream.trypopliteral(); } if (null == stream.trypop(')')) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected close parens.'); return type } } function nodeNameTest(stream, a) { var name = stream.trypopnametest(); if (name != null) return name; else return null; } /** [8] Predicate::= '[' PredicateExpr ']' * [9] PredicateExpr::= Expr */ function predicate(lhs, stream, a) { if (null == stream.trypop('[')) return null; var expr = orExpr(stream, a); if (null == expr) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected expression after ['); if (null == stream.trypop(']')) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected ] after expression.'); return a.node('Predicate', lhs, expr); } /** [14] Expr::= OrExpr */ /** [15] PrimaryExpr::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall * e.g. $x, (3+4), "hi", 32, f(x) */ function primaryExpr(stream, a) { var x = stream.trypopliteral(); if (null == x) x = stream.trypopnumber(); if (null != x) { return x; } var varRef = stream.trypopvarref(); if (null != varRef) return a.node('VariableReference', varRef); var funCall = functionCall(stream, a); if (null != funCall) { return funCall; } if (stream.trypop('(')) { var e = orExpr(stream, a); if (null == e) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected expression after (.'); if (null == stream.trypop(')')) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected ) after expression.'); return e; } return null; } /** [16] FunctionCall::= FunctionName '(' ( Argument ( ',' Argument )* )? ')' * [17] Argument::= Expr */ function functionCall(stream, a) { var name = stream.trypopfuncname(stream, a); if (null == name) return null; if (null == stream.trypop('(')) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected ( ) after function name.'); var params = []; var first = true; while (null == stream.trypop(')')) { if (!first && null == stream.trypop(',')) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected , between arguments of the function.'); first = false; var param = orExpr(stream, a); if (param == null) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected expression as argument of function.'); params.push(param); } return a.node('FunctionCall', name, params); } /** [18] UnionExpr::= PathExpr | UnionExpr '|' PathExpr */ function unionExpr(stream, a) { return binaryL(pathExpr, stream, a, '|'); } /** [19] PathExpr ::= LocationPath * | FilterExpr * | FilterExpr '/' RelativeLocationPath * | FilterExpr '//' RelativeLocationPath * Unlike most other nodes, this one always generates a node because * at this point all reverse nodesets must turn into a forward nodeset */ function pathExpr(stream, a) { // We have to do FilterExpr before LocationPath because otherwise // LocationPath will eat up the name from a function call. var filter = filterExpr(stream, a); if (null == filter) { var loc = locationPath(stream, a); if (null == loc) { throw new Error throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': The expression shouldn\'t be empty...'); } return a.node('PathExpr', loc); } var rel = relativeLocationPath(filter, stream, a, false); if (filter === rel) return rel; else return a.node('PathExpr', rel); } /** [20] FilterExpr::= PrimaryExpr | FilterExpr Predicate * aka. FilterExpr ::= PrimaryExpr Predicate* */ function filterExpr(stream, a) { var primary = primaryExpr(stream, a); if (primary == null) return null; var pred, lhs = primary; while (null != (pred = predicate(lhs, stream, a))) { lhs = pred; } return lhs; } /** [21] OrExpr::= AndExpr | OrExpr 'or' AndExpr */ function orExpr(stream, a) { var orig = (stream.peeked || '') + stream.str var r = binaryL(andExpr, stream, a, 'or'); var now = (stream.peeked || '') + stream.str; return r; } /** [22] AndExpr::= EqualityExpr | AndExpr 'and' EqualityExpr */ function andExpr(stream, a) { return binaryL(equalityExpr, stream, a, 'and'); } /** [23] EqualityExpr::= RelationalExpr | EqualityExpr '=' RelationalExpr * | EqualityExpr '!=' RelationalExpr */ function equalityExpr(stream, a) { return binaryL(relationalExpr, stream, a, ['=','!=']); } /** [24] RelationalExpr::= AdditiveExpr | RelationalExpr '<' AdditiveExpr * | RelationalExpr '>' AdditiveExpr * | RelationalExpr '<=' AdditiveExpr * | RelationalExpr '>=' AdditiveExpr */ function relationalExpr(stream, a) { return binaryL(additiveExpr, stream, a, ['<','>','<=','>=']); } /** [25] AdditiveExpr::= MultiplicativeExpr * | AdditiveExpr '+' MultiplicativeExpr * | AdditiveExpr '-' MultiplicativeExpr */ function additiveExpr(stream, a) { return binaryL(multiplicativeExpr, stream, a, ['+','-']); } /** [26] MultiplicativeExpr::= UnaryExpr * | MultiplicativeExpr MultiplyOperator UnaryExpr * | MultiplicativeExpr 'div' UnaryExpr * | MultiplicativeExpr 'mod' UnaryExpr */ function multiplicativeExpr(stream, a) { return binaryL(unaryExpr, stream, a, ['*','div','mod']); } /** [27] UnaryExpr::= UnionExpr | '-' UnaryExpr */ function unaryExpr(stream, a) { if (stream.trypop('-')) { var e = unaryExpr(stream, a); if (null == e) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected unary expression after -'); return a.node('UnaryMinus', e); } else return unionExpr(stream, a); } var astFactory = { node: function() {return Array.prototype.slice.call(arguments);} }; /*************************************************************************** * Optimizations (TODO) * ***************************************************************************/ /** * Some things I've been considering: * 1) a//b becomes a/descendant::b if there's no predicate that uses * position() or last() * 2) axis[pred]: when pred doesn't use position, evaluate it just once per * node in the node-set rather than once per (node, position, last). * For more optimizations, look up Gecko's optimizer: * http://mxr.mozilla.org/mozilla-central/source/content/xslt/src/xpath/txXPathOptimizer.cpp */ // TODO function optimize(ast) { } /*************************************************************************** * Evaluation: axes * ***************************************************************************/ /** * Data types: For string, number, boolean, we just use Javascript types. * Node-sets have the form * {nodes: [node, ...]} * or {nodes: [node, ...], pos: [[1], [2], ...], lasts: [[1], [2], ...]} * * Most of the time, only the node is used and the position information is * discarded. But if you use a predicate, we need to try every value of * position and last in case the predicate calls position() or last(). */ /** * The NodeMultiSet is a helper class to help generate * {nodes:[], pos:[], lasts:[]} structures. It is useful for the * descendant, descendant-or-self, following-sibling, and * preceding-sibling axes for which we can use a stack to organize things. */ function NodeMultiSet(isReverseAxis) { this.nodes = []; this.pos = []; this.lasts = []; this.nextPos = []; this.seriesIndexes = []; // index within nodes that each series begins. this.isReverseAxis = isReverseAxis; this._pushToNodes = isReverseAxis ? Array.prototype.unshift : Array.prototype.push; } NodeMultiSet.prototype = { pushSeries: function pushSeries() { this.nextPos.push(1); this.seriesIndexes.push(this.nodes.length); }, popSeries: function popSeries() { console.assert(0 < this.nextPos.length, this.nextPos); var last = this.nextPos.pop() - 1, indexInPos = this.nextPos.length, seriesBeginIndex = this.seriesIndexes.pop(), seriesEndIndex = this.nodes.length; for (var i = seriesBeginIndex; i < seriesEndIndex; ++i) { console.assert(indexInPos < this.lasts[i].length); console.assert(undefined === this.lasts[i][indexInPos]); this.lasts[i][indexInPos] = last; } }, finalize: function() { if (null == this.nextPos) return this; console.assert(0 === this.nextPos.length); var lastsJSON = JSON.stringify(this.lasts); for (var i = 0; i < this.lasts.length; ++i) { for (var j = 0; j < this.lasts[i].length; ++j) { console.assert(null != this.lasts[i][j], i + ',' + j + ':' + lastsJSON); } } this.pushSeries = this.popSeries = this.addNode = function() { throw new Error('Already finalized.'); }; return this; }, addNode: function addNode(node) { console.assert(node); this._pushToNodes.call(this.nodes, node) this._pushToNodes.call(this.pos, this.nextPos.slice()); this._pushToNodes.call(this.lasts, new Array(this.nextPos.length)); for (var i = 0; i < this.nextPos.length; ++i) this.nextPos[i]++; }, simplify: function() { this.finalize(); return {nodes:this.nodes, pos:this.pos, lasts:this.lasts}; } }; function eachContext(nodeMultiSet) { var r = []; for (var i = 0; i < nodeMultiSet.nodes.length; i++) { var node = nodeMultiSet.nodes[i]; if (!nodeMultiSet.pos) { r.push({nodes:[node], pos: [[i + 1]], lasts: [[nodeMultiSet.nodes.length]]}); } else { for (var j = 0; j < nodeMultiSet.pos[i].length; ++j) { r.push({nodes:[node], pos: [[nodeMultiSet.pos[i][j]]], lasts: [[nodeMultiSet.lasts[i][j]]]}); } } } return r; } /** Matcher used in the axes. */ function NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase) { this.nodeTypeNum = nodeTypeNum; this.nodeName = nodeName; this.shouldLowerCase = shouldLowerCase; this.nodeNameTest = null == nodeName ? this._alwaysTrue : shouldLowerCase ? this._nodeNameLowerCaseEquals : this._nodeNameEquals; } NodeMatcher.prototype = { matches: function matches(node) { if (0 === this.nodeTypeNum || this._nodeTypeMatches(node)) { return this.nodeNameTest(getNodeName(node)); } return false; }, _nodeTypeMatches(nodeOrAttr) { if (nodeOrAttr.constructor.name === 'Attr' && this.nodeTypeNum === 2) { return true; } return nodeOrAttr.nodeType === this.nodeTypeNum; }, _alwaysTrue: function(name) {return true;}, _nodeNameEquals: function _nodeNameEquals(name) { return this.nodeName === name; }, _nodeNameLowerCaseEquals: function _nodeNameLowerCaseEquals(name) { return this.nodeName === name.toLowerCase(); } }; function followingSiblingHelper(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, shift, peek, followingNode, andSelf, isReverseAxis) { var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase); var nodeMultiSet = new NodeMultiSet(isReverseAxis); while (0 < nodeList.length) { // can be if for following, preceding var node = shift.call(nodeList); console.assert(node != null); node = followingNode(node); nodeMultiSet.pushSeries(); var numPushed = 1; while (null != node) { if (! andSelf && matcher.matches(node)) nodeMultiSet.addNode(node); if (node === peek.call(nodeList)) { shift.call(nodeList); nodeMultiSet.pushSeries(); numPushed++; } if (andSelf && matcher.matches(node)) nodeMultiSet.addNode(node); node = followingNode(node); } while (0 < numPushed--) nodeMultiSet.popSeries(); } return nodeMultiSet; } /** Returns the next non-descendant node in document order. * This is the first node in following::node(), if node is the context. */ function followingNonDescendantNode(node) { if (node.ownerElement) { if (node.ownerElement.firstChild) return node.ownerElement.firstChild; node = node.ownerElement; } do { if (node.nextSibling) return node.nextSibling; } while (node = node.parentNode); return null; } /** Returns the next node in a document-order depth-first search. * See the definition of document order[1]: * 1) element * 2) namespace nodes * 3) attributes * 4) children * [1]: http://www.w3.org/TR/xpath/#dt-document-order */ function followingNode(node) { if (node.ownerElement) // attributes: following node of element. node = node.ownerElement; if (null != node.firstChild) return node.firstChild; do { if (null != node.nextSibling) { return node.nextSibling; } node = node.parentNode; } while (node); return null; } /** Returns the previous node in document order (excluding attributes * and namespace nodes). */ function precedingNode(node) { if (node.ownerElement) return node.ownerElement; if (null != node.previousSibling) { node = node.previousSibling; while (null != node.lastChild) { node = node.lastChild; } return node; } if (null != node.parentNode) { return node.parentNode; } return null; } /** This axis is inefficient if there are many nodes in the nodeList. * But I think it's a pretty useless axis so it's ok. */ function followingHelper(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) { var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase); var nodeMultiSet = new NodeMultiSet(false); var cursor = nodeList[0]; var unorderedFollowingStarts = []; for (var i = 0; i < nodeList.length; i++) { var node = nodeList[i]; var start = followingNonDescendantNode(node); if (start) unorderedFollowingStarts.push(start); } if (0 === unorderedFollowingStarts.length) return {nodes:[]}; var pos = [], nextPos = []; var started = 0; while (cursor = followingNode(cursor)) { for (var i = unorderedFollowingStarts.length - 1; i >= 0; i--){ if (cursor === unorderedFollowingStarts[i]) { nodeMultiSet.pushSeries(); unorderedFollowingStarts.splice(i,i+1); started++; } } if (started && matcher.matches(cursor)) { nodeMultiSet.addNode(cursor); } } console.assert(0 === unorderedFollowingStarts.length); for (var i = 0; i < started; i++) nodeMultiSet.popSeries(); return nodeMultiSet.finalize(); } function precedingHelper(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) { var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase); var cursor = nodeList.pop(); if (null == cursor) return {nodes:{}}; var r = {nodes:[], pos:[], lasts:[]}; var nextParents = [cursor.parentNode || cursor.ownerElement], nextPos = [1]; while (cursor = precedingNode(cursor)) { if (cursor === nodeList[nodeList.length - 1]) { nextParents.push(nodeList.pop()); nextPos.push(1); } var matches = matcher.matches(cursor); var pos, someoneUsed = false; if (matches) pos = nextPos.slice(); for (var i = 0; i < nextParents.length; ++i) { if (cursor === nextParents[i]) { nextParents[i] = cursor.parentNode || cursor.ownerElement; if (matches) { pos[i] = null; } } else { if (matches) { pos[i] = nextPos[i]++; someoneUsed = true; } } } if (someoneUsed) { r.nodes.unshift(cursor); r.pos.unshift(pos); } } for (var i = 0; i < r.pos.length; ++i) { var lasts = []; r.lasts.push(lasts); for (var j = r.pos[i].length - 1; j >= 0; j--) { if (null == r.pos[i][j]) { r.pos[i].splice(j, j+1); } else { lasts.unshift(nextPos[j] - 1); } } } return r; } /** node-set, axis -> node-set */ function descendantDfs(nodeMultiSet, node, remaining, matcher, andSelf, attrIndices, attrNodes) { while (0 < remaining.length && null != remaining[0].ownerElement) { var attr = remaining.shift(); if (andSelf && matcher.matches(attr)) { attrNodes.push(attr); attrIndices.push(nodeMultiSet.nodes.length); } } if (null != node && !andSelf) { if (matcher.matches(node)) nodeMultiSet.addNode(node); } var pushed = false; if (null == node) { if (0 === remaining.length) return; node = remaining.shift(); nodeMultiSet.pushSeries(); pushed = true; } else if (0 < remaining.length && node === remaining[0]) { nodeMultiSet.pushSeries(); pushed = true; remaining.shift(); } if (andSelf) { if (matcher.matches(node)) nodeMultiSet.addNode(node); } // TODO: use optimization. Also try element.getElementsByTagName // var nodeList = 1 === nodeTypeNum && null != node.children ? node.children : node.childNodes; var nodeList = node.childNodes; for (var j = 0; j < nodeList.length; ++j) { var child = nodeList[j]; descendantDfs(nodeMultiSet, child, remaining, matcher, andSelf, attrIndices, attrNodes); } if (pushed) { nodeMultiSet.popSeries(); } } function descenantHelper(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, andSelf) { var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase); var nodeMultiSet = new NodeMultiSet(false); var attrIndices = [], attrNodes = []; while (0 < nodeList.length) { // var node = nodeList.shift(); descendantDfs(nodeMultiSet, null, nodeList, matcher, andSelf, attrIndices, attrNodes); } nodeMultiSet.finalize(); for (var i = attrNodes.length-1; i >= 0; --i) { nodeMultiSet.nodes.splice(attrIndices[i], attrIndices[i], attrNodes[i]); nodeMultiSet.pos.splice(attrIndices[i], attrIndices[i], [1]); nodeMultiSet.lasts.splice(attrIndices[i], attrIndices[i], [1]); } return nodeMultiSet; } /** */ function ancestorHelper(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, andSelf) { var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase); var ancestors = []; // array of non-empty arrays of matching ancestors for (var i = 0; i < nodeList.length; ++i) { var node = nodeList[i]; var isFirst = true; var a = []; while (null != node) { if (!isFirst || andSelf) { if (matcher.matches(node)) a.push(node); } isFirst = false; node = node.parentNode || node.ownerElement; } if (0 < a.length) ancestors.push(a); } var lasts = []; for (var i = 0; i < ancestors.length; ++i) lasts.push(ancestors[i].length); var nodeMultiSet = new NodeMultiSet(true); var newCtx = {nodes:[], pos:[], lasts:[]}; while (0 < ancestors.length) { var pos = [ancestors[0].length]; var last = [lasts[0]]; var node = ancestors[0].pop(); for (var i = ancestors.length - 1; i > 0; --i) { if (node === ancestors[i][ancestors[i].length - 1]) { pos.push(ancestors[i].length); last.push(lasts[i]); ancestors[i].pop(); if (0 === ancestors[i].length) { ancestors.splice(i, i+1); lasts.splice(i, i+1); } } } if (0 === ancestors[0].length) { ancestors.shift(); lasts.shift(); } newCtx.nodes.push(node); newCtx.pos.push(pos); newCtx.lasts.push(last); } return newCtx; } /** Helper function for sortDocumentOrder. Returns a list of indices, from the * node to the root, of positions within parent. * For convenience, the node is the first element of the array. */ function addressVector(node) { var r = [node]; if (null != node.ownerElement) { node = node.ownerElement; r.push(-1); } while (null != node) { var i = 0; while (null != node.previousSibling) { node = node.previousSibling; i++; } r.push(i); node = node.parentNode } return r; } function addressComparator(a, b) { var minlen = Math.min(a.length - 1, b.length - 1), // not including [0]=node alen = a.length, blen = b.length; if (a[0] === b[0]) return 0; var c; for (var i = 0; i < minlen; ++i) { c = a[alen - i - 1] - b[blen - i - 1]; if (0 !== c) break; } if (null == c || 0 === c) { // All equal until one of the nodes. The longer one is the descendant. c = alen - blen; } if (0 === c) c = getNodeName(a) - getNodeName(b); if (0 === c) c = 1; return c; } var sortUniqDocumentOrder = xpath.sortUniqDocumentOrder = function(nodes) { var a = []; for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; var v = addressVector(node); a.push(v); } a.sort(addressComparator); var b = []; for (var i = 0; i < a.length; i++) { if (0 < i && a[i][0] === a[i - 1][0]) continue; b.push(a[i][0]); } return b; } /** Sort node multiset. Does not do any de-duping. */ function sortNodeMultiSet(nodeMultiSet) { var a = []; for (var i = 0; i < nodeMultiSet.nodes.length; i++) { var v = addressVector(nodeMultiSet.nodes[i]); a.push({v:v, n:nodeMultiSet.nodes[i], p:nodeMultiSet.pos[i], l:nodeMultiSet.lasts[i]}); } a.sort(compare); var r = {nodes:[], pos:[], lasts:[]}; for (var i = 0; i < a.length; ++i) { r.nodes.push(a[i].n); r.pos.push(a[i].p); r.lasts.push(a[i].l); } function compare(x, y) { return addressComparator(x.v, y.v); } return r; } /** Returns an array containing all the ancestors down to a node. * The array starts with document. */ function nodeAndAncestors(node) { var ancestors = [node]; var p = node; while (p = p.parentNode || p.ownerElement) { ancestors.unshift(p); } return ancestors; } function compareSiblings(a, b) { if (a === b) return 0; var c = a; while (c = c.previousSibling) { if (c === b) return 1; // b < a } c = b; while (c = c.previousSibling) { if (c === a) return -1; // a < b } throw new Error('a and b are not siblings: ' + xpath.stringifyObject(a) + ' vs ' + xpath.stringifyObject(b)); } /** The merge in merge-sort.*/ function mergeNodeLists(x, y) { var a, b, aanc, banc, r = []; if ('object' !== typeof x) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Invalid LHS for | operator ' + '(expected node-set): ' + x); if ('object' !== typeof y) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Invalid LHS for | operator ' + '(expected node-set): ' + y); while (true) { if (null == a) { a = x.shift(); if (null != a) aanc = addressVector(a); } if (null == b) { b = y.shift(); if (null != b) banc = addressVector(b); } if (null == a || null == b) break; var c = addressComparator(aanc, banc); if (c < 0) { r.push(a); a = null; aanc = null; } else if (c > 0) { r.push(b); b = null; banc = null; } else if (getNodeName(a) < getNodeName(b)) { // attributes r.push(a); a = null; aanc = null; } else if (getNodeName(a) > getNodeName(b)) { // attributes r.push(b); b = null; banc = null; } else if (a !== b) { // choose b arbitrarily r.push(b); b = null; banc = null; } else { console.assert(a === b, c); // just skip b without pushing it. b = null; banc = null; } } while (a) { r.push(a); a = x.shift(); } while (b) { r.push(b); b = y.shift(); } return r; } function comparisonHelper(test, x, y, isNumericComparison) { var coersion; if (isNumericComparison) coersion = fn.number; else coersion = 'boolean' === typeof x || 'boolean' === typeof y ? fn['boolean'] : 'number' === typeof x || 'number' === typeof y ? fn.number : fn.string; if ('object' === typeof x && 'object' === typeof y) { var aMap = {}; for (var i = 0; i < x.nodes.length; ++i) { var xi = coersion({nodes:[x.nodes[i]]}); for (var j = 0; j < y.nodes.length; ++j) { var yj = coersion({nodes:[y.nodes[j]]}); if (test(xi, yj)) return true; } } return false; } else if ('object' === typeof x && x.nodes && x.nodes.length) { for (var i = 0; i < x.nodes.length; ++i) { var xi = coersion({nodes:[x.nodes[i]]}), yc = coersion(y); if (test(xi, yc)) return true; } return false; } else if ('object' === typeof y && x.nodes && x.nodes.length) { for (var i = 0; i < x.nodes.length; ++i) { var yi = coersion({nodes:[y.nodes[i]]}), xc = coersion(x); if (test(xc, yi)) return true; } return false; } else { var xc = coersion(x), yc = coersion(y); return test(xc, yc); } } var axes = xpath.axes = { 'ancestor': function ancestor(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) { return ancestorHelper( nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, false); }, 'ancestor-or-self': function ancestorOrSelf(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) { return ancestorHelper( nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, true); }, 'attribute': function attribute(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) { // TODO: figure out whether positions should be undefined here. var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase); var nodeMultiSet = new NodeMultiSet(false); if (null != nodeName) { // TODO: with namespace for (var i = 0; i < nodeList.length; ++i) { var node = nodeList[i]; if (null == node.getAttributeNode) continue; // only Element has .getAttributeNode var attr = node.getAttributeNode(nodeName); if (null != attr && matcher.matches(attr)) { nodeMultiSet.pushSeries(); nodeMultiSet.addNode(attr); nodeMultiSet.popSeries(); } } } else { for (var i = 0; i < nodeList.length; ++i) { var node = nodeList[i]; if (null != node.attributes) { nodeMultiSet.pushSeries(); for (var j = 0; j < node.attributes.length; j++) { // all nodes have .attributes var attr = node.attributes[j]; if (matcher.matches(attr)) // TODO: I think this check is unnecessary nodeMultiSet.addNode(attr); } nodeMultiSet.popSeries(); } } } return nodeMultiSet.finalize(); }, 'child': function child(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) { var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase); var nodeMultiSet = new NodeMultiSet(false); for (var i = 0; i < nodeList.length; ++i) { var n = nodeList[i]; if (n.ownerElement) // skip attribute nodes' text child. continue; if (n.childNodes) { nodeMultiSet.pushSeries(); var childList = 1 === nodeTypeNum && null != n.children ? n.children : n.childNodes; for (var j = 0; j < childList.length; ++j) { var child = childList[j]; if (matcher.matches(child)) { nodeMultiSet.addNode(child); } // don't have to do de-duping because children have parent, // which are current context. } nodeMultiSet.popSeries(); } } nodeMultiSet.finalize(); return sortNodeMultiSet(nodeMultiSet); }, 'descendant': function descenant(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) { return descenantHelper( nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, false); }, 'descendant-or-self': function descenantOrSelf(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) { return descenantHelper( nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, true); }, 'following': function following(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) { return followingHelper(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase); }, 'following-sibling': function followingSibling(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) { return followingSiblingHelper( nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, Array.prototype.shift, function() {return this[0];}, function(node) {return node.nextSibling;}); }, 'namespace': function namespace(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) { // TODO }, 'parent': function parent(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) { var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase); var nodes = [], pos = []; for (var i = 0; i < nodeList.length; ++i) { var parent = nodeList[i].parentNode || nodeList[i].ownerElement; if (null == parent) continue; if (!matcher.matches(parent)) continue; if (nodes.length > 0 && parent === nodes[nodes.length-1]) continue; nodes.push(parent); pos.push([1]); } return {nodes:nodes, pos:pos, lasts:pos}; }, 'preceding': function preceding(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) { return precedingHelper( nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase); }, 'preceding-sibling': function precedingSibling(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) { return followingSiblingHelper( nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, Array.prototype.pop, function() {return this[this.length-1];}, function(node) {return node.previousSibling}, false, true); }, 'self': function self(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) { var nodes = [], pos = []; var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase); for (var i = 0; i < nodeList.length; ++i) { if (matcher.matches(nodeList[i])) { nodes.push(nodeList[i]); pos.push([1]); } } return {nodes: nodes, pos: pos, lasts: pos} } }; /*************************************************************************** * Evaluation: functions * ***************************************************************************/ var fn = { 'number': function number(optObject) { if ('number' === typeof optObject) return optObject; if ('string' === typeof optObject) return parseFloat(optObject); // note: parseFloat(' ') -> NaN, unlike +' ' -> 0. if ('boolean' === typeof optObject) return +optObject; return fn.number(fn.string.call(this, optObject)); // for node-sets }, 'string': function string(optObject) { if (null == optObject) return fn.string(this); if ('string' === typeof optObject || 'boolean' === typeof optObject || 'number' === typeof optObject) return '' + optObject; if (0 == optObject.nodes.length) return ''; if (null != optObject.nodes[0].textContent) return optObject.nodes[0].textContent; return optObject.nodes[0].nodeValue; }, 'boolean': function booleanVal(x) { return 'object' === typeof x ? x.nodes.length > 0 : !!x; }, 'last': function last() { console.assert(Array.isArray(this.pos)); console.assert(Array.isArray(this.lasts)); console.assert(1 === this.pos.length); console.assert(1 === this.lasts.length); console.assert(1 === this.lasts[0].length); return this.lasts[0][0]; }, 'position': function position() { console.assert(Array.isArray(this.pos)); console.assert(Array.isArray(this.lasts)); console.assert(1 === this.pos.length); console.assert(1 === this.lasts.length); console.assert(1 === this.pos[0].length); return this.pos[0][0]; }, 'count': function count(nodeSet) { if ('object' !== typeof nodeSet) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Function count(node-set) ' + 'got wrong argument type: ' + nodeSet); return nodeSet.nodes.length; }, 'id': function id(object) { var r = {nodes: []}; var doc = this.nodes[0].ownerDocument || this.nodes[0]; console.assert(doc); var ids; if ('object' === typeof object) { // for node-sets, map id over each node value. ids = []; for (var i = 0; i < object.nodes.length; ++i) { var idNode = object.nodes[i]; var idsString = fn.string({nodes:[idNode]}); var a = idsString.split(/[ \t\r\n]+/g); Array.prototype.push.apply(ids, a); } } else { var idsString = fn.string(object); var a = idsString.split(/[ \t\r\n]+/g); ids = a; } for (var i = 0; i < ids.length; ++i) { var id = ids[i]; if (0 === id.length) continue; var node = doc.getElementById(id); if (null != node) r.nodes.push(node); } r.nodes = sortUniqDocumentOrder(r.nodes); return r; }, 'local-name': function(nodeSet) { if (null == nodeSet) return fn.name(this); if (null == nodeSet.nodes) { throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'argument to name() must be a node-set. got ' + nodeSet); } // TODO: namespaced version return nodeSet.nodes[0].localName; }, 'namespace-uri': function(nodeSet) { // TODO throw new Error('not implemented yet'); }, 'name': function(nodeSet) { if (null == nodeSet) return fn.name(this); if (null == nodeSet.nodes) { throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'argument to name() must be a node-set. got ' + nodeSet); } return nodeSet.nodes[0].name; }, 'concat': function concat(x) { var l = []; for (var i = 0; i < arguments.length; ++i) { l.push(fn.string(arguments[i])); } return l.join(''); }, 'starts-with': function startsWith(a, b) { var as = fn.string(a), bs = fn.string(b); return as.substr(0, bs.length) === bs; }, 'contains': function contains(a, b) { var as = fn.string(a), bs = fn.string(b); var i = as.indexOf(bs); if (-1 === i) return false; return true; }, 'substring-before': function substringBefore(a, b) { var as = fn.string(a), bs = fn.string(b); var i = as.indexOf(bs); if (-1 === i) return ''; return as.substr(0, i); }, 'substring-after': function substringBefore(a, b) { var as = fn.string(a), bs = fn.string(b); var i = as.indexOf(bs); if (-1 === i) return ''; return as.substr(i + bs.length); }, 'substring': function substring(string, start, optEnd) { if (null == string || null == start) { throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Must be at least 2 arguments to string()'); } var sString = fn.string(string), iStart = fn.round(start), iEnd = optEnd == null ? null : fn.round(optEnd); // Note that xpath string positions user 1-based index if (iEnd == null) return sString.substr(iStart - 1); else return sString.substr(iStart - 1, iEnd); }, 'string-length': function stringLength(optString) { return fn.string.call(this, optString).length; }, 'normalize-space': function normalizeSpace(optString) { var s = fn.string.call(this, optString); return s.replace(/[ \t\r\n]+/g, ' ').replace(/^ | $/g, ''); }, 'translate': function translate(string, from, to) { var sString = fn.string.call(this, string), sFrom = fn.string(from), sTo = fn.string(to); var eachCharRe = []; var map = {}; for (var i = 0; i < sFrom.length; ++i) { var c = sFrom.charAt(i); map[c] = sTo.charAt(i); // returns '' if beyond length of sTo. // copied from goog.string.regExpEscape in the Closure library. eachCharRe.push( c.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1'). replace(/\x08/g, '\\x08')); } var re = new RegExp(eachCharRe.join('|'), 'g'); return sString.replace(re, function(c) {return map[c];}); }, /// Boolean functions 'not': function not(x) { var bx = fn['boolean'](x); return !bx; }, 'true': function trueVal() { return true; }, 'false': function falseVal() { return false; }, // TODO 'lang': function lang(string) { throw new Error('Not implemented');}, 'sum': function sum(optNodeSet) { if (null == optNodeSet) return fn.sum(this); // for node-sets, map id over each node value. var sum = 0; for (var i = 0; i < optNodeSet.nodes.length; ++i) { var node = optNodeSet.nodes[i]; var x = fn.number({nodes:[node]}); sum += x; } return sum; }, 'floor': function floor(number) { return Math.floor(fn.number(number)); }, 'ceiling': function ceiling(number) { return Math.ceil(fn.number(number)); }, 'round': function round(number) { return Math.round(fn.number(number)); } }; /*************************************************************************** * Evaluation: operators * ***************************************************************************/ var more = { UnaryMinus: function(x) { return -fn.number(x); }, '+': function(x, y) { return fn.number(x) + fn.number(y); }, '-': function(x, y) { return fn.number(x) - fn.number(y); }, '*': function(x, y) { return fn.number(x) * fn.number(y); }, 'div': function(x, y) { return fn.number(x) / fn.number(y); }, 'mod': function(x, y) { return fn.number(x) % fn.number(y); }, '<': function(x, y) { return comparisonHelper(function(x, y) { return fn.number(x) < fn.number(y);}, x, y, true); }, '<=': function(x, y) { return comparisonHelper(function(x, y) { return fn.number(x) <= fn.number(y);}, x, y, true); }, '>': function(x, y) { return comparisonHelper(function(x, y) { return fn.number(x) > fn.number(y);}, x, y, true); }, '>=': function(x, y) { return comparisonHelper(function(x, y) { return fn.number(x) >= fn.number(y);}, x, y, true); }, 'and': function(x, y) { return fn['boolean'](x) && fn['boolean'](y); }, 'or': function(x, y) { return fn['boolean'](x) || fn['boolean'](y); }, '|': function(x, y) { return {nodes: mergeNodeLists(x.nodes, y.nodes)}; }, '=': function(x, y) { // optimization for two node-sets case: avoid n^2 comparisons. if ('object' === typeof x && 'object' === typeof y) { var aMap = {}; for (var i = 0; i < x.nodes.length; ++i) { var s = fn.string({nodes:[x.nodes[i]]}); aMap[s] = true; } for (var i = 0; i < y.nodes.length; ++i) { var s = fn.string({nodes:[y.nodes[i]]}); if (aMap[s]) return true; } return false; } else { return comparisonHelper(function(x, y) {return x === y;}, x, y); } }, '!=': function(x, y) { // optimization for two node-sets case: avoid n^2 comparisons. if ('object' === typeof x && 'object' === typeof y) { if (0 === x.nodes.length || 0 === y.nodes.length) return false; var aMap = {}; for (var i = 0; i < x.nodes.length; ++i) { var s = fn.string({nodes:[x.nodes[i]]}); aMap[s] = true; } for (var i = 0; i < y.nodes.length; ++i) { var s = fn.string({nodes:[y.nodes[i]]}); if (!aMap[s]) return true; } return false; } else { return comparisonHelper(function(x, y) {return x !== y;}, x, y); } } }; var nodeTypes = xpath.nodeTypes = { 'node': 0, 'attribute': 2, 'comment': 8, // this.doc.COMMENT_NODE, 'text': 3, // this.doc.TEXT_NODE, 'processing-instruction': 7, // this.doc.PROCESSING_INSTRUCTION_NODE, 'element': 1 //this.doc.ELEMENT_NODE }; /** For debugging and unit tests: returnjs a stringified version of the * argument. */ var stringifyObject = xpath.stringifyObject = function stringifyObject(ctx) { var seenKey = 'seen' + Math.floor(Math.random()*1000000000); return JSON.stringify(helper(ctx)); function helper(ctx) { if (Array.isArray(ctx)) { return ctx.map(function(x) {return helper(x);}); } if ('object' !== typeof ctx) return ctx; if (null == ctx) return ctx; // if (ctx.toString) return ctx.toString(); if (null != ctx.outerHTML) return ctx.outerHTML; if (null != ctx.nodeValue) return ctx.nodeName + '=' + ctx.nodeValue; if (ctx[seenKey]) return '[circular]'; ctx[seenKey] = true; var nicer = {}; for (var key in ctx) { if (seenKey === key) continue; try { nicer[key] = helper(ctx[key]); } catch (e) { nicer[key] = '[exception: ' + e.message + ']'; } } delete ctx[seenKey]; return nicer; } } var Evaluator = xpath.Evaluator = function Evaluator(doc) { this.doc = doc; } Evaluator.prototype = { val: function val(ast, ctx) { console.assert(ctx.nodes); if ('number' === typeof ast || 'string' === typeof ast) return ast; if (more[ast[0]]) { var evaluatedParams = []; for (var i = 1; i < ast.length; ++i) { evaluatedParams.push(this.val(ast[i], ctx)); } var r = more[ast[0]].apply(ctx, evaluatedParams); return r; } switch (ast[0]) { case 'Root': return {nodes: [this.doc]}; case 'FunctionCall': var functionName = ast[1], functionParams = ast[2]; if (null == fn[functionName]) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Unknown function: ' + functionName); var evaluatedParams = []; for (var i = 0; i < functionParams.length; ++i) { evaluatedParams.push(this.val(functionParams[i], ctx)); } var r = fn[functionName].apply(ctx, evaluatedParams); return r; case 'Predicate': var lhs = this.val(ast[1], ctx); var ret = {nodes: []}; var contexts = eachContext(lhs); for (var i = 0; i < contexts.length; ++i) { var singleNodeSet = contexts[i]; var rhs = this.val(ast[2], singleNodeSet); var success; if ('number' === typeof rhs) { success = rhs === singleNodeSet.pos[0][0]; } else { success = fn['boolean'](rhs); } if (success) { var node = singleNodeSet.nodes[0]; ret.nodes.push(node); // skip over all the rest of the same node. while (i+1 < contexts.length && node === contexts[i+1].nodes[0]) { i++; } } } return ret; case 'PathExpr': // turn the path into an expressoin; i.e., remove the position // information of the last axis. var x = this.val(ast[1], ctx); // Make the nodeset a forward-direction-only one. if (x.finalize) { // it is a NodeMultiSet return {nodes: x.nodes}; } else { return x; } case '/': // TODO: don't generate '/' nodes, just Axis nodes. var lhs = this.val(ast[1], ctx); console.assert(null != lhs); var r = this.val(ast[2], lhs); console.assert(null != r); return r; case 'Axis': // All the axis tests from Step. We only get AxisSpecifier NodeTest, // not the predicate (which is applied later) var axis = ast[1], nodeType = ast[2], nodeTypeNum = nodeTypes[nodeType], shouldLowerCase = true, // TODO: give option nodeName = ast[3] && shouldLowerCase ? ast[3].toLowerCase() : ast[3]; nodeName = nodeName === '*' ? null : nodeName; if ('object' !== typeof ctx) return {nodes:[], pos:[]}; var nodeList = ctx.nodes.slice(); // TODO: is copy needed? var r = axes[axis](nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase); return r; } } }; var evaluate = xpath.evaluate = function evaluate(expr, doc, context) { //var astFactory = new AstEvaluatorFactory(doc, context); var stream = new Stream(expr); var ast = parse(stream, astFactory); var val = new Evaluator(doc).val(ast, {nodes: [context]}); return val; } /*************************************************************************** * DOM interface * ***************************************************************************/ var XPathException = xpath.XPathException = function XPathException(code, message) { var e = new Error(message); e.name = 'XPathException'; e.code = code; return e; } XPathException.INVALID_EXPRESSION_ERR = 51; XPathException.TYPE_ERR = 52; var XPathEvaluator = xpath.XPathEvaluator = function XPathEvaluator() {} XPathEvaluator.prototype = { createExpression: function(expression, resolver) { return new XPathExpression(expression, resolver); }, createNSResolver: function(nodeResolver) { // TODO }, evaluate: function evaluate(expression, contextNode, resolver, type, result) { var expr = new XPathExpression(expression, resolver); return expr.evaluate(contextNode, type, result); } }; var XPathExpression = xpath.XPathExpression = function XPathExpression(expression, resolver, optDoc) { var stream = new Stream(expression); this._ast = parse(stream, astFactory); this._doc = optDoc; } XPathExpression.prototype = { evaluate: function evaluate(contextNode, type, result) { if (null == contextNode.nodeType) throw new Error('bad argument (expected context node): ' + contextNode); var doc = contextNode.ownerDocument || contextNode; if (null != this._doc && this._doc !== doc) { throw new core.DOMException( core.DOMException.WRONG_DOCUMENT_ERR, 'The document must be the same as the context node\'s document.'); } var evaluator = new Evaluator(doc); var value = evaluator.val(this._ast, {nodes: [contextNode]}); if (XPathResult.NUMBER_TYPE === type) value = fn.number(value); else if (XPathResult.STRING_TYPE === type) value = fn.string(value); else if (XPathResult.BOOLEAN_TYPE === type) value = fn['boolean'](value); else if (XPathResult.ANY_TYPE !== type && XPathResult.UNORDERED_NODE_ITERATOR_TYPE !== type && XPathResult.ORDERED_NODE_ITERATOR_TYPE !== type && XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE !== type && XPathResult.ORDERED_NODE_SNAPSHOT_TYPE !== type && XPathResult.ANY_UNORDERED_NODE_TYPE !== type && XPathResult.FIRST_ORDERED_NODE_TYPE !== type) throw new core.DOMException( core.DOMException.NOT_SUPPORTED_ERR, 'You must provide an XPath result type (0=any).'); else if (XPathResult.ANY_TYPE !== type && 'object' !== typeof value) throw new XPathException( XPathException.TYPE_ERR, 'Value should be a node-set: ' + value); return new XPathResult(doc, value, type); } } var XPathResult = xpath.XPathResult = function XPathResult(doc, value, resultType) { this._value = value; this._resultType = resultType; this._i = 0; // TODO: we removed mutation events but didn't take care of this. No tests fail, so that's nice, but eventually we // should fix this, preferably by entirely replacing our XPath implementation. // this._invalidated = false; // if (this.resultType === XPathResult.UNORDERED_NODE_ITERATOR_TYPE || // this.resultType === XPathResult.ORDERED_NODE_ITERATOR_TYPE) { // doc.addEventListener('DOMSubtreeModified', invalidate, true); // var self = this; // function invalidate() { // self._invalidated = true; // doc.removeEventListener('DOMSubtreeModified', invalidate, true); // } // } } XPathResult.ANY_TYPE = 0; XPathResult.NUMBER_TYPE = 1; XPathResult.STRING_TYPE = 2; XPathResult.BOOLEAN_TYPE = 3; XPathResult.UNORDERED_NODE_ITERATOR_TYPE = 4; XPathResult.ORDERED_NODE_ITERATOR_TYPE = 5; XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE = 6; XPathResult.ORDERED_NODE_SNAPSHOT_TYPE = 7; XPathResult.ANY_UNORDERED_NODE_TYPE = 8; XPathResult.FIRST_ORDERED_NODE_TYPE = 9; var proto = { // XPathResultType get resultType() { if (this._resultType) return this._resultType; switch (typeof this._value) { case 'number': return XPathResult.NUMBER_TYPE; case 'string': return XPathResult.STRING_TYPE; case 'boolean': return XPathResult.BOOLEAN_TYPE; default: return XPathResult.UNORDERED_NODE_ITERATOR_TYPE; } }, get numberValue() { if (XPathResult.NUMBER_TYPE !== this.resultType) throw new XPathException(XPathException.TYPE_ERR, 'You should have asked for a NUMBER_TYPE.'); return this._value; }, get stringValue() { if (XPathResult.STRING_TYPE !== this.resultType) throw new XPathException(XPathException.TYPE_ERR, 'You should have asked for a STRING_TYPE.'); return this._value; }, get booleanValue() { if (XPathResult.BOOLEAN_TYPE !== this.resultType) throw new XPathException(XPathException.TYPE_ERR, 'You should have asked for a BOOLEAN_TYPE.'); return this._value; }, get singleNodeValue() { if (XPathResult.ANY_UNORDERED_NODE_TYPE !== this.resultType && XPathResult.FIRST_ORDERED_NODE_TYPE !== this.resultType) throw new XPathException( XPathException.TYPE_ERR, 'You should have asked for a FIRST_ORDERED_NODE_TYPE.'); return this._value.nodes[0] || null; }, get invalidIteratorState() { if (XPathResult.UNORDERED_NODE_ITERATOR_TYPE !== this.resultType && XPathResult.ORDERED_NODE_ITERATOR_TYPE !== this.resultType) return false; return !!this._invalidated; }, get snapshotLength() { if (XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE !== this.resultType && XPathResult.ORDERED_NODE_SNAPSHOT_TYPE !== this.resultType) throw new XPathException( XPathException.TYPE_ERR, 'You should have asked for a ORDERED_NODE_SNAPSHOT_TYPE.'); return this._value.nodes.length; }, iterateNext: function iterateNext() { if (XPathResult.UNORDERED_NODE_ITERATOR_TYPE !== this.resultType && XPathResult.ORDERED_NODE_ITERATOR_TYPE !== this.resultType) throw new XPathException( XPathException.TYPE_ERR, 'You should have asked for a ORDERED_NODE_ITERATOR_TYPE.'); if (this.invalidIteratorState) throw new core.DOMException( core.DOMException.INVALID_STATE_ERR, 'The document has been mutated since the result was returned'); return this._value.nodes[this._i++] || null; }, snapshotItem: function snapshotItem(index) { if (XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE !== this.resultType && XPathResult.ORDERED_NODE_SNAPSHOT_TYPE !== this.resultType) throw new XPathException( XPathException.TYPE_ERR, 'You should have asked for a ORDERED_NODE_SNAPSHOT_TYPE.'); return this._value.nodes[index] || null; } }; // so you can access ANY_TYPE etc. from the instances: XPathResult.prototype = Object.create(XPathResult, Object.keys(proto).reduce(function (descriptors, name) { descriptors[name] = Object.getOwnPropertyDescriptor(proto, name); return descriptors; }, { constructor: { value: XPathResult, writable: true, configurable: true } })); core.XPathException = XPathException; core.XPathExpression = XPathExpression; core.XPathResult = XPathResult; core.XPathEvaluator = XPathEvaluator; core.Document.prototype.createExpression = XPathEvaluator.prototype.createExpression; core.Document.prototype.createNSResolver = XPathEvaluator.prototype.createNSResolver; core.Document.prototype.evaluate = XPathEvaluator.prototype.evaluate; return xpath; // for tests };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/level3/xpath.js
xpath.js
"use strict"; const cssom = require("cssom"); const cssstyle = require("cssstyle"); exports.addToCore = core => { // What works now: // - Accessing the rules defined in individual stylesheets // - Modifications to style content attribute are reflected in style property // - Modifications to style property are reflected in style content attribute // TODO // - Modifications to style element's textContent are reflected in sheet property. // - Modifications to style element's sheet property are reflected in textContent. // - Modifications to link.href property are reflected in sheet property. // - Less-used features of link: disabled // - Less-used features of style: disabled, scoped, title // - CSSOM-View // - getComputedStyle(): requires default stylesheet, cascading, inheritance, // filtering by @media (screen? print?), layout for widths/heights // - Load events are not in the specs, but apparently some browsers // implement something. Should onload only fire after all @imports have been // loaded, or only the primary sheet? core.StyleSheet = cssom.StyleSheet; core.MediaList = cssom.MediaList; core.CSSStyleSheet = cssom.CSSStyleSheet; core.CSSRule = cssom.CSSRule; core.CSSStyleRule = cssom.CSSStyleRule; core.CSSMediaRule = cssom.CSSMediaRule; core.CSSImportRule = cssom.CSSImportRule; core.CSSStyleDeclaration = cssstyle.CSSStyleDeclaration; // Relavant specs // http://www.w3.org/TR/DOM-Level-2-Style (2000) // http://www.w3.org/TR/cssom-view/ (2008) // http://dev.w3.org/csswg/cssom/ (2010) Meant to replace DOM Level 2 Style // http://www.whatwg.org/specs/web-apps/current-work/multipage/ HTML5, of course // http://dev.w3.org/csswg/css-style-attr/ not sure what's new here // Objects that aren't in cssom library but should be: // CSSRuleList (cssom just uses array) // CSSFontFaceRule // CSSPageRule // These rules don't really make sense to implement, so CSSOM draft makes them // obsolete. // CSSCharsetRule // CSSUnknownRule // These objects are considered obsolete by CSSOM draft, although modern // browsers implement them. // CSSValue // CSSPrimitiveValue // CSSValueList // RGBColor // Rect // Counter };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsdom/lib/jsdom/level2/style.js
style.js
# DOMException This package implements the [`DOMException`](https://heycam.github.io/webidl/#idl-DOMException) class, from web browsers. It exists in service of [jsdom](https://github.com/tmpvar/jsdom) and related packages. Example usage: ```js const DOMException = require("domexception"); const e1 = new DOMException("Something went wrong", "BadThingsError"); console.assert(e1.name === "BadThingsError"); console.assert(e1.code === 0); const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError"); console.assert(e2.name === "NoModificationAllowedError"); console.assert(e2.code === 7); console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10); ``` ## APIs This package exposes two flavors of the `DOMException` interface depending on the imported module. ### `domexception` module This module default-exports the `DOMException` interface constructor. ### `domexception/webidl2js-wrapper` module This module exports the `DOMException` [interface wrapper API](https://github.com/jsdom/webidl2js#for-interfaces) generated by [webidl2js](https://github.com/jsdom/webidl2js).
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/domexception/README.md
README.md
# The BSD 2-Clause License Copyright (c) 2014, Domenic Denicola All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/domexception/node_modules/webidl-conversions/LICENSE.md
LICENSE.md
# Web IDL Type Conversions on JavaScript Values This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [Web IDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). The goal is that you should be able to write code like ```js "use strict"; const conversions = require("webidl-conversions"); function doStuff(x, y) { x = conversions["boolean"](x); y = conversions["unsigned long"](y); // actual algorithm code here } ``` and your function `doStuff` will behave the same as a Web IDL operation declared as ```webidl void doStuff(boolean x, unsigned long y); ``` ## API This package's main module's default export is an object with a variety of methods, each corresponding to a different Web IDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the Web IDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the Web IDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). Each method also accepts a second, optional, parameter for miscellaneous options. For conversion methods that throw errors, a string option `{ context }` may be provided to provide more information in the error message. (For example, `conversions["float"](NaN, { context: "Argument 1 of Interface's operation" })` will throw an error with message `"Argument 1 of Interface's operation is not a finite floating-point value."`) Specific conversions may also accept other options, the details of which can be found below. ## Conversions implemented Conversions for all of the basic types from the Web IDL specification are implemented: - [`any`](https://heycam.github.io/webidl/#es-any) - [`void`](https://heycam.github.io/webidl/#es-void) - [`boolean`](https://heycam.github.io/webidl/#es-boolean) - [Integer types](https://heycam.github.io/webidl/#es-integer-types), which can additionally be provided the boolean options `{ clamp, enforceRange }` as a second parameter - [`float`](https://heycam.github.io/webidl/#es-float), [`unrestricted float`](https://heycam.github.io/webidl/#es-unrestricted-float) - [`double`](https://heycam.github.io/webidl/#es-double), [`unrestricted double`](https://heycam.github.io/webidl/#es-unrestricted-double) - [`DOMString`](https://heycam.github.io/webidl/#es-DOMString), which can additionally be provided the boolean option `{ treatNullAsEmptyString }` as a second parameter - [`ByteString`](https://heycam.github.io/webidl/#es-ByteString), [`USVString`](https://heycam.github.io/webidl/#es-USVString) - [`object`](https://heycam.github.io/webidl/#es-object) - [Buffer source types](https://heycam.github.io/webidl/#es-buffer-source-types) Additionally, for convenience, the following derived type definitions are implemented: - [`ArrayBufferView`](https://heycam.github.io/webidl/#ArrayBufferView) - [`BufferSource`](https://heycam.github.io/webidl/#BufferSource) - [`DOMTimeStamp`](https://heycam.github.io/webidl/#DOMTimeStamp) - [`Function`](https://heycam.github.io/webidl/#Function) - [`VoidFunction`](https://heycam.github.io/webidl/#VoidFunction) (although it will not censor the return type) Derived types, such as nullable types, promise types, sequences, records, etc. are not handled by this library. You may wish to investigate the [webidl2js](https://github.com/jsdom/webidl2js) project. ### A note on the `long long` types The `long long` and `unsigned long long` Web IDL types can hold values that cannot be stored in JavaScript numbers, so the conversion is imperfect. For example, converting the JavaScript number `18446744073709552000` to a Web IDL `long long` is supposed to produce the Web IDL value `-18446744073709551232`. Since we are representing our Web IDL values in JavaScript, we can't represent `-18446744073709551232`, so we instead the best we could do is `-18446744073709552000` as the output. This library actually doesn't even get that far. Producing those results would require doing accurate modular arithmetic on 64-bit intermediate values, but JavaScript does not make this easy. We could pull in a big-integer library as a dependency, but in lieu of that, we for now have decided to just produce inaccurate results if you pass in numbers that are not strictly between `Number.MIN_SAFE_INTEGER` and `Number.MAX_SAFE_INTEGER`. ## Background What's actually going on here, conceptually, is pretty weird. Let's try to explain. Web IDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on Web IDL values, i.e. instances of Web IDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a Web IDL value of [Web IDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. Separately from its type system, Web IDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given Web IDL operation, how does that get converted into a Web IDL value? For example, a JavaScript `true` passed in the position of a Web IDL `boolean` argument becomes a Web IDL `true`. But, a JavaScript `true` passed in the position of a [Web IDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a Web IDL `1`. And so on. Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the Web IDL algorithms, they don't actually use Web IDL values, since those aren't "real" outside of specs. Instead, implementations apply the Web IDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. The upside of all this is that implementations can abstract all the conversion logic away, letting Web IDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of Web IDL, in a nutshell. And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given Web IDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ Web IDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ Web IDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a Web IDL `1` in an unsigned long context, which then becomes a JavaScript `1`. ## Don't use this Seriously, why would you ever use this? You really shouldn't. Web IDL is … strange, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from Web IDL. In general, your JavaScript should not be trying to become more like Web IDL; if anything, we should fix Web IDL to make it more like JavaScript. The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in Web IDL. Its main consumer is the [jsdom](https://github.com/jsdom/jsdom) project.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/domexception/node_modules/webidl-conversions/README.md
README.md
"use strict"; function _(message, opts) { return `${opts && opts.context ? opts.context : "Value"} ${message}.`; } function type(V) { if (V === null) { return "Null"; } switch (typeof V) { case "undefined": return "Undefined"; case "boolean": return "Boolean"; case "number": return "Number"; case "string": return "String"; case "symbol": return "Symbol"; case "object": // Falls through case "function": // Falls through default: // Per ES spec, typeof returns an implemention-defined value that is not any of the existing ones for // uncallable non-standard exotic objects. Yet Type() which the Web IDL spec depends on returns Object for // such cases. So treat the default case as an object. return "Object"; } } // Round x to the nearest integer, choosing the even integer if it lies halfway between two. function evenRound(x) { // There are four cases for numbers with fractional part being .5: // // case | x | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 | example // 1 | 2n + 0.5 | 2n | 2n + 1 | 2n | > | 0.5 | 0 | 0.5 -> 0 // 2 | 2n + 1.5 | 2n + 1 | 2n + 2 | 2n + 2 | > | 0.5 | 1 | 1.5 -> 2 // 3 | -2n - 0.5 | -2n - 1 | -2n | -2n | < | -0.5 | 0 | -0.5 -> 0 // 4 | -2n - 1.5 | -2n - 2 | -2n - 1 | -2n - 2 | < | -0.5 | 1 | -1.5 -> -2 // (where n is a non-negative integer) // // Branch here for cases 1 and 4 if ((x > 0 && (x % 1) === +0.5 && (x & 1) === 0) || (x < 0 && (x % 1) === -0.5 && (x & 1) === 1)) { return censorNegativeZero(Math.floor(x)); } return censorNegativeZero(Math.round(x)); } function integerPart(n) { return censorNegativeZero(Math.trunc(n)); } function sign(x) { return x < 0 ? -1 : 1; } function modulo(x, y) { // https://tc39.github.io/ecma262/#eqn-modulo // Note that http://stackoverflow.com/a/4467559/3191 does NOT work for large modulos const signMightNotMatch = x % y; if (sign(y) !== sign(signMightNotMatch)) { return signMightNotMatch + y; } return signMightNotMatch; } function censorNegativeZero(x) { return x === 0 ? 0 : x; } function createIntegerConversion(bitLength, typeOpts) { const isSigned = !typeOpts.unsigned; let lowerBound; let upperBound; if (bitLength === 64) { upperBound = Math.pow(2, 53) - 1; lowerBound = !isSigned ? 0 : -Math.pow(2, 53) + 1; } else if (!isSigned) { lowerBound = 0; upperBound = Math.pow(2, bitLength) - 1; } else { lowerBound = -Math.pow(2, bitLength - 1); upperBound = Math.pow(2, bitLength - 1) - 1; } const twoToTheBitLength = Math.pow(2, bitLength); const twoToOneLessThanTheBitLength = Math.pow(2, bitLength - 1); return (V, opts) => { if (opts === undefined) { opts = {}; } let x = +V; x = censorNegativeZero(x); // Spec discussion ongoing: https://github.com/heycam/webidl/issues/306 if (opts.enforceRange) { if (!Number.isFinite(x)) { throw new TypeError(_("is not a finite number", opts)); } x = integerPart(x); if (x < lowerBound || x > upperBound) { throw new TypeError(_( `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, opts)); } return x; } if (!Number.isNaN(x) && opts.clamp) { x = Math.min(Math.max(x, lowerBound), upperBound); x = evenRound(x); return x; } if (!Number.isFinite(x) || x === 0) { return 0; } x = integerPart(x); // Math.pow(2, 64) is not accurately representable in JavaScript, so try to avoid these per-spec operations if // possible. Hopefully it's an optimization for the non-64-bitLength cases too. if (x >= lowerBound && x <= upperBound) { return x; } // These will not work great for bitLength of 64, but oh well. See the README for more details. x = modulo(x, twoToTheBitLength); if (isSigned && x >= twoToOneLessThanTheBitLength) { return x - twoToTheBitLength; } return x; }; } exports.any = V => { return V; }; exports.void = function () { return undefined; }; exports.boolean = function (val) { return !!val; }; exports.byte = createIntegerConversion(8, { unsigned: false }); exports.octet = createIntegerConversion(8, { unsigned: true }); exports.short = createIntegerConversion(16, { unsigned: false }); exports["unsigned short"] = createIntegerConversion(16, { unsigned: true }); exports.long = createIntegerConversion(32, { unsigned: false }); exports["unsigned long"] = createIntegerConversion(32, { unsigned: true }); exports["long long"] = createIntegerConversion(64, { unsigned: false }); exports["unsigned long long"] = createIntegerConversion(64, { unsigned: true }); exports.double = (V, opts) => { const x = +V; if (!Number.isFinite(x)) { throw new TypeError(_("is not a finite floating-point value", opts)); } return x; }; exports["unrestricted double"] = V => { const x = +V; return x; }; exports.float = (V, opts) => { const x = +V; if (!Number.isFinite(x)) { throw new TypeError(_("is not a finite floating-point value", opts)); } if (Object.is(x, -0)) { return x; } const y = Math.fround(x); if (!Number.isFinite(y)) { throw new TypeError(_("is outside the range of a single-precision floating-point value", opts)); } return y; }; exports["unrestricted float"] = V => { const x = +V; if (isNaN(x)) { return x; } if (Object.is(x, -0)) { return x; } return Math.fround(x); }; exports.DOMString = function (V, opts) { if (opts === undefined) { opts = {}; } if (opts.treatNullAsEmptyString && V === null) { return ""; } if (typeof V === "symbol") { throw new TypeError(_("is a symbol, which cannot be converted to a string", opts)); } return String(V); }; exports.ByteString = (V, opts) => { const x = exports.DOMString(V, opts); let c; for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { if (c > 255) { throw new TypeError(_("is not a valid ByteString", opts)); } } return x; }; exports.USVString = (V, opts) => { const S = exports.DOMString(V, opts); const n = S.length; const U = []; for (let i = 0; i < n; ++i) { const c = S.charCodeAt(i); if (c < 0xD800 || c > 0xDFFF) { U.push(String.fromCodePoint(c)); } else if (0xDC00 <= c && c <= 0xDFFF) { U.push(String.fromCodePoint(0xFFFD)); } else if (i === n - 1) { U.push(String.fromCodePoint(0xFFFD)); } else { const d = S.charCodeAt(i + 1); if (0xDC00 <= d && d <= 0xDFFF) { const a = c & 0x3FF; const b = d & 0x3FF; U.push(String.fromCodePoint((2 << 15) + ((2 << 9) * a) + b)); ++i; } else { U.push(String.fromCodePoint(0xFFFD)); } } } return U.join(""); }; exports.object = (V, opts) => { if (type(V) !== "Object") { throw new TypeError(_("is not an object", opts)); } return V; }; // Not exported, but used in Function and VoidFunction. // Neither Function nor VoidFunction is defined with [TreatNonObjectAsNull], so // handling for that is omitted. function convertCallbackFunction(V, opts) { if (typeof V !== "function") { throw new TypeError(_("is not a function", opts)); } return V; } const abByteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; function isArrayBuffer(V) { try { abByteLengthGetter.call(V); return true; } catch (e) { return false; } } // I don't think we can reliably detect detached ArrayBuffers. exports.ArrayBuffer = (V, opts) => { if (!isArrayBuffer(V)) { throw new TypeError(_("is not a view on an ArrayBuffer object", opts)); } return V; }; const dvByteLengthGetter = Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get; exports.DataView = (V, opts) => { try { dvByteLengthGetter.call(V); return V; } catch (e) { throw new TypeError(_("is not a view on an DataView object", opts)); } }; [ Int8Array, Int16Array, Int32Array, Uint8Array, Uint16Array, Uint32Array, Uint8ClampedArray, Float32Array, Float64Array ].forEach(func => { const name = func.name; const article = /^[AEIOU]/.test(name) ? "an" : "a"; exports[name] = (V, opts) => { if (!ArrayBuffer.isView(V) || V.constructor.name !== name) { throw new TypeError(_(`is not ${article} ${name} object`, opts)); } return V; }; }); // Common definitions exports.ArrayBufferView = (V, opts) => { if (!ArrayBuffer.isView(V)) { throw new TypeError(_("is not a view on an ArrayBuffer object", opts)); } return V; }; exports.BufferSource = (V, opts) => { if (!ArrayBuffer.isView(V) && !isArrayBuffer(V)) { throw new TypeError(_("is not an ArrayBuffer object or a view on one", opts)); } return V; }; exports.DOMTimeStamp = exports["unsigned long long"]; exports.Function = convertCallbackFunction; exports.VoidFunction = convertCallbackFunction;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/domexception/node_modules/webidl-conversions/lib/index.js
index.js
"use strict"; // Returns "Type(value) is Object" in ES terminology. function isObject(value) { return typeof value === "object" && value !== null || typeof value === "function"; } function hasOwn(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } const wrapperSymbol = Symbol("wrapper"); const implSymbol = Symbol("impl"); const sameObjectCaches = Symbol("SameObject caches"); const ctorRegistrySymbol = Symbol.for("[webidl2js] constructor registry"); function getSameObject(wrapper, prop, creator) { if (!wrapper[sameObjectCaches]) { wrapper[sameObjectCaches] = Object.create(null); } if (prop in wrapper[sameObjectCaches]) { return wrapper[sameObjectCaches][prop]; } wrapper[sameObjectCaches][prop] = creator(); return wrapper[sameObjectCaches][prop]; } function wrapperForImpl(impl) { return impl ? impl[wrapperSymbol] : null; } function implForWrapper(wrapper) { return wrapper ? wrapper[implSymbol] : null; } function tryWrapperForImpl(impl) { const wrapper = wrapperForImpl(impl); return wrapper ? wrapper : impl; } function tryImplForWrapper(wrapper) { const impl = implForWrapper(wrapper); return impl ? impl : wrapper; } const iterInternalSymbol = Symbol("internal"); const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())); function isArrayIndexPropName(P) { if (typeof P !== "string") { return false; } const i = P >>> 0; if (i === Math.pow(2, 32) - 1) { return false; } const s = `${i}`; if (P !== s) { return false; } return true; } const byteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; function isArrayBuffer(value) { try { byteLengthGetter.call(value); return true; } catch (e) { return false; } } const supportsPropertyIndex = Symbol("supports property index"); const supportedPropertyIndices = Symbol("supported property indices"); const supportsPropertyName = Symbol("supports property name"); const supportedPropertyNames = Symbol("supported property names"); const indexedGet = Symbol("indexed property get"); const indexedSetNew = Symbol("indexed property set new"); const indexedSetExisting = Symbol("indexed property set existing"); const namedGet = Symbol("named property get"); const namedSetNew = Symbol("named property set new"); const namedSetExisting = Symbol("named property set existing"); const namedDelete = Symbol("named property delete"); module.exports = exports = { isObject, hasOwn, wrapperSymbol, implSymbol, getSameObject, ctorRegistrySymbol, wrapperForImpl, implForWrapper, tryWrapperForImpl, tryImplForWrapper, iterInternalSymbol, IteratorPrototype, isArrayBuffer, isArrayIndexPropName, supportsPropertyIndex, supportedPropertyIndices, supportsPropertyName, supportedPropertyNames, indexedGet, indexedSetNew, indexedSetExisting, namedGet, namedSetNew, namedSetExisting, namedDelete };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/domexception/lib/utils.js
utils.js
"use strict"; const conversions = require("webidl-conversions"); const utils = require("domexception/lib/utils.js"); const impl = utils.implSymbol; const ctorRegistry = utils.ctorRegistrySymbol; const iface = { // When an interface-module that implements this interface as a mixin is loaded, it will append its own `.is()` // method into this array. It allows objects that directly implements *those* interfaces to be recognized as // implementing this mixin interface. _mixedIntoPredicates: [], is(obj) { if (obj) { if (utils.hasOwn(obj, impl) && obj[impl] instanceof Impl.implementation) { return true; } for (const isMixedInto of module.exports._mixedIntoPredicates) { if (isMixedInto(obj)) { return true; } } } return false; }, isImpl(obj) { if (obj) { if (obj instanceof Impl.implementation) { return true; } const wrapper = utils.wrapperForImpl(obj); for (const isMixedInto of module.exports._mixedIntoPredicates) { if (isMixedInto(wrapper)) { return true; } } } return false; }, convert(obj, { context = "The provided value" } = {}) { if (module.exports.is(obj)) { return utils.implForWrapper(obj); } throw new TypeError(`${context} is not of type 'DOMException'.`); }, create(globalObject, constructorArgs, privateData) { if (globalObject[ctorRegistry] === undefined) { throw new Error("Internal error: invalid global object"); } const ctor = globalObject[ctorRegistry]["DOMException"]; if (ctor === undefined) { throw new Error("Internal error: constructor DOMException is not installed on the passed global object"); } let obj = Object.create(ctor.prototype); obj = iface.setup(obj, globalObject, constructorArgs, privateData); return obj; }, createImpl(globalObject, constructorArgs, privateData) { const obj = iface.create(globalObject, constructorArgs, privateData); return utils.implForWrapper(obj); }, _internalSetup(obj) {}, setup(obj, globalObject, constructorArgs = [], privateData = {}) { privateData.wrapper = obj; iface._internalSetup(obj); Object.defineProperty(obj, impl, { value: new Impl.implementation(globalObject, constructorArgs, privateData), configurable: true }); obj[impl][utils.wrapperSymbol] = obj; if (Impl.init) { Impl.init(obj[impl], privateData); } return obj; }, install(globalObject) { class DOMException { constructor() { const args = []; { let curArg = arguments[0]; if (curArg !== undefined) { curArg = conversions["DOMString"](curArg, { context: "Failed to construct 'DOMException': parameter 1" }); } else { curArg = ""; } args.push(curArg); } { let curArg = arguments[1]; if (curArg !== undefined) { curArg = conversions["DOMString"](curArg, { context: "Failed to construct 'DOMException': parameter 2" }); } else { curArg = "Error"; } args.push(curArg); } return iface.setup(Object.create(new.target.prototype), globalObject, args); } get name() { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl]["name"]; } get message() { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl]["message"]; } get code() { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl]["code"]; } } Object.defineProperties(DOMException.prototype, { name: { enumerable: true }, message: { enumerable: true }, code: { enumerable: true }, [Symbol.toStringTag]: { value: "DOMException", configurable: true }, INDEX_SIZE_ERR: { value: 1, enumerable: true }, DOMSTRING_SIZE_ERR: { value: 2, enumerable: true }, HIERARCHY_REQUEST_ERR: { value: 3, enumerable: true }, WRONG_DOCUMENT_ERR: { value: 4, enumerable: true }, INVALID_CHARACTER_ERR: { value: 5, enumerable: true }, NO_DATA_ALLOWED_ERR: { value: 6, enumerable: true }, NO_MODIFICATION_ALLOWED_ERR: { value: 7, enumerable: true }, NOT_FOUND_ERR: { value: 8, enumerable: true }, NOT_SUPPORTED_ERR: { value: 9, enumerable: true }, INUSE_ATTRIBUTE_ERR: { value: 10, enumerable: true }, INVALID_STATE_ERR: { value: 11, enumerable: true }, SYNTAX_ERR: { value: 12, enumerable: true }, INVALID_MODIFICATION_ERR: { value: 13, enumerable: true }, NAMESPACE_ERR: { value: 14, enumerable: true }, INVALID_ACCESS_ERR: { value: 15, enumerable: true }, VALIDATION_ERR: { value: 16, enumerable: true }, TYPE_MISMATCH_ERR: { value: 17, enumerable: true }, SECURITY_ERR: { value: 18, enumerable: true }, NETWORK_ERR: { value: 19, enumerable: true }, ABORT_ERR: { value: 20, enumerable: true }, URL_MISMATCH_ERR: { value: 21, enumerable: true }, QUOTA_EXCEEDED_ERR: { value: 22, enumerable: true }, TIMEOUT_ERR: { value: 23, enumerable: true }, INVALID_NODE_TYPE_ERR: { value: 24, enumerable: true }, DATA_CLONE_ERR: { value: 25, enumerable: true } }); Object.defineProperties(DOMException, { INDEX_SIZE_ERR: { value: 1, enumerable: true }, DOMSTRING_SIZE_ERR: { value: 2, enumerable: true }, HIERARCHY_REQUEST_ERR: { value: 3, enumerable: true }, WRONG_DOCUMENT_ERR: { value: 4, enumerable: true }, INVALID_CHARACTER_ERR: { value: 5, enumerable: true }, NO_DATA_ALLOWED_ERR: { value: 6, enumerable: true }, NO_MODIFICATION_ALLOWED_ERR: { value: 7, enumerable: true }, NOT_FOUND_ERR: { value: 8, enumerable: true }, NOT_SUPPORTED_ERR: { value: 9, enumerable: true }, INUSE_ATTRIBUTE_ERR: { value: 10, enumerable: true }, INVALID_STATE_ERR: { value: 11, enumerable: true }, SYNTAX_ERR: { value: 12, enumerable: true }, INVALID_MODIFICATION_ERR: { value: 13, enumerable: true }, NAMESPACE_ERR: { value: 14, enumerable: true }, INVALID_ACCESS_ERR: { value: 15, enumerable: true }, VALIDATION_ERR: { value: 16, enumerable: true }, TYPE_MISMATCH_ERR: { value: 17, enumerable: true }, SECURITY_ERR: { value: 18, enumerable: true }, NETWORK_ERR: { value: 19, enumerable: true }, ABORT_ERR: { value: 20, enumerable: true }, URL_MISMATCH_ERR: { value: 21, enumerable: true }, QUOTA_EXCEEDED_ERR: { value: 22, enumerable: true }, TIMEOUT_ERR: { value: 23, enumerable: true }, INVALID_NODE_TYPE_ERR: { value: 24, enumerable: true }, DATA_CLONE_ERR: { value: 25, enumerable: true } }); if (globalObject[ctorRegistry] === undefined) { globalObject[ctorRegistry] = Object.create(null); } globalObject[ctorRegistry]["DOMException"] = DOMException; Object.defineProperty(globalObject, "DOMException", { configurable: true, writable: true, value: DOMException }); } }; // iface module.exports = iface; const Impl = require("domexception/lib/DOMException-impl.js");
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/domexception/lib/DOMException.js
DOMException.js
# jsbn: javascript big number [Tom Wu's Original Website](http://www-cs-students.stanford.edu/~tjw/jsbn/) I felt compelled to put this on github and publish to npm. I haven't tested every other big integer library out there, but the few that I have tested in comparison to this one have not even come close in performance. I am aware of the `bi` module on npm, however it has been modified and I wanted to publish the original without modifications. This is jsbn and jsbn2 from Tom Wu's original website above, with the modular pattern applied to prevent global leaks and to allow for use with node.js on the server side. ## usage var BigInteger = require('jsbn'); var a = new BigInteger('91823918239182398123'); alert(a.bitLength()); // 67 ## API ### bi.toString() returns the base-10 number as a string ### bi.negate() returns a new BigInteger equal to the negation of `bi` ### bi.abs returns new BI of absolute value ### bi.compareTo ### bi.bitLength ### bi.mod ### bi.modPowInt ### bi.clone ### bi.intValue ### bi.byteValue ### bi.shortValue ### bi.signum ### bi.toByteArray ### bi.equals ### bi.min ### bi.max ### bi.and ### bi.or ### bi.xor ### bi.andNot ### bi.not ### bi.shiftLeft ### bi.shiftRight ### bi.getLowestSetBit ### bi.bitCount ### bi.testBit ### bi.setBit ### bi.clearBit ### bi.flipBit ### bi.add ### bi.subtract ### bi.multiply ### bi.divide ### bi.remainder ### bi.divideAndRemainder ### bi.modPow ### bi.modInverse ### bi.pow ### bi.gcd ### bi.isProbablePrime
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsbn/README.md
README.md
(function(){ // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); 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; } var inBrowser = typeof navigator !== "undefined"; if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(inBrowser && j_lm && (navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 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+this.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(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.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(k == 8 && (s[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); } // (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); } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; 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; // 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; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); // Copyright (c) 2005-2009 Tom Wu // 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,c) { if("number" == typeof b) { // new BigInteger(int,int,RNG) if(a < 2) this.fromInt(1); else { this.fromNumber(a,c); 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 = new Array(), t = a&7; x.length = (a>>3)+1; b.nextBytes(x); if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0; this.fromString(x,256); } } // (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; } 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.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.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; 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; // JSBN-specific extension BigInteger.prototype.square = bnSquare; // Expose the Barrett function BigInteger.prototype.Barrett = Barrett // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) // Random number generator - requires a PRNG backend, e.g. prng4.js // For best results, put code like // <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'> // in your main HTML document. var rng_state; var rng_pool; var rng_pptr; // Mix in a 32-bit integer into the pool function rng_seed_int(x) { rng_pool[rng_pptr++] ^= x & 255; rng_pool[rng_pptr++] ^= (x >> 8) & 255; rng_pool[rng_pptr++] ^= (x >> 16) & 255; rng_pool[rng_pptr++] ^= (x >> 24) & 255; if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; } // Mix in the current time (w/milliseconds) into the pool function rng_seed_time() { rng_seed_int(new Date().getTime()); } // Initialize the pool with junk if needed. if(rng_pool == null) { rng_pool = new Array(); rng_pptr = 0; var t; if(typeof window !== "undefined" && window.crypto) { if (window.crypto.getRandomValues) { // Use webcrypto if available var ua = new Uint8Array(32); window.crypto.getRandomValues(ua); for(t = 0; t < 32; ++t) rng_pool[rng_pptr++] = ua[t]; } else if(navigator.appName == "Netscape" && navigator.appVersion < "5") { // Extract entropy (256 bits) from NS4 RNG if available var z = window.crypto.random(32); for(t = 0; t < z.length; ++t) rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; } } while(rng_pptr < rng_psize) { // extract some randomness from Math.random() t = Math.floor(65536 * Math.random()); rng_pool[rng_pptr++] = t >>> 8; rng_pool[rng_pptr++] = t & 255; } rng_pptr = 0; rng_seed_time(); //rng_seed_int(window.screenX); //rng_seed_int(window.screenY); } function rng_get_byte() { if(rng_state == null) { rng_seed_time(); rng_state = prng_newstate(); rng_state.init(rng_pool); for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) rng_pool[rng_pptr] = 0; rng_pptr = 0; //rng_pool = null; } // TODO: allow reseeding after first request return rng_state.next(); } function rng_get_bytes(ba) { var i; for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); } function SecureRandom() {} SecureRandom.prototype.nextBytes = rng_get_bytes; // prng4.js - uses Arcfour as a PRNG function Arcfour() { this.i = 0; this.j = 0; this.S = new Array(); } // Initialize arcfour context from key, an array of ints, each from [0..255] function ARC4init(key) { var i, j, t; for(i = 0; i < 256; ++i) this.S[i] = i; j = 0; for(i = 0; i < 256; ++i) { j = (j + this.S[i] + key[i % key.length]) & 255; t = this.S[i]; this.S[i] = this.S[j]; this.S[j] = t; } this.i = 0; this.j = 0; } function ARC4next() { var t; this.i = (this.i + 1) & 255; this.j = (this.j + this.S[this.i]) & 255; t = this.S[this.i]; this.S[this.i] = this.S[this.j]; this.S[this.j] = t; return this.S[(t + this.S[this.i]) & 255]; } Arcfour.prototype.init = ARC4init; Arcfour.prototype.next = ARC4next; // Plug in your RNG constructor here function prng_newstate() { return new Arcfour(); } // Pool size must be a multiple of 4 and greater than 32. // An array of bytes the size of the pool will be passed to init() var rng_psize = 256; BigInteger.SecureRandom = SecureRandom; BigInteger.BigInteger = BigInteger; if (typeof exports !== 'undefined') { exports = module.exports = BigInteger; } else { this.BigInteger = BigInteger; this.SecureRandom = SecureRandom; } }).call(this);
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsbn/index.js
index.js
# HAR Validator [![License][license-image]][license-url] [![version][npm-image]][npm-url] [![Build Status][circle-image]][circle-url] > Extremely fast HTTP Archive ([HAR](https://github.com/ahmadnassri/har-spec/blob/master/versions/1.2.md)) validator using JSON Schema. ## Install ```bash npm install har-validator ``` ## CLI Usage Please refer to [`har-cli`](https://github.com/ahmadnassri/har-cli) for more info. ## API **Note**: as of [`v2.0.0`](https://github.com/ahmadnassri/node-har-validator/releases/tag/v2.0.0) this module defaults to Promise based API. _For backward compatibility with `v1.x` an [async/callback API](docs/async.md) is also provided_ - [async API](docs/async.md) - [callback API](docs/async.md) - [Promise API](docs/promise.md) _(default)_ --- > Author: [Ahmad Nassri](https://www.ahmadnassri.com/) &bull; > Github: [@ahmadnassri](https://github.com/ahmadnassri) &bull; > Twitter: [@ahmadnassri](https://twitter.com/ahmadnassri) [license-url]: LICENSE [license-image]: https://img.shields.io/github/license/ahmadnassri/node-har-validator.svg?style=for-the-badge&logo=circleci [circle-url]: https://circleci.com/gh/ahmadnassri/workflows/node-har-validator [circle-image]: https://img.shields.io/circleci/project/github/ahmadnassri/node-har-validator/master.svg?style=for-the-badge&logo=circleci [npm-url]: https://www.npmjs.com/package/har-validator [npm-image]: https://img.shields.io/npm/v/har-validator.svg?style=for-the-badge&logo=npm
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/har-validator/README.md
README.md
var Ajv = require('ajv') var HARError = require('har-validator/lib/error') var schemas = require('har-schema') var ajv function createAjvInstance () { var ajv = new Ajv({ allErrors: true }) ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json')) ajv.addSchema(schemas) return ajv } function validate (name, data, next) { data = data || {} // validator config ajv = ajv || createAjvInstance() var validate = ajv.getSchema(name + '.json') var valid = validate(data) // callback? if (typeof next === 'function') { return next(!valid ? new HARError(validate.errors) : null, valid) } return valid } exports.afterRequest = function (data, next) { return validate('afterRequest', data, next) } exports.beforeRequest = function (data, next) { return validate('beforeRequest', data, next) } exports.browser = function (data, next) { return validate('browser', data, next) } exports.cache = function (data, next) { return validate('cache', data, next) } exports.content = function (data, next) { return validate('content', data, next) } exports.cookie = function (data, next) { return validate('cookie', data, next) } exports.creator = function (data, next) { return validate('creator', data, next) } exports.entry = function (data, next) { return validate('entry', data, next) } exports.har = function (data, next) { return validate('har', data, next) } exports.header = function (data, next) { return validate('header', data, next) } exports.log = function (data, next) { return validate('log', data, next) } exports.page = function (data, next) { return validate('page', data, next) } exports.pageTimings = function (data, next) { return validate('pageTimings', data, next) } exports.postData = function (data, next) { return validate('postData', data, next) } exports.query = function (data, next) { return validate('query', data, next) } exports.request = function (data, next) { return validate('request', data, next) } exports.response = function (data, next) { return validate('response', data, next) } exports.timings = function (data, next) { return validate('timings', data, next) }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/har-validator/lib/async.js
async.js
<a href="http://promisesaplus.com/"> <img src="https://promises-aplus.github.io/promises-spec/assets/logo-small.png" align="right" alt="Promises/A+ logo" /> </a> # Request-Promise-Native [![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat-square&maxAge=2592000)](https://gitter.im/request/request-promise?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://img.shields.io/travis/request/request-promise-native/master.svg?style=flat-square&maxAge=2592000)](https://travis-ci.org/request/request-promise-native) [![Coverage Status](https://img.shields.io/coveralls/request/request-promise-native.svg?style=flat-square&maxAge=2592000)](https://coveralls.io/r/request/request-promise-native) [![Dependency Status](https://img.shields.io/david/request/request-promise-native.svg?style=flat-square&maxAge=2592000)](https://david-dm.org/request/request-promise-native) [![Known Vulnerabilities](https://snyk.io/test/npm/request-promise-native/badge.svg?style=flat-square&maxAge=2592000)](https://snyk.io/test/npm/request-promise-native) # Deprecated! As of Feb 11th 2020, [`request`](https://github.com/request/request) is fully deprecated. No new changes are expected to land. In fact, none have landed for some time. This package is also deprecated because it depends on `request`. Fyi, here is the [reasoning of `request`'s deprecation](https://github.com/request/request/issues/3142) and a [list of alternative libraries](https://github.com/request/request/issues/3143). --- This package is similar to [`request-promise`](https://www.npmjs.com/package/request-promise) but uses native ES6+ promises. Please refer to the [`request-promise` documentation](https://www.npmjs.com/package/request-promise). Everything applies to `request-promise-native` except the following: - Instead of using Bluebird promises this library uses native ES6+ promises. - Native ES6+ promises may have fewer features than Bluebird promises do. In particular, the `.finally(...)` method was not included until Node v10. ## Installation This module is installed via npm: ``` npm install --save request npm install --save request-promise-native ``` `request` is defined as a peer-dependency and thus has to be installed separately. ## Migration from `request-promise` to `request-promise-native` 1. Go through the [migration instructions](https://github.com/request/request-promise#migration-from-v3-to-v4) to upgrade to `request-promise` v4. 2. Ensure that you don't use Bluebird-specific features on the promise returned by your request calls. In particular, you can't use `.finally(...)` anymore. 3. You are done. ## Contributing To set up your development environment: 1. clone the repo to your desktop, 2. in the shell `cd` to the main folder, 3. hit `npm install`, 4. hit `npm install gulp -g` if you haven't installed gulp globally yet, and 5. run `gulp dev`. (Or run `node ./node_modules/.bin/gulp dev` if you don't want to install gulp globally.) `gulp dev` watches all source files and if you save some changes it will lint the code and execute all tests. The test coverage report can be viewed from `./coverage/lcov-report/index.html`. If you want to debug a test you should use `gulp test-without-coverage` to run all tests without obscuring the code by the test coverage instrumentation. ## Change History - v1.0.9 (2020-07-21) - Security fix: bumped `request-promise-core` which bumps `lodash` to `^4.17.19` following [this advisory](https://www.npmjs.com/advisories/1523). - v1.0.8 (2019-11-03) - Security fix: bumped `request-promise-core` which bumps `lodash` to `^4.17.15`. See [vulnerabilty reports](https://snyk.io/vuln/search?q=lodash&type=npm). *(Thanks to @aw-davidson for reporting this in issue [#49](https://github.com/request/request-promise-native/issues/49).)* - v1.0.7 (2019-02-14) - Corrected mistakenly set `tough-cookie` version, now `^2.3.3` *(Thanks to @evocateur for pointing this out.)* - If you installed `[email protected]` please make sure after the upgrade that `request` and `request-promise-native` use the same physical copy of `tough-cookie`. - v1.0.6 (2019-02-14) - Using stricter `tough-cookie@~2.3.3` to avoid installing `tough-cookie@3` which introduces breaking changes *(Thanks to @jasonmit for pull request [#33](https://github.com/request/request-promise-native/pull/33/))* - Security fix: bumped `lodash` to `^4.17.11`, see [vulnerabilty reports](https://snyk.io/vuln/search?q=lodash&type=npm) - v1.0.5 (2017-09-22) - Upgraded `tough-cookie` to a version without regex DoS vulnerability *(Thanks to @sophieklm for [pull request #13](https://github.com/request/request-promise-native/pull/13))* - v1.0.4 (2017-05-07) - Fix that allows to use `tough-cookie` for [cookie creation](https://github.com/request/request-promise#include-a-cookie) - v1.0.3 (2016-08-08) - Renamed internally used package `@request/promise-core` to `request-promise-core` because there where [too](https://github.com/request/request-promise/issues/137) [many](https://github.com/request/request-promise/issues/141) issues with the scoped package name - v1.0.2 (2016-07-18) - Fix for using with module bundlers like Webpack and Browserify - v1.0.1 (2016-07-17) - Fixed `@request/promise-core` version for safer versioning - v1.0.0 (2016-07-15) - Initial version similar to [`request-promise`](https://www.npmjs.com/package/request-promise) v4 ## License (ISC) In case you never heard about the [ISC license](http://en.wikipedia.org/wiki/ISC_license) it is functionally equivalent to the MIT license. See the [LICENSE file](LICENSE) for details.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request-promise-native/README.md
README.md
[RFC6265](https://tools.ietf.org/html/rfc6265) Cookies and CookieJar for Node.js [![npm package](https://nodei.co/npm/tough-cookie.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/tough-cookie/) [![Build Status](https://travis-ci.org/salesforce/tough-cookie.png?branch=master)](https://travis-ci.org/salesforce/tough-cookie) # Synopsis ``` javascript var tough = require('tough-cookie'); var Cookie = tough.Cookie; var cookie = Cookie.parse(header); cookie.value = 'somethingdifferent'; header = cookie.toString(); var cookiejar = new tough.CookieJar(); cookiejar.setCookie(cookie, 'http://currentdomain.example.com/path', cb); // ... cookiejar.getCookies('http://example.com/otherpath',function(err,cookies) { res.headers['cookie'] = cookies.join('; '); }); ``` # Installation It's _so_ easy! `npm install tough-cookie` Why the name? NPM modules `cookie`, `cookies` and `cookiejar` were already taken. ## Version Support Support for versions of node.js will follow that of the [request](https://www.npmjs.com/package/request) module. # API ## tough Functions on the module you get from `require('tough-cookie')`. All can be used as pure functions and don't need to be "bound". **Note**: prior to 1.0.x, several of these functions took a `strict` parameter. This has since been removed from the API as it was no longer necessary. ### `parseDate(string)` Parse a cookie date string into a `Date`. Parses according to RFC6265 Section 5.1.1, not `Date.parse()`. ### `formatDate(date)` Format a Date into a RFC1123 string (the RFC6265-recommended format). ### `canonicalDomain(str)` Transforms a domain-name into a canonical domain-name. The canonical domain-name is a trimmed, lowercased, stripped-of-leading-dot and optionally punycode-encoded domain-name (Section 5.1.2 of RFC6265). For the most part, this function is idempotent (can be run again on its output without ill effects). ### `domainMatch(str,domStr[,canonicalize=true])` Answers "does this real domain match the domain in a cookie?". The `str` is the "current" domain-name and the `domStr` is the "cookie" domain-name. Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match". The `canonicalize` parameter will run the other two parameters through `canonicalDomain` or not. ### `defaultPath(path)` Given a current request/response path, gives the Path apropriate for storing in a cookie. This is basically the "directory" of a "file" in the path, but is specified by Section 5.1.4 of the RFC. The `path` parameter MUST be _only_ the pathname part of a URI (i.e. excludes the hostname, query, fragment, etc.). This is the `.pathname` property of node's `uri.parse()` output. ### `pathMatch(reqPath,cookiePath)` Answers "does the request-path path-match a given cookie-path?" as per RFC6265 Section 5.1.4. Returns a boolean. This is essentially a prefix-match where `cookiePath` is a prefix of `reqPath`. ### `parse(cookieString[, options])` alias for `Cookie.parse(cookieString[, options])` ### `fromJSON(string)` alias for `Cookie.fromJSON(string)` ### `getPublicSuffix(hostname)` Returns the public suffix of this hostname. The public suffix is the shortest domain-name upon which a cookie can be set. Returns `null` if the hostname cannot have cookies set for it. For example: `www.example.com` and `www.subdomain.example.com` both have public suffix `example.com`. For further information, see http://publicsuffix.org/. This module derives its list from that site. This call is currently a wrapper around [`psl`](https://www.npmjs.com/package/psl)'s [get() method](https://www.npmjs.com/package/psl#pslgetdomain). ### `cookieCompare(a,b)` For use with `.sort()`, sorts a list of cookies into the recommended order given in the RFC (Section 5.4 step 2). The sort algorithm is, in order of precedence: * Longest `.path` * oldest `.creation` (which has a 1ms precision, same as `Date`) * lowest `.creationIndex` (to get beyond the 1ms precision) ``` javascript var cookies = [ /* unsorted array of Cookie objects */ ]; cookies = cookies.sort(cookieCompare); ``` **Note**: Since JavaScript's `Date` is limited to a 1ms precision, cookies within the same milisecond are entirely possible. This is especially true when using the `now` option to `.setCookie()`. The `.creationIndex` property is a per-process global counter, assigned during construction with `new Cookie()`. This preserves the spirit of the RFC sorting: older cookies go first. This works great for `MemoryCookieStore`, since `Set-Cookie` headers are parsed in order, but may not be so great for distributed systems. Sophisticated `Store`s may wish to set this to some other _logical clock_ such that if cookies A and B are created in the same millisecond, but cookie A is created before cookie B, then `A.creationIndex < B.creationIndex`. If you want to alter the global counter, which you probably _shouldn't_ do, it's stored in `Cookie.cookiesCreated`. ### `permuteDomain(domain)` Generates a list of all possible domains that `domainMatch()` the parameter. May be handy for implementing cookie stores. ### `permutePath(path)` Generates a list of all possible paths that `pathMatch()` the parameter. May be handy for implementing cookie stores. ## Cookie Exported via `tough.Cookie`. ### `Cookie.parse(cookieString[, options])` Parses a single Cookie or Set-Cookie HTTP header into a `Cookie` object. Returns `undefined` if the string can't be parsed. The options parameter is not required and currently has only one property: * _loose_ - boolean - if `true` enable parsing of key-less cookies like `=abc` and `=`, which are not RFC-compliant. If options is not an object, it is ignored, which means you can use `Array#map` with it. Here's how to process the Set-Cookie header(s) on a node HTTP/HTTPS response: ``` javascript if (res.headers['set-cookie'] instanceof Array) cookies = res.headers['set-cookie'].map(Cookie.parse); else cookies = [Cookie.parse(res.headers['set-cookie'])]; ``` _Note:_ in version 2.3.3, tough-cookie limited the number of spaces before the `=` to 256 characters. This limitation has since been removed. See [Issue 92](https://github.com/salesforce/tough-cookie/issues/92) ### Properties Cookie object properties: * _key_ - string - the name or key of the cookie (default "") * _value_ - string - the value of the cookie (default "") * _expires_ - `Date` - if set, the `Expires=` attribute of the cookie (defaults to the string `"Infinity"`). See `setExpires()` * _maxAge_ - seconds - if set, the `Max-Age=` attribute _in seconds_ of the cookie. May also be set to strings `"Infinity"` and `"-Infinity"` for non-expiry and immediate-expiry, respectively. See `setMaxAge()` * _domain_ - string - the `Domain=` attribute of the cookie * _path_ - string - the `Path=` of the cookie * _secure_ - boolean - the `Secure` cookie flag * _httpOnly_ - boolean - the `HttpOnly` cookie flag * _extensions_ - `Array` - any unrecognized cookie attributes as strings (even if equal-signs inside) * _creation_ - `Date` - when this cookie was constructed * _creationIndex_ - number - set at construction, used to provide greater sort precision (please see `cookieCompare(a,b)` for a full explanation) After a cookie has been passed through `CookieJar.setCookie()` it will have the following additional attributes: * _hostOnly_ - boolean - is this a host-only cookie (i.e. no Domain field was set, but was instead implied) * _pathIsDefault_ - boolean - if true, there was no Path field on the cookie and `defaultPath()` was used to derive one. * _creation_ - `Date` - **modified** from construction to when the cookie was added to the jar * _lastAccessed_ - `Date` - last time the cookie got accessed. Will affect cookie cleaning once implemented. Using `cookiejar.getCookies(...)` will update this attribute. ### `Cookie([{properties}])` Receives an options object that can contain any of the above Cookie properties, uses the default for unspecified properties. ### `.toString()` encode to a Set-Cookie header value. The Expires cookie field is set using `formatDate()`, but is omitted entirely if `.expires` is `Infinity`. ### `.cookieString()` encode to a Cookie header value (i.e. the `.key` and `.value` properties joined with '='). ### `.setExpires(String)` sets the expiry based on a date-string passed through `parseDate()`. If parseDate returns `null` (i.e. can't parse this date string), `.expires` is set to `"Infinity"` (a string) is set. ### `.setMaxAge(number)` sets the maxAge in seconds. Coerces `-Infinity` to `"-Infinity"` and `Infinity` to `"Infinity"` so it JSON serializes correctly. ### `.expiryTime([now=Date.now()])` ### `.expiryDate([now=Date.now()])` expiryTime() Computes the absolute unix-epoch milliseconds that this cookie expires. expiryDate() works similarly, except it returns a `Date` object. Note that in both cases the `now` parameter should be milliseconds. Max-Age takes precedence over Expires (as per the RFC). The `.creation` attribute -- or, by default, the `now` parameter -- is used to offset the `.maxAge` attribute. If Expires (`.expires`) is set, that's returned. Otherwise, `expiryTime()` returns `Infinity` and `expiryDate()` returns a `Date` object for "Tue, 19 Jan 2038 03:14:07 GMT" (latest date that can be expressed by a 32-bit `time_t`; the common limit for most user-agents). ### `.TTL([now=Date.now()])` compute the TTL relative to `now` (milliseconds). The same precedence rules as for `expiryTime`/`expiryDate` apply. The "number" `Infinity` is returned for cookies without an explicit expiry and `0` is returned if the cookie is expired. Otherwise a time-to-live in milliseconds is returned. ### `.canonicalizedDomain()` ### `.cdomain()` return the canonicalized `.domain` field. This is lower-cased and punycode (RFC3490) encoded if the domain has any non-ASCII characters. ### `.toJSON()` For convenience in using `JSON.serialize(cookie)`. Returns a plain-old `Object` that can be JSON-serialized. Any `Date` properties (i.e., `.expires`, `.creation`, and `.lastAccessed`) are exported in ISO format (`.toISOString()`). **NOTE**: Custom `Cookie` properties will be discarded. In tough-cookie 1.x, since there was no `.toJSON` method explicitly defined, all enumerable properties were captured. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array. ### `Cookie.fromJSON(strOrObj)` Does the reverse of `cookie.toJSON()`. If passed a string, will `JSON.parse()` that first. Any `Date` properties (i.e., `.expires`, `.creation`, and `.lastAccessed`) are parsed via `Date.parse()`, not the tough-cookie `parseDate`, since it's JavaScript/JSON-y timestamps being handled at this layer. Returns `null` upon JSON parsing error. ### `.clone()` Does a deep clone of this cookie, exactly implemented as `Cookie.fromJSON(cookie.toJSON())`. ### `.validate()` Status: *IN PROGRESS*. Works for a few things, but is by no means comprehensive. validates cookie attributes for semantic correctness. Useful for "lint" checking any Set-Cookie headers you generate. For now, it returns a boolean, but eventually could return a reason string -- you can future-proof with this construct: ``` javascript if (cookie.validate() === true) { // it's tasty } else { // yuck! } ``` ## CookieJar Exported via `tough.CookieJar`. ### `CookieJar([store],[options])` Simply use `new CookieJar()`. If you'd like to use a custom store, pass that to the constructor otherwise a `MemoryCookieStore` will be created and used. The `options` object can be omitted and can have the following properties: * _rejectPublicSuffixes_ - boolean - default `true` - reject cookies with domains like "com" and "co.uk" * _looseMode_ - boolean - default `false` - accept malformed cookies like `bar` and `=bar`, which have an implied empty name. This is not in the standard, but is used sometimes on the web and is accepted by (most) browsers. Since eventually this module would like to support database/remote/etc. CookieJars, continuation passing style is used for CookieJar methods. ### `.setCookie(cookieOrString, currentUrl, [{options},] cb(err,cookie))` Attempt to set the cookie in the cookie jar. If the operation fails, an error will be given to the callback `cb`, otherwise the cookie is passed through. The cookie will have updated `.creation`, `.lastAccessed` and `.hostOnly` properties. The `options` object can be omitted and can have the following properties: * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies * _ignoreError_ - boolean - default `false` - silently ignore things like parse errors and invalid domains. `Store` errors aren't ignored by this option. As per the RFC, the `.hostOnly` property is set if there was no "Domain=" parameter in the cookie string (or `.domain` was null on the Cookie object). The `.domain` property is set to the fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an exact hostname match (not a `domainMatch` as per usual). ### `.setCookieSync(cookieOrString, currentUrl, [{options}])` Synchronous version of `setCookie`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). ### `.getCookies(currentUrl, [{options},] cb(err,cookies))` Retrieve the list of cookies that can be sent in a Cookie header for the current url. If an error is encountered, that's passed as `err` to the callback, otherwise an `Array` of `Cookie` objects is passed. The array is sorted with `cookieCompare()` unless the `{sort:false}` option is given. The `options` object can be omitted and can have the following properties: * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies * _expire_ - boolean - default `true` - perform expiry-time checking of cookies and asynchronously remove expired cookies from the store. Using `false` will return expired cookies and **not** remove them from the store (which is useful for replaying Set-Cookie headers, potentially). * _allPaths_ - boolean - default `false` - if `true`, do not scope cookies by path. The default uses RFC-compliant path scoping. **Note**: may not be supported by the underlying store (the default `MemoryCookieStore` supports it). The `.lastAccessed` property of the returned cookies will have been updated. ### `.getCookiesSync(currentUrl, [{options}])` Synchronous version of `getCookies`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). ### `.getCookieString(...)` Accepts the same options as `.getCookies()` but passes a string suitable for a Cookie header rather than an array to the callback. Simply maps the `Cookie` array via `.cookieString()`. ### `.getCookieStringSync(...)` Synchronous version of `getCookieString`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). ### `.getSetCookieStrings(...)` Returns an array of strings suitable for **Set-Cookie** headers. Accepts the same options as `.getCookies()`. Simply maps the cookie array via `.toString()`. ### `.getSetCookieStringsSync(...)` Synchronous version of `getSetCookieStrings`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). ### `.serialize(cb(err,serializedObject))` Serialize the Jar if the underlying store supports `.getAllCookies`. **NOTE**: Custom `Cookie` properties will be discarded. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array. See [Serialization Format]. ### `.serializeSync()` Sync version of .serialize ### `.toJSON()` Alias of .serializeSync() for the convenience of `JSON.stringify(cookiejar)`. ### `CookieJar.deserialize(serialized, [store], cb(err,object))` A new Jar is created and the serialized Cookies are added to the underlying store. Each `Cookie` is added via `store.putCookie` in the order in which they appear in the serialization. The `store` argument is optional, but should be an instance of `Store`. By default, a new instance of `MemoryCookieStore` is created. As a convenience, if `serialized` is a string, it is passed through `JSON.parse` first. If that throws an error, this is passed to the callback. ### `CookieJar.deserializeSync(serialized, [store])` Sync version of `.deserialize`. _Note_ that the `store` must be synchronous for this to work. ### `CookieJar.fromJSON(string)` Alias of `.deserializeSync` to provide consistency with `Cookie.fromJSON()`. ### `.clone([store,]cb(err,newJar))` Produces a deep clone of this jar. Modifications to the original won't affect the clone, and vice versa. The `store` argument is optional, but should be an instance of `Store`. By default, a new instance of `MemoryCookieStore` is created. Transferring between store types is supported so long as the source implements `.getAllCookies()` and the destination implements `.putCookie()`. ### `.cloneSync([store])` Synchronous version of `.clone`, returning a new `CookieJar` instance. The `store` argument is optional, but must be a _synchronous_ `Store` instance if specified. If not passed, a new instance of `MemoryCookieStore` is used. The _source_ and _destination_ must both be synchronous `Store`s. If one or both stores are asynchronous, use `.clone` instead. Recall that `MemoryCookieStore` supports both synchronous and asynchronous API calls. ### `.removeAllCookies(cb(err))` Removes all cookies from the jar. This is a new backwards-compatible feature of `tough-cookie` version 2.5, so not all Stores will implement it efficiently. For Stores that do not implement `removeAllCookies`, the fallback is to call `removeCookie` after `getAllCookies`. If `getAllCookies` fails or isn't implemented in the Store, that error is returned. If one or more of the `removeCookie` calls fail, only the first error is returned. ### `.removeAllCookiesSync()` Sync version of `.removeAllCookies()` ## Store Base class for CookieJar stores. Available as `tough.Store`. ## Store API The storage model for each `CookieJar` instance can be replaced with a custom implementation. The default is `MemoryCookieStore` which can be found in the `lib/memstore.js` file. The API uses continuation-passing-style to allow for asynchronous stores. Stores should inherit from the base `Store` class, which is available as `require('tough-cookie').Store`. Stores are asynchronous by default, but if `store.synchronous` is set to `true`, then the `*Sync` methods on the of the containing `CookieJar` can be used (however, the continuation-passing style All `domain` parameters will have been normalized before calling. The Cookie store must have all of the following methods. ### `store.findCookie(domain, path, key, cb(err,cookie))` Retrieve a cookie with the given domain, path and key (a.k.a. name). The RFC maintains that exactly one of these cookies should exist in a store. If the store is using versioning, this means that the latest/newest such cookie should be returned. Callback takes an error and the resulting `Cookie` object. If no cookie is found then `null` MUST be passed instead (i.e. not an error). ### `store.findCookies(domain, path, cb(err,cookies))` Locates cookies matching the given domain and path. This is most often called in the context of `cookiejar.getCookies()` above. If no cookies are found, the callback MUST be passed an empty array. The resulting list will be checked for applicability to the current request according to the RFC (domain-match, path-match, http-only-flag, secure-flag, expiry, etc.), so it's OK to use an optimistic search algorithm when implementing this method. However, the search algorithm used SHOULD try to find cookies that `domainMatch()` the domain and `pathMatch()` the path in order to limit the amount of checking that needs to be done. As of version 0.9.12, the `allPaths` option to `cookiejar.getCookies()` above will cause the path here to be `null`. If the path is `null`, path-matching MUST NOT be performed (i.e. domain-matching only). ### `store.putCookie(cookie, cb(err))` Adds a new cookie to the store. The implementation SHOULD replace any existing cookie with the same `.domain`, `.path`, and `.key` properties -- depending on the nature of the implementation, it's possible that between the call to `fetchCookie` and `putCookie` that a duplicate `putCookie` can occur. The `cookie` object MUST NOT be modified; the caller will have already updated the `.creation` and `.lastAccessed` properties. Pass an error if the cookie cannot be stored. ### `store.updateCookie(oldCookie, newCookie, cb(err))` Update an existing cookie. The implementation MUST update the `.value` for a cookie with the same `domain`, `.path` and `.key`. The implementation SHOULD check that the old value in the store is equivalent to `oldCookie` - how the conflict is resolved is up to the store. The `.lastAccessed` property will always be different between the two objects (to the precision possible via JavaScript's clock). Both `.creation` and `.creationIndex` are guaranteed to be the same. Stores MAY ignore or defer the `.lastAccessed` change at the cost of affecting how cookies are selected for automatic deletion (e.g., least-recently-used, which is up to the store to implement). Stores may wish to optimize changing the `.value` of the cookie in the store versus storing a new cookie. If the implementation doesn't define this method a stub that calls `putCookie(newCookie,cb)` will be added to the store object. The `newCookie` and `oldCookie` objects MUST NOT be modified. Pass an error if the newCookie cannot be stored. ### `store.removeCookie(domain, path, key, cb(err))` Remove a cookie from the store (see notes on `findCookie` about the uniqueness constraint). The implementation MUST NOT pass an error if the cookie doesn't exist; only pass an error due to the failure to remove an existing cookie. ### `store.removeCookies(domain, path, cb(err))` Removes matching cookies from the store. The `path` parameter is optional, and if missing means all paths in a domain should be removed. Pass an error ONLY if removing any existing cookies failed. ### `store.removeAllCookies(cb(err))` _Optional_. Removes all cookies from the store. Pass an error if one or more cookies can't be removed. **Note**: New method as of `tough-cookie` version 2.5, so not all Stores will implement this, plus some stores may choose not to implement this. ### `store.getAllCookies(cb(err, cookies))` _Optional_. Produces an `Array` of all cookies during `jar.serialize()`. The items in the array can be true `Cookie` objects or generic `Object`s with the [Serialization Format] data structure. Cookies SHOULD be returned in creation order to preserve sorting via `compareCookies()`. For reference, `MemoryCookieStore` will sort by `.creationIndex` since it uses true `Cookie` objects internally. If you don't return the cookies in creation order, they'll still be sorted by creation time, but this only has a precision of 1ms. See `compareCookies` for more detail. Pass an error if retrieval fails. **Note**: not all Stores can implement this due to technical limitations, so it is optional. ## MemoryCookieStore Inherits from `Store`. A just-in-memory CookieJar synchronous store implementation, used by default. Despite being a synchronous implementation, it's usable with both the synchronous and asynchronous forms of the `CookieJar` API. Supports serialization, `getAllCookies`, and `removeAllCookies`. ## Community Cookie Stores These are some Store implementations authored and maintained by the community. They aren't official and we don't vouch for them but you may be interested to have a look: - [`db-cookie-store`](https://github.com/JSBizon/db-cookie-store): SQL including SQLite-based databases - [`file-cookie-store`](https://github.com/JSBizon/file-cookie-store): Netscape cookie file format on disk - [`redis-cookie-store`](https://github.com/benkroeger/redis-cookie-store): Redis - [`tough-cookie-filestore`](https://github.com/mitsuru/tough-cookie-filestore): JSON on disk - [`tough-cookie-web-storage-store`](https://github.com/exponentjs/tough-cookie-web-storage-store): DOM localStorage and sessionStorage # Serialization Format **NOTE**: if you want to have custom `Cookie` properties serialized, add the property name to `Cookie.serializableProperties`. ```js { // The version of tough-cookie that serialized this jar. version: '[email protected]', // add the store type, to make humans happy: storeType: 'MemoryCookieStore', // CookieJar configuration: rejectPublicSuffixes: true, // ... future items go here // Gets filled from jar.store.getAllCookies(): cookies: [ { key: 'string', value: 'string', // ... /* other Cookie.serializableProperties go here */ } ] } ``` # Copyright and License BSD-3-Clause: ```text Copyright (c) 2015, Salesforce.com, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ```
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request-promise-native/node_modules/tough-cookie/README.md
README.md
'use strict'; var Store = require('tough-cookie/lib/store').Store; var permuteDomain = require('tough-cookie/lib/permuteDomain').permuteDomain; var pathMatch = require('tough-cookie/lib/pathMatch').pathMatch; var util = require('util'); function MemoryCookieStore() { Store.call(this); this.idx = {}; } util.inherits(MemoryCookieStore, Store); exports.MemoryCookieStore = MemoryCookieStore; MemoryCookieStore.prototype.idx = null; // Since it's just a struct in RAM, this Store is synchronous MemoryCookieStore.prototype.synchronous = true; // force a default depth: MemoryCookieStore.prototype.inspect = function() { return "{ idx: "+util.inspect(this.idx, false, 2)+' }'; }; // Use the new custom inspection symbol to add the custom inspect function if // available. if (util.inspect.custom) { MemoryCookieStore.prototype[util.inspect.custom] = MemoryCookieStore.prototype.inspect; } MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) { if (!this.idx[domain]) { return cb(null,undefined); } if (!this.idx[domain][path]) { return cb(null,undefined); } return cb(null,this.idx[domain][path][key]||null); }; MemoryCookieStore.prototype.findCookies = function(domain, path, cb) { var results = []; if (!domain) { return cb(null,[]); } var pathMatcher; if (!path) { // null means "all paths" pathMatcher = function matchAll(domainIndex) { for (var curPath in domainIndex) { var pathIndex = domainIndex[curPath]; for (var key in pathIndex) { results.push(pathIndex[key]); } } }; } else { pathMatcher = function matchRFC(domainIndex) { //NOTE: we should use path-match algorithm from S5.1.4 here //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299) Object.keys(domainIndex).forEach(function (cookiePath) { if (pathMatch(path, cookiePath)) { var pathIndex = domainIndex[cookiePath]; for (var key in pathIndex) { results.push(pathIndex[key]); } } }); }; } var domains = permuteDomain(domain) || [domain]; var idx = this.idx; domains.forEach(function(curDomain) { var domainIndex = idx[curDomain]; if (!domainIndex) { return; } pathMatcher(domainIndex); }); cb(null,results); }; MemoryCookieStore.prototype.putCookie = function(cookie, cb) { if (!this.idx[cookie.domain]) { this.idx[cookie.domain] = {}; } if (!this.idx[cookie.domain][cookie.path]) { this.idx[cookie.domain][cookie.path] = {}; } this.idx[cookie.domain][cookie.path][cookie.key] = cookie; cb(null); }; MemoryCookieStore.prototype.updateCookie = function(oldCookie, newCookie, cb) { // updateCookie() may avoid updating cookies that are identical. For example, // lastAccessed may not be important to some stores and an equality // comparison could exclude that field. this.putCookie(newCookie,cb); }; MemoryCookieStore.prototype.removeCookie = function(domain, path, key, cb) { if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) { delete this.idx[domain][path][key]; } cb(null); }; MemoryCookieStore.prototype.removeCookies = function(domain, path, cb) { if (this.idx[domain]) { if (path) { delete this.idx[domain][path]; } else { delete this.idx[domain]; } } return cb(null); }; MemoryCookieStore.prototype.removeAllCookies = function(cb) { this.idx = {}; return cb(null); } MemoryCookieStore.prototype.getAllCookies = function(cb) { var cookies = []; var idx = this.idx; var domains = Object.keys(idx); domains.forEach(function(domain) { var paths = Object.keys(idx[domain]); paths.forEach(function(path) { var keys = Object.keys(idx[domain][path]); keys.forEach(function(key) { if (key !== null) { cookies.push(idx[domain][path][key]); } }); }); }); // Sort by creationIndex so deserializing retains the creation order. // When implementing your own store, this SHOULD retain the order too cookies.sort(function(a,b) { return (a.creationIndex||0) - (b.creationIndex||0); }); cb(null, cookies); };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request-promise-native/node_modules/tough-cookie/lib/memstore.js
memstore.js
'use strict'; var net = require('net'); var urlParse = require('url').parse; var util = require('util'); var pubsuffix = require('tough-cookie/lib/pubsuffix-psl'); var Store = require('tough-cookie/lib/store').Store; var MemoryCookieStore = require('tough-cookie/lib/memstore').MemoryCookieStore; var pathMatch = require('tough-cookie/lib/pathMatch').pathMatch; var VERSION = require('tough-cookie/lib/version'); var punycode; try { punycode = require('punycode'); } catch(e) { console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization"); } // From RFC6265 S4.1.1 // note that it excludes \x3B ";" var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/; var CONTROL_CHARS = /[\x00-\x1F]/; // From Chromium // '\r', '\n' and '\0' should be treated as a terminator in // the "relaxed" mode, see: // https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60 var TERMINATORS = ['\n', '\r', '\0']; // RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' // Note ';' is \x3B var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; // date-time parsing constants (RFC6265 S5.1.1) var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; var MONTH_TO_NUM = { jan:0, feb:1, mar:2, apr:3, may:4, jun:5, jul:6, aug:7, sep:8, oct:9, nov:10, dec:11 }; var NUM_TO_MONTH = [ 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' ]; var NUM_TO_DAY = [ 'Sun','Mon','Tue','Wed','Thu','Fri','Sat' ]; var MAX_TIME = 2147483647000; // 31-bit max var MIN_TIME = 0; // 31-bit min /* * Parses a Natural number (i.e., non-negative integer) with either the * <min>*<max>DIGIT ( non-digit *OCTET ) * or * <min>*<max>DIGIT * grammar (RFC6265 S5.1.1). * * The "trailingOK" boolean controls if the grammar accepts a * "( non-digit *OCTET )" trailer. */ function parseDigits(token, minDigits, maxDigits, trailingOK) { var count = 0; while (count < token.length) { var c = token.charCodeAt(count); // "non-digit = %x00-2F / %x3A-FF" if (c <= 0x2F || c >= 0x3A) { break; } count++; } // constrain to a minimum and maximum number of digits. if (count < minDigits || count > maxDigits) { return null; } if (!trailingOK && count != token.length) { return null; } return parseInt(token.substr(0,count), 10); } function parseTime(token) { var parts = token.split(':'); var result = [0,0,0]; /* RF6256 S5.1.1: * time = hms-time ( non-digit *OCTET ) * hms-time = time-field ":" time-field ":" time-field * time-field = 1*2DIGIT */ if (parts.length !== 3) { return null; } for (var i = 0; i < 3; i++) { // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be // followed by "( non-digit *OCTET )" so therefore the last time-field can // have a trailer var trailingOK = (i == 2); var num = parseDigits(parts[i], 1, 2, trailingOK); if (num === null) { return null; } result[i] = num; } return result; } function parseMonth(token) { token = String(token).substr(0,3).toLowerCase(); var num = MONTH_TO_NUM[token]; return num >= 0 ? num : null; } /* * RFC6265 S5.1.1 date parser (see RFC for full grammar) */ function parseDate(str) { if (!str) { return; } /* RFC6265 S5.1.1: * 2. Process each date-token sequentially in the order the date-tokens * appear in the cookie-date */ var tokens = str.split(DATE_DELIM); if (!tokens) { return; } var hour = null; var minute = null; var second = null; var dayOfMonth = null; var month = null; var year = null; for (var i=0; i<tokens.length; i++) { var token = tokens[i].trim(); if (!token.length) { continue; } var result; /* 2.1. If the found-time flag is not set and the token matches the time * production, set the found-time flag and set the hour- value, * minute-value, and second-value to the numbers denoted by the digits in * the date-token, respectively. Skip the remaining sub-steps and continue * to the next date-token. */ if (second === null) { result = parseTime(token); if (result) { hour = result[0]; minute = result[1]; second = result[2]; continue; } } /* 2.2. If the found-day-of-month flag is not set and the date-token matches * the day-of-month production, set the found-day-of- month flag and set * the day-of-month-value to the number denoted by the date-token. Skip * the remaining sub-steps and continue to the next date-token. */ if (dayOfMonth === null) { // "day-of-month = 1*2DIGIT ( non-digit *OCTET )" result = parseDigits(token, 1, 2, true); if (result !== null) { dayOfMonth = result; continue; } } /* 2.3. If the found-month flag is not set and the date-token matches the * month production, set the found-month flag and set the month-value to * the month denoted by the date-token. Skip the remaining sub-steps and * continue to the next date-token. */ if (month === null) { result = parseMonth(token); if (result !== null) { month = result; continue; } } /* 2.4. If the found-year flag is not set and the date-token matches the * year production, set the found-year flag and set the year-value to the * number denoted by the date-token. Skip the remaining sub-steps and * continue to the next date-token. */ if (year === null) { // "year = 2*4DIGIT ( non-digit *OCTET )" result = parseDigits(token, 2, 4, true); if (result !== null) { year = result; /* From S5.1.1: * 3. If the year-value is greater than or equal to 70 and less * than or equal to 99, increment the year-value by 1900. * 4. If the year-value is greater than or equal to 0 and less * than or equal to 69, increment the year-value by 2000. */ if (year >= 70 && year <= 99) { year += 1900; } else if (year >= 0 && year <= 69) { year += 2000; } } } } /* RFC 6265 S5.1.1 * "5. Abort these steps and fail to parse the cookie-date if: * * at least one of the found-day-of-month, found-month, found- * year, or found-time flags is not set, * * the day-of-month-value is less than 1 or greater than 31, * * the year-value is less than 1601, * * the hour-value is greater than 23, * * the minute-value is greater than 59, or * * the second-value is greater than 59. * (Note that leap seconds cannot be represented in this syntax.)" * * So, in order as above: */ if ( dayOfMonth === null || month === null || year === null || second === null || dayOfMonth < 1 || dayOfMonth > 31 || year < 1601 || hour > 23 || minute > 59 || second > 59 ) { return; } return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second)); } function formatDate(date) { var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d; var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h; var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m; var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s; return NUM_TO_DAY[date.getUTCDay()] + ', ' + d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+ h+':'+m+':'+s+' GMT'; } // S5.1.2 Canonicalized Host Names function canonicalDomain(str) { if (str == null) { return null; } str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading . // convert to IDN if any non-ASCII characters if (punycode && /[^\u0001-\u007f]/.test(str)) { str = punycode.toASCII(str); } return str.toLowerCase(); } // S5.1.3 Domain Matching function domainMatch(str, domStr, canonicalize) { if (str == null || domStr == null) { return null; } if (canonicalize !== false) { str = canonicalDomain(str); domStr = canonicalDomain(domStr); } /* * "The domain string and the string are identical. (Note that both the * domain string and the string will have been canonicalized to lower case at * this point)" */ if (str == domStr) { return true; } /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */ /* "* The string is a host name (i.e., not an IP address)." */ if (net.isIP(str)) { return false; } /* "* The domain string is a suffix of the string" */ var idx = str.indexOf(domStr); if (idx <= 0) { return false; // it's a non-match (-1) or prefix (0) } // e.g "a.b.c".indexOf("b.c") === 2 // 5 === 3+2 if (str.length !== domStr.length + idx) { // it's not a suffix return false; } /* "* The last character of the string that is not included in the domain * string is a %x2E (".") character." */ if (str.substr(idx-1,1) !== '.') { return false; } return true; } // RFC6265 S5.1.4 Paths and Path-Match /* * "The user agent MUST use an algorithm equivalent to the following algorithm * to compute the default-path of a cookie:" * * Assumption: the path (and not query part or absolute uri) is passed in. */ function defaultPath(path) { // "2. If the uri-path is empty or if the first character of the uri-path is not // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. if (!path || path.substr(0,1) !== "/") { return "/"; } // "3. If the uri-path contains no more than one %x2F ("/") character, output // %x2F ("/") and skip the remaining step." if (path === "/") { return path; } var rightSlash = path.lastIndexOf("/"); if (rightSlash === 0) { return "/"; } // "4. Output the characters of the uri-path from the first character up to, // but not including, the right-most %x2F ("/")." return path.slice(0, rightSlash); } function trimTerminator(str) { for (var t = 0; t < TERMINATORS.length; t++) { var terminatorIdx = str.indexOf(TERMINATORS[t]); if (terminatorIdx !== -1) { str = str.substr(0,terminatorIdx); } } return str; } function parseCookiePair(cookiePair, looseMode) { cookiePair = trimTerminator(cookiePair); var firstEq = cookiePair.indexOf('='); if (looseMode) { if (firstEq === 0) { // '=' is immediately at start cookiePair = cookiePair.substr(1); firstEq = cookiePair.indexOf('='); // might still need to split on '=' } } else { // non-loose mode if (firstEq <= 0) { // no '=' or is at start return; // needs to have non-empty "cookie-name" } } var cookieName, cookieValue; if (firstEq <= 0) { cookieName = ""; cookieValue = cookiePair.trim(); } else { cookieName = cookiePair.substr(0, firstEq).trim(); cookieValue = cookiePair.substr(firstEq+1).trim(); } if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) { return; } var c = new Cookie(); c.key = cookieName; c.value = cookieValue; return c; } function parse(str, options) { if (!options || typeof options !== 'object') { options = {}; } str = str.trim(); // We use a regex to parse the "name-value-pair" part of S5.2 var firstSemi = str.indexOf(';'); // S5.2 step 1 var cookiePair = (firstSemi === -1) ? str : str.substr(0, firstSemi); var c = parseCookiePair(cookiePair, !!options.loose); if (!c) { return; } if (firstSemi === -1) { return c; } // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string // (including the %x3B (";") in question)." plus later on in the same section // "discard the first ";" and trim". var unparsed = str.slice(firstSemi + 1).trim(); // "If the unparsed-attributes string is empty, skip the rest of these // steps." if (unparsed.length === 0) { return c; } /* * S5.2 says that when looping over the items "[p]rocess the attribute-name * and attribute-value according to the requirements in the following * subsections" for every item. Plus, for many of the individual attributes * in S5.3 it says to use the "attribute-value of the last attribute in the * cookie-attribute-list". Therefore, in this implementation, we overwrite * the previous value. */ var cookie_avs = unparsed.split(';'); while (cookie_avs.length) { var av = cookie_avs.shift().trim(); if (av.length === 0) { // happens if ";;" appears continue; } var av_sep = av.indexOf('='); var av_key, av_value; if (av_sep === -1) { av_key = av; av_value = null; } else { av_key = av.substr(0,av_sep); av_value = av.substr(av_sep+1); } av_key = av_key.trim().toLowerCase(); if (av_value) { av_value = av_value.trim(); } switch(av_key) { case 'expires': // S5.2.1 if (av_value) { var exp = parseDate(av_value); // "If the attribute-value failed to parse as a cookie date, ignore the // cookie-av." if (exp) { // over and underflow not realistically a concern: V8's getTime() seems to // store something larger than a 32-bit time_t (even with 32-bit node) c.expires = exp; } } break; case 'max-age': // S5.2.2 if (av_value) { // "If the first character of the attribute-value is not a DIGIT or a "-" // character ...[or]... If the remainder of attribute-value contains a // non-DIGIT character, ignore the cookie-av." if (/^-?[0-9]+$/.test(av_value)) { var delta = parseInt(av_value, 10); // "If delta-seconds is less than or equal to zero (0), let expiry-time // be the earliest representable date and time." c.setMaxAge(delta); } } break; case 'domain': // S5.2.3 // "If the attribute-value is empty, the behavior is undefined. However, // the user agent SHOULD ignore the cookie-av entirely." if (av_value) { // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E // (".") character." var domain = av_value.trim().replace(/^\./, ''); if (domain) { // "Convert the cookie-domain to lower case." c.domain = domain.toLowerCase(); } } break; case 'path': // S5.2.4 /* * "If the attribute-value is empty or if the first character of the * attribute-value is not %x2F ("/"): * Let cookie-path be the default-path. * Otherwise: * Let cookie-path be the attribute-value." * * We'll represent the default-path as null since it depends on the * context of the parsing. */ c.path = av_value && av_value[0] === "/" ? av_value : null; break; case 'secure': // S5.2.5 /* * "If the attribute-name case-insensitively matches the string "Secure", * the user agent MUST append an attribute to the cookie-attribute-list * with an attribute-name of Secure and an empty attribute-value." */ c.secure = true; break; case 'httponly': // S5.2.6 -- effectively the same as 'secure' c.httpOnly = true; break; default: c.extensions = c.extensions || []; c.extensions.push(av); break; } } return c; } // avoid the V8 deoptimization monster! function jsonParse(str) { var obj; try { obj = JSON.parse(str); } catch (e) { return e; } return obj; } function fromJSON(str) { if (!str) { return null; } var obj; if (typeof str === 'string') { obj = jsonParse(str); if (obj instanceof Error) { return null; } } else { // assume it's an Object obj = str; } var c = new Cookie(); for (var i=0; i<Cookie.serializableProperties.length; i++) { var prop = Cookie.serializableProperties[i]; if (obj[prop] === undefined || obj[prop] === Cookie.prototype[prop]) { continue; // leave as prototype default } if (prop === 'expires' || prop === 'creation' || prop === 'lastAccessed') { if (obj[prop] === null) { c[prop] = null; } else { c[prop] = obj[prop] == "Infinity" ? "Infinity" : new Date(obj[prop]); } } else { c[prop] = obj[prop]; } } return c; } /* Section 5.4 part 2: * "* Cookies with longer paths are listed before cookies with * shorter paths. * * * Among cookies that have equal-length path fields, cookies with * earlier creation-times are listed before cookies with later * creation-times." */ function cookieCompare(a,b) { var cmp = 0; // descending for length: b CMP a var aPathLen = a.path ? a.path.length : 0; var bPathLen = b.path ? b.path.length : 0; cmp = bPathLen - aPathLen; if (cmp !== 0) { return cmp; } // ascending for time: a CMP b var aTime = a.creation ? a.creation.getTime() : MAX_TIME; var bTime = b.creation ? b.creation.getTime() : MAX_TIME; cmp = aTime - bTime; if (cmp !== 0) { return cmp; } // break ties for the same millisecond (precision of JavaScript's clock) cmp = a.creationIndex - b.creationIndex; return cmp; } // Gives the permutation of all possible pathMatch()es of a given path. The // array is in longest-to-shortest order. Handy for indexing. function permutePath(path) { if (path === '/') { return ['/']; } if (path.lastIndexOf('/') === path.length-1) { path = path.substr(0,path.length-1); } var permutations = [path]; while (path.length > 1) { var lindex = path.lastIndexOf('/'); if (lindex === 0) { break; } path = path.substr(0,lindex); permutations.push(path); } permutations.push('/'); return permutations; } function getCookieContext(url) { if (url instanceof Object) { return url; } // NOTE: decodeURI will throw on malformed URIs (see GH-32). // Therefore, we will just skip decoding for such URIs. try { url = decodeURI(url); } catch(err) { // Silently swallow error } return urlParse(url); } function Cookie(options) { options = options || {}; Object.keys(options).forEach(function(prop) { if (Cookie.prototype.hasOwnProperty(prop) && Cookie.prototype[prop] !== options[prop] && prop.substr(0,1) !== '_') { this[prop] = options[prop]; } }, this); this.creation = this.creation || new Date(); // used to break creation ties in cookieCompare(): Object.defineProperty(this, 'creationIndex', { configurable: false, enumerable: false, // important for assert.deepEqual checks writable: true, value: ++Cookie.cookiesCreated }); } Cookie.cookiesCreated = 0; // incremented each time a cookie is created Cookie.parse = parse; Cookie.fromJSON = fromJSON; Cookie.prototype.key = ""; Cookie.prototype.value = ""; // the order in which the RFC has them: Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity Cookie.prototype.maxAge = null; // takes precedence over expires for TTL Cookie.prototype.domain = null; Cookie.prototype.path = null; Cookie.prototype.secure = false; Cookie.prototype.httpOnly = false; Cookie.prototype.extensions = null; // set by the CookieJar: Cookie.prototype.hostOnly = null; // boolean when set Cookie.prototype.pathIsDefault = null; // boolean when set Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse Cookie.prototype.lastAccessed = null; // Date when set Object.defineProperty(Cookie.prototype, 'creationIndex', { configurable: true, enumerable: false, writable: true, value: 0 }); Cookie.serializableProperties = Object.keys(Cookie.prototype) .filter(function(prop) { return !( Cookie.prototype[prop] instanceof Function || prop === 'creationIndex' || prop.substr(0,1) === '_' ); }); Cookie.prototype.inspect = function inspect() { var now = Date.now(); return 'Cookie="'+this.toString() + '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') + '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') + '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') + '"'; }; // Use the new custom inspection symbol to add the custom inspect function if // available. if (util.inspect.custom) { Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect; } Cookie.prototype.toJSON = function() { var obj = {}; var props = Cookie.serializableProperties; for (var i=0; i<props.length; i++) { var prop = props[i]; if (this[prop] === Cookie.prototype[prop]) { continue; // leave as prototype default } if (prop === 'expires' || prop === 'creation' || prop === 'lastAccessed') { if (this[prop] === null) { obj[prop] = null; } else { obj[prop] = this[prop] == "Infinity" ? // intentionally not === "Infinity" : this[prop].toISOString(); } } else if (prop === 'maxAge') { if (this[prop] !== null) { // again, intentionally not === obj[prop] = (this[prop] == Infinity || this[prop] == -Infinity) ? this[prop].toString() : this[prop]; } } else { if (this[prop] !== Cookie.prototype[prop]) { obj[prop] = this[prop]; } } } return obj; }; Cookie.prototype.clone = function() { return fromJSON(this.toJSON()); }; Cookie.prototype.validate = function validate() { if (!COOKIE_OCTETS.test(this.value)) { return false; } if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires)) { return false; } if (this.maxAge != null && this.maxAge <= 0) { return false; // "Max-Age=" non-zero-digit *DIGIT } if (this.path != null && !PATH_VALUE.test(this.path)) { return false; } var cdomain = this.cdomain(); if (cdomain) { if (cdomain.match(/\.$/)) { return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this } var suffix = pubsuffix.getPublicSuffix(cdomain); if (suffix == null) { // it's a public suffix return false; } } return true; }; Cookie.prototype.setExpires = function setExpires(exp) { if (exp instanceof Date) { this.expires = exp; } else { this.expires = parseDate(exp) || "Infinity"; } }; Cookie.prototype.setMaxAge = function setMaxAge(age) { if (age === Infinity || age === -Infinity) { this.maxAge = age.toString(); // so JSON.stringify() works } else { this.maxAge = age; } }; // gives Cookie header format Cookie.prototype.cookieString = function cookieString() { var val = this.value; if (val == null) { val = ''; } if (this.key === '') { return val; } return this.key+'='+val; }; // gives Set-Cookie header format Cookie.prototype.toString = function toString() { var str = this.cookieString(); if (this.expires != Infinity) { if (this.expires instanceof Date) { str += '; Expires='+formatDate(this.expires); } else { str += '; Expires='+this.expires; } } if (this.maxAge != null && this.maxAge != Infinity) { str += '; Max-Age='+this.maxAge; } if (this.domain && !this.hostOnly) { str += '; Domain='+this.domain; } if (this.path) { str += '; Path='+this.path; } if (this.secure) { str += '; Secure'; } if (this.httpOnly) { str += '; HttpOnly'; } if (this.extensions) { this.extensions.forEach(function(ext) { str += '; '+ext; }); } return str; }; // TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie() // elsewhere) // S5.3 says to give the "latest representable date" for which we use Infinity // For "expired" we use 0 Cookie.prototype.TTL = function TTL(now) { /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires * attribute, the Max-Age attribute has precedence and controls the * expiration date of the cookie. * (Concurs with S5.3 step 3) */ if (this.maxAge != null) { return this.maxAge<=0 ? 0 : this.maxAge*1000; } var expires = this.expires; if (expires != Infinity) { if (!(expires instanceof Date)) { expires = parseDate(expires) || Infinity; } if (expires == Infinity) { return Infinity; } return expires.getTime() - (now || Date.now()); } return Infinity; }; // expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() // elsewhere) Cookie.prototype.expiryTime = function expiryTime(now) { if (this.maxAge != null) { var relativeTo = now || this.creation || new Date(); var age = (this.maxAge <= 0) ? -Infinity : this.maxAge*1000; return relativeTo.getTime() + age; } if (this.expires == Infinity) { return Infinity; } return this.expires.getTime(); }; // expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() // elsewhere), except it returns a Date Cookie.prototype.expiryDate = function expiryDate(now) { var millisec = this.expiryTime(now); if (millisec == Infinity) { return new Date(MAX_TIME); } else if (millisec == -Infinity) { return new Date(MIN_TIME); } else { return new Date(millisec); } }; // This replaces the "persistent-flag" parts of S5.3 step 3 Cookie.prototype.isPersistent = function isPersistent() { return (this.maxAge != null || this.expires != Infinity); }; // Mostly S5.1.2 and S5.2.3: Cookie.prototype.cdomain = Cookie.prototype.canonicalizedDomain = function canonicalizedDomain() { if (this.domain == null) { return null; } return canonicalDomain(this.domain); }; function CookieJar(store, options) { if (typeof options === "boolean") { options = {rejectPublicSuffixes: options}; } else if (options == null) { options = {}; } if (options.rejectPublicSuffixes != null) { this.rejectPublicSuffixes = options.rejectPublicSuffixes; } if (options.looseMode != null) { this.enableLooseMode = options.looseMode; } if (!store) { store = new MemoryCookieStore(); } this.store = store; } CookieJar.prototype.store = null; CookieJar.prototype.rejectPublicSuffixes = true; CookieJar.prototype.enableLooseMode = false; var CAN_BE_SYNC = []; CAN_BE_SYNC.push('setCookie'); CookieJar.prototype.setCookie = function(cookie, url, options, cb) { var err; var context = getCookieContext(url); if (options instanceof Function) { cb = options; options = {}; } var host = canonicalDomain(context.hostname); var loose = this.enableLooseMode; if (options.loose != null) { loose = options.loose; } // S5.3 step 1 if (!(cookie instanceof Cookie)) { cookie = Cookie.parse(cookie, { loose: loose }); } if (!cookie) { err = new Error("Cookie failed to parse"); return cb(options.ignoreError ? null : err); } // S5.3 step 2 var now = options.now || new Date(); // will assign later to save effort in the face of errors // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie() // S5.3 step 4: NOOP; domain is null by default // S5.3 step 5: public suffixes if (this.rejectPublicSuffixes && cookie.domain) { var suffix = pubsuffix.getPublicSuffix(cookie.cdomain()); if (suffix == null) { // e.g. "com" err = new Error("Cookie has domain set to a public suffix"); return cb(options.ignoreError ? null : err); } } // S5.3 step 6: if (cookie.domain) { if (!domainMatch(host, cookie.cdomain(), false)) { err = new Error("Cookie not in this host's domain. Cookie:"+cookie.cdomain()+" Request:"+host); return cb(options.ignoreError ? null : err); } if (cookie.hostOnly == null) { // don't reset if already set cookie.hostOnly = false; } } else { cookie.hostOnly = true; cookie.domain = host; } //S5.2.4 If the attribute-value is empty or if the first character of the //attribute-value is not %x2F ("/"): //Let cookie-path be the default-path. if (!cookie.path || cookie.path[0] !== '/') { cookie.path = defaultPath(context.pathname); cookie.pathIsDefault = true; } // S5.3 step 8: NOOP; secure attribute // S5.3 step 9: NOOP; httpOnly attribute // S5.3 step 10 if (options.http === false && cookie.httpOnly) { err = new Error("Cookie is HttpOnly and this isn't an HTTP API"); return cb(options.ignoreError ? null : err); } var store = this.store; if (!store.updateCookie) { store.updateCookie = function(oldCookie, newCookie, cb) { this.putCookie(newCookie, cb); }; } function withCookie(err, oldCookie) { if (err) { return cb(err); } var next = function(err) { if (err) { return cb(err); } else { cb(null, cookie); } }; if (oldCookie) { // S5.3 step 11 - "If the cookie store contains a cookie with the same name, // domain, and path as the newly created cookie:" if (options.http === false && oldCookie.httpOnly) { // step 11.2 err = new Error("old Cookie is HttpOnly and this isn't an HTTP API"); return cb(options.ignoreError ? null : err); } cookie.creation = oldCookie.creation; // step 11.3 cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker cookie.lastAccessed = now; // Step 11.4 (delete cookie) is implied by just setting the new one: store.updateCookie(oldCookie, cookie, next); // step 12 } else { cookie.creation = cookie.lastAccessed = now; store.putCookie(cookie, next); // step 12 } } store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie); }; // RFC6365 S5.4 CAN_BE_SYNC.push('getCookies'); CookieJar.prototype.getCookies = function(url, options, cb) { var context = getCookieContext(url); if (options instanceof Function) { cb = options; options = {}; } var host = canonicalDomain(context.hostname); var path = context.pathname || '/'; var secure = options.secure; if (secure == null && context.protocol && (context.protocol == 'https:' || context.protocol == 'wss:')) { secure = true; } var http = options.http; if (http == null) { http = true; } var now = options.now || Date.now(); var expireCheck = options.expire !== false; var allPaths = !!options.allPaths; var store = this.store; function matchingCookie(c) { // "Either: // The cookie's host-only-flag is true and the canonicalized // request-host is identical to the cookie's domain. // Or: // The cookie's host-only-flag is false and the canonicalized // request-host domain-matches the cookie's domain." if (c.hostOnly) { if (c.domain != host) { return false; } } else { if (!domainMatch(host, c.domain, false)) { return false; } } // "The request-uri's path path-matches the cookie's path." if (!allPaths && !pathMatch(path, c.path)) { return false; } // "If the cookie's secure-only-flag is true, then the request-uri's // scheme must denote a "secure" protocol" if (c.secure && !secure) { return false; } // "If the cookie's http-only-flag is true, then exclude the cookie if the // cookie-string is being generated for a "non-HTTP" API" if (c.httpOnly && !http) { return false; } // deferred from S5.3 // non-RFC: allow retention of expired cookies by choice if (expireCheck && c.expiryTime() <= now) { store.removeCookie(c.domain, c.path, c.key, function(){}); // result ignored return false; } return true; } store.findCookies(host, allPaths ? null : path, function(err,cookies) { if (err) { return cb(err); } cookies = cookies.filter(matchingCookie); // sorting of S5.4 part 2 if (options.sort !== false) { cookies = cookies.sort(cookieCompare); } // S5.4 part 3 var now = new Date(); cookies.forEach(function(c) { c.lastAccessed = now; }); // TODO persist lastAccessed cb(null,cookies); }); }; CAN_BE_SYNC.push('getCookieString'); CookieJar.prototype.getCookieString = function(/*..., cb*/) { var args = Array.prototype.slice.call(arguments,0); var cb = args.pop(); var next = function(err,cookies) { if (err) { cb(err); } else { cb(null, cookies .sort(cookieCompare) .map(function(c){ return c.cookieString(); }) .join('; ')); } }; args.push(next); this.getCookies.apply(this,args); }; CAN_BE_SYNC.push('getSetCookieStrings'); CookieJar.prototype.getSetCookieStrings = function(/*..., cb*/) { var args = Array.prototype.slice.call(arguments,0); var cb = args.pop(); var next = function(err,cookies) { if (err) { cb(err); } else { cb(null, cookies.map(function(c){ return c.toString(); })); } }; args.push(next); this.getCookies.apply(this,args); }; CAN_BE_SYNC.push('serialize'); CookieJar.prototype.serialize = function(cb) { var type = this.store.constructor.name; if (type === 'Object') { type = null; } // update README.md "Serialization Format" if you change this, please! var serialized = { // The version of tough-cookie that serialized this jar. Generally a good // practice since future versions can make data import decisions based on // known past behavior. When/if this matters, use `semver`. version: 'tough-cookie@'+VERSION, // add the store type, to make humans happy: storeType: type, // CookieJar configuration: rejectPublicSuffixes: !!this.rejectPublicSuffixes, // this gets filled from getAllCookies: cookies: [] }; if (!(this.store.getAllCookies && typeof this.store.getAllCookies === 'function')) { return cb(new Error('store does not support getAllCookies and cannot be serialized')); } this.store.getAllCookies(function(err,cookies) { if (err) { return cb(err); } serialized.cookies = cookies.map(function(cookie) { // convert to serialized 'raw' cookies cookie = (cookie instanceof Cookie) ? cookie.toJSON() : cookie; // Remove the index so new ones get assigned during deserialization delete cookie.creationIndex; return cookie; }); return cb(null, serialized); }); }; // well-known name that JSON.stringify calls CookieJar.prototype.toJSON = function() { return this.serializeSync(); }; // use the class method CookieJar.deserialize instead of calling this directly CAN_BE_SYNC.push('_importCookies'); CookieJar.prototype._importCookies = function(serialized, cb) { var jar = this; var cookies = serialized.cookies; if (!cookies || !Array.isArray(cookies)) { return cb(new Error('serialized jar has no cookies array')); } cookies = cookies.slice(); // do not modify the original function putNext(err) { if (err) { return cb(err); } if (!cookies.length) { return cb(err, jar); } var cookie; try { cookie = fromJSON(cookies.shift()); } catch (e) { return cb(e); } if (cookie === null) { return putNext(null); // skip this cookie } jar.store.putCookie(cookie, putNext); } putNext(); }; CookieJar.deserialize = function(strOrObj, store, cb) { if (arguments.length !== 3) { // store is optional cb = store; store = null; } var serialized; if (typeof strOrObj === 'string') { serialized = jsonParse(strOrObj); if (serialized instanceof Error) { return cb(serialized); } } else { serialized = strOrObj; } var jar = new CookieJar(store, serialized.rejectPublicSuffixes); jar._importCookies(serialized, function(err) { if (err) { return cb(err); } cb(null, jar); }); }; CookieJar.deserializeSync = function(strOrObj, store) { var serialized = typeof strOrObj === 'string' ? JSON.parse(strOrObj) : strOrObj; var jar = new CookieJar(store, serialized.rejectPublicSuffixes); // catch this mistake early: if (!jar.store.synchronous) { throw new Error('CookieJar store is not synchronous; use async API instead.'); } jar._importCookiesSync(serialized); return jar; }; CookieJar.fromJSON = CookieJar.deserializeSync; CookieJar.prototype.clone = function(newStore, cb) { if (arguments.length === 1) { cb = newStore; newStore = null; } this.serialize(function(err,serialized) { if (err) { return cb(err); } CookieJar.deserialize(serialized, newStore, cb); }); }; CAN_BE_SYNC.push('removeAllCookies'); CookieJar.prototype.removeAllCookies = function(cb) { var store = this.store; // Check that the store implements its own removeAllCookies(). The default // implementation in Store will immediately call the callback with a "not // implemented" Error. if (store.removeAllCookies instanceof Function && store.removeAllCookies !== Store.prototype.removeAllCookies) { return store.removeAllCookies(cb); } store.getAllCookies(function(err, cookies) { if (err) { return cb(err); } if (cookies.length === 0) { return cb(null); } var completedCount = 0; var removeErrors = []; function removeCookieCb(removeErr) { if (removeErr) { removeErrors.push(removeErr); } completedCount++; if (completedCount === cookies.length) { return cb(removeErrors.length ? removeErrors[0] : null); } } cookies.forEach(function(cookie) { store.removeCookie(cookie.domain, cookie.path, cookie.key, removeCookieCb); }); }); }; CookieJar.prototype._cloneSync = syncWrap('clone'); CookieJar.prototype.cloneSync = function(newStore) { if (!newStore.synchronous) { throw new Error('CookieJar clone destination store is not synchronous; use async API instead.'); } return this._cloneSync(newStore); }; // Use a closure to provide a true imperative API for synchronous stores. function syncWrap(method) { return function() { if (!this.store.synchronous) { throw new Error('CookieJar store is not synchronous; use async API instead.'); } var args = Array.prototype.slice.call(arguments); var syncErr, syncResult; args.push(function syncCb(err, result) { syncErr = err; syncResult = result; }); this[method].apply(this, args); if (syncErr) { throw syncErr; } return syncResult; }; } // wrap all declared CAN_BE_SYNC methods in the sync wrapper CAN_BE_SYNC.forEach(function(method) { CookieJar.prototype[method+'Sync'] = syncWrap(method); }); exports.version = VERSION; exports.CookieJar = CookieJar; exports.Cookie = Cookie; exports.Store = Store; exports.MemoryCookieStore = MemoryCookieStore; exports.parseDate = parseDate; exports.formatDate = formatDate; exports.parse = parse; exports.fromJSON = fromJSON; exports.domainMatch = domainMatch; exports.defaultPath = defaultPath; exports.pathMatch = pathMatch; exports.getPublicSuffix = pubsuffix.getPublicSuffix; exports.cookieCompare = cookieCompare; exports.permuteDomain = require('tough-cookie/lib/permuteDomain').permuteDomain; exports.permutePath = permutePath; exports.canonicalDomain = canonicalDomain;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request-promise-native/node_modules/tough-cookie/lib/cookie.js
cookie.js
# Important! If your contribution is not trivial (not a typo fix, etc.), we can only accept it if you dedicate your copyright for the contribution to the public domain. Make sure you understand what it means (see http://unlicense.org/)! If you agree, please add yourself to AUTHORS.md file, and include the following text to your pull request description or a comment in it: ------------------------------------------------------------------------------ I dedicate any and all copyright interest in this software to the public domain. I make this dedication for the benefit of the public at large and to the detriment of my heirs and successors. I intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md
PULL_REQUEST_TEMPLATE.md
!function(r){"use strict";function n(r,n){return r<<n|r>>>32-n}function e(r,n){var e=255&r[n+3];return e=e<<8|255&r[n+2],e=e<<8|255&r[n+1],e<<8|255&r[n+0]}function t(r,n){var e=r[n]<<24|r[n+1]<<16|r[n+2]<<8|r[n+3],t=r[n+4]<<24|r[n+5]<<16|r[n+6]<<8|r[n+7];return new sr(e,t)}function o(r,n,e){var t;for(t=0;t<4;t++)r[n+t]=255&e,e>>>=8}function i(r,n,e){r[n]=e.hi>>24&255,r[n+1]=e.hi>>16&255,r[n+2]=e.hi>>8&255,r[n+3]=255&e.hi,r[n+4]=e.lo>>24&255,r[n+5]=e.lo>>16&255,r[n+6]=e.lo>>8&255,r[n+7]=255&e.lo}function a(r,n,e,t,o){var i,a=0;for(i=0;i<o;i++)a|=r[n+i]^e[t+i];return(1&a-1>>>8)-1}function f(r,n,e,t){return a(r,n,e,t,16)}function u(r,n,e,t){return a(r,n,e,t,32)}function c(r,t,i,a,f){var u,c,w,y=new Uint32Array(16),l=new Uint32Array(16),s=new Uint32Array(16),h=new Uint32Array(4);for(u=0;u<4;u++)l[5*u]=e(a,4*u),l[1+u]=e(i,4*u),l[6+u]=e(t,4*u),l[11+u]=e(i,16+4*u);for(u=0;u<16;u++)s[u]=l[u];for(u=0;u<20;u++){for(c=0;c<4;c++){for(w=0;w<4;w++)h[w]=l[(5*c+4*w)%16];for(h[1]^=n(h[0]+h[3]|0,7),h[2]^=n(h[1]+h[0]|0,9),h[3]^=n(h[2]+h[1]|0,13),h[0]^=n(h[3]+h[2]|0,18),w=0;w<4;w++)y[4*c+(c+w)%4]=h[w]}for(w=0;w<16;w++)l[w]=y[w]}if(f){for(u=0;u<16;u++)l[u]=l[u]+s[u]|0;for(u=0;u<4;u++)l[5*u]=l[5*u]-e(a,4*u)|0,l[6+u]=l[6+u]-e(t,4*u)|0;for(u=0;u<4;u++)o(r,4*u,l[5*u]),o(r,16+4*u,l[6+u])}else for(u=0;u<16;u++)o(r,4*u,l[u]+s[u]|0)}function w(r,n,e,t){return c(r,n,e,t,!1),0}function y(r,n,e,t){return c(r,n,e,t,!0),0}function l(r,n,e,t,o,i,a){var f,u,c=new Uint8Array(16),y=new Uint8Array(64);if(!o)return 0;for(u=0;u<16;u++)c[u]=0;for(u=0;u<8;u++)c[u]=i[u];for(;o>=64;){for(w(y,c,a,Br),u=0;u<64;u++)r[n+u]=(e?e[t+u]:0)^y[u];for(f=1,u=8;u<16;u++)f=f+(255&c[u])|0,c[u]=255&f,f>>>=8;o-=64,n+=64,e&&(t+=64)}if(o>0)for(w(y,c,a,Br),u=0;u<o;u++)r[n+u]=(e?e[t+u]:0)^y[u];return 0}function s(r,n,e,t,o){return l(r,n,null,0,e,t,o)}function h(r,n,e,t,o){var i=new Uint8Array(32);return y(i,t,o,Br),s(r,n,e,t.subarray(16),i)}function g(r,n,e,t,o,i,a){var f=new Uint8Array(32);return y(f,i,a,Br),l(r,n,e,t,o,i.subarray(16),f)}function v(r,n){var e,t=0;for(e=0;e<17;e++)t=t+(r[e]+n[e]|0)|0,r[e]=255&t,t>>>=8}function b(r,n,e,t,o,i){var a,f,u,c,w=new Uint32Array(17),y=new Uint32Array(17),l=new Uint32Array(17),s=new Uint32Array(17),h=new Uint32Array(17);for(u=0;u<17;u++)y[u]=l[u]=0;for(u=0;u<16;u++)y[u]=i[u];for(y[3]&=15,y[4]&=252,y[7]&=15,y[8]&=252,y[11]&=15,y[12]&=252,y[15]&=15;o>0;){for(u=0;u<17;u++)s[u]=0;for(u=0;u<16&&u<o;++u)s[u]=e[t+u];for(s[u]=1,t+=u,o-=u,v(l,s),f=0;f<17;f++)for(w[f]=0,u=0;u<17;u++)w[f]=w[f]+l[u]*(u<=f?y[f-u]:320*y[f+17-u]|0)|0|0;for(f=0;f<17;f++)l[f]=w[f];for(c=0,u=0;u<16;u++)c=c+l[u]|0,l[u]=255&c,c>>>=8;for(c=c+l[16]|0,l[16]=3&c,c=5*(c>>>2)|0,u=0;u<16;u++)c=c+l[u]|0,l[u]=255&c,c>>>=8;c=c+l[16]|0,l[16]=c}for(u=0;u<17;u++)h[u]=l[u];for(v(l,Sr),a=0|-(l[16]>>>7),u=0;u<17;u++)l[u]^=a&(h[u]^l[u]);for(u=0;u<16;u++)s[u]=i[u+16];for(s[16]=0,v(l,s),u=0;u<16;u++)r[n+u]=l[u];return 0}function p(r,n,e,t,o,i){var a=new Uint8Array(16);return b(a,0,e,t,o,i),f(r,n,a,0)}function _(r,n,e,t,o){var i;if(e<32)return-1;for(g(r,0,n,0,e,t,o),b(r,16,r,32,e-32,r),i=0;i<16;i++)r[i]=0;return 0}function A(r,n,e,t,o){var i,a=new Uint8Array(32);if(e<32)return-1;if(h(a,0,32,t,o),0!==p(n,16,n,32,e-32,a))return-1;for(g(r,0,n,0,e,t,o),i=0;i<32;i++)r[i]=0;return 0}function U(r,n){var e;for(e=0;e<16;e++)r[e]=0|n[e]}function E(r){var n,e;for(e=0;e<16;e++)r[e]+=65536,n=Math.floor(r[e]/65536),r[(e+1)*(e<15?1:0)]+=n-1+37*(n-1)*(15===e?1:0),r[e]-=65536*n}function d(r,n,e){for(var t,o=~(e-1),i=0;i<16;i++)t=o&(r[i]^n[i]),r[i]^=t,n[i]^=t}function x(r,n){var e,t,o,i=hr(),a=hr();for(e=0;e<16;e++)a[e]=n[e];for(E(a),E(a),E(a),t=0;t<2;t++){for(i[0]=a[0]-65517,e=1;e<15;e++)i[e]=a[e]-65535-(i[e-1]>>16&1),i[e-1]&=65535;i[15]=a[15]-32767-(i[14]>>16&1),o=i[15]>>16&1,i[14]&=65535,d(a,i,1-o)}for(e=0;e<16;e++)r[2*e]=255&a[e],r[2*e+1]=a[e]>>8}function m(r,n){var e=new Uint8Array(32),t=new Uint8Array(32);return x(e,r),x(t,n),u(e,0,t,0)}function B(r){var n=new Uint8Array(32);return x(n,r),1&n[0]}function S(r,n){var e;for(e=0;e<16;e++)r[e]=n[2*e]+(n[2*e+1]<<8);r[15]&=32767}function K(r,n,e){var t;for(t=0;t<16;t++)r[t]=n[t]+e[t]|0}function T(r,n,e){var t;for(t=0;t<16;t++)r[t]=n[t]-e[t]|0}function Y(r,n,e){var t,o,i=new Float64Array(31);for(t=0;t<31;t++)i[t]=0;for(t=0;t<16;t++)for(o=0;o<16;o++)i[t+o]+=n[t]*e[o];for(t=0;t<15;t++)i[t]+=38*i[t+16];for(t=0;t<16;t++)r[t]=i[t];E(r),E(r)}function L(r,n){Y(r,n,n)}function k(r,n){var e,t=hr();for(e=0;e<16;e++)t[e]=n[e];for(e=253;e>=0;e--)L(t,t),2!==e&&4!==e&&Y(t,t,n);for(e=0;e<16;e++)r[e]=t[e]}function z(r,n){var e,t=hr();for(e=0;e<16;e++)t[e]=n[e];for(e=250;e>=0;e--)L(t,t),1!==e&&Y(t,t,n);for(e=0;e<16;e++)r[e]=t[e]}function R(r,n,e){var t,o,i=new Uint8Array(32),a=new Float64Array(80),f=hr(),u=hr(),c=hr(),w=hr(),y=hr(),l=hr();for(o=0;o<31;o++)i[o]=n[o];for(i[31]=127&n[31]|64,i[0]&=248,S(a,e),o=0;o<16;o++)u[o]=a[o],w[o]=f[o]=c[o]=0;for(f[0]=w[0]=1,o=254;o>=0;--o)t=i[o>>>3]>>>(7&o)&1,d(f,u,t),d(c,w,t),K(y,f,c),T(f,f,c),K(c,u,w),T(u,u,w),L(w,y),L(l,f),Y(f,c,f),Y(c,u,y),K(y,f,c),T(f,f,c),L(u,f),T(c,w,l),Y(f,c,Ar),K(f,f,w),Y(c,c,f),Y(f,w,l),Y(w,u,a),L(u,y),d(f,u,t),d(c,w,t);for(o=0;o<16;o++)a[o+16]=f[o],a[o+32]=c[o],a[o+48]=u[o],a[o+64]=w[o];var s=a.subarray(32),h=a.subarray(16);return k(s,s),Y(h,h,s),x(r,h),0}function P(r,n){return R(r,n,br)}function O(r,n){return gr(n,32),P(r,n)}function F(r,n,e){var t=new Uint8Array(32);return R(t,e,n),y(r,vr,t,Br)}function N(r,n,e,t,o,i){var a=new Uint8Array(32);return F(a,o,i),Kr(r,n,e,t,a)}function C(r,n,e,t,o,i){var a=new Uint8Array(32);return F(a,o,i),Tr(r,n,e,t,a)}function M(){var r,n,e,t=0,o=0,i=0,a=0,f=65535;for(e=0;e<arguments.length;e++)r=arguments[e].lo,n=arguments[e].hi,t+=r&f,o+=r>>>16,i+=n&f,a+=n>>>16;return o+=t>>>16,i+=o>>>16,a+=i>>>16,new sr(i&f|a<<16,t&f|o<<16)}function G(r,n){return new sr(r.hi>>>n,r.lo>>>n|r.hi<<32-n)}function Z(){var r,n=0,e=0;for(r=0;r<arguments.length;r++)n^=arguments[r].lo,e^=arguments[r].hi;return new sr(e,n)}function j(r,n){var e,t,o=32-n;return n<32?(e=r.hi>>>n|r.lo<<o,t=r.lo>>>n|r.hi<<o):n<64&&(e=r.lo>>>n|r.hi<<o,t=r.hi>>>n|r.lo<<o),new sr(e,t)}function q(r,n,e){var t=r.hi&n.hi^~r.hi&e.hi,o=r.lo&n.lo^~r.lo&e.lo;return new sr(t,o)}function I(r,n,e){var t=r.hi&n.hi^r.hi&e.hi^n.hi&e.hi,o=r.lo&n.lo^r.lo&e.lo^n.lo&e.lo;return new sr(t,o)}function V(r){return Z(j(r,28),j(r,34),j(r,39))}function X(r){return Z(j(r,14),j(r,18),j(r,41))}function D(r){return Z(j(r,1),j(r,8),G(r,7))}function H(r){return Z(j(r,19),j(r,61),G(r,6))}function J(r,n,e){var o,a,f,u=[],c=[],w=[],y=[];for(a=0;a<8;a++)u[a]=w[a]=t(r,8*a);for(var l=0;e>=128;){for(a=0;a<16;a++)y[a]=t(n,8*a+l);for(a=0;a<80;a++){for(f=0;f<8;f++)c[f]=w[f];for(o=M(w[7],X(w[4]),q(w[4],w[5],w[6]),Yr[a],y[a%16]),c[7]=M(o,V(w[0]),I(w[0],w[1],w[2])),c[3]=M(c[3],o),f=0;f<8;f++)w[(f+1)%8]=c[f];if(a%16===15)for(f=0;f<16;f++)y[f]=M(y[f],y[(f+9)%16],D(y[(f+1)%16]),H(y[(f+14)%16]))}for(a=0;a<8;a++)w[a]=M(w[a],u[a]),u[a]=w[a];l+=128,e-=128}for(a=0;a<8;a++)i(r,8*a,u[a]);return e}function Q(r,n,e){var t,o=new Uint8Array(64),a=new Uint8Array(256),f=e;for(t=0;t<64;t++)o[t]=Lr[t];for(J(o,n,e),e%=128,t=0;t<256;t++)a[t]=0;for(t=0;t<e;t++)a[t]=n[f-e+t];for(a[e]=128,e=256-128*(e<112?1:0),a[e-9]=0,i(a,e-8,new sr(f/536870912|0,f<<3)),J(o,a,e),t=0;t<64;t++)r[t]=o[t];return 0}function W(r,n){var e=hr(),t=hr(),o=hr(),i=hr(),a=hr(),f=hr(),u=hr(),c=hr(),w=hr();T(e,r[1],r[0]),T(w,n[1],n[0]),Y(e,e,w),K(t,r[0],r[1]),K(w,n[0],n[1]),Y(t,t,w),Y(o,r[3],n[3]),Y(o,o,Er),Y(i,r[2],n[2]),K(i,i,i),T(a,t,e),T(f,i,o),K(u,i,o),K(c,t,e),Y(r[0],a,f),Y(r[1],c,u),Y(r[2],u,f),Y(r[3],a,c)}function $(r,n,e){var t;for(t=0;t<4;t++)d(r[t],n[t],e)}function rr(r,n){var e=hr(),t=hr(),o=hr();k(o,n[2]),Y(e,n[0],o),Y(t,n[1],o),x(r,t),r[31]^=B(e)<<7}function nr(r,n,e){var t,o;for(U(r[0],pr),U(r[1],_r),U(r[2],_r),U(r[3],pr),o=255;o>=0;--o)t=e[o/8|0]>>(7&o)&1,$(r,n,t),W(n,r),W(r,r),$(r,n,t)}function er(r,n){var e=[hr(),hr(),hr(),hr()];U(e[0],dr),U(e[1],xr),U(e[2],_r),Y(e[3],dr,xr),nr(r,e,n)}function tr(r,n,e){var t,o=new Uint8Array(64),i=[hr(),hr(),hr(),hr()];for(e||gr(n,32),Q(o,n,32),o[0]&=248,o[31]&=127,o[31]|=64,er(i,o),rr(r,i),t=0;t<32;t++)n[t+32]=r[t];return 0}function or(r,n){var e,t,o,i;for(t=63;t>=32;--t){for(e=0,o=t-32,i=t-12;o<i;++o)n[o]+=e-16*n[t]*kr[o-(t-32)],e=n[o]+128>>8,n[o]-=256*e;n[o]+=e,n[t]=0}for(e=0,o=0;o<32;o++)n[o]+=e-(n[31]>>4)*kr[o],e=n[o]>>8,n[o]&=255;for(o=0;o<32;o++)n[o]-=e*kr[o];for(t=0;t<32;t++)n[t+1]+=n[t]>>8,r[t]=255&n[t]}function ir(r){var n,e=new Float64Array(64);for(n=0;n<64;n++)e[n]=r[n];for(n=0;n<64;n++)r[n]=0;or(r,e)}function ar(r,n,e,t){var o,i,a=new Uint8Array(64),f=new Uint8Array(64),u=new Uint8Array(64),c=new Float64Array(64),w=[hr(),hr(),hr(),hr()];Q(a,t,32),a[0]&=248,a[31]&=127,a[31]|=64;var y=e+64;for(o=0;o<e;o++)r[64+o]=n[o];for(o=0;o<32;o++)r[32+o]=a[32+o];for(Q(u,r.subarray(32),e+32),ir(u),er(w,u),rr(r,w),o=32;o<64;o++)r[o]=t[o];for(Q(f,r,e+64),ir(f),o=0;o<64;o++)c[o]=0;for(o=0;o<32;o++)c[o]=u[o];for(o=0;o<32;o++)for(i=0;i<32;i++)c[o+i]+=f[o]*a[i];return or(r.subarray(32),c),y}function fr(r,n){var e=hr(),t=hr(),o=hr(),i=hr(),a=hr(),f=hr(),u=hr();return U(r[2],_r),S(r[1],n),L(o,r[1]),Y(i,o,Ur),T(o,o,r[2]),K(i,r[2],i),L(a,i),L(f,a),Y(u,f,a),Y(e,u,o),Y(e,e,i),z(e,e),Y(e,e,o),Y(e,e,i),Y(e,e,i),Y(r[0],e,i),L(t,r[0]),Y(t,t,i),m(t,o)&&Y(r[0],r[0],mr),L(t,r[0]),Y(t,t,i),m(t,o)?-1:(B(r[0])===n[31]>>7&&T(r[0],pr,r[0]),Y(r[3],r[0],r[1]),0)}function ur(r,n,e,t){var o,i,a=new Uint8Array(32),f=new Uint8Array(64),c=[hr(),hr(),hr(),hr()],w=[hr(),hr(),hr(),hr()];if(i=-1,e<64)return-1;if(fr(w,t))return-1;for(o=0;o<e;o++)r[o]=n[o];for(o=0;o<32;o++)r[o+32]=t[o];if(Q(f,r,e),ir(f),nr(c,w,f),er(w,n.subarray(32)),W(c,w),rr(a,c),e-=64,u(n,0,a,0)){for(o=0;o<e;o++)r[o]=0;return-1}for(o=0;o<e;o++)r[o]=n[o+64];return i=e}function cr(r,n){if(r.length!==zr)throw new Error("bad key size");if(n.length!==Rr)throw new Error("bad nonce size")}function wr(r,n){if(r.length!==Cr)throw new Error("bad public key size");if(n.length!==Mr)throw new Error("bad secret key size")}function yr(){var r,n;for(n=0;n<arguments.length;n++)if("[object Uint8Array]"!==(r=Object.prototype.toString.call(arguments[n])))throw new TypeError("unexpected type "+r+", use Uint8Array")}function lr(r){for(var n=0;n<r.length;n++)r[n]=0}var sr=function(r,n){this.hi=0|r,this.lo=0|n},hr=function(r){var n,e=new Float64Array(16);if(r)for(n=0;n<r.length;n++)e[n]=r[n];return e},gr=function(){throw new Error("no PRNG")},vr=new Uint8Array(16),br=new Uint8Array(32);br[0]=9;var pr=hr(),_r=hr([1]),Ar=hr([56129,1]),Ur=hr([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),Er=hr([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),dr=hr([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),xr=hr([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),mr=hr([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]),Br=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]),Sr=new Uint32Array([5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252]),Kr=_,Tr=A,Yr=[new sr(1116352408,3609767458),new sr(1899447441,602891725),new sr(3049323471,3964484399),new sr(3921009573,2173295548),new sr(961987163,4081628472),new sr(1508970993,3053834265),new sr(2453635748,2937671579),new sr(2870763221,3664609560),new sr(3624381080,2734883394),new sr(310598401,1164996542),new sr(607225278,1323610764),new sr(1426881987,3590304994),new sr(1925078388,4068182383),new sr(2162078206,991336113),new sr(2614888103,633803317),new sr(3248222580,3479774868),new sr(3835390401,2666613458),new sr(4022224774,944711139),new sr(264347078,2341262773),new sr(604807628,2007800933),new sr(770255983,1495990901),new sr(1249150122,1856431235),new sr(1555081692,3175218132),new sr(1996064986,2198950837),new sr(2554220882,3999719339),new sr(2821834349,766784016),new sr(2952996808,2566594879),new sr(3210313671,3203337956),new sr(3336571891,1034457026),new sr(3584528711,2466948901),new sr(113926993,3758326383),new sr(338241895,168717936),new sr(666307205,1188179964),new sr(773529912,1546045734),new sr(1294757372,1522805485),new sr(1396182291,2643833823),new sr(1695183700,2343527390),new sr(1986661051,1014477480),new sr(2177026350,1206759142),new sr(2456956037,344077627),new sr(2730485921,1290863460),new sr(2820302411,3158454273),new sr(3259730800,3505952657),new sr(3345764771,106217008),new sr(3516065817,3606008344),new sr(3600352804,1432725776),new sr(4094571909,1467031594),new sr(275423344,851169720),new sr(430227734,3100823752),new sr(506948616,1363258195),new sr(659060556,3750685593),new sr(883997877,3785050280),new sr(958139571,3318307427),new sr(1322822218,3812723403),new sr(1537002063,2003034995),new sr(1747873779,3602036899),new sr(1955562222,1575990012),new sr(2024104815,1125592928),new sr(2227730452,2716904306),new sr(2361852424,442776044),new sr(2428436474,593698344),new sr(2756734187,3733110249),new sr(3204031479,2999351573),new sr(3329325298,3815920427),new sr(3391569614,3928383900),new sr(3515267271,566280711),new sr(3940187606,3454069534),new sr(4118630271,4000239992),new sr(116418474,1914138554),new sr(174292421,2731055270),new sr(289380356,3203993006),new sr(460393269,320620315),new sr(685471733,587496836),new sr(852142971,1086792851),new sr(1017036298,365543100),new sr(1126000580,2618297676),new sr(1288033470,3409855158),new sr(1501505948,4234509866),new sr(1607167915,987167468),new sr(1816402316,1246189591)],Lr=new Uint8Array([106,9,230,103,243,188,201,8,187,103,174,133,132,202,167,59,60,110,243,114,254,148,248,43,165,79,245,58,95,29,54,241,81,14,82,127,173,230,130,209,155,5,104,140,43,62,108,31,31,131,217,171,251,65,189,107,91,224,205,25,19,126,33,121]),kr=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),zr=32,Rr=24,Pr=32,Or=16,Fr=32,Nr=32,Cr=32,Mr=32,Gr=32,Zr=Rr,jr=Pr,qr=Or,Ir=64,Vr=32,Xr=64,Dr=32,Hr=64;r.lowlevel={crypto_core_hsalsa20:y,crypto_stream_xor:g,crypto_stream:h,crypto_stream_salsa20_xor:l,crypto_stream_salsa20:s,crypto_onetimeauth:b,crypto_onetimeauth_verify:p,crypto_verify_16:f,crypto_verify_32:u,crypto_secretbox:_,crypto_secretbox_open:A,crypto_scalarmult:R,crypto_scalarmult_base:P,crypto_box_beforenm:F,crypto_box_afternm:Kr,crypto_box:N,crypto_box_open:C,crypto_box_keypair:O,crypto_hash:Q,crypto_sign:ar,crypto_sign_keypair:tr,crypto_sign_open:ur,crypto_secretbox_KEYBYTES:zr,crypto_secretbox_NONCEBYTES:Rr,crypto_secretbox_ZEROBYTES:Pr,crypto_secretbox_BOXZEROBYTES:Or,crypto_scalarmult_BYTES:Fr,crypto_scalarmult_SCALARBYTES:Nr,crypto_box_PUBLICKEYBYTES:Cr,crypto_box_SECRETKEYBYTES:Mr,crypto_box_BEFORENMBYTES:Gr,crypto_box_NONCEBYTES:Zr,crypto_box_ZEROBYTES:jr,crypto_box_BOXZEROBYTES:qr,crypto_sign_BYTES:Ir,crypto_sign_PUBLICKEYBYTES:Vr,crypto_sign_SECRETKEYBYTES:Xr,crypto_sign_SEEDBYTES:Dr,crypto_hash_BYTES:Hr},r.util||(r.util={},r.util.decodeUTF8=r.util.encodeUTF8=r.util.encodeBase64=r.util.decodeBase64=function(){throw new Error("nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js")}),r.randomBytes=function(r){var n=new Uint8Array(r);return gr(n,r),n},r.secretbox=function(r,n,e){yr(r,n,e),cr(e,n);for(var t=new Uint8Array(Pr+r.length),o=new Uint8Array(t.length),i=0;i<r.length;i++)t[i+Pr]=r[i];return _(o,t,t.length,n,e),o.subarray(Or)},r.secretbox.open=function(r,n,e){yr(r,n,e),cr(e,n);for(var t=new Uint8Array(Or+r.length),o=new Uint8Array(t.length),i=0;i<r.length;i++)t[i+Or]=r[i];return!(t.length<32)&&(0===A(o,t,t.length,n,e)&&o.subarray(Pr))},r.secretbox.keyLength=zr,r.secretbox.nonceLength=Rr,r.secretbox.overheadLength=Or,r.scalarMult=function(r,n){if(yr(r,n),r.length!==Nr)throw new Error("bad n size");if(n.length!==Fr)throw new Error("bad p size");var e=new Uint8Array(Fr);return R(e,r,n),e},r.scalarMult.base=function(r){if(yr(r),r.length!==Nr)throw new Error("bad n size");var n=new Uint8Array(Fr);return P(n,r),n},r.scalarMult.scalarLength=Nr,r.scalarMult.groupElementLength=Fr,r.box=function(n,e,t,o){var i=r.box.before(t,o);return r.secretbox(n,e,i)},r.box.before=function(r,n){yr(r,n),wr(r,n);var e=new Uint8Array(Gr);return F(e,r,n),e},r.box.after=r.secretbox,r.box.open=function(n,e,t,o){var i=r.box.before(t,o);return r.secretbox.open(n,e,i)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var r=new Uint8Array(Cr),n=new Uint8Array(Mr);return O(r,n),{publicKey:r,secretKey:n}},r.box.keyPair.fromSecretKey=function(r){if(yr(r),r.length!==Mr)throw new Error("bad secret key size");var n=new Uint8Array(Cr);return P(n,r),{publicKey:n,secretKey:new Uint8Array(r)}},r.box.publicKeyLength=Cr,r.box.secretKeyLength=Mr,r.box.sharedKeyLength=Gr,r.box.nonceLength=Zr,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(r,n){if(yr(r,n),n.length!==Xr)throw new Error("bad secret key size");var e=new Uint8Array(Ir+r.length);return ar(e,r,r.length,n),e},r.sign.open=function(r,n){if(2!==arguments.length)throw new Error("nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?");if(yr(r,n),n.length!==Vr)throw new Error("bad public key size");var e=new Uint8Array(r.length),t=ur(e,r,r.length,n);if(t<0)return null;for(var o=new Uint8Array(t),i=0;i<o.length;i++)o[i]=e[i];return o},r.sign.detached=function(n,e){for(var t=r.sign(n,e),o=new Uint8Array(Ir),i=0;i<o.length;i++)o[i]=t[i];return o},r.sign.detached.verify=function(r,n,e){if(yr(r,n,e),n.length!==Ir)throw new Error("bad signature size");if(e.length!==Vr)throw new Error("bad public key size");var t,o=new Uint8Array(Ir+r.length),i=new Uint8Array(Ir+r.length);for(t=0;t<Ir;t++)o[t]=n[t];for(t=0;t<r.length;t++)o[t+Ir]=r[t];return ur(i,o,o.length,e)>=0},r.sign.keyPair=function(){var r=new Uint8Array(Vr),n=new Uint8Array(Xr);return tr(r,n),{publicKey:r,secretKey:n}},r.sign.keyPair.fromSecretKey=function(r){if(yr(r),r.length!==Xr)throw new Error("bad secret key size");for(var n=new Uint8Array(Vr),e=0;e<n.length;e++)n[e]=r[32+e];return{publicKey:n,secretKey:new Uint8Array(r)}},r.sign.keyPair.fromSeed=function(r){if(yr(r),r.length!==Dr)throw new Error("bad seed size");for(var n=new Uint8Array(Vr),e=new Uint8Array(Xr),t=0;t<32;t++)e[t]=r[t];return tr(n,e,!0),{publicKey:n,secretKey:e}},r.sign.publicKeyLength=Vr,r.sign.secretKeyLength=Xr,r.sign.seedLength=Dr,r.sign.signatureLength=Ir,r.hash=function(r){yr(r);var n=new Uint8Array(Hr);return Q(n,r,r.length),n},r.hash.hashLength=Hr,r.verify=function(r,n){return yr(r,n),0!==r.length&&0!==n.length&&(r.length===n.length&&0===a(r,0,n,0,r.length))},r.setPRNG=function(r){gr=r},function(){var n="undefined"!=typeof self?self.crypto||self.msCrypto:null;if(n&&n.getRandomValues){var e=65536;r.setPRNG(function(r,t){var o,i=new Uint8Array(t);for(o=0;o<t;o+=e)n.getRandomValues(i.subarray(o,o+Math.min(t-o,e)));for(o=0;o<t;o++)r[o]=i[o];lr(i)})}else"undefined"!=typeof require&&(n=require("crypto"),n&&n.randomBytes&&r.setPRNG(function(r,e){var t,o=n.randomBytes(e);for(t=0;t<e;t++)r[t]=o[t];lr(o)}))}()}("undefined"!=typeof module&&module.exports?module.exports:self.nacl=self.nacl||{});
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/tweetnacl/nacl.min.js
nacl.min.js
export as namespace nacl; declare var nacl: nacl; export = nacl; declare namespace nacl { export interface BoxKeyPair { publicKey: Uint8Array; secretKey: Uint8Array; } export interface SignKeyPair { publicKey: Uint8Array; secretKey: Uint8Array; } export interface secretbox { (msg: Uint8Array, nonce: Uint8Array, key: Uint8Array): Uint8Array; open(box: Uint8Array, nonce: Uint8Array, key: Uint8Array): Uint8Array | false; readonly keyLength: number; readonly nonceLength: number; readonly overheadLength: number; } export interface scalarMult { (n: Uint8Array, p: Uint8Array): Uint8Array; base(n: Uint8Array): Uint8Array; readonly scalarLength: number; readonly groupElementLength: number; } namespace box { export interface open { (msg: Uint8Array, nonce: Uint8Array, publicKey: Uint8Array, secretKey: Uint8Array): Uint8Array | false; after(box: Uint8Array, nonce: Uint8Array, key: Uint8Array): Uint8Array | false; } export interface keyPair { (): BoxKeyPair; fromSecretKey(secretKey: Uint8Array): BoxKeyPair; } } export interface box { (msg: Uint8Array, nonce: Uint8Array, publicKey: Uint8Array, secretKey: Uint8Array): Uint8Array; before(publicKey: Uint8Array, secretKey: Uint8Array): Uint8Array; after(msg: Uint8Array, nonce: Uint8Array, key: Uint8Array): Uint8Array; open: box.open; keyPair: box.keyPair; readonly publicKeyLength: number; readonly secretKeyLength: number; readonly sharedKeyLength: number; readonly nonceLength: number; readonly overheadLength: number; } namespace sign { export interface detached { (msg: Uint8Array, secretKey: Uint8Array): Uint8Array; verify(msg: Uint8Array, sig: Uint8Array, publicKey: Uint8Array): boolean; } export interface keyPair { (): SignKeyPair; fromSecretKey(secretKey: Uint8Array): SignKeyPair; fromSeed(secretKey: Uint8Array): SignKeyPair; } } export interface sign { (msg: Uint8Array, secretKey: Uint8Array): Uint8Array; open(signedMsg: Uint8Array, publicKey: Uint8Array): Uint8Array | null; detached: sign.detached; keyPair: sign.keyPair; readonly publicKeyLength: number; readonly secretKeyLength: number; readonly seedLength: number; readonly signatureLength: number; } export interface hash { (msg: Uint8Array): Uint8Array; readonly hashLength: number; } } declare interface nacl { randomBytes(n: number): Uint8Array; secretbox: nacl.secretbox; scalarMult: nacl.scalarMult; box: nacl.box; sign: nacl.sign; hash: nacl.hash; verify(x: Uint8Array, y: Uint8Array): boolean; setPRNG(fn: (x: Uint8Array, n: number) => void): void; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/tweetnacl/nacl.d.ts
nacl.d.ts
(function(nacl) { 'use strict'; // Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. // Public domain. // // Implementation derived from TweetNaCl version 20140427. // See for details: http://tweetnacl.cr.yp.to/ var u64 = function(h, l) { this.hi = h|0 >>> 0; this.lo = l|0 >>> 0; }; var gf = function(init) { var i, r = new Float64Array(16); if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; return r; }; // Pluggable, initialized in high-level API below. var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; var _0 = new Uint8Array(16); var _9 = new Uint8Array(32); _9[0] = 9; var gf0 = gf(), gf1 = gf([1]), _121665 = gf([0xdb41, 1]), D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); function L32(x, c) { return (x << c) | (x >>> (32 - c)); } function ld32(x, i) { var u = x[i+3] & 0xff; u = (u<<8)|(x[i+2] & 0xff); u = (u<<8)|(x[i+1] & 0xff); return (u<<8)|(x[i+0] & 0xff); } function dl64(x, i) { var h = (x[i] << 24) | (x[i+1] << 16) | (x[i+2] << 8) | x[i+3]; var l = (x[i+4] << 24) | (x[i+5] << 16) | (x[i+6] << 8) | x[i+7]; return new u64(h, l); } function st32(x, j, u) { var i; for (i = 0; i < 4; i++) { x[j+i] = u & 255; u >>>= 8; } } function ts64(x, i, u) { x[i] = (u.hi >> 24) & 0xff; x[i+1] = (u.hi >> 16) & 0xff; x[i+2] = (u.hi >> 8) & 0xff; x[i+3] = u.hi & 0xff; x[i+4] = (u.lo >> 24) & 0xff; x[i+5] = (u.lo >> 16) & 0xff; x[i+6] = (u.lo >> 8) & 0xff; x[i+7] = u.lo & 0xff; } function vn(x, xi, y, yi, n) { var i,d = 0; for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; return (1 & ((d - 1) >>> 8)) - 1; } function crypto_verify_16(x, xi, y, yi) { return vn(x,xi,y,yi,16); } function crypto_verify_32(x, xi, y, yi) { return vn(x,xi,y,yi,32); } function core(out,inp,k,c,h) { var w = new Uint32Array(16), x = new Uint32Array(16), y = new Uint32Array(16), t = new Uint32Array(4); var i, j, m; for (i = 0; i < 4; i++) { x[5*i] = ld32(c, 4*i); x[1+i] = ld32(k, 4*i); x[6+i] = ld32(inp, 4*i); x[11+i] = ld32(k, 16+4*i); } for (i = 0; i < 16; i++) y[i] = x[i]; for (i = 0; i < 20; i++) { for (j = 0; j < 4; j++) { for (m = 0; m < 4; m++) t[m] = x[(5*j+4*m)%16]; t[1] ^= L32((t[0]+t[3])|0, 7); t[2] ^= L32((t[1]+t[0])|0, 9); t[3] ^= L32((t[2]+t[1])|0,13); t[0] ^= L32((t[3]+t[2])|0,18); for (m = 0; m < 4; m++) w[4*j+(j+m)%4] = t[m]; } for (m = 0; m < 16; m++) x[m] = w[m]; } if (h) { for (i = 0; i < 16; i++) x[i] = (x[i] + y[i]) | 0; for (i = 0; i < 4; i++) { x[5*i] = (x[5*i] - ld32(c, 4*i)) | 0; x[6+i] = (x[6+i] - ld32(inp, 4*i)) | 0; } for (i = 0; i < 4; i++) { st32(out,4*i,x[5*i]); st32(out,16+4*i,x[6+i]); } } else { for (i = 0; i < 16; i++) st32(out, 4 * i, (x[i] + y[i]) | 0); } } function crypto_core_salsa20(out,inp,k,c) { core(out,inp,k,c,false); return 0; } function crypto_core_hsalsa20(out,inp,k,c) { core(out,inp,k,c,true); return 0; } var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); // "expand 32-byte k" function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { var z = new Uint8Array(16), x = new Uint8Array(64); var u, i; if (!b) return 0; for (i = 0; i < 16; i++) z[i] = 0; for (i = 0; i < 8; i++) z[i] = n[i]; while (b >= 64) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < 64; i++) c[cpos+i] = (m?m[mpos+i]:0) ^ x[i]; u = 1; for (i = 8; i < 16; i++) { u = u + (z[i] & 0xff) | 0; z[i] = u & 0xff; u >>>= 8; } b -= 64; cpos += 64; if (m) mpos += 64; } if (b > 0) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < b; i++) c[cpos+i] = (m?m[mpos+i]:0) ^ x[i]; } return 0; } function crypto_stream_salsa20(c,cpos,d,n,k) { return crypto_stream_salsa20_xor(c,cpos,null,0,d,n,k); } function crypto_stream(c,cpos,d,n,k) { var s = new Uint8Array(32); crypto_core_hsalsa20(s,n,k,sigma); return crypto_stream_salsa20(c,cpos,d,n.subarray(16),s); } function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { var s = new Uint8Array(32); crypto_core_hsalsa20(s,n,k,sigma); return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,n.subarray(16),s); } function add1305(h, c) { var j, u = 0; for (j = 0; j < 17; j++) { u = (u + ((h[j] + c[j]) | 0)) | 0; h[j] = u & 255; u >>>= 8; } } var minusp = new Uint32Array([ 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 252 ]); function crypto_onetimeauth(out, outpos, m, mpos, n, k) { var s, i, j, u; var x = new Uint32Array(17), r = new Uint32Array(17), h = new Uint32Array(17), c = new Uint32Array(17), g = new Uint32Array(17); for (j = 0; j < 17; j++) r[j]=h[j]=0; for (j = 0; j < 16; j++) r[j]=k[j]; r[3]&=15; r[4]&=252; r[7]&=15; r[8]&=252; r[11]&=15; r[12]&=252; r[15]&=15; while (n > 0) { for (j = 0; j < 17; j++) c[j] = 0; for (j = 0; (j < 16) && (j < n); ++j) c[j] = m[mpos+j]; c[j] = 1; mpos += j; n -= j; add1305(h,c); for (i = 0; i < 17; i++) { x[i] = 0; for (j = 0; j < 17; j++) x[i] = (x[i] + (h[j] * ((j <= i) ? r[i - j] : ((320 * r[i + 17 - j])|0))) | 0) | 0; } for (i = 0; i < 17; i++) h[i] = x[i]; u = 0; for (j = 0; j < 16; j++) { u = (u + h[j]) | 0; h[j] = u & 255; u >>>= 8; } u = (u + h[16]) | 0; h[16] = u & 3; u = (5 * (u >>> 2)) | 0; for (j = 0; j < 16; j++) { u = (u + h[j]) | 0; h[j] = u & 255; u >>>= 8; } u = (u + h[16]) | 0; h[16] = u; } for (j = 0; j < 17; j++) g[j] = h[j]; add1305(h,minusp); s = (-(h[16] >>> 7) | 0); for (j = 0; j < 17; j++) h[j] ^= s & (g[j] ^ h[j]); for (j = 0; j < 16; j++) c[j] = k[j + 16]; c[16] = 0; add1305(h,c); for (j = 0; j < 16; j++) out[outpos+j] = h[j]; return 0; } function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { var x = new Uint8Array(16); crypto_onetimeauth(x,0,m,mpos,n,k); return crypto_verify_16(h,hpos,x,0); } function crypto_secretbox(c,m,d,n,k) { var i; if (d < 32) return -1; crypto_stream_xor(c,0,m,0,d,n,k); crypto_onetimeauth(c, 16, c, 32, d - 32, c); for (i = 0; i < 16; i++) c[i] = 0; return 0; } function crypto_secretbox_open(m,c,d,n,k) { var i; var x = new Uint8Array(32); if (d < 32) return -1; crypto_stream(x,0,32,n,k); if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; crypto_stream_xor(m,0,c,0,d,n,k); for (i = 0; i < 32; i++) m[i] = 0; return 0; } function set25519(r, a) { var i; for (i = 0; i < 16; i++) r[i] = a[i]|0; } function car25519(o) { var c; var i; for (i = 0; i < 16; i++) { o[i] += 65536; c = Math.floor(o[i] / 65536); o[(i+1)*(i<15?1:0)] += c - 1 + 37 * (c-1) * (i===15?1:0); o[i] -= (c * 65536); } } function sel25519(p, q, b) { var t, c = ~(b-1); for (var i = 0; i < 16; i++) { t = c & (p[i] ^ q[i]); p[i] ^= t; q[i] ^= t; } } function pack25519(o, n) { var i, j, b; var m = gf(), t = gf(); for (i = 0; i < 16; i++) t[i] = n[i]; car25519(t); car25519(t); car25519(t); for (j = 0; j < 2; j++) { m[0] = t[0] - 0xffed; for (i = 1; i < 15; i++) { m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); m[i-1] &= 0xffff; } m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); b = (m[15]>>16) & 1; m[14] &= 0xffff; sel25519(t, m, 1-b); } for (i = 0; i < 16; i++) { o[2*i] = t[i] & 0xff; o[2*i+1] = t[i]>>8; } } function neq25519(a, b) { var c = new Uint8Array(32), d = new Uint8Array(32); pack25519(c, a); pack25519(d, b); return crypto_verify_32(c, 0, d, 0); } function par25519(a) { var d = new Uint8Array(32); pack25519(d, a); return d[0] & 1; } function unpack25519(o, n) { var i; for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); o[15] &= 0x7fff; } function A(o, a, b) { var i; for (i = 0; i < 16; i++) o[i] = (a[i] + b[i])|0; } function Z(o, a, b) { var i; for (i = 0; i < 16; i++) o[i] = (a[i] - b[i])|0; } function M(o, a, b) { var i, j, t = new Float64Array(31); for (i = 0; i < 31; i++) t[i] = 0; for (i = 0; i < 16; i++) { for (j = 0; j < 16; j++) { t[i+j] += a[i] * b[j]; } } for (i = 0; i < 15; i++) { t[i] += 38 * t[i+16]; } for (i = 0; i < 16; i++) o[i] = t[i]; car25519(o); car25519(o); } function S(o, a) { M(o, a, a); } function inv25519(o, i) { var c = gf(); var a; for (a = 0; a < 16; a++) c[a] = i[a]; for (a = 253; a >= 0; a--) { S(c, c); if(a !== 2 && a !== 4) M(c, c, i); } for (a = 0; a < 16; a++) o[a] = c[a]; } function pow2523(o, i) { var c = gf(); var a; for (a = 0; a < 16; a++) c[a] = i[a]; for (a = 250; a >= 0; a--) { S(c, c); if(a !== 1) M(c, c, i); } for (a = 0; a < 16; a++) o[a] = c[a]; } function crypto_scalarmult(q, n, p) { var z = new Uint8Array(32); var x = new Float64Array(80), r, i; var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(); for (i = 0; i < 31; i++) z[i] = n[i]; z[31]=(n[31]&127)|64; z[0]&=248; unpack25519(x,p); for (i = 0; i < 16; i++) { b[i]=x[i]; d[i]=a[i]=c[i]=0; } a[0]=d[0]=1; for (i=254; i>=0; --i) { r=(z[i>>>3]>>>(i&7))&1; sel25519(a,b,r); sel25519(c,d,r); A(e,a,c); Z(a,a,c); A(c,b,d); Z(b,b,d); S(d,e); S(f,a); M(a,c,a); M(c,b,e); A(e,a,c); Z(a,a,c); S(b,a); Z(c,d,f); M(a,c,_121665); A(a,a,d); M(c,c,a); M(a,d,f); M(d,b,x); S(b,e); sel25519(a,b,r); sel25519(c,d,r); } for (i = 0; i < 16; i++) { x[i+16]=a[i]; x[i+32]=c[i]; x[i+48]=b[i]; x[i+64]=d[i]; } var x32 = x.subarray(32); var x16 = x.subarray(16); inv25519(x32,x32); M(x16,x16,x32); pack25519(q,x16); return 0; } function crypto_scalarmult_base(q, n) { return crypto_scalarmult(q, n, _9); } function crypto_box_keypair(y, x) { randombytes(x, 32); return crypto_scalarmult_base(y, x); } function crypto_box_beforenm(k, y, x) { var s = new Uint8Array(32); crypto_scalarmult(s, x, y); return crypto_core_hsalsa20(k, _0, s, sigma); } var crypto_box_afternm = crypto_secretbox; var crypto_box_open_afternm = crypto_secretbox_open; function crypto_box(c, m, d, n, y, x) { var k = new Uint8Array(32); crypto_box_beforenm(k, y, x); return crypto_box_afternm(c, m, d, n, k); } function crypto_box_open(m, c, d, n, y, x) { var k = new Uint8Array(32); crypto_box_beforenm(k, y, x); return crypto_box_open_afternm(m, c, d, n, k); } function add64() { var a = 0, b = 0, c = 0, d = 0, m16 = 65535, l, h, i; for (i = 0; i < arguments.length; i++) { l = arguments[i].lo; h = arguments[i].hi; a += (l & m16); b += (l >>> 16); c += (h & m16); d += (h >>> 16); } b += (a >>> 16); c += (b >>> 16); d += (c >>> 16); return new u64((c & m16) | (d << 16), (a & m16) | (b << 16)); } function shr64(x, c) { return new u64((x.hi >>> c), (x.lo >>> c) | (x.hi << (32 - c))); } function xor64() { var l = 0, h = 0, i; for (i = 0; i < arguments.length; i++) { l ^= arguments[i].lo; h ^= arguments[i].hi; } return new u64(h, l); } function R(x, c) { var h, l, c1 = 32 - c; if (c < 32) { h = (x.hi >>> c) | (x.lo << c1); l = (x.lo >>> c) | (x.hi << c1); } else if (c < 64) { h = (x.lo >>> c) | (x.hi << c1); l = (x.hi >>> c) | (x.lo << c1); } return new u64(h, l); } function Ch(x, y, z) { var h = (x.hi & y.hi) ^ (~x.hi & z.hi), l = (x.lo & y.lo) ^ (~x.lo & z.lo); return new u64(h, l); } function Maj(x, y, z) { var h = (x.hi & y.hi) ^ (x.hi & z.hi) ^ (y.hi & z.hi), l = (x.lo & y.lo) ^ (x.lo & z.lo) ^ (y.lo & z.lo); return new u64(h, l); } function Sigma0(x) { return xor64(R(x,28), R(x,34), R(x,39)); } function Sigma1(x) { return xor64(R(x,14), R(x,18), R(x,41)); } function sigma0(x) { return xor64(R(x, 1), R(x, 8), shr64(x,7)); } function sigma1(x) { return xor64(R(x,19), R(x,61), shr64(x,6)); } var K = [ new u64(0x428a2f98, 0xd728ae22), new u64(0x71374491, 0x23ef65cd), new u64(0xb5c0fbcf, 0xec4d3b2f), new u64(0xe9b5dba5, 0x8189dbbc), new u64(0x3956c25b, 0xf348b538), new u64(0x59f111f1, 0xb605d019), new u64(0x923f82a4, 0xaf194f9b), new u64(0xab1c5ed5, 0xda6d8118), new u64(0xd807aa98, 0xa3030242), new u64(0x12835b01, 0x45706fbe), new u64(0x243185be, 0x4ee4b28c), new u64(0x550c7dc3, 0xd5ffb4e2), new u64(0x72be5d74, 0xf27b896f), new u64(0x80deb1fe, 0x3b1696b1), new u64(0x9bdc06a7, 0x25c71235), new u64(0xc19bf174, 0xcf692694), new u64(0xe49b69c1, 0x9ef14ad2), new u64(0xefbe4786, 0x384f25e3), new u64(0x0fc19dc6, 0x8b8cd5b5), new u64(0x240ca1cc, 0x77ac9c65), new u64(0x2de92c6f, 0x592b0275), new u64(0x4a7484aa, 0x6ea6e483), new u64(0x5cb0a9dc, 0xbd41fbd4), new u64(0x76f988da, 0x831153b5), new u64(0x983e5152, 0xee66dfab), new u64(0xa831c66d, 0x2db43210), new u64(0xb00327c8, 0x98fb213f), new u64(0xbf597fc7, 0xbeef0ee4), new u64(0xc6e00bf3, 0x3da88fc2), new u64(0xd5a79147, 0x930aa725), new u64(0x06ca6351, 0xe003826f), new u64(0x14292967, 0x0a0e6e70), new u64(0x27b70a85, 0x46d22ffc), new u64(0x2e1b2138, 0x5c26c926), new u64(0x4d2c6dfc, 0x5ac42aed), new u64(0x53380d13, 0x9d95b3df), new u64(0x650a7354, 0x8baf63de), new u64(0x766a0abb, 0x3c77b2a8), new u64(0x81c2c92e, 0x47edaee6), new u64(0x92722c85, 0x1482353b), new u64(0xa2bfe8a1, 0x4cf10364), new u64(0xa81a664b, 0xbc423001), new u64(0xc24b8b70, 0xd0f89791), new u64(0xc76c51a3, 0x0654be30), new u64(0xd192e819, 0xd6ef5218), new u64(0xd6990624, 0x5565a910), new u64(0xf40e3585, 0x5771202a), new u64(0x106aa070, 0x32bbd1b8), new u64(0x19a4c116, 0xb8d2d0c8), new u64(0x1e376c08, 0x5141ab53), new u64(0x2748774c, 0xdf8eeb99), new u64(0x34b0bcb5, 0xe19b48a8), new u64(0x391c0cb3, 0xc5c95a63), new u64(0x4ed8aa4a, 0xe3418acb), new u64(0x5b9cca4f, 0x7763e373), new u64(0x682e6ff3, 0xd6b2b8a3), new u64(0x748f82ee, 0x5defb2fc), new u64(0x78a5636f, 0x43172f60), new u64(0x84c87814, 0xa1f0ab72), new u64(0x8cc70208, 0x1a6439ec), new u64(0x90befffa, 0x23631e28), new u64(0xa4506ceb, 0xde82bde9), new u64(0xbef9a3f7, 0xb2c67915), new u64(0xc67178f2, 0xe372532b), new u64(0xca273ece, 0xea26619c), new u64(0xd186b8c7, 0x21c0c207), new u64(0xeada7dd6, 0xcde0eb1e), new u64(0xf57d4f7f, 0xee6ed178), new u64(0x06f067aa, 0x72176fba), new u64(0x0a637dc5, 0xa2c898a6), new u64(0x113f9804, 0xbef90dae), new u64(0x1b710b35, 0x131c471b), new u64(0x28db77f5, 0x23047d84), new u64(0x32caab7b, 0x40c72493), new u64(0x3c9ebe0a, 0x15c9bebc), new u64(0x431d67c4, 0x9c100d4c), new u64(0x4cc5d4be, 0xcb3e42b6), new u64(0x597f299c, 0xfc657e2a), new u64(0x5fcb6fab, 0x3ad6faec), new u64(0x6c44198c, 0x4a475817) ]; function crypto_hashblocks(x, m, n) { var z = [], b = [], a = [], w = [], t, i, j; for (i = 0; i < 8; i++) z[i] = a[i] = dl64(x, 8*i); var pos = 0; while (n >= 128) { for (i = 0; i < 16; i++) w[i] = dl64(m, 8*i+pos); for (i = 0; i < 80; i++) { for (j = 0; j < 8; j++) b[j] = a[j]; t = add64(a[7], Sigma1(a[4]), Ch(a[4], a[5], a[6]), K[i], w[i%16]); b[7] = add64(t, Sigma0(a[0]), Maj(a[0], a[1], a[2])); b[3] = add64(b[3], t); for (j = 0; j < 8; j++) a[(j+1)%8] = b[j]; if (i%16 === 15) { for (j = 0; j < 16; j++) { w[j] = add64(w[j], w[(j+9)%16], sigma0(w[(j+1)%16]), sigma1(w[(j+14)%16])); } } } for (i = 0; i < 8; i++) { a[i] = add64(a[i], z[i]); z[i] = a[i]; } pos += 128; n -= 128; } for (i = 0; i < 8; i++) ts64(x, 8*i, z[i]); return n; } var iv = new Uint8Array([ 0x6a,0x09,0xe6,0x67,0xf3,0xbc,0xc9,0x08, 0xbb,0x67,0xae,0x85,0x84,0xca,0xa7,0x3b, 0x3c,0x6e,0xf3,0x72,0xfe,0x94,0xf8,0x2b, 0xa5,0x4f,0xf5,0x3a,0x5f,0x1d,0x36,0xf1, 0x51,0x0e,0x52,0x7f,0xad,0xe6,0x82,0xd1, 0x9b,0x05,0x68,0x8c,0x2b,0x3e,0x6c,0x1f, 0x1f,0x83,0xd9,0xab,0xfb,0x41,0xbd,0x6b, 0x5b,0xe0,0xcd,0x19,0x13,0x7e,0x21,0x79 ]); function crypto_hash(out, m, n) { var h = new Uint8Array(64), x = new Uint8Array(256); var i, b = n; for (i = 0; i < 64; i++) h[i] = iv[i]; crypto_hashblocks(h, m, n); n %= 128; for (i = 0; i < 256; i++) x[i] = 0; for (i = 0; i < n; i++) x[i] = m[b-n+i]; x[n] = 128; n = 256-128*(n<112?1:0); x[n-9] = 0; ts64(x, n-8, new u64((b / 0x20000000) | 0, b << 3)); crypto_hashblocks(h, x, n); for (i = 0; i < 64; i++) out[i] = h[i]; return 0; } function add(p, q) { var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf(); Z(a, p[1], p[0]); Z(t, q[1], q[0]); M(a, a, t); A(b, p[0], p[1]); A(t, q[0], q[1]); M(b, b, t); M(c, p[3], q[3]); M(c, c, D2); M(d, p[2], q[2]); A(d, d, d); Z(e, b, a); Z(f, d, c); A(g, d, c); A(h, b, a); M(p[0], e, f); M(p[1], h, g); M(p[2], g, f); M(p[3], e, h); } function cswap(p, q, b) { var i; for (i = 0; i < 4; i++) { sel25519(p[i], q[i], b); } } function pack(r, p) { var tx = gf(), ty = gf(), zi = gf(); inv25519(zi, p[2]); M(tx, p[0], zi); M(ty, p[1], zi); pack25519(r, ty); r[31] ^= par25519(tx) << 7; } function scalarmult(p, q, s) { var b, i; set25519(p[0], gf0); set25519(p[1], gf1); set25519(p[2], gf1); set25519(p[3], gf0); for (i = 255; i >= 0; --i) { b = (s[(i/8)|0] >> (i&7)) & 1; cswap(p, q, b); add(q, p); add(p, p); cswap(p, q, b); } } function scalarbase(p, s) { var q = [gf(), gf(), gf(), gf()]; set25519(q[0], X); set25519(q[1], Y); set25519(q[2], gf1); M(q[3], X, Y); scalarmult(p, q, s); } function crypto_sign_keypair(pk, sk, seeded) { var d = new Uint8Array(64); var p = [gf(), gf(), gf(), gf()]; var i; if (!seeded) randombytes(sk, 32); crypto_hash(d, sk, 32); d[0] &= 248; d[31] &= 127; d[31] |= 64; scalarbase(p, d); pack(pk, p); for (i = 0; i < 32; i++) sk[i+32] = pk[i]; return 0; } var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); function modL(r, x) { var carry, i, j, k; for (i = 63; i >= 32; --i) { carry = 0; for (j = i - 32, k = i - 12; j < k; ++j) { x[j] += carry - 16 * x[i] * L[j - (i - 32)]; carry = (x[j] + 128) >> 8; x[j] -= carry * 256; } x[j] += carry; x[i] = 0; } carry = 0; for (j = 0; j < 32; j++) { x[j] += carry - (x[31] >> 4) * L[j]; carry = x[j] >> 8; x[j] &= 255; } for (j = 0; j < 32; j++) x[j] -= carry * L[j]; for (i = 0; i < 32; i++) { x[i+1] += x[i] >> 8; r[i] = x[i] & 255; } } function reduce(r) { var x = new Float64Array(64), i; for (i = 0; i < 64; i++) x[i] = r[i]; for (i = 0; i < 64; i++) r[i] = 0; modL(r, x); } // Note: difference from C - smlen returned, not passed as argument. function crypto_sign(sm, m, n, sk) { var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); var i, j, x = new Float64Array(64); var p = [gf(), gf(), gf(), gf()]; crypto_hash(d, sk, 32); d[0] &= 248; d[31] &= 127; d[31] |= 64; var smlen = n + 64; for (i = 0; i < n; i++) sm[64 + i] = m[i]; for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; crypto_hash(r, sm.subarray(32), n+32); reduce(r); scalarbase(p, r); pack(sm, p); for (i = 32; i < 64; i++) sm[i] = sk[i]; crypto_hash(h, sm, n + 64); reduce(h); for (i = 0; i < 64; i++) x[i] = 0; for (i = 0; i < 32; i++) x[i] = r[i]; for (i = 0; i < 32; i++) { for (j = 0; j < 32; j++) { x[i+j] += h[i] * d[j]; } } modL(sm.subarray(32), x); return smlen; } function unpackneg(r, p) { var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); set25519(r[2], gf1); unpack25519(r[1], p); S(num, r[1]); M(den, num, D); Z(num, num, r[2]); A(den, r[2], den); S(den2, den); S(den4, den2); M(den6, den4, den2); M(t, den6, num); M(t, t, den); pow2523(t, t); M(t, t, num); M(t, t, den); M(t, t, den); M(r[0], t, den); S(chk, r[0]); M(chk, chk, den); if (neq25519(chk, num)) M(r[0], r[0], I); S(chk, r[0]); M(chk, chk, den); if (neq25519(chk, num)) return -1; if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); M(r[3], r[0], r[1]); return 0; } function crypto_sign_open(m, sm, n, pk) { var i, mlen; var t = new Uint8Array(32), h = new Uint8Array(64); var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; mlen = -1; if (n < 64) return -1; if (unpackneg(q, pk)) return -1; for (i = 0; i < n; i++) m[i] = sm[i]; for (i = 0; i < 32; i++) m[i+32] = pk[i]; crypto_hash(h, m, n); reduce(h); scalarmult(p, q, h); scalarbase(q, sm.subarray(32)); add(p, q); pack(t, p); n -= 64; if (crypto_verify_32(sm, 0, t, 0)) { for (i = 0; i < n; i++) m[i] = 0; return -1; } for (i = 0; i < n; i++) m[i] = sm[i + 64]; mlen = n; return mlen; } var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64; nacl.lowlevel = { crypto_core_hsalsa20: crypto_core_hsalsa20, crypto_stream_xor: crypto_stream_xor, crypto_stream: crypto_stream, crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, crypto_stream_salsa20: crypto_stream_salsa20, crypto_onetimeauth: crypto_onetimeauth, crypto_onetimeauth_verify: crypto_onetimeauth_verify, crypto_verify_16: crypto_verify_16, crypto_verify_32: crypto_verify_32, crypto_secretbox: crypto_secretbox, crypto_secretbox_open: crypto_secretbox_open, crypto_scalarmult: crypto_scalarmult, crypto_scalarmult_base: crypto_scalarmult_base, crypto_box_beforenm: crypto_box_beforenm, crypto_box_afternm: crypto_box_afternm, crypto_box: crypto_box, crypto_box_open: crypto_box_open, crypto_box_keypair: crypto_box_keypair, crypto_hash: crypto_hash, crypto_sign: crypto_sign, crypto_sign_keypair: crypto_sign_keypair, crypto_sign_open: crypto_sign_open, crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, crypto_sign_BYTES: crypto_sign_BYTES, crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, crypto_hash_BYTES: crypto_hash_BYTES }; /* High-level API */ function checkLengths(k, n) { if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); } function checkBoxLengths(pk, sk) { if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); } function checkArrayTypes() { var t, i; for (i = 0; i < arguments.length; i++) { if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') throw new TypeError('unexpected type ' + t + ', use Uint8Array'); } } function cleanup(arr) { for (var i = 0; i < arr.length; i++) arr[i] = 0; } // TODO: Completely remove this in v0.15. if (!nacl.util) { nacl.util = {}; nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); }; } nacl.randomBytes = function(n) { var b = new Uint8Array(n); randombytes(b, n); return b; }; nacl.secretbox = function(msg, nonce, key) { checkArrayTypes(msg, nonce, key); checkLengths(key, nonce); var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); var c = new Uint8Array(m.length); for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; crypto_secretbox(c, m, m.length, nonce, key); return c.subarray(crypto_secretbox_BOXZEROBYTES); }; nacl.secretbox.open = function(box, nonce, key) { checkArrayTypes(box, nonce, key); checkLengths(key, nonce); var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); var m = new Uint8Array(c.length); for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; if (c.length < 32) return false; if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; return m.subarray(crypto_secretbox_ZEROBYTES); }; nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; nacl.scalarMult = function(n, p) { checkArrayTypes(n, p); if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); var q = new Uint8Array(crypto_scalarmult_BYTES); crypto_scalarmult(q, n, p); return q; }; nacl.scalarMult.base = function(n) { checkArrayTypes(n); if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); var q = new Uint8Array(crypto_scalarmult_BYTES); crypto_scalarmult_base(q, n); return q; }; nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; nacl.box = function(msg, nonce, publicKey, secretKey) { var k = nacl.box.before(publicKey, secretKey); return nacl.secretbox(msg, nonce, k); }; nacl.box.before = function(publicKey, secretKey) { checkArrayTypes(publicKey, secretKey); checkBoxLengths(publicKey, secretKey); var k = new Uint8Array(crypto_box_BEFORENMBYTES); crypto_box_beforenm(k, publicKey, secretKey); return k; }; nacl.box.after = nacl.secretbox; nacl.box.open = function(msg, nonce, publicKey, secretKey) { var k = nacl.box.before(publicKey, secretKey); return nacl.secretbox.open(msg, nonce, k); }; nacl.box.open.after = nacl.secretbox.open; nacl.box.keyPair = function() { var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); crypto_box_keypair(pk, sk); return {publicKey: pk, secretKey: sk}; }; nacl.box.keyPair.fromSecretKey = function(secretKey) { checkArrayTypes(secretKey); if (secretKey.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); crypto_scalarmult_base(pk, secretKey); return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; }; nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; nacl.box.nonceLength = crypto_box_NONCEBYTES; nacl.box.overheadLength = nacl.secretbox.overheadLength; nacl.sign = function(msg, secretKey) { checkArrayTypes(msg, secretKey); if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error('bad secret key size'); var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); crypto_sign(signedMsg, msg, msg.length, secretKey); return signedMsg; }; nacl.sign.open = function(signedMsg, publicKey) { if (arguments.length !== 2) throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); checkArrayTypes(signedMsg, publicKey); if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error('bad public key size'); var tmp = new Uint8Array(signedMsg.length); var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); if (mlen < 0) return null; var m = new Uint8Array(mlen); for (var i = 0; i < m.length; i++) m[i] = tmp[i]; return m; }; nacl.sign.detached = function(msg, secretKey) { var signedMsg = nacl.sign(msg, secretKey); var sig = new Uint8Array(crypto_sign_BYTES); for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; return sig; }; nacl.sign.detached.verify = function(msg, sig, publicKey) { checkArrayTypes(msg, sig, publicKey); if (sig.length !== crypto_sign_BYTES) throw new Error('bad signature size'); if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error('bad public key size'); var sm = new Uint8Array(crypto_sign_BYTES + msg.length); var m = new Uint8Array(crypto_sign_BYTES + msg.length); var i; for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); }; nacl.sign.keyPair = function() { var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); crypto_sign_keypair(pk, sk); return {publicKey: pk, secretKey: sk}; }; nacl.sign.keyPair.fromSecretKey = function(secretKey) { checkArrayTypes(secretKey); if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error('bad secret key size'); var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; }; nacl.sign.keyPair.fromSeed = function(seed) { checkArrayTypes(seed); if (seed.length !== crypto_sign_SEEDBYTES) throw new Error('bad seed size'); var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); for (var i = 0; i < 32; i++) sk[i] = seed[i]; crypto_sign_keypair(pk, sk, true); return {publicKey: pk, secretKey: sk}; }; nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; nacl.sign.seedLength = crypto_sign_SEEDBYTES; nacl.sign.signatureLength = crypto_sign_BYTES; nacl.hash = function(msg) { checkArrayTypes(msg); var h = new Uint8Array(crypto_hash_BYTES); crypto_hash(h, msg, msg.length); return h; }; nacl.hash.hashLength = crypto_hash_BYTES; nacl.verify = function(x, y) { checkArrayTypes(x, y); // Zero length arguments are considered not equal. if (x.length === 0 || y.length === 0) return false; if (x.length !== y.length) return false; return (vn(x, 0, y, 0, x.length) === 0) ? true : false; }; nacl.setPRNG = function(fn) { randombytes = fn; }; (function() { // Initialize PRNG if environment provides CSPRNG. // If not, methods calling randombytes will throw. var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; if (crypto && crypto.getRandomValues) { // Browsers. var QUOTA = 65536; nacl.setPRNG(function(x, n) { var i, v = new Uint8Array(n); for (i = 0; i < n; i += QUOTA) { crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); } for (i = 0; i < n; i++) x[i] = v[i]; cleanup(v); }); } else if (typeof require !== 'undefined') { // Node.js. crypto = require('crypto'); if (crypto && crypto.randomBytes) { nacl.setPRNG(function(x, n) { var i, v = crypto.randomBytes(n); for (i = 0; i < n; i++) x[i] = v[i]; cleanup(v); }); } } })(); })(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/tweetnacl/nacl.js
nacl.js
(function(nacl) { 'use strict'; // Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. // Public domain. // // Implementation derived from TweetNaCl version 20140427. // See for details: http://tweetnacl.cr.yp.to/ var gf = function(init) { var i, r = new Float64Array(16); if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; return r; }; // Pluggable, initialized in high-level API below. var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; var _0 = new Uint8Array(16); var _9 = new Uint8Array(32); _9[0] = 9; var gf0 = gf(), gf1 = gf([1]), _121665 = gf([0xdb41, 1]), D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); function ts64(x, i, h, l) { x[i] = (h >> 24) & 0xff; x[i+1] = (h >> 16) & 0xff; x[i+2] = (h >> 8) & 0xff; x[i+3] = h & 0xff; x[i+4] = (l >> 24) & 0xff; x[i+5] = (l >> 16) & 0xff; x[i+6] = (l >> 8) & 0xff; x[i+7] = l & 0xff; } function vn(x, xi, y, yi, n) { var i,d = 0; for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; return (1 & ((d - 1) >>> 8)) - 1; } function crypto_verify_16(x, xi, y, yi) { return vn(x,xi,y,yi,16); } function crypto_verify_32(x, xi, y, yi) { return vn(x,xi,y,yi,32); } function core_salsa20(o, p, k, c) { var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u; for (var i = 0; i < 20; i += 2) { u = x0 + x12 | 0; x4 ^= u<<7 | u>>>(32-7); u = x4 + x0 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x4 | 0; x12 ^= u<<13 | u>>>(32-13); u = x12 + x8 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x1 | 0; x9 ^= u<<7 | u>>>(32-7); u = x9 + x5 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x9 | 0; x1 ^= u<<13 | u>>>(32-13); u = x1 + x13 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x6 | 0; x14 ^= u<<7 | u>>>(32-7); u = x14 + x10 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x14 | 0; x6 ^= u<<13 | u>>>(32-13); u = x6 + x2 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x11 | 0; x3 ^= u<<7 | u>>>(32-7); u = x3 + x15 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x3 | 0; x11 ^= u<<13 | u>>>(32-13); u = x11 + x7 | 0; x15 ^= u<<18 | u>>>(32-18); u = x0 + x3 | 0; x1 ^= u<<7 | u>>>(32-7); u = x1 + x0 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x1 | 0; x3 ^= u<<13 | u>>>(32-13); u = x3 + x2 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x4 | 0; x6 ^= u<<7 | u>>>(32-7); u = x6 + x5 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x6 | 0; x4 ^= u<<13 | u>>>(32-13); u = x4 + x7 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x9 | 0; x11 ^= u<<7 | u>>>(32-7); u = x11 + x10 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x11 | 0; x9 ^= u<<13 | u>>>(32-13); u = x9 + x8 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x14 | 0; x12 ^= u<<7 | u>>>(32-7); u = x12 + x15 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x12 | 0; x14 ^= u<<13 | u>>>(32-13); u = x14 + x13 | 0; x15 ^= u<<18 | u>>>(32-18); } x0 = x0 + j0 | 0; x1 = x1 + j1 | 0; x2 = x2 + j2 | 0; x3 = x3 + j3 | 0; x4 = x4 + j4 | 0; x5 = x5 + j5 | 0; x6 = x6 + j6 | 0; x7 = x7 + j7 | 0; x8 = x8 + j8 | 0; x9 = x9 + j9 | 0; x10 = x10 + j10 | 0; x11 = x11 + j11 | 0; x12 = x12 + j12 | 0; x13 = x13 + j13 | 0; x14 = x14 + j14 | 0; x15 = x15 + j15 | 0; o[ 0] = x0 >>> 0 & 0xff; o[ 1] = x0 >>> 8 & 0xff; o[ 2] = x0 >>> 16 & 0xff; o[ 3] = x0 >>> 24 & 0xff; o[ 4] = x1 >>> 0 & 0xff; o[ 5] = x1 >>> 8 & 0xff; o[ 6] = x1 >>> 16 & 0xff; o[ 7] = x1 >>> 24 & 0xff; o[ 8] = x2 >>> 0 & 0xff; o[ 9] = x2 >>> 8 & 0xff; o[10] = x2 >>> 16 & 0xff; o[11] = x2 >>> 24 & 0xff; o[12] = x3 >>> 0 & 0xff; o[13] = x3 >>> 8 & 0xff; o[14] = x3 >>> 16 & 0xff; o[15] = x3 >>> 24 & 0xff; o[16] = x4 >>> 0 & 0xff; o[17] = x4 >>> 8 & 0xff; o[18] = x4 >>> 16 & 0xff; o[19] = x4 >>> 24 & 0xff; o[20] = x5 >>> 0 & 0xff; o[21] = x5 >>> 8 & 0xff; o[22] = x5 >>> 16 & 0xff; o[23] = x5 >>> 24 & 0xff; o[24] = x6 >>> 0 & 0xff; o[25] = x6 >>> 8 & 0xff; o[26] = x6 >>> 16 & 0xff; o[27] = x6 >>> 24 & 0xff; o[28] = x7 >>> 0 & 0xff; o[29] = x7 >>> 8 & 0xff; o[30] = x7 >>> 16 & 0xff; o[31] = x7 >>> 24 & 0xff; o[32] = x8 >>> 0 & 0xff; o[33] = x8 >>> 8 & 0xff; o[34] = x8 >>> 16 & 0xff; o[35] = x8 >>> 24 & 0xff; o[36] = x9 >>> 0 & 0xff; o[37] = x9 >>> 8 & 0xff; o[38] = x9 >>> 16 & 0xff; o[39] = x9 >>> 24 & 0xff; o[40] = x10 >>> 0 & 0xff; o[41] = x10 >>> 8 & 0xff; o[42] = x10 >>> 16 & 0xff; o[43] = x10 >>> 24 & 0xff; o[44] = x11 >>> 0 & 0xff; o[45] = x11 >>> 8 & 0xff; o[46] = x11 >>> 16 & 0xff; o[47] = x11 >>> 24 & 0xff; o[48] = x12 >>> 0 & 0xff; o[49] = x12 >>> 8 & 0xff; o[50] = x12 >>> 16 & 0xff; o[51] = x12 >>> 24 & 0xff; o[52] = x13 >>> 0 & 0xff; o[53] = x13 >>> 8 & 0xff; o[54] = x13 >>> 16 & 0xff; o[55] = x13 >>> 24 & 0xff; o[56] = x14 >>> 0 & 0xff; o[57] = x14 >>> 8 & 0xff; o[58] = x14 >>> 16 & 0xff; o[59] = x14 >>> 24 & 0xff; o[60] = x15 >>> 0 & 0xff; o[61] = x15 >>> 8 & 0xff; o[62] = x15 >>> 16 & 0xff; o[63] = x15 >>> 24 & 0xff; } function core_hsalsa20(o,p,k,c) { var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u; for (var i = 0; i < 20; i += 2) { u = x0 + x12 | 0; x4 ^= u<<7 | u>>>(32-7); u = x4 + x0 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x4 | 0; x12 ^= u<<13 | u>>>(32-13); u = x12 + x8 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x1 | 0; x9 ^= u<<7 | u>>>(32-7); u = x9 + x5 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x9 | 0; x1 ^= u<<13 | u>>>(32-13); u = x1 + x13 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x6 | 0; x14 ^= u<<7 | u>>>(32-7); u = x14 + x10 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x14 | 0; x6 ^= u<<13 | u>>>(32-13); u = x6 + x2 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x11 | 0; x3 ^= u<<7 | u>>>(32-7); u = x3 + x15 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x3 | 0; x11 ^= u<<13 | u>>>(32-13); u = x11 + x7 | 0; x15 ^= u<<18 | u>>>(32-18); u = x0 + x3 | 0; x1 ^= u<<7 | u>>>(32-7); u = x1 + x0 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x1 | 0; x3 ^= u<<13 | u>>>(32-13); u = x3 + x2 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x4 | 0; x6 ^= u<<7 | u>>>(32-7); u = x6 + x5 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x6 | 0; x4 ^= u<<13 | u>>>(32-13); u = x4 + x7 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x9 | 0; x11 ^= u<<7 | u>>>(32-7); u = x11 + x10 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x11 | 0; x9 ^= u<<13 | u>>>(32-13); u = x9 + x8 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x14 | 0; x12 ^= u<<7 | u>>>(32-7); u = x12 + x15 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x12 | 0; x14 ^= u<<13 | u>>>(32-13); u = x14 + x13 | 0; x15 ^= u<<18 | u>>>(32-18); } o[ 0] = x0 >>> 0 & 0xff; o[ 1] = x0 >>> 8 & 0xff; o[ 2] = x0 >>> 16 & 0xff; o[ 3] = x0 >>> 24 & 0xff; o[ 4] = x5 >>> 0 & 0xff; o[ 5] = x5 >>> 8 & 0xff; o[ 6] = x5 >>> 16 & 0xff; o[ 7] = x5 >>> 24 & 0xff; o[ 8] = x10 >>> 0 & 0xff; o[ 9] = x10 >>> 8 & 0xff; o[10] = x10 >>> 16 & 0xff; o[11] = x10 >>> 24 & 0xff; o[12] = x15 >>> 0 & 0xff; o[13] = x15 >>> 8 & 0xff; o[14] = x15 >>> 16 & 0xff; o[15] = x15 >>> 24 & 0xff; o[16] = x6 >>> 0 & 0xff; o[17] = x6 >>> 8 & 0xff; o[18] = x6 >>> 16 & 0xff; o[19] = x6 >>> 24 & 0xff; o[20] = x7 >>> 0 & 0xff; o[21] = x7 >>> 8 & 0xff; o[22] = x7 >>> 16 & 0xff; o[23] = x7 >>> 24 & 0xff; o[24] = x8 >>> 0 & 0xff; o[25] = x8 >>> 8 & 0xff; o[26] = x8 >>> 16 & 0xff; o[27] = x8 >>> 24 & 0xff; o[28] = x9 >>> 0 & 0xff; o[29] = x9 >>> 8 & 0xff; o[30] = x9 >>> 16 & 0xff; o[31] = x9 >>> 24 & 0xff; } function crypto_core_salsa20(out,inp,k,c) { core_salsa20(out,inp,k,c); } function crypto_core_hsalsa20(out,inp,k,c) { core_hsalsa20(out,inp,k,c); } var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); // "expand 32-byte k" function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { var z = new Uint8Array(16), x = new Uint8Array(64); var u, i; for (i = 0; i < 16; i++) z[i] = 0; for (i = 0; i < 8; i++) z[i] = n[i]; while (b >= 64) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; u = 1; for (i = 8; i < 16; i++) { u = u + (z[i] & 0xff) | 0; z[i] = u & 0xff; u >>>= 8; } b -= 64; cpos += 64; mpos += 64; } if (b > 0) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; } return 0; } function crypto_stream_salsa20(c,cpos,b,n,k) { var z = new Uint8Array(16), x = new Uint8Array(64); var u, i; for (i = 0; i < 16; i++) z[i] = 0; for (i = 0; i < 8; i++) z[i] = n[i]; while (b >= 64) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < 64; i++) c[cpos+i] = x[i]; u = 1; for (i = 8; i < 16; i++) { u = u + (z[i] & 0xff) | 0; z[i] = u & 0xff; u >>>= 8; } b -= 64; cpos += 64; } if (b > 0) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < b; i++) c[cpos+i] = x[i]; } return 0; } function crypto_stream(c,cpos,d,n,k) { var s = new Uint8Array(32); crypto_core_hsalsa20(s,n,k,sigma); var sn = new Uint8Array(8); for (var i = 0; i < 8; i++) sn[i] = n[i+16]; return crypto_stream_salsa20(c,cpos,d,sn,s); } function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { var s = new Uint8Array(32); crypto_core_hsalsa20(s,n,k,sigma); var sn = new Uint8Array(8); for (var i = 0; i < 8; i++) sn[i] = n[i+16]; return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); } /* * Port of Andrew Moon's Poly1305-donna-16. Public domain. * https://github.com/floodyberry/poly1305-donna */ var poly1305 = function(key) { this.buffer = new Uint8Array(16); this.r = new Uint16Array(10); this.h = new Uint16Array(10); this.pad = new Uint16Array(8); this.leftover = 0; this.fin = 0; var t0, t1, t2, t3, t4, t5, t6, t7; t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; this.r[5] = ((t4 >>> 1)) & 0x1ffe; t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; this.r[9] = ((t7 >>> 5)) & 0x007f; this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; }; poly1305.prototype.blocks = function(m, mpos, bytes) { var hibit = this.fin ? 0 : (1 << 11); var t0, t1, t2, t3, t4, t5, t6, t7, c; var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; var h0 = this.h[0], h1 = this.h[1], h2 = this.h[2], h3 = this.h[3], h4 = this.h[4], h5 = this.h[5], h6 = this.h[6], h7 = this.h[7], h8 = this.h[8], h9 = this.h[9]; var r0 = this.r[0], r1 = this.r[1], r2 = this.r[2], r3 = this.r[3], r4 = this.r[4], r5 = this.r[5], r6 = this.r[6], r7 = this.r[7], r8 = this.r[8], r9 = this.r[9]; while (bytes >= 16) { t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; h5 += ((t4 >>> 1)) & 0x1fff; t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; h9 += ((t7 >>> 5)) | hibit; c = 0; d0 = c; d0 += h0 * r0; d0 += h1 * (5 * r9); d0 += h2 * (5 * r8); d0 += h3 * (5 * r7); d0 += h4 * (5 * r6); c = (d0 >>> 13); d0 &= 0x1fff; d0 += h5 * (5 * r5); d0 += h6 * (5 * r4); d0 += h7 * (5 * r3); d0 += h8 * (5 * r2); d0 += h9 * (5 * r1); c += (d0 >>> 13); d0 &= 0x1fff; d1 = c; d1 += h0 * r1; d1 += h1 * r0; d1 += h2 * (5 * r9); d1 += h3 * (5 * r8); d1 += h4 * (5 * r7); c = (d1 >>> 13); d1 &= 0x1fff; d1 += h5 * (5 * r6); d1 += h6 * (5 * r5); d1 += h7 * (5 * r4); d1 += h8 * (5 * r3); d1 += h9 * (5 * r2); c += (d1 >>> 13); d1 &= 0x1fff; d2 = c; d2 += h0 * r2; d2 += h1 * r1; d2 += h2 * r0; d2 += h3 * (5 * r9); d2 += h4 * (5 * r8); c = (d2 >>> 13); d2 &= 0x1fff; d2 += h5 * (5 * r7); d2 += h6 * (5 * r6); d2 += h7 * (5 * r5); d2 += h8 * (5 * r4); d2 += h9 * (5 * r3); c += (d2 >>> 13); d2 &= 0x1fff; d3 = c; d3 += h0 * r3; d3 += h1 * r2; d3 += h2 * r1; d3 += h3 * r0; d3 += h4 * (5 * r9); c = (d3 >>> 13); d3 &= 0x1fff; d3 += h5 * (5 * r8); d3 += h6 * (5 * r7); d3 += h7 * (5 * r6); d3 += h8 * (5 * r5); d3 += h9 * (5 * r4); c += (d3 >>> 13); d3 &= 0x1fff; d4 = c; d4 += h0 * r4; d4 += h1 * r3; d4 += h2 * r2; d4 += h3 * r1; d4 += h4 * r0; c = (d4 >>> 13); d4 &= 0x1fff; d4 += h5 * (5 * r9); d4 += h6 * (5 * r8); d4 += h7 * (5 * r7); d4 += h8 * (5 * r6); d4 += h9 * (5 * r5); c += (d4 >>> 13); d4 &= 0x1fff; d5 = c; d5 += h0 * r5; d5 += h1 * r4; d5 += h2 * r3; d5 += h3 * r2; d5 += h4 * r1; c = (d5 >>> 13); d5 &= 0x1fff; d5 += h5 * r0; d5 += h6 * (5 * r9); d5 += h7 * (5 * r8); d5 += h8 * (5 * r7); d5 += h9 * (5 * r6); c += (d5 >>> 13); d5 &= 0x1fff; d6 = c; d6 += h0 * r6; d6 += h1 * r5; d6 += h2 * r4; d6 += h3 * r3; d6 += h4 * r2; c = (d6 >>> 13); d6 &= 0x1fff; d6 += h5 * r1; d6 += h6 * r0; d6 += h7 * (5 * r9); d6 += h8 * (5 * r8); d6 += h9 * (5 * r7); c += (d6 >>> 13); d6 &= 0x1fff; d7 = c; d7 += h0 * r7; d7 += h1 * r6; d7 += h2 * r5; d7 += h3 * r4; d7 += h4 * r3; c = (d7 >>> 13); d7 &= 0x1fff; d7 += h5 * r2; d7 += h6 * r1; d7 += h7 * r0; d7 += h8 * (5 * r9); d7 += h9 * (5 * r8); c += (d7 >>> 13); d7 &= 0x1fff; d8 = c; d8 += h0 * r8; d8 += h1 * r7; d8 += h2 * r6; d8 += h3 * r5; d8 += h4 * r4; c = (d8 >>> 13); d8 &= 0x1fff; d8 += h5 * r3; d8 += h6 * r2; d8 += h7 * r1; d8 += h8 * r0; d8 += h9 * (5 * r9); c += (d8 >>> 13); d8 &= 0x1fff; d9 = c; d9 += h0 * r9; d9 += h1 * r8; d9 += h2 * r7; d9 += h3 * r6; d9 += h4 * r5; c = (d9 >>> 13); d9 &= 0x1fff; d9 += h5 * r4; d9 += h6 * r3; d9 += h7 * r2; d9 += h8 * r1; d9 += h9 * r0; c += (d9 >>> 13); d9 &= 0x1fff; c = (((c << 2) + c)) | 0; c = (c + d0) | 0; d0 = c & 0x1fff; c = (c >>> 13); d1 += c; h0 = d0; h1 = d1; h2 = d2; h3 = d3; h4 = d4; h5 = d5; h6 = d6; h7 = d7; h8 = d8; h9 = d9; mpos += 16; bytes -= 16; } this.h[0] = h0; this.h[1] = h1; this.h[2] = h2; this.h[3] = h3; this.h[4] = h4; this.h[5] = h5; this.h[6] = h6; this.h[7] = h7; this.h[8] = h8; this.h[9] = h9; }; poly1305.prototype.finish = function(mac, macpos) { var g = new Uint16Array(10); var c, mask, f, i; if (this.leftover) { i = this.leftover; this.buffer[i++] = 1; for (; i < 16; i++) this.buffer[i] = 0; this.fin = 1; this.blocks(this.buffer, 0, 16); } c = this.h[1] >>> 13; this.h[1] &= 0x1fff; for (i = 2; i < 10; i++) { this.h[i] += c; c = this.h[i] >>> 13; this.h[i] &= 0x1fff; } this.h[0] += (c * 5); c = this.h[0] >>> 13; this.h[0] &= 0x1fff; this.h[1] += c; c = this.h[1] >>> 13; this.h[1] &= 0x1fff; this.h[2] += c; g[0] = this.h[0] + 5; c = g[0] >>> 13; g[0] &= 0x1fff; for (i = 1; i < 10; i++) { g[i] = this.h[i] + c; c = g[i] >>> 13; g[i] &= 0x1fff; } g[9] -= (1 << 13); mask = (c ^ 1) - 1; for (i = 0; i < 10; i++) g[i] &= mask; mask = ~mask; for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; f = this.h[0] + this.pad[0]; this.h[0] = f & 0xffff; for (i = 1; i < 8; i++) { f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; this.h[i] = f & 0xffff; } mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; mac[macpos+10] = (this.h[5] >>> 0) & 0xff; mac[macpos+11] = (this.h[5] >>> 8) & 0xff; mac[macpos+12] = (this.h[6] >>> 0) & 0xff; mac[macpos+13] = (this.h[6] >>> 8) & 0xff; mac[macpos+14] = (this.h[7] >>> 0) & 0xff; mac[macpos+15] = (this.h[7] >>> 8) & 0xff; }; poly1305.prototype.update = function(m, mpos, bytes) { var i, want; if (this.leftover) { want = (16 - this.leftover); if (want > bytes) want = bytes; for (i = 0; i < want; i++) this.buffer[this.leftover + i] = m[mpos+i]; bytes -= want; mpos += want; this.leftover += want; if (this.leftover < 16) return; this.blocks(this.buffer, 0, 16); this.leftover = 0; } if (bytes >= 16) { want = bytes - (bytes % 16); this.blocks(m, mpos, want); mpos += want; bytes -= want; } if (bytes) { for (i = 0; i < bytes; i++) this.buffer[this.leftover + i] = m[mpos+i]; this.leftover += bytes; } }; function crypto_onetimeauth(out, outpos, m, mpos, n, k) { var s = new poly1305(k); s.update(m, mpos, n); s.finish(out, outpos); return 0; } function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { var x = new Uint8Array(16); crypto_onetimeauth(x,0,m,mpos,n,k); return crypto_verify_16(h,hpos,x,0); } function crypto_secretbox(c,m,d,n,k) { var i; if (d < 32) return -1; crypto_stream_xor(c,0,m,0,d,n,k); crypto_onetimeauth(c, 16, c, 32, d - 32, c); for (i = 0; i < 16; i++) c[i] = 0; return 0; } function crypto_secretbox_open(m,c,d,n,k) { var i; var x = new Uint8Array(32); if (d < 32) return -1; crypto_stream(x,0,32,n,k); if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; crypto_stream_xor(m,0,c,0,d,n,k); for (i = 0; i < 32; i++) m[i] = 0; return 0; } function set25519(r, a) { var i; for (i = 0; i < 16; i++) r[i] = a[i]|0; } function car25519(o) { var i, v, c = 1; for (i = 0; i < 16; i++) { v = o[i] + c + 65535; c = Math.floor(v / 65536); o[i] = v - c * 65536; } o[0] += c-1 + 37 * (c-1); } function sel25519(p, q, b) { var t, c = ~(b-1); for (var i = 0; i < 16; i++) { t = c & (p[i] ^ q[i]); p[i] ^= t; q[i] ^= t; } } function pack25519(o, n) { var i, j, b; var m = gf(), t = gf(); for (i = 0; i < 16; i++) t[i] = n[i]; car25519(t); car25519(t); car25519(t); for (j = 0; j < 2; j++) { m[0] = t[0] - 0xffed; for (i = 1; i < 15; i++) { m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); m[i-1] &= 0xffff; } m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); b = (m[15]>>16) & 1; m[14] &= 0xffff; sel25519(t, m, 1-b); } for (i = 0; i < 16; i++) { o[2*i] = t[i] & 0xff; o[2*i+1] = t[i]>>8; } } function neq25519(a, b) { var c = new Uint8Array(32), d = new Uint8Array(32); pack25519(c, a); pack25519(d, b); return crypto_verify_32(c, 0, d, 0); } function par25519(a) { var d = new Uint8Array(32); pack25519(d, a); return d[0] & 1; } function unpack25519(o, n) { var i; for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); o[15] &= 0x7fff; } function A(o, a, b) { for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; } function Z(o, a, b) { for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; } function M(o, a, b) { var v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15]; v = a[0]; t0 += v * b0; t1 += v * b1; t2 += v * b2; t3 += v * b3; t4 += v * b4; t5 += v * b5; t6 += v * b6; t7 += v * b7; t8 += v * b8; t9 += v * b9; t10 += v * b10; t11 += v * b11; t12 += v * b12; t13 += v * b13; t14 += v * b14; t15 += v * b15; v = a[1]; t1 += v * b0; t2 += v * b1; t3 += v * b2; t4 += v * b3; t5 += v * b4; t6 += v * b5; t7 += v * b6; t8 += v * b7; t9 += v * b8; t10 += v * b9; t11 += v * b10; t12 += v * b11; t13 += v * b12; t14 += v * b13; t15 += v * b14; t16 += v * b15; v = a[2]; t2 += v * b0; t3 += v * b1; t4 += v * b2; t5 += v * b3; t6 += v * b4; t7 += v * b5; t8 += v * b6; t9 += v * b7; t10 += v * b8; t11 += v * b9; t12 += v * b10; t13 += v * b11; t14 += v * b12; t15 += v * b13; t16 += v * b14; t17 += v * b15; v = a[3]; t3 += v * b0; t4 += v * b1; t5 += v * b2; t6 += v * b3; t7 += v * b4; t8 += v * b5; t9 += v * b6; t10 += v * b7; t11 += v * b8; t12 += v * b9; t13 += v * b10; t14 += v * b11; t15 += v * b12; t16 += v * b13; t17 += v * b14; t18 += v * b15; v = a[4]; t4 += v * b0; t5 += v * b1; t6 += v * b2; t7 += v * b3; t8 += v * b4; t9 += v * b5; t10 += v * b6; t11 += v * b7; t12 += v * b8; t13 += v * b9; t14 += v * b10; t15 += v * b11; t16 += v * b12; t17 += v * b13; t18 += v * b14; t19 += v * b15; v = a[5]; t5 += v * b0; t6 += v * b1; t7 += v * b2; t8 += v * b3; t9 += v * b4; t10 += v * b5; t11 += v * b6; t12 += v * b7; t13 += v * b8; t14 += v * b9; t15 += v * b10; t16 += v * b11; t17 += v * b12; t18 += v * b13; t19 += v * b14; t20 += v * b15; v = a[6]; t6 += v * b0; t7 += v * b1; t8 += v * b2; t9 += v * b3; t10 += v * b4; t11 += v * b5; t12 += v * b6; t13 += v * b7; t14 += v * b8; t15 += v * b9; t16 += v * b10; t17 += v * b11; t18 += v * b12; t19 += v * b13; t20 += v * b14; t21 += v * b15; v = a[7]; t7 += v * b0; t8 += v * b1; t9 += v * b2; t10 += v * b3; t11 += v * b4; t12 += v * b5; t13 += v * b6; t14 += v * b7; t15 += v * b8; t16 += v * b9; t17 += v * b10; t18 += v * b11; t19 += v * b12; t20 += v * b13; t21 += v * b14; t22 += v * b15; v = a[8]; t8 += v * b0; t9 += v * b1; t10 += v * b2; t11 += v * b3; t12 += v * b4; t13 += v * b5; t14 += v * b6; t15 += v * b7; t16 += v * b8; t17 += v * b9; t18 += v * b10; t19 += v * b11; t20 += v * b12; t21 += v * b13; t22 += v * b14; t23 += v * b15; v = a[9]; t9 += v * b0; t10 += v * b1; t11 += v * b2; t12 += v * b3; t13 += v * b4; t14 += v * b5; t15 += v * b6; t16 += v * b7; t17 += v * b8; t18 += v * b9; t19 += v * b10; t20 += v * b11; t21 += v * b12; t22 += v * b13; t23 += v * b14; t24 += v * b15; v = a[10]; t10 += v * b0; t11 += v * b1; t12 += v * b2; t13 += v * b3; t14 += v * b4; t15 += v * b5; t16 += v * b6; t17 += v * b7; t18 += v * b8; t19 += v * b9; t20 += v * b10; t21 += v * b11; t22 += v * b12; t23 += v * b13; t24 += v * b14; t25 += v * b15; v = a[11]; t11 += v * b0; t12 += v * b1; t13 += v * b2; t14 += v * b3; t15 += v * b4; t16 += v * b5; t17 += v * b6; t18 += v * b7; t19 += v * b8; t20 += v * b9; t21 += v * b10; t22 += v * b11; t23 += v * b12; t24 += v * b13; t25 += v * b14; t26 += v * b15; v = a[12]; t12 += v * b0; t13 += v * b1; t14 += v * b2; t15 += v * b3; t16 += v * b4; t17 += v * b5; t18 += v * b6; t19 += v * b7; t20 += v * b8; t21 += v * b9; t22 += v * b10; t23 += v * b11; t24 += v * b12; t25 += v * b13; t26 += v * b14; t27 += v * b15; v = a[13]; t13 += v * b0; t14 += v * b1; t15 += v * b2; t16 += v * b3; t17 += v * b4; t18 += v * b5; t19 += v * b6; t20 += v * b7; t21 += v * b8; t22 += v * b9; t23 += v * b10; t24 += v * b11; t25 += v * b12; t26 += v * b13; t27 += v * b14; t28 += v * b15; v = a[14]; t14 += v * b0; t15 += v * b1; t16 += v * b2; t17 += v * b3; t18 += v * b4; t19 += v * b5; t20 += v * b6; t21 += v * b7; t22 += v * b8; t23 += v * b9; t24 += v * b10; t25 += v * b11; t26 += v * b12; t27 += v * b13; t28 += v * b14; t29 += v * b15; v = a[15]; t15 += v * b0; t16 += v * b1; t17 += v * b2; t18 += v * b3; t19 += v * b4; t20 += v * b5; t21 += v * b6; t22 += v * b7; t23 += v * b8; t24 += v * b9; t25 += v * b10; t26 += v * b11; t27 += v * b12; t28 += v * b13; t29 += v * b14; t30 += v * b15; t0 += 38 * t16; t1 += 38 * t17; t2 += 38 * t18; t3 += 38 * t19; t4 += 38 * t20; t5 += 38 * t21; t6 += 38 * t22; t7 += 38 * t23; t8 += 38 * t24; t9 += 38 * t25; t10 += 38 * t26; t11 += 38 * t27; t12 += 38 * t28; t13 += 38 * t29; t14 += 38 * t30; // t15 left as is // first car c = 1; v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; t0 += c-1 + 37 * (c-1); // second car c = 1; v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; t0 += c-1 + 37 * (c-1); o[ 0] = t0; o[ 1] = t1; o[ 2] = t2; o[ 3] = t3; o[ 4] = t4; o[ 5] = t5; o[ 6] = t6; o[ 7] = t7; o[ 8] = t8; o[ 9] = t9; o[10] = t10; o[11] = t11; o[12] = t12; o[13] = t13; o[14] = t14; o[15] = t15; } function S(o, a) { M(o, a, a); } function inv25519(o, i) { var c = gf(); var a; for (a = 0; a < 16; a++) c[a] = i[a]; for (a = 253; a >= 0; a--) { S(c, c); if(a !== 2 && a !== 4) M(c, c, i); } for (a = 0; a < 16; a++) o[a] = c[a]; } function pow2523(o, i) { var c = gf(); var a; for (a = 0; a < 16; a++) c[a] = i[a]; for (a = 250; a >= 0; a--) { S(c, c); if(a !== 1) M(c, c, i); } for (a = 0; a < 16; a++) o[a] = c[a]; } function crypto_scalarmult(q, n, p) { var z = new Uint8Array(32); var x = new Float64Array(80), r, i; var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(); for (i = 0; i < 31; i++) z[i] = n[i]; z[31]=(n[31]&127)|64; z[0]&=248; unpack25519(x,p); for (i = 0; i < 16; i++) { b[i]=x[i]; d[i]=a[i]=c[i]=0; } a[0]=d[0]=1; for (i=254; i>=0; --i) { r=(z[i>>>3]>>>(i&7))&1; sel25519(a,b,r); sel25519(c,d,r); A(e,a,c); Z(a,a,c); A(c,b,d); Z(b,b,d); S(d,e); S(f,a); M(a,c,a); M(c,b,e); A(e,a,c); Z(a,a,c); S(b,a); Z(c,d,f); M(a,c,_121665); A(a,a,d); M(c,c,a); M(a,d,f); M(d,b,x); S(b,e); sel25519(a,b,r); sel25519(c,d,r); } for (i = 0; i < 16; i++) { x[i+16]=a[i]; x[i+32]=c[i]; x[i+48]=b[i]; x[i+64]=d[i]; } var x32 = x.subarray(32); var x16 = x.subarray(16); inv25519(x32,x32); M(x16,x16,x32); pack25519(q,x16); return 0; } function crypto_scalarmult_base(q, n) { return crypto_scalarmult(q, n, _9); } function crypto_box_keypair(y, x) { randombytes(x, 32); return crypto_scalarmult_base(y, x); } function crypto_box_beforenm(k, y, x) { var s = new Uint8Array(32); crypto_scalarmult(s, x, y); return crypto_core_hsalsa20(k, _0, s, sigma); } var crypto_box_afternm = crypto_secretbox; var crypto_box_open_afternm = crypto_secretbox_open; function crypto_box(c, m, d, n, y, x) { var k = new Uint8Array(32); crypto_box_beforenm(k, y, x); return crypto_box_afternm(c, m, d, n, k); } function crypto_box_open(m, c, d, n, y, x) { var k = new Uint8Array(32); crypto_box_beforenm(k, y, x); return crypto_box_open_afternm(m, c, d, n, k); } var K = [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ]; function crypto_hashblocks_hl(hh, hl, m, n) { var wh = new Int32Array(16), wl = new Int32Array(16), bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i, j, h, l, a, b, c, d; var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7]; var pos = 0; while (n >= 128) { for (i = 0; i < 16; i++) { j = 8 * i + pos; wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; } for (i = 0; i < 80; i++) { bh0 = ah0; bh1 = ah1; bh2 = ah2; bh3 = ah3; bh4 = ah4; bh5 = ah5; bh6 = ah6; bh7 = ah7; bl0 = al0; bl1 = al1; bl2 = al2; bl3 = al3; bl4 = al4; bl5 = al5; bl6 = al6; bl7 = al7; // add h = ah7; l = al7; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; // Sigma1 h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // Ch h = (ah4 & ah5) ^ (~ah4 & ah6); l = (al4 & al5) ^ (~al4 & al6); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // K h = K[i*2]; l = K[i*2+1]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // w h = wh[i%16]; l = wl[i%16]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; th = c & 0xffff | d << 16; tl = a & 0xffff | b << 16; // add h = th; l = tl; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; // Sigma0 h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // Maj h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; bh7 = (c & 0xffff) | (d << 16); bl7 = (a & 0xffff) | (b << 16); // add h = bh3; l = bl3; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = th; l = tl; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; bh3 = (c & 0xffff) | (d << 16); bl3 = (a & 0xffff) | (b << 16); ah1 = bh0; ah2 = bh1; ah3 = bh2; ah4 = bh3; ah5 = bh4; ah6 = bh5; ah7 = bh6; ah0 = bh7; al1 = bl0; al2 = bl1; al3 = bl2; al4 = bl3; al5 = bl4; al6 = bl5; al7 = bl6; al0 = bl7; if (i%16 === 15) { for (j = 0; j < 16; j++) { // add h = wh[j]; l = wl[j]; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = wh[(j+9)%16]; l = wl[(j+9)%16]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // sigma0 th = wh[(j+1)%16]; tl = wl[(j+1)%16]; h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // sigma1 th = wh[(j+14)%16]; tl = wl[(j+14)%16]; h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; wh[j] = (c & 0xffff) | (d << 16); wl[j] = (a & 0xffff) | (b << 16); } } } // add h = ah0; l = al0; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[0]; l = hl[0]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[0] = ah0 = (c & 0xffff) | (d << 16); hl[0] = al0 = (a & 0xffff) | (b << 16); h = ah1; l = al1; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[1]; l = hl[1]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[1] = ah1 = (c & 0xffff) | (d << 16); hl[1] = al1 = (a & 0xffff) | (b << 16); h = ah2; l = al2; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[2]; l = hl[2]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[2] = ah2 = (c & 0xffff) | (d << 16); hl[2] = al2 = (a & 0xffff) | (b << 16); h = ah3; l = al3; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[3]; l = hl[3]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[3] = ah3 = (c & 0xffff) | (d << 16); hl[3] = al3 = (a & 0xffff) | (b << 16); h = ah4; l = al4; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[4]; l = hl[4]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[4] = ah4 = (c & 0xffff) | (d << 16); hl[4] = al4 = (a & 0xffff) | (b << 16); h = ah5; l = al5; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[5]; l = hl[5]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[5] = ah5 = (c & 0xffff) | (d << 16); hl[5] = al5 = (a & 0xffff) | (b << 16); h = ah6; l = al6; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[6]; l = hl[6]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[6] = ah6 = (c & 0xffff) | (d << 16); hl[6] = al6 = (a & 0xffff) | (b << 16); h = ah7; l = al7; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[7]; l = hl[7]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[7] = ah7 = (c & 0xffff) | (d << 16); hl[7] = al7 = (a & 0xffff) | (b << 16); pos += 128; n -= 128; } return n; } function crypto_hash(out, m, n) { var hh = new Int32Array(8), hl = new Int32Array(8), x = new Uint8Array(256), i, b = n; hh[0] = 0x6a09e667; hh[1] = 0xbb67ae85; hh[2] = 0x3c6ef372; hh[3] = 0xa54ff53a; hh[4] = 0x510e527f; hh[5] = 0x9b05688c; hh[6] = 0x1f83d9ab; hh[7] = 0x5be0cd19; hl[0] = 0xf3bcc908; hl[1] = 0x84caa73b; hl[2] = 0xfe94f82b; hl[3] = 0x5f1d36f1; hl[4] = 0xade682d1; hl[5] = 0x2b3e6c1f; hl[6] = 0xfb41bd6b; hl[7] = 0x137e2179; crypto_hashblocks_hl(hh, hl, m, n); n %= 128; for (i = 0; i < n; i++) x[i] = m[b-n+i]; x[n] = 128; n = 256-128*(n<112?1:0); x[n-9] = 0; ts64(x, n-8, (b / 0x20000000) | 0, b << 3); crypto_hashblocks_hl(hh, hl, x, n); for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); return 0; } function add(p, q) { var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf(); Z(a, p[1], p[0]); Z(t, q[1], q[0]); M(a, a, t); A(b, p[0], p[1]); A(t, q[0], q[1]); M(b, b, t); M(c, p[3], q[3]); M(c, c, D2); M(d, p[2], q[2]); A(d, d, d); Z(e, b, a); Z(f, d, c); A(g, d, c); A(h, b, a); M(p[0], e, f); M(p[1], h, g); M(p[2], g, f); M(p[3], e, h); } function cswap(p, q, b) { var i; for (i = 0; i < 4; i++) { sel25519(p[i], q[i], b); } } function pack(r, p) { var tx = gf(), ty = gf(), zi = gf(); inv25519(zi, p[2]); M(tx, p[0], zi); M(ty, p[1], zi); pack25519(r, ty); r[31] ^= par25519(tx) << 7; } function scalarmult(p, q, s) { var b, i; set25519(p[0], gf0); set25519(p[1], gf1); set25519(p[2], gf1); set25519(p[3], gf0); for (i = 255; i >= 0; --i) { b = (s[(i/8)|0] >> (i&7)) & 1; cswap(p, q, b); add(q, p); add(p, p); cswap(p, q, b); } } function scalarbase(p, s) { var q = [gf(), gf(), gf(), gf()]; set25519(q[0], X); set25519(q[1], Y); set25519(q[2], gf1); M(q[3], X, Y); scalarmult(p, q, s); } function crypto_sign_keypair(pk, sk, seeded) { var d = new Uint8Array(64); var p = [gf(), gf(), gf(), gf()]; var i; if (!seeded) randombytes(sk, 32); crypto_hash(d, sk, 32); d[0] &= 248; d[31] &= 127; d[31] |= 64; scalarbase(p, d); pack(pk, p); for (i = 0; i < 32; i++) sk[i+32] = pk[i]; return 0; } var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); function modL(r, x) { var carry, i, j, k; for (i = 63; i >= 32; --i) { carry = 0; for (j = i - 32, k = i - 12; j < k; ++j) { x[j] += carry - 16 * x[i] * L[j - (i - 32)]; carry = (x[j] + 128) >> 8; x[j] -= carry * 256; } x[j] += carry; x[i] = 0; } carry = 0; for (j = 0; j < 32; j++) { x[j] += carry - (x[31] >> 4) * L[j]; carry = x[j] >> 8; x[j] &= 255; } for (j = 0; j < 32; j++) x[j] -= carry * L[j]; for (i = 0; i < 32; i++) { x[i+1] += x[i] >> 8; r[i] = x[i] & 255; } } function reduce(r) { var x = new Float64Array(64), i; for (i = 0; i < 64; i++) x[i] = r[i]; for (i = 0; i < 64; i++) r[i] = 0; modL(r, x); } // Note: difference from C - smlen returned, not passed as argument. function crypto_sign(sm, m, n, sk) { var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); var i, j, x = new Float64Array(64); var p = [gf(), gf(), gf(), gf()]; crypto_hash(d, sk, 32); d[0] &= 248; d[31] &= 127; d[31] |= 64; var smlen = n + 64; for (i = 0; i < n; i++) sm[64 + i] = m[i]; for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; crypto_hash(r, sm.subarray(32), n+32); reduce(r); scalarbase(p, r); pack(sm, p); for (i = 32; i < 64; i++) sm[i] = sk[i]; crypto_hash(h, sm, n + 64); reduce(h); for (i = 0; i < 64; i++) x[i] = 0; for (i = 0; i < 32; i++) x[i] = r[i]; for (i = 0; i < 32; i++) { for (j = 0; j < 32; j++) { x[i+j] += h[i] * d[j]; } } modL(sm.subarray(32), x); return smlen; } function unpackneg(r, p) { var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); set25519(r[2], gf1); unpack25519(r[1], p); S(num, r[1]); M(den, num, D); Z(num, num, r[2]); A(den, r[2], den); S(den2, den); S(den4, den2); M(den6, den4, den2); M(t, den6, num); M(t, t, den); pow2523(t, t); M(t, t, num); M(t, t, den); M(t, t, den); M(r[0], t, den); S(chk, r[0]); M(chk, chk, den); if (neq25519(chk, num)) M(r[0], r[0], I); S(chk, r[0]); M(chk, chk, den); if (neq25519(chk, num)) return -1; if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); M(r[3], r[0], r[1]); return 0; } function crypto_sign_open(m, sm, n, pk) { var i, mlen; var t = new Uint8Array(32), h = new Uint8Array(64); var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; mlen = -1; if (n < 64) return -1; if (unpackneg(q, pk)) return -1; for (i = 0; i < n; i++) m[i] = sm[i]; for (i = 0; i < 32; i++) m[i+32] = pk[i]; crypto_hash(h, m, n); reduce(h); scalarmult(p, q, h); scalarbase(q, sm.subarray(32)); add(p, q); pack(t, p); n -= 64; if (crypto_verify_32(sm, 0, t, 0)) { for (i = 0; i < n; i++) m[i] = 0; return -1; } for (i = 0; i < n; i++) m[i] = sm[i + 64]; mlen = n; return mlen; } var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64; nacl.lowlevel = { crypto_core_hsalsa20: crypto_core_hsalsa20, crypto_stream_xor: crypto_stream_xor, crypto_stream: crypto_stream, crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, crypto_stream_salsa20: crypto_stream_salsa20, crypto_onetimeauth: crypto_onetimeauth, crypto_onetimeauth_verify: crypto_onetimeauth_verify, crypto_verify_16: crypto_verify_16, crypto_verify_32: crypto_verify_32, crypto_secretbox: crypto_secretbox, crypto_secretbox_open: crypto_secretbox_open, crypto_scalarmult: crypto_scalarmult, crypto_scalarmult_base: crypto_scalarmult_base, crypto_box_beforenm: crypto_box_beforenm, crypto_box_afternm: crypto_box_afternm, crypto_box: crypto_box, crypto_box_open: crypto_box_open, crypto_box_keypair: crypto_box_keypair, crypto_hash: crypto_hash, crypto_sign: crypto_sign, crypto_sign_keypair: crypto_sign_keypair, crypto_sign_open: crypto_sign_open, crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, crypto_sign_BYTES: crypto_sign_BYTES, crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, crypto_hash_BYTES: crypto_hash_BYTES }; /* High-level API */ function checkLengths(k, n) { if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); } function checkBoxLengths(pk, sk) { if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); } function checkArrayTypes() { var t, i; for (i = 0; i < arguments.length; i++) { if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') throw new TypeError('unexpected type ' + t + ', use Uint8Array'); } } function cleanup(arr) { for (var i = 0; i < arr.length; i++) arr[i] = 0; } // TODO: Completely remove this in v0.15. if (!nacl.util) { nacl.util = {}; nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); }; } nacl.randomBytes = function(n) { var b = new Uint8Array(n); randombytes(b, n); return b; }; nacl.secretbox = function(msg, nonce, key) { checkArrayTypes(msg, nonce, key); checkLengths(key, nonce); var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); var c = new Uint8Array(m.length); for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; crypto_secretbox(c, m, m.length, nonce, key); return c.subarray(crypto_secretbox_BOXZEROBYTES); }; nacl.secretbox.open = function(box, nonce, key) { checkArrayTypes(box, nonce, key); checkLengths(key, nonce); var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); var m = new Uint8Array(c.length); for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; if (c.length < 32) return false; if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; return m.subarray(crypto_secretbox_ZEROBYTES); }; nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; nacl.scalarMult = function(n, p) { checkArrayTypes(n, p); if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); var q = new Uint8Array(crypto_scalarmult_BYTES); crypto_scalarmult(q, n, p); return q; }; nacl.scalarMult.base = function(n) { checkArrayTypes(n); if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); var q = new Uint8Array(crypto_scalarmult_BYTES); crypto_scalarmult_base(q, n); return q; }; nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; nacl.box = function(msg, nonce, publicKey, secretKey) { var k = nacl.box.before(publicKey, secretKey); return nacl.secretbox(msg, nonce, k); }; nacl.box.before = function(publicKey, secretKey) { checkArrayTypes(publicKey, secretKey); checkBoxLengths(publicKey, secretKey); var k = new Uint8Array(crypto_box_BEFORENMBYTES); crypto_box_beforenm(k, publicKey, secretKey); return k; }; nacl.box.after = nacl.secretbox; nacl.box.open = function(msg, nonce, publicKey, secretKey) { var k = nacl.box.before(publicKey, secretKey); return nacl.secretbox.open(msg, nonce, k); }; nacl.box.open.after = nacl.secretbox.open; nacl.box.keyPair = function() { var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); crypto_box_keypair(pk, sk); return {publicKey: pk, secretKey: sk}; }; nacl.box.keyPair.fromSecretKey = function(secretKey) { checkArrayTypes(secretKey); if (secretKey.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); crypto_scalarmult_base(pk, secretKey); return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; }; nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; nacl.box.nonceLength = crypto_box_NONCEBYTES; nacl.box.overheadLength = nacl.secretbox.overheadLength; nacl.sign = function(msg, secretKey) { checkArrayTypes(msg, secretKey); if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error('bad secret key size'); var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); crypto_sign(signedMsg, msg, msg.length, secretKey); return signedMsg; }; nacl.sign.open = function(signedMsg, publicKey) { if (arguments.length !== 2) throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); checkArrayTypes(signedMsg, publicKey); if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error('bad public key size'); var tmp = new Uint8Array(signedMsg.length); var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); if (mlen < 0) return null; var m = new Uint8Array(mlen); for (var i = 0; i < m.length; i++) m[i] = tmp[i]; return m; }; nacl.sign.detached = function(msg, secretKey) { var signedMsg = nacl.sign(msg, secretKey); var sig = new Uint8Array(crypto_sign_BYTES); for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; return sig; }; nacl.sign.detached.verify = function(msg, sig, publicKey) { checkArrayTypes(msg, sig, publicKey); if (sig.length !== crypto_sign_BYTES) throw new Error('bad signature size'); if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error('bad public key size'); var sm = new Uint8Array(crypto_sign_BYTES + msg.length); var m = new Uint8Array(crypto_sign_BYTES + msg.length); var i; for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); }; nacl.sign.keyPair = function() { var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); crypto_sign_keypair(pk, sk); return {publicKey: pk, secretKey: sk}; }; nacl.sign.keyPair.fromSecretKey = function(secretKey) { checkArrayTypes(secretKey); if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error('bad secret key size'); var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; }; nacl.sign.keyPair.fromSeed = function(seed) { checkArrayTypes(seed); if (seed.length !== crypto_sign_SEEDBYTES) throw new Error('bad seed size'); var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); for (var i = 0; i < 32; i++) sk[i] = seed[i]; crypto_sign_keypair(pk, sk, true); return {publicKey: pk, secretKey: sk}; }; nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; nacl.sign.seedLength = crypto_sign_SEEDBYTES; nacl.sign.signatureLength = crypto_sign_BYTES; nacl.hash = function(msg) { checkArrayTypes(msg); var h = new Uint8Array(crypto_hash_BYTES); crypto_hash(h, msg, msg.length); return h; }; nacl.hash.hashLength = crypto_hash_BYTES; nacl.verify = function(x, y) { checkArrayTypes(x, y); // Zero length arguments are considered not equal. if (x.length === 0 || y.length === 0) return false; if (x.length !== y.length) return false; return (vn(x, 0, y, 0, x.length) === 0) ? true : false; }; nacl.setPRNG = function(fn) { randombytes = fn; }; (function() { // Initialize PRNG if environment provides CSPRNG. // If not, methods calling randombytes will throw. var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; if (crypto && crypto.getRandomValues) { // Browsers. var QUOTA = 65536; nacl.setPRNG(function(x, n) { var i, v = new Uint8Array(n); for (i = 0; i < n; i += QUOTA) { crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); } for (i = 0; i < n; i++) x[i] = v[i]; cleanup(v); }); } else if (typeof require !== 'undefined') { // Node.js. crypto = require('crypto'); if (crypto && crypto.randomBytes) { nacl.setPRNG(function(x, n) { var i, v = crypto.randomBytes(n); for (i = 0; i < n; i++) x[i] = v[i]; cleanup(v); }); } } })(); })(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/tweetnacl/nacl-fast.js
nacl-fast.js
TweetNaCl.js ============ Port of [TweetNaCl](http://tweetnacl.cr.yp.to) / [NaCl](http://nacl.cr.yp.to/) to JavaScript for modern browsers and Node.js. Public domain. [![Build Status](https://travis-ci.org/dchest/tweetnacl-js.svg?branch=master) ](https://travis-ci.org/dchest/tweetnacl-js) Demo: <https://tweetnacl.js.org> **:warning: The library is stable and API is frozen, however it has not been independently reviewed. If you can help reviewing it, please [contact me](mailto:[email protected]).** Documentation ============= * [Overview](#overview) * [Installation](#installation) * [Usage](#usage) * [Public-key authenticated encryption (box)](#public-key-authenticated-encryption-box) * [Secret-key authenticated encryption (secretbox)](#secret-key-authenticated-encryption-secretbox) * [Scalar multiplication](#scalar-multiplication) * [Signatures](#signatures) * [Hashing](#hashing) * [Random bytes generation](#random-bytes-generation) * [Constant-time comparison](#constant-time-comparison) * [System requirements](#system-requirements) * [Development and testing](#development-and-testing) * [Benchmarks](#benchmarks) * [Contributors](#contributors) * [Who uses it](#who-uses-it) Overview -------- The primary goal of this project is to produce a translation of TweetNaCl to JavaScript which is as close as possible to the original C implementation, plus a thin layer of idiomatic high-level API on top of it. There are two versions, you can use either of them: * `nacl.js` is the port of TweetNaCl with minimum differences from the original + high-level API. * `nacl-fast.js` is like `nacl.js`, but with some functions replaced with faster versions. Installation ------------ You can install TweetNaCl.js via a package manager: [Bower](http://bower.io): $ bower install tweetnacl [NPM](https://www.npmjs.org/): $ npm install tweetnacl or [download source code](https://github.com/dchest/tweetnacl-js/releases). Usage ----- All API functions accept and return bytes as `Uint8Array`s. If you need to encode or decode strings, use functions from <https://github.com/dchest/tweetnacl-util-js> or one of the more robust codec packages. In Node.js v4 and later `Buffer` objects are backed by `Uint8Array`s, so you can freely pass them to TweetNaCl.js functions as arguments. The returned objects are still `Uint8Array`s, so if you need `Buffer`s, you'll have to convert them manually; make sure to convert using copying: `new Buffer(array)`, instead of sharing: `new Buffer(array.buffer)`, because some functions return subarrays of their buffers. ### Public-key authenticated encryption (box) Implements *curve25519-xsalsa20-poly1305*. #### nacl.box.keyPair() Generates a new random key pair for box and returns it as an object with `publicKey` and `secretKey` members: { publicKey: ..., // Uint8Array with 32-byte public key secretKey: ... // Uint8Array with 32-byte secret key } #### nacl.box.keyPair.fromSecretKey(secretKey) Returns a key pair for box with public key corresponding to the given secret key. #### nacl.box(message, nonce, theirPublicKey, mySecretKey) Encrypt and authenticates message using peer's public key, our secret key, and the given nonce, which must be unique for each distinct message for a key pair. Returns an encrypted and authenticated message, which is `nacl.box.overheadLength` longer than the original message. #### nacl.box.open(box, nonce, theirPublicKey, mySecretKey) Authenticates and decrypts the given box with peer's public key, our secret key, and the given nonce. Returns the original message, or `false` if authentication fails. #### nacl.box.before(theirPublicKey, mySecretKey) Returns a precomputed shared key which can be used in `nacl.box.after` and `nacl.box.open.after`. #### nacl.box.after(message, nonce, sharedKey) Same as `nacl.box`, but uses a shared key precomputed with `nacl.box.before`. #### nacl.box.open.after(box, nonce, sharedKey) Same as `nacl.box.open`, but uses a shared key precomputed with `nacl.box.before`. #### nacl.box.publicKeyLength = 32 Length of public key in bytes. #### nacl.box.secretKeyLength = 32 Length of secret key in bytes. #### nacl.box.sharedKeyLength = 32 Length of precomputed shared key in bytes. #### nacl.box.nonceLength = 24 Length of nonce in bytes. #### nacl.box.overheadLength = 16 Length of overhead added to box compared to original message. ### Secret-key authenticated encryption (secretbox) Implements *xsalsa20-poly1305*. #### nacl.secretbox(message, nonce, key) Encrypt and authenticates message using the key and the nonce. The nonce must be unique for each distinct message for this key. Returns an encrypted and authenticated message, which is `nacl.secretbox.overheadLength` longer than the original message. #### nacl.secretbox.open(box, nonce, key) Authenticates and decrypts the given secret box using the key and the nonce. Returns the original message, or `false` if authentication fails. #### nacl.secretbox.keyLength = 32 Length of key in bytes. #### nacl.secretbox.nonceLength = 24 Length of nonce in bytes. #### nacl.secretbox.overheadLength = 16 Length of overhead added to secret box compared to original message. ### Scalar multiplication Implements *curve25519*. #### nacl.scalarMult(n, p) Multiplies an integer `n` by a group element `p` and returns the resulting group element. #### nacl.scalarMult.base(n) Multiplies an integer `n` by a standard group element and returns the resulting group element. #### nacl.scalarMult.scalarLength = 32 Length of scalar in bytes. #### nacl.scalarMult.groupElementLength = 32 Length of group element in bytes. ### Signatures Implements [ed25519](http://ed25519.cr.yp.to). #### nacl.sign.keyPair() Generates new random key pair for signing and returns it as an object with `publicKey` and `secretKey` members: { publicKey: ..., // Uint8Array with 32-byte public key secretKey: ... // Uint8Array with 64-byte secret key } #### nacl.sign.keyPair.fromSecretKey(secretKey) Returns a signing key pair with public key corresponding to the given 64-byte secret key. The secret key must have been generated by `nacl.sign.keyPair` or `nacl.sign.keyPair.fromSeed`. #### nacl.sign.keyPair.fromSeed(seed) Returns a new signing key pair generated deterministically from a 32-byte seed. The seed must contain enough entropy to be secure. This method is not recommended for general use: instead, use `nacl.sign.keyPair` to generate a new key pair from a random seed. #### nacl.sign(message, secretKey) Signs the message using the secret key and returns a signed message. #### nacl.sign.open(signedMessage, publicKey) Verifies the signed message and returns the message without signature. Returns `null` if verification failed. #### nacl.sign.detached(message, secretKey) Signs the message using the secret key and returns a signature. #### nacl.sign.detached.verify(message, signature, publicKey) Verifies the signature for the message and returns `true` if verification succeeded or `false` if it failed. #### nacl.sign.publicKeyLength = 32 Length of signing public key in bytes. #### nacl.sign.secretKeyLength = 64 Length of signing secret key in bytes. #### nacl.sign.seedLength = 32 Length of seed for `nacl.sign.keyPair.fromSeed` in bytes. #### nacl.sign.signatureLength = 64 Length of signature in bytes. ### Hashing Implements *SHA-512*. #### nacl.hash(message) Returns SHA-512 hash of the message. #### nacl.hash.hashLength = 64 Length of hash in bytes. ### Random bytes generation #### nacl.randomBytes(length) Returns a `Uint8Array` of the given length containing random bytes of cryptographic quality. **Implementation note** TweetNaCl.js uses the following methods to generate random bytes, depending on the platform it runs on: * `window.crypto.getRandomValues` (WebCrypto standard) * `window.msCrypto.getRandomValues` (Internet Explorer 11) * `crypto.randomBytes` (Node.js) If the platform doesn't provide a suitable PRNG, the following functions, which require random numbers, will throw exception: * `nacl.randomBytes` * `nacl.box.keyPair` * `nacl.sign.keyPair` Other functions are deterministic and will continue working. If a platform you are targeting doesn't implement secure random number generator, but you somehow have a cryptographically-strong source of entropy (not `Math.random`!), and you know what you are doing, you can plug it into TweetNaCl.js like this: nacl.setPRNG(function(x, n) { // ... copy n random bytes into x ... }); Note that `nacl.setPRNG` *completely replaces* internal random byte generator with the one provided. ### Constant-time comparison #### nacl.verify(x, y) Compares `x` and `y` in constant time and returns `true` if their lengths are non-zero and equal, and their contents are equal. Returns `false` if either of the arguments has zero length, or arguments have different lengths, or their contents differ. System requirements ------------------- TweetNaCl.js supports modern browsers that have a cryptographically secure pseudorandom number generator and typed arrays, including the latest versions of: * Chrome * Firefox * Safari (Mac, iOS) * Internet Explorer 11 Other systems: * Node.js Development and testing ------------------------ Install NPM modules needed for development: $ npm install To build minified versions: $ npm run build Tests use minified version, so make sure to rebuild it every time you change `nacl.js` or `nacl-fast.js`. ### Testing To run tests in Node.js: $ npm run test-node By default all tests described here work on `nacl.min.js`. To test other versions, set environment variable `NACL_SRC` to the file name you want to test. For example, the following command will test fast minified version: $ NACL_SRC=nacl-fast.min.js npm run test-node To run full suite of tests in Node.js, including comparing outputs of JavaScript port to outputs of the original C version: $ npm run test-node-all To prepare tests for browsers: $ npm run build-test-browser and then open `test/browser/test.html` (or `test/browser/test-fast.html`) to run them. To run headless browser tests with `tape-run` (powered by Electron): $ npm run test-browser (If you get `Error: spawn ENOENT`, install *xvfb*: `sudo apt-get install xvfb`.) To run tests in both Node and Electron: $ npm test ### Benchmarking To run benchmarks in Node.js: $ npm run bench $ NACL_SRC=nacl-fast.min.js npm run bench To run benchmarks in a browser, open `test/benchmark/bench.html` (or `test/benchmark/bench-fast.html`). Benchmarks ---------- For reference, here are benchmarks from MacBook Pro (Retina, 13-inch, Mid 2014) laptop with 2.6 GHz Intel Core i5 CPU (Intel) in Chrome 53/OS X and Xiaomi Redmi Note 3 smartphone with 1.8 GHz Qualcomm Snapdragon 650 64-bit CPU (ARM) in Chrome 52/Android: | | nacl.js Intel | nacl-fast.js Intel | nacl.js ARM | nacl-fast.js ARM | | ------------- |:-------------:|:-------------------:|:-------------:|:-----------------:| | salsa20 | 1.3 MB/s | 128 MB/s | 0.4 MB/s | 43 MB/s | | poly1305 | 13 MB/s | 171 MB/s | 4 MB/s | 52 MB/s | | hash | 4 MB/s | 34 MB/s | 0.9 MB/s | 12 MB/s | | secretbox 1K | 1113 op/s | 57583 op/s | 334 op/s | 14227 op/s | | box 1K | 145 op/s | 718 op/s | 37 op/s | 368 op/s | | scalarMult | 171 op/s | 733 op/s | 56 op/s | 380 op/s | | sign | 77 op/s | 200 op/s | 20 op/s | 61 op/s | | sign.open | 39 op/s | 102 op/s | 11 op/s | 31 op/s | (You can run benchmarks on your devices by clicking on the links at the bottom of the [home page](https://tweetnacl.js.org)). In short, with *nacl-fast.js* and 1024-byte messages you can expect to encrypt and authenticate more than 57000 messages per second on a typical laptop or more than 14000 messages per second on a $170 smartphone, sign about 200 and verify 100 messages per second on a laptop or 60 and 30 messages per second on a smartphone, per CPU core (with Web Workers you can do these operations in parallel), which is good enough for most applications. Contributors ------------ See AUTHORS.md file. Third-party libraries based on TweetNaCl.js ------------------------------------------- * [forward-secrecy](https://github.com/alax/forward-secrecy) — Axolotl ratchet implementation * [nacl-stream](https://github.com/dchest/nacl-stream-js) - streaming encryption * [tweetnacl-auth-js](https://github.com/dchest/tweetnacl-auth-js) — implementation of [`crypto_auth`](http://nacl.cr.yp.to/auth.html) * [chloride](https://github.com/dominictarr/chloride) - unified API for various NaCl modules Who uses it ----------- Some notable users of TweetNaCl.js: * [miniLock](http://minilock.io/) * [Stellar](https://www.stellar.org/)
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/tweetnacl/README.md
README.md
List of TweetNaCl.js authors ============================ Alphabetical order by first name. Format: Name (GitHub username or URL) * AndSDev (@AndSDev) * Devi Mandiri (@devi) * Dmitry Chestnykh (@dchest) List of authors of third-party public domain code from which TweetNaCl.js code was derived ========================================================================================== [TweetNaCl](http://tweetnacl.cr.yp.to/) -------------------------------------- * Bernard van Gastel * Daniel J. Bernstein <http://cr.yp.to/djb.html> * Peter Schwabe <http://www.cryptojedi.org/users/peter/> * Sjaak Smetsers <http://www.cs.ru.nl/~sjakie/> * Tanja Lange <http://hyperelliptic.org/tanja> * Wesley Janssen [Poly1305-donna](https://github.com/floodyberry/poly1305-donna) -------------------------------------------------------------- * Andrew Moon (@floodyberry)
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/tweetnacl/AUTHORS.md
AUTHORS.md
TweetNaCl.js Changelog ====================== v0.14.5 ------- * Fixed incomplete return types in TypeScript typings. * Replaced COPYING.txt with LICENSE file, which now has public domain dedication text from The Unlicense. License fields in package.json and bower.json have been set to "Unlicense". The project was and will be in the public domain -- this change just makes it easier for automated tools to know about this fact by using the widely recognized and SPDX-compatible template for public domain dedication. v0.14.4 ------- * Added TypeScript type definitions (contributed by @AndSDev). * Improved benchmarking code. v0.14.3 ------- Fixed a bug in the fast version of Poly1305 and brought it back. Thanks to @floodyberry for promptly responding and fixing the original C code: > "The issue was not properly detecting if st->h was >= 2^130 - 5, coupled with > [testing mistake] not catching the failure. The chance of the bug affecting > anything in the real world is essentially zero luckily, but it's good to have > it fixed." https://github.com/floodyberry/poly1305-donna/issues/2#issuecomment-202698577 v0.14.2 ------- Switched Poly1305 fast version back to original (slow) version due to a bug. v0.14.1 ------- No code changes, just tweaked packaging and added COPYING.txt. v0.14.0 ------- * **Breaking change!** All functions from `nacl.util` have been removed. These functions are no longer available: nacl.util.decodeUTF8 nacl.util.encodeUTF8 nacl.util.decodeBase64 nacl.util.encodeBase64 If want to continue using them, you can include <https://github.com/dchest/tweetnacl-util-js> package: <script src="nacl.min.js"></script> <script src="nacl-util.min.js"></script> or var nacl = require('tweetnacl'); nacl.util = require('tweetnacl-util'); However it is recommended to use better packages that have wider compatibility and better performance. Functions from `nacl.util` were never intended to be robust solution for string conversion and were included for convenience: cryptography library is not the right place for them. Currently calling these functions will throw error pointing to `tweetnacl-util-js` (in the next version this error message will be removed). * Improved detection of available random number generators, making it possible to use `nacl.randomBytes` and related functions in Web Workers without changes. * Changes to testing (see README). v0.13.3 ------- No code changes. * Reverted license field in package.json to "Public domain". * Fixed typo in README. v0.13.2 ------- * Fixed undefined variable bug in fast version of Poly1305. No worries, this bug was *never* triggered. * Specified CC0 public domain dedication. * Updated development dependencies. v0.13.1 ------- * Exclude `crypto` and `buffer` modules from browserify builds. v0.13.0 ------- * Made `nacl-fast` the default version in NPM package. Now `require("tweetnacl")` will use fast version; to get the original version, use `require("tweetnacl/nacl.js")`. * Cleanup temporary array after generating random bytes. v0.12.2 ------- * Improved performance of curve operations, making `nacl.scalarMult`, `nacl.box`, `nacl.sign` and related functions up to 3x faster in `nacl-fast` version. v0.12.1 ------- * Significantly improved performance of Salsa20 (~1.5x faster) and Poly1305 (~3.5x faster) in `nacl-fast` version. v0.12.0 ------- * Instead of using the given secret key directly, TweetNaCl.js now copies it to a new array in `nacl.box.keyPair.fromSecretKey` and `nacl.sign.keyPair.fromSecretKey`. v0.11.2 ------- * Added new constant: `nacl.sign.seedLength`. v0.11.1 ------- * Even faster hash for both short and long inputs (in `nacl-fast`). v0.11.0 ------- * Implement `nacl.sign.keyPair.fromSeed` to enable creation of sign key pairs deterministically from a 32-byte seed. (It behaves like [libsodium's](http://doc.libsodium.org/public-key_cryptography/public-key_signatures.html) `crypto_sign_seed_keypair`: the seed becomes a secret part of the secret key.) * Fast version now has an improved hash implementation that is 2x-5x faster. * Fixed benchmarks, which may have produced incorrect measurements. v0.10.1 ------- * Exported undocumented `nacl.lowlevel.crypto_core_hsalsa20`. v0.10.0 ------- * **Signature API breaking change!** `nacl.sign` and `nacl.sign.open` now deal with signed messages, and new `nacl.sign.detached` and `nacl.sign.detached.verify` are available. Previously, `nacl.sign` returned a signature, and `nacl.sign.open` accepted a message and "detached" signature. This was unlike NaCl's API, which dealt with signed messages (concatenation of signature and message). The new API is: nacl.sign(message, secretKey) -> signedMessage nacl.sign.open(signedMessage, publicKey) -> message | null Since detached signatures are common, two new API functions were introduced: nacl.sign.detached(message, secretKey) -> signature nacl.sign.detached.verify(message, signature, publicKey) -> true | false (Note that it's `verify`, not `open`, and it returns a boolean value, unlike `open`, which returns an "unsigned" message.) * NPM package now comes without `test` directory to keep it small. v0.9.2 ------ * Improved documentation. * Fast version: increased theoretical message size limit from 2^32-1 to 2^52 bytes in Poly1305 (and thus, secretbox and box). However this has no impact in practice since JavaScript arrays or ArrayBuffers are limited to 32-bit indexes, and most implementations won't allocate more than a gigabyte or so. (Obviously, there are no tests for the correctness of implementation.) Also, it's not recommended to use messages that large without splitting them into smaller packets anyway. v0.9.1 ------ * Initial release
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/tweetnacl/CHANGELOG.md
CHANGELOG.md
!function(r){"use strict";function t(r,t,n,e){r[t]=n>>24&255,r[t+1]=n>>16&255,r[t+2]=n>>8&255,r[t+3]=255&n,r[t+4]=e>>24&255,r[t+5]=e>>16&255,r[t+6]=e>>8&255,r[t+7]=255&e}function n(r,t,n,e,o){var i,h=0;for(i=0;i<o;i++)h|=r[t+i]^n[e+i];return(1&h-1>>>8)-1}function e(r,t,e,o){return n(r,t,e,o,16)}function o(r,t,e,o){return n(r,t,e,o,32)}function i(r,t,n,e){for(var o,i=255&e[0]|(255&e[1])<<8|(255&e[2])<<16|(255&e[3])<<24,h=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,s=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,c=255&e[4]|(255&e[5])<<8|(255&e[6])<<16|(255&e[7])<<24,u=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,y=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,l=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,w=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,p=255&e[8]|(255&e[9])<<8|(255&e[10])<<16|(255&e[11])<<24,v=255&n[16]|(255&n[17])<<8|(255&n[18])<<16|(255&n[19])<<24,b=255&n[20]|(255&n[21])<<8|(255&n[22])<<16|(255&n[23])<<24,g=255&n[24]|(255&n[25])<<8|(255&n[26])<<16|(255&n[27])<<24,_=255&n[28]|(255&n[29])<<8|(255&n[30])<<16|(255&n[31])<<24,A=255&e[12]|(255&e[13])<<8|(255&e[14])<<16|(255&e[15])<<24,d=i,U=h,E=a,x=f,M=s,m=c,B=u,S=y,K=l,T=w,Y=p,k=v,L=b,z=g,R=_,P=A,O=0;O<20;O+=2)o=d+L|0,M^=o<<7|o>>>25,o=M+d|0,K^=o<<9|o>>>23,o=K+M|0,L^=o<<13|o>>>19,o=L+K|0,d^=o<<18|o>>>14,o=m+U|0,T^=o<<7|o>>>25,o=T+m|0,z^=o<<9|o>>>23,o=z+T|0,U^=o<<13|o>>>19,o=U+z|0,m^=o<<18|o>>>14,o=Y+B|0,R^=o<<7|o>>>25,o=R+Y|0,E^=o<<9|o>>>23,o=E+R|0,B^=o<<13|o>>>19,o=B+E|0,Y^=o<<18|o>>>14,o=P+k|0,x^=o<<7|o>>>25,o=x+P|0,S^=o<<9|o>>>23,o=S+x|0,k^=o<<13|o>>>19,o=k+S|0,P^=o<<18|o>>>14,o=d+x|0,U^=o<<7|o>>>25,o=U+d|0,E^=o<<9|o>>>23,o=E+U|0,x^=o<<13|o>>>19,o=x+E|0,d^=o<<18|o>>>14,o=m+M|0,B^=o<<7|o>>>25,o=B+m|0,S^=o<<9|o>>>23,o=S+B|0,M^=o<<13|o>>>19,o=M+S|0,m^=o<<18|o>>>14,o=Y+T|0,k^=o<<7|o>>>25,o=k+Y|0,K^=o<<9|o>>>23,o=K+k|0,T^=o<<13|o>>>19,o=T+K|0,Y^=o<<18|o>>>14,o=P+R|0,L^=o<<7|o>>>25,o=L+P|0,z^=o<<9|o>>>23,o=z+L|0,R^=o<<13|o>>>19,o=R+z|0,P^=o<<18|o>>>14;d=d+i|0,U=U+h|0,E=E+a|0,x=x+f|0,M=M+s|0,m=m+c|0,B=B+u|0,S=S+y|0,K=K+l|0,T=T+w|0,Y=Y+p|0,k=k+v|0,L=L+b|0,z=z+g|0,R=R+_|0,P=P+A|0,r[0]=d>>>0&255,r[1]=d>>>8&255,r[2]=d>>>16&255,r[3]=d>>>24&255,r[4]=U>>>0&255,r[5]=U>>>8&255,r[6]=U>>>16&255,r[7]=U>>>24&255,r[8]=E>>>0&255,r[9]=E>>>8&255,r[10]=E>>>16&255,r[11]=E>>>24&255,r[12]=x>>>0&255,r[13]=x>>>8&255,r[14]=x>>>16&255,r[15]=x>>>24&255,r[16]=M>>>0&255,r[17]=M>>>8&255,r[18]=M>>>16&255,r[19]=M>>>24&255,r[20]=m>>>0&255,r[21]=m>>>8&255,r[22]=m>>>16&255,r[23]=m>>>24&255,r[24]=B>>>0&255,r[25]=B>>>8&255,r[26]=B>>>16&255,r[27]=B>>>24&255,r[28]=S>>>0&255,r[29]=S>>>8&255,r[30]=S>>>16&255,r[31]=S>>>24&255,r[32]=K>>>0&255,r[33]=K>>>8&255,r[34]=K>>>16&255,r[35]=K>>>24&255,r[36]=T>>>0&255,r[37]=T>>>8&255,r[38]=T>>>16&255,r[39]=T>>>24&255,r[40]=Y>>>0&255,r[41]=Y>>>8&255,r[42]=Y>>>16&255,r[43]=Y>>>24&255,r[44]=k>>>0&255,r[45]=k>>>8&255,r[46]=k>>>16&255,r[47]=k>>>24&255,r[48]=L>>>0&255,r[49]=L>>>8&255,r[50]=L>>>16&255,r[51]=L>>>24&255,r[52]=z>>>0&255,r[53]=z>>>8&255,r[54]=z>>>16&255,r[55]=z>>>24&255,r[56]=R>>>0&255,r[57]=R>>>8&255,r[58]=R>>>16&255,r[59]=R>>>24&255,r[60]=P>>>0&255,r[61]=P>>>8&255,r[62]=P>>>16&255,r[63]=P>>>24&255}function h(r,t,n,e){for(var o,i=255&e[0]|(255&e[1])<<8|(255&e[2])<<16|(255&e[3])<<24,h=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,s=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,c=255&e[4]|(255&e[5])<<8|(255&e[6])<<16|(255&e[7])<<24,u=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,y=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,l=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,w=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,p=255&e[8]|(255&e[9])<<8|(255&e[10])<<16|(255&e[11])<<24,v=255&n[16]|(255&n[17])<<8|(255&n[18])<<16|(255&n[19])<<24,b=255&n[20]|(255&n[21])<<8|(255&n[22])<<16|(255&n[23])<<24,g=255&n[24]|(255&n[25])<<8|(255&n[26])<<16|(255&n[27])<<24,_=255&n[28]|(255&n[29])<<8|(255&n[30])<<16|(255&n[31])<<24,A=255&e[12]|(255&e[13])<<8|(255&e[14])<<16|(255&e[15])<<24,d=i,U=h,E=a,x=f,M=s,m=c,B=u,S=y,K=l,T=w,Y=p,k=v,L=b,z=g,R=_,P=A,O=0;O<20;O+=2)o=d+L|0,M^=o<<7|o>>>25,o=M+d|0,K^=o<<9|o>>>23,o=K+M|0,L^=o<<13|o>>>19,o=L+K|0,d^=o<<18|o>>>14,o=m+U|0,T^=o<<7|o>>>25,o=T+m|0,z^=o<<9|o>>>23,o=z+T|0,U^=o<<13|o>>>19,o=U+z|0,m^=o<<18|o>>>14,o=Y+B|0,R^=o<<7|o>>>25,o=R+Y|0,E^=o<<9|o>>>23,o=E+R|0,B^=o<<13|o>>>19,o=B+E|0,Y^=o<<18|o>>>14,o=P+k|0,x^=o<<7|o>>>25,o=x+P|0,S^=o<<9|o>>>23,o=S+x|0,k^=o<<13|o>>>19,o=k+S|0,P^=o<<18|o>>>14,o=d+x|0,U^=o<<7|o>>>25,o=U+d|0,E^=o<<9|o>>>23,o=E+U|0,x^=o<<13|o>>>19,o=x+E|0,d^=o<<18|o>>>14,o=m+M|0,B^=o<<7|o>>>25,o=B+m|0,S^=o<<9|o>>>23,o=S+B|0,M^=o<<13|o>>>19,o=M+S|0,m^=o<<18|o>>>14,o=Y+T|0,k^=o<<7|o>>>25,o=k+Y|0,K^=o<<9|o>>>23,o=K+k|0,T^=o<<13|o>>>19,o=T+K|0,Y^=o<<18|o>>>14,o=P+R|0,L^=o<<7|o>>>25,o=L+P|0,z^=o<<9|o>>>23,o=z+L|0,R^=o<<13|o>>>19,o=R+z|0,P^=o<<18|o>>>14;r[0]=d>>>0&255,r[1]=d>>>8&255,r[2]=d>>>16&255,r[3]=d>>>24&255,r[4]=m>>>0&255,r[5]=m>>>8&255,r[6]=m>>>16&255,r[7]=m>>>24&255,r[8]=Y>>>0&255,r[9]=Y>>>8&255,r[10]=Y>>>16&255,r[11]=Y>>>24&255,r[12]=P>>>0&255,r[13]=P>>>8&255,r[14]=P>>>16&255,r[15]=P>>>24&255,r[16]=B>>>0&255,r[17]=B>>>8&255,r[18]=B>>>16&255,r[19]=B>>>24&255,r[20]=S>>>0&255,r[21]=S>>>8&255,r[22]=S>>>16&255,r[23]=S>>>24&255,r[24]=K>>>0&255,r[25]=K>>>8&255,r[26]=K>>>16&255,r[27]=K>>>24&255,r[28]=T>>>0&255,r[29]=T>>>8&255,r[30]=T>>>16&255,r[31]=T>>>24&255}function a(r,t,n,e){i(r,t,n,e)}function f(r,t,n,e){h(r,t,n,e)}function s(r,t,n,e,o,i,h){var f,s,c=new Uint8Array(16),u=new Uint8Array(64);for(s=0;s<16;s++)c[s]=0;for(s=0;s<8;s++)c[s]=i[s];for(;o>=64;){for(a(u,c,h,ur),s=0;s<64;s++)r[t+s]=n[e+s]^u[s];for(f=1,s=8;s<16;s++)f=f+(255&c[s])|0,c[s]=255&f,f>>>=8;o-=64,t+=64,e+=64}if(o>0)for(a(u,c,h,ur),s=0;s<o;s++)r[t+s]=n[e+s]^u[s];return 0}function c(r,t,n,e,o){var i,h,f=new Uint8Array(16),s=new Uint8Array(64);for(h=0;h<16;h++)f[h]=0;for(h=0;h<8;h++)f[h]=e[h];for(;n>=64;){for(a(s,f,o,ur),h=0;h<64;h++)r[t+h]=s[h];for(i=1,h=8;h<16;h++)i=i+(255&f[h])|0,f[h]=255&i,i>>>=8;n-=64,t+=64}if(n>0)for(a(s,f,o,ur),h=0;h<n;h++)r[t+h]=s[h];return 0}function u(r,t,n,e,o){var i=new Uint8Array(32);f(i,e,o,ur);for(var h=new Uint8Array(8),a=0;a<8;a++)h[a]=e[a+16];return c(r,t,n,h,i)}function y(r,t,n,e,o,i,h){var a=new Uint8Array(32);f(a,i,h,ur);for(var c=new Uint8Array(8),u=0;u<8;u++)c[u]=i[u+16];return s(r,t,n,e,o,c,a)}function l(r,t,n,e,o,i){var h=new yr(i);return h.update(n,e,o),h.finish(r,t),0}function w(r,t,n,o,i,h){var a=new Uint8Array(16);return l(a,0,n,o,i,h),e(r,t,a,0)}function p(r,t,n,e,o){var i;if(n<32)return-1;for(y(r,0,t,0,n,e,o),l(r,16,r,32,n-32,r),i=0;i<16;i++)r[i]=0;return 0}function v(r,t,n,e,o){var i,h=new Uint8Array(32);if(n<32)return-1;if(u(h,0,32,e,o),0!==w(t,16,t,32,n-32,h))return-1;for(y(r,0,t,0,n,e,o),i=0;i<32;i++)r[i]=0;return 0}function b(r,t){var n;for(n=0;n<16;n++)r[n]=0|t[n]}function g(r){var t,n,e=1;for(t=0;t<16;t++)n=r[t]+e+65535,e=Math.floor(n/65536),r[t]=n-65536*e;r[0]+=e-1+37*(e-1)}function _(r,t,n){for(var e,o=~(n-1),i=0;i<16;i++)e=o&(r[i]^t[i]),r[i]^=e,t[i]^=e}function A(r,t){var n,e,o,i=$(),h=$();for(n=0;n<16;n++)h[n]=t[n];for(g(h),g(h),g(h),e=0;e<2;e++){for(i[0]=h[0]-65517,n=1;n<15;n++)i[n]=h[n]-65535-(i[n-1]>>16&1),i[n-1]&=65535;i[15]=h[15]-32767-(i[14]>>16&1),o=i[15]>>16&1,i[14]&=65535,_(h,i,1-o)}for(n=0;n<16;n++)r[2*n]=255&h[n],r[2*n+1]=h[n]>>8}function d(r,t){var n=new Uint8Array(32),e=new Uint8Array(32);return A(n,r),A(e,t),o(n,0,e,0)}function U(r){var t=new Uint8Array(32);return A(t,r),1&t[0]}function E(r,t){var n;for(n=0;n<16;n++)r[n]=t[2*n]+(t[2*n+1]<<8);r[15]&=32767}function x(r,t,n){for(var e=0;e<16;e++)r[e]=t[e]+n[e]}function M(r,t,n){for(var e=0;e<16;e++)r[e]=t[e]-n[e]}function m(r,t,n){var e,o,i=0,h=0,a=0,f=0,s=0,c=0,u=0,y=0,l=0,w=0,p=0,v=0,b=0,g=0,_=0,A=0,d=0,U=0,E=0,x=0,M=0,m=0,B=0,S=0,K=0,T=0,Y=0,k=0,L=0,z=0,R=0,P=n[0],O=n[1],N=n[2],C=n[3],F=n[4],I=n[5],G=n[6],Z=n[7],j=n[8],q=n[9],V=n[10],X=n[11],D=n[12],H=n[13],J=n[14],Q=n[15];e=t[0],i+=e*P,h+=e*O,a+=e*N,f+=e*C,s+=e*F,c+=e*I,u+=e*G,y+=e*Z,l+=e*j,w+=e*q,p+=e*V,v+=e*X,b+=e*D,g+=e*H,_+=e*J,A+=e*Q,e=t[1],h+=e*P,a+=e*O,f+=e*N,s+=e*C,c+=e*F,u+=e*I,y+=e*G,l+=e*Z,w+=e*j,p+=e*q,v+=e*V,b+=e*X,g+=e*D,_+=e*H,A+=e*J,d+=e*Q,e=t[2],a+=e*P,f+=e*O,s+=e*N,c+=e*C,u+=e*F,y+=e*I,l+=e*G,w+=e*Z,p+=e*j,v+=e*q,b+=e*V,g+=e*X,_+=e*D,A+=e*H,d+=e*J,U+=e*Q,e=t[3],f+=e*P,s+=e*O,c+=e*N,u+=e*C,y+=e*F,l+=e*I,w+=e*G,p+=e*Z,v+=e*j,b+=e*q,g+=e*V,_+=e*X,A+=e*D,d+=e*H,U+=e*J,E+=e*Q,e=t[4],s+=e*P,c+=e*O,u+=e*N,y+=e*C,l+=e*F,w+=e*I,p+=e*G,v+=e*Z,b+=e*j,g+=e*q,_+=e*V,A+=e*X,d+=e*D,U+=e*H,E+=e*J,x+=e*Q,e=t[5],c+=e*P,u+=e*O,y+=e*N,l+=e*C,w+=e*F,p+=e*I,v+=e*G,b+=e*Z,g+=e*j,_+=e*q,A+=e*V,d+=e*X,U+=e*D,E+=e*H,x+=e*J,M+=e*Q,e=t[6],u+=e*P,y+=e*O,l+=e*N,w+=e*C,p+=e*F,v+=e*I,b+=e*G,g+=e*Z,_+=e*j,A+=e*q,d+=e*V,U+=e*X,E+=e*D,x+=e*H,M+=e*J,m+=e*Q,e=t[7],y+=e*P,l+=e*O,w+=e*N,p+=e*C,v+=e*F,b+=e*I,g+=e*G,_+=e*Z,A+=e*j,d+=e*q,U+=e*V,E+=e*X,x+=e*D,M+=e*H,m+=e*J,B+=e*Q,e=t[8],l+=e*P,w+=e*O,p+=e*N,v+=e*C,b+=e*F,g+=e*I,_+=e*G,A+=e*Z,d+=e*j,U+=e*q,E+=e*V,x+=e*X,M+=e*D,m+=e*H,B+=e*J,S+=e*Q,e=t[9],w+=e*P,p+=e*O,v+=e*N,b+=e*C,g+=e*F,_+=e*I,A+=e*G,d+=e*Z,U+=e*j,E+=e*q,x+=e*V,M+=e*X,m+=e*D,B+=e*H,S+=e*J,K+=e*Q,e=t[10],p+=e*P,v+=e*O,b+=e*N,g+=e*C,_+=e*F,A+=e*I,d+=e*G,U+=e*Z,E+=e*j,x+=e*q,M+=e*V,m+=e*X,B+=e*D,S+=e*H,K+=e*J,T+=e*Q,e=t[11],v+=e*P,b+=e*O,g+=e*N,_+=e*C,A+=e*F,d+=e*I,U+=e*G,E+=e*Z,x+=e*j,M+=e*q,m+=e*V,B+=e*X;S+=e*D;K+=e*H,T+=e*J,Y+=e*Q,e=t[12],b+=e*P,g+=e*O,_+=e*N,A+=e*C,d+=e*F,U+=e*I,E+=e*G,x+=e*Z,M+=e*j,m+=e*q,B+=e*V,S+=e*X,K+=e*D,T+=e*H,Y+=e*J,k+=e*Q,e=t[13],g+=e*P,_+=e*O,A+=e*N,d+=e*C,U+=e*F,E+=e*I,x+=e*G,M+=e*Z,m+=e*j,B+=e*q,S+=e*V,K+=e*X,T+=e*D,Y+=e*H,k+=e*J,L+=e*Q,e=t[14],_+=e*P,A+=e*O,d+=e*N,U+=e*C,E+=e*F,x+=e*I,M+=e*G,m+=e*Z,B+=e*j,S+=e*q,K+=e*V,T+=e*X,Y+=e*D,k+=e*H,L+=e*J,z+=e*Q,e=t[15],A+=e*P,d+=e*O,U+=e*N,E+=e*C,x+=e*F,M+=e*I,m+=e*G,B+=e*Z,S+=e*j,K+=e*q,T+=e*V,Y+=e*X,k+=e*D,L+=e*H,z+=e*J,R+=e*Q,i+=38*d,h+=38*U,a+=38*E,f+=38*x,s+=38*M,c+=38*m,u+=38*B,y+=38*S,l+=38*K,w+=38*T,p+=38*Y,v+=38*k,b+=38*L,g+=38*z,_+=38*R,o=1,e=i+o+65535,o=Math.floor(e/65536),i=e-65536*o,e=h+o+65535,o=Math.floor(e/65536),h=e-65536*o,e=a+o+65535,o=Math.floor(e/65536),a=e-65536*o,e=f+o+65535,o=Math.floor(e/65536),f=e-65536*o,e=s+o+65535,o=Math.floor(e/65536),s=e-65536*o,e=c+o+65535,o=Math.floor(e/65536),c=e-65536*o,e=u+o+65535,o=Math.floor(e/65536),u=e-65536*o,e=y+o+65535,o=Math.floor(e/65536),y=e-65536*o,e=l+o+65535,o=Math.floor(e/65536),l=e-65536*o,e=w+o+65535,o=Math.floor(e/65536),w=e-65536*o,e=p+o+65535,o=Math.floor(e/65536),p=e-65536*o,e=v+o+65535,o=Math.floor(e/65536),v=e-65536*o,e=b+o+65535,o=Math.floor(e/65536),b=e-65536*o,e=g+o+65535,o=Math.floor(e/65536),g=e-65536*o,e=_+o+65535,o=Math.floor(e/65536),_=e-65536*o,e=A+o+65535,o=Math.floor(e/65536),A=e-65536*o,i+=o-1+37*(o-1),o=1,e=i+o+65535,o=Math.floor(e/65536),i=e-65536*o,e=h+o+65535,o=Math.floor(e/65536),h=e-65536*o,e=a+o+65535,o=Math.floor(e/65536),a=e-65536*o,e=f+o+65535,o=Math.floor(e/65536),f=e-65536*o,e=s+o+65535,o=Math.floor(e/65536),s=e-65536*o,e=c+o+65535,o=Math.floor(e/65536),c=e-65536*o,e=u+o+65535,o=Math.floor(e/65536),u=e-65536*o,e=y+o+65535,o=Math.floor(e/65536),y=e-65536*o,e=l+o+65535,o=Math.floor(e/65536),l=e-65536*o,e=w+o+65535,o=Math.floor(e/65536),w=e-65536*o,e=p+o+65535,o=Math.floor(e/65536),p=e-65536*o,e=v+o+65535,o=Math.floor(e/65536),v=e-65536*o,e=b+o+65535,o=Math.floor(e/65536),b=e-65536*o,e=g+o+65535,o=Math.floor(e/65536),g=e-65536*o,e=_+o+65535,o=Math.floor(e/65536),_=e-65536*o,e=A+o+65535,o=Math.floor(e/65536),A=e-65536*o,i+=o-1+37*(o-1),r[0]=i,r[1]=h,r[2]=a,r[3]=f,r[4]=s,r[5]=c,r[6]=u,r[7]=y,r[8]=l,r[9]=w,r[10]=p,r[11]=v,r[12]=b,r[13]=g;r[14]=_;r[15]=A}function B(r,t){m(r,t,t)}function S(r,t){var n,e=$();for(n=0;n<16;n++)e[n]=t[n];for(n=253;n>=0;n--)B(e,e),2!==n&&4!==n&&m(e,e,t);for(n=0;n<16;n++)r[n]=e[n]}function K(r,t){var n,e=$();for(n=0;n<16;n++)e[n]=t[n];for(n=250;n>=0;n--)B(e,e),1!==n&&m(e,e,t);for(n=0;n<16;n++)r[n]=e[n]}function T(r,t,n){var e,o,i=new Uint8Array(32),h=new Float64Array(80),a=$(),f=$(),s=$(),c=$(),u=$(),y=$();for(o=0;o<31;o++)i[o]=t[o];for(i[31]=127&t[31]|64,i[0]&=248,E(h,n),o=0;o<16;o++)f[o]=h[o],c[o]=a[o]=s[o]=0;for(a[0]=c[0]=1,o=254;o>=0;--o)e=i[o>>>3]>>>(7&o)&1,_(a,f,e),_(s,c,e),x(u,a,s),M(a,a,s),x(s,f,c),M(f,f,c),B(c,u),B(y,a),m(a,s,a),m(s,f,u),x(u,a,s),M(a,a,s),B(f,a),M(s,c,y),m(a,s,ir),x(a,a,c),m(s,s,a),m(a,c,y),m(c,f,h),B(f,u),_(a,f,e),_(s,c,e);for(o=0;o<16;o++)h[o+16]=a[o],h[o+32]=s[o],h[o+48]=f[o],h[o+64]=c[o];var l=h.subarray(32),w=h.subarray(16);return S(l,l),m(w,w,l),A(r,w),0}function Y(r,t){return T(r,t,nr)}function k(r,t){return rr(t,32),Y(r,t)}function L(r,t,n){var e=new Uint8Array(32);return T(e,n,t),f(r,tr,e,ur)}function z(r,t,n,e,o,i){var h=new Uint8Array(32);return L(h,o,i),lr(r,t,n,e,h)}function R(r,t,n,e,o,i){var h=new Uint8Array(32);return L(h,o,i),wr(r,t,n,e,h)}function P(r,t,n,e){for(var o,i,h,a,f,s,c,u,y,l,w,p,v,b,g,_,A,d,U,E,x,M,m,B,S,K,T=new Int32Array(16),Y=new Int32Array(16),k=r[0],L=r[1],z=r[2],R=r[3],P=r[4],O=r[5],N=r[6],C=r[7],F=t[0],I=t[1],G=t[2],Z=t[3],j=t[4],q=t[5],V=t[6],X=t[7],D=0;e>=128;){for(U=0;U<16;U++)E=8*U+D,T[U]=n[E+0]<<24|n[E+1]<<16|n[E+2]<<8|n[E+3],Y[U]=n[E+4]<<24|n[E+5]<<16|n[E+6]<<8|n[E+7];for(U=0;U<80;U++)if(o=k,i=L,h=z,a=R,f=P,s=O,c=N,u=C,y=F,l=I,w=G,p=Z,v=j,b=q,g=V,_=X,x=C,M=X,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=(P>>>14|j<<18)^(P>>>18|j<<14)^(j>>>9|P<<23),M=(j>>>14|P<<18)^(j>>>18|P<<14)^(P>>>9|j<<23),m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,x=P&O^~P&N,M=j&q^~j&V,m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,x=pr[2*U],M=pr[2*U+1],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,x=T[U%16],M=Y[U%16],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,A=65535&S|K<<16,d=65535&m|B<<16,x=A,M=d,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=(k>>>28|F<<4)^(F>>>2|k<<30)^(F>>>7|k<<25),M=(F>>>28|k<<4)^(k>>>2|F<<30)^(k>>>7|F<<25),m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,x=k&L^k&z^L&z,M=F&I^F&G^I&G,m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,u=65535&S|K<<16,_=65535&m|B<<16,x=a,M=p,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=A,M=d,m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,a=65535&S|K<<16,p=65535&m|B<<16,L=o,z=i,R=h,P=a,O=f,N=s,C=c,k=u,I=y,G=l,Z=w,j=p,q=v,V=b,X=g,F=_,U%16===15)for(E=0;E<16;E++)x=T[E],M=Y[E],m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=T[(E+9)%16],M=Y[(E+9)%16],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,A=T[(E+1)%16],d=Y[(E+1)%16],x=(A>>>1|d<<31)^(A>>>8|d<<24)^A>>>7,M=(d>>>1|A<<31)^(d>>>8|A<<24)^(d>>>7|A<<25),m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,A=T[(E+14)%16],d=Y[(E+14)%16],x=(A>>>19|d<<13)^(d>>>29|A<<3)^A>>>6,M=(d>>>19|A<<13)^(A>>>29|d<<3)^(d>>>6|A<<26),m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,T[E]=65535&S|K<<16,Y[E]=65535&m|B<<16;x=k,M=F,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[0],M=t[0],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[0]=k=65535&S|K<<16,t[0]=F=65535&m|B<<16,x=L,M=I,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[1],M=t[1],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[1]=L=65535&S|K<<16,t[1]=I=65535&m|B<<16,x=z,M=G,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[2],M=t[2],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[2]=z=65535&S|K<<16,t[2]=G=65535&m|B<<16,x=R,M=Z,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[3],M=t[3],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[3]=R=65535&S|K<<16,t[3]=Z=65535&m|B<<16,x=P,M=j,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[4],M=t[4],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[4]=P=65535&S|K<<16,t[4]=j=65535&m|B<<16,x=O,M=q,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[5],M=t[5],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[5]=O=65535&S|K<<16,t[5]=q=65535&m|B<<16,x=N,M=V,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[6],M=t[6],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[6]=N=65535&S|K<<16,t[6]=V=65535&m|B<<16,x=C,M=X,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[7],M=t[7],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[7]=C=65535&S|K<<16,t[7]=X=65535&m|B<<16,D+=128,e-=128}return e}function O(r,n,e){var o,i=new Int32Array(8),h=new Int32Array(8),a=new Uint8Array(256),f=e;for(i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225,h[0]=4089235720,h[1]=2227873595,h[2]=4271175723,h[3]=1595750129,h[4]=2917565137,h[5]=725511199,h[6]=4215389547,h[7]=327033209,P(i,h,n,e),e%=128,o=0;o<e;o++)a[o]=n[f-e+o];for(a[e]=128,e=256-128*(e<112?1:0),a[e-9]=0,t(a,e-8,f/536870912|0,f<<3),P(i,h,a,e),o=0;o<8;o++)t(r,8*o,i[o],h[o]);return 0}function N(r,t){var n=$(),e=$(),o=$(),i=$(),h=$(),a=$(),f=$(),s=$(),c=$();M(n,r[1],r[0]),M(c,t[1],t[0]),m(n,n,c),x(e,r[0],r[1]),x(c,t[0],t[1]),m(e,e,c),m(o,r[3],t[3]),m(o,o,ar),m(i,r[2],t[2]),x(i,i,i),M(h,e,n),M(a,i,o),x(f,i,o),x(s,e,n),m(r[0],h,a),m(r[1],s,f),m(r[2],f,a),m(r[3],h,s)}function C(r,t,n){var e;for(e=0;e<4;e++)_(r[e],t[e],n)}function F(r,t){var n=$(),e=$(),o=$();S(o,t[2]),m(n,t[0],o),m(e,t[1],o),A(r,e),r[31]^=U(n)<<7}function I(r,t,n){var e,o;for(b(r[0],er),b(r[1],or),b(r[2],or),b(r[3],er),o=255;o>=0;--o)e=n[o/8|0]>>(7&o)&1,C(r,t,e),N(t,r),N(r,r),C(r,t,e)}function G(r,t){var n=[$(),$(),$(),$()];b(n[0],fr),b(n[1],sr),b(n[2],or),m(n[3],fr,sr),I(r,n,t)}function Z(r,t,n){var e,o=new Uint8Array(64),i=[$(),$(),$(),$()];for(n||rr(t,32),O(o,t,32),o[0]&=248,o[31]&=127,o[31]|=64,G(i,o),F(r,i),e=0;e<32;e++)t[e+32]=r[e];return 0}function j(r,t){var n,e,o,i;for(e=63;e>=32;--e){for(n=0,o=e-32,i=e-12;o<i;++o)t[o]+=n-16*t[e]*vr[o-(e-32)],n=t[o]+128>>8,t[o]-=256*n;t[o]+=n,t[e]=0}for(n=0,o=0;o<32;o++)t[o]+=n-(t[31]>>4)*vr[o],n=t[o]>>8,t[o]&=255;for(o=0;o<32;o++)t[o]-=n*vr[o];for(e=0;e<32;e++)t[e+1]+=t[e]>>8,r[e]=255&t[e]}function q(r){var t,n=new Float64Array(64);for(t=0;t<64;t++)n[t]=r[t];for(t=0;t<64;t++)r[t]=0;j(r,n)}function V(r,t,n,e){var o,i,h=new Uint8Array(64),a=new Uint8Array(64),f=new Uint8Array(64),s=new Float64Array(64),c=[$(),$(),$(),$()];O(h,e,32),h[0]&=248,h[31]&=127,h[31]|=64;var u=n+64;for(o=0;o<n;o++)r[64+o]=t[o];for(o=0;o<32;o++)r[32+o]=h[32+o];for(O(f,r.subarray(32),n+32),q(f),G(c,f),F(r,c),o=32;o<64;o++)r[o]=e[o];for(O(a,r,n+64),q(a),o=0;o<64;o++)s[o]=0;for(o=0;o<32;o++)s[o]=f[o];for(o=0;o<32;o++)for(i=0;i<32;i++)s[o+i]+=a[o]*h[i];return j(r.subarray(32),s),u}function X(r,t){var n=$(),e=$(),o=$(),i=$(),h=$(),a=$(),f=$();return b(r[2],or),E(r[1],t),B(o,r[1]),m(i,o,hr),M(o,o,r[2]),x(i,r[2],i),B(h,i),B(a,h),m(f,a,h),m(n,f,o),m(n,n,i),K(n,n),m(n,n,o),m(n,n,i),m(n,n,i),m(r[0],n,i),B(e,r[0]),m(e,e,i),d(e,o)&&m(r[0],r[0],cr),B(e,r[0]),m(e,e,i),d(e,o)?-1:(U(r[0])===t[31]>>7&&M(r[0],er,r[0]),m(r[3],r[0],r[1]),0)}function D(r,t,n,e){var i,h,a=new Uint8Array(32),f=new Uint8Array(64),s=[$(),$(),$(),$()],c=[$(),$(),$(),$()];if(h=-1,n<64)return-1;if(X(c,e))return-1;for(i=0;i<n;i++)r[i]=t[i];for(i=0;i<32;i++)r[i+32]=e[i];if(O(f,r,n),q(f),I(s,c,f),G(c,t.subarray(32)),N(s,c),F(a,s),n-=64,o(t,0,a,0)){for(i=0;i<n;i++)r[i]=0;return-1}for(i=0;i<n;i++)r[i]=t[i+64];return h=n}function H(r,t){if(r.length!==br)throw new Error("bad key size");if(t.length!==gr)throw new Error("bad nonce size")}function J(r,t){if(r.length!==Er)throw new Error("bad public key size");if(t.length!==xr)throw new Error("bad secret key size")}function Q(){var r,t;for(t=0;t<arguments.length;t++)if("[object Uint8Array]"!==(r=Object.prototype.toString.call(arguments[t])))throw new TypeError("unexpected type "+r+", use Uint8Array")}function W(r){for(var t=0;t<r.length;t++)r[t]=0}var $=function(r){var t,n=new Float64Array(16);if(r)for(t=0;t<r.length;t++)n[t]=r[t];return n},rr=function(){throw new Error("no PRNG")},tr=new Uint8Array(16),nr=new Uint8Array(32);nr[0]=9;var er=$(),or=$([1]),ir=$([56129,1]),hr=$([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),ar=$([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),fr=$([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),sr=$([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),cr=$([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]),ur=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]),yr=function(r){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var t,n,e,o,i,h,a,f;t=255&r[0]|(255&r[1])<<8,this.r[0]=8191&t,n=255&r[2]|(255&r[3])<<8,this.r[1]=8191&(t>>>13|n<<3),e=255&r[4]|(255&r[5])<<8,this.r[2]=7939&(n>>>10|e<<6),o=255&r[6]|(255&r[7])<<8,this.r[3]=8191&(e>>>7|o<<9),i=255&r[8]|(255&r[9])<<8,this.r[4]=255&(o>>>4|i<<12),this.r[5]=i>>>1&8190,h=255&r[10]|(255&r[11])<<8,this.r[6]=8191&(i>>>14|h<<2),a=255&r[12]|(255&r[13])<<8,this.r[7]=8065&(h>>>11|a<<5),f=255&r[14]|(255&r[15])<<8,this.r[8]=8191&(a>>>8|f<<8),this.r[9]=f>>>5&127,this.pad[0]=255&r[16]|(255&r[17])<<8,this.pad[1]=255&r[18]|(255&r[19])<<8,this.pad[2]=255&r[20]|(255&r[21])<<8,this.pad[3]=255&r[22]|(255&r[23])<<8,this.pad[4]=255&r[24]|(255&r[25])<<8,this.pad[5]=255&r[26]|(255&r[27])<<8,this.pad[6]=255&r[28]|(255&r[29])<<8,this.pad[7]=255&r[30]|(255&r[31])<<8};yr.prototype.blocks=function(r,t,n){for(var e,o,i,h,a,f,s,c,u,y,l,w,p,v,b,g,_,A,d,U=this.fin?0:2048,E=this.h[0],x=this.h[1],M=this.h[2],m=this.h[3],B=this.h[4],S=this.h[5],K=this.h[6],T=this.h[7],Y=this.h[8],k=this.h[9],L=this.r[0],z=this.r[1],R=this.r[2],P=this.r[3],O=this.r[4],N=this.r[5],C=this.r[6],F=this.r[7],I=this.r[8],G=this.r[9];n>=16;)e=255&r[t+0]|(255&r[t+1])<<8,E+=8191&e,o=255&r[t+2]|(255&r[t+3])<<8,x+=8191&(e>>>13|o<<3),i=255&r[t+4]|(255&r[t+5])<<8,M+=8191&(o>>>10|i<<6),h=255&r[t+6]|(255&r[t+7])<<8,m+=8191&(i>>>7|h<<9),a=255&r[t+8]|(255&r[t+9])<<8,B+=8191&(h>>>4|a<<12),S+=a>>>1&8191,f=255&r[t+10]|(255&r[t+11])<<8,K+=8191&(a>>>14|f<<2),s=255&r[t+12]|(255&r[t+13])<<8,T+=8191&(f>>>11|s<<5),c=255&r[t+14]|(255&r[t+15])<<8,Y+=8191&(s>>>8|c<<8),k+=c>>>5|U,u=0,y=u,y+=E*L,y+=x*(5*G),y+=M*(5*I),y+=m*(5*F),y+=B*(5*C),u=y>>>13,y&=8191,y+=S*(5*N),y+=K*(5*O),y+=T*(5*P),y+=Y*(5*R),y+=k*(5*z),u+=y>>>13,y&=8191,l=u,l+=E*z,l+=x*L,l+=M*(5*G),l+=m*(5*I),l+=B*(5*F),u=l>>>13,l&=8191,l+=S*(5*C),l+=K*(5*N),l+=T*(5*O),l+=Y*(5*P),l+=k*(5*R),u+=l>>>13,l&=8191,w=u,w+=E*R,w+=x*z,w+=M*L,w+=m*(5*G),w+=B*(5*I),u=w>>>13,w&=8191,w+=S*(5*F),w+=K*(5*C),w+=T*(5*N),w+=Y*(5*O),w+=k*(5*P),u+=w>>>13,w&=8191,p=u,p+=E*P,p+=x*R,p+=M*z,p+=m*L,p+=B*(5*G),u=p>>>13,p&=8191,p+=S*(5*I),p+=K*(5*F),p+=T*(5*C),p+=Y*(5*N),p+=k*(5*O),u+=p>>>13,p&=8191,v=u,v+=E*O,v+=x*P,v+=M*R,v+=m*z,v+=B*L,u=v>>>13,v&=8191,v+=S*(5*G),v+=K*(5*I),v+=T*(5*F),v+=Y*(5*C),v+=k*(5*N),u+=v>>>13,v&=8191,b=u,b+=E*N,b+=x*O,b+=M*P,b+=m*R,b+=B*z,u=b>>>13,b&=8191,b+=S*L,b+=K*(5*G),b+=T*(5*I),b+=Y*(5*F),b+=k*(5*C),u+=b>>>13,b&=8191,g=u,g+=E*C,g+=x*N,g+=M*O,g+=m*P,g+=B*R,u=g>>>13,g&=8191,g+=S*z,g+=K*L,g+=T*(5*G),g+=Y*(5*I),g+=k*(5*F),u+=g>>>13,g&=8191,_=u,_+=E*F,_+=x*C,_+=M*N,_+=m*O,_+=B*P,u=_>>>13,_&=8191,_+=S*R,_+=K*z,_+=T*L,_+=Y*(5*G),_+=k*(5*I),u+=_>>>13,_&=8191,A=u,A+=E*I,A+=x*F,A+=M*C,A+=m*N,A+=B*O,u=A>>>13,A&=8191,A+=S*P,A+=K*R,A+=T*z,A+=Y*L,A+=k*(5*G),u+=A>>>13,A&=8191,d=u,d+=E*G,d+=x*I,d+=M*F,d+=m*C,d+=B*N,u=d>>>13,d&=8191,d+=S*O,d+=K*P,d+=T*R,d+=Y*z,d+=k*L,u+=d>>>13,d&=8191,u=(u<<2)+u|0,u=u+y|0,y=8191&u,u>>>=13,l+=u,E=y,x=l,M=w,m=p,B=v,S=b,K=g,T=_,Y=A,k=d,t+=16,n-=16;this.h[0]=E,this.h[1]=x,this.h[2]=M,this.h[3]=m,this.h[4]=B,this.h[5]=S,this.h[6]=K,this.h[7]=T,this.h[8]=Y,this.h[9]=k},yr.prototype.finish=function(r,t){var n,e,o,i,h=new Uint16Array(10);if(this.leftover){for(i=this.leftover,this.buffer[i++]=1;i<16;i++)this.buffer[i]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(n=this.h[1]>>>13,this.h[1]&=8191,i=2;i<10;i++)this.h[i]+=n,n=this.h[i]>>>13,this.h[i]&=8191;for(this.h[0]+=5*n,n=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=n,n=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=n,h[0]=this.h[0]+5,n=h[0]>>>13,h[0]&=8191,i=1;i<10;i++)h[i]=this.h[i]+n,n=h[i]>>>13,h[i]&=8191;for(h[9]-=8192,e=(1^n)-1,i=0;i<10;i++)h[i]&=e;for(e=~e,i=0;i<10;i++)this.h[i]=this.h[i]&e|h[i];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),o=this.h[0]+this.pad[0],this.h[0]=65535&o,i=1;i<8;i++)o=(this.h[i]+this.pad[i]|0)+(o>>>16)|0,this.h[i]=65535&o;r[t+0]=this.h[0]>>>0&255,r[t+1]=this.h[0]>>>8&255,r[t+2]=this.h[1]>>>0&255,r[t+3]=this.h[1]>>>8&255,r[t+4]=this.h[2]>>>0&255,r[t+5]=this.h[2]>>>8&255,r[t+6]=this.h[3]>>>0&255,r[t+7]=this.h[3]>>>8&255,r[t+8]=this.h[4]>>>0&255,r[t+9]=this.h[4]>>>8&255,r[t+10]=this.h[5]>>>0&255,r[t+11]=this.h[5]>>>8&255,r[t+12]=this.h[6]>>>0&255,r[t+13]=this.h[6]>>>8&255,r[t+14]=this.h[7]>>>0&255,r[t+15]=this.h[7]>>>8&255},yr.prototype.update=function(r,t,n){var e,o;if(this.leftover){for(o=16-this.leftover,o>n&&(o=n),e=0;e<o;e++)this.buffer[this.leftover+e]=r[t+e];if(n-=o,t+=o,this.leftover+=o,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(n>=16&&(o=n-n%16,this.blocks(r,t,o),t+=o,n-=o),n){for(e=0;e<n;e++)this.buffer[this.leftover+e]=r[t+e];this.leftover+=n}};var lr=p,wr=v,pr=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],vr=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),br=32,gr=24,_r=32,Ar=16,dr=32,Ur=32,Er=32,xr=32,Mr=32,mr=gr,Br=_r,Sr=Ar,Kr=64,Tr=32,Yr=64,kr=32,Lr=64;r.lowlevel={crypto_core_hsalsa20:f,crypto_stream_xor:y,crypto_stream:u,crypto_stream_salsa20_xor:s,crypto_stream_salsa20:c,crypto_onetimeauth:l,crypto_onetimeauth_verify:w,crypto_verify_16:e,crypto_verify_32:o,crypto_secretbox:p,crypto_secretbox_open:v,crypto_scalarmult:T,crypto_scalarmult_base:Y,crypto_box_beforenm:L,crypto_box_afternm:lr,crypto_box:z,crypto_box_open:R,crypto_box_keypair:k,crypto_hash:O,crypto_sign:V,crypto_sign_keypair:Z,crypto_sign_open:D,crypto_secretbox_KEYBYTES:br,crypto_secretbox_NONCEBYTES:gr,crypto_secretbox_ZEROBYTES:_r,crypto_secretbox_BOXZEROBYTES:Ar,crypto_scalarmult_BYTES:dr,crypto_scalarmult_SCALARBYTES:Ur,crypto_box_PUBLICKEYBYTES:Er,crypto_box_SECRETKEYBYTES:xr,crypto_box_BEFORENMBYTES:Mr,crypto_box_NONCEBYTES:mr,crypto_box_ZEROBYTES:Br,crypto_box_BOXZEROBYTES:Sr,crypto_sign_BYTES:Kr,crypto_sign_PUBLICKEYBYTES:Tr,crypto_sign_SECRETKEYBYTES:Yr,crypto_sign_SEEDBYTES:kr,crypto_hash_BYTES:Lr},r.util||(r.util={},r.util.decodeUTF8=r.util.encodeUTF8=r.util.encodeBase64=r.util.decodeBase64=function(){throw new Error("nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js")}),r.randomBytes=function(r){var t=new Uint8Array(r);return rr(t,r),t},r.secretbox=function(r,t,n){Q(r,t,n),H(n,t);for(var e=new Uint8Array(_r+r.length),o=new Uint8Array(e.length),i=0;i<r.length;i++)e[i+_r]=r[i];return p(o,e,e.length,t,n),o.subarray(Ar)},r.secretbox.open=function(r,t,n){Q(r,t,n),H(n,t);for(var e=new Uint8Array(Ar+r.length),o=new Uint8Array(e.length),i=0;i<r.length;i++)e[i+Ar]=r[i];return!(e.length<32)&&(0===v(o,e,e.length,t,n)&&o.subarray(_r))},r.secretbox.keyLength=br,r.secretbox.nonceLength=gr,r.secretbox.overheadLength=Ar,r.scalarMult=function(r,t){if(Q(r,t),r.length!==Ur)throw new Error("bad n size");if(t.length!==dr)throw new Error("bad p size");var n=new Uint8Array(dr);return T(n,r,t),n},r.scalarMult.base=function(r){if(Q(r),r.length!==Ur)throw new Error("bad n size");var t=new Uint8Array(dr);return Y(t,r),t},r.scalarMult.scalarLength=Ur,r.scalarMult.groupElementLength=dr,r.box=function(t,n,e,o){var i=r.box.before(e,o);return r.secretbox(t,n,i)},r.box.before=function(r,t){Q(r,t),J(r,t);var n=new Uint8Array(Mr);return L(n,r,t),n},r.box.after=r.secretbox,r.box.open=function(t,n,e,o){var i=r.box.before(e,o);return r.secretbox.open(t,n,i)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var r=new Uint8Array(Er),t=new Uint8Array(xr);return k(r,t),{publicKey:r,secretKey:t}},r.box.keyPair.fromSecretKey=function(r){if(Q(r),r.length!==xr)throw new Error("bad secret key size");var t=new Uint8Array(Er);return Y(t,r),{publicKey:t,secretKey:new Uint8Array(r)}},r.box.publicKeyLength=Er,r.box.secretKeyLength=xr,r.box.sharedKeyLength=Mr,r.box.nonceLength=mr,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(r,t){if(Q(r,t),t.length!==Yr)throw new Error("bad secret key size");var n=new Uint8Array(Kr+r.length);return V(n,r,r.length,t),n},r.sign.open=function(r,t){if(2!==arguments.length)throw new Error("nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?");if(Q(r,t),t.length!==Tr)throw new Error("bad public key size");var n=new Uint8Array(r.length),e=D(n,r,r.length,t);if(e<0)return null;for(var o=new Uint8Array(e),i=0;i<o.length;i++)o[i]=n[i];return o},r.sign.detached=function(t,n){for(var e=r.sign(t,n),o=new Uint8Array(Kr),i=0;i<o.length;i++)o[i]=e[i];return o},r.sign.detached.verify=function(r,t,n){if(Q(r,t,n),t.length!==Kr)throw new Error("bad signature size");if(n.length!==Tr)throw new Error("bad public key size");var e,o=new Uint8Array(Kr+r.length),i=new Uint8Array(Kr+r.length);for(e=0;e<Kr;e++)o[e]=t[e];for(e=0;e<r.length;e++)o[e+Kr]=r[e];return D(i,o,o.length,n)>=0},r.sign.keyPair=function(){var r=new Uint8Array(Tr),t=new Uint8Array(Yr);return Z(r,t),{publicKey:r,secretKey:t}},r.sign.keyPair.fromSecretKey=function(r){if(Q(r),r.length!==Yr)throw new Error("bad secret key size");for(var t=new Uint8Array(Tr),n=0;n<t.length;n++)t[n]=r[32+n];return{publicKey:t,secretKey:new Uint8Array(r)}},r.sign.keyPair.fromSeed=function(r){if(Q(r),r.length!==kr)throw new Error("bad seed size");for(var t=new Uint8Array(Tr),n=new Uint8Array(Yr),e=0;e<32;e++)n[e]=r[e];return Z(t,n,!0),{publicKey:t,secretKey:n}},r.sign.publicKeyLength=Tr,r.sign.secretKeyLength=Yr,r.sign.seedLength=kr,r.sign.signatureLength=Kr,r.hash=function(r){Q(r);var t=new Uint8Array(Lr);return O(t,r,r.length),t},r.hash.hashLength=Lr,r.verify=function(r,t){return Q(r,t), 0!==r.length&&0!==t.length&&(r.length===t.length&&0===n(r,0,t,0,r.length))},r.setPRNG=function(r){rr=r},function(){var t="undefined"!=typeof self?self.crypto||self.msCrypto:null;if(t&&t.getRandomValues){var n=65536;r.setPRNG(function(r,e){var o,i=new Uint8Array(e);for(o=0;o<e;o+=n)t.getRandomValues(i.subarray(o,o+Math.min(e-o,n)));for(o=0;o<e;o++)r[o]=i[o];W(i)})}else"undefined"!=typeof require&&(t=require("crypto"),t&&t.randomBytes&&r.setPRNG(function(r,n){var e,o=t.randomBytes(n);for(e=0;e<n;e++)r[e]=o[e];W(o)}))}()}("undefined"!=typeof module&&module.exports?module.exports:self.nacl=self.nacl||{});
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/tweetnacl/nacl-fast.min.js
nacl-fast.min.js
The MIT License (MIT) Copyright (c) 2010-2016 Robert Kieffer and other contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/uuid/LICENSE.md
LICENSE.md
var rng = require('uuid/lib/rng'); var bytesToUuid = require('uuid/lib/bytesToUuid'); // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html var _nodeId; var _clockseq; // Previous uuid creation time var _lastMSecs = 0; var _lastNSecs = 0; // See https://github.com/uuidjs/uuid 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;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/uuid/v1.js
v1.js
# Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ## [3.4.0](https://github.com/uuidjs/uuid/compare/v3.3.3...v3.4.0) (2020-01-16) ### Features * rename repository to github:uuidjs/uuid ([#351](https://github.com/uuidjs/uuid/issues/351)) ([e2d7314](https://github.com/uuidjs/uuid/commit/e2d7314)), closes [#338](https://github.com/uuidjs/uuid/issues/338) ### [3.3.3](https://github.com/uuidjs/uuid/compare/v3.3.2...v3.3.3) (2019-08-19) <a name="3.3.2"></a> ## [3.3.2](https://github.com/uuidjs/uuid/compare/v3.3.1...v3.3.2) (2018-06-28) ### Bug Fixes * typo ([305d877](https://github.com/uuidjs/uuid/commit/305d877)) <a name="3.3.1"></a> ## [3.3.1](https://github.com/uuidjs/uuid/compare/v3.3.0...v3.3.1) (2018-06-28) ### Bug Fixes * fix [#284](https://github.com/uuidjs/uuid/issues/284) by setting function name in try-catch ([f2a60f2](https://github.com/uuidjs/uuid/commit/f2a60f2)) <a name="3.3.0"></a> # [3.3.0](https://github.com/uuidjs/uuid/compare/v3.2.1...v3.3.0) (2018-06-22) ### Bug Fixes * assignment to readonly property to allow running in strict mode ([#270](https://github.com/uuidjs/uuid/issues/270)) ([d062fdc](https://github.com/uuidjs/uuid/commit/d062fdc)) * fix [#229](https://github.com/uuidjs/uuid/issues/229) ([c9684d4](https://github.com/uuidjs/uuid/commit/c9684d4)) * Get correct version of IE11 crypto ([#274](https://github.com/uuidjs/uuid/issues/274)) ([153d331](https://github.com/uuidjs/uuid/commit/153d331)) * mem issue when generating uuid ([#267](https://github.com/uuidjs/uuid/issues/267)) ([c47702c](https://github.com/uuidjs/uuid/commit/c47702c)) ### Features * enforce Conventional Commit style commit messages ([#282](https://github.com/uuidjs/uuid/issues/282)) ([cc9a182](https://github.com/uuidjs/uuid/commit/cc9a182)) <a name="3.2.1"></a> ## [3.2.1](https://github.com/uuidjs/uuid/compare/v3.2.0...v3.2.1) (2018-01-16) ### Bug Fixes * use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) <a name="3.2.0"></a> # [3.2.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.2.0) (2018-01-16) ### Bug Fixes * remove mistakenly added typescript dependency, rollback version (standard-version will auto-increment) ([09fa824](https://github.com/uuidjs/uuid/commit/09fa824)) * use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) ### Features * Add v3 Support ([#217](https://github.com/uuidjs/uuid/issues/217)) ([d94f726](https://github.com/uuidjs/uuid/commit/d94f726)) # [3.1.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.0.1) (2017-06-17) ### Bug Fixes * (fix) Add .npmignore file to exclude test/ and other non-essential files from packing. (#183) * Fix typo (#178) * Simple typo fix (#165) ### Features * v5 support in CLI (#197) * V5 support (#188) # 3.0.1 (2016-11-28) * split uuid versions into separate files # 3.0.0 (2016-11-17) * remove .parse and .unparse # 2.0.0 * Removed uuid.BufferClass # 1.4.0 * Improved module context detection * Removed public RNG functions # 1.3.2 * Improve tests and handling of v1() options (Issue #24) * Expose RNG option to allow for perf testing with different generators # 1.3.0 * Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)! * Support for node.js crypto API * De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/uuid/CHANGELOG.md
CHANGELOG.md