code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
'use strict'; function md5(bytes) { if (typeof(bytes) == 'string') { var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape bytes = new Array(msg.length); for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i); } return md5ToHexEncodedArray( wordsToMd5( bytesToWords(bytes) , bytes.length * 8) ); } /* * Convert an array of little-endian words to an array of bytes */ function md5ToHexEncodedArray(input) { var i; var x; var output = []; var length32 = input.length * 32; var hexTab = '0123456789abcdef'; var hex; for (i = 0; i < length32; i += 8) { x = (input[i >> 5] >>> (i % 32)) & 0xFF; hex = parseInt(hexTab.charAt((x >>> 4) & 0x0F) + hexTab.charAt(x & 0x0F), 16); output.push(hex); } return output; } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function wordsToMd5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var i; var olda; var oldb; var oldc; var oldd; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5ff(a, b, c, d, x[i], 7, -680876936); d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5ff(c, d, a, b, x[i + 10], 17, -42063); b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5gg(b, c, d, a, x[i], 20, -373897302); a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5hh(a, b, c, d, x[i + 5], 4, -378558); d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5hh(d, a, b, c, x[i], 11, -358537222); c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5ii(a, b, c, d, x[i], 6, -198630844); d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); a = safeAdd(a, olda); b = safeAdd(b, oldb); c = safeAdd(c, oldc); d = safeAdd(d, oldd); } return [a, b, c, d]; } /* * Convert an array bytes to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function bytesToWords(input) { var i; var output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } var length8 = input.length * 8; for (i = 0; i < length8; i += 8) { output[i >> 5] |= (input[(i / 8)] & 0xFF) << (i % 32); } return output; } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safeAdd(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bitRotateLeft(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * These functions implement the four basic operations the algorithm uses. */ function md5cmn(q, a, b, x, s, t) { return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); } function md5ff(a, b, c, d, x, s, t) { return md5cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5gg(a, b, c, d, x, s, t) { return md5cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5hh(a, b, c, d, x, s, t) { return md5cmn(b ^ c ^ d, a, b, x, s, t); } function md5ii(a, b, c, d, x, s, t) { return md5cmn(c ^ (b | (~d)), a, b, x, s, t); } module.exports = md5;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/uuid/lib/md5-browser.js
md5-browser.js
'use strict'; function f(s, x, y, z) { switch (s) { case 0: return (x & y) ^ (~x & z); case 1: return x ^ y ^ z; case 2: return (x & y) ^ (x & z) ^ (y & z); case 3: return x ^ y ^ z; } } function ROTL(x, n) { return (x << n) | (x>>> (32 - n)); } function sha1(bytes) { var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; if (typeof(bytes) == 'string') { var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape bytes = new Array(msg.length); for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i); } bytes.push(0x80); var l = bytes.length/4 + 2; var N = Math.ceil(l/16); var M = new Array(N); for (var i=0; i<N; i++) { M[i] = new Array(16); for (var j=0; j<16; j++) { M[i][j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; } } M[N - 1][14] = ((bytes.length - 1) * 8) / Math.pow(2, 32); M[N - 1][14] = Math.floor(M[N - 1][14]); M[N - 1][15] = ((bytes.length - 1) * 8) & 0xffffffff; for (var i=0; i<N; i++) { var W = new Array(80); for (var t=0; t<16; t++) W[t] = M[i][t]; for (var t=16; t<80; t++) { W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); } var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; for (var t=0; t<80; t++) { var s = Math.floor(t/20); var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; e = d; d = c; c = ROTL(b, 30) >>> 0; b = a; a = T; } H[0] = (H[0] + a) >>> 0; H[1] = (H[1] + b) >>> 0; H[2] = (H[2] + c) >>> 0; H[3] = (H[3] + d) >>> 0; H[4] = (H[4] + e) >>> 0; } return [ H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff ]; } module.exports = sha1;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/uuid/lib/sha1-browser.js
sha1-browser.js
# Changelog ## Not yet released None yet. ## v1.10.0 * #49 want convenience functions for MultiErrors ## v1.9.0 * #47 could use VError.hasCauseWithName() ## v1.8.1 * #39 captureStackTrace lost when inheriting from WError ## v1.8.0 * #23 Preserve original stack trace(s) ## v1.7.0 * #10 better support for extra properties on Errors * #11 make it easy to find causes of a particular kind * #29 No documentation on how to Install this package * #36 elide development-only files from npm package
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/verror/CHANGES.md
CHANGES.md
# verror: rich JavaScript errors This module provides several classes in support of Joyent's [Best Practices for Error Handling in Node.js](http://www.joyent.com/developers/node/design/errors). If you find any of the behavior here confusing or surprising, check out that document first. The error classes here support: * printf-style arguments for the message * chains of causes * properties to provide extra information about the error * creating your own subclasses that support all of these The classes here are: * **VError**, for chaining errors while preserving each one's error message. This is useful in servers and command-line utilities when you want to propagate an error up a call stack, but allow various levels to add their own context. See examples below. * **WError**, for wrapping errors while hiding the lower-level messages from the top-level error. This is useful for API endpoints where you don't want to expose internal error messages, but you still want to preserve the error chain for logging and debugging. * **SError**, which is just like VError but interprets printf-style arguments more strictly. * **MultiError**, which is just an Error that encapsulates one or more other errors. (This is used for parallel operations that return several errors.) # Quick start First, install the package: npm install verror If nothing else, you can use VError as a drop-in replacement for the built-in JavaScript Error class, with the addition of printf-style messages: ```javascript var err = new VError('missing file: "%s"', '/etc/passwd'); console.log(err.message); ``` This prints: missing file: "/etc/passwd" You can also pass a `cause` argument, which is any other Error object: ```javascript var fs = require('fs'); var filename = '/nonexistent'; fs.stat(filename, function (err1) { var err2 = new VError(err1, 'stat "%s"', filename); console.error(err2.message); }); ``` This prints out: stat "/nonexistent": ENOENT, stat '/nonexistent' which resembles how Unix programs typically report errors: $ sort /nonexistent sort: open failed: /nonexistent: No such file or directory To match the Unixy feel, when you print out the error, just prepend the program's name to the VError's `message`. Or just call [node-cmdutil.fail(your_verror)](https://github.com/joyent/node-cmdutil), which does this for you. You can get the next-level Error using `err.cause()`: ```javascript console.error(err2.cause().message); ``` prints: ENOENT, stat '/nonexistent' Of course, you can chain these as many times as you want, and it works with any kind of Error: ```javascript var err1 = new Error('No such file or directory'); var err2 = new VError(err1, 'failed to stat "%s"', '/junk'); var err3 = new VError(err2, 'request failed'); console.error(err3.message); ``` This prints: request failed: failed to stat "/junk": No such file or directory The idea is that each layer in the stack annotates the error with a description of what it was doing. The end result is a message that explains what happened at each level. You can also decorate Error objects with additional information so that callers can not only handle each kind of error differently, but also construct their own error messages (e.g., to localize them, format them, group them by type, and so on). See the example below. # Deeper dive The two main goals for VError are: * **Make it easy to construct clear, complete error messages intended for people.** Clear error messages greatly improve both user experience and debuggability, so we wanted to make it easy to build them. That's why the constructor takes printf-style arguments. * **Make it easy to construct objects with programmatically-accessible metadata** (which we call _informational properties_). Instead of just saying "connection refused while connecting to 192.168.1.2:80", you can add properties like `"ip": "192.168.1.2"` and `"tcpPort": 80`. This can be used for feeding into monitoring systems, analyzing large numbers of Errors (as from a log file), or localizing error messages. To really make this useful, it also needs to be easy to compose Errors: higher-level code should be able to augment the Errors reported by lower-level code to provide a more complete description of what happened. Instead of saying "connection refused", you can say "operation X failed: connection refused". That's why VError supports `causes`. In order for all this to work, programmers need to know that it's generally safe to wrap lower-level Errors with higher-level ones. If you have existing code that handles Errors produced by a library, you should be able to wrap those Errors with a VError to add information without breaking the error handling code. There are two obvious ways that this could break such consumers: * The error's name might change. People typically use `name` to determine what kind of Error they've got. To ensure compatibility, you can create VErrors with custom names, but this approach isn't great because it prevents you from representing complex failures. For this reason, VError provides `findCauseByName`, which essentially asks: does this Error _or any of its causes_ have this specific type? If error handling code uses `findCauseByName`, then subsystems can construct very specific causal chains for debuggability and still let people handle simple cases easily. There's an example below. * The error's properties might change. People often hang additional properties off of Error objects. If we wrap an existing Error in a new Error, those properties would be lost unless we copied them. But there are a variety of both standard and non-standard Error properties that should _not_ be copied in this way: most obviously `name`, `message`, and `stack`, but also `fileName`, `lineNumber`, and a few others. Plus, it's useful for some Error subclasses to have their own private properties -- and there'd be no way to know whether these should be copied. For these reasons, VError first-classes these information properties. You have to provide them in the constructor, you can only fetch them with the `info()` function, and VError takes care of making sure properties from causes wind up in the `info()` output. Let's put this all together with an example from the node-fast RPC library. node-fast implements a simple RPC protocol for Node programs. There's a server and client interface, and clients make RPC requests to servers. Let's say the server fails with an UnauthorizedError with message "user 'bob' is not authorized". The client wraps all server errors with a FastServerError. The client also wraps all request errors with a FastRequestError that includes the name of the RPC call being made. The result of this failed RPC might look like this: name: FastRequestError message: "request failed: server error: user 'bob' is not authorized" rpcMsgid: <unique identifier for this request> rpcMethod: GetObject cause: name: FastServerError message: "server error: user 'bob' is not authorized" cause: name: UnauthorizedError message: "user 'bob' is not authorized" rpcUser: "bob" When the caller uses `VError.info()`, the information properties are collapsed so that it looks like this: message: "request failed: server error: user 'bob' is not authorized" rpcMsgid: <unique identifier for this request> rpcMethod: GetObject rpcUser: "bob" Taking this apart: * The error's message is a complete description of the problem. The caller can report this directly to its caller, which can potentially make its way back to an end user (if appropriate). It can also be logged. * The caller can tell that the request failed on the server, rather than as a result of a client problem (e.g., failure to serialize the request), a transport problem (e.g., failure to connect to the server), or something else (e.g., a timeout). They do this using `findCauseByName('FastServerError')` rather than checking the `name` field directly. * If the caller logs this error, the logs can be analyzed to aggregate errors by cause, by RPC method name, by user, or whatever. Or the error can be correlated with other events for the same rpcMsgid. * It wasn't very hard for any part of the code to contribute to this Error. Each part of the stack has just a few lines to provide exactly what it knows, with very little boilerplate. It's not expected that you'd use these complex forms all the time. Despite supporting the complex case above, you can still just do: new VError("my service isn't working"); for the simple cases. # Reference: VError, WError, SError VError, WError, and SError are convenient drop-in replacements for `Error` that support printf-style arguments, first-class causes, informational properties, and other useful features. ## Constructors The VError constructor has several forms: ```javascript /* * This is the most general form. You can specify any supported options * (including "cause" and "info") this way. */ new VError(options, sprintf_args...) /* * This is a useful shorthand when the only option you need is "cause". */ new VError(cause, sprintf_args...) /* * This is a useful shorthand when you don't need any options at all. */ new VError(sprintf_args...) ``` All of these forms construct a new VError that behaves just like the built-in JavaScript `Error` class, with some additional methods described below. In the first form, `options` is a plain object with any of the following optional properties: Option name | Type | Meaning ---------------- | ---------------- | ------- `name` | string | Describes what kind of error this is. This is intended for programmatic use to distinguish between different kinds of errors. Note that in modern versions of Node.js, this name is ignored in the `stack` property value, but callers can still use the `name` property to get at it. `cause` | any Error object | Indicates that the new error was caused by `cause`. See `cause()` below. If unspecified, the cause will be `null`. `strict` | boolean | If true, then `null` and `undefined` values in `sprintf_args` are passed through to `sprintf()`. Otherwise, these are replaced with the strings `'null'`, and '`undefined`', respectively. `constructorOpt` | function | If specified, then the stack trace for this error ends at function `constructorOpt`. Functions called by `constructorOpt` will not show up in the stack. This is useful when this class is subclassed. `info` | object | Specifies arbitrary informational properties that are available through the `VError.info(err)` static class method. See that method for details. The second form is equivalent to using the first form with the specified `cause` as the error's cause. This form is distinguished from the first form because the first argument is an Error. The third form is equivalent to using the first form with all default option values. This form is distinguished from the other forms because the first argument is not an object or an Error. The `WError` constructor is used exactly the same way as the `VError` constructor. The `SError` constructor is also used the same way as the `VError` constructor except that in all cases, the `strict` property is overriden to `true. ## Public properties `VError`, `WError`, and `SError` all provide the same public properties as JavaScript's built-in Error objects. Property name | Type | Meaning ------------- | ------ | ------- `name` | string | Programmatically-usable name of the error. `message` | string | Human-readable summary of the failure. Programmatically-accessible details are provided through `VError.info(err)` class method. `stack` | string | Human-readable stack trace where the Error was constructed. For all of these classes, the printf-style arguments passed to the constructor are processed with `sprintf()` to form a message. For `WError`, this becomes the complete `message` property. For `SError` and `VError`, this message is prepended to the message of the cause, if any (with a suitable separator), and the result becomes the `message` property. The `stack` property is managed entirely by the underlying JavaScript implementation. It's generally implemented using a getter function because constructing the human-readable stack trace is somewhat expensive. ## Class methods The following methods are defined on the `VError` class and as exported functions on the `verror` module. They're defined this way rather than using methods on VError instances so that they can be used on Errors not created with `VError`. ### `VError.cause(err)` The `cause()` function returns the next Error in the cause chain for `err`, or `null` if there is no next error. See the `cause` argument to the constructor. Errors can have arbitrarily long cause chains. You can walk the `cause` chain by invoking `VError.cause(err)` on each subsequent return value. If `err` is not a `VError`, the cause is `null`. ### `VError.info(err)` Returns an object with all of the extra error information that's been associated with this Error and all of its causes. These are the properties passed in using the `info` option to the constructor. Properties not specified in the constructor for this Error are implicitly inherited from this error's cause. These properties are intended to provide programmatically-accessible metadata about the error. For an error that indicates a failure to resolve a DNS name, informational properties might include the DNS name to be resolved, or even the list of resolvers used to resolve it. The values of these properties should generally be plain objects (i.e., consisting only of null, undefined, numbers, booleans, strings, and objects and arrays containing only other plain objects). ### `VError.fullStack(err)` Returns a string containing the full stack trace, with all nested errors recursively reported as `'caused by:' + err.stack`. ### `VError.findCauseByName(err, name)` The `findCauseByName()` function traverses the cause chain for `err`, looking for an error whose `name` property matches the passed in `name` value. If no match is found, `null` is returned. If all you want is to know _whether_ there's a cause (and you don't care what it is), you can use `VError.hasCauseWithName(err, name)`. If a vanilla error or a non-VError error is passed in, then there is no cause chain to traverse. In this scenario, the function will check the `name` property of only `err`. ### `VError.hasCauseWithName(err, name)` Returns true if and only if `VError.findCauseByName(err, name)` would return a non-null value. This essentially determines whether `err` has any cause in its cause chain that has name `name`. ### `VError.errorFromList(errors)` Given an array of Error objects (possibly empty), return a single error representing the whole collection of errors. If the list has: * 0 elements, returns `null` * 1 element, returns the sole error * more than 1 element, returns a MultiError referencing the whole list This is useful for cases where an operation may produce any number of errors, and you ultimately want to implement the usual `callback(err)` pattern. You can accumulate the errors in an array and then invoke `callback(VError.errorFromList(errors))` when the operation is complete. ### `VError.errorForEach(err, func)` Convenience function for iterating an error that may itself be a MultiError. In all cases, `err` must be an Error. If `err` is a MultiError, then `func` is invoked as `func(errorN)` for each of the underlying errors of the MultiError. If `err` is any other kind of error, `func` is invoked once as `func(err)`. In all cases, `func` is invoked synchronously. This is useful for cases where an operation may produce any number of warnings that may be encapsulated with a MultiError -- but may not be. This function does not iterate an error's cause chain. ## Examples The "Demo" section above covers several basic cases. Here's a more advanced case: ```javascript var err1 = new VError('something bad happened'); /* ... */ var err2 = new VError({ 'name': 'ConnectionError', 'cause': err1, 'info': { 'errno': 'ECONNREFUSED', 'remote_ip': '127.0.0.1', 'port': 215 } }, 'failed to connect to "%s:%d"', '127.0.0.1', 215); console.log(err2.message); console.log(err2.name); console.log(VError.info(err2)); console.log(err2.stack); ``` This outputs: failed to connect to "127.0.0.1:215": something bad happened ConnectionError { errno: 'ECONNREFUSED', remote_ip: '127.0.0.1', port: 215 } ConnectionError: failed to connect to "127.0.0.1:215": something bad happened at Object.<anonymous> (/home/dap/node-verror/examples/info.js:5:12) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:935:3 Information properties are inherited up the cause chain, with values at the top of the chain overriding same-named values lower in the chain. To continue that example: ```javascript var err3 = new VError({ 'name': 'RequestError', 'cause': err2, 'info': { 'errno': 'EBADREQUEST' } }, 'request failed'); console.log(err3.message); console.log(err3.name); console.log(VError.info(err3)); console.log(err3.stack); ``` This outputs: request failed: failed to connect to "127.0.0.1:215": something bad happened RequestError { errno: 'EBADREQUEST', remote_ip: '127.0.0.1', port: 215 } RequestError: request failed: failed to connect to "127.0.0.1:215": something bad happened at Object.<anonymous> (/home/dap/node-verror/examples/info.js:20:12) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:935:3 You can also print the complete stack trace of combined `Error`s by using `VError.fullStack(err).` ```javascript var err1 = new VError('something bad happened'); /* ... */ var err2 = new VError(err1, 'something really bad happened here'); console.log(VError.fullStack(err2)); ``` This outputs: VError: something really bad happened here: something bad happened at Object.<anonymous> (/home/dap/node-verror/examples/fullStack.js:5:12) at Module._compile (module.js:409:26) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Function.Module.runMain (module.js:441:10) at startup (node.js:139:18) at node.js:968:3 caused by: VError: something bad happened at Object.<anonymous> (/home/dap/node-verror/examples/fullStack.js:3:12) at Module._compile (module.js:409:26) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Function.Module.runMain (module.js:441:10) at startup (node.js:139:18) at node.js:968:3 `VError.fullStack` is also safe to use on regular `Error`s, so feel free to use it whenever you need to extract the stack trace from an `Error`, regardless if it's a `VError` or not. # Reference: MultiError MultiError is an Error class that represents a group of Errors. This is used when you logically need to provide a single Error, but you want to preserve information about multiple underying Errors. A common case is when you execute several operations in parallel and some of them fail. MultiErrors are constructed as: ```javascript new MultiError(error_list) ``` `error_list` is an array of at least one `Error` object. The cause of the MultiError is the first error provided. None of the other `VError` options are supported. The `message` for a MultiError consists the `message` from the first error, prepended with a message indicating that there were other errors. For example: ```javascript err = new MultiError([ new Error('failed to resolve DNS name "abc.example.com"'), new Error('failed to resolve DNS name "def.example.com"'), ]); console.error(err.message); ``` outputs: first of 2 errors: failed to resolve DNS name "abc.example.com" See the convenience function `VError.errorFromList`, which is sometimes simpler to use than this constructor. ## Public methods ### `errors()` Returns an array of the errors used to construct this MultiError. # Contributing See separate [contribution guidelines](CONTRIBUTING.md).
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/verror/README.md
README.md
# Contributing This repository uses [cr.joyent.us](https://cr.joyent.us) (Gerrit) for new changes. Anyone can submit changes. To get started, see the [cr.joyent.us user guide](https://github.com/joyent/joyent-gerrit/blob/master/docs/user/README.md). This repo does not use GitHub pull requests. See the [Joyent Engineering Guidelines](https://github.com/joyent/eng/blob/master/docs/index.md) for general best practices expected in this repository. Contributions should be "make prepush" clean. The "prepush" target runs the "check" target, which requires these separate tools: * https://github.com/davepacheco/jsstyle * https://github.com/davepacheco/javascriptlint If you're changing something non-trivial or user-facing, you may want to submit an issue first.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/verror/CONTRIBUTING.md
CONTRIBUTING.md
var mod_assertplus = require('assert-plus'); var mod_util = require('util'); var mod_extsprintf = require('extsprintf'); var mod_isError = require('core-util-is').isError; var sprintf = mod_extsprintf.sprintf; /* * Public interface */ /* So you can 'var VError = require('verror')' */ module.exports = VError; /* For compatibility */ VError.VError = VError; /* Other exported classes */ VError.SError = SError; VError.WError = WError; VError.MultiError = MultiError; /* * Common function used to parse constructor arguments for VError, WError, and * SError. Named arguments to this function: * * strict force strict interpretation of sprintf arguments, even * if the options in "argv" don't say so * * argv error's constructor arguments, which are to be * interpreted as described in README.md. For quick * reference, "argv" has one of the following forms: * * [ sprintf_args... ] (argv[0] is a string) * [ cause, sprintf_args... ] (argv[0] is an Error) * [ options, sprintf_args... ] (argv[0] is an object) * * This function normalizes these forms, producing an object with the following * properties: * * options equivalent to "options" in third form. This will never * be a direct reference to what the caller passed in * (i.e., it may be a shallow copy), so it can be freely * modified. * * shortmessage result of sprintf(sprintf_args), taking options.strict * into account as described in README.md. */ function parseConstructorArguments(args) { var argv, options, sprintf_args, shortmessage, k; mod_assertplus.object(args, 'args'); mod_assertplus.bool(args.strict, 'args.strict'); mod_assertplus.array(args.argv, 'args.argv'); argv = args.argv; /* * First, figure out which form of invocation we've been given. */ if (argv.length === 0) { options = {}; sprintf_args = []; } else if (mod_isError(argv[0])) { options = { 'cause': argv[0] }; sprintf_args = argv.slice(1); } else if (typeof (argv[0]) === 'object') { options = {}; for (k in argv[0]) { options[k] = argv[0][k]; } sprintf_args = argv.slice(1); } else { mod_assertplus.string(argv[0], 'first argument to VError, SError, or WError ' + 'constructor must be a string, object, or Error'); options = {}; sprintf_args = argv; } /* * Now construct the error's message. * * extsprintf (which we invoke here with our caller's arguments in order * to construct this Error's message) is strict in its interpretation of * values to be processed by the "%s" specifier. The value passed to * extsprintf must actually be a string or something convertible to a * String using .toString(). Passing other values (notably "null" and * "undefined") is considered a programmer error. The assumption is * that if you actually want to print the string "null" or "undefined", * then that's easy to do that when you're calling extsprintf; on the * other hand, if you did NOT want that (i.e., there's actually a bug * where the program assumes some variable is non-null and tries to * print it, which might happen when constructing a packet or file in * some specific format), then it's better to stop immediately than * produce bogus output. * * However, sometimes the bug is only in the code calling VError, and a * programmer might prefer to have the error message contain "null" or * "undefined" rather than have the bug in the error path crash the * program (making the first bug harder to identify). For that reason, * by default VError converts "null" or "undefined" arguments to their * string representations and passes those to extsprintf. Programmers * desiring the strict behavior can use the SError class or pass the * "strict" option to the VError constructor. */ mod_assertplus.object(options); if (!options.strict && !args.strict) { sprintf_args = sprintf_args.map(function (a) { return (a === null ? 'null' : a === undefined ? 'undefined' : a); }); } if (sprintf_args.length === 0) { shortmessage = ''; } else { shortmessage = sprintf.apply(null, sprintf_args); } return ({ 'options': options, 'shortmessage': shortmessage }); } /* * See README.md for reference documentation. */ function VError() { var args, obj, parsed, cause, ctor, message, k; args = Array.prototype.slice.call(arguments, 0); /* * This is a regrettable pattern, but JavaScript's built-in Error class * is defined to work this way, so we allow the constructor to be called * without "new". */ if (!(this instanceof VError)) { obj = Object.create(VError.prototype); VError.apply(obj, arguments); return (obj); } /* * For convenience and backwards compatibility, we support several * different calling forms. Normalize them here. */ parsed = parseConstructorArguments({ 'argv': args, 'strict': false }); /* * If we've been given a name, apply it now. */ if (parsed.options.name) { mod_assertplus.string(parsed.options.name, 'error\'s "name" must be a string'); this.name = parsed.options.name; } /* * For debugging, we keep track of the original short message (attached * this Error particularly) separately from the complete message (which * includes the messages of our cause chain). */ this.jse_shortmsg = parsed.shortmessage; message = parsed.shortmessage; /* * If we've been given a cause, record a reference to it and update our * message appropriately. */ cause = parsed.options.cause; if (cause) { mod_assertplus.ok(mod_isError(cause), 'cause is not an Error'); this.jse_cause = cause; if (!parsed.options.skipCauseMessage) { message += ': ' + cause.message; } } /* * If we've been given an object with properties, shallow-copy that * here. We don't want to use a deep copy in case there are non-plain * objects here, but we don't want to use the original object in case * the caller modifies it later. */ this.jse_info = {}; if (parsed.options.info) { for (k in parsed.options.info) { this.jse_info[k] = parsed.options.info[k]; } } this.message = message; Error.call(this, message); if (Error.captureStackTrace) { ctor = parsed.options.constructorOpt || this.constructor; Error.captureStackTrace(this, ctor); } return (this); } mod_util.inherits(VError, Error); VError.prototype.name = 'VError'; VError.prototype.toString = function ve_toString() { var str = (this.hasOwnProperty('name') && this.name || this.constructor.name || this.constructor.prototype.name); if (this.message) str += ': ' + this.message; return (str); }; /* * This method is provided for compatibility. New callers should use * VError.cause() instead. That method also uses the saner `null` return value * when there is no cause. */ VError.prototype.cause = function ve_cause() { var cause = VError.cause(this); return (cause === null ? undefined : cause); }; /* * Static methods * * These class-level methods are provided so that callers can use them on * instances of Errors that are not VErrors. New interfaces should be provided * only using static methods to eliminate the class of programming mistake where * people fail to check whether the Error object has the corresponding methods. */ VError.cause = function (err) { mod_assertplus.ok(mod_isError(err), 'err must be an Error'); return (mod_isError(err.jse_cause) ? err.jse_cause : null); }; VError.info = function (err) { var rv, cause, k; mod_assertplus.ok(mod_isError(err), 'err must be an Error'); cause = VError.cause(err); if (cause !== null) { rv = VError.info(cause); } else { rv = {}; } if (typeof (err.jse_info) == 'object' && err.jse_info !== null) { for (k in err.jse_info) { rv[k] = err.jse_info[k]; } } return (rv); }; VError.findCauseByName = function (err, name) { var cause; mod_assertplus.ok(mod_isError(err), 'err must be an Error'); mod_assertplus.string(name, 'name'); mod_assertplus.ok(name.length > 0, 'name cannot be empty'); for (cause = err; cause !== null; cause = VError.cause(cause)) { mod_assertplus.ok(mod_isError(cause)); if (cause.name == name) { return (cause); } } return (null); }; VError.hasCauseWithName = function (err, name) { return (VError.findCauseByName(err, name) !== null); }; VError.fullStack = function (err) { mod_assertplus.ok(mod_isError(err), 'err must be an Error'); var cause = VError.cause(err); if (cause) { return (err.stack + '\ncaused by: ' + VError.fullStack(cause)); } return (err.stack); }; VError.errorFromList = function (errors) { mod_assertplus.arrayOfObject(errors, 'errors'); if (errors.length === 0) { return (null); } errors.forEach(function (e) { mod_assertplus.ok(mod_isError(e)); }); if (errors.length == 1) { return (errors[0]); } return (new MultiError(errors)); }; VError.errorForEach = function (err, func) { mod_assertplus.ok(mod_isError(err), 'err must be an Error'); mod_assertplus.func(func, 'func'); if (err instanceof MultiError) { err.errors().forEach(function iterError(e) { func(e); }); } else { func(err); } }; /* * SError is like VError, but stricter about types. You cannot pass "null" or * "undefined" as string arguments to the formatter. */ function SError() { var args, obj, parsed, options; args = Array.prototype.slice.call(arguments, 0); if (!(this instanceof SError)) { obj = Object.create(SError.prototype); SError.apply(obj, arguments); return (obj); } parsed = parseConstructorArguments({ 'argv': args, 'strict': true }); options = parsed.options; VError.call(this, options, '%s', parsed.shortmessage); return (this); } /* * We don't bother setting SError.prototype.name because once constructed, * SErrors are just like VErrors. */ mod_util.inherits(SError, VError); /* * Represents a collection of errors for the purpose of consumers that generally * only deal with one error. Callers can extract the individual errors * contained in this object, but may also just treat it as a normal single * error, in which case a summary message will be printed. */ function MultiError(errors) { mod_assertplus.array(errors, 'list of errors'); mod_assertplus.ok(errors.length > 0, 'must be at least one error'); this.ase_errors = errors; VError.call(this, { 'cause': errors[0] }, 'first of %d error%s', errors.length, errors.length == 1 ? '' : 's'); } mod_util.inherits(MultiError, VError); MultiError.prototype.name = 'MultiError'; MultiError.prototype.errors = function me_errors() { return (this.ase_errors.slice(0)); }; /* * See README.md for reference details. */ function WError() { var args, obj, parsed, options; args = Array.prototype.slice.call(arguments, 0); if (!(this instanceof WError)) { obj = Object.create(WError.prototype); WError.apply(obj, args); return (obj); } parsed = parseConstructorArguments({ 'argv': args, 'strict': false }); options = parsed.options; options['skipCauseMessage'] = true; VError.call(this, options, '%s', parsed.shortmessage); return (this); } mod_util.inherits(WError, VError); WError.prototype.name = 'WError'; WError.prototype.toString = function we_toString() { var str = (this.hasOwnProperty('name') && this.name || this.constructor.name || this.constructor.prototype.name); if (this.message) str += ': ' + this.message; if (this.jse_cause && this.jse_cause.message) str += '; caused by ' + this.jse_cause.toString(); return (str); }; /* * For purely historical reasons, WError's cause() function allows you to set * the cause. */ WError.prototype.cause = function we_cause(c) { if (mod_isError(c)) this.jse_cause = c; return (this.jse_cause); };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/verror/lib/verror.js
verror.js
# Parse, serialize, and manipulate MIME types This package will parse [MIME types](https://mimesniff.spec.whatwg.org/#understanding-mime-types) into a structured format, which can then be manipulated and serialized: ```js const MIMEType = require("whatwg-mimetype"); const mimeType = new MIMEType(`Text/HTML;Charset="utf-8"`); console.assert(mimeType.toString() === "text/html;charset=utf-8"); console.assert(mimeType.type === "text"); console.assert(mimeType.subtype === "html"); console.assert(mimeType.essence === "text/html"); console.assert(mimeType.parameters.get("charset") === "utf-8"); mimeType.parameters.set("charset", "windows-1252"); console.assert(mimeType.parameters.get("charset") === "windows-1252"); console.assert(mimeType.toString() === "text/html;charset=windows-1252"); console.assert(mimeType.isHTML() === true); console.assert(mimeType.isXML() === false); ``` Parsing is a fairly complex process; see [the specification](https://mimesniff.spec.whatwg.org/#parsing-a-mime-type) for details (and similarly [for serialization](https://mimesniff.spec.whatwg.org/#serializing-a-mime-type)). This package's algorithms conform to those of the WHATWG [MIME Sniffing Standard](https://mimesniff.spec.whatwg.org/), and is aligned up to commit [126286a](https://github.com/whatwg/mimesniff/commit/126286ab2dcf3e2d541349ed93539a88bf394ad5). ## `MIMEType` API This package's main module's default export is a class, `MIMEType`. Its constructor takes a string which it will attempt to parse into a MIME type; if parsing fails, an `Error` will be thrown. ### The `parse()` static factory method As an alternative to the constructor, you can use `MIMEType.parse(string)`. The only difference is that `parse()` will return `null` on failed parsing, whereas the constructor will throw. It thus makes the most sense to use the constructor in cases where unparseable MIME types would be exceptional, and use `parse()` when dealing with input from some unconstrained source. ### Properties - `type`: the MIME type's [type](https://mimesniff.spec.whatwg.org/#mime-type-type), e.g. `"text"` - `subtype`: the MIME type's [subtype](https://mimesniff.spec.whatwg.org/#mime-type-subtype), e.g. `"html"` - `essence`: the MIME type's [essence](https://mimesniff.spec.whatwg.org/#mime-type-essence), e.g. `"text/html"` - `parameters`: an instance of `MIMETypeParameters`, containing this MIME type's [parameters](https://mimesniff.spec.whatwg.org/#mime-type-parameters) `type` and `subtype` can be changed. They will be validated to be non-empty and only contain [HTTP token code points](https://mimesniff.spec.whatwg.org/#http-token-code-point). `essence` is only a getter, and cannot be changed. `parameters` is also a getter, but the contents of the `MIMETypeParameters` object are mutable, as described below. ### Methods - `toString()` serializes the MIME type to a string - `isHTML()`: returns true if this instance represents [a HTML MIME type](https://mimesniff.spec.whatwg.org/#html-mime-type) - `isXML()`: returns true if this instance represents [an XML MIME type](https://mimesniff.spec.whatwg.org/#xml-mime-type) - `isJavaScript({ allowParameters })`: returns true if this instance represents [a JavaScript MIME type](https://html.spec.whatwg.org/multipage/scripting.html#javascript-mime-type); `allowParameters` can be set to true to allow arbitrary parameters, instead of their presence causing the method to return `false` _Note: the `isHTML()`, `isXML()`, and `isJavaScript()` methods are speculative, and may be removed or changed in future major versions. See [whatwg/mimesniff#48](https://github.com/whatwg/mimesniff/issues/48) for brainstorming in this area. Currently we implement these mainly because they are useful in jsdom._ ## `MIMETypeParameters` API The `MIMETypeParameters` class, instances of which are returned by `mimeType.parameters`, has equivalent surface API to a [JavaScript `Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map). However, `MIMETypeParameters` methods will always interpret their arguments as appropriate for MIME types, so e.g. parameter names will be lowercased, and attempting to set invalid characters will throw. Some examples: ```js const mimeType = new MIMEType(`x/x;a=b;c=D;E="F"`); // Logs: // a b // c D // e F for (const [name, value] of mimeType.parameters) { console.log(name, value); } console.assert(mimeType.parameters.has("a")); console.assert(mimeType.parameters.has("A")); console.assert(mimeType.parameters.get("A") === "b"); mimeType.parameters.set("Q", "X"); console.assert(mimeType.parameters.get("q") === "X"); console.assert(mimeType.toString() === "x/x;a=b;c=d;e=F;q=X"); // Throws: mimeType.parameters.set("@", "x"); ``` ## Raw parsing/serialization APIs If you want primitives on which to build your own API, you can get direct access to the parsing and serialization algorithms as follows: ```js const parse = require("whatwg-mimetype/parser"); const serialize = require("whatwg-mimetype/serialize"); ``` `parse(string)` returns an object containing the `type` and `subtype` strings, plus `parameters`, which is a `Map`. This is roughly our equivalent of the spec's [MIME type record](https://mimesniff.spec.whatwg.org/#mime-type). If parsing fails, it instead returns `null`. `serialize(record)` operates on the such an object, giving back a string according to the serialization algorithm.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/whatwg-mimetype/README.md
README.md
"use strict"; const { removeLeadingAndTrailingHTTPWhitespace, removeTrailingHTTPWhitespace, isHTTPWhitespaceChar, solelyContainsHTTPTokenCodePoints, soleyContainsHTTPQuotedStringTokenCodePoints, asciiLowercase } = require("whatwg-mimetype/lib/utils.js"); module.exports = input => { input = removeLeadingAndTrailingHTTPWhitespace(input); let position = 0; let type = ""; while (position < input.length && input[position] !== "/") { type += input[position]; ++position; } if (type.length === 0 || !solelyContainsHTTPTokenCodePoints(type)) { return null; } if (position >= input.length) { return null; } // Skips past "/" ++position; let subtype = ""; while (position < input.length && input[position] !== ";") { subtype += input[position]; ++position; } subtype = removeTrailingHTTPWhitespace(subtype); if (subtype.length === 0 || !solelyContainsHTTPTokenCodePoints(subtype)) { return null; } const mimeType = { type: asciiLowercase(type), subtype: asciiLowercase(subtype), parameters: new Map() }; while (position < input.length) { // Skip past ";" ++position; while (isHTTPWhitespaceChar(input[position])) { ++position; } let parameterName = ""; while (position < input.length && input[position] !== ";" && input[position] !== "=") { parameterName += input[position]; ++position; } parameterName = asciiLowercase(parameterName); if (position < input.length) { if (input[position] === ";") { continue; } // Skip past "=" ++position; } let parameterValue = ""; if (input[position] === "\"") { ++position; while (true) { while (position < input.length && input[position] !== "\"" && input[position] !== "\\") { parameterValue += input[position]; ++position; } if (position < input.length && input[position] === "\\") { ++position; if (position < input.length) { parameterValue += input[position]; ++position; continue; } else { parameterValue += "\\"; break; } } else { break; } } while (position < input.length && input[position] !== ";") { ++position; } } else { while (position < input.length && input[position] !== ";") { parameterValue += input[position]; ++position; } parameterValue = removeTrailingHTTPWhitespace(parameterValue); if (parameterValue === "") { continue; } } if (parameterName.length > 0 && solelyContainsHTTPTokenCodePoints(parameterName) && soleyContainsHTTPQuotedStringTokenCodePoints(parameterValue) && !mimeType.parameters.has(parameterName)) { mimeType.parameters.set(parameterName, parameterValue); } } return mimeType; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/whatwg-mimetype/lib/parser.js
parser.js
"use strict"; const parse = require("whatwg-mimetype/lib/parser.js"); const serialize = require("whatwg-mimetype/lib/serializer.js"); const { asciiLowercase, solelyContainsHTTPTokenCodePoints, soleyContainsHTTPQuotedStringTokenCodePoints } = require("whatwg-mimetype/lib/utils.js"); module.exports = class MIMEType { constructor(string) { string = String(string); const result = parse(string); if (result === null) { throw new Error(`Could not parse MIME type string "${string}"`); } this._type = result.type; this._subtype = result.subtype; this._parameters = new MIMETypeParameters(result.parameters); } static parse(string) { try { return new this(string); } catch (e) { return null; } } get essence() { return `${this.type}/${this.subtype}`; } get type() { return this._type; } set type(value) { value = asciiLowercase(String(value)); if (value.length === 0) { throw new Error("Invalid type: must be a non-empty string"); } if (!solelyContainsHTTPTokenCodePoints(value)) { throw new Error(`Invalid type ${value}: must contain only HTTP token code points`); } this._type = value; } get subtype() { return this._subtype; } set subtype(value) { value = asciiLowercase(String(value)); if (value.length === 0) { throw new Error("Invalid subtype: must be a non-empty string"); } if (!solelyContainsHTTPTokenCodePoints(value)) { throw new Error(`Invalid subtype ${value}: must contain only HTTP token code points`); } this._subtype = value; } get parameters() { return this._parameters; } toString() { // The serialize function works on both "MIME type records" (i.e. the results of parse) and on this class, since // this class's interface is identical. return serialize(this); } isJavaScript({ allowParameters = false } = {}) { switch (this._type) { case "text": { switch (this._subtype) { case "ecmascript": case "javascript": case "javascript1.0": case "javascript1.1": case "javascript1.2": case "javascript1.3": case "javascript1.4": case "javascript1.5": case "jscript": case "livescript": case "x-ecmascript": case "x-javascript": { return allowParameters || this._parameters.size === 0; } default: { return false; } } } case "application": { switch (this._subtype) { case "ecmascript": case "javascript": case "x-ecmascript": case "x-javascript": { return allowParameters || this._parameters.size === 0; } default: { return false; } } } default: { return false; } } } isXML() { return (this._subtype === "xml" && (this._type === "text" || this._type === "application")) || this._subtype.endsWith("+xml"); } isHTML() { return this._subtype === "html" && this._type === "text"; } }; class MIMETypeParameters { constructor(map) { this._map = map; } get size() { return this._map.size; } get(name) { name = asciiLowercase(String(name)); return this._map.get(name); } has(name) { name = asciiLowercase(String(name)); return this._map.has(name); } set(name, value) { name = asciiLowercase(String(name)); value = String(value); if (!solelyContainsHTTPTokenCodePoints(name)) { throw new Error(`Invalid MIME type parameter name "${name}": only HTTP token code points are valid.`); } if (!soleyContainsHTTPQuotedStringTokenCodePoints(value)) { throw new Error(`Invalid MIME type parameter value "${value}": only HTTP quoted-string token code points are ` + `valid.`); } return this._map.set(name, value); } clear() { this._map.clear(); } delete(name) { name = asciiLowercase(String(name)); return this._map.delete(name); } forEach(callbackFn, thisArg) { this._map.forEach(callbackFn, thisArg); } keys() { return this._map.keys(); } values() { return this._map.values(); } entries() { return this._map.entries(); } [Symbol.iterator]() { return this._map[Symbol.iterator](); } }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/whatwg-mimetype/lib/mime-type.js
mime-type.js
<p align="center"> <a href="https://github.com/inikulin/parse5"> <img src="https://raw.github.com/inikulin/parse5/master/media/logo.png" alt="parse5" /> </a> </p> <div align="center"> <h1>parse5</h1> <i><b>HTML parser and serializer.</b></i> </div> <br> <div align="center"> <code>npm install --save parse5</code> </div> <br> <p align="center"> 📖 <a href="https://github.com/inikulin/parse5/tree/master/packages/parse5/docs/index.md"><b>Documentation</b></a> 📖 </p> --- <p align="center"> <a href="https://github.com/inikulin/parse5/tree/master/docs/list-of-packages.md">List of parse5 toolset packages</a> </p> <p align="center"> <a href="https://github.com/inikulin/parse5">GitHub</a> </p> <p align="center"> <a href="http://astexplorer.net/#/1CHlCXc4n4">Online playground</a> </p> <p align="center"> <a href="https://github.com/inikulin/parse5/tree/master/docs/version-history.md">Version history</a> </p>
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/parse5/README.md
README.md
'use strict'; const Mixin = require('parse5/lib/utils/mixin'); const Tokenizer = require('parse5/lib/tokenizer'); const PositionTrackingPreprocessorMixin = require('parse5/lib/extensions/position-tracking/preprocessor-mixin'); class LocationInfoTokenizerMixin extends Mixin { constructor(tokenizer) { super(tokenizer); this.tokenizer = tokenizer; this.posTracker = Mixin.install(tokenizer.preprocessor, PositionTrackingPreprocessorMixin); this.currentAttrLocation = null; this.ctLoc = null; } _getCurrentLocation() { return { startLine: this.posTracker.line, startCol: this.posTracker.col, startOffset: this.posTracker.offset, endLine: -1, endCol: -1, endOffset: -1 }; } _attachCurrentAttrLocationInfo() { this.currentAttrLocation.endLine = this.posTracker.line; this.currentAttrLocation.endCol = this.posTracker.col; this.currentAttrLocation.endOffset = this.posTracker.offset; const currentToken = this.tokenizer.currentToken; const currentAttr = this.tokenizer.currentAttr; if (!currentToken.location.attrs) { currentToken.location.attrs = Object.create(null); } currentToken.location.attrs[currentAttr.name] = this.currentAttrLocation; } _getOverriddenMethods(mxn, orig) { const methods = { _createStartTagToken() { orig._createStartTagToken.call(this); this.currentToken.location = mxn.ctLoc; }, _createEndTagToken() { orig._createEndTagToken.call(this); this.currentToken.location = mxn.ctLoc; }, _createCommentToken() { orig._createCommentToken.call(this); this.currentToken.location = mxn.ctLoc; }, _createDoctypeToken(initialName) { orig._createDoctypeToken.call(this, initialName); this.currentToken.location = mxn.ctLoc; }, _createCharacterToken(type, ch) { orig._createCharacterToken.call(this, type, ch); this.currentCharacterToken.location = mxn.ctLoc; }, _createEOFToken() { orig._createEOFToken.call(this); this.currentToken.location = mxn._getCurrentLocation(); }, _createAttr(attrNameFirstCh) { orig._createAttr.call(this, attrNameFirstCh); mxn.currentAttrLocation = mxn._getCurrentLocation(); }, _leaveAttrName(toState) { orig._leaveAttrName.call(this, toState); mxn._attachCurrentAttrLocationInfo(); }, _leaveAttrValue(toState) { orig._leaveAttrValue.call(this, toState); mxn._attachCurrentAttrLocationInfo(); }, _emitCurrentToken() { const ctLoc = this.currentToken.location; //NOTE: if we have pending character token make it's end location equal to the //current token's start location. if (this.currentCharacterToken) { this.currentCharacterToken.location.endLine = ctLoc.startLine; this.currentCharacterToken.location.endCol = ctLoc.startCol; this.currentCharacterToken.location.endOffset = ctLoc.startOffset; } if (this.currentToken.type === Tokenizer.EOF_TOKEN) { ctLoc.endLine = ctLoc.startLine; ctLoc.endCol = ctLoc.startCol; ctLoc.endOffset = ctLoc.startOffset; } else { ctLoc.endLine = mxn.posTracker.line; ctLoc.endCol = mxn.posTracker.col + 1; ctLoc.endOffset = mxn.posTracker.offset + 1; } orig._emitCurrentToken.call(this); }, _emitCurrentCharacterToken() { const ctLoc = this.currentCharacterToken && this.currentCharacterToken.location; //NOTE: if we have character token and it's location wasn't set in the _emitCurrentToken(), //then set it's location at the current preprocessor position. //We don't need to increment preprocessor position, since character token //emission is always forced by the start of the next character token here. //So, we already have advanced position. if (ctLoc && ctLoc.endOffset === -1) { ctLoc.endLine = mxn.posTracker.line; ctLoc.endCol = mxn.posTracker.col; ctLoc.endOffset = mxn.posTracker.offset; } orig._emitCurrentCharacterToken.call(this); } }; //NOTE: patch initial states for each mode to obtain token start position Object.keys(Tokenizer.MODE).forEach(modeName => { const state = Tokenizer.MODE[modeName]; methods[state] = function(cp) { mxn.ctLoc = mxn._getCurrentLocation(); orig[state].call(this, cp); }; }); return methods; } } module.exports = LocationInfoTokenizerMixin;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/parse5/lib/extensions/location-info/tokenizer-mixin.js
tokenizer-mixin.js
'use strict'; const Mixin = require('parse5/lib/utils/mixin'); const Tokenizer = require('parse5/lib/tokenizer'); const LocationInfoTokenizerMixin = require('parse5/lib/extensions/location-info/tokenizer-mixin'); const LocationInfoOpenElementStackMixin = require('parse5/lib/extensions/location-info/open-element-stack-mixin'); const HTML = require('parse5/lib/common/html'); //Aliases const $ = HTML.TAG_NAMES; class LocationInfoParserMixin extends Mixin { constructor(parser) { super(parser); this.parser = parser; this.treeAdapter = this.parser.treeAdapter; this.posTracker = null; this.lastStartTagToken = null; this.lastFosterParentingLocation = null; this.currentToken = null; } _setStartLocation(element) { let loc = null; if (this.lastStartTagToken) { loc = Object.assign({}, this.lastStartTagToken.location); loc.startTag = this.lastStartTagToken.location; } this.treeAdapter.setNodeSourceCodeLocation(element, loc); } _setEndLocation(element, closingToken) { const loc = this.treeAdapter.getNodeSourceCodeLocation(element); if (loc) { if (closingToken.location) { const ctLoc = closingToken.location; const tn = this.treeAdapter.getTagName(element); // NOTE: For cases like <p> <p> </p> - First 'p' closes without a closing // tag and for cases like <td> <p> </td> - 'p' closes without a closing tag. const isClosingEndTag = closingToken.type === Tokenizer.END_TAG_TOKEN && tn === closingToken.tagName; if (isClosingEndTag) { loc.endTag = Object.assign({}, ctLoc); loc.endLine = ctLoc.endLine; loc.endCol = ctLoc.endCol; loc.endOffset = ctLoc.endOffset; } else { loc.endLine = ctLoc.startLine; loc.endCol = ctLoc.startCol; loc.endOffset = ctLoc.startOffset; } } } } _getOverriddenMethods(mxn, orig) { return { _bootstrap(document, fragmentContext) { orig._bootstrap.call(this, document, fragmentContext); mxn.lastStartTagToken = null; mxn.lastFosterParentingLocation = null; mxn.currentToken = null; const tokenizerMixin = Mixin.install(this.tokenizer, LocationInfoTokenizerMixin); mxn.posTracker = tokenizerMixin.posTracker; Mixin.install(this.openElements, LocationInfoOpenElementStackMixin, { onItemPop: function(element) { mxn._setEndLocation(element, mxn.currentToken); } }); }, _runParsingLoop(scriptHandler) { orig._runParsingLoop.call(this, scriptHandler); // NOTE: generate location info for elements // that remains on open element stack for (let i = this.openElements.stackTop; i >= 0; i--) { mxn._setEndLocation(this.openElements.items[i], mxn.currentToken); } }, //Token processing _processTokenInForeignContent(token) { mxn.currentToken = token; orig._processTokenInForeignContent.call(this, token); }, _processToken(token) { mxn.currentToken = token; orig._processToken.call(this, token); //NOTE: <body> and <html> are never popped from the stack, so we need to updated //their end location explicitly. const requireExplicitUpdate = token.type === Tokenizer.END_TAG_TOKEN && (token.tagName === $.HTML || (token.tagName === $.BODY && this.openElements.hasInScope($.BODY))); if (requireExplicitUpdate) { for (let i = this.openElements.stackTop; i >= 0; i--) { const element = this.openElements.items[i]; if (this.treeAdapter.getTagName(element) === token.tagName) { mxn._setEndLocation(element, token); break; } } } }, //Doctype _setDocumentType(token) { orig._setDocumentType.call(this, token); const documentChildren = this.treeAdapter.getChildNodes(this.document); const cnLength = documentChildren.length; for (let i = 0; i < cnLength; i++) { const node = documentChildren[i]; if (this.treeAdapter.isDocumentTypeNode(node)) { this.treeAdapter.setNodeSourceCodeLocation(node, token.location); break; } } }, //Elements _attachElementToTree(element) { //NOTE: _attachElementToTree is called from _appendElement, _insertElement and _insertTemplate methods. //So we will use token location stored in this methods for the element. mxn._setStartLocation(element); mxn.lastStartTagToken = null; orig._attachElementToTree.call(this, element); }, _appendElement(token, namespaceURI) { mxn.lastStartTagToken = token; orig._appendElement.call(this, token, namespaceURI); }, _insertElement(token, namespaceURI) { mxn.lastStartTagToken = token; orig._insertElement.call(this, token, namespaceURI); }, _insertTemplate(token) { mxn.lastStartTagToken = token; orig._insertTemplate.call(this, token); const tmplContent = this.treeAdapter.getTemplateContent(this.openElements.current); this.treeAdapter.setNodeSourceCodeLocation(tmplContent, null); }, _insertFakeRootElement() { orig._insertFakeRootElement.call(this); this.treeAdapter.setNodeSourceCodeLocation(this.openElements.current, null); }, //Comments _appendCommentNode(token, parent) { orig._appendCommentNode.call(this, token, parent); const children = this.treeAdapter.getChildNodes(parent); const commentNode = children[children.length - 1]; this.treeAdapter.setNodeSourceCodeLocation(commentNode, token.location); }, //Text _findFosterParentingLocation() { //NOTE: store last foster parenting location, so we will be able to find inserted text //in case of foster parenting mxn.lastFosterParentingLocation = orig._findFosterParentingLocation.call(this); return mxn.lastFosterParentingLocation; }, _insertCharacters(token) { orig._insertCharacters.call(this, token); const hasFosterParent = this._shouldFosterParentOnInsertion(); const parent = (hasFosterParent && mxn.lastFosterParentingLocation.parent) || this.openElements.currentTmplContent || this.openElements.current; const siblings = this.treeAdapter.getChildNodes(parent); const textNodeIdx = hasFosterParent && mxn.lastFosterParentingLocation.beforeElement ? siblings.indexOf(mxn.lastFosterParentingLocation.beforeElement) - 1 : siblings.length - 1; const textNode = siblings[textNodeIdx]; //NOTE: if we have location assigned by another token, then just update end position const tnLoc = this.treeAdapter.getNodeSourceCodeLocation(textNode); if (tnLoc) { tnLoc.endLine = token.location.endLine; tnLoc.endCol = token.location.endCol; tnLoc.endOffset = token.location.endOffset; } else { this.treeAdapter.setNodeSourceCodeLocation(textNode, token.location); } } }; } } module.exports = LocationInfoParserMixin;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/parse5/lib/extensions/location-info/parser-mixin.js
parser-mixin.js
'use strict'; const defaultTreeAdapter = require('parse5/lib/tree-adapters/default'); const mergeOptions = require('parse5/lib/utils/merge-options'); const doctype = require('parse5/lib/common/doctype'); const HTML = require('parse5/lib/common/html'); //Aliases const $ = HTML.TAG_NAMES; const NS = HTML.NAMESPACES; //Default serializer options const DEFAULT_OPTIONS = { treeAdapter: defaultTreeAdapter }; //Escaping regexes const AMP_REGEX = /&/g; const NBSP_REGEX = /\u00a0/g; const DOUBLE_QUOTE_REGEX = /"/g; const LT_REGEX = /</g; const GT_REGEX = />/g; //Serializer class Serializer { constructor(node, options) { this.options = mergeOptions(DEFAULT_OPTIONS, options); this.treeAdapter = this.options.treeAdapter; this.html = ''; this.startNode = node; } //API serialize() { this._serializeChildNodes(this.startNode); return this.html; } //Internals _serializeChildNodes(parentNode) { const childNodes = this.treeAdapter.getChildNodes(parentNode); if (childNodes) { for (let i = 0, cnLength = childNodes.length; i < cnLength; i++) { const currentNode = childNodes[i]; if (this.treeAdapter.isElementNode(currentNode)) { this._serializeElement(currentNode); } else if (this.treeAdapter.isTextNode(currentNode)) { this._serializeTextNode(currentNode); } else if (this.treeAdapter.isCommentNode(currentNode)) { this._serializeCommentNode(currentNode); } else if (this.treeAdapter.isDocumentTypeNode(currentNode)) { this._serializeDocumentTypeNode(currentNode); } } } } _serializeElement(node) { const tn = this.treeAdapter.getTagName(node); const ns = this.treeAdapter.getNamespaceURI(node); this.html += '<' + tn; this._serializeAttributes(node); this.html += '>'; if ( tn !== $.AREA && tn !== $.BASE && tn !== $.BASEFONT && tn !== $.BGSOUND && tn !== $.BR && tn !== $.COL && tn !== $.EMBED && tn !== $.FRAME && tn !== $.HR && tn !== $.IMG && tn !== $.INPUT && tn !== $.KEYGEN && tn !== $.LINK && tn !== $.META && tn !== $.PARAM && tn !== $.SOURCE && tn !== $.TRACK && tn !== $.WBR ) { const childNodesHolder = tn === $.TEMPLATE && ns === NS.HTML ? this.treeAdapter.getTemplateContent(node) : node; this._serializeChildNodes(childNodesHolder); this.html += '</' + tn + '>'; } } _serializeAttributes(node) { const attrs = this.treeAdapter.getAttrList(node); for (let i = 0, attrsLength = attrs.length; i < attrsLength; i++) { const attr = attrs[i]; const value = Serializer.escapeString(attr.value, true); this.html += ' '; if (!attr.namespace) { this.html += attr.name; } else if (attr.namespace === NS.XML) { this.html += 'xml:' + attr.name; } else if (attr.namespace === NS.XMLNS) { if (attr.name !== 'xmlns') { this.html += 'xmlns:'; } this.html += attr.name; } else if (attr.namespace === NS.XLINK) { this.html += 'xlink:' + attr.name; } else { this.html += attr.prefix + ':' + attr.name; } this.html += '="' + value + '"'; } } _serializeTextNode(node) { const content = this.treeAdapter.getTextNodeContent(node); const parent = this.treeAdapter.getParentNode(node); let parentTn = void 0; if (parent && this.treeAdapter.isElementNode(parent)) { parentTn = this.treeAdapter.getTagName(parent); } if ( parentTn === $.STYLE || parentTn === $.SCRIPT || parentTn === $.XMP || parentTn === $.IFRAME || parentTn === $.NOEMBED || parentTn === $.NOFRAMES || parentTn === $.PLAINTEXT || parentTn === $.NOSCRIPT ) { this.html += content; } else { this.html += Serializer.escapeString(content, false); } } _serializeCommentNode(node) { this.html += '<!--' + this.treeAdapter.getCommentNodeContent(node) + '-->'; } _serializeDocumentTypeNode(node) { const name = this.treeAdapter.getDocumentTypeNodeName(node); this.html += '<' + doctype.serializeContent(name, null, null) + '>'; } } // NOTE: used in tests and by rewriting stream Serializer.escapeString = function(str, attrMode) { str = str.replace(AMP_REGEX, '&amp;').replace(NBSP_REGEX, '&nbsp;'); if (attrMode) { str = str.replace(DOUBLE_QUOTE_REGEX, '&quot;'); } else { str = str.replace(LT_REGEX, '&lt;').replace(GT_REGEX, '&gt;'); } return str; }; module.exports = Serializer;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/parse5/lib/serializer/index.js
index.js
'use strict'; const Preprocessor = require('parse5/lib/tokenizer/preprocessor'); const unicode = require('parse5/lib/common/unicode'); const neTree = require('parse5/lib/tokenizer/named-entity-data'); const ERR = require('parse5/lib/common/error-codes'); //Aliases const $ = unicode.CODE_POINTS; const $$ = unicode.CODE_POINT_SEQUENCES; //C1 Unicode control character reference replacements const C1_CONTROLS_REFERENCE_REPLACEMENTS = { 0x80: 0x20ac, 0x82: 0x201a, 0x83: 0x0192, 0x84: 0x201e, 0x85: 0x2026, 0x86: 0x2020, 0x87: 0x2021, 0x88: 0x02c6, 0x89: 0x2030, 0x8a: 0x0160, 0x8b: 0x2039, 0x8c: 0x0152, 0x8e: 0x017d, 0x91: 0x2018, 0x92: 0x2019, 0x93: 0x201c, 0x94: 0x201d, 0x95: 0x2022, 0x96: 0x2013, 0x97: 0x2014, 0x98: 0x02dc, 0x99: 0x2122, 0x9a: 0x0161, 0x9b: 0x203a, 0x9c: 0x0153, 0x9e: 0x017e, 0x9f: 0x0178 }; // Named entity tree flags const HAS_DATA_FLAG = 1 << 0; const DATA_DUPLET_FLAG = 1 << 1; const HAS_BRANCHES_FLAG = 1 << 2; const MAX_BRANCH_MARKER_VALUE = HAS_DATA_FLAG | DATA_DUPLET_FLAG | HAS_BRANCHES_FLAG; //States const DATA_STATE = 'DATA_STATE'; const RCDATA_STATE = 'RCDATA_STATE'; const RAWTEXT_STATE = 'RAWTEXT_STATE'; const SCRIPT_DATA_STATE = 'SCRIPT_DATA_STATE'; const PLAINTEXT_STATE = 'PLAINTEXT_STATE'; const TAG_OPEN_STATE = 'TAG_OPEN_STATE'; const END_TAG_OPEN_STATE = 'END_TAG_OPEN_STATE'; const TAG_NAME_STATE = 'TAG_NAME_STATE'; const RCDATA_LESS_THAN_SIGN_STATE = 'RCDATA_LESS_THAN_SIGN_STATE'; const RCDATA_END_TAG_OPEN_STATE = 'RCDATA_END_TAG_OPEN_STATE'; const RCDATA_END_TAG_NAME_STATE = 'RCDATA_END_TAG_NAME_STATE'; const RAWTEXT_LESS_THAN_SIGN_STATE = 'RAWTEXT_LESS_THAN_SIGN_STATE'; const RAWTEXT_END_TAG_OPEN_STATE = 'RAWTEXT_END_TAG_OPEN_STATE'; const RAWTEXT_END_TAG_NAME_STATE = 'RAWTEXT_END_TAG_NAME_STATE'; const SCRIPT_DATA_LESS_THAN_SIGN_STATE = 'SCRIPT_DATA_LESS_THAN_SIGN_STATE'; const SCRIPT_DATA_END_TAG_OPEN_STATE = 'SCRIPT_DATA_END_TAG_OPEN_STATE'; const SCRIPT_DATA_END_TAG_NAME_STATE = 'SCRIPT_DATA_END_TAG_NAME_STATE'; const SCRIPT_DATA_ESCAPE_START_STATE = 'SCRIPT_DATA_ESCAPE_START_STATE'; const SCRIPT_DATA_ESCAPE_START_DASH_STATE = 'SCRIPT_DATA_ESCAPE_START_DASH_STATE'; const SCRIPT_DATA_ESCAPED_STATE = 'SCRIPT_DATA_ESCAPED_STATE'; const SCRIPT_DATA_ESCAPED_DASH_STATE = 'SCRIPT_DATA_ESCAPED_DASH_STATE'; const SCRIPT_DATA_ESCAPED_DASH_DASH_STATE = 'SCRIPT_DATA_ESCAPED_DASH_DASH_STATE'; const SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN_STATE = 'SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN_STATE'; const SCRIPT_DATA_ESCAPED_END_TAG_OPEN_STATE = 'SCRIPT_DATA_ESCAPED_END_TAG_OPEN_STATE'; const SCRIPT_DATA_ESCAPED_END_TAG_NAME_STATE = 'SCRIPT_DATA_ESCAPED_END_TAG_NAME_STATE'; const SCRIPT_DATA_DOUBLE_ESCAPE_START_STATE = 'SCRIPT_DATA_DOUBLE_ESCAPE_START_STATE'; const SCRIPT_DATA_DOUBLE_ESCAPED_STATE = 'SCRIPT_DATA_DOUBLE_ESCAPED_STATE'; const SCRIPT_DATA_DOUBLE_ESCAPED_DASH_STATE = 'SCRIPT_DATA_DOUBLE_ESCAPED_DASH_STATE'; const SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH_STATE = 'SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH_STATE'; const SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN_STATE = 'SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN_STATE'; const SCRIPT_DATA_DOUBLE_ESCAPE_END_STATE = 'SCRIPT_DATA_DOUBLE_ESCAPE_END_STATE'; const BEFORE_ATTRIBUTE_NAME_STATE = 'BEFORE_ATTRIBUTE_NAME_STATE'; const ATTRIBUTE_NAME_STATE = 'ATTRIBUTE_NAME_STATE'; const AFTER_ATTRIBUTE_NAME_STATE = 'AFTER_ATTRIBUTE_NAME_STATE'; const BEFORE_ATTRIBUTE_VALUE_STATE = 'BEFORE_ATTRIBUTE_VALUE_STATE'; const ATTRIBUTE_VALUE_DOUBLE_QUOTED_STATE = 'ATTRIBUTE_VALUE_DOUBLE_QUOTED_STATE'; const ATTRIBUTE_VALUE_SINGLE_QUOTED_STATE = 'ATTRIBUTE_VALUE_SINGLE_QUOTED_STATE'; const ATTRIBUTE_VALUE_UNQUOTED_STATE = 'ATTRIBUTE_VALUE_UNQUOTED_STATE'; const AFTER_ATTRIBUTE_VALUE_QUOTED_STATE = 'AFTER_ATTRIBUTE_VALUE_QUOTED_STATE'; const SELF_CLOSING_START_TAG_STATE = 'SELF_CLOSING_START_TAG_STATE'; const BOGUS_COMMENT_STATE = 'BOGUS_COMMENT_STATE'; const MARKUP_DECLARATION_OPEN_STATE = 'MARKUP_DECLARATION_OPEN_STATE'; const COMMENT_START_STATE = 'COMMENT_START_STATE'; const COMMENT_START_DASH_STATE = 'COMMENT_START_DASH_STATE'; const COMMENT_STATE = 'COMMENT_STATE'; const COMMENT_LESS_THAN_SIGN_STATE = 'COMMENT_LESS_THAN_SIGN_STATE'; const COMMENT_LESS_THAN_SIGN_BANG_STATE = 'COMMENT_LESS_THAN_SIGN_BANG_STATE'; const COMMENT_LESS_THAN_SIGN_BANG_DASH_STATE = 'COMMENT_LESS_THAN_SIGN_BANG_DASH_STATE'; const COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH_STATE = 'COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH_STATE'; const COMMENT_END_DASH_STATE = 'COMMENT_END_DASH_STATE'; const COMMENT_END_STATE = 'COMMENT_END_STATE'; const COMMENT_END_BANG_STATE = 'COMMENT_END_BANG_STATE'; const DOCTYPE_STATE = 'DOCTYPE_STATE'; const BEFORE_DOCTYPE_NAME_STATE = 'BEFORE_DOCTYPE_NAME_STATE'; const DOCTYPE_NAME_STATE = 'DOCTYPE_NAME_STATE'; const AFTER_DOCTYPE_NAME_STATE = 'AFTER_DOCTYPE_NAME_STATE'; const AFTER_DOCTYPE_PUBLIC_KEYWORD_STATE = 'AFTER_DOCTYPE_PUBLIC_KEYWORD_STATE'; const BEFORE_DOCTYPE_PUBLIC_IDENTIFIER_STATE = 'BEFORE_DOCTYPE_PUBLIC_IDENTIFIER_STATE'; const DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED_STATE = 'DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED_STATE'; const DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED_STATE = 'DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED_STATE'; const AFTER_DOCTYPE_PUBLIC_IDENTIFIER_STATE = 'AFTER_DOCTYPE_PUBLIC_IDENTIFIER_STATE'; const BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS_STATE = 'BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS_STATE'; const AFTER_DOCTYPE_SYSTEM_KEYWORD_STATE = 'AFTER_DOCTYPE_SYSTEM_KEYWORD_STATE'; const BEFORE_DOCTYPE_SYSTEM_IDENTIFIER_STATE = 'BEFORE_DOCTYPE_SYSTEM_IDENTIFIER_STATE'; const DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED_STATE = 'DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED_STATE'; const DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED_STATE = 'DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED_STATE'; const AFTER_DOCTYPE_SYSTEM_IDENTIFIER_STATE = 'AFTER_DOCTYPE_SYSTEM_IDENTIFIER_STATE'; const BOGUS_DOCTYPE_STATE = 'BOGUS_DOCTYPE_STATE'; const CDATA_SECTION_STATE = 'CDATA_SECTION_STATE'; const CDATA_SECTION_BRACKET_STATE = 'CDATA_SECTION_BRACKET_STATE'; const CDATA_SECTION_END_STATE = 'CDATA_SECTION_END_STATE'; const CHARACTER_REFERENCE_STATE = 'CHARACTER_REFERENCE_STATE'; const NAMED_CHARACTER_REFERENCE_STATE = 'NAMED_CHARACTER_REFERENCE_STATE'; const AMBIGUOUS_AMPERSAND_STATE = 'AMBIGUOS_AMPERSAND_STATE'; const NUMERIC_CHARACTER_REFERENCE_STATE = 'NUMERIC_CHARACTER_REFERENCE_STATE'; const HEXADEMICAL_CHARACTER_REFERENCE_START_STATE = 'HEXADEMICAL_CHARACTER_REFERENCE_START_STATE'; const DECIMAL_CHARACTER_REFERENCE_START_STATE = 'DECIMAL_CHARACTER_REFERENCE_START_STATE'; const HEXADEMICAL_CHARACTER_REFERENCE_STATE = 'HEXADEMICAL_CHARACTER_REFERENCE_STATE'; const DECIMAL_CHARACTER_REFERENCE_STATE = 'DECIMAL_CHARACTER_REFERENCE_STATE'; const NUMERIC_CHARACTER_REFERENCE_END_STATE = 'NUMERIC_CHARACTER_REFERENCE_END_STATE'; //Utils //OPTIMIZATION: these utility functions should not be moved out of this module. V8 Crankshaft will not inline //this functions if they will be situated in another module due to context switch. //Always perform inlining check before modifying this functions ('node --trace-inlining'). function isWhitespace(cp) { return cp === $.SPACE || cp === $.LINE_FEED || cp === $.TABULATION || cp === $.FORM_FEED; } function isAsciiDigit(cp) { return cp >= $.DIGIT_0 && cp <= $.DIGIT_9; } function isAsciiUpper(cp) { return cp >= $.LATIN_CAPITAL_A && cp <= $.LATIN_CAPITAL_Z; } function isAsciiLower(cp) { return cp >= $.LATIN_SMALL_A && cp <= $.LATIN_SMALL_Z; } function isAsciiLetter(cp) { return isAsciiLower(cp) || isAsciiUpper(cp); } function isAsciiAlphaNumeric(cp) { return isAsciiLetter(cp) || isAsciiDigit(cp); } function isAsciiUpperHexDigit(cp) { return cp >= $.LATIN_CAPITAL_A && cp <= $.LATIN_CAPITAL_F; } function isAsciiLowerHexDigit(cp) { return cp >= $.LATIN_SMALL_A && cp <= $.LATIN_SMALL_F; } function isAsciiHexDigit(cp) { return isAsciiDigit(cp) || isAsciiUpperHexDigit(cp) || isAsciiLowerHexDigit(cp); } function toAsciiLowerCodePoint(cp) { return cp + 0x0020; } //NOTE: String.fromCharCode() function can handle only characters from BMP subset. //So, we need to workaround this manually. //(see: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/fromCharCode#Getting_it_to_work_with_higher_values) function toChar(cp) { if (cp <= 0xffff) { return String.fromCharCode(cp); } cp -= 0x10000; return String.fromCharCode(((cp >>> 10) & 0x3ff) | 0xd800) + String.fromCharCode(0xdc00 | (cp & 0x3ff)); } function toAsciiLowerChar(cp) { return String.fromCharCode(toAsciiLowerCodePoint(cp)); } function findNamedEntityTreeBranch(nodeIx, cp) { const branchCount = neTree[++nodeIx]; let lo = ++nodeIx; let hi = lo + branchCount - 1; while (lo <= hi) { const mid = (lo + hi) >>> 1; const midCp = neTree[mid]; if (midCp < cp) { lo = mid + 1; } else if (midCp > cp) { hi = mid - 1; } else { return neTree[mid + branchCount]; } } return -1; } //Tokenizer class Tokenizer { constructor() { this.preprocessor = new Preprocessor(); this.tokenQueue = []; this.allowCDATA = false; this.state = DATA_STATE; this.returnState = ''; this.charRefCode = -1; this.tempBuff = []; this.lastStartTagName = ''; this.consumedAfterSnapshot = -1; this.active = false; this.currentCharacterToken = null; this.currentToken = null; this.currentAttr = null; } //Errors _err() { // NOTE: err reporting is noop by default. Enabled by mixin. } _errOnNextCodePoint(err) { this._consume(); this._err(err); this._unconsume(); } //API getNextToken() { while (!this.tokenQueue.length && this.active) { this.consumedAfterSnapshot = 0; const cp = this._consume(); if (!this._ensureHibernation()) { this[this.state](cp); } } return this.tokenQueue.shift(); } write(chunk, isLastChunk) { this.active = true; this.preprocessor.write(chunk, isLastChunk); } insertHtmlAtCurrentPos(chunk) { this.active = true; this.preprocessor.insertHtmlAtCurrentPos(chunk); } //Hibernation _ensureHibernation() { if (this.preprocessor.endOfChunkHit) { for (; this.consumedAfterSnapshot > 0; this.consumedAfterSnapshot--) { this.preprocessor.retreat(); } this.active = false; this.tokenQueue.push({ type: Tokenizer.HIBERNATION_TOKEN }); return true; } return false; } //Consumption _consume() { this.consumedAfterSnapshot++; return this.preprocessor.advance(); } _unconsume() { this.consumedAfterSnapshot--; this.preprocessor.retreat(); } _reconsumeInState(state) { this.state = state; this._unconsume(); } _consumeSequenceIfMatch(pattern, startCp, caseSensitive) { let consumedCount = 0; let isMatch = true; const patternLength = pattern.length; let patternPos = 0; let cp = startCp; let patternCp = void 0; for (; patternPos < patternLength; patternPos++) { if (patternPos > 0) { cp = this._consume(); consumedCount++; } if (cp === $.EOF) { isMatch = false; break; } patternCp = pattern[patternPos]; if (cp !== patternCp && (caseSensitive || cp !== toAsciiLowerCodePoint(patternCp))) { isMatch = false; break; } } if (!isMatch) { while (consumedCount--) { this._unconsume(); } } return isMatch; } //Temp buffer _isTempBufferEqualToScriptString() { if (this.tempBuff.length !== $$.SCRIPT_STRING.length) { return false; } for (let i = 0; i < this.tempBuff.length; i++) { if (this.tempBuff[i] !== $$.SCRIPT_STRING[i]) { return false; } } return true; } //Token creation _createStartTagToken() { this.currentToken = { type: Tokenizer.START_TAG_TOKEN, tagName: '', selfClosing: false, ackSelfClosing: false, attrs: [] }; } _createEndTagToken() { this.currentToken = { type: Tokenizer.END_TAG_TOKEN, tagName: '', selfClosing: false, attrs: [] }; } _createCommentToken() { this.currentToken = { type: Tokenizer.COMMENT_TOKEN, data: '' }; } _createDoctypeToken(initialName) { this.currentToken = { type: Tokenizer.DOCTYPE_TOKEN, name: initialName, forceQuirks: false, publicId: null, systemId: null }; } _createCharacterToken(type, ch) { this.currentCharacterToken = { type: type, chars: ch }; } _createEOFToken() { this.currentToken = { type: Tokenizer.EOF_TOKEN }; } //Tag attributes _createAttr(attrNameFirstCh) { this.currentAttr = { name: attrNameFirstCh, value: '' }; } _leaveAttrName(toState) { if (Tokenizer.getTokenAttr(this.currentToken, this.currentAttr.name) === null) { this.currentToken.attrs.push(this.currentAttr); } else { this._err(ERR.duplicateAttribute); } this.state = toState; } _leaveAttrValue(toState) { this.state = toState; } //Token emission _emitCurrentToken() { this._emitCurrentCharacterToken(); const ct = this.currentToken; this.currentToken = null; //NOTE: store emited start tag's tagName to determine is the following end tag token is appropriate. if (ct.type === Tokenizer.START_TAG_TOKEN) { this.lastStartTagName = ct.tagName; } else if (ct.type === Tokenizer.END_TAG_TOKEN) { if (ct.attrs.length > 0) { this._err(ERR.endTagWithAttributes); } if (ct.selfClosing) { this._err(ERR.endTagWithTrailingSolidus); } } this.tokenQueue.push(ct); } _emitCurrentCharacterToken() { if (this.currentCharacterToken) { this.tokenQueue.push(this.currentCharacterToken); this.currentCharacterToken = null; } } _emitEOFToken() { this._createEOFToken(); this._emitCurrentToken(); } //Characters emission //OPTIMIZATION: specification uses only one type of character tokens (one token per character). //This causes a huge memory overhead and a lot of unnecessary parser loops. parse5 uses 3 groups of characters. //If we have a sequence of characters that belong to the same group, parser can process it //as a single solid character token. //So, there are 3 types of character tokens in parse5: //1)NULL_CHARACTER_TOKEN - \u0000-character sequences (e.g. '\u0000\u0000\u0000') //2)WHITESPACE_CHARACTER_TOKEN - any whitespace/new-line character sequences (e.g. '\n \r\t \f') //3)CHARACTER_TOKEN - any character sequence which don't belong to groups 1 and 2 (e.g. 'abcdef1234@@#$%^') _appendCharToCurrentCharacterToken(type, ch) { if (this.currentCharacterToken && this.currentCharacterToken.type !== type) { this._emitCurrentCharacterToken(); } if (this.currentCharacterToken) { this.currentCharacterToken.chars += ch; } else { this._createCharacterToken(type, ch); } } _emitCodePoint(cp) { let type = Tokenizer.CHARACTER_TOKEN; if (isWhitespace(cp)) { type = Tokenizer.WHITESPACE_CHARACTER_TOKEN; } else if (cp === $.NULL) { type = Tokenizer.NULL_CHARACTER_TOKEN; } this._appendCharToCurrentCharacterToken(type, toChar(cp)); } _emitSeveralCodePoints(codePoints) { for (let i = 0; i < codePoints.length; i++) { this._emitCodePoint(codePoints[i]); } } //NOTE: used then we emit character explicitly. This is always a non-whitespace and a non-null character. //So we can avoid additional checks here. _emitChars(ch) { this._appendCharToCurrentCharacterToken(Tokenizer.CHARACTER_TOKEN, ch); } // Character reference helpers _matchNamedCharacterReference(startCp) { let result = null; let excess = 1; let i = findNamedEntityTreeBranch(0, startCp); this.tempBuff.push(startCp); while (i > -1) { const current = neTree[i]; const inNode = current < MAX_BRANCH_MARKER_VALUE; const nodeWithData = inNode && current & HAS_DATA_FLAG; if (nodeWithData) { //NOTE: we use greedy search, so we continue lookup at this point result = current & DATA_DUPLET_FLAG ? [neTree[++i], neTree[++i]] : [neTree[++i]]; excess = 0; } const cp = this._consume(); this.tempBuff.push(cp); excess++; if (cp === $.EOF) { break; } if (inNode) { i = current & HAS_BRANCHES_FLAG ? findNamedEntityTreeBranch(i, cp) : -1; } else { i = cp === current ? ++i : -1; } } while (excess--) { this.tempBuff.pop(); this._unconsume(); } return result; } _isCharacterReferenceInAttribute() { return ( this.returnState === ATTRIBUTE_VALUE_DOUBLE_QUOTED_STATE || this.returnState === ATTRIBUTE_VALUE_SINGLE_QUOTED_STATE || this.returnState === ATTRIBUTE_VALUE_UNQUOTED_STATE ); } _isCharacterReferenceAttributeQuirk(withSemicolon) { if (!withSemicolon && this._isCharacterReferenceInAttribute()) { const nextCp = this._consume(); this._unconsume(); return nextCp === $.EQUALS_SIGN || isAsciiAlphaNumeric(nextCp); } return false; } _flushCodePointsConsumedAsCharacterReference() { if (this._isCharacterReferenceInAttribute()) { for (let i = 0; i < this.tempBuff.length; i++) { this.currentAttr.value += toChar(this.tempBuff[i]); } } else { this._emitSeveralCodePoints(this.tempBuff); } this.tempBuff = []; } // State machine // Data state //------------------------------------------------------------------ [DATA_STATE](cp) { this.preprocessor.dropParsedChunk(); if (cp === $.LESS_THAN_SIGN) { this.state = TAG_OPEN_STATE; } else if (cp === $.AMPERSAND) { this.returnState = DATA_STATE; this.state = CHARACTER_REFERENCE_STATE; } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this._emitCodePoint(cp); } else if (cp === $.EOF) { this._emitEOFToken(); } else { this._emitCodePoint(cp); } } // RCDATA state //------------------------------------------------------------------ [RCDATA_STATE](cp) { this.preprocessor.dropParsedChunk(); if (cp === $.AMPERSAND) { this.returnState = RCDATA_STATE; this.state = CHARACTER_REFERENCE_STATE; } else if (cp === $.LESS_THAN_SIGN) { this.state = RCDATA_LESS_THAN_SIGN_STATE; } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this._emitChars(unicode.REPLACEMENT_CHARACTER); } else if (cp === $.EOF) { this._emitEOFToken(); } else { this._emitCodePoint(cp); } } // RAWTEXT state //------------------------------------------------------------------ [RAWTEXT_STATE](cp) { this.preprocessor.dropParsedChunk(); if (cp === $.LESS_THAN_SIGN) { this.state = RAWTEXT_LESS_THAN_SIGN_STATE; } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this._emitChars(unicode.REPLACEMENT_CHARACTER); } else if (cp === $.EOF) { this._emitEOFToken(); } else { this._emitCodePoint(cp); } } // Script data state //------------------------------------------------------------------ [SCRIPT_DATA_STATE](cp) { this.preprocessor.dropParsedChunk(); if (cp === $.LESS_THAN_SIGN) { this.state = SCRIPT_DATA_LESS_THAN_SIGN_STATE; } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this._emitChars(unicode.REPLACEMENT_CHARACTER); } else if (cp === $.EOF) { this._emitEOFToken(); } else { this._emitCodePoint(cp); } } // PLAINTEXT state //------------------------------------------------------------------ [PLAINTEXT_STATE](cp) { this.preprocessor.dropParsedChunk(); if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this._emitChars(unicode.REPLACEMENT_CHARACTER); } else if (cp === $.EOF) { this._emitEOFToken(); } else { this._emitCodePoint(cp); } } // Tag open state //------------------------------------------------------------------ [TAG_OPEN_STATE](cp) { if (cp === $.EXCLAMATION_MARK) { this.state = MARKUP_DECLARATION_OPEN_STATE; } else if (cp === $.SOLIDUS) { this.state = END_TAG_OPEN_STATE; } else if (isAsciiLetter(cp)) { this._createStartTagToken(); this._reconsumeInState(TAG_NAME_STATE); } else if (cp === $.QUESTION_MARK) { this._err(ERR.unexpectedQuestionMarkInsteadOfTagName); this._createCommentToken(); this._reconsumeInState(BOGUS_COMMENT_STATE); } else if (cp === $.EOF) { this._err(ERR.eofBeforeTagName); this._emitChars('<'); this._emitEOFToken(); } else { this._err(ERR.invalidFirstCharacterOfTagName); this._emitChars('<'); this._reconsumeInState(DATA_STATE); } } // End tag open state //------------------------------------------------------------------ [END_TAG_OPEN_STATE](cp) { if (isAsciiLetter(cp)) { this._createEndTagToken(); this._reconsumeInState(TAG_NAME_STATE); } else if (cp === $.GREATER_THAN_SIGN) { this._err(ERR.missingEndTagName); this.state = DATA_STATE; } else if (cp === $.EOF) { this._err(ERR.eofBeforeTagName); this._emitChars('</'); this._emitEOFToken(); } else { this._err(ERR.invalidFirstCharacterOfTagName); this._createCommentToken(); this._reconsumeInState(BOGUS_COMMENT_STATE); } } // Tag name state //------------------------------------------------------------------ [TAG_NAME_STATE](cp) { if (isWhitespace(cp)) { this.state = BEFORE_ATTRIBUTE_NAME_STATE; } else if (cp === $.SOLIDUS) { this.state = SELF_CLOSING_START_TAG_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this.state = DATA_STATE; this._emitCurrentToken(); } else if (isAsciiUpper(cp)) { this.currentToken.tagName += toAsciiLowerChar(cp); } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.currentToken.tagName += unicode.REPLACEMENT_CHARACTER; } else if (cp === $.EOF) { this._err(ERR.eofInTag); this._emitEOFToken(); } else { this.currentToken.tagName += toChar(cp); } } // RCDATA less-than sign state //------------------------------------------------------------------ [RCDATA_LESS_THAN_SIGN_STATE](cp) { if (cp === $.SOLIDUS) { this.tempBuff = []; this.state = RCDATA_END_TAG_OPEN_STATE; } else { this._emitChars('<'); this._reconsumeInState(RCDATA_STATE); } } // RCDATA end tag open state //------------------------------------------------------------------ [RCDATA_END_TAG_OPEN_STATE](cp) { if (isAsciiLetter(cp)) { this._createEndTagToken(); this._reconsumeInState(RCDATA_END_TAG_NAME_STATE); } else { this._emitChars('</'); this._reconsumeInState(RCDATA_STATE); } } // RCDATA end tag name state //------------------------------------------------------------------ [RCDATA_END_TAG_NAME_STATE](cp) { if (isAsciiUpper(cp)) { this.currentToken.tagName += toAsciiLowerChar(cp); this.tempBuff.push(cp); } else if (isAsciiLower(cp)) { this.currentToken.tagName += toChar(cp); this.tempBuff.push(cp); } else { if (this.lastStartTagName === this.currentToken.tagName) { if (isWhitespace(cp)) { this.state = BEFORE_ATTRIBUTE_NAME_STATE; return; } if (cp === $.SOLIDUS) { this.state = SELF_CLOSING_START_TAG_STATE; return; } if (cp === $.GREATER_THAN_SIGN) { this.state = DATA_STATE; this._emitCurrentToken(); return; } } this._emitChars('</'); this._emitSeveralCodePoints(this.tempBuff); this._reconsumeInState(RCDATA_STATE); } } // RAWTEXT less-than sign state //------------------------------------------------------------------ [RAWTEXT_LESS_THAN_SIGN_STATE](cp) { if (cp === $.SOLIDUS) { this.tempBuff = []; this.state = RAWTEXT_END_TAG_OPEN_STATE; } else { this._emitChars('<'); this._reconsumeInState(RAWTEXT_STATE); } } // RAWTEXT end tag open state //------------------------------------------------------------------ [RAWTEXT_END_TAG_OPEN_STATE](cp) { if (isAsciiLetter(cp)) { this._createEndTagToken(); this._reconsumeInState(RAWTEXT_END_TAG_NAME_STATE); } else { this._emitChars('</'); this._reconsumeInState(RAWTEXT_STATE); } } // RAWTEXT end tag name state //------------------------------------------------------------------ [RAWTEXT_END_TAG_NAME_STATE](cp) { if (isAsciiUpper(cp)) { this.currentToken.tagName += toAsciiLowerChar(cp); this.tempBuff.push(cp); } else if (isAsciiLower(cp)) { this.currentToken.tagName += toChar(cp); this.tempBuff.push(cp); } else { if (this.lastStartTagName === this.currentToken.tagName) { if (isWhitespace(cp)) { this.state = BEFORE_ATTRIBUTE_NAME_STATE; return; } if (cp === $.SOLIDUS) { this.state = SELF_CLOSING_START_TAG_STATE; return; } if (cp === $.GREATER_THAN_SIGN) { this._emitCurrentToken(); this.state = DATA_STATE; return; } } this._emitChars('</'); this._emitSeveralCodePoints(this.tempBuff); this._reconsumeInState(RAWTEXT_STATE); } } // Script data less-than sign state //------------------------------------------------------------------ [SCRIPT_DATA_LESS_THAN_SIGN_STATE](cp) { if (cp === $.SOLIDUS) { this.tempBuff = []; this.state = SCRIPT_DATA_END_TAG_OPEN_STATE; } else if (cp === $.EXCLAMATION_MARK) { this.state = SCRIPT_DATA_ESCAPE_START_STATE; this._emitChars('<!'); } else { this._emitChars('<'); this._reconsumeInState(SCRIPT_DATA_STATE); } } // Script data end tag open state //------------------------------------------------------------------ [SCRIPT_DATA_END_TAG_OPEN_STATE](cp) { if (isAsciiLetter(cp)) { this._createEndTagToken(); this._reconsumeInState(SCRIPT_DATA_END_TAG_NAME_STATE); } else { this._emitChars('</'); this._reconsumeInState(SCRIPT_DATA_STATE); } } // Script data end tag name state //------------------------------------------------------------------ [SCRIPT_DATA_END_TAG_NAME_STATE](cp) { if (isAsciiUpper(cp)) { this.currentToken.tagName += toAsciiLowerChar(cp); this.tempBuff.push(cp); } else if (isAsciiLower(cp)) { this.currentToken.tagName += toChar(cp); this.tempBuff.push(cp); } else { if (this.lastStartTagName === this.currentToken.tagName) { if (isWhitespace(cp)) { this.state = BEFORE_ATTRIBUTE_NAME_STATE; return; } else if (cp === $.SOLIDUS) { this.state = SELF_CLOSING_START_TAG_STATE; return; } else if (cp === $.GREATER_THAN_SIGN) { this._emitCurrentToken(); this.state = DATA_STATE; return; } } this._emitChars('</'); this._emitSeveralCodePoints(this.tempBuff); this._reconsumeInState(SCRIPT_DATA_STATE); } } // Script data escape start state //------------------------------------------------------------------ [SCRIPT_DATA_ESCAPE_START_STATE](cp) { if (cp === $.HYPHEN_MINUS) { this.state = SCRIPT_DATA_ESCAPE_START_DASH_STATE; this._emitChars('-'); } else { this._reconsumeInState(SCRIPT_DATA_STATE); } } // Script data escape start dash state //------------------------------------------------------------------ [SCRIPT_DATA_ESCAPE_START_DASH_STATE](cp) { if (cp === $.HYPHEN_MINUS) { this.state = SCRIPT_DATA_ESCAPED_DASH_DASH_STATE; this._emitChars('-'); } else { this._reconsumeInState(SCRIPT_DATA_STATE); } } // Script data escaped state //------------------------------------------------------------------ [SCRIPT_DATA_ESCAPED_STATE](cp) { if (cp === $.HYPHEN_MINUS) { this.state = SCRIPT_DATA_ESCAPED_DASH_STATE; this._emitChars('-'); } else if (cp === $.LESS_THAN_SIGN) { this.state = SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN_STATE; } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this._emitChars(unicode.REPLACEMENT_CHARACTER); } else if (cp === $.EOF) { this._err(ERR.eofInScriptHtmlCommentLikeText); this._emitEOFToken(); } else { this._emitCodePoint(cp); } } // Script data escaped dash state //------------------------------------------------------------------ [SCRIPT_DATA_ESCAPED_DASH_STATE](cp) { if (cp === $.HYPHEN_MINUS) { this.state = SCRIPT_DATA_ESCAPED_DASH_DASH_STATE; this._emitChars('-'); } else if (cp === $.LESS_THAN_SIGN) { this.state = SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN_STATE; } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.state = SCRIPT_DATA_ESCAPED_STATE; this._emitChars(unicode.REPLACEMENT_CHARACTER); } else if (cp === $.EOF) { this._err(ERR.eofInScriptHtmlCommentLikeText); this._emitEOFToken(); } else { this.state = SCRIPT_DATA_ESCAPED_STATE; this._emitCodePoint(cp); } } // Script data escaped dash dash state //------------------------------------------------------------------ [SCRIPT_DATA_ESCAPED_DASH_DASH_STATE](cp) { if (cp === $.HYPHEN_MINUS) { this._emitChars('-'); } else if (cp === $.LESS_THAN_SIGN) { this.state = SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this.state = SCRIPT_DATA_STATE; this._emitChars('>'); } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.state = SCRIPT_DATA_ESCAPED_STATE; this._emitChars(unicode.REPLACEMENT_CHARACTER); } else if (cp === $.EOF) { this._err(ERR.eofInScriptHtmlCommentLikeText); this._emitEOFToken(); } else { this.state = SCRIPT_DATA_ESCAPED_STATE; this._emitCodePoint(cp); } } // Script data escaped less-than sign state //------------------------------------------------------------------ [SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN_STATE](cp) { if (cp === $.SOLIDUS) { this.tempBuff = []; this.state = SCRIPT_DATA_ESCAPED_END_TAG_OPEN_STATE; } else if (isAsciiLetter(cp)) { this.tempBuff = []; this._emitChars('<'); this._reconsumeInState(SCRIPT_DATA_DOUBLE_ESCAPE_START_STATE); } else { this._emitChars('<'); this._reconsumeInState(SCRIPT_DATA_ESCAPED_STATE); } } // Script data escaped end tag open state //------------------------------------------------------------------ [SCRIPT_DATA_ESCAPED_END_TAG_OPEN_STATE](cp) { if (isAsciiLetter(cp)) { this._createEndTagToken(); this._reconsumeInState(SCRIPT_DATA_ESCAPED_END_TAG_NAME_STATE); } else { this._emitChars('</'); this._reconsumeInState(SCRIPT_DATA_ESCAPED_STATE); } } // Script data escaped end tag name state //------------------------------------------------------------------ [SCRIPT_DATA_ESCAPED_END_TAG_NAME_STATE](cp) { if (isAsciiUpper(cp)) { this.currentToken.tagName += toAsciiLowerChar(cp); this.tempBuff.push(cp); } else if (isAsciiLower(cp)) { this.currentToken.tagName += toChar(cp); this.tempBuff.push(cp); } else { if (this.lastStartTagName === this.currentToken.tagName) { if (isWhitespace(cp)) { this.state = BEFORE_ATTRIBUTE_NAME_STATE; return; } if (cp === $.SOLIDUS) { this.state = SELF_CLOSING_START_TAG_STATE; return; } if (cp === $.GREATER_THAN_SIGN) { this._emitCurrentToken(); this.state = DATA_STATE; return; } } this._emitChars('</'); this._emitSeveralCodePoints(this.tempBuff); this._reconsumeInState(SCRIPT_DATA_ESCAPED_STATE); } } // Script data double escape start state //------------------------------------------------------------------ [SCRIPT_DATA_DOUBLE_ESCAPE_START_STATE](cp) { if (isWhitespace(cp) || cp === $.SOLIDUS || cp === $.GREATER_THAN_SIGN) { this.state = this._isTempBufferEqualToScriptString() ? SCRIPT_DATA_DOUBLE_ESCAPED_STATE : SCRIPT_DATA_ESCAPED_STATE; this._emitCodePoint(cp); } else if (isAsciiUpper(cp)) { this.tempBuff.push(toAsciiLowerCodePoint(cp)); this._emitCodePoint(cp); } else if (isAsciiLower(cp)) { this.tempBuff.push(cp); this._emitCodePoint(cp); } else { this._reconsumeInState(SCRIPT_DATA_ESCAPED_STATE); } } // Script data double escaped state //------------------------------------------------------------------ [SCRIPT_DATA_DOUBLE_ESCAPED_STATE](cp) { if (cp === $.HYPHEN_MINUS) { this.state = SCRIPT_DATA_DOUBLE_ESCAPED_DASH_STATE; this._emitChars('-'); } else if (cp === $.LESS_THAN_SIGN) { this.state = SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN_STATE; this._emitChars('<'); } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this._emitChars(unicode.REPLACEMENT_CHARACTER); } else if (cp === $.EOF) { this._err(ERR.eofInScriptHtmlCommentLikeText); this._emitEOFToken(); } else { this._emitCodePoint(cp); } } // Script data double escaped dash state //------------------------------------------------------------------ [SCRIPT_DATA_DOUBLE_ESCAPED_DASH_STATE](cp) { if (cp === $.HYPHEN_MINUS) { this.state = SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH_STATE; this._emitChars('-'); } else if (cp === $.LESS_THAN_SIGN) { this.state = SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN_STATE; this._emitChars('<'); } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.state = SCRIPT_DATA_DOUBLE_ESCAPED_STATE; this._emitChars(unicode.REPLACEMENT_CHARACTER); } else if (cp === $.EOF) { this._err(ERR.eofInScriptHtmlCommentLikeText); this._emitEOFToken(); } else { this.state = SCRIPT_DATA_DOUBLE_ESCAPED_STATE; this._emitCodePoint(cp); } } // Script data double escaped dash dash state //------------------------------------------------------------------ [SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH_STATE](cp) { if (cp === $.HYPHEN_MINUS) { this._emitChars('-'); } else if (cp === $.LESS_THAN_SIGN) { this.state = SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN_STATE; this._emitChars('<'); } else if (cp === $.GREATER_THAN_SIGN) { this.state = SCRIPT_DATA_STATE; this._emitChars('>'); } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.state = SCRIPT_DATA_DOUBLE_ESCAPED_STATE; this._emitChars(unicode.REPLACEMENT_CHARACTER); } else if (cp === $.EOF) { this._err(ERR.eofInScriptHtmlCommentLikeText); this._emitEOFToken(); } else { this.state = SCRIPT_DATA_DOUBLE_ESCAPED_STATE; this._emitCodePoint(cp); } } // Script data double escaped less-than sign state //------------------------------------------------------------------ [SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN_STATE](cp) { if (cp === $.SOLIDUS) { this.tempBuff = []; this.state = SCRIPT_DATA_DOUBLE_ESCAPE_END_STATE; this._emitChars('/'); } else { this._reconsumeInState(SCRIPT_DATA_DOUBLE_ESCAPED_STATE); } } // Script data double escape end state //------------------------------------------------------------------ [SCRIPT_DATA_DOUBLE_ESCAPE_END_STATE](cp) { if (isWhitespace(cp) || cp === $.SOLIDUS || cp === $.GREATER_THAN_SIGN) { this.state = this._isTempBufferEqualToScriptString() ? SCRIPT_DATA_ESCAPED_STATE : SCRIPT_DATA_DOUBLE_ESCAPED_STATE; this._emitCodePoint(cp); } else if (isAsciiUpper(cp)) { this.tempBuff.push(toAsciiLowerCodePoint(cp)); this._emitCodePoint(cp); } else if (isAsciiLower(cp)) { this.tempBuff.push(cp); this._emitCodePoint(cp); } else { this._reconsumeInState(SCRIPT_DATA_DOUBLE_ESCAPED_STATE); } } // Before attribute name state //------------------------------------------------------------------ [BEFORE_ATTRIBUTE_NAME_STATE](cp) { if (isWhitespace(cp)) { return; } if (cp === $.SOLIDUS || cp === $.GREATER_THAN_SIGN || cp === $.EOF) { this._reconsumeInState(AFTER_ATTRIBUTE_NAME_STATE); } else if (cp === $.EQUALS_SIGN) { this._err(ERR.unexpectedEqualsSignBeforeAttributeName); this._createAttr('='); this.state = ATTRIBUTE_NAME_STATE; } else { this._createAttr(''); this._reconsumeInState(ATTRIBUTE_NAME_STATE); } } // Attribute name state //------------------------------------------------------------------ [ATTRIBUTE_NAME_STATE](cp) { if (isWhitespace(cp) || cp === $.SOLIDUS || cp === $.GREATER_THAN_SIGN || cp === $.EOF) { this._leaveAttrName(AFTER_ATTRIBUTE_NAME_STATE); this._unconsume(); } else if (cp === $.EQUALS_SIGN) { this._leaveAttrName(BEFORE_ATTRIBUTE_VALUE_STATE); } else if (isAsciiUpper(cp)) { this.currentAttr.name += toAsciiLowerChar(cp); } else if (cp === $.QUOTATION_MARK || cp === $.APOSTROPHE || cp === $.LESS_THAN_SIGN) { this._err(ERR.unexpectedCharacterInAttributeName); this.currentAttr.name += toChar(cp); } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.currentAttr.name += unicode.REPLACEMENT_CHARACTER; } else { this.currentAttr.name += toChar(cp); } } // After attribute name state //------------------------------------------------------------------ [AFTER_ATTRIBUTE_NAME_STATE](cp) { if (isWhitespace(cp)) { return; } if (cp === $.SOLIDUS) { this.state = SELF_CLOSING_START_TAG_STATE; } else if (cp === $.EQUALS_SIGN) { this.state = BEFORE_ATTRIBUTE_VALUE_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this.state = DATA_STATE; this._emitCurrentToken(); } else if (cp === $.EOF) { this._err(ERR.eofInTag); this._emitEOFToken(); } else { this._createAttr(''); this._reconsumeInState(ATTRIBUTE_NAME_STATE); } } // Before attribute value state //------------------------------------------------------------------ [BEFORE_ATTRIBUTE_VALUE_STATE](cp) { if (isWhitespace(cp)) { return; } if (cp === $.QUOTATION_MARK) { this.state = ATTRIBUTE_VALUE_DOUBLE_QUOTED_STATE; } else if (cp === $.APOSTROPHE) { this.state = ATTRIBUTE_VALUE_SINGLE_QUOTED_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this._err(ERR.missingAttributeValue); this.state = DATA_STATE; this._emitCurrentToken(); } else { this._reconsumeInState(ATTRIBUTE_VALUE_UNQUOTED_STATE); } } // Attribute value (double-quoted) state //------------------------------------------------------------------ [ATTRIBUTE_VALUE_DOUBLE_QUOTED_STATE](cp) { if (cp === $.QUOTATION_MARK) { this.state = AFTER_ATTRIBUTE_VALUE_QUOTED_STATE; } else if (cp === $.AMPERSAND) { this.returnState = ATTRIBUTE_VALUE_DOUBLE_QUOTED_STATE; this.state = CHARACTER_REFERENCE_STATE; } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.currentAttr.value += unicode.REPLACEMENT_CHARACTER; } else if (cp === $.EOF) { this._err(ERR.eofInTag); this._emitEOFToken(); } else { this.currentAttr.value += toChar(cp); } } // Attribute value (single-quoted) state //------------------------------------------------------------------ [ATTRIBUTE_VALUE_SINGLE_QUOTED_STATE](cp) { if (cp === $.APOSTROPHE) { this.state = AFTER_ATTRIBUTE_VALUE_QUOTED_STATE; } else if (cp === $.AMPERSAND) { this.returnState = ATTRIBUTE_VALUE_SINGLE_QUOTED_STATE; this.state = CHARACTER_REFERENCE_STATE; } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.currentAttr.value += unicode.REPLACEMENT_CHARACTER; } else if (cp === $.EOF) { this._err(ERR.eofInTag); this._emitEOFToken(); } else { this.currentAttr.value += toChar(cp); } } // Attribute value (unquoted) state //------------------------------------------------------------------ [ATTRIBUTE_VALUE_UNQUOTED_STATE](cp) { if (isWhitespace(cp)) { this._leaveAttrValue(BEFORE_ATTRIBUTE_NAME_STATE); } else if (cp === $.AMPERSAND) { this.returnState = ATTRIBUTE_VALUE_UNQUOTED_STATE; this.state = CHARACTER_REFERENCE_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this._leaveAttrValue(DATA_STATE); this._emitCurrentToken(); } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.currentAttr.value += unicode.REPLACEMENT_CHARACTER; } else if ( cp === $.QUOTATION_MARK || cp === $.APOSTROPHE || cp === $.LESS_THAN_SIGN || cp === $.EQUALS_SIGN || cp === $.GRAVE_ACCENT ) { this._err(ERR.unexpectedCharacterInUnquotedAttributeValue); this.currentAttr.value += toChar(cp); } else if (cp === $.EOF) { this._err(ERR.eofInTag); this._emitEOFToken(); } else { this.currentAttr.value += toChar(cp); } } // After attribute value (quoted) state //------------------------------------------------------------------ [AFTER_ATTRIBUTE_VALUE_QUOTED_STATE](cp) { if (isWhitespace(cp)) { this._leaveAttrValue(BEFORE_ATTRIBUTE_NAME_STATE); } else if (cp === $.SOLIDUS) { this._leaveAttrValue(SELF_CLOSING_START_TAG_STATE); } else if (cp === $.GREATER_THAN_SIGN) { this._leaveAttrValue(DATA_STATE); this._emitCurrentToken(); } else if (cp === $.EOF) { this._err(ERR.eofInTag); this._emitEOFToken(); } else { this._err(ERR.missingWhitespaceBetweenAttributes); this._reconsumeInState(BEFORE_ATTRIBUTE_NAME_STATE); } } // Self-closing start tag state //------------------------------------------------------------------ [SELF_CLOSING_START_TAG_STATE](cp) { if (cp === $.GREATER_THAN_SIGN) { this.currentToken.selfClosing = true; this.state = DATA_STATE; this._emitCurrentToken(); } else if (cp === $.EOF) { this._err(ERR.eofInTag); this._emitEOFToken(); } else { this._err(ERR.unexpectedSolidusInTag); this._reconsumeInState(BEFORE_ATTRIBUTE_NAME_STATE); } } // Bogus comment state //------------------------------------------------------------------ [BOGUS_COMMENT_STATE](cp) { if (cp === $.GREATER_THAN_SIGN) { this.state = DATA_STATE; this._emitCurrentToken(); } else if (cp === $.EOF) { this._emitCurrentToken(); this._emitEOFToken(); } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.currentToken.data += unicode.REPLACEMENT_CHARACTER; } else { this.currentToken.data += toChar(cp); } } // Markup declaration open state //------------------------------------------------------------------ [MARKUP_DECLARATION_OPEN_STATE](cp) { if (this._consumeSequenceIfMatch($$.DASH_DASH_STRING, cp, true)) { this._createCommentToken(); this.state = COMMENT_START_STATE; } else if (this._consumeSequenceIfMatch($$.DOCTYPE_STRING, cp, false)) { this.state = DOCTYPE_STATE; } else if (this._consumeSequenceIfMatch($$.CDATA_START_STRING, cp, true)) { if (this.allowCDATA) { this.state = CDATA_SECTION_STATE; } else { this._err(ERR.cdataInHtmlContent); this._createCommentToken(); this.currentToken.data = '[CDATA['; this.state = BOGUS_COMMENT_STATE; } } //NOTE: sequence lookup can be abrupted by hibernation. In that case lookup //results are no longer valid and we will need to start over. else if (!this._ensureHibernation()) { this._err(ERR.incorrectlyOpenedComment); this._createCommentToken(); this._reconsumeInState(BOGUS_COMMENT_STATE); } } // Comment start state //------------------------------------------------------------------ [COMMENT_START_STATE](cp) { if (cp === $.HYPHEN_MINUS) { this.state = COMMENT_START_DASH_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this._err(ERR.abruptClosingOfEmptyComment); this.state = DATA_STATE; this._emitCurrentToken(); } else { this._reconsumeInState(COMMENT_STATE); } } // Comment start dash state //------------------------------------------------------------------ [COMMENT_START_DASH_STATE](cp) { if (cp === $.HYPHEN_MINUS) { this.state = COMMENT_END_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this._err(ERR.abruptClosingOfEmptyComment); this.state = DATA_STATE; this._emitCurrentToken(); } else if (cp === $.EOF) { this._err(ERR.eofInComment); this._emitCurrentToken(); this._emitEOFToken(); } else { this.currentToken.data += '-'; this._reconsumeInState(COMMENT_STATE); } } // Comment state //------------------------------------------------------------------ [COMMENT_STATE](cp) { if (cp === $.HYPHEN_MINUS) { this.state = COMMENT_END_DASH_STATE; } else if (cp === $.LESS_THAN_SIGN) { this.currentToken.data += '<'; this.state = COMMENT_LESS_THAN_SIGN_STATE; } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.currentToken.data += unicode.REPLACEMENT_CHARACTER; } else if (cp === $.EOF) { this._err(ERR.eofInComment); this._emitCurrentToken(); this._emitEOFToken(); } else { this.currentToken.data += toChar(cp); } } // Comment less-than sign state //------------------------------------------------------------------ [COMMENT_LESS_THAN_SIGN_STATE](cp) { if (cp === $.EXCLAMATION_MARK) { this.currentToken.data += '!'; this.state = COMMENT_LESS_THAN_SIGN_BANG_STATE; } else if (cp === $.LESS_THAN_SIGN) { this.currentToken.data += '!'; } else { this._reconsumeInState(COMMENT_STATE); } } // Comment less-than sign bang state //------------------------------------------------------------------ [COMMENT_LESS_THAN_SIGN_BANG_STATE](cp) { if (cp === $.HYPHEN_MINUS) { this.state = COMMENT_LESS_THAN_SIGN_BANG_DASH_STATE; } else { this._reconsumeInState(COMMENT_STATE); } } // Comment less-than sign bang dash state //------------------------------------------------------------------ [COMMENT_LESS_THAN_SIGN_BANG_DASH_STATE](cp) { if (cp === $.HYPHEN_MINUS) { this.state = COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH_STATE; } else { this._reconsumeInState(COMMENT_END_DASH_STATE); } } // Comment less-than sign bang dash dash state //------------------------------------------------------------------ [COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH_STATE](cp) { if (cp !== $.GREATER_THAN_SIGN && cp !== $.EOF) { this._err(ERR.nestedComment); } this._reconsumeInState(COMMENT_END_STATE); } // Comment end dash state //------------------------------------------------------------------ [COMMENT_END_DASH_STATE](cp) { if (cp === $.HYPHEN_MINUS) { this.state = COMMENT_END_STATE; } else if (cp === $.EOF) { this._err(ERR.eofInComment); this._emitCurrentToken(); this._emitEOFToken(); } else { this.currentToken.data += '-'; this._reconsumeInState(COMMENT_STATE); } } // Comment end state //------------------------------------------------------------------ [COMMENT_END_STATE](cp) { if (cp === $.GREATER_THAN_SIGN) { this.state = DATA_STATE; this._emitCurrentToken(); } else if (cp === $.EXCLAMATION_MARK) { this.state = COMMENT_END_BANG_STATE; } else if (cp === $.HYPHEN_MINUS) { this.currentToken.data += '-'; } else if (cp === $.EOF) { this._err(ERR.eofInComment); this._emitCurrentToken(); this._emitEOFToken(); } else { this.currentToken.data += '--'; this._reconsumeInState(COMMENT_STATE); } } // Comment end bang state //------------------------------------------------------------------ [COMMENT_END_BANG_STATE](cp) { if (cp === $.HYPHEN_MINUS) { this.currentToken.data += '--!'; this.state = COMMENT_END_DASH_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this._err(ERR.incorrectlyClosedComment); this.state = DATA_STATE; this._emitCurrentToken(); } else if (cp === $.EOF) { this._err(ERR.eofInComment); this._emitCurrentToken(); this._emitEOFToken(); } else { this.currentToken.data += '--!'; this._reconsumeInState(COMMENT_STATE); } } // DOCTYPE state //------------------------------------------------------------------ [DOCTYPE_STATE](cp) { if (isWhitespace(cp)) { this.state = BEFORE_DOCTYPE_NAME_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this._reconsumeInState(BEFORE_DOCTYPE_NAME_STATE); } else if (cp === $.EOF) { this._err(ERR.eofInDoctype); this._createDoctypeToken(null); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this._emitEOFToken(); } else { this._err(ERR.missingWhitespaceBeforeDoctypeName); this._reconsumeInState(BEFORE_DOCTYPE_NAME_STATE); } } // Before DOCTYPE name state //------------------------------------------------------------------ [BEFORE_DOCTYPE_NAME_STATE](cp) { if (isWhitespace(cp)) { return; } if (isAsciiUpper(cp)) { this._createDoctypeToken(toAsciiLowerChar(cp)); this.state = DOCTYPE_NAME_STATE; } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this._createDoctypeToken(unicode.REPLACEMENT_CHARACTER); this.state = DOCTYPE_NAME_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this._err(ERR.missingDoctypeName); this._createDoctypeToken(null); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this.state = DATA_STATE; } else if (cp === $.EOF) { this._err(ERR.eofInDoctype); this._createDoctypeToken(null); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this._emitEOFToken(); } else { this._createDoctypeToken(toChar(cp)); this.state = DOCTYPE_NAME_STATE; } } // DOCTYPE name state //------------------------------------------------------------------ [DOCTYPE_NAME_STATE](cp) { if (isWhitespace(cp)) { this.state = AFTER_DOCTYPE_NAME_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this.state = DATA_STATE; this._emitCurrentToken(); } else if (isAsciiUpper(cp)) { this.currentToken.name += toAsciiLowerChar(cp); } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.currentToken.name += unicode.REPLACEMENT_CHARACTER; } else if (cp === $.EOF) { this._err(ERR.eofInDoctype); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this._emitEOFToken(); } else { this.currentToken.name += toChar(cp); } } // After DOCTYPE name state //------------------------------------------------------------------ [AFTER_DOCTYPE_NAME_STATE](cp) { if (isWhitespace(cp)) { return; } if (cp === $.GREATER_THAN_SIGN) { this.state = DATA_STATE; this._emitCurrentToken(); } else if (cp === $.EOF) { this._err(ERR.eofInDoctype); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this._emitEOFToken(); } else if (this._consumeSequenceIfMatch($$.PUBLIC_STRING, cp, false)) { this.state = AFTER_DOCTYPE_PUBLIC_KEYWORD_STATE; } else if (this._consumeSequenceIfMatch($$.SYSTEM_STRING, cp, false)) { this.state = AFTER_DOCTYPE_SYSTEM_KEYWORD_STATE; } //NOTE: sequence lookup can be abrupted by hibernation. In that case lookup //results are no longer valid and we will need to start over. else if (!this._ensureHibernation()) { this._err(ERR.invalidCharacterSequenceAfterDoctypeName); this.currentToken.forceQuirks = true; this._reconsumeInState(BOGUS_DOCTYPE_STATE); } } // After DOCTYPE public keyword state //------------------------------------------------------------------ [AFTER_DOCTYPE_PUBLIC_KEYWORD_STATE](cp) { if (isWhitespace(cp)) { this.state = BEFORE_DOCTYPE_PUBLIC_IDENTIFIER_STATE; } else if (cp === $.QUOTATION_MARK) { this._err(ERR.missingWhitespaceAfterDoctypePublicKeyword); this.currentToken.publicId = ''; this.state = DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED_STATE; } else if (cp === $.APOSTROPHE) { this._err(ERR.missingWhitespaceAfterDoctypePublicKeyword); this.currentToken.publicId = ''; this.state = DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this._err(ERR.missingDoctypePublicIdentifier); this.currentToken.forceQuirks = true; this.state = DATA_STATE; this._emitCurrentToken(); } else if (cp === $.EOF) { this._err(ERR.eofInDoctype); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this._emitEOFToken(); } else { this._err(ERR.missingQuoteBeforeDoctypePublicIdentifier); this.currentToken.forceQuirks = true; this._reconsumeInState(BOGUS_DOCTYPE_STATE); } } // Before DOCTYPE public identifier state //------------------------------------------------------------------ [BEFORE_DOCTYPE_PUBLIC_IDENTIFIER_STATE](cp) { if (isWhitespace(cp)) { return; } if (cp === $.QUOTATION_MARK) { this.currentToken.publicId = ''; this.state = DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED_STATE; } else if (cp === $.APOSTROPHE) { this.currentToken.publicId = ''; this.state = DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this._err(ERR.missingDoctypePublicIdentifier); this.currentToken.forceQuirks = true; this.state = DATA_STATE; this._emitCurrentToken(); } else if (cp === $.EOF) { this._err(ERR.eofInDoctype); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this._emitEOFToken(); } else { this._err(ERR.missingQuoteBeforeDoctypePublicIdentifier); this.currentToken.forceQuirks = true; this._reconsumeInState(BOGUS_DOCTYPE_STATE); } } // DOCTYPE public identifier (double-quoted) state //------------------------------------------------------------------ [DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED_STATE](cp) { if (cp === $.QUOTATION_MARK) { this.state = AFTER_DOCTYPE_PUBLIC_IDENTIFIER_STATE; } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.currentToken.publicId += unicode.REPLACEMENT_CHARACTER; } else if (cp === $.GREATER_THAN_SIGN) { this._err(ERR.abruptDoctypePublicIdentifier); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this.state = DATA_STATE; } else if (cp === $.EOF) { this._err(ERR.eofInDoctype); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this._emitEOFToken(); } else { this.currentToken.publicId += toChar(cp); } } // DOCTYPE public identifier (single-quoted) state //------------------------------------------------------------------ [DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED_STATE](cp) { if (cp === $.APOSTROPHE) { this.state = AFTER_DOCTYPE_PUBLIC_IDENTIFIER_STATE; } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.currentToken.publicId += unicode.REPLACEMENT_CHARACTER; } else if (cp === $.GREATER_THAN_SIGN) { this._err(ERR.abruptDoctypePublicIdentifier); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this.state = DATA_STATE; } else if (cp === $.EOF) { this._err(ERR.eofInDoctype); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this._emitEOFToken(); } else { this.currentToken.publicId += toChar(cp); } } // After DOCTYPE public identifier state //------------------------------------------------------------------ [AFTER_DOCTYPE_PUBLIC_IDENTIFIER_STATE](cp) { if (isWhitespace(cp)) { this.state = BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this.state = DATA_STATE; this._emitCurrentToken(); } else if (cp === $.QUOTATION_MARK) { this._err(ERR.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers); this.currentToken.systemId = ''; this.state = DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED_STATE; } else if (cp === $.APOSTROPHE) { this._err(ERR.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers); this.currentToken.systemId = ''; this.state = DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED_STATE; } else if (cp === $.EOF) { this._err(ERR.eofInDoctype); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this._emitEOFToken(); } else { this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier); this.currentToken.forceQuirks = true; this._reconsumeInState(BOGUS_DOCTYPE_STATE); } } // Between DOCTYPE public and system identifiers state //------------------------------------------------------------------ [BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS_STATE](cp) { if (isWhitespace(cp)) { return; } if (cp === $.GREATER_THAN_SIGN) { this._emitCurrentToken(); this.state = DATA_STATE; } else if (cp === $.QUOTATION_MARK) { this.currentToken.systemId = ''; this.state = DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED_STATE; } else if (cp === $.APOSTROPHE) { this.currentToken.systemId = ''; this.state = DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED_STATE; } else if (cp === $.EOF) { this._err(ERR.eofInDoctype); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this._emitEOFToken(); } else { this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier); this.currentToken.forceQuirks = true; this._reconsumeInState(BOGUS_DOCTYPE_STATE); } } // After DOCTYPE system keyword state //------------------------------------------------------------------ [AFTER_DOCTYPE_SYSTEM_KEYWORD_STATE](cp) { if (isWhitespace(cp)) { this.state = BEFORE_DOCTYPE_SYSTEM_IDENTIFIER_STATE; } else if (cp === $.QUOTATION_MARK) { this._err(ERR.missingWhitespaceAfterDoctypeSystemKeyword); this.currentToken.systemId = ''; this.state = DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED_STATE; } else if (cp === $.APOSTROPHE) { this._err(ERR.missingWhitespaceAfterDoctypeSystemKeyword); this.currentToken.systemId = ''; this.state = DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this._err(ERR.missingDoctypeSystemIdentifier); this.currentToken.forceQuirks = true; this.state = DATA_STATE; this._emitCurrentToken(); } else if (cp === $.EOF) { this._err(ERR.eofInDoctype); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this._emitEOFToken(); } else { this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier); this.currentToken.forceQuirks = true; this._reconsumeInState(BOGUS_DOCTYPE_STATE); } } // Before DOCTYPE system identifier state //------------------------------------------------------------------ [BEFORE_DOCTYPE_SYSTEM_IDENTIFIER_STATE](cp) { if (isWhitespace(cp)) { return; } if (cp === $.QUOTATION_MARK) { this.currentToken.systemId = ''; this.state = DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED_STATE; } else if (cp === $.APOSTROPHE) { this.currentToken.systemId = ''; this.state = DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED_STATE; } else if (cp === $.GREATER_THAN_SIGN) { this._err(ERR.missingDoctypeSystemIdentifier); this.currentToken.forceQuirks = true; this.state = DATA_STATE; this._emitCurrentToken(); } else if (cp === $.EOF) { this._err(ERR.eofInDoctype); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this._emitEOFToken(); } else { this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier); this.currentToken.forceQuirks = true; this._reconsumeInState(BOGUS_DOCTYPE_STATE); } } // DOCTYPE system identifier (double-quoted) state //------------------------------------------------------------------ [DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED_STATE](cp) { if (cp === $.QUOTATION_MARK) { this.state = AFTER_DOCTYPE_SYSTEM_IDENTIFIER_STATE; } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.currentToken.systemId += unicode.REPLACEMENT_CHARACTER; } else if (cp === $.GREATER_THAN_SIGN) { this._err(ERR.abruptDoctypeSystemIdentifier); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this.state = DATA_STATE; } else if (cp === $.EOF) { this._err(ERR.eofInDoctype); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this._emitEOFToken(); } else { this.currentToken.systemId += toChar(cp); } } // DOCTYPE system identifier (single-quoted) state //------------------------------------------------------------------ [DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED_STATE](cp) { if (cp === $.APOSTROPHE) { this.state = AFTER_DOCTYPE_SYSTEM_IDENTIFIER_STATE; } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); this.currentToken.systemId += unicode.REPLACEMENT_CHARACTER; } else if (cp === $.GREATER_THAN_SIGN) { this._err(ERR.abruptDoctypeSystemIdentifier); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this.state = DATA_STATE; } else if (cp === $.EOF) { this._err(ERR.eofInDoctype); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this._emitEOFToken(); } else { this.currentToken.systemId += toChar(cp); } } // After DOCTYPE system identifier state //------------------------------------------------------------------ [AFTER_DOCTYPE_SYSTEM_IDENTIFIER_STATE](cp) { if (isWhitespace(cp)) { return; } if (cp === $.GREATER_THAN_SIGN) { this._emitCurrentToken(); this.state = DATA_STATE; } else if (cp === $.EOF) { this._err(ERR.eofInDoctype); this.currentToken.forceQuirks = true; this._emitCurrentToken(); this._emitEOFToken(); } else { this._err(ERR.unexpectedCharacterAfterDoctypeSystemIdentifier); this._reconsumeInState(BOGUS_DOCTYPE_STATE); } } // Bogus DOCTYPE state //------------------------------------------------------------------ [BOGUS_DOCTYPE_STATE](cp) { if (cp === $.GREATER_THAN_SIGN) { this._emitCurrentToken(); this.state = DATA_STATE; } else if (cp === $.NULL) { this._err(ERR.unexpectedNullCharacter); } else if (cp === $.EOF) { this._emitCurrentToken(); this._emitEOFToken(); } } // CDATA section state //------------------------------------------------------------------ [CDATA_SECTION_STATE](cp) { if (cp === $.RIGHT_SQUARE_BRACKET) { this.state = CDATA_SECTION_BRACKET_STATE; } else if (cp === $.EOF) { this._err(ERR.eofInCdata); this._emitEOFToken(); } else { this._emitCodePoint(cp); } } // CDATA section bracket state //------------------------------------------------------------------ [CDATA_SECTION_BRACKET_STATE](cp) { if (cp === $.RIGHT_SQUARE_BRACKET) { this.state = CDATA_SECTION_END_STATE; } else { this._emitChars(']'); this._reconsumeInState(CDATA_SECTION_STATE); } } // CDATA section end state //------------------------------------------------------------------ [CDATA_SECTION_END_STATE](cp) { if (cp === $.GREATER_THAN_SIGN) { this.state = DATA_STATE; } else if (cp === $.RIGHT_SQUARE_BRACKET) { this._emitChars(']'); } else { this._emitChars(']]'); this._reconsumeInState(CDATA_SECTION_STATE); } } // Character reference state //------------------------------------------------------------------ [CHARACTER_REFERENCE_STATE](cp) { this.tempBuff = [$.AMPERSAND]; if (cp === $.NUMBER_SIGN) { this.tempBuff.push(cp); this.state = NUMERIC_CHARACTER_REFERENCE_STATE; } else if (isAsciiAlphaNumeric(cp)) { this._reconsumeInState(NAMED_CHARACTER_REFERENCE_STATE); } else { this._flushCodePointsConsumedAsCharacterReference(); this._reconsumeInState(this.returnState); } } // Named character reference state //------------------------------------------------------------------ [NAMED_CHARACTER_REFERENCE_STATE](cp) { const matchResult = this._matchNamedCharacterReference(cp); //NOTE: matching can be abrupted by hibernation. In that case match //results are no longer valid and we will need to start over. if (this._ensureHibernation()) { this.tempBuff = [$.AMPERSAND]; } else if (matchResult) { const withSemicolon = this.tempBuff[this.tempBuff.length - 1] === $.SEMICOLON; if (!this._isCharacterReferenceAttributeQuirk(withSemicolon)) { if (!withSemicolon) { this._errOnNextCodePoint(ERR.missingSemicolonAfterCharacterReference); } this.tempBuff = matchResult; } this._flushCodePointsConsumedAsCharacterReference(); this.state = this.returnState; } else { this._flushCodePointsConsumedAsCharacterReference(); this.state = AMBIGUOUS_AMPERSAND_STATE; } } // Ambiguos ampersand state //------------------------------------------------------------------ [AMBIGUOUS_AMPERSAND_STATE](cp) { if (isAsciiAlphaNumeric(cp)) { if (this._isCharacterReferenceInAttribute()) { this.currentAttr.value += toChar(cp); } else { this._emitCodePoint(cp); } } else { if (cp === $.SEMICOLON) { this._err(ERR.unknownNamedCharacterReference); } this._reconsumeInState(this.returnState); } } // Numeric character reference state //------------------------------------------------------------------ [NUMERIC_CHARACTER_REFERENCE_STATE](cp) { this.charRefCode = 0; if (cp === $.LATIN_SMALL_X || cp === $.LATIN_CAPITAL_X) { this.tempBuff.push(cp); this.state = HEXADEMICAL_CHARACTER_REFERENCE_START_STATE; } else { this._reconsumeInState(DECIMAL_CHARACTER_REFERENCE_START_STATE); } } // Hexademical character reference start state //------------------------------------------------------------------ [HEXADEMICAL_CHARACTER_REFERENCE_START_STATE](cp) { if (isAsciiHexDigit(cp)) { this._reconsumeInState(HEXADEMICAL_CHARACTER_REFERENCE_STATE); } else { this._err(ERR.absenceOfDigitsInNumericCharacterReference); this._flushCodePointsConsumedAsCharacterReference(); this._reconsumeInState(this.returnState); } } // Decimal character reference start state //------------------------------------------------------------------ [DECIMAL_CHARACTER_REFERENCE_START_STATE](cp) { if (isAsciiDigit(cp)) { this._reconsumeInState(DECIMAL_CHARACTER_REFERENCE_STATE); } else { this._err(ERR.absenceOfDigitsInNumericCharacterReference); this._flushCodePointsConsumedAsCharacterReference(); this._reconsumeInState(this.returnState); } } // Hexademical character reference state //------------------------------------------------------------------ [HEXADEMICAL_CHARACTER_REFERENCE_STATE](cp) { if (isAsciiUpperHexDigit(cp)) { this.charRefCode = this.charRefCode * 16 + cp - 0x37; } else if (isAsciiLowerHexDigit(cp)) { this.charRefCode = this.charRefCode * 16 + cp - 0x57; } else if (isAsciiDigit(cp)) { this.charRefCode = this.charRefCode * 16 + cp - 0x30; } else if (cp === $.SEMICOLON) { this.state = NUMERIC_CHARACTER_REFERENCE_END_STATE; } else { this._err(ERR.missingSemicolonAfterCharacterReference); this._reconsumeInState(NUMERIC_CHARACTER_REFERENCE_END_STATE); } } // Decimal character reference state //------------------------------------------------------------------ [DECIMAL_CHARACTER_REFERENCE_STATE](cp) { if (isAsciiDigit(cp)) { this.charRefCode = this.charRefCode * 10 + cp - 0x30; } else if (cp === $.SEMICOLON) { this.state = NUMERIC_CHARACTER_REFERENCE_END_STATE; } else { this._err(ERR.missingSemicolonAfterCharacterReference); this._reconsumeInState(NUMERIC_CHARACTER_REFERENCE_END_STATE); } } // Numeric character reference end state //------------------------------------------------------------------ [NUMERIC_CHARACTER_REFERENCE_END_STATE]() { if (this.charRefCode === $.NULL) { this._err(ERR.nullCharacterReference); this.charRefCode = $.REPLACEMENT_CHARACTER; } else if (this.charRefCode > 0x10ffff) { this._err(ERR.characterReferenceOutsideUnicodeRange); this.charRefCode = $.REPLACEMENT_CHARACTER; } else if (unicode.isSurrogate(this.charRefCode)) { this._err(ERR.surrogateCharacterReference); this.charRefCode = $.REPLACEMENT_CHARACTER; } else if (unicode.isUndefinedCodePoint(this.charRefCode)) { this._err(ERR.noncharacterCharacterReference); } else if (unicode.isControlCodePoint(this.charRefCode) || this.charRefCode === $.CARRIAGE_RETURN) { this._err(ERR.controlCharacterReference); const replacement = C1_CONTROLS_REFERENCE_REPLACEMENTS[this.charRefCode]; if (replacement) { this.charRefCode = replacement; } } this.tempBuff = [this.charRefCode]; this._flushCodePointsConsumedAsCharacterReference(); this._reconsumeInState(this.returnState); } } //Token types Tokenizer.CHARACTER_TOKEN = 'CHARACTER_TOKEN'; Tokenizer.NULL_CHARACTER_TOKEN = 'NULL_CHARACTER_TOKEN'; Tokenizer.WHITESPACE_CHARACTER_TOKEN = 'WHITESPACE_CHARACTER_TOKEN'; Tokenizer.START_TAG_TOKEN = 'START_TAG_TOKEN'; Tokenizer.END_TAG_TOKEN = 'END_TAG_TOKEN'; Tokenizer.COMMENT_TOKEN = 'COMMENT_TOKEN'; Tokenizer.DOCTYPE_TOKEN = 'DOCTYPE_TOKEN'; Tokenizer.EOF_TOKEN = 'EOF_TOKEN'; Tokenizer.HIBERNATION_TOKEN = 'HIBERNATION_TOKEN'; //Tokenizer initial states for different modes Tokenizer.MODE = { DATA: DATA_STATE, RCDATA: RCDATA_STATE, RAWTEXT: RAWTEXT_STATE, SCRIPT_DATA: SCRIPT_DATA_STATE, PLAINTEXT: PLAINTEXT_STATE }; //Static Tokenizer.getTokenAttr = function(token, attrName) { for (let i = token.attrs.length - 1; i >= 0; i--) { if (token.attrs[i].name === attrName) { return token.attrs[i].value; } } return null; }; module.exports = Tokenizer;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/parse5/lib/tokenizer/index.js
index.js
'use strict'; const unicode = require('parse5/lib/common/unicode'); const ERR = require('parse5/lib/common/error-codes'); //Aliases const $ = unicode.CODE_POINTS; //Const const DEFAULT_BUFFER_WATERLINE = 1 << 16; //Preprocessor //NOTE: HTML input preprocessing //(see: http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#preprocessing-the-input-stream) class Preprocessor { constructor() { this.html = null; this.pos = -1; this.lastGapPos = -1; this.lastCharPos = -1; this.gapStack = []; this.skipNextNewLine = false; this.lastChunkWritten = false; this.endOfChunkHit = false; this.bufferWaterline = DEFAULT_BUFFER_WATERLINE; } _err() { // NOTE: err reporting is noop by default. Enabled by mixin. } _addGap() { this.gapStack.push(this.lastGapPos); this.lastGapPos = this.pos; } _processSurrogate(cp) { //NOTE: try to peek a surrogate pair if (this.pos !== this.lastCharPos) { const nextCp = this.html.charCodeAt(this.pos + 1); if (unicode.isSurrogatePair(nextCp)) { //NOTE: we have a surrogate pair. Peek pair character and recalculate code point. this.pos++; //NOTE: add gap that should be avoided during retreat this._addGap(); return unicode.getSurrogatePairCodePoint(cp, nextCp); } } //NOTE: we are at the end of a chunk, therefore we can't infer surrogate pair yet. else if (!this.lastChunkWritten) { this.endOfChunkHit = true; return $.EOF; } //NOTE: isolated surrogate this._err(ERR.surrogateInInputStream); return cp; } dropParsedChunk() { if (this.pos > this.bufferWaterline) { this.lastCharPos -= this.pos; this.html = this.html.substring(this.pos); this.pos = 0; this.lastGapPos = -1; this.gapStack = []; } } write(chunk, isLastChunk) { if (this.html) { this.html += chunk; } else { this.html = chunk; } this.lastCharPos = this.html.length - 1; this.endOfChunkHit = false; this.lastChunkWritten = isLastChunk; } insertHtmlAtCurrentPos(chunk) { this.html = this.html.substring(0, this.pos + 1) + chunk + this.html.substring(this.pos + 1, this.html.length); this.lastCharPos = this.html.length - 1; this.endOfChunkHit = false; } advance() { this.pos++; if (this.pos > this.lastCharPos) { this.endOfChunkHit = !this.lastChunkWritten; return $.EOF; } let cp = this.html.charCodeAt(this.pos); //NOTE: any U+000A LINE FEED (LF) characters that immediately follow a U+000D CARRIAGE RETURN (CR) character //must be ignored. if (this.skipNextNewLine && cp === $.LINE_FEED) { this.skipNextNewLine = false; this._addGap(); return this.advance(); } //NOTE: all U+000D CARRIAGE RETURN (CR) characters must be converted to U+000A LINE FEED (LF) characters if (cp === $.CARRIAGE_RETURN) { this.skipNextNewLine = true; return $.LINE_FEED; } this.skipNextNewLine = false; if (unicode.isSurrogate(cp)) { cp = this._processSurrogate(cp); } //OPTIMIZATION: first check if code point is in the common allowed //range (ASCII alphanumeric, whitespaces, big chunk of BMP) //before going into detailed performance cost validation. const isCommonValidRange = (cp > 0x1f && cp < 0x7f) || cp === $.LINE_FEED || cp === $.CARRIAGE_RETURN || (cp > 0x9f && cp < 0xfdd0); if (!isCommonValidRange) { this._checkForProblematicCharacters(cp); } return cp; } _checkForProblematicCharacters(cp) { if (unicode.isControlCodePoint(cp)) { this._err(ERR.controlCharacterInInputStream); } else if (unicode.isUndefinedCodePoint(cp)) { this._err(ERR.noncharacterInInputStream); } } retreat() { if (this.pos === this.lastGapPos) { this.lastGapPos = this.gapStack.pop(); this.pos--; } this.pos--; } } module.exports = Preprocessor;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/parse5/lib/tokenizer/preprocessor.js
preprocessor.js
'use strict'; const HTML = require('parse5/lib/common/html'); //Aliases const $ = HTML.TAG_NAMES; const NS = HTML.NAMESPACES; //Element utils //OPTIMIZATION: Integer comparisons are low-cost, so we can use very fast tag name length filters here. //It's faster than using dictionary. function isImpliedEndTagRequired(tn) { switch (tn.length) { case 1: return tn === $.P; case 2: return tn === $.RB || tn === $.RP || tn === $.RT || tn === $.DD || tn === $.DT || tn === $.LI; case 3: return tn === $.RTC; case 6: return tn === $.OPTION; case 8: return tn === $.OPTGROUP; } return false; } function isImpliedEndTagRequiredThoroughly(tn) { switch (tn.length) { case 1: return tn === $.P; case 2: return ( tn === $.RB || tn === $.RP || tn === $.RT || tn === $.DD || tn === $.DT || tn === $.LI || tn === $.TD || tn === $.TH || tn === $.TR ); case 3: return tn === $.RTC; case 5: return tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD; case 6: return tn === $.OPTION; case 7: return tn === $.CAPTION; case 8: return tn === $.OPTGROUP || tn === $.COLGROUP; } return false; } function isScopingElement(tn, ns) { switch (tn.length) { case 2: if (tn === $.TD || tn === $.TH) { return ns === NS.HTML; } else if (tn === $.MI || tn === $.MO || tn === $.MN || tn === $.MS) { return ns === NS.MATHML; } break; case 4: if (tn === $.HTML) { return ns === NS.HTML; } else if (tn === $.DESC) { return ns === NS.SVG; } break; case 5: if (tn === $.TABLE) { return ns === NS.HTML; } else if (tn === $.MTEXT) { return ns === NS.MATHML; } else if (tn === $.TITLE) { return ns === NS.SVG; } break; case 6: return (tn === $.APPLET || tn === $.OBJECT) && ns === NS.HTML; case 7: return (tn === $.CAPTION || tn === $.MARQUEE) && ns === NS.HTML; case 8: return tn === $.TEMPLATE && ns === NS.HTML; case 13: return tn === $.FOREIGN_OBJECT && ns === NS.SVG; case 14: return tn === $.ANNOTATION_XML && ns === NS.MATHML; } return false; } //Stack of open elements class OpenElementStack { constructor(document, treeAdapter) { this.stackTop = -1; this.items = []; this.current = document; this.currentTagName = null; this.currentTmplContent = null; this.tmplCount = 0; this.treeAdapter = treeAdapter; } //Index of element _indexOf(element) { let idx = -1; for (let i = this.stackTop; i >= 0; i--) { if (this.items[i] === element) { idx = i; break; } } return idx; } //Update current element _isInTemplate() { return this.currentTagName === $.TEMPLATE && this.treeAdapter.getNamespaceURI(this.current) === NS.HTML; } _updateCurrentElement() { this.current = this.items[this.stackTop]; this.currentTagName = this.current && this.treeAdapter.getTagName(this.current); this.currentTmplContent = this._isInTemplate() ? this.treeAdapter.getTemplateContent(this.current) : null; } //Mutations push(element) { this.items[++this.stackTop] = element; this._updateCurrentElement(); if (this._isInTemplate()) { this.tmplCount++; } } pop() { this.stackTop--; if (this.tmplCount > 0 && this._isInTemplate()) { this.tmplCount--; } this._updateCurrentElement(); } replace(oldElement, newElement) { const idx = this._indexOf(oldElement); this.items[idx] = newElement; if (idx === this.stackTop) { this._updateCurrentElement(); } } insertAfter(referenceElement, newElement) { const insertionIdx = this._indexOf(referenceElement) + 1; this.items.splice(insertionIdx, 0, newElement); if (insertionIdx === ++this.stackTop) { this._updateCurrentElement(); } } popUntilTagNamePopped(tagName) { while (this.stackTop > -1) { const tn = this.currentTagName; const ns = this.treeAdapter.getNamespaceURI(this.current); this.pop(); if (tn === tagName && ns === NS.HTML) { break; } } } popUntilElementPopped(element) { while (this.stackTop > -1) { const poppedElement = this.current; this.pop(); if (poppedElement === element) { break; } } } popUntilNumberedHeaderPopped() { while (this.stackTop > -1) { const tn = this.currentTagName; const ns = this.treeAdapter.getNamespaceURI(this.current); this.pop(); if ( tn === $.H1 || tn === $.H2 || tn === $.H3 || tn === $.H4 || tn === $.H5 || (tn === $.H6 && ns === NS.HTML) ) { break; } } } popUntilTableCellPopped() { while (this.stackTop > -1) { const tn = this.currentTagName; const ns = this.treeAdapter.getNamespaceURI(this.current); this.pop(); if (tn === $.TD || (tn === $.TH && ns === NS.HTML)) { break; } } } popAllUpToHtmlElement() { //NOTE: here we assume that root <html> element is always first in the open element stack, so //we perform this fast stack clean up. this.stackTop = 0; this._updateCurrentElement(); } clearBackToTableContext() { while ( (this.currentTagName !== $.TABLE && this.currentTagName !== $.TEMPLATE && this.currentTagName !== $.HTML) || this.treeAdapter.getNamespaceURI(this.current) !== NS.HTML ) { this.pop(); } } clearBackToTableBodyContext() { while ( (this.currentTagName !== $.TBODY && this.currentTagName !== $.TFOOT && this.currentTagName !== $.THEAD && this.currentTagName !== $.TEMPLATE && this.currentTagName !== $.HTML) || this.treeAdapter.getNamespaceURI(this.current) !== NS.HTML ) { this.pop(); } } clearBackToTableRowContext() { while ( (this.currentTagName !== $.TR && this.currentTagName !== $.TEMPLATE && this.currentTagName !== $.HTML) || this.treeAdapter.getNamespaceURI(this.current) !== NS.HTML ) { this.pop(); } } remove(element) { for (let i = this.stackTop; i >= 0; i--) { if (this.items[i] === element) { this.items.splice(i, 1); this.stackTop--; this._updateCurrentElement(); break; } } } //Search tryPeekProperlyNestedBodyElement() { //Properly nested <body> element (should be second element in stack). const element = this.items[1]; return element && this.treeAdapter.getTagName(element) === $.BODY ? element : null; } contains(element) { return this._indexOf(element) > -1; } getCommonAncestor(element) { let elementIdx = this._indexOf(element); return --elementIdx >= 0 ? this.items[elementIdx] : null; } isRootHtmlElementCurrent() { return this.stackTop === 0 && this.currentTagName === $.HTML; } //Element in scope hasInScope(tagName) { for (let i = this.stackTop; i >= 0; i--) { const tn = this.treeAdapter.getTagName(this.items[i]); const ns = this.treeAdapter.getNamespaceURI(this.items[i]); if (tn === tagName && ns === NS.HTML) { return true; } if (isScopingElement(tn, ns)) { return false; } } return true; } hasNumberedHeaderInScope() { for (let i = this.stackTop; i >= 0; i--) { const tn = this.treeAdapter.getTagName(this.items[i]); const ns = this.treeAdapter.getNamespaceURI(this.items[i]); if ( (tn === $.H1 || tn === $.H2 || tn === $.H3 || tn === $.H4 || tn === $.H5 || tn === $.H6) && ns === NS.HTML ) { return true; } if (isScopingElement(tn, ns)) { return false; } } return true; } hasInListItemScope(tagName) { for (let i = this.stackTop; i >= 0; i--) { const tn = this.treeAdapter.getTagName(this.items[i]); const ns = this.treeAdapter.getNamespaceURI(this.items[i]); if (tn === tagName && ns === NS.HTML) { return true; } if (((tn === $.UL || tn === $.OL) && ns === NS.HTML) || isScopingElement(tn, ns)) { return false; } } return true; } hasInButtonScope(tagName) { for (let i = this.stackTop; i >= 0; i--) { const tn = this.treeAdapter.getTagName(this.items[i]); const ns = this.treeAdapter.getNamespaceURI(this.items[i]); if (tn === tagName && ns === NS.HTML) { return true; } if ((tn === $.BUTTON && ns === NS.HTML) || isScopingElement(tn, ns)) { return false; } } return true; } hasInTableScope(tagName) { for (let i = this.stackTop; i >= 0; i--) { const tn = this.treeAdapter.getTagName(this.items[i]); const ns = this.treeAdapter.getNamespaceURI(this.items[i]); if (ns !== NS.HTML) { continue; } if (tn === tagName) { return true; } if (tn === $.TABLE || tn === $.TEMPLATE || tn === $.HTML) { return false; } } return true; } hasTableBodyContextInTableScope() { for (let i = this.stackTop; i >= 0; i--) { const tn = this.treeAdapter.getTagName(this.items[i]); const ns = this.treeAdapter.getNamespaceURI(this.items[i]); if (ns !== NS.HTML) { continue; } if (tn === $.TBODY || tn === $.THEAD || tn === $.TFOOT) { return true; } if (tn === $.TABLE || tn === $.HTML) { return false; } } return true; } hasInSelectScope(tagName) { for (let i = this.stackTop; i >= 0; i--) { const tn = this.treeAdapter.getTagName(this.items[i]); const ns = this.treeAdapter.getNamespaceURI(this.items[i]); if (ns !== NS.HTML) { continue; } if (tn === tagName) { return true; } if (tn !== $.OPTION && tn !== $.OPTGROUP) { return false; } } return true; } //Implied end tags generateImpliedEndTags() { while (isImpliedEndTagRequired(this.currentTagName)) { this.pop(); } } generateImpliedEndTagsThoroughly() { while (isImpliedEndTagRequiredThoroughly(this.currentTagName)) { this.pop(); } } generateImpliedEndTagsWithExclusion(exclusionTagName) { while (isImpliedEndTagRequired(this.currentTagName) && this.currentTagName !== exclusionTagName) { this.pop(); } } } module.exports = OpenElementStack;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/parse5/lib/parser/open-element-stack.js
open-element-stack.js
'use strict'; const Tokenizer = require('parse5/lib/tokenizer'); const OpenElementStack = require('parse5/lib/parser/open-element-stack'); const FormattingElementList = require('parse5/lib/parser/formatting-element-list'); const LocationInfoParserMixin = require('parse5/lib/extensions/location-info/parser-mixin'); const ErrorReportingParserMixin = require('parse5/lib/extensions/error-reporting/parser-mixin'); const Mixin = require('parse5/lib/utils/mixin'); const defaultTreeAdapter = require('parse5/lib/tree-adapters/default'); const mergeOptions = require('parse5/lib/utils/merge-options'); const doctype = require('parse5/lib/common/doctype'); const foreignContent = require('parse5/lib/common/foreign-content'); const ERR = require('parse5/lib/common/error-codes'); const unicode = require('parse5/lib/common/unicode'); const HTML = require('parse5/lib/common/html'); //Aliases const $ = HTML.TAG_NAMES; const NS = HTML.NAMESPACES; const ATTRS = HTML.ATTRS; const DEFAULT_OPTIONS = { scriptingEnabled: true, sourceCodeLocationInfo: false, onParseError: null, treeAdapter: defaultTreeAdapter }; //Misc constants const HIDDEN_INPUT_TYPE = 'hidden'; //Adoption agency loops iteration count const AA_OUTER_LOOP_ITER = 8; const AA_INNER_LOOP_ITER = 3; //Insertion modes const INITIAL_MODE = 'INITIAL_MODE'; const BEFORE_HTML_MODE = 'BEFORE_HTML_MODE'; const BEFORE_HEAD_MODE = 'BEFORE_HEAD_MODE'; const IN_HEAD_MODE = 'IN_HEAD_MODE'; const IN_HEAD_NO_SCRIPT_MODE = 'IN_HEAD_NO_SCRIPT_MODE'; const AFTER_HEAD_MODE = 'AFTER_HEAD_MODE'; const IN_BODY_MODE = 'IN_BODY_MODE'; const TEXT_MODE = 'TEXT_MODE'; const IN_TABLE_MODE = 'IN_TABLE_MODE'; const IN_TABLE_TEXT_MODE = 'IN_TABLE_TEXT_MODE'; const IN_CAPTION_MODE = 'IN_CAPTION_MODE'; const IN_COLUMN_GROUP_MODE = 'IN_COLUMN_GROUP_MODE'; const IN_TABLE_BODY_MODE = 'IN_TABLE_BODY_MODE'; const IN_ROW_MODE = 'IN_ROW_MODE'; const IN_CELL_MODE = 'IN_CELL_MODE'; const IN_SELECT_MODE = 'IN_SELECT_MODE'; const IN_SELECT_IN_TABLE_MODE = 'IN_SELECT_IN_TABLE_MODE'; const IN_TEMPLATE_MODE = 'IN_TEMPLATE_MODE'; const AFTER_BODY_MODE = 'AFTER_BODY_MODE'; const IN_FRAMESET_MODE = 'IN_FRAMESET_MODE'; const AFTER_FRAMESET_MODE = 'AFTER_FRAMESET_MODE'; const AFTER_AFTER_BODY_MODE = 'AFTER_AFTER_BODY_MODE'; const AFTER_AFTER_FRAMESET_MODE = 'AFTER_AFTER_FRAMESET_MODE'; //Insertion mode reset map const INSERTION_MODE_RESET_MAP = { [$.TR]: IN_ROW_MODE, [$.TBODY]: IN_TABLE_BODY_MODE, [$.THEAD]: IN_TABLE_BODY_MODE, [$.TFOOT]: IN_TABLE_BODY_MODE, [$.CAPTION]: IN_CAPTION_MODE, [$.COLGROUP]: IN_COLUMN_GROUP_MODE, [$.TABLE]: IN_TABLE_MODE, [$.BODY]: IN_BODY_MODE, [$.FRAMESET]: IN_FRAMESET_MODE }; //Template insertion mode switch map const TEMPLATE_INSERTION_MODE_SWITCH_MAP = { [$.CAPTION]: IN_TABLE_MODE, [$.COLGROUP]: IN_TABLE_MODE, [$.TBODY]: IN_TABLE_MODE, [$.TFOOT]: IN_TABLE_MODE, [$.THEAD]: IN_TABLE_MODE, [$.COL]: IN_COLUMN_GROUP_MODE, [$.TR]: IN_TABLE_BODY_MODE, [$.TD]: IN_ROW_MODE, [$.TH]: IN_ROW_MODE }; //Token handlers map for insertion modes const TOKEN_HANDLERS = { [INITIAL_MODE]: { [Tokenizer.CHARACTER_TOKEN]: tokenInInitialMode, [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInInitialMode, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: doctypeInInitialMode, [Tokenizer.START_TAG_TOKEN]: tokenInInitialMode, [Tokenizer.END_TAG_TOKEN]: tokenInInitialMode, [Tokenizer.EOF_TOKEN]: tokenInInitialMode }, [BEFORE_HTML_MODE]: { [Tokenizer.CHARACTER_TOKEN]: tokenBeforeHtml, [Tokenizer.NULL_CHARACTER_TOKEN]: tokenBeforeHtml, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagBeforeHtml, [Tokenizer.END_TAG_TOKEN]: endTagBeforeHtml, [Tokenizer.EOF_TOKEN]: tokenBeforeHtml }, [BEFORE_HEAD_MODE]: { [Tokenizer.CHARACTER_TOKEN]: tokenBeforeHead, [Tokenizer.NULL_CHARACTER_TOKEN]: tokenBeforeHead, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, [Tokenizer.START_TAG_TOKEN]: startTagBeforeHead, [Tokenizer.END_TAG_TOKEN]: endTagBeforeHead, [Tokenizer.EOF_TOKEN]: tokenBeforeHead }, [IN_HEAD_MODE]: { [Tokenizer.CHARACTER_TOKEN]: tokenInHead, [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInHead, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, [Tokenizer.START_TAG_TOKEN]: startTagInHead, [Tokenizer.END_TAG_TOKEN]: endTagInHead, [Tokenizer.EOF_TOKEN]: tokenInHead }, [IN_HEAD_NO_SCRIPT_MODE]: { [Tokenizer.CHARACTER_TOKEN]: tokenInHeadNoScript, [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInHeadNoScript, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, [Tokenizer.START_TAG_TOKEN]: startTagInHeadNoScript, [Tokenizer.END_TAG_TOKEN]: endTagInHeadNoScript, [Tokenizer.EOF_TOKEN]: tokenInHeadNoScript }, [AFTER_HEAD_MODE]: { [Tokenizer.CHARACTER_TOKEN]: tokenAfterHead, [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterHead, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, [Tokenizer.START_TAG_TOKEN]: startTagAfterHead, [Tokenizer.END_TAG_TOKEN]: endTagAfterHead, [Tokenizer.EOF_TOKEN]: tokenAfterHead }, [IN_BODY_MODE]: { [Tokenizer.CHARACTER_TOKEN]: characterInBody, [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagInBody, [Tokenizer.END_TAG_TOKEN]: endTagInBody, [Tokenizer.EOF_TOKEN]: eofInBody }, [TEXT_MODE]: { [Tokenizer.CHARACTER_TOKEN]: insertCharacters, [Tokenizer.NULL_CHARACTER_TOKEN]: insertCharacters, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, [Tokenizer.COMMENT_TOKEN]: ignoreToken, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: ignoreToken, [Tokenizer.END_TAG_TOKEN]: endTagInText, [Tokenizer.EOF_TOKEN]: eofInText }, [IN_TABLE_MODE]: { [Tokenizer.CHARACTER_TOKEN]: characterInTable, [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagInTable, [Tokenizer.END_TAG_TOKEN]: endTagInTable, [Tokenizer.EOF_TOKEN]: eofInBody }, [IN_TABLE_TEXT_MODE]: { [Tokenizer.CHARACTER_TOKEN]: characterInTableText, [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInTableText, [Tokenizer.COMMENT_TOKEN]: tokenInTableText, [Tokenizer.DOCTYPE_TOKEN]: tokenInTableText, [Tokenizer.START_TAG_TOKEN]: tokenInTableText, [Tokenizer.END_TAG_TOKEN]: tokenInTableText, [Tokenizer.EOF_TOKEN]: tokenInTableText }, [IN_CAPTION_MODE]: { [Tokenizer.CHARACTER_TOKEN]: characterInBody, [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagInCaption, [Tokenizer.END_TAG_TOKEN]: endTagInCaption, [Tokenizer.EOF_TOKEN]: eofInBody }, [IN_COLUMN_GROUP_MODE]: { [Tokenizer.CHARACTER_TOKEN]: tokenInColumnGroup, [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInColumnGroup, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagInColumnGroup, [Tokenizer.END_TAG_TOKEN]: endTagInColumnGroup, [Tokenizer.EOF_TOKEN]: eofInBody }, [IN_TABLE_BODY_MODE]: { [Tokenizer.CHARACTER_TOKEN]: characterInTable, [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagInTableBody, [Tokenizer.END_TAG_TOKEN]: endTagInTableBody, [Tokenizer.EOF_TOKEN]: eofInBody }, [IN_ROW_MODE]: { [Tokenizer.CHARACTER_TOKEN]: characterInTable, [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagInRow, [Tokenizer.END_TAG_TOKEN]: endTagInRow, [Tokenizer.EOF_TOKEN]: eofInBody }, [IN_CELL_MODE]: { [Tokenizer.CHARACTER_TOKEN]: characterInBody, [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagInCell, [Tokenizer.END_TAG_TOKEN]: endTagInCell, [Tokenizer.EOF_TOKEN]: eofInBody }, [IN_SELECT_MODE]: { [Tokenizer.CHARACTER_TOKEN]: insertCharacters, [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagInSelect, [Tokenizer.END_TAG_TOKEN]: endTagInSelect, [Tokenizer.EOF_TOKEN]: eofInBody }, [IN_SELECT_IN_TABLE_MODE]: { [Tokenizer.CHARACTER_TOKEN]: insertCharacters, [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagInSelectInTable, [Tokenizer.END_TAG_TOKEN]: endTagInSelectInTable, [Tokenizer.EOF_TOKEN]: eofInBody }, [IN_TEMPLATE_MODE]: { [Tokenizer.CHARACTER_TOKEN]: characterInBody, [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagInTemplate, [Tokenizer.END_TAG_TOKEN]: endTagInTemplate, [Tokenizer.EOF_TOKEN]: eofInTemplate }, [AFTER_BODY_MODE]: { [Tokenizer.CHARACTER_TOKEN]: tokenAfterBody, [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterBody, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, [Tokenizer.COMMENT_TOKEN]: appendCommentToRootHtmlElement, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagAfterBody, [Tokenizer.END_TAG_TOKEN]: endTagAfterBody, [Tokenizer.EOF_TOKEN]: stopParsing }, [IN_FRAMESET_MODE]: { [Tokenizer.CHARACTER_TOKEN]: ignoreToken, [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagInFrameset, [Tokenizer.END_TAG_TOKEN]: endTagInFrameset, [Tokenizer.EOF_TOKEN]: stopParsing }, [AFTER_FRAMESET_MODE]: { [Tokenizer.CHARACTER_TOKEN]: ignoreToken, [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, [Tokenizer.COMMENT_TOKEN]: appendComment, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagAfterFrameset, [Tokenizer.END_TAG_TOKEN]: endTagAfterFrameset, [Tokenizer.EOF_TOKEN]: stopParsing }, [AFTER_AFTER_BODY_MODE]: { [Tokenizer.CHARACTER_TOKEN]: tokenAfterAfterBody, [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterAfterBody, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, [Tokenizer.COMMENT_TOKEN]: appendCommentToDocument, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagAfterAfterBody, [Tokenizer.END_TAG_TOKEN]: tokenAfterAfterBody, [Tokenizer.EOF_TOKEN]: stopParsing }, [AFTER_AFTER_FRAMESET_MODE]: { [Tokenizer.CHARACTER_TOKEN]: ignoreToken, [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, [Tokenizer.COMMENT_TOKEN]: appendCommentToDocument, [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, [Tokenizer.START_TAG_TOKEN]: startTagAfterAfterFrameset, [Tokenizer.END_TAG_TOKEN]: ignoreToken, [Tokenizer.EOF_TOKEN]: stopParsing } }; //Parser class Parser { constructor(options) { this.options = mergeOptions(DEFAULT_OPTIONS, options); this.treeAdapter = this.options.treeAdapter; this.pendingScript = null; if (this.options.sourceCodeLocationInfo) { Mixin.install(this, LocationInfoParserMixin); } if (this.options.onParseError) { Mixin.install(this, ErrorReportingParserMixin, { onParseError: this.options.onParseError }); } } // API parse(html) { const document = this.treeAdapter.createDocument(); this._bootstrap(document, null); this.tokenizer.write(html, true); this._runParsingLoop(null); return document; } parseFragment(html, fragmentContext) { //NOTE: use <template> element as a fragment context if context element was not provided, //so we will parse in "forgiving" manner if (!fragmentContext) { fragmentContext = this.treeAdapter.createElement($.TEMPLATE, NS.HTML, []); } //NOTE: create fake element which will be used as 'document' for fragment parsing. //This is important for jsdom there 'document' can't be recreated, therefore //fragment parsing causes messing of the main `document`. const documentMock = this.treeAdapter.createElement('documentmock', NS.HTML, []); this._bootstrap(documentMock, fragmentContext); if (this.treeAdapter.getTagName(fragmentContext) === $.TEMPLATE) { this._pushTmplInsertionMode(IN_TEMPLATE_MODE); } this._initTokenizerForFragmentParsing(); this._insertFakeRootElement(); this._resetInsertionMode(); this._findFormInFragmentContext(); this.tokenizer.write(html, true); this._runParsingLoop(null); const rootElement = this.treeAdapter.getFirstChild(documentMock); const fragment = this.treeAdapter.createDocumentFragment(); this._adoptNodes(rootElement, fragment); return fragment; } //Bootstrap parser _bootstrap(document, fragmentContext) { this.tokenizer = new Tokenizer(this.options); this.stopped = false; this.insertionMode = INITIAL_MODE; this.originalInsertionMode = ''; this.document = document; this.fragmentContext = fragmentContext; this.headElement = null; this.formElement = null; this.openElements = new OpenElementStack(this.document, this.treeAdapter); this.activeFormattingElements = new FormattingElementList(this.treeAdapter); this.tmplInsertionModeStack = []; this.tmplInsertionModeStackTop = -1; this.currentTmplInsertionMode = null; this.pendingCharacterTokens = []; this.hasNonWhitespacePendingCharacterToken = false; this.framesetOk = true; this.skipNextNewLine = false; this.fosterParentingEnabled = false; } //Errors _err() { // NOTE: err reporting is noop by default. Enabled by mixin. } //Parsing loop _runParsingLoop(scriptHandler) { while (!this.stopped) { this._setupTokenizerCDATAMode(); const token = this.tokenizer.getNextToken(); if (token.type === Tokenizer.HIBERNATION_TOKEN) { break; } if (this.skipNextNewLine) { this.skipNextNewLine = false; if (token.type === Tokenizer.WHITESPACE_CHARACTER_TOKEN && token.chars[0] === '\n') { if (token.chars.length === 1) { continue; } token.chars = token.chars.substr(1); } } this._processInputToken(token); if (scriptHandler && this.pendingScript) { break; } } } runParsingLoopForCurrentChunk(writeCallback, scriptHandler) { this._runParsingLoop(scriptHandler); if (scriptHandler && this.pendingScript) { const script = this.pendingScript; this.pendingScript = null; scriptHandler(script); return; } if (writeCallback) { writeCallback(); } } //Text parsing _setupTokenizerCDATAMode() { const current = this._getAdjustedCurrentElement(); this.tokenizer.allowCDATA = current && current !== this.document && this.treeAdapter.getNamespaceURI(current) !== NS.HTML && !this._isIntegrationPoint(current); } _switchToTextParsing(currentToken, nextTokenizerState) { this._insertElement(currentToken, NS.HTML); this.tokenizer.state = nextTokenizerState; this.originalInsertionMode = this.insertionMode; this.insertionMode = TEXT_MODE; } switchToPlaintextParsing() { this.insertionMode = TEXT_MODE; this.originalInsertionMode = IN_BODY_MODE; this.tokenizer.state = Tokenizer.MODE.PLAINTEXT; } //Fragment parsing _getAdjustedCurrentElement() { return this.openElements.stackTop === 0 && this.fragmentContext ? this.fragmentContext : this.openElements.current; } _findFormInFragmentContext() { let node = this.fragmentContext; do { if (this.treeAdapter.getTagName(node) === $.FORM) { this.formElement = node; break; } node = this.treeAdapter.getParentNode(node); } while (node); } _initTokenizerForFragmentParsing() { if (this.treeAdapter.getNamespaceURI(this.fragmentContext) === NS.HTML) { const tn = this.treeAdapter.getTagName(this.fragmentContext); if (tn === $.TITLE || tn === $.TEXTAREA) { this.tokenizer.state = Tokenizer.MODE.RCDATA; } else if ( tn === $.STYLE || tn === $.XMP || tn === $.IFRAME || tn === $.NOEMBED || tn === $.NOFRAMES || tn === $.NOSCRIPT ) { this.tokenizer.state = Tokenizer.MODE.RAWTEXT; } else if (tn === $.SCRIPT) { this.tokenizer.state = Tokenizer.MODE.SCRIPT_DATA; } else if (tn === $.PLAINTEXT) { this.tokenizer.state = Tokenizer.MODE.PLAINTEXT; } } } //Tree mutation _setDocumentType(token) { const name = token.name || ''; const publicId = token.publicId || ''; const systemId = token.systemId || ''; this.treeAdapter.setDocumentType(this.document, name, publicId, systemId); } _attachElementToTree(element) { if (this._shouldFosterParentOnInsertion()) { this._fosterParentElement(element); } else { const parent = this.openElements.currentTmplContent || this.openElements.current; this.treeAdapter.appendChild(parent, element); } } _appendElement(token, namespaceURI) { const element = this.treeAdapter.createElement(token.tagName, namespaceURI, token.attrs); this._attachElementToTree(element); } _insertElement(token, namespaceURI) { const element = this.treeAdapter.createElement(token.tagName, namespaceURI, token.attrs); this._attachElementToTree(element); this.openElements.push(element); } _insertFakeElement(tagName) { const element = this.treeAdapter.createElement(tagName, NS.HTML, []); this._attachElementToTree(element); this.openElements.push(element); } _insertTemplate(token) { const tmpl = this.treeAdapter.createElement(token.tagName, NS.HTML, token.attrs); const content = this.treeAdapter.createDocumentFragment(); this.treeAdapter.setTemplateContent(tmpl, content); this._attachElementToTree(tmpl); this.openElements.push(tmpl); } _insertFakeRootElement() { const element = this.treeAdapter.createElement($.HTML, NS.HTML, []); this.treeAdapter.appendChild(this.openElements.current, element); this.openElements.push(element); } _appendCommentNode(token, parent) { const commentNode = this.treeAdapter.createCommentNode(token.data); this.treeAdapter.appendChild(parent, commentNode); } _insertCharacters(token) { if (this._shouldFosterParentOnInsertion()) { this._fosterParentText(token.chars); } else { const parent = this.openElements.currentTmplContent || this.openElements.current; this.treeAdapter.insertText(parent, token.chars); } } _adoptNodes(donor, recipient) { for (let child = this.treeAdapter.getFirstChild(donor); child; child = this.treeAdapter.getFirstChild(donor)) { this.treeAdapter.detachNode(child); this.treeAdapter.appendChild(recipient, child); } } //Token processing _shouldProcessTokenInForeignContent(token) { const current = this._getAdjustedCurrentElement(); if (!current || current === this.document) { return false; } const ns = this.treeAdapter.getNamespaceURI(current); if (ns === NS.HTML) { return false; } if ( this.treeAdapter.getTagName(current) === $.ANNOTATION_XML && ns === NS.MATHML && token.type === Tokenizer.START_TAG_TOKEN && token.tagName === $.SVG ) { return false; } const isCharacterToken = token.type === Tokenizer.CHARACTER_TOKEN || token.type === Tokenizer.NULL_CHARACTER_TOKEN || token.type === Tokenizer.WHITESPACE_CHARACTER_TOKEN; const isMathMLTextStartTag = token.type === Tokenizer.START_TAG_TOKEN && token.tagName !== $.MGLYPH && token.tagName !== $.MALIGNMARK; if ((isMathMLTextStartTag || isCharacterToken) && this._isIntegrationPoint(current, NS.MATHML)) { return false; } if ( (token.type === Tokenizer.START_TAG_TOKEN || isCharacterToken) && this._isIntegrationPoint(current, NS.HTML) ) { return false; } return token.type !== Tokenizer.EOF_TOKEN; } _processToken(token) { TOKEN_HANDLERS[this.insertionMode][token.type](this, token); } _processTokenInBodyMode(token) { TOKEN_HANDLERS[IN_BODY_MODE][token.type](this, token); } _processTokenInForeignContent(token) { if (token.type === Tokenizer.CHARACTER_TOKEN) { characterInForeignContent(this, token); } else if (token.type === Tokenizer.NULL_CHARACTER_TOKEN) { nullCharacterInForeignContent(this, token); } else if (token.type === Tokenizer.WHITESPACE_CHARACTER_TOKEN) { insertCharacters(this, token); } else if (token.type === Tokenizer.COMMENT_TOKEN) { appendComment(this, token); } else if (token.type === Tokenizer.START_TAG_TOKEN) { startTagInForeignContent(this, token); } else if (token.type === Tokenizer.END_TAG_TOKEN) { endTagInForeignContent(this, token); } } _processInputToken(token) { if (this._shouldProcessTokenInForeignContent(token)) { this._processTokenInForeignContent(token); } else { this._processToken(token); } if (token.type === Tokenizer.START_TAG_TOKEN && token.selfClosing && !token.ackSelfClosing) { this._err(ERR.nonVoidHtmlElementStartTagWithTrailingSolidus); } } //Integration points _isIntegrationPoint(element, foreignNS) { const tn = this.treeAdapter.getTagName(element); const ns = this.treeAdapter.getNamespaceURI(element); const attrs = this.treeAdapter.getAttrList(element); return foreignContent.isIntegrationPoint(tn, ns, attrs, foreignNS); } //Active formatting elements reconstruction _reconstructActiveFormattingElements() { const listLength = this.activeFormattingElements.length; if (listLength) { let unopenIdx = listLength; let entry = null; do { unopenIdx--; entry = this.activeFormattingElements.entries[unopenIdx]; if (entry.type === FormattingElementList.MARKER_ENTRY || this.openElements.contains(entry.element)) { unopenIdx++; break; } } while (unopenIdx > 0); for (let i = unopenIdx; i < listLength; i++) { entry = this.activeFormattingElements.entries[i]; this._insertElement(entry.token, this.treeAdapter.getNamespaceURI(entry.element)); entry.element = this.openElements.current; } } } //Close elements _closeTableCell() { this.openElements.generateImpliedEndTags(); this.openElements.popUntilTableCellPopped(); this.activeFormattingElements.clearToLastMarker(); this.insertionMode = IN_ROW_MODE; } _closePElement() { this.openElements.generateImpliedEndTagsWithExclusion($.P); this.openElements.popUntilTagNamePopped($.P); } //Insertion modes _resetInsertionMode() { for (let i = this.openElements.stackTop, last = false; i >= 0; i--) { let element = this.openElements.items[i]; if (i === 0) { last = true; if (this.fragmentContext) { element = this.fragmentContext; } } const tn = this.treeAdapter.getTagName(element); const newInsertionMode = INSERTION_MODE_RESET_MAP[tn]; if (newInsertionMode) { this.insertionMode = newInsertionMode; break; } else if (!last && (tn === $.TD || tn === $.TH)) { this.insertionMode = IN_CELL_MODE; break; } else if (!last && tn === $.HEAD) { this.insertionMode = IN_HEAD_MODE; break; } else if (tn === $.SELECT) { this._resetInsertionModeForSelect(i); break; } else if (tn === $.TEMPLATE) { this.insertionMode = this.currentTmplInsertionMode; break; } else if (tn === $.HTML) { this.insertionMode = this.headElement ? AFTER_HEAD_MODE : BEFORE_HEAD_MODE; break; } else if (last) { this.insertionMode = IN_BODY_MODE; break; } } } _resetInsertionModeForSelect(selectIdx) { if (selectIdx > 0) { for (let i = selectIdx - 1; i > 0; i--) { const ancestor = this.openElements.items[i]; const tn = this.treeAdapter.getTagName(ancestor); if (tn === $.TEMPLATE) { break; } else if (tn === $.TABLE) { this.insertionMode = IN_SELECT_IN_TABLE_MODE; return; } } } this.insertionMode = IN_SELECT_MODE; } _pushTmplInsertionMode(mode) { this.tmplInsertionModeStack.push(mode); this.tmplInsertionModeStackTop++; this.currentTmplInsertionMode = mode; } _popTmplInsertionMode() { this.tmplInsertionModeStack.pop(); this.tmplInsertionModeStackTop--; this.currentTmplInsertionMode = this.tmplInsertionModeStack[this.tmplInsertionModeStackTop]; } //Foster parenting _isElementCausesFosterParenting(element) { const tn = this.treeAdapter.getTagName(element); return tn === $.TABLE || tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD || tn === $.TR; } _shouldFosterParentOnInsertion() { return this.fosterParentingEnabled && this._isElementCausesFosterParenting(this.openElements.current); } _findFosterParentingLocation() { const location = { parent: null, beforeElement: null }; for (let i = this.openElements.stackTop; i >= 0; i--) { const openElement = this.openElements.items[i]; const tn = this.treeAdapter.getTagName(openElement); const ns = this.treeAdapter.getNamespaceURI(openElement); if (tn === $.TEMPLATE && ns === NS.HTML) { location.parent = this.treeAdapter.getTemplateContent(openElement); break; } else if (tn === $.TABLE) { location.parent = this.treeAdapter.getParentNode(openElement); if (location.parent) { location.beforeElement = openElement; } else { location.parent = this.openElements.items[i - 1]; } break; } } if (!location.parent) { location.parent = this.openElements.items[0]; } return location; } _fosterParentElement(element) { const location = this._findFosterParentingLocation(); if (location.beforeElement) { this.treeAdapter.insertBefore(location.parent, element, location.beforeElement); } else { this.treeAdapter.appendChild(location.parent, element); } } _fosterParentText(chars) { const location = this._findFosterParentingLocation(); if (location.beforeElement) { this.treeAdapter.insertTextBefore(location.parent, chars, location.beforeElement); } else { this.treeAdapter.insertText(location.parent, chars); } } //Special elements _isSpecialElement(element) { const tn = this.treeAdapter.getTagName(element); const ns = this.treeAdapter.getNamespaceURI(element); return HTML.SPECIAL_ELEMENTS[ns][tn]; } } module.exports = Parser; //Adoption agency algorithm //(see: http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#adoptionAgency) //------------------------------------------------------------------ //Steps 5-8 of the algorithm function aaObtainFormattingElementEntry(p, token) { let formattingElementEntry = p.activeFormattingElements.getElementEntryInScopeWithTagName(token.tagName); if (formattingElementEntry) { if (!p.openElements.contains(formattingElementEntry.element)) { p.activeFormattingElements.removeEntry(formattingElementEntry); formattingElementEntry = null; } else if (!p.openElements.hasInScope(token.tagName)) { formattingElementEntry = null; } } else { genericEndTagInBody(p, token); } return formattingElementEntry; } //Steps 9 and 10 of the algorithm function aaObtainFurthestBlock(p, formattingElementEntry) { let furthestBlock = null; for (let i = p.openElements.stackTop; i >= 0; i--) { const element = p.openElements.items[i]; if (element === formattingElementEntry.element) { break; } if (p._isSpecialElement(element)) { furthestBlock = element; } } if (!furthestBlock) { p.openElements.popUntilElementPopped(formattingElementEntry.element); p.activeFormattingElements.removeEntry(formattingElementEntry); } return furthestBlock; } //Step 13 of the algorithm function aaInnerLoop(p, furthestBlock, formattingElement) { let lastElement = furthestBlock; let nextElement = p.openElements.getCommonAncestor(furthestBlock); for (let i = 0, element = nextElement; element !== formattingElement; i++, element = nextElement) { //NOTE: store next element for the next loop iteration (it may be deleted from the stack by step 9.5) nextElement = p.openElements.getCommonAncestor(element); const elementEntry = p.activeFormattingElements.getElementEntry(element); const counterOverflow = elementEntry && i >= AA_INNER_LOOP_ITER; const shouldRemoveFromOpenElements = !elementEntry || counterOverflow; if (shouldRemoveFromOpenElements) { if (counterOverflow) { p.activeFormattingElements.removeEntry(elementEntry); } p.openElements.remove(element); } else { element = aaRecreateElementFromEntry(p, elementEntry); if (lastElement === furthestBlock) { p.activeFormattingElements.bookmark = elementEntry; } p.treeAdapter.detachNode(lastElement); p.treeAdapter.appendChild(element, lastElement); lastElement = element; } } return lastElement; } //Step 13.7 of the algorithm function aaRecreateElementFromEntry(p, elementEntry) { const ns = p.treeAdapter.getNamespaceURI(elementEntry.element); const newElement = p.treeAdapter.createElement(elementEntry.token.tagName, ns, elementEntry.token.attrs); p.openElements.replace(elementEntry.element, newElement); elementEntry.element = newElement; return newElement; } //Step 14 of the algorithm function aaInsertLastNodeInCommonAncestor(p, commonAncestor, lastElement) { if (p._isElementCausesFosterParenting(commonAncestor)) { p._fosterParentElement(lastElement); } else { const tn = p.treeAdapter.getTagName(commonAncestor); const ns = p.treeAdapter.getNamespaceURI(commonAncestor); if (tn === $.TEMPLATE && ns === NS.HTML) { commonAncestor = p.treeAdapter.getTemplateContent(commonAncestor); } p.treeAdapter.appendChild(commonAncestor, lastElement); } } //Steps 15-19 of the algorithm function aaReplaceFormattingElement(p, furthestBlock, formattingElementEntry) { const ns = p.treeAdapter.getNamespaceURI(formattingElementEntry.element); const token = formattingElementEntry.token; const newElement = p.treeAdapter.createElement(token.tagName, ns, token.attrs); p._adoptNodes(furthestBlock, newElement); p.treeAdapter.appendChild(furthestBlock, newElement); p.activeFormattingElements.insertElementAfterBookmark(newElement, formattingElementEntry.token); p.activeFormattingElements.removeEntry(formattingElementEntry); p.openElements.remove(formattingElementEntry.element); p.openElements.insertAfter(furthestBlock, newElement); } //Algorithm entry point function callAdoptionAgency(p, token) { let formattingElementEntry; for (let i = 0; i < AA_OUTER_LOOP_ITER; i++) { formattingElementEntry = aaObtainFormattingElementEntry(p, token, formattingElementEntry); if (!formattingElementEntry) { break; } const furthestBlock = aaObtainFurthestBlock(p, formattingElementEntry); if (!furthestBlock) { break; } p.activeFormattingElements.bookmark = formattingElementEntry; const lastElement = aaInnerLoop(p, furthestBlock, formattingElementEntry.element); const commonAncestor = p.openElements.getCommonAncestor(formattingElementEntry.element); p.treeAdapter.detachNode(lastElement); aaInsertLastNodeInCommonAncestor(p, commonAncestor, lastElement); aaReplaceFormattingElement(p, furthestBlock, formattingElementEntry); } } //Generic token handlers //------------------------------------------------------------------ function ignoreToken() { //NOTE: do nothing =) } function misplacedDoctype(p) { p._err(ERR.misplacedDoctype); } function appendComment(p, token) { p._appendCommentNode(token, p.openElements.currentTmplContent || p.openElements.current); } function appendCommentToRootHtmlElement(p, token) { p._appendCommentNode(token, p.openElements.items[0]); } function appendCommentToDocument(p, token) { p._appendCommentNode(token, p.document); } function insertCharacters(p, token) { p._insertCharacters(token); } function stopParsing(p) { p.stopped = true; } // The "initial" insertion mode //------------------------------------------------------------------ function doctypeInInitialMode(p, token) { p._setDocumentType(token); const mode = token.forceQuirks ? HTML.DOCUMENT_MODE.QUIRKS : doctype.getDocumentMode(token); if (!doctype.isConforming(token)) { p._err(ERR.nonConformingDoctype); } p.treeAdapter.setDocumentMode(p.document, mode); p.insertionMode = BEFORE_HTML_MODE; } function tokenInInitialMode(p, token) { p._err(ERR.missingDoctype, { beforeToken: true }); p.treeAdapter.setDocumentMode(p.document, HTML.DOCUMENT_MODE.QUIRKS); p.insertionMode = BEFORE_HTML_MODE; p._processToken(token); } // The "before html" insertion mode //------------------------------------------------------------------ function startTagBeforeHtml(p, token) { if (token.tagName === $.HTML) { p._insertElement(token, NS.HTML); p.insertionMode = BEFORE_HEAD_MODE; } else { tokenBeforeHtml(p, token); } } function endTagBeforeHtml(p, token) { const tn = token.tagName; if (tn === $.HTML || tn === $.HEAD || tn === $.BODY || tn === $.BR) { tokenBeforeHtml(p, token); } } function tokenBeforeHtml(p, token) { p._insertFakeRootElement(); p.insertionMode = BEFORE_HEAD_MODE; p._processToken(token); } // The "before head" insertion mode //------------------------------------------------------------------ function startTagBeforeHead(p, token) { const tn = token.tagName; if (tn === $.HTML) { startTagInBody(p, token); } else if (tn === $.HEAD) { p._insertElement(token, NS.HTML); p.headElement = p.openElements.current; p.insertionMode = IN_HEAD_MODE; } else { tokenBeforeHead(p, token); } } function endTagBeforeHead(p, token) { const tn = token.tagName; if (tn === $.HEAD || tn === $.BODY || tn === $.HTML || tn === $.BR) { tokenBeforeHead(p, token); } else { p._err(ERR.endTagWithoutMatchingOpenElement); } } function tokenBeforeHead(p, token) { p._insertFakeElement($.HEAD); p.headElement = p.openElements.current; p.insertionMode = IN_HEAD_MODE; p._processToken(token); } // The "in head" insertion mode //------------------------------------------------------------------ function startTagInHead(p, token) { const tn = token.tagName; if (tn === $.HTML) { startTagInBody(p, token); } else if (tn === $.BASE || tn === $.BASEFONT || tn === $.BGSOUND || tn === $.LINK || tn === $.META) { p._appendElement(token, NS.HTML); token.ackSelfClosing = true; } else if (tn === $.TITLE) { p._switchToTextParsing(token, Tokenizer.MODE.RCDATA); } else if (tn === $.NOSCRIPT) { if (p.options.scriptingEnabled) { p._switchToTextParsing(token, Tokenizer.MODE.RAWTEXT); } else { p._insertElement(token, NS.HTML); p.insertionMode = IN_HEAD_NO_SCRIPT_MODE; } } else if (tn === $.NOFRAMES || tn === $.STYLE) { p._switchToTextParsing(token, Tokenizer.MODE.RAWTEXT); } else if (tn === $.SCRIPT) { p._switchToTextParsing(token, Tokenizer.MODE.SCRIPT_DATA); } else if (tn === $.TEMPLATE) { p._insertTemplate(token, NS.HTML); p.activeFormattingElements.insertMarker(); p.framesetOk = false; p.insertionMode = IN_TEMPLATE_MODE; p._pushTmplInsertionMode(IN_TEMPLATE_MODE); } else if (tn === $.HEAD) { p._err(ERR.misplacedStartTagForHeadElement); } else { tokenInHead(p, token); } } function endTagInHead(p, token) { const tn = token.tagName; if (tn === $.HEAD) { p.openElements.pop(); p.insertionMode = AFTER_HEAD_MODE; } else if (tn === $.BODY || tn === $.BR || tn === $.HTML) { tokenInHead(p, token); } else if (tn === $.TEMPLATE) { if (p.openElements.tmplCount > 0) { p.openElements.generateImpliedEndTagsThoroughly(); if (p.openElements.currentTagName !== $.TEMPLATE) { p._err(ERR.closingOfElementWithOpenChildElements); } p.openElements.popUntilTagNamePopped($.TEMPLATE); p.activeFormattingElements.clearToLastMarker(); p._popTmplInsertionMode(); p._resetInsertionMode(); } else { p._err(ERR.endTagWithoutMatchingOpenElement); } } else { p._err(ERR.endTagWithoutMatchingOpenElement); } } function tokenInHead(p, token) { p.openElements.pop(); p.insertionMode = AFTER_HEAD_MODE; p._processToken(token); } // The "in head no script" insertion mode //------------------------------------------------------------------ function startTagInHeadNoScript(p, token) { const tn = token.tagName; if (tn === $.HTML) { startTagInBody(p, token); } else if ( tn === $.BASEFONT || tn === $.BGSOUND || tn === $.HEAD || tn === $.LINK || tn === $.META || tn === $.NOFRAMES || tn === $.STYLE ) { startTagInHead(p, token); } else if (tn === $.NOSCRIPT) { p._err(ERR.nestedNoscriptInHead); } else { tokenInHeadNoScript(p, token); } } function endTagInHeadNoScript(p, token) { const tn = token.tagName; if (tn === $.NOSCRIPT) { p.openElements.pop(); p.insertionMode = IN_HEAD_MODE; } else if (tn === $.BR) { tokenInHeadNoScript(p, token); } else { p._err(ERR.endTagWithoutMatchingOpenElement); } } function tokenInHeadNoScript(p, token) { const errCode = token.type === Tokenizer.EOF_TOKEN ? ERR.openElementsLeftAfterEof : ERR.disallowedContentInNoscriptInHead; p._err(errCode); p.openElements.pop(); p.insertionMode = IN_HEAD_MODE; p._processToken(token); } // The "after head" insertion mode //------------------------------------------------------------------ function startTagAfterHead(p, token) { const tn = token.tagName; if (tn === $.HTML) { startTagInBody(p, token); } else if (tn === $.BODY) { p._insertElement(token, NS.HTML); p.framesetOk = false; p.insertionMode = IN_BODY_MODE; } else if (tn === $.FRAMESET) { p._insertElement(token, NS.HTML); p.insertionMode = IN_FRAMESET_MODE; } else if ( tn === $.BASE || tn === $.BASEFONT || tn === $.BGSOUND || tn === $.LINK || tn === $.META || tn === $.NOFRAMES || tn === $.SCRIPT || tn === $.STYLE || tn === $.TEMPLATE || tn === $.TITLE ) { p._err(ERR.abandonedHeadElementChild); p.openElements.push(p.headElement); startTagInHead(p, token); p.openElements.remove(p.headElement); } else if (tn === $.HEAD) { p._err(ERR.misplacedStartTagForHeadElement); } else { tokenAfterHead(p, token); } } function endTagAfterHead(p, token) { const tn = token.tagName; if (tn === $.BODY || tn === $.HTML || tn === $.BR) { tokenAfterHead(p, token); } else if (tn === $.TEMPLATE) { endTagInHead(p, token); } else { p._err(ERR.endTagWithoutMatchingOpenElement); } } function tokenAfterHead(p, token) { p._insertFakeElement($.BODY); p.insertionMode = IN_BODY_MODE; p._processToken(token); } // The "in body" insertion mode //------------------------------------------------------------------ function whitespaceCharacterInBody(p, token) { p._reconstructActiveFormattingElements(); p._insertCharacters(token); } function characterInBody(p, token) { p._reconstructActiveFormattingElements(); p._insertCharacters(token); p.framesetOk = false; } function htmlStartTagInBody(p, token) { if (p.openElements.tmplCount === 0) { p.treeAdapter.adoptAttributes(p.openElements.items[0], token.attrs); } } function bodyStartTagInBody(p, token) { const bodyElement = p.openElements.tryPeekProperlyNestedBodyElement(); if (bodyElement && p.openElements.tmplCount === 0) { p.framesetOk = false; p.treeAdapter.adoptAttributes(bodyElement, token.attrs); } } function framesetStartTagInBody(p, token) { const bodyElement = p.openElements.tryPeekProperlyNestedBodyElement(); if (p.framesetOk && bodyElement) { p.treeAdapter.detachNode(bodyElement); p.openElements.popAllUpToHtmlElement(); p._insertElement(token, NS.HTML); p.insertionMode = IN_FRAMESET_MODE; } } function addressStartTagInBody(p, token) { if (p.openElements.hasInButtonScope($.P)) { p._closePElement(); } p._insertElement(token, NS.HTML); } function numberedHeaderStartTagInBody(p, token) { if (p.openElements.hasInButtonScope($.P)) { p._closePElement(); } const tn = p.openElements.currentTagName; if (tn === $.H1 || tn === $.H2 || tn === $.H3 || tn === $.H4 || tn === $.H5 || tn === $.H6) { p.openElements.pop(); } p._insertElement(token, NS.HTML); } function preStartTagInBody(p, token) { if (p.openElements.hasInButtonScope($.P)) { p._closePElement(); } p._insertElement(token, NS.HTML); //NOTE: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move //on to the next one. (Newlines at the start of pre blocks are ignored as an authoring convenience.) p.skipNextNewLine = true; p.framesetOk = false; } function formStartTagInBody(p, token) { const inTemplate = p.openElements.tmplCount > 0; if (!p.formElement || inTemplate) { if (p.openElements.hasInButtonScope($.P)) { p._closePElement(); } p._insertElement(token, NS.HTML); if (!inTemplate) { p.formElement = p.openElements.current; } } } function listItemStartTagInBody(p, token) { p.framesetOk = false; const tn = token.tagName; for (let i = p.openElements.stackTop; i >= 0; i--) { const element = p.openElements.items[i]; const elementTn = p.treeAdapter.getTagName(element); let closeTn = null; if (tn === $.LI && elementTn === $.LI) { closeTn = $.LI; } else if ((tn === $.DD || tn === $.DT) && (elementTn === $.DD || elementTn === $.DT)) { closeTn = elementTn; } if (closeTn) { p.openElements.generateImpliedEndTagsWithExclusion(closeTn); p.openElements.popUntilTagNamePopped(closeTn); break; } if (elementTn !== $.ADDRESS && elementTn !== $.DIV && elementTn !== $.P && p._isSpecialElement(element)) { break; } } if (p.openElements.hasInButtonScope($.P)) { p._closePElement(); } p._insertElement(token, NS.HTML); } function plaintextStartTagInBody(p, token) { if (p.openElements.hasInButtonScope($.P)) { p._closePElement(); } p._insertElement(token, NS.HTML); p.tokenizer.state = Tokenizer.MODE.PLAINTEXT; } function buttonStartTagInBody(p, token) { if (p.openElements.hasInScope($.BUTTON)) { p.openElements.generateImpliedEndTags(); p.openElements.popUntilTagNamePopped($.BUTTON); } p._reconstructActiveFormattingElements(); p._insertElement(token, NS.HTML); p.framesetOk = false; } function aStartTagInBody(p, token) { const activeElementEntry = p.activeFormattingElements.getElementEntryInScopeWithTagName($.A); if (activeElementEntry) { callAdoptionAgency(p, token); p.openElements.remove(activeElementEntry.element); p.activeFormattingElements.removeEntry(activeElementEntry); } p._reconstructActiveFormattingElements(); p._insertElement(token, NS.HTML); p.activeFormattingElements.pushElement(p.openElements.current, token); } function bStartTagInBody(p, token) { p._reconstructActiveFormattingElements(); p._insertElement(token, NS.HTML); p.activeFormattingElements.pushElement(p.openElements.current, token); } function nobrStartTagInBody(p, token) { p._reconstructActiveFormattingElements(); if (p.openElements.hasInScope($.NOBR)) { callAdoptionAgency(p, token); p._reconstructActiveFormattingElements(); } p._insertElement(token, NS.HTML); p.activeFormattingElements.pushElement(p.openElements.current, token); } function appletStartTagInBody(p, token) { p._reconstructActiveFormattingElements(); p._insertElement(token, NS.HTML); p.activeFormattingElements.insertMarker(); p.framesetOk = false; } function tableStartTagInBody(p, token) { if ( p.treeAdapter.getDocumentMode(p.document) !== HTML.DOCUMENT_MODE.QUIRKS && p.openElements.hasInButtonScope($.P) ) { p._closePElement(); } p._insertElement(token, NS.HTML); p.framesetOk = false; p.insertionMode = IN_TABLE_MODE; } function areaStartTagInBody(p, token) { p._reconstructActiveFormattingElements(); p._appendElement(token, NS.HTML); p.framesetOk = false; token.ackSelfClosing = true; } function inputStartTagInBody(p, token) { p._reconstructActiveFormattingElements(); p._appendElement(token, NS.HTML); const inputType = Tokenizer.getTokenAttr(token, ATTRS.TYPE); if (!inputType || inputType.toLowerCase() !== HIDDEN_INPUT_TYPE) { p.framesetOk = false; } token.ackSelfClosing = true; } function paramStartTagInBody(p, token) { p._appendElement(token, NS.HTML); token.ackSelfClosing = true; } function hrStartTagInBody(p, token) { if (p.openElements.hasInButtonScope($.P)) { p._closePElement(); } p._appendElement(token, NS.HTML); p.framesetOk = false; p.ackSelfClosing = true; } function imageStartTagInBody(p, token) { token.tagName = $.IMG; areaStartTagInBody(p, token); } function textareaStartTagInBody(p, token) { p._insertElement(token, NS.HTML); //NOTE: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move //on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.) p.skipNextNewLine = true; p.tokenizer.state = Tokenizer.MODE.RCDATA; p.originalInsertionMode = p.insertionMode; p.framesetOk = false; p.insertionMode = TEXT_MODE; } function xmpStartTagInBody(p, token) { if (p.openElements.hasInButtonScope($.P)) { p._closePElement(); } p._reconstructActiveFormattingElements(); p.framesetOk = false; p._switchToTextParsing(token, Tokenizer.MODE.RAWTEXT); } function iframeStartTagInBody(p, token) { p.framesetOk = false; p._switchToTextParsing(token, Tokenizer.MODE.RAWTEXT); } //NOTE: here we assume that we always act as an user agent with enabled plugins, so we parse //<noembed> as a rawtext. function noembedStartTagInBody(p, token) { p._switchToTextParsing(token, Tokenizer.MODE.RAWTEXT); } function selectStartTagInBody(p, token) { p._reconstructActiveFormattingElements(); p._insertElement(token, NS.HTML); p.framesetOk = false; if ( p.insertionMode === IN_TABLE_MODE || p.insertionMode === IN_CAPTION_MODE || p.insertionMode === IN_TABLE_BODY_MODE || p.insertionMode === IN_ROW_MODE || p.insertionMode === IN_CELL_MODE ) { p.insertionMode = IN_SELECT_IN_TABLE_MODE; } else { p.insertionMode = IN_SELECT_MODE; } } function optgroupStartTagInBody(p, token) { if (p.openElements.currentTagName === $.OPTION) { p.openElements.pop(); } p._reconstructActiveFormattingElements(); p._insertElement(token, NS.HTML); } function rbStartTagInBody(p, token) { if (p.openElements.hasInScope($.RUBY)) { p.openElements.generateImpliedEndTags(); } p._insertElement(token, NS.HTML); } function rtStartTagInBody(p, token) { if (p.openElements.hasInScope($.RUBY)) { p.openElements.generateImpliedEndTagsWithExclusion($.RTC); } p._insertElement(token, NS.HTML); } function menuStartTagInBody(p, token) { if (p.openElements.hasInButtonScope($.P)) { p._closePElement(); } p._insertElement(token, NS.HTML); } function mathStartTagInBody(p, token) { p._reconstructActiveFormattingElements(); foreignContent.adjustTokenMathMLAttrs(token); foreignContent.adjustTokenXMLAttrs(token); if (token.selfClosing) { p._appendElement(token, NS.MATHML); } else { p._insertElement(token, NS.MATHML); } token.ackSelfClosing = true; } function svgStartTagInBody(p, token) { p._reconstructActiveFormattingElements(); foreignContent.adjustTokenSVGAttrs(token); foreignContent.adjustTokenXMLAttrs(token); if (token.selfClosing) { p._appendElement(token, NS.SVG); } else { p._insertElement(token, NS.SVG); } token.ackSelfClosing = true; } function genericStartTagInBody(p, token) { p._reconstructActiveFormattingElements(); p._insertElement(token, NS.HTML); } //OPTIMIZATION: Integer comparisons are low-cost, so we can use very fast tag name length filters here. //It's faster than using dictionary. function startTagInBody(p, token) { const tn = token.tagName; switch (tn.length) { case 1: if (tn === $.I || tn === $.S || tn === $.B || tn === $.U) { bStartTagInBody(p, token); } else if (tn === $.P) { addressStartTagInBody(p, token); } else if (tn === $.A) { aStartTagInBody(p, token); } else { genericStartTagInBody(p, token); } break; case 2: if (tn === $.DL || tn === $.OL || tn === $.UL) { addressStartTagInBody(p, token); } else if (tn === $.H1 || tn === $.H2 || tn === $.H3 || tn === $.H4 || tn === $.H5 || tn === $.H6) { numberedHeaderStartTagInBody(p, token); } else if (tn === $.LI || tn === $.DD || tn === $.DT) { listItemStartTagInBody(p, token); } else if (tn === $.EM || tn === $.TT) { bStartTagInBody(p, token); } else if (tn === $.BR) { areaStartTagInBody(p, token); } else if (tn === $.HR) { hrStartTagInBody(p, token); } else if (tn === $.RB) { rbStartTagInBody(p, token); } else if (tn === $.RT || tn === $.RP) { rtStartTagInBody(p, token); } else if (tn !== $.TH && tn !== $.TD && tn !== $.TR) { genericStartTagInBody(p, token); } break; case 3: if (tn === $.DIV || tn === $.DIR || tn === $.NAV) { addressStartTagInBody(p, token); } else if (tn === $.PRE) { preStartTagInBody(p, token); } else if (tn === $.BIG) { bStartTagInBody(p, token); } else if (tn === $.IMG || tn === $.WBR) { areaStartTagInBody(p, token); } else if (tn === $.XMP) { xmpStartTagInBody(p, token); } else if (tn === $.SVG) { svgStartTagInBody(p, token); } else if (tn === $.RTC) { rbStartTagInBody(p, token); } else if (tn !== $.COL) { genericStartTagInBody(p, token); } break; case 4: if (tn === $.HTML) { htmlStartTagInBody(p, token); } else if (tn === $.BASE || tn === $.LINK || tn === $.META) { startTagInHead(p, token); } else if (tn === $.BODY) { bodyStartTagInBody(p, token); } else if (tn === $.MAIN || tn === $.MENU) { addressStartTagInBody(p, token); } else if (tn === $.FORM) { formStartTagInBody(p, token); } else if (tn === $.CODE || tn === $.FONT) { bStartTagInBody(p, token); } else if (tn === $.NOBR) { nobrStartTagInBody(p, token); } else if (tn === $.AREA) { areaStartTagInBody(p, token); } else if (tn === $.MATH) { mathStartTagInBody(p, token); } else if (tn === $.MENU) { menuStartTagInBody(p, token); } else if (tn !== $.HEAD) { genericStartTagInBody(p, token); } break; case 5: if (tn === $.STYLE || tn === $.TITLE) { startTagInHead(p, token); } else if (tn === $.ASIDE) { addressStartTagInBody(p, token); } else if (tn === $.SMALL) { bStartTagInBody(p, token); } else if (tn === $.TABLE) { tableStartTagInBody(p, token); } else if (tn === $.EMBED) { areaStartTagInBody(p, token); } else if (tn === $.INPUT) { inputStartTagInBody(p, token); } else if (tn === $.PARAM || tn === $.TRACK) { paramStartTagInBody(p, token); } else if (tn === $.IMAGE) { imageStartTagInBody(p, token); } else if (tn !== $.FRAME && tn !== $.TBODY && tn !== $.TFOOT && tn !== $.THEAD) { genericStartTagInBody(p, token); } break; case 6: if (tn === $.SCRIPT) { startTagInHead(p, token); } else if ( tn === $.CENTER || tn === $.FIGURE || tn === $.FOOTER || tn === $.HEADER || tn === $.HGROUP || tn === $.DIALOG ) { addressStartTagInBody(p, token); } else if (tn === $.BUTTON) { buttonStartTagInBody(p, token); } else if (tn === $.STRIKE || tn === $.STRONG) { bStartTagInBody(p, token); } else if (tn === $.APPLET || tn === $.OBJECT) { appletStartTagInBody(p, token); } else if (tn === $.KEYGEN) { areaStartTagInBody(p, token); } else if (tn === $.SOURCE) { paramStartTagInBody(p, token); } else if (tn === $.IFRAME) { iframeStartTagInBody(p, token); } else if (tn === $.SELECT) { selectStartTagInBody(p, token); } else if (tn === $.OPTION) { optgroupStartTagInBody(p, token); } else { genericStartTagInBody(p, token); } break; case 7: if (tn === $.BGSOUND) { startTagInHead(p, token); } else if ( tn === $.DETAILS || tn === $.ADDRESS || tn === $.ARTICLE || tn === $.SECTION || tn === $.SUMMARY ) { addressStartTagInBody(p, token); } else if (tn === $.LISTING) { preStartTagInBody(p, token); } else if (tn === $.MARQUEE) { appletStartTagInBody(p, token); } else if (tn === $.NOEMBED) { noembedStartTagInBody(p, token); } else if (tn !== $.CAPTION) { genericStartTagInBody(p, token); } break; case 8: if (tn === $.BASEFONT) { startTagInHead(p, token); } else if (tn === $.FRAMESET) { framesetStartTagInBody(p, token); } else if (tn === $.FIELDSET) { addressStartTagInBody(p, token); } else if (tn === $.TEXTAREA) { textareaStartTagInBody(p, token); } else if (tn === $.TEMPLATE) { startTagInHead(p, token); } else if (tn === $.NOSCRIPT) { if (p.options.scriptingEnabled) { noembedStartTagInBody(p, token); } else { genericStartTagInBody(p, token); } } else if (tn === $.OPTGROUP) { optgroupStartTagInBody(p, token); } else if (tn !== $.COLGROUP) { genericStartTagInBody(p, token); } break; case 9: if (tn === $.PLAINTEXT) { plaintextStartTagInBody(p, token); } else { genericStartTagInBody(p, token); } break; case 10: if (tn === $.BLOCKQUOTE || tn === $.FIGCAPTION) { addressStartTagInBody(p, token); } else { genericStartTagInBody(p, token); } break; default: genericStartTagInBody(p, token); } } function bodyEndTagInBody(p) { if (p.openElements.hasInScope($.BODY)) { p.insertionMode = AFTER_BODY_MODE; } } function htmlEndTagInBody(p, token) { if (p.openElements.hasInScope($.BODY)) { p.insertionMode = AFTER_BODY_MODE; p._processToken(token); } } function addressEndTagInBody(p, token) { const tn = token.tagName; if (p.openElements.hasInScope(tn)) { p.openElements.generateImpliedEndTags(); p.openElements.popUntilTagNamePopped(tn); } } function formEndTagInBody(p) { const inTemplate = p.openElements.tmplCount > 0; const formElement = p.formElement; if (!inTemplate) { p.formElement = null; } if ((formElement || inTemplate) && p.openElements.hasInScope($.FORM)) { p.openElements.generateImpliedEndTags(); if (inTemplate) { p.openElements.popUntilTagNamePopped($.FORM); } else { p.openElements.remove(formElement); } } } function pEndTagInBody(p) { if (!p.openElements.hasInButtonScope($.P)) { p._insertFakeElement($.P); } p._closePElement(); } function liEndTagInBody(p) { if (p.openElements.hasInListItemScope($.LI)) { p.openElements.generateImpliedEndTagsWithExclusion($.LI); p.openElements.popUntilTagNamePopped($.LI); } } function ddEndTagInBody(p, token) { const tn = token.tagName; if (p.openElements.hasInScope(tn)) { p.openElements.generateImpliedEndTagsWithExclusion(tn); p.openElements.popUntilTagNamePopped(tn); } } function numberedHeaderEndTagInBody(p) { if (p.openElements.hasNumberedHeaderInScope()) { p.openElements.generateImpliedEndTags(); p.openElements.popUntilNumberedHeaderPopped(); } } function appletEndTagInBody(p, token) { const tn = token.tagName; if (p.openElements.hasInScope(tn)) { p.openElements.generateImpliedEndTags(); p.openElements.popUntilTagNamePopped(tn); p.activeFormattingElements.clearToLastMarker(); } } function brEndTagInBody(p) { p._reconstructActiveFormattingElements(); p._insertFakeElement($.BR); p.openElements.pop(); p.framesetOk = false; } function genericEndTagInBody(p, token) { const tn = token.tagName; for (let i = p.openElements.stackTop; i > 0; i--) { const element = p.openElements.items[i]; if (p.treeAdapter.getTagName(element) === tn) { p.openElements.generateImpliedEndTagsWithExclusion(tn); p.openElements.popUntilElementPopped(element); break; } if (p._isSpecialElement(element)) { break; } } } //OPTIMIZATION: Integer comparisons are low-cost, so we can use very fast tag name length filters here. //It's faster than using dictionary. function endTagInBody(p, token) { const tn = token.tagName; switch (tn.length) { case 1: if (tn === $.A || tn === $.B || tn === $.I || tn === $.S || tn === $.U) { callAdoptionAgency(p, token); } else if (tn === $.P) { pEndTagInBody(p, token); } else { genericEndTagInBody(p, token); } break; case 2: if (tn === $.DL || tn === $.UL || tn === $.OL) { addressEndTagInBody(p, token); } else if (tn === $.LI) { liEndTagInBody(p, token); } else if (tn === $.DD || tn === $.DT) { ddEndTagInBody(p, token); } else if (tn === $.H1 || tn === $.H2 || tn === $.H3 || tn === $.H4 || tn === $.H5 || tn === $.H6) { numberedHeaderEndTagInBody(p, token); } else if (tn === $.BR) { brEndTagInBody(p, token); } else if (tn === $.EM || tn === $.TT) { callAdoptionAgency(p, token); } else { genericEndTagInBody(p, token); } break; case 3: if (tn === $.BIG) { callAdoptionAgency(p, token); } else if (tn === $.DIR || tn === $.DIV || tn === $.NAV || tn === $.PRE) { addressEndTagInBody(p, token); } else { genericEndTagInBody(p, token); } break; case 4: if (tn === $.BODY) { bodyEndTagInBody(p, token); } else if (tn === $.HTML) { htmlEndTagInBody(p, token); } else if (tn === $.FORM) { formEndTagInBody(p, token); } else if (tn === $.CODE || tn === $.FONT || tn === $.NOBR) { callAdoptionAgency(p, token); } else if (tn === $.MAIN || tn === $.MENU) { addressEndTagInBody(p, token); } else { genericEndTagInBody(p, token); } break; case 5: if (tn === $.ASIDE) { addressEndTagInBody(p, token); } else if (tn === $.SMALL) { callAdoptionAgency(p, token); } else { genericEndTagInBody(p, token); } break; case 6: if ( tn === $.CENTER || tn === $.FIGURE || tn === $.FOOTER || tn === $.HEADER || tn === $.HGROUP || tn === $.DIALOG ) { addressEndTagInBody(p, token); } else if (tn === $.APPLET || tn === $.OBJECT) { appletEndTagInBody(p, token); } else if (tn === $.STRIKE || tn === $.STRONG) { callAdoptionAgency(p, token); } else { genericEndTagInBody(p, token); } break; case 7: if ( tn === $.ADDRESS || tn === $.ARTICLE || tn === $.DETAILS || tn === $.SECTION || tn === $.SUMMARY || tn === $.LISTING ) { addressEndTagInBody(p, token); } else if (tn === $.MARQUEE) { appletEndTagInBody(p, token); } else { genericEndTagInBody(p, token); } break; case 8: if (tn === $.FIELDSET) { addressEndTagInBody(p, token); } else if (tn === $.TEMPLATE) { endTagInHead(p, token); } else { genericEndTagInBody(p, token); } break; case 10: if (tn === $.BLOCKQUOTE || tn === $.FIGCAPTION) { addressEndTagInBody(p, token); } else { genericEndTagInBody(p, token); } break; default: genericEndTagInBody(p, token); } } function eofInBody(p, token) { if (p.tmplInsertionModeStackTop > -1) { eofInTemplate(p, token); } else { p.stopped = true; } } // The "text" insertion mode //------------------------------------------------------------------ function endTagInText(p, token) { if (token.tagName === $.SCRIPT) { p.pendingScript = p.openElements.current; } p.openElements.pop(); p.insertionMode = p.originalInsertionMode; } function eofInText(p, token) { p._err(ERR.eofInElementThatCanContainOnlyText); p.openElements.pop(); p.insertionMode = p.originalInsertionMode; p._processToken(token); } // The "in table" insertion mode //------------------------------------------------------------------ function characterInTable(p, token) { const curTn = p.openElements.currentTagName; if (curTn === $.TABLE || curTn === $.TBODY || curTn === $.TFOOT || curTn === $.THEAD || curTn === $.TR) { p.pendingCharacterTokens = []; p.hasNonWhitespacePendingCharacterToken = false; p.originalInsertionMode = p.insertionMode; p.insertionMode = IN_TABLE_TEXT_MODE; p._processToken(token); } else { tokenInTable(p, token); } } function captionStartTagInTable(p, token) { p.openElements.clearBackToTableContext(); p.activeFormattingElements.insertMarker(); p._insertElement(token, NS.HTML); p.insertionMode = IN_CAPTION_MODE; } function colgroupStartTagInTable(p, token) { p.openElements.clearBackToTableContext(); p._insertElement(token, NS.HTML); p.insertionMode = IN_COLUMN_GROUP_MODE; } function colStartTagInTable(p, token) { p.openElements.clearBackToTableContext(); p._insertFakeElement($.COLGROUP); p.insertionMode = IN_COLUMN_GROUP_MODE; p._processToken(token); } function tbodyStartTagInTable(p, token) { p.openElements.clearBackToTableContext(); p._insertElement(token, NS.HTML); p.insertionMode = IN_TABLE_BODY_MODE; } function tdStartTagInTable(p, token) { p.openElements.clearBackToTableContext(); p._insertFakeElement($.TBODY); p.insertionMode = IN_TABLE_BODY_MODE; p._processToken(token); } function tableStartTagInTable(p, token) { if (p.openElements.hasInTableScope($.TABLE)) { p.openElements.popUntilTagNamePopped($.TABLE); p._resetInsertionMode(); p._processToken(token); } } function inputStartTagInTable(p, token) { const inputType = Tokenizer.getTokenAttr(token, ATTRS.TYPE); if (inputType && inputType.toLowerCase() === HIDDEN_INPUT_TYPE) { p._appendElement(token, NS.HTML); } else { tokenInTable(p, token); } token.ackSelfClosing = true; } function formStartTagInTable(p, token) { if (!p.formElement && p.openElements.tmplCount === 0) { p._insertElement(token, NS.HTML); p.formElement = p.openElements.current; p.openElements.pop(); } } function startTagInTable(p, token) { const tn = token.tagName; switch (tn.length) { case 2: if (tn === $.TD || tn === $.TH || tn === $.TR) { tdStartTagInTable(p, token); } else { tokenInTable(p, token); } break; case 3: if (tn === $.COL) { colStartTagInTable(p, token); } else { tokenInTable(p, token); } break; case 4: if (tn === $.FORM) { formStartTagInTable(p, token); } else { tokenInTable(p, token); } break; case 5: if (tn === $.TABLE) { tableStartTagInTable(p, token); } else if (tn === $.STYLE) { startTagInHead(p, token); } else if (tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD) { tbodyStartTagInTable(p, token); } else if (tn === $.INPUT) { inputStartTagInTable(p, token); } else { tokenInTable(p, token); } break; case 6: if (tn === $.SCRIPT) { startTagInHead(p, token); } else { tokenInTable(p, token); } break; case 7: if (tn === $.CAPTION) { captionStartTagInTable(p, token); } else { tokenInTable(p, token); } break; case 8: if (tn === $.COLGROUP) { colgroupStartTagInTable(p, token); } else if (tn === $.TEMPLATE) { startTagInHead(p, token); } else { tokenInTable(p, token); } break; default: tokenInTable(p, token); } } function endTagInTable(p, token) { const tn = token.tagName; if (tn === $.TABLE) { if (p.openElements.hasInTableScope($.TABLE)) { p.openElements.popUntilTagNamePopped($.TABLE); p._resetInsertionMode(); } } else if (tn === $.TEMPLATE) { endTagInHead(p, token); } else if ( tn !== $.BODY && tn !== $.CAPTION && tn !== $.COL && tn !== $.COLGROUP && tn !== $.HTML && tn !== $.TBODY && tn !== $.TD && tn !== $.TFOOT && tn !== $.TH && tn !== $.THEAD && tn !== $.TR ) { tokenInTable(p, token); } } function tokenInTable(p, token) { const savedFosterParentingState = p.fosterParentingEnabled; p.fosterParentingEnabled = true; p._processTokenInBodyMode(token); p.fosterParentingEnabled = savedFosterParentingState; } // The "in table text" insertion mode //------------------------------------------------------------------ function whitespaceCharacterInTableText(p, token) { p.pendingCharacterTokens.push(token); } function characterInTableText(p, token) { p.pendingCharacterTokens.push(token); p.hasNonWhitespacePendingCharacterToken = true; } function tokenInTableText(p, token) { let i = 0; if (p.hasNonWhitespacePendingCharacterToken) { for (; i < p.pendingCharacterTokens.length; i++) { tokenInTable(p, p.pendingCharacterTokens[i]); } } else { for (; i < p.pendingCharacterTokens.length; i++) { p._insertCharacters(p.pendingCharacterTokens[i]); } } p.insertionMode = p.originalInsertionMode; p._processToken(token); } // The "in caption" insertion mode //------------------------------------------------------------------ function startTagInCaption(p, token) { const tn = token.tagName; if ( tn === $.CAPTION || tn === $.COL || tn === $.COLGROUP || tn === $.TBODY || tn === $.TD || tn === $.TFOOT || tn === $.TH || tn === $.THEAD || tn === $.TR ) { if (p.openElements.hasInTableScope($.CAPTION)) { p.openElements.generateImpliedEndTags(); p.openElements.popUntilTagNamePopped($.CAPTION); p.activeFormattingElements.clearToLastMarker(); p.insertionMode = IN_TABLE_MODE; p._processToken(token); } } else { startTagInBody(p, token); } } function endTagInCaption(p, token) { const tn = token.tagName; if (tn === $.CAPTION || tn === $.TABLE) { if (p.openElements.hasInTableScope($.CAPTION)) { p.openElements.generateImpliedEndTags(); p.openElements.popUntilTagNamePopped($.CAPTION); p.activeFormattingElements.clearToLastMarker(); p.insertionMode = IN_TABLE_MODE; if (tn === $.TABLE) { p._processToken(token); } } } else if ( tn !== $.BODY && tn !== $.COL && tn !== $.COLGROUP && tn !== $.HTML && tn !== $.TBODY && tn !== $.TD && tn !== $.TFOOT && tn !== $.TH && tn !== $.THEAD && tn !== $.TR ) { endTagInBody(p, token); } } // The "in column group" insertion mode //------------------------------------------------------------------ function startTagInColumnGroup(p, token) { const tn = token.tagName; if (tn === $.HTML) { startTagInBody(p, token); } else if (tn === $.COL) { p._appendElement(token, NS.HTML); token.ackSelfClosing = true; } else if (tn === $.TEMPLATE) { startTagInHead(p, token); } else { tokenInColumnGroup(p, token); } } function endTagInColumnGroup(p, token) { const tn = token.tagName; if (tn === $.COLGROUP) { if (p.openElements.currentTagName === $.COLGROUP) { p.openElements.pop(); p.insertionMode = IN_TABLE_MODE; } } else if (tn === $.TEMPLATE) { endTagInHead(p, token); } else if (tn !== $.COL) { tokenInColumnGroup(p, token); } } function tokenInColumnGroup(p, token) { if (p.openElements.currentTagName === $.COLGROUP) { p.openElements.pop(); p.insertionMode = IN_TABLE_MODE; p._processToken(token); } } // The "in table body" insertion mode //------------------------------------------------------------------ function startTagInTableBody(p, token) { const tn = token.tagName; if (tn === $.TR) { p.openElements.clearBackToTableBodyContext(); p._insertElement(token, NS.HTML); p.insertionMode = IN_ROW_MODE; } else if (tn === $.TH || tn === $.TD) { p.openElements.clearBackToTableBodyContext(); p._insertFakeElement($.TR); p.insertionMode = IN_ROW_MODE; p._processToken(token); } else if ( tn === $.CAPTION || tn === $.COL || tn === $.COLGROUP || tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD ) { if (p.openElements.hasTableBodyContextInTableScope()) { p.openElements.clearBackToTableBodyContext(); p.openElements.pop(); p.insertionMode = IN_TABLE_MODE; p._processToken(token); } } else { startTagInTable(p, token); } } function endTagInTableBody(p, token) { const tn = token.tagName; if (tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD) { if (p.openElements.hasInTableScope(tn)) { p.openElements.clearBackToTableBodyContext(); p.openElements.pop(); p.insertionMode = IN_TABLE_MODE; } } else if (tn === $.TABLE) { if (p.openElements.hasTableBodyContextInTableScope()) { p.openElements.clearBackToTableBodyContext(); p.openElements.pop(); p.insertionMode = IN_TABLE_MODE; p._processToken(token); } } else if ( (tn !== $.BODY && tn !== $.CAPTION && tn !== $.COL && tn !== $.COLGROUP) || (tn !== $.HTML && tn !== $.TD && tn !== $.TH && tn !== $.TR) ) { endTagInTable(p, token); } } // The "in row" insertion mode //------------------------------------------------------------------ function startTagInRow(p, token) { const tn = token.tagName; if (tn === $.TH || tn === $.TD) { p.openElements.clearBackToTableRowContext(); p._insertElement(token, NS.HTML); p.insertionMode = IN_CELL_MODE; p.activeFormattingElements.insertMarker(); } else if ( tn === $.CAPTION || tn === $.COL || tn === $.COLGROUP || tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD || tn === $.TR ) { if (p.openElements.hasInTableScope($.TR)) { p.openElements.clearBackToTableRowContext(); p.openElements.pop(); p.insertionMode = IN_TABLE_BODY_MODE; p._processToken(token); } } else { startTagInTable(p, token); } } function endTagInRow(p, token) { const tn = token.tagName; if (tn === $.TR) { if (p.openElements.hasInTableScope($.TR)) { p.openElements.clearBackToTableRowContext(); p.openElements.pop(); p.insertionMode = IN_TABLE_BODY_MODE; } } else if (tn === $.TABLE) { if (p.openElements.hasInTableScope($.TR)) { p.openElements.clearBackToTableRowContext(); p.openElements.pop(); p.insertionMode = IN_TABLE_BODY_MODE; p._processToken(token); } } else if (tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD) { if (p.openElements.hasInTableScope(tn) || p.openElements.hasInTableScope($.TR)) { p.openElements.clearBackToTableRowContext(); p.openElements.pop(); p.insertionMode = IN_TABLE_BODY_MODE; p._processToken(token); } } else if ( (tn !== $.BODY && tn !== $.CAPTION && tn !== $.COL && tn !== $.COLGROUP) || (tn !== $.HTML && tn !== $.TD && tn !== $.TH) ) { endTagInTable(p, token); } } // The "in cell" insertion mode //------------------------------------------------------------------ function startTagInCell(p, token) { const tn = token.tagName; if ( tn === $.CAPTION || tn === $.COL || tn === $.COLGROUP || tn === $.TBODY || tn === $.TD || tn === $.TFOOT || tn === $.TH || tn === $.THEAD || tn === $.TR ) { if (p.openElements.hasInTableScope($.TD) || p.openElements.hasInTableScope($.TH)) { p._closeTableCell(); p._processToken(token); } } else { startTagInBody(p, token); } } function endTagInCell(p, token) { const tn = token.tagName; if (tn === $.TD || tn === $.TH) { if (p.openElements.hasInTableScope(tn)) { p.openElements.generateImpliedEndTags(); p.openElements.popUntilTagNamePopped(tn); p.activeFormattingElements.clearToLastMarker(); p.insertionMode = IN_ROW_MODE; } } else if (tn === $.TABLE || tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD || tn === $.TR) { if (p.openElements.hasInTableScope(tn)) { p._closeTableCell(); p._processToken(token); } } else if (tn !== $.BODY && tn !== $.CAPTION && tn !== $.COL && tn !== $.COLGROUP && tn !== $.HTML) { endTagInBody(p, token); } } // The "in select" insertion mode //------------------------------------------------------------------ function startTagInSelect(p, token) { const tn = token.tagName; if (tn === $.HTML) { startTagInBody(p, token); } else if (tn === $.OPTION) { if (p.openElements.currentTagName === $.OPTION) { p.openElements.pop(); } p._insertElement(token, NS.HTML); } else if (tn === $.OPTGROUP) { if (p.openElements.currentTagName === $.OPTION) { p.openElements.pop(); } if (p.openElements.currentTagName === $.OPTGROUP) { p.openElements.pop(); } p._insertElement(token, NS.HTML); } else if (tn === $.INPUT || tn === $.KEYGEN || tn === $.TEXTAREA || tn === $.SELECT) { if (p.openElements.hasInSelectScope($.SELECT)) { p.openElements.popUntilTagNamePopped($.SELECT); p._resetInsertionMode(); if (tn !== $.SELECT) { p._processToken(token); } } } else if (tn === $.SCRIPT || tn === $.TEMPLATE) { startTagInHead(p, token); } } function endTagInSelect(p, token) { const tn = token.tagName; if (tn === $.OPTGROUP) { const prevOpenElement = p.openElements.items[p.openElements.stackTop - 1]; const prevOpenElementTn = prevOpenElement && p.treeAdapter.getTagName(prevOpenElement); if (p.openElements.currentTagName === $.OPTION && prevOpenElementTn === $.OPTGROUP) { p.openElements.pop(); } if (p.openElements.currentTagName === $.OPTGROUP) { p.openElements.pop(); } } else if (tn === $.OPTION) { if (p.openElements.currentTagName === $.OPTION) { p.openElements.pop(); } } else if (tn === $.SELECT && p.openElements.hasInSelectScope($.SELECT)) { p.openElements.popUntilTagNamePopped($.SELECT); p._resetInsertionMode(); } else if (tn === $.TEMPLATE) { endTagInHead(p, token); } } //12.2.5.4.17 The "in select in table" insertion mode //------------------------------------------------------------------ function startTagInSelectInTable(p, token) { const tn = token.tagName; if ( tn === $.CAPTION || tn === $.TABLE || tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD || tn === $.TR || tn === $.TD || tn === $.TH ) { p.openElements.popUntilTagNamePopped($.SELECT); p._resetInsertionMode(); p._processToken(token); } else { startTagInSelect(p, token); } } function endTagInSelectInTable(p, token) { const tn = token.tagName; if ( tn === $.CAPTION || tn === $.TABLE || tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD || tn === $.TR || tn === $.TD || tn === $.TH ) { if (p.openElements.hasInTableScope(tn)) { p.openElements.popUntilTagNamePopped($.SELECT); p._resetInsertionMode(); p._processToken(token); } } else { endTagInSelect(p, token); } } // The "in template" insertion mode //------------------------------------------------------------------ function startTagInTemplate(p, token) { const tn = token.tagName; if ( tn === $.BASE || tn === $.BASEFONT || tn === $.BGSOUND || tn === $.LINK || tn === $.META || tn === $.NOFRAMES || tn === $.SCRIPT || tn === $.STYLE || tn === $.TEMPLATE || tn === $.TITLE ) { startTagInHead(p, token); } else { const newInsertionMode = TEMPLATE_INSERTION_MODE_SWITCH_MAP[tn] || IN_BODY_MODE; p._popTmplInsertionMode(); p._pushTmplInsertionMode(newInsertionMode); p.insertionMode = newInsertionMode; p._processToken(token); } } function endTagInTemplate(p, token) { if (token.tagName === $.TEMPLATE) { endTagInHead(p, token); } } function eofInTemplate(p, token) { if (p.openElements.tmplCount > 0) { p.openElements.popUntilTagNamePopped($.TEMPLATE); p.activeFormattingElements.clearToLastMarker(); p._popTmplInsertionMode(); p._resetInsertionMode(); p._processToken(token); } else { p.stopped = true; } } // The "after body" insertion mode //------------------------------------------------------------------ function startTagAfterBody(p, token) { if (token.tagName === $.HTML) { startTagInBody(p, token); } else { tokenAfterBody(p, token); } } function endTagAfterBody(p, token) { if (token.tagName === $.HTML) { if (!p.fragmentContext) { p.insertionMode = AFTER_AFTER_BODY_MODE; } } else { tokenAfterBody(p, token); } } function tokenAfterBody(p, token) { p.insertionMode = IN_BODY_MODE; p._processToken(token); } // The "in frameset" insertion mode //------------------------------------------------------------------ function startTagInFrameset(p, token) { const tn = token.tagName; if (tn === $.HTML) { startTagInBody(p, token); } else if (tn === $.FRAMESET) { p._insertElement(token, NS.HTML); } else if (tn === $.FRAME) { p._appendElement(token, NS.HTML); token.ackSelfClosing = true; } else if (tn === $.NOFRAMES) { startTagInHead(p, token); } } function endTagInFrameset(p, token) { if (token.tagName === $.FRAMESET && !p.openElements.isRootHtmlElementCurrent()) { p.openElements.pop(); if (!p.fragmentContext && p.openElements.currentTagName !== $.FRAMESET) { p.insertionMode = AFTER_FRAMESET_MODE; } } } // The "after frameset" insertion mode //------------------------------------------------------------------ function startTagAfterFrameset(p, token) { const tn = token.tagName; if (tn === $.HTML) { startTagInBody(p, token); } else if (tn === $.NOFRAMES) { startTagInHead(p, token); } } function endTagAfterFrameset(p, token) { if (token.tagName === $.HTML) { p.insertionMode = AFTER_AFTER_FRAMESET_MODE; } } // The "after after body" insertion mode //------------------------------------------------------------------ function startTagAfterAfterBody(p, token) { if (token.tagName === $.HTML) { startTagInBody(p, token); } else { tokenAfterAfterBody(p, token); } } function tokenAfterAfterBody(p, token) { p.insertionMode = IN_BODY_MODE; p._processToken(token); } // The "after after frameset" insertion mode //------------------------------------------------------------------ function startTagAfterAfterFrameset(p, token) { const tn = token.tagName; if (tn === $.HTML) { startTagInBody(p, token); } else if (tn === $.NOFRAMES) { startTagInHead(p, token); } } // The rules for parsing tokens in foreign content //------------------------------------------------------------------ function nullCharacterInForeignContent(p, token) { token.chars = unicode.REPLACEMENT_CHARACTER; p._insertCharacters(token); } function characterInForeignContent(p, token) { p._insertCharacters(token); p.framesetOk = false; } function startTagInForeignContent(p, token) { if (foreignContent.causesExit(token) && !p.fragmentContext) { while ( p.treeAdapter.getNamespaceURI(p.openElements.current) !== NS.HTML && !p._isIntegrationPoint(p.openElements.current) ) { p.openElements.pop(); } p._processToken(token); } else { const current = p._getAdjustedCurrentElement(); const currentNs = p.treeAdapter.getNamespaceURI(current); if (currentNs === NS.MATHML) { foreignContent.adjustTokenMathMLAttrs(token); } else if (currentNs === NS.SVG) { foreignContent.adjustTokenSVGTagName(token); foreignContent.adjustTokenSVGAttrs(token); } foreignContent.adjustTokenXMLAttrs(token); if (token.selfClosing) { p._appendElement(token, currentNs); } else { p._insertElement(token, currentNs); } token.ackSelfClosing = true; } } function endTagInForeignContent(p, token) { for (let i = p.openElements.stackTop; i > 0; i--) { const element = p.openElements.items[i]; if (p.treeAdapter.getNamespaceURI(element) === NS.HTML) { p._processToken(token); break; } if (p.treeAdapter.getTagName(element).toLowerCase() === token.tagName) { p.openElements.popUntilElementPopped(element); break; } } }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/parse5/lib/parser/index.js
index.js
'use strict'; //Const const NOAH_ARK_CAPACITY = 3; //List of formatting elements class FormattingElementList { constructor(treeAdapter) { this.length = 0; this.entries = []; this.treeAdapter = treeAdapter; this.bookmark = null; } //Noah Ark's condition //OPTIMIZATION: at first we try to find possible candidates for exclusion using //lightweight heuristics without thorough attributes check. _getNoahArkConditionCandidates(newElement) { const candidates = []; if (this.length >= NOAH_ARK_CAPACITY) { const neAttrsLength = this.treeAdapter.getAttrList(newElement).length; const neTagName = this.treeAdapter.getTagName(newElement); const neNamespaceURI = this.treeAdapter.getNamespaceURI(newElement); for (let i = this.length - 1; i >= 0; i--) { const entry = this.entries[i]; if (entry.type === FormattingElementList.MARKER_ENTRY) { break; } const element = entry.element; const elementAttrs = this.treeAdapter.getAttrList(element); const isCandidate = this.treeAdapter.getTagName(element) === neTagName && this.treeAdapter.getNamespaceURI(element) === neNamespaceURI && elementAttrs.length === neAttrsLength; if (isCandidate) { candidates.push({ idx: i, attrs: elementAttrs }); } } } return candidates.length < NOAH_ARK_CAPACITY ? [] : candidates; } _ensureNoahArkCondition(newElement) { const candidates = this._getNoahArkConditionCandidates(newElement); let cLength = candidates.length; if (cLength) { const neAttrs = this.treeAdapter.getAttrList(newElement); const neAttrsLength = neAttrs.length; const neAttrsMap = Object.create(null); //NOTE: build attrs map for the new element so we can perform fast lookups for (let i = 0; i < neAttrsLength; i++) { const neAttr = neAttrs[i]; neAttrsMap[neAttr.name] = neAttr.value; } for (let i = 0; i < neAttrsLength; i++) { for (let j = 0; j < cLength; j++) { const cAttr = candidates[j].attrs[i]; if (neAttrsMap[cAttr.name] !== cAttr.value) { candidates.splice(j, 1); cLength--; } if (candidates.length < NOAH_ARK_CAPACITY) { return; } } } //NOTE: remove bottommost candidates until Noah's Ark condition will not be met for (let i = cLength - 1; i >= NOAH_ARK_CAPACITY - 1; i--) { this.entries.splice(candidates[i].idx, 1); this.length--; } } } //Mutations insertMarker() { this.entries.push({ type: FormattingElementList.MARKER_ENTRY }); this.length++; } pushElement(element, token) { this._ensureNoahArkCondition(element); this.entries.push({ type: FormattingElementList.ELEMENT_ENTRY, element: element, token: token }); this.length++; } insertElementAfterBookmark(element, token) { let bookmarkIdx = this.length - 1; for (; bookmarkIdx >= 0; bookmarkIdx--) { if (this.entries[bookmarkIdx] === this.bookmark) { break; } } this.entries.splice(bookmarkIdx + 1, 0, { type: FormattingElementList.ELEMENT_ENTRY, element: element, token: token }); this.length++; } removeEntry(entry) { for (let i = this.length - 1; i >= 0; i--) { if (this.entries[i] === entry) { this.entries.splice(i, 1); this.length--; break; } } } clearToLastMarker() { while (this.length) { const entry = this.entries.pop(); this.length--; if (entry.type === FormattingElementList.MARKER_ENTRY) { break; } } } //Search getElementEntryInScopeWithTagName(tagName) { for (let i = this.length - 1; i >= 0; i--) { const entry = this.entries[i]; if (entry.type === FormattingElementList.MARKER_ENTRY) { return null; } if (this.treeAdapter.getTagName(entry.element) === tagName) { return entry; } } return null; } getElementEntry(element) { for (let i = this.length - 1; i >= 0; i--) { const entry = this.entries[i]; if (entry.type === FormattingElementList.ELEMENT_ENTRY && entry.element === element) { return entry; } } return null; } } //Entry types FormattingElementList.MARKER_ENTRY = 'MARKER_ENTRY'; FormattingElementList.ELEMENT_ENTRY = 'ELEMENT_ENTRY'; module.exports = FormattingElementList;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/parse5/lib/parser/formatting-element-list.js
formatting-element-list.js
'use strict'; const { DOCUMENT_MODE } = require('parse5/lib/common/html'); //Node construction exports.createDocument = function() { return { nodeName: '#document', mode: DOCUMENT_MODE.NO_QUIRKS, childNodes: [] }; }; exports.createDocumentFragment = function() { return { nodeName: '#document-fragment', childNodes: [] }; }; exports.createElement = function(tagName, namespaceURI, attrs) { return { nodeName: tagName, tagName: tagName, attrs: attrs, namespaceURI: namespaceURI, childNodes: [], parentNode: null }; }; exports.createCommentNode = function(data) { return { nodeName: '#comment', data: data, parentNode: null }; }; const createTextNode = function(value) { return { nodeName: '#text', value: value, parentNode: null }; }; //Tree mutation const appendChild = (exports.appendChild = function(parentNode, newNode) { parentNode.childNodes.push(newNode); newNode.parentNode = parentNode; }); const insertBefore = (exports.insertBefore = function(parentNode, newNode, referenceNode) { const insertionIdx = parentNode.childNodes.indexOf(referenceNode); parentNode.childNodes.splice(insertionIdx, 0, newNode); newNode.parentNode = parentNode; }); exports.setTemplateContent = function(templateElement, contentElement) { templateElement.content = contentElement; }; exports.getTemplateContent = function(templateElement) { return templateElement.content; }; exports.setDocumentType = function(document, name, publicId, systemId) { let doctypeNode = null; for (let i = 0; i < document.childNodes.length; i++) { if (document.childNodes[i].nodeName === '#documentType') { doctypeNode = document.childNodes[i]; break; } } if (doctypeNode) { doctypeNode.name = name; doctypeNode.publicId = publicId; doctypeNode.systemId = systemId; } else { appendChild(document, { nodeName: '#documentType', name: name, publicId: publicId, systemId: systemId }); } }; exports.setDocumentMode = function(document, mode) { document.mode = mode; }; exports.getDocumentMode = function(document) { return document.mode; }; exports.detachNode = function(node) { if (node.parentNode) { const idx = node.parentNode.childNodes.indexOf(node); node.parentNode.childNodes.splice(idx, 1); node.parentNode = null; } }; exports.insertText = function(parentNode, text) { if (parentNode.childNodes.length) { const prevNode = parentNode.childNodes[parentNode.childNodes.length - 1]; if (prevNode.nodeName === '#text') { prevNode.value += text; return; } } appendChild(parentNode, createTextNode(text)); }; exports.insertTextBefore = function(parentNode, text, referenceNode) { const prevNode = parentNode.childNodes[parentNode.childNodes.indexOf(referenceNode) - 1]; if (prevNode && prevNode.nodeName === '#text') { prevNode.value += text; } else { insertBefore(parentNode, createTextNode(text), referenceNode); } }; exports.adoptAttributes = function(recipient, attrs) { const recipientAttrsMap = []; for (let i = 0; i < recipient.attrs.length; i++) { recipientAttrsMap.push(recipient.attrs[i].name); } for (let j = 0; j < attrs.length; j++) { if (recipientAttrsMap.indexOf(attrs[j].name) === -1) { recipient.attrs.push(attrs[j]); } } }; //Tree traversing exports.getFirstChild = function(node) { return node.childNodes[0]; }; exports.getChildNodes = function(node) { return node.childNodes; }; exports.getParentNode = function(node) { return node.parentNode; }; exports.getAttrList = function(element) { return element.attrs; }; //Node data exports.getTagName = function(element) { return element.tagName; }; exports.getNamespaceURI = function(element) { return element.namespaceURI; }; exports.getTextNodeContent = function(textNode) { return textNode.value; }; exports.getCommentNodeContent = function(commentNode) { return commentNode.data; }; exports.getDocumentTypeNodeName = function(doctypeNode) { return doctypeNode.name; }; exports.getDocumentTypeNodePublicId = function(doctypeNode) { return doctypeNode.publicId; }; exports.getDocumentTypeNodeSystemId = function(doctypeNode) { return doctypeNode.systemId; }; //Node types exports.isTextNode = function(node) { return node.nodeName === '#text'; }; exports.isCommentNode = function(node) { return node.nodeName === '#comment'; }; exports.isDocumentTypeNode = function(node) { return node.nodeName === '#documentType'; }; exports.isElementNode = function(node) { return !!node.tagName; }; // Source code location exports.setNodeSourceCodeLocation = function(node, location) { node.sourceCodeLocation = location; }; exports.getNodeSourceCodeLocation = function(node) { return node.sourceCodeLocation; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/parse5/lib/tree-adapters/default.js
default.js
'use strict'; const Tokenizer = require('parse5/lib/tokenizer'); const HTML = require('parse5/lib/common/html'); //Aliases const $ = HTML.TAG_NAMES; const NS = HTML.NAMESPACES; const ATTRS = HTML.ATTRS; //MIME types const MIME_TYPES = { TEXT_HTML: 'text/html', APPLICATION_XML: 'application/xhtml+xml' }; //Attributes const DEFINITION_URL_ATTR = 'definitionurl'; const ADJUSTED_DEFINITION_URL_ATTR = 'definitionURL'; const SVG_ATTRS_ADJUSTMENT_MAP = { attributename: 'attributeName', attributetype: 'attributeType', basefrequency: 'baseFrequency', baseprofile: 'baseProfile', calcmode: 'calcMode', clippathunits: 'clipPathUnits', diffuseconstant: 'diffuseConstant', edgemode: 'edgeMode', filterunits: 'filterUnits', glyphref: 'glyphRef', gradienttransform: 'gradientTransform', gradientunits: 'gradientUnits', kernelmatrix: 'kernelMatrix', kernelunitlength: 'kernelUnitLength', keypoints: 'keyPoints', keysplines: 'keySplines', keytimes: 'keyTimes', lengthadjust: 'lengthAdjust', limitingconeangle: 'limitingConeAngle', markerheight: 'markerHeight', markerunits: 'markerUnits', markerwidth: 'markerWidth', maskcontentunits: 'maskContentUnits', maskunits: 'maskUnits', numoctaves: 'numOctaves', pathlength: 'pathLength', patterncontentunits: 'patternContentUnits', patterntransform: 'patternTransform', patternunits: 'patternUnits', pointsatx: 'pointsAtX', pointsaty: 'pointsAtY', pointsatz: 'pointsAtZ', preservealpha: 'preserveAlpha', preserveaspectratio: 'preserveAspectRatio', primitiveunits: 'primitiveUnits', refx: 'refX', refy: 'refY', repeatcount: 'repeatCount', repeatdur: 'repeatDur', requiredextensions: 'requiredExtensions', requiredfeatures: 'requiredFeatures', specularconstant: 'specularConstant', specularexponent: 'specularExponent', spreadmethod: 'spreadMethod', startoffset: 'startOffset', stddeviation: 'stdDeviation', stitchtiles: 'stitchTiles', surfacescale: 'surfaceScale', systemlanguage: 'systemLanguage', tablevalues: 'tableValues', targetx: 'targetX', targety: 'targetY', textlength: 'textLength', viewbox: 'viewBox', viewtarget: 'viewTarget', xchannelselector: 'xChannelSelector', ychannelselector: 'yChannelSelector', zoomandpan: 'zoomAndPan' }; const XML_ATTRS_ADJUSTMENT_MAP = { 'xlink:actuate': { prefix: 'xlink', name: 'actuate', namespace: NS.XLINK }, 'xlink:arcrole': { prefix: 'xlink', name: 'arcrole', namespace: NS.XLINK }, 'xlink:href': { prefix: 'xlink', name: 'href', namespace: NS.XLINK }, 'xlink:role': { prefix: 'xlink', name: 'role', namespace: NS.XLINK }, 'xlink:show': { prefix: 'xlink', name: 'show', namespace: NS.XLINK }, 'xlink:title': { prefix: 'xlink', name: 'title', namespace: NS.XLINK }, 'xlink:type': { prefix: 'xlink', name: 'type', namespace: NS.XLINK }, 'xml:base': { prefix: 'xml', name: 'base', namespace: NS.XML }, 'xml:lang': { prefix: 'xml', name: 'lang', namespace: NS.XML }, 'xml:space': { prefix: 'xml', name: 'space', namespace: NS.XML }, xmlns: { prefix: '', name: 'xmlns', namespace: NS.XMLNS }, 'xmlns:xlink': { prefix: 'xmlns', name: 'xlink', namespace: NS.XMLNS } }; //SVG tag names adjustment map const SVG_TAG_NAMES_ADJUSTMENT_MAP = (exports.SVG_TAG_NAMES_ADJUSTMENT_MAP = { altglyph: 'altGlyph', altglyphdef: 'altGlyphDef', altglyphitem: 'altGlyphItem', animatecolor: 'animateColor', animatemotion: 'animateMotion', animatetransform: 'animateTransform', clippath: 'clipPath', feblend: 'feBlend', fecolormatrix: 'feColorMatrix', fecomponenttransfer: 'feComponentTransfer', fecomposite: 'feComposite', feconvolvematrix: 'feConvolveMatrix', fediffuselighting: 'feDiffuseLighting', fedisplacementmap: 'feDisplacementMap', fedistantlight: 'feDistantLight', feflood: 'feFlood', fefunca: 'feFuncA', fefuncb: 'feFuncB', fefuncg: 'feFuncG', fefuncr: 'feFuncR', fegaussianblur: 'feGaussianBlur', feimage: 'feImage', femerge: 'feMerge', femergenode: 'feMergeNode', femorphology: 'feMorphology', feoffset: 'feOffset', fepointlight: 'fePointLight', fespecularlighting: 'feSpecularLighting', fespotlight: 'feSpotLight', fetile: 'feTile', feturbulence: 'feTurbulence', foreignobject: 'foreignObject', glyphref: 'glyphRef', lineargradient: 'linearGradient', radialgradient: 'radialGradient', textpath: 'textPath' }); //Tags that causes exit from foreign content const EXITS_FOREIGN_CONTENT = { [$.B]: true, [$.BIG]: true, [$.BLOCKQUOTE]: true, [$.BODY]: true, [$.BR]: true, [$.CENTER]: true, [$.CODE]: true, [$.DD]: true, [$.DIV]: true, [$.DL]: true, [$.DT]: true, [$.EM]: true, [$.EMBED]: true, [$.H1]: true, [$.H2]: true, [$.H3]: true, [$.H4]: true, [$.H5]: true, [$.H6]: true, [$.HEAD]: true, [$.HR]: true, [$.I]: true, [$.IMG]: true, [$.LI]: true, [$.LISTING]: true, [$.MENU]: true, [$.META]: true, [$.NOBR]: true, [$.OL]: true, [$.P]: true, [$.PRE]: true, [$.RUBY]: true, [$.S]: true, [$.SMALL]: true, [$.SPAN]: true, [$.STRONG]: true, [$.STRIKE]: true, [$.SUB]: true, [$.SUP]: true, [$.TABLE]: true, [$.TT]: true, [$.U]: true, [$.UL]: true, [$.VAR]: true }; //Check exit from foreign content exports.causesExit = function(startTagToken) { const tn = startTagToken.tagName; const isFontWithAttrs = tn === $.FONT && (Tokenizer.getTokenAttr(startTagToken, ATTRS.COLOR) !== null || Tokenizer.getTokenAttr(startTagToken, ATTRS.SIZE) !== null || Tokenizer.getTokenAttr(startTagToken, ATTRS.FACE) !== null); return isFontWithAttrs ? true : EXITS_FOREIGN_CONTENT[tn]; }; //Token adjustments exports.adjustTokenMathMLAttrs = function(token) { for (let i = 0; i < token.attrs.length; i++) { if (token.attrs[i].name === DEFINITION_URL_ATTR) { token.attrs[i].name = ADJUSTED_DEFINITION_URL_ATTR; break; } } }; exports.adjustTokenSVGAttrs = function(token) { for (let i = 0; i < token.attrs.length; i++) { const adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name]; if (adjustedAttrName) { token.attrs[i].name = adjustedAttrName; } } }; exports.adjustTokenXMLAttrs = function(token) { for (let i = 0; i < token.attrs.length; i++) { const adjustedAttrEntry = XML_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name]; if (adjustedAttrEntry) { token.attrs[i].prefix = adjustedAttrEntry.prefix; token.attrs[i].name = adjustedAttrEntry.name; token.attrs[i].namespace = adjustedAttrEntry.namespace; } } }; exports.adjustTokenSVGTagName = function(token) { const adjustedTagName = SVG_TAG_NAMES_ADJUSTMENT_MAP[token.tagName]; if (adjustedTagName) { token.tagName = adjustedTagName; } }; //Integration points function isMathMLTextIntegrationPoint(tn, ns) { return ns === NS.MATHML && (tn === $.MI || tn === $.MO || tn === $.MN || tn === $.MS || tn === $.MTEXT); } function isHtmlIntegrationPoint(tn, ns, attrs) { if (ns === NS.MATHML && tn === $.ANNOTATION_XML) { for (let i = 0; i < attrs.length; i++) { if (attrs[i].name === ATTRS.ENCODING) { const value = attrs[i].value.toLowerCase(); return value === MIME_TYPES.TEXT_HTML || value === MIME_TYPES.APPLICATION_XML; } } } return ns === NS.SVG && (tn === $.FOREIGN_OBJECT || tn === $.DESC || tn === $.TITLE); } exports.isIntegrationPoint = function(tn, ns, attrs, foreignNS) { if ((!foreignNS || foreignNS === NS.HTML) && isHtmlIntegrationPoint(tn, ns, attrs)) { return true; } if ((!foreignNS || foreignNS === NS.MATHML) && isMathMLTextIntegrationPoint(tn, ns)) { return true; } return false; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/parse5/lib/common/foreign-content.js
foreign-content.js
'use strict'; const { DOCUMENT_MODE } = require('parse5/lib/common/html'); //Const const VALID_DOCTYPE_NAME = 'html'; const VALID_SYSTEM_ID = 'about:legacy-compat'; const QUIRKS_MODE_SYSTEM_ID = 'http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd'; const QUIRKS_MODE_PUBLIC_ID_PREFIXES = [ '+//silmaril//dtd html pro v0r11 19970101//', '-//as//dtd html 3.0 aswedit + extensions//', '-//advasoft ltd//dtd html 3.0 aswedit + extensions//', '-//ietf//dtd html 2.0 level 1//', '-//ietf//dtd html 2.0 level 2//', '-//ietf//dtd html 2.0 strict level 1//', '-//ietf//dtd html 2.0 strict level 2//', '-//ietf//dtd html 2.0 strict//', '-//ietf//dtd html 2.0//', '-//ietf//dtd html 2.1e//', '-//ietf//dtd html 3.0//', '-//ietf//dtd html 3.2 final//', '-//ietf//dtd html 3.2//', '-//ietf//dtd html 3//', '-//ietf//dtd html level 0//', '-//ietf//dtd html level 1//', '-//ietf//dtd html level 2//', '-//ietf//dtd html level 3//', '-//ietf//dtd html strict level 0//', '-//ietf//dtd html strict level 1//', '-//ietf//dtd html strict level 2//', '-//ietf//dtd html strict level 3//', '-//ietf//dtd html strict//', '-//ietf//dtd html//', '-//metrius//dtd metrius presentational//', '-//microsoft//dtd internet explorer 2.0 html strict//', '-//microsoft//dtd internet explorer 2.0 html//', '-//microsoft//dtd internet explorer 2.0 tables//', '-//microsoft//dtd internet explorer 3.0 html strict//', '-//microsoft//dtd internet explorer 3.0 html//', '-//microsoft//dtd internet explorer 3.0 tables//', '-//netscape comm. corp.//dtd html//', '-//netscape comm. corp.//dtd strict html//', "-//o'reilly and associates//dtd html 2.0//", "-//o'reilly and associates//dtd html extended 1.0//", "-//o'reilly and associates//dtd html extended relaxed 1.0//", '-//sq//dtd html 2.0 hotmetal + extensions//', '-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//', '-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//', '-//spyglass//dtd html 2.0 extended//', '-//sun microsystems corp.//dtd hotjava html//', '-//sun microsystems corp.//dtd hotjava strict html//', '-//w3c//dtd html 3 1995-03-24//', '-//w3c//dtd html 3.2 draft//', '-//w3c//dtd html 3.2 final//', '-//w3c//dtd html 3.2//', '-//w3c//dtd html 3.2s draft//', '-//w3c//dtd html 4.0 frameset//', '-//w3c//dtd html 4.0 transitional//', '-//w3c//dtd html experimental 19960712//', '-//w3c//dtd html experimental 970421//', '-//w3c//dtd w3 html//', '-//w3o//dtd w3 html 3.0//', '-//webtechs//dtd mozilla html 2.0//', '-//webtechs//dtd mozilla html//' ]; const QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES = QUIRKS_MODE_PUBLIC_ID_PREFIXES.concat([ '-//w3c//dtd html 4.01 frameset//', '-//w3c//dtd html 4.01 transitional//' ]); const QUIRKS_MODE_PUBLIC_IDS = ['-//w3o//dtd w3 html strict 3.0//en//', '-/w3c/dtd html 4.0 transitional/en', 'html']; const LIMITED_QUIRKS_PUBLIC_ID_PREFIXES = ['-//w3c//dtd xhtml 1.0 frameset//', '-//w3c//dtd xhtml 1.0 transitional//']; const LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES = LIMITED_QUIRKS_PUBLIC_ID_PREFIXES.concat([ '-//w3c//dtd html 4.01 frameset//', '-//w3c//dtd html 4.01 transitional//' ]); //Utils function enquoteDoctypeId(id) { const quote = id.indexOf('"') !== -1 ? "'" : '"'; return quote + id + quote; } function hasPrefix(publicId, prefixes) { for (let i = 0; i < prefixes.length; i++) { if (publicId.indexOf(prefixes[i]) === 0) { return true; } } return false; } //API exports.isConforming = function(token) { return ( token.name === VALID_DOCTYPE_NAME && token.publicId === null && (token.systemId === null || token.systemId === VALID_SYSTEM_ID) ); }; exports.getDocumentMode = function(token) { if (token.name !== VALID_DOCTYPE_NAME) { return DOCUMENT_MODE.QUIRKS; } const systemId = token.systemId; if (systemId && systemId.toLowerCase() === QUIRKS_MODE_SYSTEM_ID) { return DOCUMENT_MODE.QUIRKS; } let publicId = token.publicId; if (publicId !== null) { publicId = publicId.toLowerCase(); if (QUIRKS_MODE_PUBLIC_IDS.indexOf(publicId) > -1) { return DOCUMENT_MODE.QUIRKS; } let prefixes = systemId === null ? QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES : QUIRKS_MODE_PUBLIC_ID_PREFIXES; if (hasPrefix(publicId, prefixes)) { return DOCUMENT_MODE.QUIRKS; } prefixes = systemId === null ? LIMITED_QUIRKS_PUBLIC_ID_PREFIXES : LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES; if (hasPrefix(publicId, prefixes)) { return DOCUMENT_MODE.LIMITED_QUIRKS; } } return DOCUMENT_MODE.NO_QUIRKS; }; exports.serializeContent = function(name, publicId, systemId) { let str = '!DOCTYPE '; if (name) { str += name; } if (publicId) { str += ' PUBLIC ' + enquoteDoctypeId(publicId); } else if (systemId) { str += ' SYSTEM'; } if (systemId !== null) { str += ' ' + enquoteDoctypeId(systemId); } return str; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/parse5/lib/common/doctype.js
doctype.js
'use strict'; module.exports = { controlCharacterInInputStream: 'control-character-in-input-stream', noncharacterInInputStream: 'noncharacter-in-input-stream', surrogateInInputStream: 'surrogate-in-input-stream', nonVoidHtmlElementStartTagWithTrailingSolidus: 'non-void-html-element-start-tag-with-trailing-solidus', endTagWithAttributes: 'end-tag-with-attributes', endTagWithTrailingSolidus: 'end-tag-with-trailing-solidus', unexpectedSolidusInTag: 'unexpected-solidus-in-tag', unexpectedNullCharacter: 'unexpected-null-character', unexpectedQuestionMarkInsteadOfTagName: 'unexpected-question-mark-instead-of-tag-name', invalidFirstCharacterOfTagName: 'invalid-first-character-of-tag-name', unexpectedEqualsSignBeforeAttributeName: 'unexpected-equals-sign-before-attribute-name', missingEndTagName: 'missing-end-tag-name', unexpectedCharacterInAttributeName: 'unexpected-character-in-attribute-name', unknownNamedCharacterReference: 'unknown-named-character-reference', missingSemicolonAfterCharacterReference: 'missing-semicolon-after-character-reference', unexpectedCharacterAfterDoctypeSystemIdentifier: 'unexpected-character-after-doctype-system-identifier', unexpectedCharacterInUnquotedAttributeValue: 'unexpected-character-in-unquoted-attribute-value', eofBeforeTagName: 'eof-before-tag-name', eofInTag: 'eof-in-tag', missingAttributeValue: 'missing-attribute-value', missingWhitespaceBetweenAttributes: 'missing-whitespace-between-attributes', missingWhitespaceAfterDoctypePublicKeyword: 'missing-whitespace-after-doctype-public-keyword', missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers: 'missing-whitespace-between-doctype-public-and-system-identifiers', missingWhitespaceAfterDoctypeSystemKeyword: 'missing-whitespace-after-doctype-system-keyword', missingQuoteBeforeDoctypePublicIdentifier: 'missing-quote-before-doctype-public-identifier', missingQuoteBeforeDoctypeSystemIdentifier: 'missing-quote-before-doctype-system-identifier', missingDoctypePublicIdentifier: 'missing-doctype-public-identifier', missingDoctypeSystemIdentifier: 'missing-doctype-system-identifier', abruptDoctypePublicIdentifier: 'abrupt-doctype-public-identifier', abruptDoctypeSystemIdentifier: 'abrupt-doctype-system-identifier', cdataInHtmlContent: 'cdata-in-html-content', incorrectlyOpenedComment: 'incorrectly-opened-comment', eofInScriptHtmlCommentLikeText: 'eof-in-script-html-comment-like-text', eofInDoctype: 'eof-in-doctype', nestedComment: 'nested-comment', abruptClosingOfEmptyComment: 'abrupt-closing-of-empty-comment', eofInComment: 'eof-in-comment', incorrectlyClosedComment: 'incorrectly-closed-comment', eofInCdata: 'eof-in-cdata', absenceOfDigitsInNumericCharacterReference: 'absence-of-digits-in-numeric-character-reference', nullCharacterReference: 'null-character-reference', surrogateCharacterReference: 'surrogate-character-reference', characterReferenceOutsideUnicodeRange: 'character-reference-outside-unicode-range', controlCharacterReference: 'control-character-reference', noncharacterCharacterReference: 'noncharacter-character-reference', missingWhitespaceBeforeDoctypeName: 'missing-whitespace-before-doctype-name', missingDoctypeName: 'missing-doctype-name', invalidCharacterSequenceAfterDoctypeName: 'invalid-character-sequence-after-doctype-name', duplicateAttribute: 'duplicate-attribute', nonConformingDoctype: 'non-conforming-doctype', missingDoctype: 'missing-doctype', misplacedDoctype: 'misplaced-doctype', endTagWithoutMatchingOpenElement: 'end-tag-without-matching-open-element', closingOfElementWithOpenChildElements: 'closing-of-element-with-open-child-elements', disallowedContentInNoscriptInHead: 'disallowed-content-in-noscript-in-head', openElementsLeftAfterEof: 'open-elements-left-after-eof', abandonedHeadElementChild: 'abandoned-head-element-child', misplacedStartTagForHeadElement: 'misplaced-start-tag-for-head-element', nestedNoscriptInHead: 'nested-noscript-in-head', eofInElementThatCanContainOnlyText: 'eof-in-element-that-can-contain-only-text' };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/parse5/lib/common/error-codes.js
error-codes.js
'use strict'; const UNDEFINED_CODE_POINTS = [ 0xfffe, 0xffff, 0x1fffe, 0x1ffff, 0x2fffe, 0x2ffff, 0x3fffe, 0x3ffff, 0x4fffe, 0x4ffff, 0x5fffe, 0x5ffff, 0x6fffe, 0x6ffff, 0x7fffe, 0x7ffff, 0x8fffe, 0x8ffff, 0x9fffe, 0x9ffff, 0xafffe, 0xaffff, 0xbfffe, 0xbffff, 0xcfffe, 0xcffff, 0xdfffe, 0xdffff, 0xefffe, 0xeffff, 0xffffe, 0xfffff, 0x10fffe, 0x10ffff ]; exports.REPLACEMENT_CHARACTER = '\uFFFD'; exports.CODE_POINTS = { EOF: -1, NULL: 0x00, TABULATION: 0x09, CARRIAGE_RETURN: 0x0d, LINE_FEED: 0x0a, FORM_FEED: 0x0c, SPACE: 0x20, EXCLAMATION_MARK: 0x21, QUOTATION_MARK: 0x22, NUMBER_SIGN: 0x23, AMPERSAND: 0x26, APOSTROPHE: 0x27, HYPHEN_MINUS: 0x2d, SOLIDUS: 0x2f, DIGIT_0: 0x30, DIGIT_9: 0x39, SEMICOLON: 0x3b, LESS_THAN_SIGN: 0x3c, EQUALS_SIGN: 0x3d, GREATER_THAN_SIGN: 0x3e, QUESTION_MARK: 0x3f, LATIN_CAPITAL_A: 0x41, LATIN_CAPITAL_F: 0x46, LATIN_CAPITAL_X: 0x58, LATIN_CAPITAL_Z: 0x5a, RIGHT_SQUARE_BRACKET: 0x5d, GRAVE_ACCENT: 0x60, LATIN_SMALL_A: 0x61, LATIN_SMALL_F: 0x66, LATIN_SMALL_X: 0x78, LATIN_SMALL_Z: 0x7a, REPLACEMENT_CHARACTER: 0xfffd }; exports.CODE_POINT_SEQUENCES = { DASH_DASH_STRING: [0x2d, 0x2d], //-- DOCTYPE_STRING: [0x44, 0x4f, 0x43, 0x54, 0x59, 0x50, 0x45], //DOCTYPE CDATA_START_STRING: [0x5b, 0x43, 0x44, 0x41, 0x54, 0x41, 0x5b], //[CDATA[ SCRIPT_STRING: [0x73, 0x63, 0x72, 0x69, 0x70, 0x74], //script PUBLIC_STRING: [0x50, 0x55, 0x42, 0x4c, 0x49, 0x43], //PUBLIC SYSTEM_STRING: [0x53, 0x59, 0x53, 0x54, 0x45, 0x4d] //SYSTEM }; //Surrogates exports.isSurrogate = function(cp) { return cp >= 0xd800 && cp <= 0xdfff; }; exports.isSurrogatePair = function(cp) { return cp >= 0xdc00 && cp <= 0xdfff; }; exports.getSurrogatePairCodePoint = function(cp1, cp2) { return (cp1 - 0xd800) * 0x400 + 0x2400 + cp2; }; //NOTE: excluding NULL and ASCII whitespace exports.isControlCodePoint = function(cp) { return ( (cp !== 0x20 && cp !== 0x0a && cp !== 0x0d && cp !== 0x09 && cp !== 0x0c && cp >= 0x01 && cp <= 0x1f) || (cp >= 0x7f && cp <= 0x9f) ); }; exports.isUndefinedCodePoint = function(cp) { return (cp >= 0xfdd0 && cp <= 0xfdef) || UNDEFINED_CODE_POINTS.indexOf(cp) > -1; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/parse5/lib/common/unicode.js
unicode.js
'use strict'; const NS = (exports.NAMESPACES = { HTML: 'http://www.w3.org/1999/xhtml', MATHML: 'http://www.w3.org/1998/Math/MathML', SVG: 'http://www.w3.org/2000/svg', XLINK: 'http://www.w3.org/1999/xlink', XML: 'http://www.w3.org/XML/1998/namespace', XMLNS: 'http://www.w3.org/2000/xmlns/' }); exports.ATTRS = { TYPE: 'type', ACTION: 'action', ENCODING: 'encoding', PROMPT: 'prompt', NAME: 'name', COLOR: 'color', FACE: 'face', SIZE: 'size' }; exports.DOCUMENT_MODE = { NO_QUIRKS: 'no-quirks', QUIRKS: 'quirks', LIMITED_QUIRKS: 'limited-quirks' }; const $ = (exports.TAG_NAMES = { A: 'a', ADDRESS: 'address', ANNOTATION_XML: 'annotation-xml', APPLET: 'applet', AREA: 'area', ARTICLE: 'article', ASIDE: 'aside', B: 'b', BASE: 'base', BASEFONT: 'basefont', BGSOUND: 'bgsound', BIG: 'big', BLOCKQUOTE: 'blockquote', BODY: 'body', BR: 'br', BUTTON: 'button', CAPTION: 'caption', CENTER: 'center', CODE: 'code', COL: 'col', COLGROUP: 'colgroup', DD: 'dd', DESC: 'desc', DETAILS: 'details', DIALOG: 'dialog', DIR: 'dir', DIV: 'div', DL: 'dl', DT: 'dt', EM: 'em', EMBED: 'embed', FIELDSET: 'fieldset', FIGCAPTION: 'figcaption', FIGURE: 'figure', FONT: 'font', FOOTER: 'footer', FOREIGN_OBJECT: 'foreignObject', FORM: 'form', FRAME: 'frame', FRAMESET: 'frameset', H1: 'h1', H2: 'h2', H3: 'h3', H4: 'h4', H5: 'h5', H6: 'h6', HEAD: 'head', HEADER: 'header', HGROUP: 'hgroup', HR: 'hr', HTML: 'html', I: 'i', IMG: 'img', IMAGE: 'image', INPUT: 'input', IFRAME: 'iframe', KEYGEN: 'keygen', LABEL: 'label', LI: 'li', LINK: 'link', LISTING: 'listing', MAIN: 'main', MALIGNMARK: 'malignmark', MARQUEE: 'marquee', MATH: 'math', MENU: 'menu', META: 'meta', MGLYPH: 'mglyph', MI: 'mi', MO: 'mo', MN: 'mn', MS: 'ms', MTEXT: 'mtext', NAV: 'nav', NOBR: 'nobr', NOFRAMES: 'noframes', NOEMBED: 'noembed', NOSCRIPT: 'noscript', OBJECT: 'object', OL: 'ol', OPTGROUP: 'optgroup', OPTION: 'option', P: 'p', PARAM: 'param', PLAINTEXT: 'plaintext', PRE: 'pre', RB: 'rb', RP: 'rp', RT: 'rt', RTC: 'rtc', RUBY: 'ruby', S: 's', SCRIPT: 'script', SECTION: 'section', SELECT: 'select', SOURCE: 'source', SMALL: 'small', SPAN: 'span', STRIKE: 'strike', STRONG: 'strong', STYLE: 'style', SUB: 'sub', SUMMARY: 'summary', SUP: 'sup', TABLE: 'table', TBODY: 'tbody', TEMPLATE: 'template', TEXTAREA: 'textarea', TFOOT: 'tfoot', TD: 'td', TH: 'th', THEAD: 'thead', TITLE: 'title', TR: 'tr', TRACK: 'track', TT: 'tt', U: 'u', UL: 'ul', SVG: 'svg', VAR: 'var', WBR: 'wbr', XMP: 'xmp' }); exports.SPECIAL_ELEMENTS = { [NS.HTML]: { [$.ADDRESS]: true, [$.APPLET]: true, [$.AREA]: true, [$.ARTICLE]: true, [$.ASIDE]: true, [$.BASE]: true, [$.BASEFONT]: true, [$.BGSOUND]: true, [$.BLOCKQUOTE]: true, [$.BODY]: true, [$.BR]: true, [$.BUTTON]: true, [$.CAPTION]: true, [$.CENTER]: true, [$.COL]: true, [$.COLGROUP]: true, [$.DD]: true, [$.DETAILS]: true, [$.DIR]: true, [$.DIV]: true, [$.DL]: true, [$.DT]: true, [$.EMBED]: true, [$.FIELDSET]: true, [$.FIGCAPTION]: true, [$.FIGURE]: true, [$.FOOTER]: true, [$.FORM]: true, [$.FRAME]: true, [$.FRAMESET]: true, [$.H1]: true, [$.H2]: true, [$.H3]: true, [$.H4]: true, [$.H5]: true, [$.H6]: true, [$.HEAD]: true, [$.HEADER]: true, [$.HGROUP]: true, [$.HR]: true, [$.HTML]: true, [$.IFRAME]: true, [$.IMG]: true, [$.INPUT]: true, [$.LI]: true, [$.LINK]: true, [$.LISTING]: true, [$.MAIN]: true, [$.MARQUEE]: true, [$.MENU]: true, [$.META]: true, [$.NAV]: true, [$.NOEMBED]: true, [$.NOFRAMES]: true, [$.NOSCRIPT]: true, [$.OBJECT]: true, [$.OL]: true, [$.P]: true, [$.PARAM]: true, [$.PLAINTEXT]: true, [$.PRE]: true, [$.SCRIPT]: true, [$.SECTION]: true, [$.SELECT]: true, [$.SOURCE]: true, [$.STYLE]: true, [$.SUMMARY]: true, [$.TABLE]: true, [$.TBODY]: true, [$.TD]: true, [$.TEMPLATE]: true, [$.TEXTAREA]: true, [$.TFOOT]: true, [$.TH]: true, [$.THEAD]: true, [$.TITLE]: true, [$.TR]: true, [$.TRACK]: true, [$.UL]: true, [$.WBR]: true, [$.XMP]: true }, [NS.MATHML]: { [$.MI]: true, [$.MO]: true, [$.MN]: true, [$.MS]: true, [$.MTEXT]: true, [$.ANNOTATION_XML]: true }, [NS.SVG]: { [$.TITLE]: true, [$.FOREIGN_OBJECT]: true, [$.DESC]: true } };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/parse5/lib/common/html.js
html.js
# 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/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."`) If we are dealing with multiple JavaScript realms (such as those created using Node.js' [vm](https://nodejs.org/api/vm.html) module or the HTML `iframe` element), and exceptions from another realm need to be thrown, one can supply an object option `globals` containing the following properties: ```js { globals: { Number, String, TypeError } } ``` Those specific functions will be used when throwing exceptions. 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), which can additionally be provided with the boolean option `{ allowShared }` as a second parameter Additionally, for convenience, the following derived type definitions are implemented: - [`ArrayBufferView`](https://heycam.github.io/webidl/#ArrayBufferView), which can additionally be provided with the boolean option `{ allowShared }` as a second parameter - [`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. Conversions are still accurate as we make use of BigInt in the conversion process, but in the case of `unsigned long long` we simply cannot represent some possible output values in JavaScript. For example, converting the JavaScript number `-1` to a Web IDL `unsigned long long` is supposed to produce the Web IDL value `18446744073709551615`. Since we are representing our Web IDL values in JavaScript, we can't represent `18446744073709551615`, so we instead the best we could do is `18446744073709551616` as the output. To mitigate this, we could return the raw BigInt value from the conversion function, but right now it is not implemented. If your use case requires such precision, [file an issue](https://github.com/jsdom/webidl-conversions/issues/new). On the other hand, `long long` conversion is always accurate, since the input value can never be more precise than the output value. ### A note on `BufferSource` types All of the `BufferSource` types will throw when the relevant `ArrayBuffer` has been detached. This technically is not part of the [specified conversion algorithm](https://heycam.github.io/webidl/#es-buffer-source-types), but instead part of the [getting a reference/getting a copy](https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-reference%E2%91%A0) algorithms. We've consolidated them here for convenience and ease of implementation, but if there is a need to separate them in the future, please open an issue so we can investigate. ## 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/webidl-conversions/README.md
README.md
"use strict"; function makeException(ErrorType, message, opts = {}) { if (opts.globals) { ErrorType = opts.globals[ErrorType.name]; } return new ErrorType(`${opts.context ? opts.context : "Value"} ${message}.`); } function toNumber(value, opts = {}) { if (!opts.globals) { return +value; } if (typeof value === "bigint") { throw opts.globals.TypeError("Cannot convert a BigInt value to a number"); } return opts.globals.Number(value); } 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 "bigint": return "BigInt"; 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 = Number.MAX_SAFE_INTEGER; lowerBound = !isSigned ? 0 : Number.MIN_SAFE_INTEGER; } 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 = {}) => { let x = toNumber(V, opts); x = censorNegativeZero(x); if (opts.enforceRange) { if (!Number.isFinite(x)) { throw makeException(TypeError, "is not a finite number", opts); } x = integerPart(x); if (x < lowerBound || x > upperBound) { throw makeException(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; }; } function createLongLongConversion(bitLength, { unsigned }) { const upperBound = Number.MAX_SAFE_INTEGER; const lowerBound = unsigned ? 0 : Number.MIN_SAFE_INTEGER; const asBigIntN = unsigned ? BigInt.asUintN : BigInt.asIntN; return (V, opts = {}) => { if (opts === undefined) { opts = {}; } let x = toNumber(V, opts); x = censorNegativeZero(x); if (opts.enforceRange) { if (!Number.isFinite(x)) { throw makeException(TypeError, "is not a finite number", opts); } x = integerPart(x); if (x < lowerBound || x > upperBound) { throw makeException(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; } let xBigInt = BigInt(integerPart(x)); xBigInt = asBigIntN(bitLength, xBigInt); return Number(xBigInt); }; } 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"] = createLongLongConversion(64, { unsigned: false }); exports["unsigned long long"] = createLongLongConversion(64, { unsigned: true }); exports.double = (V, opts) => { const x = toNumber(V, opts); if (!Number.isFinite(x)) { throw makeException(TypeError, "is not a finite floating-point value", opts); } return x; }; exports["unrestricted double"] = (V, opts) => { const x = toNumber(V, opts); return x; }; exports.float = (V, opts) => { const x = toNumber(V, opts); if (!Number.isFinite(x)) { throw makeException(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 makeException(TypeError, "is outside the range of a single-precision floating-point value", opts); } return y; }; exports["unrestricted float"] = (V, opts) => { const x = toNumber(V, opts); if (isNaN(x)) { return x; } if (Object.is(x, -0)) { return x; } return Math.fround(x); }; exports.DOMString = function (V, opts = {}) { if (opts.treatNullAsEmptyString && V === null) { return ""; } if (typeof V === "symbol") { throw makeException(TypeError, "is a symbol, which cannot be converted to a string", opts); } const StringCtor = opts.globals ? opts.globals.String : String; return StringCtor(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 makeException(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 makeException(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 makeException(TypeError, "is not a function", opts); } return V; } const abByteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; const sabByteLengthGetter = Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, "byteLength").get; function isNonSharedArrayBuffer(V) { try { // This will throw on SharedArrayBuffers, but not detached ArrayBuffers. // (The spec says it should throw, but the spec conflicts with implementations: https://github.com/tc39/ecma262/issues/678) abByteLengthGetter.call(V); return true; } catch { return false; } } function isSharedArrayBuffer(V) { try { sabByteLengthGetter.call(V); return true; } catch { return false; } } function isArrayBufferDetached(V) { try { // eslint-disable-next-line no-new new Uint8Array(V); return false; } catch { return true; } } exports.ArrayBuffer = (V, opts = {}) => { if (!isNonSharedArrayBuffer(V)) { if (opts.allowShared && !isSharedArrayBuffer(V)) { throw makeException(TypeError, "is not an ArrayBuffer or SharedArrayBuffer", opts); } throw makeException(TypeError, "is not an ArrayBuffer", opts); } if (isArrayBufferDetached(V)) { throw makeException(TypeError, "is a detached ArrayBuffer", opts); } return V; }; const dvByteLengthGetter = Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get; exports.DataView = (V, opts = {}) => { try { dvByteLengthGetter.call(V); } catch (e) { throw makeException(TypeError, "is not a DataView", opts); } if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) { throw makeException(TypeError, "is backed by a SharedArrayBuffer, which is not allowed", opts); } if (isArrayBufferDetached(V.buffer)) { throw makeException(TypeError, "is backed by a detached ArrayBuffer", opts); } return V; }; // Returns the unforgeable `TypedArray` constructor name or `undefined`, // if the `this` value isn't a valid `TypedArray` object. // // https://tc39.es/ecma262/#sec-get-%typedarray%.prototype-@@tostringtag const typedArrayNameGetter = Object.getOwnPropertyDescriptor( Object.getPrototypeOf(Uint8Array).prototype, Symbol.toStringTag ).get; [ 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) || typedArrayNameGetter.call(V) !== name) { throw makeException(TypeError, `is not ${article} ${name} object`, opts); } if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) { throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", opts); } if (isArrayBufferDetached(V.buffer)) { throw makeException(TypeError, "is a view on a detached ArrayBuffer", opts); } return V; }; }); // Common definitions exports.ArrayBufferView = (V, opts = {}) => { if (!ArrayBuffer.isView(V)) { throw makeException(TypeError, "is not a view on an ArrayBuffer or SharedArrayBuffer", opts); } if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) { throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", opts); } if (isArrayBufferDetached(V.buffer)) { throw makeException(TypeError, "is a view on a detached ArrayBuffer", opts); } return V; }; exports.BufferSource = (V, opts = {}) => { if (ArrayBuffer.isView(V)) { if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) { throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", opts); } if (isArrayBufferDetached(V.buffer)) { throw makeException(TypeError, "is a view on a detached ArrayBuffer", opts); } return V; } if (!opts.allowShared && !isNonSharedArrayBuffer(V)) { throw makeException(TypeError, "is not an ArrayBuffer or a view on one", opts); } if (opts.allowShared && !isSharedArrayBuffer(V) && !isNonSharedArrayBuffer(V)) { throw makeException(TypeError, "is not an ArrayBuffer, SharedArrayBufer, or a view on one", opts); } if (isArrayBufferDetached(V)) { throw makeException(TypeError, "is a detached ArrayBuffer", 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/webidl-conversions/lib/index.js
index.js
## getpass Get a password from the terminal. Sounds simple? Sounds like the `readline` module should be able to do it? NOPE. ## Install and use it ```bash npm install --save getpass ``` ```javascript const mod_getpass = require('getpass'); ``` ## API ### `mod_getpass.getPass([options, ]callback)` Gets a password from the terminal. If available, this uses `/dev/tty` to avoid interfering with any data being piped in or out of stdio. This function prints a prompt (by default `Password:`) and then accepts input without echoing. Parameters: * `options`, an Object, with properties: * `prompt`, an optional String * `callback`, a `Func(error, password)`, with arguments: * `error`, either `null` (no error) or an `Error` instance * `password`, a String
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/getpass/README.md
README.md
module.exports = { getPass: getPass }; const mod_tty = require('tty'); const mod_fs = require('fs'); const mod_assert = require('assert-plus'); var BACKSPACE = String.fromCharCode(127); var CTRLC = '\u0003'; var CTRLD = '\u0004'; function getPass(opts, cb) { if (typeof (opts) === 'function' && cb === undefined) { cb = opts; opts = {}; } mod_assert.object(opts, 'options'); mod_assert.func(cb, 'callback'); mod_assert.optionalString(opts.prompt, 'options.prompt'); if (opts.prompt === undefined) opts.prompt = 'Password'; openTTY(function (err, rfd, wfd, rtty, wtty) { if (err) { cb(err); return; } wtty.write(opts.prompt + ':'); rtty.resume(); rtty.setRawMode(true); rtty.resume(); rtty.setEncoding('utf8'); var pw = ''; rtty.on('data', onData); function onData(data) { var str = data.toString('utf8'); for (var i = 0; i < str.length; ++i) { var ch = str[i]; switch (ch) { case '\r': case '\n': case CTRLD: cleanup(); cb(null, pw); return; case CTRLC: cleanup(); cb(new Error('Aborted')); return; case BACKSPACE: pw = pw.slice(0, pw.length - 1); break; default: pw += ch; break; } } } function cleanup() { wtty.write('\r\n'); rtty.setRawMode(false); rtty.pause(); rtty.removeListener('data', onData); if (wfd !== undefined && wfd !== rfd) { wtty.end(); mod_fs.closeSync(wfd); } if (rfd !== undefined) { rtty.end(); mod_fs.closeSync(rfd); } } }); } function openTTY(cb) { mod_fs.open('/dev/tty', 'r+', function (err, rttyfd) { if ((err && (err.code === 'ENOENT' || err.code === 'EACCES')) || (process.version.match(/^v0[.][0-8][.]/))) { cb(null, undefined, undefined, process.stdin, process.stdout); return; } var rtty = new mod_tty.ReadStream(rttyfd); mod_fs.open('/dev/tty', 'w+', function (err3, wttyfd) { var wtty = new mod_tty.WriteStream(wttyfd); if (err3) { cb(err3); return; } cb(null, rttyfd, wttyfd, rtty, wtty); }); }); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/getpass/lib/index.js
index.js
## Caseless -- wrap an object to set and get property with caseless semantics but also preserve caseing. This library is incredibly useful when working with HTTP headers. It allows you to get/set/check for headers in a caseless manner while also preserving the caseing of headers the first time they are set. ## Usage ```javascript var headers = {} , c = caseless(headers) ; c.set('a-Header', 'asdf') c.get('a-header') === 'asdf' ``` ## has(key) Has takes a name and if it finds a matching header will return that header name with the preserved caseing it was set with. ```javascript c.has('a-header') === 'a-Header' ``` ## set(key, value[, clobber=true]) Set is fairly straight forward except that if the header exists and clobber is disabled it will add `','+value` to the existing header. ```javascript c.set('a-Header', 'fdas') c.set('a-HEADER', 'more', false) c.get('a-header') === 'fdsa,more' ``` ## swap(key) Swaps the casing of a header with the new one that is passed in. ```javascript var headers = {} , c = caseless(headers) ; c.set('a-Header', 'fdas') c.swap('a-HEADER') c.has('a-header') === 'a-HEADER' headers === {'a-HEADER': 'fdas'} ```
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/caseless/README.md
README.md
var pSlice = Array.prototype.slice; var Object_keys = typeof Object.keys === 'function' ? Object.keys : function (obj) { var keys = []; for (var key in obj) keys.push(key); return keys; } ; var deepEqual = module.exports = function (actual, expected) { // enforce Object.is +0 !== -0 if (actual === 0 && expected === 0) { return areZerosEqual(actual, expected); // 7.1. All identical values are equivalent, as determined by ===. } else if (actual === expected) { return true; } else if (actual instanceof Date && expected instanceof Date) { return actual.getTime() === expected.getTime(); } else if (isNumberNaN(actual)) { return isNumberNaN(expected); // 7.3. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if (typeof actual != 'object' && typeof expected != 'object') { return actual == expected; // 7.4. For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else { return objEquiv(actual, expected); } }; function isUndefinedOrNull(value) { return value === null || value === undefined; } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function isNumberNaN(value) { // NaN === NaN -> false return typeof value == 'number' && value !== value; } function areZerosEqual(zeroA, zeroB) { // (1 / +0|0) -> Infinity, but (1 / -0) -> -Infinity and (Infinity !== -Infinity) return (1 / zeroA) === (1 / zeroB); } function objEquiv(a, b) { if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; //~~~I've managed to break Object.keys through screwy arguments passing. // Converting to array solves the problem. if (isArguments(a)) { if (!isArguments(b)) { return false; } a = pSlice.call(a); b = pSlice.call(b); return deepEqual(a, b); } try { var ka = Object_keys(a), kb = Object_keys(b), key, i; } catch (e) {//happens when one is a string literal and the other isn't return false; } // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!deepEqual(a[key], b[key])) return false; } return true; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/deep-is/index.js
index.js
# asynckit [![NPM Module](https://img.shields.io/npm/v/asynckit.svg?style=flat)](https://www.npmjs.com/package/asynckit) Minimal async jobs utility library, with streams support. [![PhantomJS Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=browser&style=flat)](https://travis-ci.org/alexindigo/asynckit) [![Linux Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=linux:0.12-6.x&style=flat)](https://travis-ci.org/alexindigo/asynckit) [![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/asynckit/v0.4.0.svg?label=windows:0.12-6.x&style=flat)](https://ci.appveyor.com/project/alexindigo/asynckit) [![Coverage Status](https://img.shields.io/coveralls/alexindigo/asynckit/v0.4.0.svg?label=code+coverage&style=flat)](https://coveralls.io/github/alexindigo/asynckit?branch=master) [![Dependency Status](https://img.shields.io/david/alexindigo/asynckit/v0.4.0.svg?style=flat)](https://david-dm.org/alexindigo/asynckit) [![bitHound Overall Score](https://www.bithound.io/github/alexindigo/asynckit/badges/score.svg)](https://www.bithound.io/github/alexindigo/asynckit) <!-- [![Readme](https://img.shields.io/badge/readme-tested-brightgreen.svg?style=flat)](https://www.npmjs.com/package/reamde) --> AsyncKit provides harness for `parallel` and `serial` iterators over list of items represented by arrays or objects. Optionally it accepts abort function (should be synchronously return by iterator for each item), and terminates left over jobs upon an error event. For specific iteration order built-in (`ascending` and `descending`) and custom sort helpers also supported, via `asynckit.serialOrdered` method. It ensures async operations to keep behavior more stable and prevent `Maximum call stack size exceeded` errors, from sync iterators. | compression | size | | :----------------- | -------: | | asynckit.js | 12.34 kB | | asynckit.min.js | 4.11 kB | | asynckit.min.js.gz | 1.47 kB | ## Install ```sh $ npm install --save asynckit ``` ## Examples ### Parallel Jobs Runs iterator over provided array in parallel. Stores output in the `result` array, on the matching positions. In unlikely event of an error from one of the jobs, will terminate rest of the active jobs (if abort function is provided) and return error along with salvaged data to the main callback function. #### Input Array ```javascript var parallel = require('asynckit').parallel , assert = require('assert') ; var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] , target = [] ; parallel(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); }); // async job accepts one element from the array // and a callback function function asyncJob(item, cb) { // different delays (in ms) per item var delay = item * 25; // pretend different jobs take different time to finish // and not in consequential order var timeoutId = setTimeout(function() { target.push(item); cb(null, item * 2); }, delay); // allow to cancel "leftover" jobs upon error // return function, invoking of which will abort this job return clearTimeout.bind(null, timeoutId); } ``` More examples could be found in [test/test-parallel-array.js](test/test-parallel-array.js). #### Input Object Also it supports named jobs, listed via object. ```javascript var parallel = require('asynckit/parallel') , assert = require('assert') ; var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] , expectedKeys = [ 'first', 'one', 'two', 'four', 'eight', 'sixteen', 'thirtyTwo', 'sixtyFour' ] , target = [] , keys = [] ; parallel(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); assert.deepEqual(keys, expectedKeys); }); // supports full value, key, callback (shortcut) interface function asyncJob(item, key, cb) { // different delays (in ms) per item var delay = item * 25; // pretend different jobs take different time to finish // and not in consequential order var timeoutId = setTimeout(function() { keys.push(key); target.push(item); cb(null, item * 2); }, delay); // allow to cancel "leftover" jobs upon error // return function, invoking of which will abort this job return clearTimeout.bind(null, timeoutId); } ``` More examples could be found in [test/test-parallel-object.js](test/test-parallel-object.js). ### Serial Jobs Runs iterator over provided array sequentially. Stores output in the `result` array, on the matching positions. In unlikely event of an error from one of the jobs, will not proceed to the rest of the items in the list and return error along with salvaged data to the main callback function. #### Input Array ```javascript var serial = require('asynckit/serial') , assert = require('assert') ; var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] , target = [] ; serial(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); }); // extended interface (item, key, callback) // also supported for arrays function asyncJob(item, key, cb) { target.push(key); // it will be automatically made async // even it iterator "returns" in the same event loop cb(null, item * 2); } ``` More examples could be found in [test/test-serial-array.js](test/test-serial-array.js). #### Input Object Also it supports named jobs, listed via object. ```javascript var serial = require('asynckit').serial , assert = require('assert') ; var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] , target = [] ; var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } , expectedTarget = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , target = [] ; serial(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); }); // shortcut interface (item, callback) // works for object as well as for the arrays function asyncJob(item, cb) { target.push(item); // it will be automatically made async // even it iterator "returns" in the same event loop cb(null, item * 2); } ``` More examples could be found in [test/test-serial-object.js](test/test-serial-object.js). _Note: Since _object_ is an _unordered_ collection of properties, it may produce unexpected results with sequential iterations. Whenever order of the jobs' execution is important please use `serialOrdered` method._ ### Ordered Serial Iterations TBD For example [compare-property](compare-property) package. ### Streaming interface TBD ## Want to Know More? More examples can be found in [test folder](test/). Or open an [issue](https://github.com/alexindigo/asynckit/issues) with questions and/or suggestions. ## License AsyncKit is licensed under the MIT license.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/asynckit/README.md
README.md
var async = require('asynckit/lib/async.js'); // API module.exports = { iterator: wrapIterator, callback: wrapCallback }; /** * Wraps iterators with long signature * * @this ReadableAsyncKit# * @param {function} iterator - function to wrap * @returns {function} - wrapped function */ function wrapIterator(iterator) { var stream = this; return function(item, key, cb) { var aborter , wrappedCb = async(wrapIteratorCallback.call(stream, cb, key)) ; stream.jobs[key] = wrappedCb; // it's either shortcut (item, cb) if (iterator.length == 2) { aborter = iterator(item, wrappedCb); } // or long format (item, key, cb) else { aborter = iterator(item, key, wrappedCb); } return aborter; }; } /** * Wraps provided callback function * allowing to execute snitch function before * real callback * * @this ReadableAsyncKit# * @param {function} callback - function to wrap * @returns {function} - wrapped function */ function wrapCallback(callback) { var stream = this; var wrapped = function(error, result) { return finisher.call(stream, error, result, callback); }; return wrapped; } /** * Wraps provided iterator callback function * makes sure snitch only called once, * but passes secondary calls to the original callback * * @this ReadableAsyncKit# * @param {function} callback - callback to wrap * @param {number|string} key - iteration key * @returns {function} wrapped callback */ function wrapIteratorCallback(callback, key) { var stream = this; return function(error, output) { // don't repeat yourself if (!(key in stream.jobs)) { callback(error, output); return; } // clean up jobs delete stream.jobs[key]; return streamer.call(stream, error, {key: key, value: output}, callback); }; } /** * Stream wrapper for iterator callback * * @this ReadableAsyncKit# * @param {mixed} error - error response * @param {mixed} output - iterator output * @param {function} callback - callback that expects iterator results */ function streamer(error, output, callback) { if (error && !this.error) { this.error = error; this.pause(); this.emit('error', error); // send back value only, as expected callback(error, output && output.value); return; } // stream stuff this.push(output); // back to original track // send back value only, as expected callback(error, output && output.value); } /** * Stream wrapper for finishing callback * * @this ReadableAsyncKit# * @param {mixed} error - error response * @param {mixed} output - iterator output * @param {function} callback - callback that expects final results */ function finisher(error, output, callback) { // signal end of the stream // only for successfully finished streams if (!error) { this.push(null); } // back to original track callback(error, output); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/asynckit/lib/streamify.js
streamify.js
# word-wrap [![NPM version](https://img.shields.io/npm/v/word-wrap.svg?style=flat)](https://www.npmjs.com/package/word-wrap) [![NPM monthly downloads](https://img.shields.io/npm/dm/word-wrap.svg?style=flat)](https://npmjs.org/package/word-wrap) [![NPM total downloads](https://img.shields.io/npm/dt/word-wrap.svg?style=flat)](https://npmjs.org/package/word-wrap) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/word-wrap.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/word-wrap) > Wrap words to a specified length. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save word-wrap ``` ## Usage ```js var wrap = require('word-wrap'); wrap('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'); ``` Results in: ``` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ``` ## Options ![image](https://cloud.githubusercontent.com/assets/383994/6543728/7a381c08-c4f6-11e4-8b7d-b6ba197569c9.png) ### options.width Type: `Number` Default: `50` The width of the text before wrapping to a new line. **Example:** ```js wrap(str, {width: 60}); ``` ### options.indent Type: `String` Default: `` (two spaces) The string to use at the beginning of each line. **Example:** ```js wrap(str, {indent: ' '}); ``` ### options.newline Type: `String` Default: `\n` The string to use at the end of each line. **Example:** ```js wrap(str, {newline: '\n\n'}); ``` ### options.escape Type: `function` Default: `function(str){return str;}` An escape function to run on each line after splitting them. **Example:** ```js var xmlescape = require('xml-escape'); wrap(str, { escape: function(string){ return xmlescape(string); } }); ``` ### options.trim Type: `Boolean` Default: `false` Trim trailing whitespace from the returned string. This option is included since `.trim()` would also strip the leading indentation from the first line. **Example:** ```js wrap(str, {trim: true}); ``` ### options.cut Type: `Boolean` Default: `false` Break a word between any two letters when the word is longer than the specified width. **Example:** ```js wrap(str, {cut: true}); ``` ## About ### Related projects * [common-words](https://www.npmjs.com/package/common-words): Updated list (JSON) of the 100 most common words in the English language. Useful for… [more](https://github.com/jonschlinkert/common-words) | [homepage](https://github.com/jonschlinkert/common-words "Updated list (JSON) of the 100 most common words in the English language. Useful for excluding these words from arrays.") * [shuffle-words](https://www.npmjs.com/package/shuffle-words): Shuffle the words in a string and optionally the letters in each word using the… [more](https://github.com/jonschlinkert/shuffle-words) | [homepage](https://github.com/jonschlinkert/shuffle-words "Shuffle the words in a string and optionally the letters in each word using the Fisher-Yates algorithm. Useful for creating test fixtures, benchmarking samples, etc.") * [unique-words](https://www.npmjs.com/package/unique-words): Return the unique words in a string or array. | [homepage](https://github.com/jonschlinkert/unique-words "Return the unique words in a string or array.") * [wordcount](https://www.npmjs.com/package/wordcount): Count the words in a string. Support for english, CJK and Cyrillic. | [homepage](https://github.com/jonschlinkert/wordcount "Count the words in a string. Support for english, CJK and Cyrillic.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 43 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [lordvlad](https://github.com/lordvlad) | | 2 | [hildjj](https://github.com/hildjj) | | 1 | [danilosampaio](https://github.com/danilosampaio) | | 1 | [2fd](https://github.com/2fd) | | 1 | [toddself](https://github.com/toddself) | | 1 | [wolfgang42](https://github.com/wolfgang42) | | 1 | [zachhale](https://github.com/zachhale) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 02, 2017._
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/word-wrap/README.md
README.md
# Validate XML Names and Qualified Names This package simply tells you whether or not a string matches the [`Name`](http://www.w3.org/TR/xml/#NT-Name) or [`QName`](http://www.w3.org/TR/xml-names/#NT-QName) productions in the XML Namespaces specification. We use it for implementing the [validate](https://dom.spec.whatwg.org/#validate) algorithm in jsdom, but you can use it for whatever you want. ## Usage This package's main module's default export takes a string and will return an object of the form `{ success, error }`, where `success` is a boolean and if it is `false`, then `error` is a string containing some hint as to where the match went wrong. ```js "use strict": var xnv = require("xml-name-validator"); var assert = require("assert"); // Will return { success: true, error: undefined } xnv.name("x"); xnv.name(":"); xnv.name("a:0"); xnv.name("a:b:c"); // Will return { success: false, error: <an explanatory string> } xnv.name("\\"); xnv.name("'"); xnv.name("0"); xnv.name("a!"); // Will return { success: true, error: undefined } xnv.qname("x"); xnv.qname("a0"); xnv.qname("a:b"); // Will return { success: false, error: <an explanatory string> } xnv.qname(":a"); xnv.qname(":b"); xnv.qname("a:b:c"); xnv.qname("a:0"); ```
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/xml-name-validator/README.md
README.md
module.exports = (function(){function _waka(parser, startRule) { if(startRule && ! parser.rules[startRule]) throw new Error('start rule missing: ' + JSON.stringify(startRule)) return { getState: function() { return parser.state }, getTrace: function(message) { return (message ? message + '\n' : '') + parser.state.traceLine() }, exec: function(input) { if(! startRule) throw new Error('no start rule given') parser.state.setInput(input) try { var value = parser.rules[startRule]() } catch(err) { var error = err } if(error == null) { if(! parser.state.adv || ! parser.state.isEOF()) var error = new Error('Unexpected syntax in top') } return { success: error == null, value: ! error ? value : undefined, error: error } }, startWith: function(rule) { return _waka(parser, rule) }, } }; return _waka((function(){'use strict'; var _rules={}; _rules.NameStartChar = function() { var _R=_P.match(":"); if(!_P.adv){ _P.adv=true; var $0=_P.cur(); if($0==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("A"<=$0&&$0<="Z"); } } if(!_P.adv){ _P.adv=true; var _R=_P.match("_"); } if(!_P.adv){ _P.adv=true; var $1=_P.cur(); if($1==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("a"<=$1&&$1<="z"); } } if(!_P.adv){ _P.adv=true; var $2=_P.cur(); if($2==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u00C0"<=$2&&$2<="\u00D6"); } } if(!_P.adv){ _P.adv=true; var $3=_P.cur(); if($3==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u00D8"<=$3&&$3<="\u00F6"); } } if(!_P.adv){ _P.adv=true; var $4=_P.cur(); if($4==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u00F8"<=$4&&$4<="\u02FF"); } } if(!_P.adv){ _P.adv=true; var $5=_P.cur(); if($5==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u0370"<=$5&&$5<="\u037D"); } } if(!_P.adv){ _P.adv=true; var $6=_P.cur(); if($6==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u037F"<=$6&&$6<="\u1FFF"); } } if(!_P.adv){ _P.adv=true; var $7=_P.cur(); if($7==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u200C"<=$7&&$7<="\u200D"); } } if(!_P.adv){ _P.adv=true; var $8=_P.cur(); if($8==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u2070"<=$8&&$8<="\u218F"); } } if(!_P.adv){ _P.adv=true; var $9=_P.cur(); if($9==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u2C00"<=$9&&$9<="\u2FEF"); } } if(!_P.adv){ _P.adv=true; var $a=_P.cur(); if($a==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u3001"<=$a&&$a<="\uD7FF"); } } if(!_P.adv){ _P.adv=true; var $b=_P.cur(); if($b==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\uF900"<=$b&&$b<="\uFDCF"); } } if(!_P.adv){ _P.adv=true; var $c=_P.cur(); if($c==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\uFDF0"<=$c&&$c<="\uFFFD"); } } if(!_P.adv){ _P.adv=true; $d:{var $e=_P.pos; var $f=_P.cur(); if($f==null){_P.adv=false; null; }else{ _P.step("\uD800"<=$f&&$f<="\uDB7F"); } if(!_P.adv) break $d; var $g=_P.cur(); if($g==null){_P.adv=false; null; }else{ _P.step("\uDC00"<=$g&&$g<="\uDFFF"); } var _R=_P.doc.substring($e,_P.pos); } if(!_P.adv) _P.pos=$e; } return _R; } _rules.NameChar = function() { var _R=_rules.NameStartChar(); if(!_P.adv){ _P.adv=true; var _R=_P.match("-"); } if(!_P.adv){ _P.adv=true; var _R=_P.match("."); } if(!_P.adv){ _P.adv=true; var $0=_P.cur(); if($0==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("0"<=$0&&$0<="9"); } } if(!_P.adv){ _P.adv=true; var _R=_P.match("\u00B7"); } if(!_P.adv){ _P.adv=true; var $1=_P.cur(); if($1==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u0300"<=$1&&$1<="\u036F"); } } if(!_P.adv){ _P.adv=true; var $2=_P.cur(); if($2==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u203F"<=$2&&$2<="\u2040"); } } return _R; } _rules.Name = function() { $0:{var $1=_P.pos; _rules.NameStartChar(); if(!_P.adv) break $0; var $2=false; for(;;) { _rules.NameChar(); if(!_P.adv) break; $2=true; }; _P.adv=true; var _R=_P.doc.substring($1,_P.pos); } if(!_P.adv) _P.pos=$1; return _R; } _rules.QName = function() { var _R=_rules.PrefixedName(); if(!_P.adv){ _P.adv=true; var _R=_rules.UnprefixedName(); } return _R; } _rules.PrefixedName = function() { $0:{var $1=_P.pos; _rules.Prefix(); if(!_P.adv) break $0; _P.match(":"); if(!_P.adv) break $0; _rules.LocalPart(); var _R=_P.doc.substring($1,_P.pos); } if(!_P.adv) _P.pos=$1; return _R; } _rules.UnprefixedName = function() { var _R=_rules.LocalPart(); return _R; } _rules.Prefix = function() { var _R=_rules.NCName(); return _R; } _rules.LocalPart = function() { var _R=_rules.NCName(); return _R; } _rules.NCNameStartChar = function() { var $0=_P.cur(); if($0==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("A"<=$0&&$0<="Z"); } if(!_P.adv){ _P.adv=true; var _R=_P.match("_"); } if(!_P.adv){ _P.adv=true; var $1=_P.cur(); if($1==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("a"<=$1&&$1<="z"); } } if(!_P.adv){ _P.adv=true; var $2=_P.cur(); if($2==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u00C0"<=$2&&$2<="\u00D6"); } } if(!_P.adv){ _P.adv=true; var $3=_P.cur(); if($3==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u00D8"<=$3&&$3<="\u00F6"); } } if(!_P.adv){ _P.adv=true; var $4=_P.cur(); if($4==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u00F8"<=$4&&$4<="\u02FF"); } } if(!_P.adv){ _P.adv=true; var $5=_P.cur(); if($5==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u0370"<=$5&&$5<="\u037D"); } } if(!_P.adv){ _P.adv=true; var $6=_P.cur(); if($6==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u037F"<=$6&&$6<="\u1FFF"); } } if(!_P.adv){ _P.adv=true; var $7=_P.cur(); if($7==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u200C"<=$7&&$7<="\u200D"); } } if(!_P.adv){ _P.adv=true; var $8=_P.cur(); if($8==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u2070"<=$8&&$8<="\u218F"); } } if(!_P.adv){ _P.adv=true; var $9=_P.cur(); if($9==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u2C00"<=$9&&$9<="\u2FEF"); } } if(!_P.adv){ _P.adv=true; var $a=_P.cur(); if($a==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u3001"<=$a&&$a<="\uD7FF"); } } if(!_P.adv){ _P.adv=true; var $b=_P.cur(); if($b==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\uF900"<=$b&&$b<="\uFDCF"); } } if(!_P.adv){ _P.adv=true; var $c=_P.cur(); if($c==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\uFDF0"<=$c&&$c<="\uFFFD"); } } if(!_P.adv){ _P.adv=true; $d:{var $e=_P.pos; var $f=_P.cur(); if($f==null){_P.adv=false; null; }else{ _P.step("\uD800"<=$f&&$f<="\uDB7F"); } if(!_P.adv) break $d; var $g=_P.cur(); if($g==null){_P.adv=false; null; }else{ _P.step("\uDC00"<=$g&&$g<="\uDFFF"); } var _R=_P.doc.substring($e,_P.pos); } if(!_P.adv) _P.pos=$e; } return _R; } _rules.NCNameChar = function() { var _R=_rules.NCNameStartChar(); if(!_P.adv){ _P.adv=true; var _R=_P.match("-"); } if(!_P.adv){ _P.adv=true; var _R=_P.match("."); } if(!_P.adv){ _P.adv=true; var $0=_P.cur(); if($0==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("0"<=$0&&$0<="9"); } } if(!_P.adv){ _P.adv=true; var _R=_P.match("\u00B7"); } if(!_P.adv){ _P.adv=true; var $1=_P.cur(); if($1==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u0300"<=$1&&$1<="\u036F"); } } if(!_P.adv){ _P.adv=true; var $2=_P.cur(); if($2==null){_P.adv=false; var _R=null; }else{ var _R=_P.step("\u203F"<=$2&&$2<="\u2040"); } } return _R; } _rules.NCName = function() { $0:{var $1=_P.pos; _rules.NCNameStartChar(); if(!_P.adv) break $0; var $2=false; for(;;) { _rules.NCNameChar(); if(!_P.adv) break; $2=true; }; _P.adv=true; var _R=_P.doc.substring($1,_P.pos); } if(!_P.adv) _P.pos=$1; return _R; } function ParserState() { this.doc = '' this.pos = 0 this.adv = true this.setInput = function(doc) { this.doc = doc this.pos = 0 this.adv = true } this.isEOF = function() { return this.pos == this.doc.length } this.cur = function() { return _P.doc[_P.pos] } this.match = function(str) { if(_P.adv = _P.doc.substr(_P.pos, str.length) == str) { _P.pos += str.length return str } } this.step = function(flag) { if(_P.adv = flag) { _P.pos++ return _P.doc[_P.pos - 1] } } this.unexpected = function(rule) { throw new Error('Unexpected syntax in ' + rule) } this.traceLine = function(pos) { if(! pos) pos = _P.pos var from = _P.doc.lastIndexOf('\n', pos), to = _P.doc.indexOf('\n', pos) if(from == -1) from = 0 else from++ if(to == -1) to = pos.length var lineNo = _P.doc.substring(0, from).split('\n').length var line = _P.doc.substring(from, to) var pointer = Array(200).join(' ').substr(0, pos - from) + '^^^' return ( 'Line ' + lineNo + ':\n' + line + '\n' + pointer ) } } var _P = new ParserState return { state: _P, rules: _rules, } })(),null)})()
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/xml-name-validator/lib/generated-parser.js
generated-parser.js
symbol-tree =========== [![Travis CI Build Status](https://api.travis-ci.org/jsdom/js-symbol-tree.svg?branch=master)](https://travis-ci.org/jsdom/js-symbol-tree) [![Coverage Status](https://coveralls.io/repos/github/jsdom/js-symbol-tree/badge.svg?branch=master)](https://coveralls.io/github/jsdom/js-symbol-tree?branch=master) Turn any collection of objects into its own efficient tree or linked list using `Symbol`. This library has been designed to provide an efficient backing data structure for DOM trees. You can also use this library as an efficient linked list. Any meta data is stored on your objects directly, which ensures any kind of insertion or deletion is performed in constant time. Because an ES6 `Symbol` is used, the meta data does not interfere with your object in any way. Node.js 4+, io.js and modern browsers are supported. Example ------- A linked list: ```javascript const SymbolTree = require('symbol-tree'); const tree = new SymbolTree(); let a = {foo: 'bar'}; // or `new Whatever()` let b = {foo: 'baz'}; let c = {foo: 'qux'}; tree.insertBefore(b, a); // insert a before b tree.insertAfter(b, c); // insert c after b console.log(tree.nextSibling(a) === b); console.log(tree.nextSibling(b) === c); console.log(tree.previousSibling(c) === b); tree.remove(b); console.log(tree.nextSibling(a) === c); ``` A tree: ```javascript const SymbolTree = require('symbol-tree'); const tree = new SymbolTree(); let parent = {}; let a = {}; let b = {}; let c = {}; tree.prependChild(parent, a); // insert a as the first child tree.appendChild(parent,c ); // insert c as the last child tree.insertAfter(a, b); // insert b after a, it now has the same parent as a console.log(tree.firstChild(parent) === a); console.log(tree.nextSibling(tree.firstChild(parent)) === b); console.log(tree.lastChild(parent) === c); let grandparent = {}; tree.prependChild(grandparent, parent); console.log(tree.firstChild(tree.firstChild(grandparent)) === a); ``` See [api.md](api.md) for more documentation. Testing ------- Make sure you install the dependencies first: npm install You can now run the unit tests by executing: npm test The line and branch coverage should be 100%. API Documentation ----------------- <a name="module_symbol-tree"></a> ## symbol-tree **Author**: Joris van der Wel <[email protected]> * [symbol-tree](#module_symbol-tree) * [SymbolTree](#exp_module_symbol-tree--SymbolTree) ⏏ * [new SymbolTree([description])](#new_module_symbol-tree--SymbolTree_new) * [.initialize(object)](#module_symbol-tree--SymbolTree+initialize) ⇒ <code>Object</code> * [.hasChildren(object)](#module_symbol-tree--SymbolTree+hasChildren) ⇒ <code>Boolean</code> * [.firstChild(object)](#module_symbol-tree--SymbolTree+firstChild) ⇒ <code>Object</code> * [.lastChild(object)](#module_symbol-tree--SymbolTree+lastChild) ⇒ <code>Object</code> * [.previousSibling(object)](#module_symbol-tree--SymbolTree+previousSibling) ⇒ <code>Object</code> * [.nextSibling(object)](#module_symbol-tree--SymbolTree+nextSibling) ⇒ <code>Object</code> * [.parent(object)](#module_symbol-tree--SymbolTree+parent) ⇒ <code>Object</code> * [.lastInclusiveDescendant(object)](#module_symbol-tree--SymbolTree+lastInclusiveDescendant) ⇒ <code>Object</code> * [.preceding(object, [options])](#module_symbol-tree--SymbolTree+preceding) ⇒ <code>Object</code> * [.following(object, [options])](#module_symbol-tree--SymbolTree+following) ⇒ <code>Object</code> * [.childrenToArray(parent, [options])](#module_symbol-tree--SymbolTree+childrenToArray) ⇒ <code>Array.&lt;Object&gt;</code> * [.ancestorsToArray(object, [options])](#module_symbol-tree--SymbolTree+ancestorsToArray) ⇒ <code>Array.&lt;Object&gt;</code> * [.treeToArray(root, [options])](#module_symbol-tree--SymbolTree+treeToArray) ⇒ <code>Array.&lt;Object&gt;</code> * [.childrenIterator(parent, [options])](#module_symbol-tree--SymbolTree+childrenIterator) ⇒ <code>Object</code> * [.previousSiblingsIterator(object)](#module_symbol-tree--SymbolTree+previousSiblingsIterator) ⇒ <code>Object</code> * [.nextSiblingsIterator(object)](#module_symbol-tree--SymbolTree+nextSiblingsIterator) ⇒ <code>Object</code> * [.ancestorsIterator(object)](#module_symbol-tree--SymbolTree+ancestorsIterator) ⇒ <code>Object</code> * [.treeIterator(root, options)](#module_symbol-tree--SymbolTree+treeIterator) ⇒ <code>Object</code> * [.index(child)](#module_symbol-tree--SymbolTree+index) ⇒ <code>Number</code> * [.childrenCount(parent)](#module_symbol-tree--SymbolTree+childrenCount) ⇒ <code>Number</code> * [.compareTreePosition(left, right)](#module_symbol-tree--SymbolTree+compareTreePosition) ⇒ <code>Number</code> * [.remove(removeObject)](#module_symbol-tree--SymbolTree+remove) ⇒ <code>Object</code> * [.insertBefore(referenceObject, newObject)](#module_symbol-tree--SymbolTree+insertBefore) ⇒ <code>Object</code> * [.insertAfter(referenceObject, newObject)](#module_symbol-tree--SymbolTree+insertAfter) ⇒ <code>Object</code> * [.prependChild(referenceObject, newObject)](#module_symbol-tree--SymbolTree+prependChild) ⇒ <code>Object</code> * [.appendChild(referenceObject, newObject)](#module_symbol-tree--SymbolTree+appendChild) ⇒ <code>Object</code> <a name="exp_module_symbol-tree--SymbolTree"></a> ### SymbolTree ⏏ **Kind**: Exported class <a name="new_module_symbol-tree--SymbolTree_new"></a> #### new SymbolTree([description]) | Param | Type | Default | Description | | --- | --- | --- | --- | | [description] | <code>string</code> | <code>&quot;&#x27;SymbolTree data&#x27;&quot;</code> | Description used for the Symbol | <a name="module_symbol-tree--SymbolTree+initialize"></a> #### symbolTree.initialize(object) ⇒ <code>Object</code> You can use this function to (optionally) initialize an object right after its creation, to take advantage of V8's fast properties. Also useful if you would like to freeze your object. `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - object | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+hasChildren"></a> #### symbolTree.hasChildren(object) ⇒ <code>Boolean</code> Returns `true` if the object has any children. Otherwise it returns `false`. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+firstChild"></a> #### symbolTree.firstChild(object) ⇒ <code>Object</code> Returns the first child of the given object. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+lastChild"></a> #### symbolTree.lastChild(object) ⇒ <code>Object</code> Returns the last child of the given object. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+previousSibling"></a> #### symbolTree.previousSibling(object) ⇒ <code>Object</code> Returns the previous sibling of the given object. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+nextSibling"></a> #### symbolTree.nextSibling(object) ⇒ <code>Object</code> Returns the next sibling of the given object. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+parent"></a> #### symbolTree.parent(object) ⇒ <code>Object</code> Return the parent of the given object. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+lastInclusiveDescendant"></a> #### symbolTree.lastInclusiveDescendant(object) ⇒ <code>Object</code> Find the inclusive descendant that is last in tree order of the given object. * `O(n)` (worst case) where `n` is the depth of the subtree of `object` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+preceding"></a> #### symbolTree.preceding(object, [options]) ⇒ <code>Object</code> Find the preceding object (A) of the given object (B). An object A is preceding an object B if A and B are in the same tree and A comes before B in tree order. * `O(n)` (worst case) * `O(1)` (amortized when walking the entire tree) **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | Description | | --- | --- | --- | | object | <code>Object</code> | | | [options] | <code>Object</code> | | | [options.root] | <code>Object</code> | If set, `root` must be an inclusive ancestor of the return value (or else null is returned). This check _assumes_ that `root` is also an inclusive ancestor of the given `object` | <a name="module_symbol-tree--SymbolTree+following"></a> #### symbolTree.following(object, [options]) ⇒ <code>Object</code> Find the following object (A) of the given object (B). An object A is following an object B if A and B are in the same tree and A comes after B in tree order. * `O(n)` (worst case) where `n` is the amount of objects in the entire tree * `O(1)` (amortized when walking the entire tree) **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | Default | Description | | --- | --- | --- | --- | | object | <code>Object</code> | | | | [options] | <code>Object</code> | | | | [options.root] | <code>Object</code> | | If set, `root` must be an inclusive ancestor of the return value (or else null is returned). This check _assumes_ that `root` is also an inclusive ancestor of the given `object` | | [options.skipChildren] | <code>Boolean</code> | <code>false</code> | If set, ignore the children of `object` | <a name="module_symbol-tree--SymbolTree+childrenToArray"></a> #### symbolTree.childrenToArray(parent, [options]) ⇒ <code>Array.&lt;Object&gt;</code> Append all children of the given object to an array. * `O(n)` where `n` is the amount of children of the given `parent` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | Default | Description | | --- | --- | --- | --- | | parent | <code>Object</code> | | | | [options] | <code>Object</code> | | | | [options.array] | <code>Array.&lt;Object&gt;</code> | <code>[]</code> | | | [options.filter] | <code>function</code> | | Function to test each object before it is added to the array. Invoked with arguments (object). Should return `true` if an object is to be included. | | [options.thisArg] | <code>\*</code> | | Value to use as `this` when executing `filter`. | <a name="module_symbol-tree--SymbolTree+ancestorsToArray"></a> #### symbolTree.ancestorsToArray(object, [options]) ⇒ <code>Array.&lt;Object&gt;</code> Append all inclusive ancestors of the given object to an array. * `O(n)` where `n` is the amount of ancestors of the given `object` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | Default | Description | | --- | --- | --- | --- | | object | <code>Object</code> | | | | [options] | <code>Object</code> | | | | [options.array] | <code>Array.&lt;Object&gt;</code> | <code>[]</code> | | | [options.filter] | <code>function</code> | | Function to test each object before it is added to the array. Invoked with arguments (object). Should return `true` if an object is to be included. | | [options.thisArg] | <code>\*</code> | | Value to use as `this` when executing `filter`. | <a name="module_symbol-tree--SymbolTree+treeToArray"></a> #### symbolTree.treeToArray(root, [options]) ⇒ <code>Array.&lt;Object&gt;</code> Append all descendants of the given object to an array (in tree order). * `O(n)` where `n` is the amount of objects in the sub-tree of the given `object` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | Default | Description | | --- | --- | --- | --- | | root | <code>Object</code> | | | | [options] | <code>Object</code> | | | | [options.array] | <code>Array.&lt;Object&gt;</code> | <code>[]</code> | | | [options.filter] | <code>function</code> | | Function to test each object before it is added to the array. Invoked with arguments (object). Should return `true` if an object is to be included. | | [options.thisArg] | <code>\*</code> | | Value to use as `this` when executing `filter`. | <a name="module_symbol-tree--SymbolTree+childrenIterator"></a> #### symbolTree.childrenIterator(parent, [options]) ⇒ <code>Object</code> Iterate over all children of the given object * `O(1)` for a single iteration **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - An iterable iterator (ES6) | Param | Type | Default | | --- | --- | --- | | parent | <code>Object</code> | | | [options] | <code>Object</code> | | | [options.reverse] | <code>Boolean</code> | <code>false</code> | <a name="module_symbol-tree--SymbolTree+previousSiblingsIterator"></a> #### symbolTree.previousSiblingsIterator(object) ⇒ <code>Object</code> Iterate over all the previous siblings of the given object. (in reverse tree order) * `O(1)` for a single iteration **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - An iterable iterator (ES6) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+nextSiblingsIterator"></a> #### symbolTree.nextSiblingsIterator(object) ⇒ <code>Object</code> Iterate over all the next siblings of the given object. (in tree order) * `O(1)` for a single iteration **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - An iterable iterator (ES6) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+ancestorsIterator"></a> #### symbolTree.ancestorsIterator(object) ⇒ <code>Object</code> Iterate over all inclusive ancestors of the given object * `O(1)` for a single iteration **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - An iterable iterator (ES6) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+treeIterator"></a> #### symbolTree.treeIterator(root, options) ⇒ <code>Object</code> Iterate over all descendants of the given object (in tree order). Where `n` is the amount of objects in the sub-tree of the given `root`: * `O(n)` (worst case for a single iteration) * `O(n)` (amortized, when completing the iterator) **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - An iterable iterator (ES6) | Param | Type | Default | | --- | --- | --- | | root | <code>Object</code> | | | options | <code>Object</code> | | | [options.reverse] | <code>Boolean</code> | <code>false</code> | <a name="module_symbol-tree--SymbolTree+index"></a> #### symbolTree.index(child) ⇒ <code>Number</code> Find the index of the given object (the number of preceding siblings). * `O(n)` where `n` is the amount of preceding siblings * `O(1)` (amortized, if the tree is not modified) **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Number</code> - The number of preceding siblings, or -1 if the object has no parent | Param | Type | | --- | --- | | child | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+childrenCount"></a> #### symbolTree.childrenCount(parent) ⇒ <code>Number</code> Calculate the number of children. * `O(n)` where `n` is the amount of children * `O(1)` (amortized, if the tree is not modified) **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | parent | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+compareTreePosition"></a> #### symbolTree.compareTreePosition(left, right) ⇒ <code>Number</code> Compare the position of an object relative to another object. A bit set is returned: <ul> <li>DISCONNECTED : 1</li> <li>PRECEDING : 2</li> <li>FOLLOWING : 4</li> <li>CONTAINS : 8</li> <li>CONTAINED_BY : 16</li> </ul> The semantics are the same as compareDocumentPosition in DOM, with the exception that DISCONNECTED never occurs with any other bit. where `n` and `m` are the amount of ancestors of `left` and `right`; where `o` is the amount of children of the lowest common ancestor of `left` and `right`: * `O(n + m + o)` (worst case) * `O(n + m)` (amortized, if the tree is not modified) **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | left | <code>Object</code> | | right | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+remove"></a> #### symbolTree.remove(removeObject) ⇒ <code>Object</code> Remove the object from this tree. Has no effect if already removed. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - removeObject | Param | Type | | --- | --- | | removeObject | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+insertBefore"></a> #### symbolTree.insertBefore(referenceObject, newObject) ⇒ <code>Object</code> Insert the given object before the reference object. `newObject` is now the previous sibling of `referenceObject`. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - newObject **Throws**: - <code>Error</code> If the newObject is already present in this SymbolTree | Param | Type | | --- | --- | | referenceObject | <code>Object</code> | | newObject | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+insertAfter"></a> #### symbolTree.insertAfter(referenceObject, newObject) ⇒ <code>Object</code> Insert the given object after the reference object. `newObject` is now the next sibling of `referenceObject`. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - newObject **Throws**: - <code>Error</code> If the newObject is already present in this SymbolTree | Param | Type | | --- | --- | | referenceObject | <code>Object</code> | | newObject | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+prependChild"></a> #### symbolTree.prependChild(referenceObject, newObject) ⇒ <code>Object</code> Insert the given object as the first child of the given reference object. `newObject` is now the first child of `referenceObject`. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - newObject **Throws**: - <code>Error</code> If the newObject is already present in this SymbolTree | Param | Type | | --- | --- | | referenceObject | <code>Object</code> | | newObject | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+appendChild"></a> #### symbolTree.appendChild(referenceObject, newObject) ⇒ <code>Object</code> Insert the given object as the last child of the given reference object. `newObject` is now the last child of `referenceObject`. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - newObject **Throws**: - <code>Error</code> If the newObject is already present in this SymbolTree | Param | Type | | --- | --- | | referenceObject | <code>Object</code> | | newObject | <code>Object</code> |
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/symbol-tree/README.md
README.md
'use strict'; /** * @module symbol-tree * @author Joris van der Wel <[email protected]> */ const SymbolTreeNode = require('symbol-tree/lib/SymbolTreeNode'); const TreePosition = require('symbol-tree/lib/TreePosition'); const TreeIterator = require('symbol-tree/lib/TreeIterator'); function returnTrue() { return true; } function reverseArrayIndex(array, reverseIndex) { return array[array.length - 1 - reverseIndex]; // no need to check `index >= 0` } class SymbolTree { /** * @constructor * @alias module:symbol-tree * @param {string} [description='SymbolTree data'] Description used for the Symbol */ constructor(description) { this.symbol = Symbol(description || 'SymbolTree data'); } /** * You can use this function to (optionally) initialize an object right after its creation, * to take advantage of V8's fast properties. Also useful if you would like to * freeze your object. * * `O(1)` * * @method * @alias module:symbol-tree#initialize * @param {Object} object * @return {Object} object */ initialize(object) { this._node(object); return object; } _node(object) { if (!object) { return null; } const node = object[this.symbol]; if (node) { return node; } return (object[this.symbol] = new SymbolTreeNode()); } /** * Returns `true` if the object has any children. Otherwise it returns `false`. * * * `O(1)` * * @method hasChildren * @memberOf module:symbol-tree# * @param {Object} object * @return {Boolean} */ hasChildren(object) { return this._node(object).hasChildren; } /** * Returns the first child of the given object. * * * `O(1)` * * @method firstChild * @memberOf module:symbol-tree# * @param {Object} object * @return {Object} */ firstChild(object) { return this._node(object).firstChild; } /** * Returns the last child of the given object. * * * `O(1)` * * @method lastChild * @memberOf module:symbol-tree# * @param {Object} object * @return {Object} */ lastChild(object) { return this._node(object).lastChild; } /** * Returns the previous sibling of the given object. * * * `O(1)` * * @method previousSibling * @memberOf module:symbol-tree# * @param {Object} object * @return {Object} */ previousSibling(object) { return this._node(object).previousSibling; } /** * Returns the next sibling of the given object. * * * `O(1)` * * @method nextSibling * @memberOf module:symbol-tree# * @param {Object} object * @return {Object} */ nextSibling(object) { return this._node(object).nextSibling; } /** * Return the parent of the given object. * * * `O(1)` * * @method parent * @memberOf module:symbol-tree# * @param {Object} object * @return {Object} */ parent(object) { return this._node(object).parent; } /** * Find the inclusive descendant that is last in tree order of the given object. * * * `O(n)` (worst case) where `n` is the depth of the subtree of `object` * * @method lastInclusiveDescendant * @memberOf module:symbol-tree# * @param {Object} object * @return {Object} */ lastInclusiveDescendant(object) { let lastChild; let current = object; while ((lastChild = this._node(current).lastChild)) { current = lastChild; } return current; } /** * Find the preceding object (A) of the given object (B). * An object A is preceding an object B if A and B are in the same tree * and A comes before B in tree order. * * * `O(n)` (worst case) * * `O(1)` (amortized when walking the entire tree) * * @method preceding * @memberOf module:symbol-tree# * @param {Object} object * @param {Object} [options] * @param {Object} [options.root] If set, `root` must be an inclusive ancestor * of the return value (or else null is returned). This check _assumes_ * that `root` is also an inclusive ancestor of the given `object` * @return {?Object} */ preceding(object, options) { const treeRoot = options && options.root; if (object === treeRoot) { return null; } const previousSibling = this._node(object).previousSibling; if (previousSibling) { return this.lastInclusiveDescendant(previousSibling); } // if there is no previous sibling return the parent (might be null) return this._node(object).parent; } /** * Find the following object (A) of the given object (B). * An object A is following an object B if A and B are in the same tree * and A comes after B in tree order. * * * `O(n)` (worst case) where `n` is the amount of objects in the entire tree * * `O(1)` (amortized when walking the entire tree) * * @method following * @memberOf module:symbol-tree# * @param {!Object} object * @param {Object} [options] * @param {Object} [options.root] If set, `root` must be an inclusive ancestor * of the return value (or else null is returned). This check _assumes_ * that `root` is also an inclusive ancestor of the given `object` * @param {Boolean} [options.skipChildren=false] If set, ignore the children of `object` * @return {?Object} */ following(object, options) { const treeRoot = options && options.root; const skipChildren = options && options.skipChildren; const firstChild = !skipChildren && this._node(object).firstChild; if (firstChild) { return firstChild; } let current = object; do { if (current === treeRoot) { return null; } const nextSibling = this._node(current).nextSibling; if (nextSibling) { return nextSibling; } current = this._node(current).parent; } while (current); return null; } /** * Append all children of the given object to an array. * * * `O(n)` where `n` is the amount of children of the given `parent` * * @method childrenToArray * @memberOf module:symbol-tree# * @param {Object} parent * @param {Object} [options] * @param {Object[]} [options.array=[]] * @param {Function} [options.filter] Function to test each object before it is added to the array. * Invoked with arguments (object). Should return `true` if an object * is to be included. * @param {*} [options.thisArg] Value to use as `this` when executing `filter`. * @return {Object[]} */ childrenToArray(parent, options) { const array = (options && options.array) || []; const filter = (options && options.filter) || returnTrue; const thisArg = (options && options.thisArg) || undefined; const parentNode = this._node(parent); let object = parentNode.firstChild; let index = 0; while (object) { const node = this._node(object); node.setCachedIndex(parentNode, index); if (filter.call(thisArg, object)) { array.push(object); } object = node.nextSibling; ++index; } return array; } /** * Append all inclusive ancestors of the given object to an array. * * * `O(n)` where `n` is the amount of ancestors of the given `object` * * @method ancestorsToArray * @memberOf module:symbol-tree# * @param {Object} object * @param {Object} [options] * @param {Object[]} [options.array=[]] * @param {Function} [options.filter] Function to test each object before it is added to the array. * Invoked with arguments (object). Should return `true` if an object * is to be included. * @param {*} [options.thisArg] Value to use as `this` when executing `filter`. * @return {Object[]} */ ancestorsToArray(object, options) { const array = (options && options.array) || []; const filter = (options && options.filter) || returnTrue; const thisArg = (options && options.thisArg) || undefined; let ancestor = object; while (ancestor) { if (filter.call(thisArg, ancestor)) { array.push(ancestor); } ancestor = this._node(ancestor).parent; } return array; } /** * Append all descendants of the given object to an array (in tree order). * * * `O(n)` where `n` is the amount of objects in the sub-tree of the given `object` * * @method treeToArray * @memberOf module:symbol-tree# * @param {Object} root * @param {Object} [options] * @param {Object[]} [options.array=[]] * @param {Function} [options.filter] Function to test each object before it is added to the array. * Invoked with arguments (object). Should return `true` if an object * is to be included. * @param {*} [options.thisArg] Value to use as `this` when executing `filter`. * @return {Object[]} */ treeToArray(root, options) { const array = (options && options.array) || []; const filter = (options && options.filter) || returnTrue; const thisArg = (options && options.thisArg) || undefined; let object = root; while (object) { if (filter.call(thisArg, object)) { array.push(object); } object = this.following(object, {root: root}); } return array; } /** * Iterate over all children of the given object * * * `O(1)` for a single iteration * * @method childrenIterator * @memberOf module:symbol-tree# * @param {Object} parent * @param {Object} [options] * @param {Boolean} [options.reverse=false] * @return {Object} An iterable iterator (ES6) */ childrenIterator(parent, options) { const reverse = options && options.reverse; const parentNode = this._node(parent); return new TreeIterator( this, parent, reverse ? parentNode.lastChild : parentNode.firstChild, reverse ? TreeIterator.PREV : TreeIterator.NEXT ); } /** * Iterate over all the previous siblings of the given object. (in reverse tree order) * * * `O(1)` for a single iteration * * @method previousSiblingsIterator * @memberOf module:symbol-tree# * @param {Object} object * @return {Object} An iterable iterator (ES6) */ previousSiblingsIterator(object) { return new TreeIterator( this, object, this._node(object).previousSibling, TreeIterator.PREV ); } /** * Iterate over all the next siblings of the given object. (in tree order) * * * `O(1)` for a single iteration * * @method nextSiblingsIterator * @memberOf module:symbol-tree# * @param {Object} object * @return {Object} An iterable iterator (ES6) */ nextSiblingsIterator(object) { return new TreeIterator( this, object, this._node(object).nextSibling, TreeIterator.NEXT ); } /** * Iterate over all inclusive ancestors of the given object * * * `O(1)` for a single iteration * * @method ancestorsIterator * @memberOf module:symbol-tree# * @param {Object} object * @return {Object} An iterable iterator (ES6) */ ancestorsIterator(object) { return new TreeIterator( this, object, object, TreeIterator.PARENT ); } /** * Iterate over all descendants of the given object (in tree order). * * Where `n` is the amount of objects in the sub-tree of the given `root`: * * * `O(n)` (worst case for a single iteration) * * `O(n)` (amortized, when completing the iterator) * * @method treeIterator * @memberOf module:symbol-tree# * @param {Object} root * @param {Object} options * @param {Boolean} [options.reverse=false] * @return {Object} An iterable iterator (ES6) */ treeIterator(root, options) { const reverse = options && options.reverse; return new TreeIterator( this, root, reverse ? this.lastInclusiveDescendant(root) : root, reverse ? TreeIterator.PRECEDING : TreeIterator.FOLLOWING ); } /** * Find the index of the given object (the number of preceding siblings). * * * `O(n)` where `n` is the amount of preceding siblings * * `O(1)` (amortized, if the tree is not modified) * * @method index * @memberOf module:symbol-tree# * @param {Object} child * @return {Number} The number of preceding siblings, or -1 if the object has no parent */ index(child) { const childNode = this._node(child); const parentNode = this._node(childNode.parent); if (!parentNode) { // In principal, you could also find out the number of preceding siblings // for objects that do not have a parent. This method limits itself only to // objects that have a parent because that lets us optimize more. return -1; } let currentIndex = childNode.getCachedIndex(parentNode); if (currentIndex >= 0) { return currentIndex; } currentIndex = 0; let object = parentNode.firstChild; if (parentNode.childIndexCachedUpTo) { const cachedUpToNode = this._node(parentNode.childIndexCachedUpTo); object = cachedUpToNode.nextSibling; currentIndex = cachedUpToNode.getCachedIndex(parentNode) + 1; } while (object) { const node = this._node(object); node.setCachedIndex(parentNode, currentIndex); if (object === child) { break; } ++currentIndex; object = node.nextSibling; } parentNode.childIndexCachedUpTo = child; return currentIndex; } /** * Calculate the number of children. * * * `O(n)` where `n` is the amount of children * * `O(1)` (amortized, if the tree is not modified) * * @method childrenCount * @memberOf module:symbol-tree# * @param {Object} parent * @return {Number} */ childrenCount(parent) { const parentNode = this._node(parent); if (!parentNode.lastChild) { return 0; } return this.index(parentNode.lastChild) + 1; } /** * Compare the position of an object relative to another object. A bit set is returned: * * <ul> * <li>DISCONNECTED : 1</li> * <li>PRECEDING : 2</li> * <li>FOLLOWING : 4</li> * <li>CONTAINS : 8</li> * <li>CONTAINED_BY : 16</li> * </ul> * * The semantics are the same as compareDocumentPosition in DOM, with the exception that * DISCONNECTED never occurs with any other bit. * * where `n` and `m` are the amount of ancestors of `left` and `right`; * where `o` is the amount of children of the lowest common ancestor of `left` and `right`: * * * `O(n + m + o)` (worst case) * * `O(n + m)` (amortized, if the tree is not modified) * * @method compareTreePosition * @memberOf module:symbol-tree# * @param {Object} left * @param {Object} right * @return {Number} */ compareTreePosition(left, right) { // In DOM terms: // left = reference / context object // right = other if (left === right) { return 0; } /* jshint -W016 */ const leftAncestors = []; { // inclusive let leftAncestor = left; while (leftAncestor) { if (leftAncestor === right) { return TreePosition.CONTAINS | TreePosition.PRECEDING; // other is ancestor of reference } leftAncestors.push(leftAncestor); leftAncestor = this.parent(leftAncestor); } } const rightAncestors = []; { let rightAncestor = right; while (rightAncestor) { if (rightAncestor === left) { return TreePosition.CONTAINED_BY | TreePosition.FOLLOWING; } rightAncestors.push(rightAncestor); rightAncestor = this.parent(rightAncestor); } } const root = reverseArrayIndex(leftAncestors, 0); if (!root || root !== reverseArrayIndex(rightAncestors, 0)) { // note: unlike DOM, preceding / following is not set here return TreePosition.DISCONNECTED; } // find the lowest common ancestor let commonAncestorIndex = 0; const ancestorsMinLength = Math.min(leftAncestors.length, rightAncestors.length); for (let i = 0; i < ancestorsMinLength; ++i) { const leftAncestor = reverseArrayIndex(leftAncestors, i); const rightAncestor = reverseArrayIndex(rightAncestors, i); if (leftAncestor !== rightAncestor) { break; } commonAncestorIndex = i; } // indexes within the common ancestor const leftIndex = this.index(reverseArrayIndex(leftAncestors, commonAncestorIndex + 1)); const rightIndex = this.index(reverseArrayIndex(rightAncestors, commonAncestorIndex + 1)); return rightIndex < leftIndex ? TreePosition.PRECEDING : TreePosition.FOLLOWING; } /** * Remove the object from this tree. * Has no effect if already removed. * * * `O(1)` * * @method remove * @memberOf module:symbol-tree# * @param {Object} removeObject * @return {Object} removeObject */ remove(removeObject) { const removeNode = this._node(removeObject); const parentNode = this._node(removeNode.parent); const prevNode = this._node(removeNode.previousSibling); const nextNode = this._node(removeNode.nextSibling); if (parentNode) { if (parentNode.firstChild === removeObject) { parentNode.firstChild = removeNode.nextSibling; } if (parentNode.lastChild === removeObject) { parentNode.lastChild = removeNode.previousSibling; } } if (prevNode) { prevNode.nextSibling = removeNode.nextSibling; } if (nextNode) { nextNode.previousSibling = removeNode.previousSibling; } removeNode.parent = null; removeNode.previousSibling = null; removeNode.nextSibling = null; removeNode.cachedIndex = -1; removeNode.cachedIndexVersion = NaN; if (parentNode) { parentNode.childrenChanged(); } return removeObject; } /** * Insert the given object before the reference object. * `newObject` is now the previous sibling of `referenceObject`. * * * `O(1)` * * @method insertBefore * @memberOf module:symbol-tree# * @param {Object} referenceObject * @param {Object} newObject * @throws {Error} If the newObject is already present in this SymbolTree * @return {Object} newObject */ insertBefore(referenceObject, newObject) { const referenceNode = this._node(referenceObject); const prevNode = this._node(referenceNode.previousSibling); const newNode = this._node(newObject); const parentNode = this._node(referenceNode.parent); if (newNode.isAttached) { throw Error('Given object is already present in this SymbolTree, remove it first'); } newNode.parent = referenceNode.parent; newNode.previousSibling = referenceNode.previousSibling; newNode.nextSibling = referenceObject; referenceNode.previousSibling = newObject; if (prevNode) { prevNode.nextSibling = newObject; } if (parentNode && parentNode.firstChild === referenceObject) { parentNode.firstChild = newObject; } if (parentNode) { parentNode.childrenChanged(); } return newObject; } /** * Insert the given object after the reference object. * `newObject` is now the next sibling of `referenceObject`. * * * `O(1)` * * @method insertAfter * @memberOf module:symbol-tree# * @param {Object} referenceObject * @param {Object} newObject * @throws {Error} If the newObject is already present in this SymbolTree * @return {Object} newObject */ insertAfter(referenceObject, newObject) { const referenceNode = this._node(referenceObject); const nextNode = this._node(referenceNode.nextSibling); const newNode = this._node(newObject); const parentNode = this._node(referenceNode.parent); if (newNode.isAttached) { throw Error('Given object is already present in this SymbolTree, remove it first'); } newNode.parent = referenceNode.parent; newNode.previousSibling = referenceObject; newNode.nextSibling = referenceNode.nextSibling; referenceNode.nextSibling = newObject; if (nextNode) { nextNode.previousSibling = newObject; } if (parentNode && parentNode.lastChild === referenceObject) { parentNode.lastChild = newObject; } if (parentNode) { parentNode.childrenChanged(); } return newObject; } /** * Insert the given object as the first child of the given reference object. * `newObject` is now the first child of `referenceObject`. * * * `O(1)` * * @method prependChild * @memberOf module:symbol-tree# * @param {Object} referenceObject * @param {Object} newObject * @throws {Error} If the newObject is already present in this SymbolTree * @return {Object} newObject */ prependChild(referenceObject, newObject) { const referenceNode = this._node(referenceObject); const newNode = this._node(newObject); if (newNode.isAttached) { throw Error('Given object is already present in this SymbolTree, remove it first'); } if (referenceNode.hasChildren) { this.insertBefore(referenceNode.firstChild, newObject); } else { newNode.parent = referenceObject; referenceNode.firstChild = newObject; referenceNode.lastChild = newObject; referenceNode.childrenChanged(); } return newObject; } /** * Insert the given object as the last child of the given reference object. * `newObject` is now the last child of `referenceObject`. * * * `O(1)` * * @method appendChild * @memberOf module:symbol-tree# * @param {Object} referenceObject * @param {Object} newObject * @throws {Error} If the newObject is already present in this SymbolTree * @return {Object} newObject */ appendChild(referenceObject, newObject) { const referenceNode = this._node(referenceObject); const newNode = this._node(newObject); if (newNode.isAttached) { throw Error('Given object is already present in this SymbolTree, remove it first'); } if (referenceNode.hasChildren) { this.insertAfter(referenceNode.lastChild, newObject); } else { newNode.parent = referenceObject; referenceNode.firstChild = newObject; referenceNode.lastChild = newObject; referenceNode.childrenChanged(); } return newObject; } } module.exports = SymbolTree; SymbolTree.TreePosition = TreePosition;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/symbol-tree/lib/SymbolTree.js
SymbolTree.js
CSSOM.js is a CSS parser written in pure JavaScript. It is also a partial implementation of [CSS Object Model](http://dev.w3.org/csswg/cssom/). CSSOM.parse("body {color: black}") -> { cssRules: [ { selectorText: "body", style: { 0: "color", color: "black", length: 1 } } ] } ## [Parser demo](http://nv.github.com/CSSOM/docs/parse.html) Works well in Google Chrome 6+, Safari 5+, Firefox 3.6+, Opera 10.63+. Doesn't work in IE < 9 because of unsupported getters/setters. To use CSSOM.js in the browser you might want to build a one-file version that exposes a single `CSSOM` global variable: ➤ git clone https://github.com/NV/CSSOM.git ➤ cd CSSOM ➤ node build.js build/CSSOM.js is done To use it with Node.js or any other CommonJS loader: ➤ npm install cssom ## Don’t use it if... You parse CSS to mungle, minify or reformat code like this: ```css div { background: gray; background: linear-gradient(to bottom, white 0%, black 100%); } ``` This pattern is often used to give browsers that don’t understand linear gradients a fallback solution (e.g. gray color in the example). In CSSOM, `background: gray` [gets overwritten](http://nv.github.io/CSSOM/docs/parse.html#css=div%20%7B%0A%20%20%20%20%20%20background%3A%20gray%3B%0A%20%20%20%20background%3A%20linear-gradient(to%20bottom%2C%20white%200%25%2C%20black%20100%25)%3B%0A%7D). It doesn't get preserved. If you do CSS mungling, minification, image inlining, and such, CSSOM.js is no good for you, considere using one of the following: * [postcss](https://github.com/postcss/postcss) * [reworkcss/css](https://github.com/reworkcss/css) * [csso](https://github.com/css/csso) * [mensch](https://github.com/brettstimmerman/mensch) ## [Tests](http://nv.github.com/CSSOM/spec/) To run tests locally: ➤ git submodule init ➤ git submodule update ## [Who uses CSSOM.js](https://github.com/NV/CSSOM/wiki/Who-uses-CSSOM.js)
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssom/README.mdown
README.mdown
var CSSOM = { StyleSheet: require("cssom/lib/StyleSheet").StyleSheet, CSSStyleRule: require("cssom/lib/CSSStyleRule").CSSStyleRule }; ///CommonJS /** * @constructor * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet */ CSSOM.CSSStyleSheet = function CSSStyleSheet() { CSSOM.StyleSheet.call(this); this.cssRules = []; }; CSSOM.CSSStyleSheet.prototype = new CSSOM.StyleSheet(); CSSOM.CSSStyleSheet.prototype.constructor = CSSOM.CSSStyleSheet; /** * Used to insert a new rule into the style sheet. The new rule now becomes part of the cascade. * * sheet = new Sheet("body {margin: 0}") * sheet.toString() * -> "body{margin:0;}" * sheet.insertRule("img {border: none}", 0) * -> 0 * sheet.toString() * -> "img{border:none;}body{margin:0;}" * * @param {string} rule * @param {number} index * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-insertRule * @return {number} The index within the style sheet's rule collection of the newly inserted rule. */ CSSOM.CSSStyleSheet.prototype.insertRule = function(rule, index) { if (index < 0 || index > this.cssRules.length) { throw new RangeError("INDEX_SIZE_ERR"); } var cssRule = CSSOM.parse(rule).cssRules[0]; cssRule.parentStyleSheet = this; this.cssRules.splice(index, 0, cssRule); return index; }; /** * Used to delete a rule from the style sheet. * * sheet = new Sheet("img{border:none} body{margin:0}") * sheet.toString() * -> "img{border:none;}body{margin:0;}" * sheet.deleteRule(0) * sheet.toString() * -> "body{margin:0;}" * * @param {number} index within the style sheet's rule list of the rule to remove. * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-deleteRule */ CSSOM.CSSStyleSheet.prototype.deleteRule = function(index) { if (index < 0 || index >= this.cssRules.length) { throw new RangeError("INDEX_SIZE_ERR"); } this.cssRules.splice(index, 1); }; /** * NON-STANDARD * @return {string} serialize stylesheet */ CSSOM.CSSStyleSheet.prototype.toString = function() { var result = ""; var rules = this.cssRules; for (var i=0; i<rules.length; i++) { result += rules[i].cssText + "\n"; } return result; }; //.CommonJS exports.CSSStyleSheet = CSSOM.CSSStyleSheet; CSSOM.parse = require('cssom/lib/parse').parse; // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleSheet.js ///CommonJS
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssom/lib/CSSStyleSheet.js
CSSStyleSheet.js
var CSSOM = { CSSValue: require('cssom/lib/CSSValue').CSSValue }; ///CommonJS /** * @constructor * @see http://msdn.microsoft.com/en-us/library/ms537634(v=vs.85).aspx * */ CSSOM.CSSValueExpression = function CSSValueExpression(token, idx) { this._token = token; this._idx = idx; }; CSSOM.CSSValueExpression.prototype = new CSSOM.CSSValue(); CSSOM.CSSValueExpression.prototype.constructor = CSSOM.CSSValueExpression; /** * parse css expression() value * * @return {Object} * - error: * or * - idx: * - expression: * * Example: * * .selector { * zoom: expression(documentElement.clientWidth > 1000 ? '1000px' : 'auto'); * } */ CSSOM.CSSValueExpression.prototype.parse = function() { var token = this._token, idx = this._idx; var character = '', expression = '', error = '', info, paren = []; for (; ; ++idx) { character = token.charAt(idx); // end of token if (character === '') { error = 'css expression error: unfinished expression!'; break; } switch(character) { case '(': paren.push(character); expression += character; break; case ')': paren.pop(character); expression += character; break; case '/': if ((info = this._parseJSComment(token, idx))) { // comment? if (info.error) { error = 'css expression error: unfinished comment in expression!'; } else { idx = info.idx; // ignore the comment } } else if ((info = this._parseJSRexExp(token, idx))) { // regexp idx = info.idx; expression += info.text; } else { // other expression += character; } break; case "'": case '"': info = this._parseJSString(token, idx, character); if (info) { // string idx = info.idx; expression += info.text; } else { expression += character; } break; default: expression += character; break; } if (error) { break; } // end of expression if (paren.length === 0) { break; } } var ret; if (error) { ret = { error: error }; } else { ret = { idx: idx, expression: expression }; } return ret; }; /** * * @return {Object|false} * - idx: * - text: * or * - error: * or * false * */ CSSOM.CSSValueExpression.prototype._parseJSComment = function(token, idx) { var nextChar = token.charAt(idx + 1), text; if (nextChar === '/' || nextChar === '*') { var startIdx = idx, endIdx, commentEndChar; if (nextChar === '/') { // line comment commentEndChar = '\n'; } else if (nextChar === '*') { // block comment commentEndChar = '*/'; } endIdx = token.indexOf(commentEndChar, startIdx + 1 + 1); if (endIdx !== -1) { endIdx = endIdx + commentEndChar.length - 1; text = token.substring(idx, endIdx + 1); return { idx: endIdx, text: text }; } else { var error = 'css expression error: unfinished comment in expression!'; return { error: error }; } } else { return false; } }; /** * * @return {Object|false} * - idx: * - text: * or * false * */ CSSOM.CSSValueExpression.prototype._parseJSString = function(token, idx, sep) { var endIdx = this._findMatchedIdx(token, idx, sep), text; if (endIdx === -1) { return false; } else { text = token.substring(idx, endIdx + sep.length); return { idx: endIdx, text: text }; } }; /** * parse regexp in css expression * * @return {Object|false} * - idx: * - regExp: * or * false */ /* all legal RegExp /a/ (/a/) [/a/] [12, /a/] !/a/ +/a/ -/a/ * /a/ / /a/ %/a/ ===/a/ !==/a/ ==/a/ !=/a/ >/a/ >=/a/ </a/ <=/a/ &/a/ |/a/ ^/a/ ~/a/ <</a/ >>/a/ >>>/a/ &&/a/ ||/a/ ?/a/ =/a/ ,/a/ delete /a/ in /a/ instanceof /a/ new /a/ typeof /a/ void /a/ */ CSSOM.CSSValueExpression.prototype._parseJSRexExp = function(token, idx) { var before = token.substring(0, idx).replace(/\s+$/, ""), legalRegx = [ /^$/, /\($/, /\[$/, /\!$/, /\+$/, /\-$/, /\*$/, /\/\s+/, /\%$/, /\=$/, /\>$/, /<$/, /\&$/, /\|$/, /\^$/, /\~$/, /\?$/, /\,$/, /delete$/, /in$/, /instanceof$/, /new$/, /typeof$/, /void$/ ]; var isLegal = legalRegx.some(function(reg) { return reg.test(before); }); if (!isLegal) { return false; } else { var sep = '/'; // same logic as string return this._parseJSString(token, idx, sep); } }; /** * * find next sep(same line) index in `token` * * @return {Number} * */ CSSOM.CSSValueExpression.prototype._findMatchedIdx = function(token, idx, sep) { var startIdx = idx, endIdx; var NOT_FOUND = -1; while(true) { endIdx = token.indexOf(sep, startIdx + 1); if (endIdx === -1) { // not found endIdx = NOT_FOUND; break; } else { var text = token.substring(idx + 1, endIdx), matched = text.match(/\\+$/); if (!matched || matched[0] % 2 === 0) { // not escaped break; } else { startIdx = endIdx; } } } // boundary must be in the same line(js sting or regexp) var nextNewLineIdx = token.indexOf('\n', idx + 1); if (nextNewLineIdx < endIdx) { endIdx = NOT_FOUND; } return endIdx; }; //.CommonJS exports.CSSValueExpression = CSSOM.CSSValueExpression; ///CommonJS
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssom/lib/CSSValueExpression.js
CSSValueExpression.js
var CSSOM = {}; ///CommonJS /** * @param {string} token */ CSSOM.parse = function parse(token) { var i = 0; /** "before-selector" or "selector" or "atRule" or "atBlock" or "conditionBlock" or "before-name" or "name" or "before-value" or "value" */ var state = "before-selector"; var index; var buffer = ""; var valueParenthesisDepth = 0; var SIGNIFICANT_WHITESPACE = { "selector": true, "value": true, "value-parenthesis": true, "atRule": true, "importRule-begin": true, "importRule": true, "atBlock": true, "conditionBlock": true, 'documentRule-begin': true }; var styleSheet = new CSSOM.CSSStyleSheet(); // @type CSSStyleSheet|CSSMediaRule|CSSSupportsRule|CSSFontFaceRule|CSSKeyframesRule|CSSDocumentRule var currentScope = styleSheet; // @type CSSMediaRule|CSSSupportsRule|CSSKeyframesRule|CSSDocumentRule var parentRule; var ancestorRules = []; var hasAncestors = false; var prevScope; var name, priority="", styleRule, mediaRule, supportsRule, importRule, fontFaceRule, keyframesRule, documentRule, hostRule; var atKeyframesRegExp = /@(-(?:\w+-)+)?keyframes/g; var parseError = function(message) { var lines = token.substring(0, i).split('\n'); var lineCount = lines.length; var charCount = lines.pop().length + 1; var error = new Error(message + ' (line ' + lineCount + ', char ' + charCount + ')'); error.line = lineCount; /* jshint sub : true */ error['char'] = charCount; error.styleSheet = styleSheet; throw error; }; for (var character; (character = token.charAt(i)); i++) { switch (character) { case " ": case "\t": case "\r": case "\n": case "\f": if (SIGNIFICANT_WHITESPACE[state]) { buffer += character; } break; // String case '"': index = i + 1; do { index = token.indexOf('"', index) + 1; if (!index) { parseError('Unmatched "'); } } while (token[index - 2] === '\\'); buffer += token.slice(i, index); i = index - 1; switch (state) { case 'before-value': state = 'value'; break; case 'importRule-begin': state = 'importRule'; break; } break; case "'": index = i + 1; do { index = token.indexOf("'", index) + 1; if (!index) { parseError("Unmatched '"); } } while (token[index - 2] === '\\'); buffer += token.slice(i, index); i = index - 1; switch (state) { case 'before-value': state = 'value'; break; case 'importRule-begin': state = 'importRule'; break; } break; // Comment case "/": if (token.charAt(i + 1) === "*") { i += 2; index = token.indexOf("*/", i); if (index === -1) { parseError("Missing */"); } else { i = index + 1; } } else { buffer += character; } if (state === "importRule-begin") { buffer += " "; state = "importRule"; } break; // At-rule case "@": if (token.indexOf("@-moz-document", i) === i) { state = "documentRule-begin"; documentRule = new CSSOM.CSSDocumentRule(); documentRule.__starts = i; i += "-moz-document".length; buffer = ""; break; } else if (token.indexOf("@media", i) === i) { state = "atBlock"; mediaRule = new CSSOM.CSSMediaRule(); mediaRule.__starts = i; i += "media".length; buffer = ""; break; } else if (token.indexOf("@supports", i) === i) { state = "conditionBlock"; supportsRule = new CSSOM.CSSSupportsRule(); supportsRule.__starts = i; i += "supports".length; buffer = ""; break; } else if (token.indexOf("@host", i) === i) { state = "hostRule-begin"; i += "host".length; hostRule = new CSSOM.CSSHostRule(); hostRule.__starts = i; buffer = ""; break; } else if (token.indexOf("@import", i) === i) { state = "importRule-begin"; i += "import".length; buffer += "@import"; break; } else if (token.indexOf("@font-face", i) === i) { state = "fontFaceRule-begin"; i += "font-face".length; fontFaceRule = new CSSOM.CSSFontFaceRule(); fontFaceRule.__starts = i; buffer = ""; break; } else { atKeyframesRegExp.lastIndex = i; var matchKeyframes = atKeyframesRegExp.exec(token); if (matchKeyframes && matchKeyframes.index === i) { state = "keyframesRule-begin"; keyframesRule = new CSSOM.CSSKeyframesRule(); keyframesRule.__starts = i; keyframesRule._vendorPrefix = matchKeyframes[1]; // Will come out as undefined if no prefix was found i += matchKeyframes[0].length - 1; buffer = ""; break; } else if (state === "selector") { state = "atRule"; } } buffer += character; break; case "{": if (state === "selector" || state === "atRule") { styleRule.selectorText = buffer.trim(); styleRule.style.__starts = i; buffer = ""; state = "before-name"; } else if (state === "atBlock") { mediaRule.media.mediaText = buffer.trim(); if (parentRule) { ancestorRules.push(parentRule); } currentScope = parentRule = mediaRule; mediaRule.parentStyleSheet = styleSheet; buffer = ""; state = "before-selector"; } else if (state === "conditionBlock") { supportsRule.conditionText = buffer.trim(); if (parentRule) { ancestorRules.push(parentRule); } currentScope = parentRule = supportsRule; supportsRule.parentStyleSheet = styleSheet; buffer = ""; state = "before-selector"; } else if (state === "hostRule-begin") { if (parentRule) { ancestorRules.push(parentRule); } currentScope = parentRule = hostRule; hostRule.parentStyleSheet = styleSheet; buffer = ""; state = "before-selector"; } else if (state === "fontFaceRule-begin") { if (parentRule) { fontFaceRule.parentRule = parentRule; } fontFaceRule.parentStyleSheet = styleSheet; styleRule = fontFaceRule; buffer = ""; state = "before-name"; } else if (state === "keyframesRule-begin") { keyframesRule.name = buffer.trim(); if (parentRule) { ancestorRules.push(parentRule); keyframesRule.parentRule = parentRule; } keyframesRule.parentStyleSheet = styleSheet; currentScope = parentRule = keyframesRule; buffer = ""; state = "keyframeRule-begin"; } else if (state === "keyframeRule-begin") { styleRule = new CSSOM.CSSKeyframeRule(); styleRule.keyText = buffer.trim(); styleRule.__starts = i; buffer = ""; state = "before-name"; } else if (state === "documentRule-begin") { // FIXME: what if this '{' is in the url text of the match function? documentRule.matcher.matcherText = buffer.trim(); if (parentRule) { ancestorRules.push(parentRule); documentRule.parentRule = parentRule; } currentScope = parentRule = documentRule; documentRule.parentStyleSheet = styleSheet; buffer = ""; state = "before-selector"; } break; case ":": if (state === "name") { name = buffer.trim(); buffer = ""; state = "before-value"; } else { buffer += character; } break; case "(": if (state === 'value') { // ie css expression mode if (buffer.trim() === 'expression') { var info = (new CSSOM.CSSValueExpression(token, i)).parse(); if (info.error) { parseError(info.error); } else { buffer += info.expression; i = info.idx; } } else { state = 'value-parenthesis'; //always ensure this is reset to 1 on transition //from value to value-parenthesis valueParenthesisDepth = 1; buffer += character; } } else if (state === 'value-parenthesis') { valueParenthesisDepth++; buffer += character; } else { buffer += character; } break; case ")": if (state === 'value-parenthesis') { valueParenthesisDepth--; if (valueParenthesisDepth === 0) state = 'value'; } buffer += character; break; case "!": if (state === "value" && token.indexOf("!important", i) === i) { priority = "important"; i += "important".length; } else { buffer += character; } break; case ";": switch (state) { case "value": styleRule.style.setProperty(name, buffer.trim(), priority); priority = ""; buffer = ""; state = "before-name"; break; case "atRule": buffer = ""; state = "before-selector"; break; case "importRule": importRule = new CSSOM.CSSImportRule(); importRule.parentStyleSheet = importRule.styleSheet.parentStyleSheet = styleSheet; importRule.cssText = buffer + character; styleSheet.cssRules.push(importRule); buffer = ""; state = "before-selector"; break; default: buffer += character; break; } break; case "}": switch (state) { case "value": styleRule.style.setProperty(name, buffer.trim(), priority); priority = ""; /* falls through */ case "before-name": case "name": styleRule.__ends = i + 1; if (parentRule) { styleRule.parentRule = parentRule; } styleRule.parentStyleSheet = styleSheet; currentScope.cssRules.push(styleRule); buffer = ""; if (currentScope.constructor === CSSOM.CSSKeyframesRule) { state = "keyframeRule-begin"; } else { state = "before-selector"; } break; case "keyframeRule-begin": case "before-selector": case "selector": // End of media/supports/document rule. if (!parentRule) { parseError("Unexpected }"); } // Handle rules nested in @media or @supports hasAncestors = ancestorRules.length > 0; while (ancestorRules.length > 0) { parentRule = ancestorRules.pop(); if ( parentRule.constructor.name === "CSSMediaRule" || parentRule.constructor.name === "CSSSupportsRule" ) { prevScope = currentScope; currentScope = parentRule; currentScope.cssRules.push(prevScope); break; } if (ancestorRules.length === 0) { hasAncestors = false; } } if (!hasAncestors) { currentScope.__ends = i + 1; styleSheet.cssRules.push(currentScope); currentScope = styleSheet; parentRule = null; } buffer = ""; state = "before-selector"; break; } break; default: switch (state) { case "before-selector": state = "selector"; styleRule = new CSSOM.CSSStyleRule(); styleRule.__starts = i; break; case "before-name": state = "name"; break; case "before-value": state = "value"; break; case "importRule-begin": state = "importRule"; break; } buffer += character; break; } } return styleSheet; }; //.CommonJS exports.parse = CSSOM.parse; // The following modules cannot be included sooner due to the mutual dependency with parse.js CSSOM.CSSStyleSheet = require("cssom/lib/CSSStyleSheet").CSSStyleSheet; CSSOM.CSSStyleRule = require("cssom/lib/CSSStyleRule").CSSStyleRule; CSSOM.CSSImportRule = require("cssom/lib/CSSImportRule").CSSImportRule; CSSOM.CSSMediaRule = require("cssom/lib/CSSMediaRule").CSSMediaRule; CSSOM.CSSSupportsRule = require("cssom/lib/CSSSupportsRule").CSSSupportsRule; CSSOM.CSSFontFaceRule = require("cssom/lib/CSSFontFaceRule").CSSFontFaceRule; CSSOM.CSSHostRule = require("cssom/lib/CSSHostRule").CSSHostRule; CSSOM.CSSStyleDeclaration = require('cssom/lib/CSSStyleDeclaration').CSSStyleDeclaration; CSSOM.CSSKeyframeRule = require('cssom/lib/CSSKeyframeRule').CSSKeyframeRule; CSSOM.CSSKeyframesRule = require('cssom/lib/CSSKeyframesRule').CSSKeyframesRule; CSSOM.CSSValueExpression = require('cssom/lib/CSSValueExpression').CSSValueExpression; CSSOM.CSSDocumentRule = require('cssom/lib/CSSDocumentRule').CSSDocumentRule; ///CommonJS
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssom/lib/parse.js
parse.js
var CSSOM = {}; ///CommonJS /** * @constructor * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration */ CSSOM.CSSStyleDeclaration = function CSSStyleDeclaration(){ this.length = 0; this.parentRule = null; // NON-STANDARD this._importants = {}; }; CSSOM.CSSStyleDeclaration.prototype = { constructor: CSSOM.CSSStyleDeclaration, /** * * @param {string} name * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-getPropertyValue * @return {string} the value of the property if it has been explicitly set for this declaration block. * Returns the empty string if the property has not been set. */ getPropertyValue: function(name) { return this[name] || ""; }, /** * * @param {string} name * @param {string} value * @param {string} [priority=null] "important" or null * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-setProperty */ setProperty: function(name, value, priority) { if (this[name]) { // Property already exist. Overwrite it. var index = Array.prototype.indexOf.call(this, name); if (index < 0) { this[this.length] = name; this.length++; } } else { // New property. this[this.length] = name; this.length++; } this[name] = value + ""; this._importants[name] = priority; }, /** * * @param {string} name * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-removeProperty * @return {string} the value of the property if it has been explicitly set for this declaration block. * Returns the empty string if the property has not been set or the property name does not correspond to a known CSS property. */ removeProperty: function(name) { if (!(name in this)) { return ""; } var index = Array.prototype.indexOf.call(this, name); if (index < 0) { return ""; } var prevValue = this[name]; this[name] = ""; // That's what WebKit and Opera do Array.prototype.splice.call(this, index, 1); // That's what Firefox does //this[index] = "" return prevValue; }, getPropertyCSSValue: function() { //FIXME }, /** * * @param {String} name */ getPropertyPriority: function(name) { return this._importants[name] || ""; }, /** * element.style.overflow = "auto" * element.style.getPropertyShorthand("overflow-x") * -> "overflow" */ getPropertyShorthand: function() { //FIXME }, isPropertyImplicit: function() { //FIXME }, // Doesn't work in IE < 9 get cssText(){ var properties = []; for (var i=0, length=this.length; i < length; ++i) { var name = this[i]; var value = this.getPropertyValue(name); var priority = this.getPropertyPriority(name); if (priority) { priority = " !" + priority; } properties[i] = name + ": " + value + priority + ";"; } return properties.join(" "); }, set cssText(text){ var i, name; for (i = this.length; i--;) { name = this[i]; this[name] = ""; } Array.prototype.splice.call(this, 0, this.length); this._importants = {}; var dummyRule = CSSOM.parse('#bogus{' + text + '}').cssRules[0].style; var length = dummyRule.length; for (i = 0; i < length; ++i) { name = dummyRule[i]; this.setProperty(dummyRule[i], dummyRule.getPropertyValue(name), dummyRule.getPropertyPriority(name)); } } }; //.CommonJS exports.CSSStyleDeclaration = CSSOM.CSSStyleDeclaration; CSSOM.parse = require('cssom/lib/parse').parse; // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleDeclaration.js ///CommonJS
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssom/lib/CSSStyleDeclaration.js
CSSStyleDeclaration.js
var CSSOM = { CSSRule: require("cssom/lib/CSSRule").CSSRule, CSSStyleSheet: require("cssom/lib/CSSStyleSheet").CSSStyleSheet, MediaList: require("cssom/lib/MediaList").MediaList }; ///CommonJS /** * @constructor * @see http://dev.w3.org/csswg/cssom/#cssimportrule * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSImportRule */ CSSOM.CSSImportRule = function CSSImportRule() { CSSOM.CSSRule.call(this); this.href = ""; this.media = new CSSOM.MediaList(); this.styleSheet = new CSSOM.CSSStyleSheet(); }; CSSOM.CSSImportRule.prototype = new CSSOM.CSSRule(); CSSOM.CSSImportRule.prototype.constructor = CSSOM.CSSImportRule; CSSOM.CSSImportRule.prototype.type = 3; Object.defineProperty(CSSOM.CSSImportRule.prototype, "cssText", { get: function() { var mediaText = this.media.mediaText; return "@import url(" + this.href + ")" + (mediaText ? " " + mediaText : "") + ";"; }, set: function(cssText) { var i = 0; /** * @import url(partial.css) screen, handheld; * || | * after-import media * | * url */ var state = ''; var buffer = ''; var index; for (var character; (character = cssText.charAt(i)); i++) { switch (character) { case ' ': case '\t': case '\r': case '\n': case '\f': if (state === 'after-import') { state = 'url'; } else { buffer += character; } break; case '@': if (!state && cssText.indexOf('@import', i) === i) { state = 'after-import'; i += 'import'.length; buffer = ''; } break; case 'u': if (state === 'url' && cssText.indexOf('url(', i) === i) { index = cssText.indexOf(')', i + 1); if (index === -1) { throw i + ': ")" not found'; } i += 'url('.length; var url = cssText.slice(i, index); if (url[0] === url[url.length - 1]) { if (url[0] === '"' || url[0] === "'") { url = url.slice(1, -1); } } this.href = url; i = index; state = 'media'; } break; case '"': if (state === 'url') { index = cssText.indexOf('"', i + 1); if (!index) { throw i + ": '\"' not found"; } this.href = cssText.slice(i + 1, index); i = index; state = 'media'; } break; case "'": if (state === 'url') { index = cssText.indexOf("'", i + 1); if (!index) { throw i + ': "\'" not found'; } this.href = cssText.slice(i + 1, index); i = index; state = 'media'; } break; case ';': if (state === 'media') { if (buffer) { this.media.mediaText = buffer.trim(); } } break; default: if (state === 'media') { buffer += character; } break; } } } }); //.CommonJS exports.CSSImportRule = CSSOM.CSSImportRule; ///CommonJS
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssom/lib/CSSImportRule.js
CSSImportRule.js
var CSSOM = { CSSStyleDeclaration: require("cssom/lib/CSSStyleDeclaration").CSSStyleDeclaration, CSSRule: require("cssom/lib/CSSRule").CSSRule }; ///CommonJS /** * @constructor * @see http://dev.w3.org/csswg/cssom/#cssstylerule * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleRule */ CSSOM.CSSStyleRule = function CSSStyleRule() { CSSOM.CSSRule.call(this); this.selectorText = ""; this.style = new CSSOM.CSSStyleDeclaration(); this.style.parentRule = this; }; CSSOM.CSSStyleRule.prototype = new CSSOM.CSSRule(); CSSOM.CSSStyleRule.prototype.constructor = CSSOM.CSSStyleRule; CSSOM.CSSStyleRule.prototype.type = 1; Object.defineProperty(CSSOM.CSSStyleRule.prototype, "cssText", { get: function() { var text; if (this.selectorText) { text = this.selectorText + " {" + this.style.cssText + "}"; } else { text = ""; } return text; }, set: function(cssText) { var rule = CSSOM.CSSStyleRule.parse(cssText); this.style = rule.style; this.selectorText = rule.selectorText; } }); /** * NON-STANDARD * lightweight version of parse.js. * @param {string} ruleText * @return CSSStyleRule */ CSSOM.CSSStyleRule.parse = function(ruleText) { var i = 0; var state = "selector"; var index; var j = i; var buffer = ""; var SIGNIFICANT_WHITESPACE = { "selector": true, "value": true }; var styleRule = new CSSOM.CSSStyleRule(); var name, priority=""; for (var character; (character = ruleText.charAt(i)); i++) { switch (character) { case " ": case "\t": case "\r": case "\n": case "\f": if (SIGNIFICANT_WHITESPACE[state]) { // Squash 2 or more white-spaces in the row into 1 switch (ruleText.charAt(i - 1)) { case " ": case "\t": case "\r": case "\n": case "\f": break; default: buffer += " "; break; } } break; // String case '"': j = i + 1; index = ruleText.indexOf('"', j) + 1; if (!index) { throw '" is missing'; } buffer += ruleText.slice(i, index); i = index - 1; break; case "'": j = i + 1; index = ruleText.indexOf("'", j) + 1; if (!index) { throw "' is missing"; } buffer += ruleText.slice(i, index); i = index - 1; break; // Comment case "/": if (ruleText.charAt(i + 1) === "*") { i += 2; index = ruleText.indexOf("*/", i); if (index === -1) { throw new SyntaxError("Missing */"); } else { i = index + 1; } } else { buffer += character; } break; case "{": if (state === "selector") { styleRule.selectorText = buffer.trim(); buffer = ""; state = "name"; } break; case ":": if (state === "name") { name = buffer.trim(); buffer = ""; state = "value"; } else { buffer += character; } break; case "!": if (state === "value" && ruleText.indexOf("!important", i) === i) { priority = "important"; i += "important".length; } else { buffer += character; } break; case ";": if (state === "value") { styleRule.style.setProperty(name, buffer.trim(), priority); priority = ""; buffer = ""; state = "name"; } else { buffer += character; } break; case "}": if (state === "value") { styleRule.style.setProperty(name, buffer.trim(), priority); priority = ""; buffer = ""; } else if (state === "name") { break; } else { buffer += character; } state = "selector"; break; default: buffer += character; break; } } return styleRule; }; //.CommonJS exports.CSSStyleRule = CSSOM.CSSStyleRule; ///CommonJS
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssom/lib/CSSStyleRule.js
CSSStyleRule.js
# ws: a Node.js WebSocket library [![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws) [![Build](https://img.shields.io/travis/websockets/ws/master.svg?logo=travis)](https://travis-ci.com/websockets/ws) [![Windows x86 Build](https://img.shields.io/appveyor/ci/lpinca/ws/master.svg?logo=appveyor)](https://ci.appveyor.com/project/lpinca/ws) [![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg)](https://coveralls.io/github/websockets/ws) ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and server implementation. Passes the quite extensive Autobahn test suite: [server][server-report], [client][client-report]. **Note**: This module does not work in the browser. The client in the docs is a reference to a back end with the role of a client in the WebSocket communication. Browser clients must use the native [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) object. To make the same code work seamlessly on Node.js and the browser, you can use one of the many wrappers available on npm, like [isomorphic-ws](https://github.com/heineiuo/isomorphic-ws). ## Table of Contents - [Protocol support](#protocol-support) - [Installing](#installing) - [Opt-in for performance and spec compliance](#opt-in-for-performance-and-spec-compliance) - [API docs](#api-docs) - [WebSocket compression](#websocket-compression) - [Usage examples](#usage-examples) - [Sending and receiving text data](#sending-and-receiving-text-data) - [Sending binary data](#sending-binary-data) - [Simple server](#simple-server) - [External HTTP/S server](#external-https-server) - [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server) - [Client authentication](#client-authentication) - [Server broadcast](#server-broadcast) - [echo.websocket.org demo](#echowebsocketorg-demo) - [Use the Node.js streams API](#use-the-nodejs-streams-api) - [Other examples](#other-examples) - [FAQ](#faq) - [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client) - [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections) - [How to connect via a proxy?](#how-to-connect-via-a-proxy) - [Changelog](#changelog) - [License](#license) ## Protocol support - **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) - **HyBi drafts 13-17** (Current default, alternatively option `protocolVersion: 13`) ## Installing ``` npm install ws ``` ### Opt-in for performance and spec compliance There are 2 optional modules that can be installed along side with the ws module. These modules are binary addons which improve certain operations. Prebuilt binaries are available for the most popular platforms so you don't necessarily need to have a C++ compiler installed on your machine. - `npm install --save-optional bufferutil`: Allows to efficiently perform operations such as masking and unmasking the data payload of the WebSocket frames. - `npm install --save-optional utf-8-validate`: Allows to efficiently check if a message contains valid UTF-8 as required by the spec. ## API docs See [`/doc/ws.md`](./doc/ws.md) for Node.js-like documentation of ws classes and utility functions. ## WebSocket compression ws supports the [permessage-deflate extension][permessage-deflate] which enables the client and server to negotiate a compression algorithm and its parameters, and then selectively apply it to the data payloads of each WebSocket message. The extension is disabled by default on the server and enabled by default on the client. It adds a significant overhead in terms of performance and memory consumption so we suggest to enable it only if it is really needed. Note that Node.js has a variety of issues with high-performance compression, where increased concurrency, especially on Linux, can lead to [catastrophic memory fragmentation][node-zlib-bug] and slow performance. If you intend to use permessage-deflate in production, it is worthwhile to set up a test representative of your workload and ensure Node.js/zlib will handle it with acceptable performance and memory usage. Tuning of permessage-deflate can be done via the options defined below. You can also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs]. See [the docs][ws-server-options] for more options. ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080, perMessageDeflate: { zlibDeflateOptions: { // See zlib defaults. chunkSize: 1024, memLevel: 7, level: 3 }, zlibInflateOptions: { chunkSize: 10 * 1024 }, // Other options settable: clientNoContextTakeover: true, // Defaults to negotiated value. serverNoContextTakeover: true, // Defaults to negotiated value. serverMaxWindowBits: 10, // Defaults to negotiated value. // Below options specified as default values. concurrencyLimit: 10, // Limits zlib concurrency for perf. threshold: 1024 // Size (in bytes) below which messages // should not be compressed. } }); ``` The client will only use the extension if it is supported and enabled on the server. To always disable the extension on the client set the `perMessageDeflate` option to `false`. ```js const WebSocket = require('ws'); const ws = new WebSocket('ws://www.host.com/path', { perMessageDeflate: false }); ``` ## Usage examples ### Sending and receiving text data ```js const WebSocket = require('ws'); const ws = new WebSocket('ws://www.host.com/path'); ws.on('open', function open() { ws.send('something'); }); ws.on('message', function incoming(data) { console.log(data); }); ``` ### Sending binary data ```js const WebSocket = require('ws'); const ws = new WebSocket('ws://www.host.com/path'); ws.on('open', function open() { const array = new Float32Array(5); for (var i = 0; i < array.length; ++i) { array[i] = i / 2; } ws.send(array); }); ``` ### Simple server ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { console.log('received: %s', message); }); ws.send('something'); }); ``` ### External HTTP/S server ```js const fs = require('fs'); const https = require('https'); const WebSocket = require('ws'); const server = https.createServer({ cert: fs.readFileSync('/path/to/cert.pem'), key: fs.readFileSync('/path/to/key.pem') }); const wss = new WebSocket.Server({ server }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { console.log('received: %s', message); }); ws.send('something'); }); server.listen(8080); ``` ### Multiple servers sharing a single HTTP/S server ```js const http = require('http'); const WebSocket = require('ws'); const url = require('url'); const server = http.createServer(); const wss1 = new WebSocket.Server({ noServer: true }); const wss2 = new WebSocket.Server({ noServer: true }); wss1.on('connection', function connection(ws) { // ... }); wss2.on('connection', function connection(ws) { // ... }); server.on('upgrade', function upgrade(request, socket, head) { const pathname = url.parse(request.url).pathname; if (pathname === '/foo') { wss1.handleUpgrade(request, socket, head, function done(ws) { wss1.emit('connection', ws, request); }); } else if (pathname === '/bar') { wss2.handleUpgrade(request, socket, head, function done(ws) { wss2.emit('connection', ws, request); }); } else { socket.destroy(); } }); server.listen(8080); ``` ### Client authentication ```js const http = require('http'); const WebSocket = require('ws'); const server = http.createServer(); const wss = new WebSocket.Server({ noServer: true }); wss.on('connection', function connection(ws, request, client) { ws.on('message', function message(msg) { console.log(`Received message ${msg} from user ${client}`); }); }); server.on('upgrade', function upgrade(request, socket, head) { // This function is not defined on purpose. Implement it with your own logic. authenticate(request, (err, client) => { if (err || !client) { socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); socket.destroy(); return; } wss.handleUpgrade(request, socket, head, function done(ws) { wss.emit('connection', ws, request, client); }); }); }); server.listen(8080); ``` Also see the provided [example][session-parse-example] using `express-session`. ### Server broadcast A client WebSocket broadcasting to all connected WebSocket clients, including itself. ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(data) { wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { client.send(data); } }); }); }); ``` A client WebSocket broadcasting to every other connected WebSocket clients, excluding itself. ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(data) { wss.clients.forEach(function each(client) { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(data); } }); }); }); ``` ### echo.websocket.org demo ```js const WebSocket = require('ws'); const ws = new WebSocket('wss://echo.websocket.org/', { origin: 'https://websocket.org' }); ws.on('open', function open() { console.log('connected'); ws.send(Date.now()); }); ws.on('close', function close() { console.log('disconnected'); }); ws.on('message', function incoming(data) { console.log(`Roundtrip time: ${Date.now() - data} ms`); setTimeout(function timeout() { ws.send(Date.now()); }, 500); }); ``` ### Use the Node.js streams API ```js const WebSocket = require('ws'); const ws = new WebSocket('wss://echo.websocket.org/', { origin: 'https://websocket.org' }); const duplex = WebSocket.createWebSocketStream(ws, { encoding: 'utf8' }); duplex.pipe(process.stdout); process.stdin.pipe(duplex); ``` ### Other examples For a full example with a browser client communicating with a ws server, see the examples folder. Otherwise, see the test cases. ## FAQ ### How to get the IP address of the client? The remote IP address can be obtained from the raw socket. ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws, req) { const ip = req.socket.remoteAddress; }); ``` When the server runs behind a proxy like NGINX, the de-facto standard is to use the `X-Forwarded-For` header. ```js wss.on('connection', function connection(ws, req) { const ip = req.headers['x-forwarded-for'].split(/\s*,\s*/)[0]; }); ``` ### How to detect and close broken connections? Sometimes the link between the server and the client can be interrupted in a way that keeps both the server and the client unaware of the broken state of the connection (e.g. when pulling the cord). In these cases ping messages can be used as a means to verify that the remote endpoint is still responsive. ```js const WebSocket = require('ws'); function noop() {} function heartbeat() { this.isAlive = true; } const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.isAlive = true; ws.on('pong', heartbeat); }); const interval = setInterval(function ping() { wss.clients.forEach(function each(ws) { if (ws.isAlive === false) return ws.terminate(); ws.isAlive = false; ws.ping(noop); }); }, 30000); wss.on('close', function close() { clearInterval(interval); }); ``` Pong messages are automatically sent in response to ping messages as required by the spec. Just like the server example above your clients might as well lose connection without knowing it. You might want to add a ping listener on your clients to prevent that. A simple implementation would be: ```js const WebSocket = require('ws'); function heartbeat() { clearTimeout(this.pingTimeout); // Use `WebSocket#terminate()`, which immediately destroys the connection, // instead of `WebSocket#close()`, which waits for the close timer. // Delay should be equal to the interval at which your server // sends out pings plus a conservative assumption of the latency. this.pingTimeout = setTimeout(() => { this.terminate(); }, 30000 + 1000); } const client = new WebSocket('wss://echo.websocket.org/'); client.on('open', heartbeat); client.on('ping', heartbeat); client.on('close', function clear() { clearTimeout(this.pingTimeout); }); ``` ### How to connect via a proxy? Use a custom `http.Agent` implementation like [https-proxy-agent][] or [socks-proxy-agent][]. ## Changelog We're using the GitHub [releases][changelog] for changelog entries. ## License [MIT](LICENSE) [changelog]: https://github.com/websockets/ws/releases [client-report]: http://websockets.github.io/ws/autobahn/clients/ [https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent [node-zlib-bug]: https://github.com/nodejs/node/issues/8871 [node-zlib-deflaterawdocs]: https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options [permessage-deflate]: https://tools.ietf.org/html/rfc7692 [server-report]: http://websockets.github.io/ws/autobahn/servers/ [session-parse-example]: ./examples/express-session-parse [socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent [ws-server-options]: https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ws/README.md
README.md
'use strict'; const { randomFillSync } = require('crypto'); const PerMessageDeflate = require('ws/lib/permessage-deflate'); const { EMPTY_BUFFER } = require('ws/lib/constants'); const { isValidStatusCode } = require('ws/lib/validation'); const { mask: applyMask, toBuffer } = require('ws/lib/buffer-util'); const mask = Buffer.alloc(4); /** * HyBi Sender implementation. */ class Sender { /** * Creates a Sender instance. * * @param {net.Socket} socket The connection socket * @param {Object} extensions An object containing the negotiated extensions */ constructor(socket, extensions) { this._extensions = extensions || {}; this._socket = socket; this._firstFragment = true; this._compress = false; this._bufferedBytes = 0; this._deflating = false; this._queue = []; } /** * Frames a piece of data according to the HyBi WebSocket protocol. * * @param {Buffer} data The data to frame * @param {Object} options Options object * @param {Number} options.opcode The opcode * @param {Boolean} options.readOnly Specifies whether `data` can be modified * @param {Boolean} options.fin Specifies whether or not to set the FIN bit * @param {Boolean} options.mask Specifies whether or not to mask `data` * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit * @return {Buffer[]} The framed data as a list of `Buffer` instances * @public */ static frame(data, options) { const merge = options.mask && options.readOnly; let offset = options.mask ? 6 : 2; let payloadLength = data.length; if (data.length >= 65536) { offset += 8; payloadLength = 127; } else if (data.length > 125) { offset += 2; payloadLength = 126; } const target = Buffer.allocUnsafe(merge ? data.length + offset : offset); target[0] = options.fin ? options.opcode | 0x80 : options.opcode; if (options.rsv1) target[0] |= 0x40; target[1] = payloadLength; if (payloadLength === 126) { target.writeUInt16BE(data.length, 2); } else if (payloadLength === 127) { target.writeUInt32BE(0, 2); target.writeUInt32BE(data.length, 6); } if (!options.mask) return [target, data]; randomFillSync(mask, 0, 4); target[1] |= 0x80; target[offset - 4] = mask[0]; target[offset - 3] = mask[1]; target[offset - 2] = mask[2]; target[offset - 1] = mask[3]; if (merge) { applyMask(data, mask, target, offset, data.length); return [target]; } applyMask(data, mask, data, 0, data.length); return [target, data]; } /** * Sends a close message to the other peer. * * @param {(Number|undefined)} code The status code component of the body * @param {String} data The message component of the body * @param {Boolean} mask Specifies whether or not to mask the message * @param {Function} cb Callback * @public */ close(code, data, mask, cb) { let buf; if (code === undefined) { buf = EMPTY_BUFFER; } else if (typeof code !== 'number' || !isValidStatusCode(code)) { throw new TypeError('First argument must be a valid error code number'); } else if (data === undefined || data === '') { buf = Buffer.allocUnsafe(2); buf.writeUInt16BE(code, 0); } else { const length = Buffer.byteLength(data); if (length > 123) { throw new RangeError('The message must not be greater than 123 bytes'); } buf = Buffer.allocUnsafe(2 + length); buf.writeUInt16BE(code, 0); buf.write(data, 2); } if (this._deflating) { this.enqueue([this.doClose, buf, mask, cb]); } else { this.doClose(buf, mask, cb); } } /** * Frames and sends a close message. * * @param {Buffer} data The message to send * @param {Boolean} mask Specifies whether or not to mask `data` * @param {Function} cb Callback * @private */ doClose(data, mask, cb) { this.sendFrame( Sender.frame(data, { fin: true, rsv1: false, opcode: 0x08, mask, readOnly: false }), cb ); } /** * Sends a ping message to the other peer. * * @param {*} data The message to send * @param {Boolean} mask Specifies whether or not to mask `data` * @param {Function} cb Callback * @public */ ping(data, mask, cb) { const buf = toBuffer(data); if (buf.length > 125) { throw new RangeError('The data size must not be greater than 125 bytes'); } if (this._deflating) { this.enqueue([this.doPing, buf, mask, toBuffer.readOnly, cb]); } else { this.doPing(buf, mask, toBuffer.readOnly, cb); } } /** * Frames and sends a ping message. * * @param {Buffer} data The message to send * @param {Boolean} mask Specifies whether or not to mask `data` * @param {Boolean} readOnly Specifies whether `data` can be modified * @param {Function} cb Callback * @private */ doPing(data, mask, readOnly, cb) { this.sendFrame( Sender.frame(data, { fin: true, rsv1: false, opcode: 0x09, mask, readOnly }), cb ); } /** * Sends a pong message to the other peer. * * @param {*} data The message to send * @param {Boolean} mask Specifies whether or not to mask `data` * @param {Function} cb Callback * @public */ pong(data, mask, cb) { const buf = toBuffer(data); if (buf.length > 125) { throw new RangeError('The data size must not be greater than 125 bytes'); } if (this._deflating) { this.enqueue([this.doPong, buf, mask, toBuffer.readOnly, cb]); } else { this.doPong(buf, mask, toBuffer.readOnly, cb); } } /** * Frames and sends a pong message. * * @param {Buffer} data The message to send * @param {Boolean} mask Specifies whether or not to mask `data` * @param {Boolean} readOnly Specifies whether `data` can be modified * @param {Function} cb Callback * @private */ doPong(data, mask, readOnly, cb) { this.sendFrame( Sender.frame(data, { fin: true, rsv1: false, opcode: 0x0a, mask, readOnly }), cb ); } /** * Sends a data message to the other peer. * * @param {*} data The message to send * @param {Object} options Options object * @param {Boolean} options.compress Specifies whether or not to compress `data` * @param {Boolean} options.binary Specifies whether `data` is binary or text * @param {Boolean} options.fin Specifies whether the fragment is the last one * @param {Boolean} options.mask Specifies whether or not to mask `data` * @param {Function} cb Callback * @public */ send(data, options, cb) { const buf = toBuffer(data); const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; let opcode = options.binary ? 2 : 1; let rsv1 = options.compress; if (this._firstFragment) { this._firstFragment = false; if (rsv1 && perMessageDeflate) { rsv1 = buf.length >= perMessageDeflate._threshold; } this._compress = rsv1; } else { rsv1 = false; opcode = 0; } if (options.fin) this._firstFragment = true; if (perMessageDeflate) { const opts = { fin: options.fin, rsv1, opcode, mask: options.mask, readOnly: toBuffer.readOnly }; if (this._deflating) { this.enqueue([this.dispatch, buf, this._compress, opts, cb]); } else { this.dispatch(buf, this._compress, opts, cb); } } else { this.sendFrame( Sender.frame(buf, { fin: options.fin, rsv1: false, opcode, mask: options.mask, readOnly: toBuffer.readOnly }), cb ); } } /** * Dispatches a data message. * * @param {Buffer} data The message to send * @param {Boolean} compress Specifies whether or not to compress `data` * @param {Object} options Options object * @param {Number} options.opcode The opcode * @param {Boolean} options.readOnly Specifies whether `data` can be modified * @param {Boolean} options.fin Specifies whether or not to set the FIN bit * @param {Boolean} options.mask Specifies whether or not to mask `data` * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit * @param {Function} cb Callback * @private */ dispatch(data, compress, options, cb) { if (!compress) { this.sendFrame(Sender.frame(data, options), cb); return; } const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; this._bufferedBytes += data.length; this._deflating = true; perMessageDeflate.compress(data, options.fin, (_, buf) => { if (this._socket.destroyed) { const err = new Error( 'The socket was closed while data was being compressed' ); if (typeof cb === 'function') cb(err); for (let i = 0; i < this._queue.length; i++) { const callback = this._queue[i][4]; if (typeof callback === 'function') callback(err); } return; } this._bufferedBytes -= data.length; this._deflating = false; options.readOnly = false; this.sendFrame(Sender.frame(buf, options), cb); this.dequeue(); }); } /** * Executes queued send operations. * * @private */ dequeue() { while (!this._deflating && this._queue.length) { const params = this._queue.shift(); this._bufferedBytes -= params[1].length; Reflect.apply(params[0], this, params.slice(1)); } } /** * Enqueues a send operation. * * @param {Array} params Send operation parameters. * @private */ enqueue(params) { this._bufferedBytes += params[1].length; this._queue.push(params); } /** * Sends a frame. * * @param {Buffer[]} list The frame to send * @param {Function} cb Callback * @private */ sendFrame(list, cb) { if (list.length === 2) { this._socket.cork(); this._socket.write(list[0]); this._socket.write(list[1], cb); this._socket.uncork(); } else { this._socket.write(list[0], cb); } } } module.exports = Sender;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ws/lib/sender.js
sender.js
'use strict'; const { EMPTY_BUFFER } = require('ws/lib/constants'); /** * Merges an array of buffers into a new buffer. * * @param {Buffer[]} list The array of buffers to concat * @param {Number} totalLength The total length of buffers in the list * @return {Buffer} The resulting buffer * @public */ function concat(list, totalLength) { if (list.length === 0) return EMPTY_BUFFER; if (list.length === 1) return list[0]; const target = Buffer.allocUnsafe(totalLength); let offset = 0; for (let i = 0; i < list.length; i++) { const buf = list[i]; target.set(buf, offset); offset += buf.length; } if (offset < totalLength) return target.slice(0, offset); return target; } /** * Masks a buffer using the given mask. * * @param {Buffer} source The buffer to mask * @param {Buffer} mask The mask to use * @param {Buffer} output The buffer where to store the result * @param {Number} offset The offset at which to start writing * @param {Number} length The number of bytes to mask. * @public */ function _mask(source, mask, output, offset, length) { for (let i = 0; i < length; i++) { output[offset + i] = source[i] ^ mask[i & 3]; } } /** * Unmasks a buffer using the given mask. * * @param {Buffer} buffer The buffer to unmask * @param {Buffer} mask The mask to use * @public */ function _unmask(buffer, mask) { // Required until https://github.com/nodejs/node/issues/9006 is resolved. const length = buffer.length; for (let i = 0; i < length; i++) { buffer[i] ^= mask[i & 3]; } } /** * Converts a buffer to an `ArrayBuffer`. * * @param {Buffer} buf The buffer to convert * @return {ArrayBuffer} Converted buffer * @public */ function toArrayBuffer(buf) { if (buf.byteLength === buf.buffer.byteLength) { return buf.buffer; } return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); } /** * Converts `data` to a `Buffer`. * * @param {*} data The data to convert * @return {Buffer} The buffer * @throws {TypeError} * @public */ function toBuffer(data) { toBuffer.readOnly = true; if (Buffer.isBuffer(data)) return data; let buf; if (data instanceof ArrayBuffer) { buf = Buffer.from(data); } else if (ArrayBuffer.isView(data)) { buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength); } else { buf = Buffer.from(data); toBuffer.readOnly = false; } return buf; } try { const bufferUtil = require('bufferutil'); const bu = bufferUtil.BufferUtil || bufferUtil; module.exports = { concat, mask(source, mask, output, offset, length) { if (length < 48) _mask(source, mask, output, offset, length); else bu.mask(source, mask, output, offset, length); }, toArrayBuffer, toBuffer, unmask(buffer, mask) { if (buffer.length < 32) _unmask(buffer, mask); else bu.unmask(buffer, mask); } }; } catch (e) /* istanbul ignore next */ { module.exports = { concat, mask: _mask, toArrayBuffer, toBuffer, unmask: _unmask }; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ws/lib/buffer-util.js
buffer-util.js
'use strict'; const zlib = require('zlib'); const bufferUtil = require('ws/lib/buffer-util'); const Limiter = require('ws/lib/limiter'); const { kStatusCode, NOOP } = require('ws/lib/constants'); const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); const kPerMessageDeflate = Symbol('permessage-deflate'); const kTotalLength = Symbol('total-length'); const kCallback = Symbol('callback'); const kBuffers = Symbol('buffers'); const kError = Symbol('error'); // // We limit zlib concurrency, which prevents severe memory fragmentation // as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 // and https://github.com/websockets/ws/issues/1202 // // Intentionally global; it's the global thread pool that's an issue. // let zlibLimiter; /** * permessage-deflate implementation. */ class PerMessageDeflate { /** * Creates a PerMessageDeflate instance. * * @param {Object} options Configuration options * @param {Boolean} options.serverNoContextTakeover Request/accept disabling * of server context takeover * @param {Boolean} options.clientNoContextTakeover Advertise/acknowledge * disabling of client context takeover * @param {(Boolean|Number)} options.serverMaxWindowBits Request/confirm the * use of a custom server window size * @param {(Boolean|Number)} options.clientMaxWindowBits Advertise support * for, or request, a custom client window size * @param {Object} options.zlibDeflateOptions Options to pass to zlib on deflate * @param {Object} options.zlibInflateOptions Options to pass to zlib on inflate * @param {Number} options.threshold Size (in bytes) below which messages * should not be compressed * @param {Number} options.concurrencyLimit The number of concurrent calls to * zlib * @param {Boolean} isServer Create the instance in either server or client * mode * @param {Number} maxPayload The maximum allowed message length */ constructor(options, isServer, maxPayload) { this._maxPayload = maxPayload | 0; this._options = options || {}; this._threshold = this._options.threshold !== undefined ? this._options.threshold : 1024; this._isServer = !!isServer; this._deflate = null; this._inflate = null; this.params = null; if (!zlibLimiter) { const concurrency = this._options.concurrencyLimit !== undefined ? this._options.concurrencyLimit : 10; zlibLimiter = new Limiter(concurrency); } } /** * @type {String} */ static get extensionName() { return 'permessage-deflate'; } /** * Create an extension negotiation offer. * * @return {Object} Extension parameters * @public */ offer() { const params = {}; if (this._options.serverNoContextTakeover) { params.server_no_context_takeover = true; } if (this._options.clientNoContextTakeover) { params.client_no_context_takeover = true; } if (this._options.serverMaxWindowBits) { params.server_max_window_bits = this._options.serverMaxWindowBits; } if (this._options.clientMaxWindowBits) { params.client_max_window_bits = this._options.clientMaxWindowBits; } else if (this._options.clientMaxWindowBits == null) { params.client_max_window_bits = true; } return params; } /** * Accept an extension negotiation offer/response. * * @param {Array} configurations The extension negotiation offers/reponse * @return {Object} Accepted configuration * @public */ accept(configurations) { configurations = this.normalizeParams(configurations); this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations); return this.params; } /** * Releases all resources used by the extension. * * @public */ cleanup() { if (this._inflate) { this._inflate.close(); this._inflate = null; } if (this._deflate) { const callback = this._deflate[kCallback]; this._deflate.close(); this._deflate = null; if (callback) { callback( new Error( 'The deflate stream was closed while data was being processed' ) ); } } } /** * Accept an extension negotiation offer. * * @param {Array} offers The extension negotiation offers * @return {Object} Accepted configuration * @private */ acceptAsServer(offers) { const opts = this._options; const accepted = offers.find((params) => { if ( (opts.serverNoContextTakeover === false && params.server_no_context_takeover) || (params.server_max_window_bits && (opts.serverMaxWindowBits === false || (typeof opts.serverMaxWindowBits === 'number' && opts.serverMaxWindowBits > params.server_max_window_bits))) || (typeof opts.clientMaxWindowBits === 'number' && !params.client_max_window_bits) ) { return false; } return true; }); if (!accepted) { throw new Error('None of the extension offers can be accepted'); } if (opts.serverNoContextTakeover) { accepted.server_no_context_takeover = true; } if (opts.clientNoContextTakeover) { accepted.client_no_context_takeover = true; } if (typeof opts.serverMaxWindowBits === 'number') { accepted.server_max_window_bits = opts.serverMaxWindowBits; } if (typeof opts.clientMaxWindowBits === 'number') { accepted.client_max_window_bits = opts.clientMaxWindowBits; } else if ( accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false ) { delete accepted.client_max_window_bits; } return accepted; } /** * Accept the extension negotiation response. * * @param {Array} response The extension negotiation response * @return {Object} Accepted configuration * @private */ acceptAsClient(response) { const params = response[0]; if ( this._options.clientNoContextTakeover === false && params.client_no_context_takeover ) { throw new Error('Unexpected parameter "client_no_context_takeover"'); } if (!params.client_max_window_bits) { if (typeof this._options.clientMaxWindowBits === 'number') { params.client_max_window_bits = this._options.clientMaxWindowBits; } } else if ( this._options.clientMaxWindowBits === false || (typeof this._options.clientMaxWindowBits === 'number' && params.client_max_window_bits > this._options.clientMaxWindowBits) ) { throw new Error( 'Unexpected or invalid parameter "client_max_window_bits"' ); } return params; } /** * Normalize parameters. * * @param {Array} configurations The extension negotiation offers/reponse * @return {Array} The offers/response with normalized parameters * @private */ normalizeParams(configurations) { configurations.forEach((params) => { Object.keys(params).forEach((key) => { let value = params[key]; if (value.length > 1) { throw new Error(`Parameter "${key}" must have only a single value`); } value = value[0]; if (key === 'client_max_window_bits') { if (value !== true) { const num = +value; if (!Number.isInteger(num) || num < 8 || num > 15) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } value = num; } else if (!this._isServer) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } } else if (key === 'server_max_window_bits') { const num = +value; if (!Number.isInteger(num) || num < 8 || num > 15) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } value = num; } else if ( key === 'client_no_context_takeover' || key === 'server_no_context_takeover' ) { if (value !== true) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } } else { throw new Error(`Unknown parameter "${key}"`); } params[key] = value; }); }); return configurations; } /** * Decompress data. Concurrency limited. * * @param {Buffer} data Compressed data * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @public */ decompress(data, fin, callback) { zlibLimiter.add((done) => { this._decompress(data, fin, (err, result) => { done(); callback(err, result); }); }); } /** * Compress data. Concurrency limited. * * @param {Buffer} data Data to compress * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @public */ compress(data, fin, callback) { zlibLimiter.add((done) => { this._compress(data, fin, (err, result) => { done(); callback(err, result); }); }); } /** * Decompress data. * * @param {Buffer} data Compressed data * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @private */ _decompress(data, fin, callback) { const endpoint = this._isServer ? 'client' : 'server'; if (!this._inflate) { const key = `${endpoint}_max_window_bits`; const windowBits = typeof this.params[key] !== 'number' ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; this._inflate = zlib.createInflateRaw({ ...this._options.zlibInflateOptions, windowBits }); this._inflate[kPerMessageDeflate] = this; this._inflate[kTotalLength] = 0; this._inflate[kBuffers] = []; this._inflate.on('error', inflateOnError); this._inflate.on('data', inflateOnData); } this._inflate[kCallback] = callback; this._inflate.write(data); if (fin) this._inflate.write(TRAILER); this._inflate.flush(() => { const err = this._inflate[kError]; if (err) { this._inflate.close(); this._inflate = null; callback(err); return; } const data = bufferUtil.concat( this._inflate[kBuffers], this._inflate[kTotalLength] ); if (fin && this.params[`${endpoint}_no_context_takeover`]) { this._inflate.close(); this._inflate = null; } else { this._inflate[kTotalLength] = 0; this._inflate[kBuffers] = []; } callback(null, data); }); } /** * Compress data. * * @param {Buffer} data Data to compress * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @private */ _compress(data, fin, callback) { const endpoint = this._isServer ? 'server' : 'client'; if (!this._deflate) { const key = `${endpoint}_max_window_bits`; const windowBits = typeof this.params[key] !== 'number' ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; this._deflate = zlib.createDeflateRaw({ ...this._options.zlibDeflateOptions, windowBits }); this._deflate[kTotalLength] = 0; this._deflate[kBuffers] = []; // // An `'error'` event is emitted, only on Node.js < 10.0.0, if the // `zlib.DeflateRaw` instance is closed while data is being processed. // This can happen if `PerMessageDeflate#cleanup()` is called at the wrong // time due to an abnormal WebSocket closure. // this._deflate.on('error', NOOP); this._deflate.on('data', deflateOnData); } this._deflate[kCallback] = callback; this._deflate.write(data); this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { if (!this._deflate) { // // The deflate stream was closed while data was being processed. // return; } let data = bufferUtil.concat( this._deflate[kBuffers], this._deflate[kTotalLength] ); if (fin) data = data.slice(0, data.length - 4); // // Ensure that the callback will not be called again in // `PerMessageDeflate#cleanup()`. // this._deflate[kCallback] = null; if (fin && this.params[`${endpoint}_no_context_takeover`]) { this._deflate.close(); this._deflate = null; } else { this._deflate[kTotalLength] = 0; this._deflate[kBuffers] = []; } callback(null, data); }); } } module.exports = PerMessageDeflate; /** * The listener of the `zlib.DeflateRaw` stream `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function deflateOnData(chunk) { this[kBuffers].push(chunk); this[kTotalLength] += chunk.length; } /** * The listener of the `zlib.InflateRaw` stream `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function inflateOnData(chunk) { this[kTotalLength] += chunk.length; if ( this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload ) { this[kBuffers].push(chunk); return; } this[kError] = new RangeError('Max payload size exceeded'); this[kError][kStatusCode] = 1009; this.removeListener('data', inflateOnData); this.reset(); } /** * The listener of the `zlib.InflateRaw` stream `'error'` event. * * @param {Error} err The emitted error * @private */ function inflateOnError(err) { // // There is no need to call `Zlib#close()` as the handle is automatically // closed when an error is emitted. // this[kPerMessageDeflate]._inflate = null; err[kStatusCode] = 1007; this[kCallback](err); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ws/lib/permessage-deflate.js
permessage-deflate.js
'use strict'; const EventEmitter = require('events'); const { createHash } = require('crypto'); const { createServer, STATUS_CODES } = require('http'); const PerMessageDeflate = require('ws/lib/permessage-deflate'); const WebSocket = require('ws/lib/websocket'); const { format, parse } = require('ws/lib/extension'); const { GUID, kWebSocket } = require('ws/lib/constants'); const keyRegex = /^[+/0-9A-Za-z]{22}==$/; /** * Class representing a WebSocket server. * * @extends EventEmitter */ class WebSocketServer extends EventEmitter { /** * Create a `WebSocketServer` instance. * * @param {Object} options Configuration options * @param {Number} options.backlog The maximum length of the queue of pending * connections * @param {Boolean} options.clientTracking Specifies whether or not to track * clients * @param {Function} options.handleProtocols A hook to handle protocols * @param {String} options.host The hostname where to bind the server * @param {Number} options.maxPayload The maximum allowed message size * @param {Boolean} options.noServer Enable no server mode * @param {String} options.path Accept only connections matching this path * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable * permessage-deflate * @param {Number} options.port The port where to bind the server * @param {http.Server} options.server A pre-created HTTP/S server to use * @param {Function} options.verifyClient A hook to reject connections * @param {Function} callback A listener for the `listening` event */ constructor(options, callback) { super(); options = { maxPayload: 100 * 1024 * 1024, perMessageDeflate: false, handleProtocols: null, clientTracking: true, verifyClient: null, noServer: false, backlog: null, // use default (511 as implemented in net.js) server: null, host: null, path: null, port: null, ...options }; if (options.port == null && !options.server && !options.noServer) { throw new TypeError( 'One of the "port", "server", or "noServer" options must be specified' ); } if (options.port != null) { this._server = createServer((req, res) => { const body = STATUS_CODES[426]; res.writeHead(426, { 'Content-Length': body.length, 'Content-Type': 'text/plain' }); res.end(body); }); this._server.listen( options.port, options.host, options.backlog, callback ); } else if (options.server) { this._server = options.server; } if (this._server) { this._removeListeners = addListeners(this._server, { listening: this.emit.bind(this, 'listening'), error: this.emit.bind(this, 'error'), upgrade: (req, socket, head) => { this.handleUpgrade(req, socket, head, (ws) => { this.emit('connection', ws, req); }); } }); } if (options.perMessageDeflate === true) options.perMessageDeflate = {}; if (options.clientTracking) this.clients = new Set(); this.options = options; } /** * Returns the bound address, the address family name, and port of the server * as reported by the operating system if listening on an IP socket. * If the server is listening on a pipe or UNIX domain socket, the name is * returned as a string. * * @return {(Object|String|null)} The address of the server * @public */ address() { if (this.options.noServer) { throw new Error('The server is operating in "noServer" mode'); } if (!this._server) return null; return this._server.address(); } /** * Close the server. * * @param {Function} cb Callback * @public */ close(cb) { if (cb) this.once('close', cb); // // Terminate all associated clients. // if (this.clients) { for (const client of this.clients) client.terminate(); } const server = this._server; if (server) { this._removeListeners(); this._removeListeners = this._server = null; // // Close the http server if it was internally created. // if (this.options.port != null) { server.close(() => this.emit('close')); return; } } process.nextTick(emitClose, this); } /** * See if a given request should be handled by this server instance. * * @param {http.IncomingMessage} req Request object to inspect * @return {Boolean} `true` if the request is valid, else `false` * @public */ shouldHandle(req) { if (this.options.path) { const index = req.url.indexOf('?'); const pathname = index !== -1 ? req.url.slice(0, index) : req.url; if (pathname !== this.options.path) return false; } return true; } /** * Handle a HTTP Upgrade request. * * @param {http.IncomingMessage} req The request object * @param {net.Socket} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @public */ handleUpgrade(req, socket, head, cb) { socket.on('error', socketOnError); const key = req.headers['sec-websocket-key'] !== undefined ? req.headers['sec-websocket-key'].trim() : false; const version = +req.headers['sec-websocket-version']; const extensions = {}; if ( req.method !== 'GET' || req.headers.upgrade.toLowerCase() !== 'websocket' || !key || !keyRegex.test(key) || (version !== 8 && version !== 13) || !this.shouldHandle(req) ) { return abortHandshake(socket, 400); } if (this.options.perMessageDeflate) { const perMessageDeflate = new PerMessageDeflate( this.options.perMessageDeflate, true, this.options.maxPayload ); try { const offers = parse(req.headers['sec-websocket-extensions']); if (offers[PerMessageDeflate.extensionName]) { perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); extensions[PerMessageDeflate.extensionName] = perMessageDeflate; } } catch (err) { return abortHandshake(socket, 400); } } // // Optionally call external client verification handler. // if (this.options.verifyClient) { const info = { origin: req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], secure: !!(req.connection.authorized || req.connection.encrypted), req }; if (this.options.verifyClient.length === 2) { this.options.verifyClient(info, (verified, code, message, headers) => { if (!verified) { return abortHandshake(socket, code || 401, message, headers); } this.completeUpgrade(key, extensions, req, socket, head, cb); }); return; } if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); } this.completeUpgrade(key, extensions, req, socket, head, cb); } /** * Upgrade the connection to WebSocket. * * @param {String} key The value of the `Sec-WebSocket-Key` header * @param {Object} extensions The accepted extensions * @param {http.IncomingMessage} req The request object * @param {net.Socket} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @throws {Error} If called more than once with the same socket * @private */ completeUpgrade(key, extensions, req, socket, head, cb) { // // Destroy the socket if the client has already sent a FIN packet. // if (!socket.readable || !socket.writable) return socket.destroy(); if (socket[kWebSocket]) { throw new Error( 'server.handleUpgrade() was called more than once with the same ' + 'socket, possibly due to a misconfiguration' ); } const digest = createHash('sha1') .update(key + GUID) .digest('base64'); const headers = [ 'HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', `Sec-WebSocket-Accept: ${digest}` ]; const ws = new WebSocket(null); let protocol = req.headers['sec-websocket-protocol']; if (protocol) { protocol = protocol.trim().split(/ *, */); // // Optionally call external protocol selection handler. // if (this.options.handleProtocols) { protocol = this.options.handleProtocols(protocol, req); } else { protocol = protocol[0]; } if (protocol) { headers.push(`Sec-WebSocket-Protocol: ${protocol}`); ws.protocol = protocol; } } if (extensions[PerMessageDeflate.extensionName]) { const params = extensions[PerMessageDeflate.extensionName].params; const value = format({ [PerMessageDeflate.extensionName]: [params] }); headers.push(`Sec-WebSocket-Extensions: ${value}`); ws._extensions = extensions; } // // Allow external modification/inspection of handshake headers. // this.emit('headers', headers, req); socket.write(headers.concat('\r\n').join('\r\n')); socket.removeListener('error', socketOnError); ws.setSocket(socket, head, this.options.maxPayload); if (this.clients) { this.clients.add(ws); ws.on('close', () => this.clients.delete(ws)); } cb(ws); } } module.exports = WebSocketServer; /** * Add event listeners on an `EventEmitter` using a map of <event, listener> * pairs. * * @param {EventEmitter} server The event emitter * @param {Object.<String, Function>} map The listeners to add * @return {Function} A function that will remove the added listeners when called * @private */ function addListeners(server, map) { for (const event of Object.keys(map)) server.on(event, map[event]); return function removeListeners() { for (const event of Object.keys(map)) { server.removeListener(event, map[event]); } }; } /** * Emit a `'close'` event on an `EventEmitter`. * * @param {EventEmitter} server The event emitter * @private */ function emitClose(server) { server.emit('close'); } /** * Handle premature socket errors. * * @private */ function socketOnError() { this.destroy(); } /** * Close the connection when preconditions are not fulfilled. * * @param {net.Socket} socket The socket of the upgrade request * @param {Number} code The HTTP response status code * @param {String} [message] The HTTP response body * @param {Object} [headers] Additional HTTP response headers * @private */ function abortHandshake(socket, code, message, headers) { if (socket.writable) { message = message || STATUS_CODES[code]; headers = { Connection: 'close', 'Content-Type': 'text/html', 'Content-Length': Buffer.byteLength(message), ...headers }; socket.write( `HTTP/1.1 ${code} ${STATUS_CODES[code]}\r\n` + Object.keys(headers) .map((h) => `${h}: ${headers[h]}`) .join('\r\n') + '\r\n\r\n' + message ); } socket.removeListener('error', socketOnError); socket.destroy(); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ws/lib/websocket-server.js
websocket-server.js
'use strict'; const { Writable } = require('stream'); const PerMessageDeflate = require('ws/lib/permessage-deflate'); const { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = require('ws/lib/constants'); const { concat, toArrayBuffer, unmask } = require('ws/lib/buffer-util'); const { isValidStatusCode, isValidUTF8 } = require('ws/lib/validation'); const GET_INFO = 0; const GET_PAYLOAD_LENGTH_16 = 1; const GET_PAYLOAD_LENGTH_64 = 2; const GET_MASK = 3; const GET_DATA = 4; const INFLATING = 5; /** * HyBi Receiver implementation. * * @extends stream.Writable */ class Receiver extends Writable { /** * Creates a Receiver instance. * * @param {String} binaryType The type for binary data * @param {Object} extensions An object containing the negotiated extensions * @param {Boolean} isServer Specifies whether to operate in client or server * mode * @param {Number} maxPayload The maximum allowed message length */ constructor(binaryType, extensions, isServer, maxPayload) { super(); this._binaryType = binaryType || BINARY_TYPES[0]; this[kWebSocket] = undefined; this._extensions = extensions || {}; this._isServer = !!isServer; this._maxPayload = maxPayload | 0; this._bufferedBytes = 0; this._buffers = []; this._compressed = false; this._payloadLength = 0; this._mask = undefined; this._fragmented = 0; this._masked = false; this._fin = false; this._opcode = 0; this._totalPayloadLength = 0; this._messageLength = 0; this._fragments = []; this._state = GET_INFO; this._loop = false; } /** * Implements `Writable.prototype._write()`. * * @param {Buffer} chunk The chunk of data to write * @param {String} encoding The character encoding of `chunk` * @param {Function} cb Callback * @private */ _write(chunk, encoding, cb) { if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); this._bufferedBytes += chunk.length; this._buffers.push(chunk); this.startLoop(cb); } /** * Consumes `n` bytes from the buffered data. * * @param {Number} n The number of bytes to consume * @return {Buffer} The consumed bytes * @private */ consume(n) { this._bufferedBytes -= n; if (n === this._buffers[0].length) return this._buffers.shift(); if (n < this._buffers[0].length) { const buf = this._buffers[0]; this._buffers[0] = buf.slice(n); return buf.slice(0, n); } const dst = Buffer.allocUnsafe(n); do { const buf = this._buffers[0]; const offset = dst.length - n; if (n >= buf.length) { dst.set(this._buffers.shift(), offset); } else { dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); this._buffers[0] = buf.slice(n); } n -= buf.length; } while (n > 0); return dst; } /** * Starts the parsing loop. * * @param {Function} cb Callback * @private */ startLoop(cb) { let err; this._loop = true; do { switch (this._state) { case GET_INFO: err = this.getInfo(); break; case GET_PAYLOAD_LENGTH_16: err = this.getPayloadLength16(); break; case GET_PAYLOAD_LENGTH_64: err = this.getPayloadLength64(); break; case GET_MASK: this.getMask(); break; case GET_DATA: err = this.getData(cb); break; default: // `INFLATING` this._loop = false; return; } } while (this._loop); cb(err); } /** * Reads the first two bytes of a frame. * * @return {(RangeError|undefined)} A possible error * @private */ getInfo() { if (this._bufferedBytes < 2) { this._loop = false; return; } const buf = this.consume(2); if ((buf[0] & 0x30) !== 0x00) { this._loop = false; return error(RangeError, 'RSV2 and RSV3 must be clear', true, 1002); } const compressed = (buf[0] & 0x40) === 0x40; if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { this._loop = false; return error(RangeError, 'RSV1 must be clear', true, 1002); } this._fin = (buf[0] & 0x80) === 0x80; this._opcode = buf[0] & 0x0f; this._payloadLength = buf[1] & 0x7f; if (this._opcode === 0x00) { if (compressed) { this._loop = false; return error(RangeError, 'RSV1 must be clear', true, 1002); } if (!this._fragmented) { this._loop = false; return error(RangeError, 'invalid opcode 0', true, 1002); } this._opcode = this._fragmented; } else if (this._opcode === 0x01 || this._opcode === 0x02) { if (this._fragmented) { this._loop = false; return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002); } this._compressed = compressed; } else if (this._opcode > 0x07 && this._opcode < 0x0b) { if (!this._fin) { this._loop = false; return error(RangeError, 'FIN must be set', true, 1002); } if (compressed) { this._loop = false; return error(RangeError, 'RSV1 must be clear', true, 1002); } if (this._payloadLength > 0x7d) { this._loop = false; return error( RangeError, `invalid payload length ${this._payloadLength}`, true, 1002 ); } } else { this._loop = false; return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002); } if (!this._fin && !this._fragmented) this._fragmented = this._opcode; this._masked = (buf[1] & 0x80) === 0x80; if (this._isServer) { if (!this._masked) { this._loop = false; return error(RangeError, 'MASK must be set', true, 1002); } } else if (this._masked) { this._loop = false; return error(RangeError, 'MASK must be clear', true, 1002); } if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; else return this.haveLength(); } /** * Gets extended payload length (7+16). * * @return {(RangeError|undefined)} A possible error * @private */ getPayloadLength16() { if (this._bufferedBytes < 2) { this._loop = false; return; } this._payloadLength = this.consume(2).readUInt16BE(0); return this.haveLength(); } /** * Gets extended payload length (7+64). * * @return {(RangeError|undefined)} A possible error * @private */ getPayloadLength64() { if (this._bufferedBytes < 8) { this._loop = false; return; } const buf = this.consume(8); const num = buf.readUInt32BE(0); // // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned // if payload length is greater than this number. // if (num > Math.pow(2, 53 - 32) - 1) { this._loop = false; return error( RangeError, 'Unsupported WebSocket frame: payload length > 2^53 - 1', false, 1009 ); } this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); return this.haveLength(); } /** * Payload length has been read. * * @return {(RangeError|undefined)} A possible error * @private */ haveLength() { if (this._payloadLength && this._opcode < 0x08) { this._totalPayloadLength += this._payloadLength; if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { this._loop = false; return error(RangeError, 'Max payload size exceeded', false, 1009); } } if (this._masked) this._state = GET_MASK; else this._state = GET_DATA; } /** * Reads mask bytes. * * @private */ getMask() { if (this._bufferedBytes < 4) { this._loop = false; return; } this._mask = this.consume(4); this._state = GET_DATA; } /** * Reads data bytes. * * @param {Function} cb Callback * @return {(Error|RangeError|undefined)} A possible error * @private */ getData(cb) { let data = EMPTY_BUFFER; if (this._payloadLength) { if (this._bufferedBytes < this._payloadLength) { this._loop = false; return; } data = this.consume(this._payloadLength); if (this._masked) unmask(data, this._mask); } if (this._opcode > 0x07) return this.controlMessage(data); if (this._compressed) { this._state = INFLATING; this.decompress(data, cb); return; } if (data.length) { // // This message is not compressed so its lenght is the sum of the payload // length of all fragments. // this._messageLength = this._totalPayloadLength; this._fragments.push(data); } return this.dataMessage(); } /** * Decompresses data. * * @param {Buffer} data Compressed data * @param {Function} cb Callback * @private */ decompress(data, cb) { const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; perMessageDeflate.decompress(data, this._fin, (err, buf) => { if (err) return cb(err); if (buf.length) { this._messageLength += buf.length; if (this._messageLength > this._maxPayload && this._maxPayload > 0) { return cb( error(RangeError, 'Max payload size exceeded', false, 1009) ); } this._fragments.push(buf); } const er = this.dataMessage(); if (er) return cb(er); this.startLoop(cb); }); } /** * Handles a data message. * * @return {(Error|undefined)} A possible error * @private */ dataMessage() { if (this._fin) { const messageLength = this._messageLength; const fragments = this._fragments; this._totalPayloadLength = 0; this._messageLength = 0; this._fragmented = 0; this._fragments = []; if (this._opcode === 2) { let data; if (this._binaryType === 'nodebuffer') { data = concat(fragments, messageLength); } else if (this._binaryType === 'arraybuffer') { data = toArrayBuffer(concat(fragments, messageLength)); } else { data = fragments; } this.emit('message', data); } else { const buf = concat(fragments, messageLength); if (!isValidUTF8(buf)) { this._loop = false; return error(Error, 'invalid UTF-8 sequence', true, 1007); } this.emit('message', buf.toString()); } } this._state = GET_INFO; } /** * Handles a control message. * * @param {Buffer} data Data to handle * @return {(Error|RangeError|undefined)} A possible error * @private */ controlMessage(data) { if (this._opcode === 0x08) { this._loop = false; if (data.length === 0) { this.emit('conclude', 1005, ''); this.end(); } else if (data.length === 1) { return error(RangeError, 'invalid payload length 1', true, 1002); } else { const code = data.readUInt16BE(0); if (!isValidStatusCode(code)) { return error(RangeError, `invalid status code ${code}`, true, 1002); } const buf = data.slice(2); if (!isValidUTF8(buf)) { return error(Error, 'invalid UTF-8 sequence', true, 1007); } this.emit('conclude', code, buf.toString()); this.end(); } } else if (this._opcode === 0x09) { this.emit('ping', data); } else { this.emit('pong', data); } this._state = GET_INFO; } } module.exports = Receiver; /** * Builds an error object. * * @param {(Error|RangeError)} ErrorCtor The error constructor * @param {String} message The error message * @param {Boolean} prefix Specifies whether or not to add a default prefix to * `message` * @param {Number} statusCode The status code * @return {(Error|RangeError)} The error * @private */ function error(ErrorCtor, message, prefix, statusCode) { const err = new ErrorCtor( prefix ? `Invalid WebSocket frame: ${message}` : message ); Error.captureStackTrace(err, error); err[kStatusCode] = statusCode; return err; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ws/lib/receiver.js
receiver.js
'use strict'; const { Duplex } = require('stream'); /** * Emits the `'close'` event on a stream. * * @param {stream.Duplex} The stream. * @private */ function emitClose(stream) { stream.emit('close'); } /** * The listener of the `'end'` event. * * @private */ function duplexOnEnd() { if (!this.destroyed && this._writableState.finished) { this.destroy(); } } /** * The listener of the `'error'` event. * * @private */ function duplexOnError(err) { this.removeListener('error', duplexOnError); this.destroy(); if (this.listenerCount('error') === 0) { // Do not suppress the throwing behavior. this.emit('error', err); } } /** * Wraps a `WebSocket` in a duplex stream. * * @param {WebSocket} ws The `WebSocket` to wrap * @param {Object} options The options for the `Duplex` constructor * @return {stream.Duplex} The duplex stream * @public */ function createWebSocketStream(ws, options) { let resumeOnReceiverDrain = true; function receiverOnDrain() { if (resumeOnReceiverDrain) ws._socket.resume(); } if (ws.readyState === ws.CONNECTING) { ws.once('open', function open() { ws._receiver.removeAllListeners('drain'); ws._receiver.on('drain', receiverOnDrain); }); } else { ws._receiver.removeAllListeners('drain'); ws._receiver.on('drain', receiverOnDrain); } const duplex = new Duplex({ ...options, autoDestroy: false, emitClose: false, objectMode: false, writableObjectMode: false }); ws.on('message', function message(msg) { if (!duplex.push(msg)) { resumeOnReceiverDrain = false; ws._socket.pause(); } }); ws.once('error', function error(err) { if (duplex.destroyed) return; duplex.destroy(err); }); ws.once('close', function close() { if (duplex.destroyed) return; duplex.push(null); }); duplex._destroy = function (err, callback) { if (ws.readyState === ws.CLOSED) { callback(err); process.nextTick(emitClose, duplex); return; } let called = false; ws.once('error', function error(err) { called = true; callback(err); }); ws.once('close', function close() { if (!called) callback(err); process.nextTick(emitClose, duplex); }); ws.terminate(); }; duplex._final = function (callback) { if (ws.readyState === ws.CONNECTING) { ws.once('open', function open() { duplex._final(callback); }); return; } // If the value of the `_socket` property is `null` it means that `ws` is a // client websocket and the handshake failed. In fact, when this happens, a // socket is never assigned to the websocket. Wait for the `'error'` event // that will be emitted by the websocket. if (ws._socket === null) return; if (ws._socket._writableState.finished) { callback(); if (duplex._readableState.endEmitted) duplex.destroy(); } else { ws._socket.once('finish', function finish() { // `duplex` is not destroyed here because the `'end'` event will be // emitted on `duplex` after this `'finish'` event. The EOF signaling // `null` chunk is, in fact, pushed when the websocket emits `'close'`. callback(); }); ws.close(); } }; duplex._read = function () { if (ws.readyState === ws.OPEN && !resumeOnReceiverDrain) { resumeOnReceiverDrain = true; if (!ws._receiver._writableState.needDrain) ws._socket.resume(); } }; duplex._write = function (chunk, encoding, callback) { if (ws.readyState === ws.CONNECTING) { ws.once('open', function open() { duplex._write(chunk, encoding, callback); }); return; } ws.send(chunk, callback); }; duplex.on('end', duplexOnEnd); duplex.on('error', duplexOnError); return duplex; } module.exports = createWebSocketStream;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ws/lib/stream.js
stream.js
'use strict'; const EventEmitter = require('events'); const https = require('https'); const http = require('http'); const net = require('net'); const tls = require('tls'); const { randomBytes, createHash } = require('crypto'); const { URL } = require('url'); const PerMessageDeflate = require('ws/lib/permessage-deflate'); const Receiver = require('ws/lib/receiver'); const Sender = require('ws/lib/sender'); const { BINARY_TYPES, EMPTY_BUFFER, GUID, kStatusCode, kWebSocket, NOOP } = require('ws/lib/constants'); const { addEventListener, removeEventListener } = require('ws/lib/event-target'); const { format, parse } = require('ws/lib/extension'); const { toBuffer } = require('ws/lib/buffer-util'); const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; const protocolVersions = [8, 13]; const closeTimeout = 30 * 1000; /** * Class representing a WebSocket. * * @extends EventEmitter */ class WebSocket extends EventEmitter { /** * Create a new `WebSocket`. * * @param {(String|url.URL)} address The URL to which to connect * @param {(String|String[])} protocols The subprotocols * @param {Object} options Connection options */ constructor(address, protocols, options) { super(); this.readyState = WebSocket.CONNECTING; this.protocol = ''; this._binaryType = BINARY_TYPES[0]; this._closeFrameReceived = false; this._closeFrameSent = false; this._closeMessage = ''; this._closeTimer = null; this._closeCode = 1006; this._extensions = {}; this._receiver = null; this._sender = null; this._socket = null; if (address !== null) { this._bufferedAmount = 0; this._isServer = false; this._redirects = 0; if (Array.isArray(protocols)) { protocols = protocols.join(', '); } else if (typeof protocols === 'object' && protocols !== null) { options = protocols; protocols = undefined; } initAsClient(this, address, protocols, options); } else { this._isServer = true; } } get CONNECTING() { return WebSocket.CONNECTING; } get CLOSING() { return WebSocket.CLOSING; } get CLOSED() { return WebSocket.CLOSED; } get OPEN() { return WebSocket.OPEN; } /** * This deviates from the WHATWG interface since ws doesn't support the * required default "blob" type (instead we define a custom "nodebuffer" * type). * * @type {String} */ get binaryType() { return this._binaryType; } set binaryType(type) { if (!BINARY_TYPES.includes(type)) return; this._binaryType = type; // // Allow to change `binaryType` on the fly. // if (this._receiver) this._receiver._binaryType = type; } /** * @type {Number} */ get bufferedAmount() { if (!this._socket) return this._bufferedAmount; return this._socket._writableState.length + this._sender._bufferedBytes; } /** * @type {String} */ get extensions() { return Object.keys(this._extensions).join(); } /** * Set up the socket and the internal resources. * * @param {net.Socket} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Number} maxPayload The maximum allowed message size * @private */ setSocket(socket, head, maxPayload) { const receiver = new Receiver( this._binaryType, this._extensions, this._isServer, maxPayload ); this._sender = new Sender(socket, this._extensions); this._receiver = receiver; this._socket = socket; receiver[kWebSocket] = this; socket[kWebSocket] = this; receiver.on('conclude', receiverOnConclude); receiver.on('drain', receiverOnDrain); receiver.on('error', receiverOnError); receiver.on('message', receiverOnMessage); receiver.on('ping', receiverOnPing); receiver.on('pong', receiverOnPong); socket.setTimeout(0); socket.setNoDelay(); if (head.length > 0) socket.unshift(head); socket.on('close', socketOnClose); socket.on('data', socketOnData); socket.on('end', socketOnEnd); socket.on('error', socketOnError); this.readyState = WebSocket.OPEN; this.emit('open'); } /** * Emit the `'close'` event. * * @private */ emitClose() { if (!this._socket) { this.readyState = WebSocket.CLOSED; this.emit('close', this._closeCode, this._closeMessage); return; } if (this._extensions[PerMessageDeflate.extensionName]) { this._extensions[PerMessageDeflate.extensionName].cleanup(); } this._receiver.removeAllListeners(); this.readyState = WebSocket.CLOSED; this.emit('close', this._closeCode, this._closeMessage); } /** * Start a closing handshake. * * +----------+ +-----------+ +----------+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - * | +----------+ +-----------+ +----------+ | * +----------+ +-----------+ | * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING * +----------+ +-----------+ | * | | | +---+ | * +------------------------+-->|fin| - - - - * | +---+ | +---+ * - - - - -|fin|<---------------------+ * +---+ * * @param {Number} code Status code explaining why the connection is closing * @param {String} data A string explaining why the connection is closing * @public */ close(code, data) { if (this.readyState === WebSocket.CLOSED) return; if (this.readyState === WebSocket.CONNECTING) { const msg = 'WebSocket was closed before the connection was established'; return abortHandshake(this, this._req, msg); } if (this.readyState === WebSocket.CLOSING) { if (this._closeFrameSent && this._closeFrameReceived) this._socket.end(); return; } this.readyState = WebSocket.CLOSING; this._sender.close(code, data, !this._isServer, (err) => { // // This error is handled by the `'error'` listener on the socket. We only // want to know if the close frame has been sent here. // if (err) return; this._closeFrameSent = true; if (this._closeFrameReceived) this._socket.end(); }); // // Specify a timeout for the closing handshake to complete. // this._closeTimer = setTimeout( this._socket.destroy.bind(this._socket), closeTimeout ); } /** * Send a ping. * * @param {*} data The data to send * @param {Boolean} mask Indicates whether or not to mask `data` * @param {Function} cb Callback which is executed when the ping is sent * @public */ ping(data, mask, cb) { if (this.readyState === WebSocket.CONNECTING) { throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); } if (typeof data === 'function') { cb = data; data = mask = undefined; } else if (typeof mask === 'function') { cb = mask; mask = undefined; } if (typeof data === 'number') data = data.toString(); if (this.readyState !== WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === undefined) mask = !this._isServer; this._sender.ping(data || EMPTY_BUFFER, mask, cb); } /** * Send a pong. * * @param {*} data The data to send * @param {Boolean} mask Indicates whether or not to mask `data` * @param {Function} cb Callback which is executed when the pong is sent * @public */ pong(data, mask, cb) { if (this.readyState === WebSocket.CONNECTING) { throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); } if (typeof data === 'function') { cb = data; data = mask = undefined; } else if (typeof mask === 'function') { cb = mask; mask = undefined; } if (typeof data === 'number') data = data.toString(); if (this.readyState !== WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === undefined) mask = !this._isServer; this._sender.pong(data || EMPTY_BUFFER, mask, cb); } /** * Send a data message. * * @param {*} data The message to send * @param {Object} options Options object * @param {Boolean} options.compress Specifies whether or not to compress * `data` * @param {Boolean} options.binary Specifies whether `data` is binary or text * @param {Boolean} options.fin Specifies whether the fragment is the last one * @param {Boolean} options.mask Specifies whether or not to mask `data` * @param {Function} cb Callback which is executed when data is written out * @public */ send(data, options, cb) { if (this.readyState === WebSocket.CONNECTING) { throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); } if (typeof options === 'function') { cb = options; options = {}; } if (typeof data === 'number') data = data.toString(); if (this.readyState !== WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } const opts = { binary: typeof data !== 'string', mask: !this._isServer, compress: true, fin: true, ...options }; if (!this._extensions[PerMessageDeflate.extensionName]) { opts.compress = false; } this._sender.send(data || EMPTY_BUFFER, opts, cb); } /** * Forcibly close the connection. * * @public */ terminate() { if (this.readyState === WebSocket.CLOSED) return; if (this.readyState === WebSocket.CONNECTING) { const msg = 'WebSocket was closed before the connection was established'; return abortHandshake(this, this._req, msg); } if (this._socket) { this.readyState = WebSocket.CLOSING; this._socket.destroy(); } } } readyStates.forEach((readyState, i) => { WebSocket[readyState] = i; }); // // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface // ['open', 'error', 'close', 'message'].forEach((method) => { Object.defineProperty(WebSocket.prototype, `on${method}`, { /** * Return the listener of the event. * * @return {(Function|undefined)} The event listener or `undefined` * @public */ get() { const listeners = this.listeners(method); for (let i = 0; i < listeners.length; i++) { if (listeners[i]._listener) return listeners[i]._listener; } return undefined; }, /** * Add a listener for the event. * * @param {Function} listener The listener to add * @public */ set(listener) { const listeners = this.listeners(method); for (let i = 0; i < listeners.length; i++) { // // Remove only the listeners added via `addEventListener`. // if (listeners[i]._listener) this.removeListener(method, listeners[i]); } this.addEventListener(method, listener); } }); }); WebSocket.prototype.addEventListener = addEventListener; WebSocket.prototype.removeEventListener = removeEventListener; module.exports = WebSocket; /** * Initialize a WebSocket client. * * @param {WebSocket} websocket The client to initialize * @param {(String|url.URL)} address The URL to which to connect * @param {String} protocols The subprotocols * @param {Object} options Connection options * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable * permessage-deflate * @param {Number} options.handshakeTimeout Timeout in milliseconds for the * handshake request * @param {Number} options.protocolVersion Value of the `Sec-WebSocket-Version` * header * @param {String} options.origin Value of the `Origin` or * `Sec-WebSocket-Origin` header * @param {Number} options.maxPayload The maximum allowed message size * @param {Boolean} options.followRedirects Whether or not to follow redirects * @param {Number} options.maxRedirects The maximum number of redirects allowed * @private */ function initAsClient(websocket, address, protocols, options) { const opts = { protocolVersion: protocolVersions[1], maxPayload: 100 * 1024 * 1024, perMessageDeflate: true, followRedirects: false, maxRedirects: 10, ...options, createConnection: undefined, socketPath: undefined, hostname: undefined, protocol: undefined, timeout: undefined, method: undefined, host: undefined, path: undefined, port: undefined }; if (!protocolVersions.includes(opts.protocolVersion)) { throw new RangeError( `Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(', ')})` ); } let parsedUrl; if (address instanceof URL) { parsedUrl = address; websocket.url = address.href; } else { parsedUrl = new URL(address); websocket.url = address; } const isUnixSocket = parsedUrl.protocol === 'ws+unix:'; if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) { throw new Error(`Invalid URL: ${websocket.url}`); } const isSecure = parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:'; const defaultPort = isSecure ? 443 : 80; const key = randomBytes(16).toString('base64'); const get = isSecure ? https.get : http.get; let perMessageDeflate; opts.createConnection = isSecure ? tlsConnect : netConnect; opts.defaultPort = opts.defaultPort || defaultPort; opts.port = parsedUrl.port || defaultPort; opts.host = parsedUrl.hostname.startsWith('[') ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; opts.headers = { 'Sec-WebSocket-Version': opts.protocolVersion, 'Sec-WebSocket-Key': key, Connection: 'Upgrade', Upgrade: 'websocket', ...opts.headers }; opts.path = parsedUrl.pathname + parsedUrl.search; opts.timeout = opts.handshakeTimeout; if (opts.perMessageDeflate) { perMessageDeflate = new PerMessageDeflate( opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, false, opts.maxPayload ); opts.headers['Sec-WebSocket-Extensions'] = format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() }); } if (protocols) { opts.headers['Sec-WebSocket-Protocol'] = protocols; } if (opts.origin) { if (opts.protocolVersion < 13) { opts.headers['Sec-WebSocket-Origin'] = opts.origin; } else { opts.headers.Origin = opts.origin; } } if (parsedUrl.username || parsedUrl.password) { opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; } if (isUnixSocket) { const parts = opts.path.split(':'); opts.socketPath = parts[0]; opts.path = parts[1]; } let req = (websocket._req = get(opts)); if (opts.timeout) { req.on('timeout', () => { abortHandshake(websocket, req, 'Opening handshake has timed out'); }); } req.on('error', (err) => { if (websocket._req.aborted) return; req = websocket._req = null; websocket.readyState = WebSocket.CLOSING; websocket.emit('error', err); websocket.emitClose(); }); req.on('response', (res) => { const location = res.headers.location; const statusCode = res.statusCode; if ( location && opts.followRedirects && statusCode >= 300 && statusCode < 400 ) { if (++websocket._redirects > opts.maxRedirects) { abortHandshake(websocket, req, 'Maximum redirects exceeded'); return; } req.abort(); const addr = new URL(location, address); initAsClient(websocket, addr, protocols, options); } else if (!websocket.emit('unexpected-response', req, res)) { abortHandshake( websocket, req, `Unexpected server response: ${res.statusCode}` ); } }); req.on('upgrade', (res, socket, head) => { websocket.emit('upgrade', res); // // The user may have closed the connection from a listener of the `upgrade` // event. // if (websocket.readyState !== WebSocket.CONNECTING) return; req = websocket._req = null; const digest = createHash('sha1') .update(key + GUID) .digest('base64'); if (res.headers['sec-websocket-accept'] !== digest) { abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); return; } const serverProt = res.headers['sec-websocket-protocol']; const protList = (protocols || '').split(/, */); let protError; if (!protocols && serverProt) { protError = 'Server sent a subprotocol but none was requested'; } else if (protocols && !serverProt) { protError = 'Server sent no subprotocol'; } else if (serverProt && !protList.includes(serverProt)) { protError = 'Server sent an invalid subprotocol'; } if (protError) { abortHandshake(websocket, socket, protError); return; } if (serverProt) websocket.protocol = serverProt; if (perMessageDeflate) { try { const extensions = parse(res.headers['sec-websocket-extensions']); if (extensions[PerMessageDeflate.extensionName]) { perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); websocket._extensions[ PerMessageDeflate.extensionName ] = perMessageDeflate; } } catch (err) { abortHandshake( websocket, socket, 'Invalid Sec-WebSocket-Extensions header' ); return; } } websocket.setSocket(socket, head, opts.maxPayload); }); } /** * Create a `net.Socket` and initiate a connection. * * @param {Object} options Connection options * @return {net.Socket} The newly created socket used to start the connection * @private */ function netConnect(options) { options.path = options.socketPath; return net.connect(options); } /** * Create a `tls.TLSSocket` and initiate a connection. * * @param {Object} options Connection options * @return {tls.TLSSocket} The newly created socket used to start the connection * @private */ function tlsConnect(options) { options.path = undefined; if (!options.servername && options.servername !== '') { options.servername = options.host; } return tls.connect(options); } /** * Abort the handshake and emit an error. * * @param {WebSocket} websocket The WebSocket instance * @param {(http.ClientRequest|net.Socket)} stream The request to abort or the * socket to destroy * @param {String} message The error message * @private */ function abortHandshake(websocket, stream, message) { websocket.readyState = WebSocket.CLOSING; const err = new Error(message); Error.captureStackTrace(err, abortHandshake); if (stream.setHeader) { stream.abort(); stream.once('abort', websocket.emitClose.bind(websocket)); websocket.emit('error', err); } else { stream.destroy(err); stream.once('error', websocket.emit.bind(websocket, 'error')); stream.once('close', websocket.emitClose.bind(websocket)); } } /** * Handle cases where the `ping()`, `pong()`, or `send()` methods are called * when the `readyState` attribute is `CLOSING` or `CLOSED`. * * @param {WebSocket} websocket The WebSocket instance * @param {*} data The data to send * @param {Function} cb Callback * @private */ function sendAfterClose(websocket, data, cb) { if (data) { const length = toBuffer(data).length; // // The `_bufferedAmount` property is used only when the peer is a client and // the opening handshake fails. Under these circumstances, in fact, the // `setSocket()` method is not called, so the `_socket` and `_sender` // properties are set to `null`. // if (websocket._socket) websocket._sender._bufferedBytes += length; else websocket._bufferedAmount += length; } if (cb) { const err = new Error( `WebSocket is not open: readyState ${websocket.readyState} ` + `(${readyStates[websocket.readyState]})` ); cb(err); } } /** * The listener of the `Receiver` `'conclude'` event. * * @param {Number} code The status code * @param {String} reason The reason for closing * @private */ function receiverOnConclude(code, reason) { const websocket = this[kWebSocket]; websocket._socket.removeListener('data', socketOnData); websocket._socket.resume(); websocket._closeFrameReceived = true; websocket._closeMessage = reason; websocket._closeCode = code; if (code === 1005) websocket.close(); else websocket.close(code, reason); } /** * The listener of the `Receiver` `'drain'` event. * * @private */ function receiverOnDrain() { this[kWebSocket]._socket.resume(); } /** * The listener of the `Receiver` `'error'` event. * * @param {(RangeError|Error)} err The emitted error * @private */ function receiverOnError(err) { const websocket = this[kWebSocket]; websocket._socket.removeListener('data', socketOnData); websocket.readyState = WebSocket.CLOSING; websocket._closeCode = err[kStatusCode]; websocket.emit('error', err); websocket._socket.destroy(); } /** * The listener of the `Receiver` `'finish'` event. * * @private */ function receiverOnFinish() { this[kWebSocket].emitClose(); } /** * The listener of the `Receiver` `'message'` event. * * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message * @private */ function receiverOnMessage(data) { this[kWebSocket].emit('message', data); } /** * The listener of the `Receiver` `'ping'` event. * * @param {Buffer} data The data included in the ping frame * @private */ function receiverOnPing(data) { const websocket = this[kWebSocket]; websocket.pong(data, !websocket._isServer, NOOP); websocket.emit('ping', data); } /** * The listener of the `Receiver` `'pong'` event. * * @param {Buffer} data The data included in the pong frame * @private */ function receiverOnPong(data) { this[kWebSocket].emit('pong', data); } /** * The listener of the `net.Socket` `'close'` event. * * @private */ function socketOnClose() { const websocket = this[kWebSocket]; this.removeListener('close', socketOnClose); this.removeListener('end', socketOnEnd); websocket.readyState = WebSocket.CLOSING; // // The close frame might not have been received or the `'end'` event emitted, // for example, if the socket was destroyed due to an error. Ensure that the // `receiver` stream is closed after writing any remaining buffered data to // it. If the readable side of the socket is in flowing mode then there is no // buffered data as everything has been already written and `readable.read()` // will return `null`. If instead, the socket is paused, any possible buffered // data will be read as a single chunk and emitted synchronously in a single // `'data'` event. // websocket._socket.read(); websocket._receiver.end(); this.removeListener('data', socketOnData); this[kWebSocket] = undefined; clearTimeout(websocket._closeTimer); if ( websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted ) { websocket.emitClose(); } else { websocket._receiver.on('error', receiverOnFinish); websocket._receiver.on('finish', receiverOnFinish); } } /** * The listener of the `net.Socket` `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function socketOnData(chunk) { if (!this[kWebSocket]._receiver.write(chunk)) { this.pause(); } } /** * The listener of the `net.Socket` `'end'` event. * * @private */ function socketOnEnd() { const websocket = this[kWebSocket]; websocket.readyState = WebSocket.CLOSING; websocket._receiver.end(); this.end(); } /** * The listener of the `net.Socket` `'error'` event. * * @private */ function socketOnError() { const websocket = this[kWebSocket]; this.removeListener('error', socketOnError); this.on('error', NOOP); if (websocket) { websocket.readyState = WebSocket.CLOSING; this.destroy(); } }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ws/lib/websocket.js
websocket.js
'use strict'; /** * Class representing an event. * * @private */ class Event { /** * Create a new `Event`. * * @param {String} type The name of the event * @param {Object} target A reference to the target to which the event was dispatched */ constructor(type, target) { this.target = target; this.type = type; } } /** * Class representing a message event. * * @extends Event * @private */ class MessageEvent extends Event { /** * Create a new `MessageEvent`. * * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data * @param {WebSocket} target A reference to the target to which the event was dispatched */ constructor(data, target) { super('message', target); this.data = data; } } /** * Class representing a close event. * * @extends Event * @private */ class CloseEvent extends Event { /** * Create a new `CloseEvent`. * * @param {Number} code The status code explaining why the connection is being closed * @param {String} reason A human-readable string explaining why the connection is closing * @param {WebSocket} target A reference to the target to which the event was dispatched */ constructor(code, reason, target) { super('close', target); this.wasClean = target._closeFrameReceived && target._closeFrameSent; this.reason = reason; this.code = code; } } /** * Class representing an open event. * * @extends Event * @private */ class OpenEvent extends Event { /** * Create a new `OpenEvent`. * * @param {WebSocket} target A reference to the target to which the event was dispatched */ constructor(target) { super('open', target); } } /** * Class representing an error event. * * @extends Event * @private */ class ErrorEvent extends Event { /** * Create a new `ErrorEvent`. * * @param {Object} error The error that generated this event * @param {WebSocket} target A reference to the target to which the event was dispatched */ constructor(error, target) { super('error', target); this.message = error.message; this.error = error; } } /** * This provides methods for emulating the `EventTarget` interface. It's not * meant to be used directly. * * @mixin */ const EventTarget = { /** * Register an event listener. * * @param {String} type A string representing the event type to listen for * @param {Function} listener The listener to add * @param {Object} options An options object specifies characteristics about * the event listener * @param {Boolean} options.once A `Boolean`` indicating that the listener * should be invoked at most once after being added. If `true`, the * listener would be automatically removed when invoked. * @public */ addEventListener(type, listener, options) { if (typeof listener !== 'function') return; function onMessage(data) { listener.call(this, new MessageEvent(data, this)); } function onClose(code, message) { listener.call(this, new CloseEvent(code, message, this)); } function onError(error) { listener.call(this, new ErrorEvent(error, this)); } function onOpen() { listener.call(this, new OpenEvent(this)); } const method = options && options.once ? 'once' : 'on'; if (type === 'message') { onMessage._listener = listener; this[method](type, onMessage); } else if (type === 'close') { onClose._listener = listener; this[method](type, onClose); } else if (type === 'error') { onError._listener = listener; this[method](type, onError); } else if (type === 'open') { onOpen._listener = listener; this[method](type, onOpen); } else { this[method](type, listener); } }, /** * Remove an event listener. * * @param {String} type A string representing the event type to remove * @param {Function} listener The listener to remove * @public */ removeEventListener(type, listener) { const listeners = this.listeners(type); for (let i = 0; i < listeners.length; i++) { if (listeners[i] === listener || listeners[i]._listener === listener) { this.removeListener(type, listeners[i]); } } } }; module.exports = EventTarget;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ws/lib/event-target.js
event-target.js
'use strict'; // // Allowed token characters: // // '!', '#', '$', '%', '&', ''', '*', '+', '-', // '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' // // tokenChars[32] === 0 // ' ' // tokenChars[33] === 1 // '!' // tokenChars[34] === 0 // '"' // ... // // prettier-ignore const tokenChars = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 ]; /** * Adds an offer to the map of extension offers or a parameter to the map of * parameters. * * @param {Object} dest The map of extension offers or parameters * @param {String} name The extension or parameter name * @param {(Object|Boolean|String)} elem The extension parameters or the * parameter value * @private */ function push(dest, name, elem) { if (dest[name] === undefined) dest[name] = [elem]; else dest[name].push(elem); } /** * Parses the `Sec-WebSocket-Extensions` header into an object. * * @param {String} header The field value of the header * @return {Object} The parsed object * @public */ function parse(header) { const offers = Object.create(null); if (header === undefined || header === '') return offers; let params = Object.create(null); let mustUnescape = false; let isEscaping = false; let inQuotes = false; let extensionName; let paramName; let start = -1; let end = -1; let i = 0; for (; i < header.length; i++) { const code = header.charCodeAt(i); if (extensionName === undefined) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (code === 0x20 /* ' ' */ || code === 0x09 /* '\t' */) { if (end === -1 && start !== -1) end = i; } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; const name = header.slice(start, end); if (code === 0x2c) { push(offers, name, params); params = Object.create(null); } else { extensionName = name; } start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else if (paramName === undefined) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (code === 0x20 || code === 0x09) { if (end === -1 && start !== -1) end = i; } else if (code === 0x3b || code === 0x2c) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; push(params, header.slice(start, end), true); if (code === 0x2c) { push(offers, extensionName, params); params = Object.create(null); extensionName = undefined; } start = end = -1; } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { paramName = header.slice(start, i); start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else { // // The value of a quoted-string after unescaping must conform to the // token ABNF, so only token characters are valid. // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 // if (isEscaping) { if (tokenChars[code] !== 1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (start === -1) start = i; else if (!mustUnescape) mustUnescape = true; isEscaping = false; } else if (inQuotes) { if (tokenChars[code] === 1) { if (start === -1) start = i; } else if (code === 0x22 /* '"' */ && start !== -1) { inQuotes = false; end = i; } else if (code === 0x5c /* '\' */) { isEscaping = true; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { inQuotes = true; } else if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (start !== -1 && (code === 0x20 || code === 0x09)) { if (end === -1) end = i; } else if (code === 0x3b || code === 0x2c) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; let value = header.slice(start, end); if (mustUnescape) { value = value.replace(/\\/g, ''); mustUnescape = false; } push(params, paramName, value); if (code === 0x2c) { push(offers, extensionName, params); params = Object.create(null); extensionName = undefined; } paramName = undefined; start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } } if (start === -1 || inQuotes) { throw new SyntaxError('Unexpected end of input'); } if (end === -1) end = i; const token = header.slice(start, end); if (extensionName === undefined) { push(offers, token, params); } else { if (paramName === undefined) { push(params, token, true); } else if (mustUnescape) { push(params, paramName, token.replace(/\\/g, '')); } else { push(params, paramName, token); } push(offers, extensionName, params); } return offers; } /** * Builds the `Sec-WebSocket-Extensions` header field value. * * @param {Object} extensions The map of extensions and parameters to format * @return {String} A string representing the given object * @public */ function format(extensions) { return Object.keys(extensions) .map((extension) => { let configurations = extensions[extension]; if (!Array.isArray(configurations)) configurations = [configurations]; return configurations .map((params) => { return [extension] .concat( Object.keys(params).map((k) => { let values = params[k]; if (!Array.isArray(values)) values = [values]; return values .map((v) => (v === true ? k : `${k}=${v}`)) .join('; '); }) ) .join('; '); }) .join(', '); }) .join(', '); } module.exports = { format, parse };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ws/lib/extension.js
extension.js
# Changelog ## not yet released None yet. ## v1.4.1 (2017-08-02) * #21 Update verror dep * #22 Update extsprintf dependency * #23 update contribution guidelines ## v1.4.0 (2017-03-13) * #7 Add parseInteger() function for safer number parsing ## v1.3.1 (2016-09-12) * #13 Incompatible with webpack ## v1.3.0 (2016-06-22) * #14 add safer version of hasOwnProperty() * #15 forEachKey() should ignore inherited properties ## v1.2.2 (2015-10-15) * #11 NPM package shouldn't include any code that does `require('JSV')` * #12 jsl.node.conf missing definition for "module" ## v1.2.1 (2015-10-14) * #8 odd date parsing behaviour ## v1.2.0 (2015-10-13) * #9 want function for returning RFC1123 dates ## v1.1.0 (2015-09-02) * #6 a new suite of hrtime manipulation routines: `hrtimeAdd()`, `hrtimeAccum()`, `hrtimeNanosec()`, `hrtimeMicrosec()` and `hrtimeMillisec()`. ## v1.0.0 (2015-09-01) First tracked release. Includes everything in previous releases, plus: * #4 want function for merging objects
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsprim/CHANGES.md
CHANGES.md
# jsprim: utilities for primitive JavaScript types This module provides miscellaneous facilities for working with strings, numbers, dates, and objects and arrays of these basic types. ### deepCopy(obj) Creates a deep copy of a primitive type, object, or array of primitive types. ### deepEqual(obj1, obj2) Returns whether two objects are equal. ### isEmpty(obj) Returns true if the given object has no properties and false otherwise. This is O(1) (unlike `Object.keys(obj).length === 0`, which is O(N)). ### hasKey(obj, key) Returns true if the given object has an enumerable, non-inherited property called `key`. [For information on enumerability and ownership of properties, see the MDN documentation.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) ### forEachKey(obj, callback) Like Array.forEach, but iterates enumerable, owned properties of an object rather than elements of an array. Equivalent to: for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { callback(key, obj[key]); } } ### flattenObject(obj, depth) Flattens an object up to a given level of nesting, returning an array of arrays of length "depth + 1", where the first "depth" elements correspond to flattened columns and the last element contains the remaining object . For example: flattenObject({ 'I': { 'A': { 'i': { 'datum1': [ 1, 2 ], 'datum2': [ 3, 4 ] }, 'ii': { 'datum1': [ 3, 4 ] } }, 'B': { 'i': { 'datum1': [ 5, 6 ] }, 'ii': { 'datum1': [ 7, 8 ], 'datum2': [ 3, 4 ], }, 'iii': { } } }, 'II': { 'A': { 'i': { 'datum1': [ 1, 2 ], 'datum2': [ 3, 4 ] } } } }, 3) becomes: [ [ 'I', 'A', 'i', { 'datum1': [ 1, 2 ], 'datum2': [ 3, 4 ] } ], [ 'I', 'A', 'ii', { 'datum1': [ 3, 4 ] } ], [ 'I', 'B', 'i', { 'datum1': [ 5, 6 ] } ], [ 'I', 'B', 'ii', { 'datum1': [ 7, 8 ], 'datum2': [ 3, 4 ] } ], [ 'I', 'B', 'iii', {} ], [ 'II', 'A', 'i', { 'datum1': [ 1, 2 ], 'datum2': [ 3, 4 ] } ] ] This function is strict: "depth" must be a non-negative integer and "obj" must be a non-null object with at least "depth" levels of nesting under all keys. ### flattenIter(obj, depth, func) This is similar to `flattenObject` except that instead of returning an array, this function invokes `func(entry)` for each `entry` in the array that `flattenObject` would return. `flattenIter(obj, depth, func)` is logically equivalent to `flattenObject(obj, depth).forEach(func)`. Importantly, this version never constructs the full array. Its memory usage is O(depth) rather than O(n) (where `n` is the number of flattened elements). There's another difference between `flattenObject` and `flattenIter` that's related to the special case where `depth === 0`. In this case, `flattenObject` omits the array wrapping `obj` (which is regrettable). ### pluck(obj, key) Fetch nested property "key" from object "obj", traversing objects as needed. For example, `pluck(obj, "foo.bar.baz")` is roughly equivalent to `obj.foo.bar.baz`, except that: 1. If traversal fails, the resulting value is undefined, and no error is thrown. For example, `pluck({}, "foo.bar")` is just undefined. 2. If "obj" has property "key" directly (without traversing), the corresponding property is returned. For example, `pluck({ 'foo.bar': 1 }, 'foo.bar')` is 1, not undefined. This is also true recursively, so `pluck({ 'a': { 'foo.bar': 1 } }, 'a.foo.bar')` is also 1, not undefined. ### randElt(array) Returns an element from "array" selected uniformly at random. If "array" is empty, throws an Error. ### startsWith(str, prefix) Returns true if the given string starts with the given prefix and false otherwise. ### endsWith(str, suffix) Returns true if the given string ends with the given suffix and false otherwise. ### parseInteger(str, options) Parses the contents of `str` (a string) as an integer. On success, the integer value is returned (as a number). On failure, an error is **returned** describing why parsing failed. By default, leading and trailing whitespace characters are not allowed, nor are trailing characters that are not part of the numeric representation. This behaviour can be toggled by using the options below. The empty string (`''`) is not considered valid input. If the return value cannot be precisely represented as a number (i.e., is smaller than `Number.MIN_SAFE_INTEGER` or larger than `Number.MAX_SAFE_INTEGER`), an error is returned. Additionally, the string `'-0'` will be parsed as the integer `0`, instead of as the IEEE floating point value `-0`. This function accepts both upper and lowercase characters for digits, similar to `parseInt()`, `Number()`, and [strtol(3C)](https://illumos.org/man/3C/strtol). The following may be specified in `options`: Option | Type | Default | Meaning ------------------ | ------- | ------- | --------------------------- base | number | 10 | numeric base (radix) to use, in the range 2 to 36 allowSign | boolean | true | whether to interpret any leading `+` (positive) and `-` (negative) characters allowImprecise | boolean | false | whether to accept values that may have lost precision (past `MAX_SAFE_INTEGER` or below `MIN_SAFE_INTEGER`) allowPrefix | boolean | false | whether to interpret the prefixes `0b` (base 2), `0o` (base 8), `0t` (base 10), or `0x` (base 16) allowTrailing | boolean | false | whether to ignore trailing characters trimWhitespace | boolean | false | whether to trim any leading or trailing whitespace/line terminators leadingZeroIsOctal | boolean | false | whether a leading zero indicates octal Note that if `base` is unspecified, and `allowPrefix` or `leadingZeroIsOctal` are, then the leading characters can change the default base from 10. If `base` is explicitly specified and `allowPrefix` is true, then the prefix will only be accepted if it matches the specified base. `base` and `leadingZeroIsOctal` cannot be used together. **Context:** It's tricky to parse integers with JavaScript's built-in facilities for several reasons: - `parseInt()` and `Number()` by default allow the base to be specified in the input string by a prefix (e.g., `0x` for hex). - `parseInt()` allows trailing nonnumeric characters. - `Number(str)` returns 0 when `str` is the empty string (`''`). - Both functions return incorrect values when the input string represents a valid integer outside the range of integers that can be represented precisely. Specifically, `parseInt('9007199254740993')` returns 9007199254740992. - Both functions always accept `-` and `+` signs before the digit. - Some older JavaScript engines always interpret a leading 0 as indicating octal, which can be surprising when parsing input from users who expect a leading zero to be insignificant. While each of these may be desirable in some contexts, there are also times when none of them are wanted. `parseInteger()` grants greater control over what input's permissible. ### iso8601(date) Converts a Date object to an ISO8601 date string of the form "YYYY-MM-DDTHH:MM:SS.sssZ". This format is not customizable. ### parseDateTime(str) Parses a date expressed as a string, as either a number of milliseconds since the epoch or any string format that Date accepts, giving preference to the former where these two sets overlap (e.g., strings containing small numbers). ### hrtimeDiff(timeA, timeB) Given two hrtime readings (as from Node's `process.hrtime()`), where timeA is later than timeB, compute the difference and return that as an hrtime. It is illegal to invoke this for a pair of times where timeB is newer than timeA. ### hrtimeAdd(timeA, timeB) Add two hrtime intervals (as from Node's `process.hrtime()`), returning a new hrtime interval array. This function does not modify either input argument. ### hrtimeAccum(timeA, timeB) Add two hrtime intervals (as from Node's `process.hrtime()`), storing the result in `timeA`. This function overwrites (and returns) the first argument passed in. ### hrtimeNanosec(timeA), hrtimeMicrosec(timeA), hrtimeMillisec(timeA) This suite of functions converts a hrtime interval (as from Node's `process.hrtime()`) into a scalar number of nanoseconds, microseconds or milliseconds. Results are truncated, as with `Math.floor()`. ### validateJsonObject(schema, object) Uses JSON validation (via JSV) to validate the given object against the given schema. On success, returns null. On failure, *returns* (does not throw) a useful Error object. ### extraProperties(object, allowed) Check an object for unexpected properties. Accepts the object to check, and an array of allowed property name strings. If extra properties are detected, an array of extra property names is returned. If no properties other than those in the allowed list are present on the object, the returned array will be of zero length. ### mergeObjects(provided, overrides, defaults) Merge properties from objects "provided", "overrides", and "defaults". The intended use case is for functions that accept named arguments in an "args" object, but want to provide some default values and override other values. In that case, "provided" is what the caller specified, "overrides" are what the function wants to override, and "defaults" contains default values. The function starts with the values in "defaults", overrides them with the values in "provided", and then overrides those with the values in "overrides". For convenience, any of these objects may be falsey, in which case they will be ignored. The input objects are never modified, but properties in the returned object are not deep-copied. For example: mergeObjects(undefined, { 'objectMode': true }, { 'highWaterMark': 0 }) returns: { 'objectMode': true, 'highWaterMark': 0 } For another example: mergeObjects( { 'highWaterMark': 16, 'objectMode': 7 }, /* from caller */ { 'objectMode': true }, /* overrides */ { 'highWaterMark': 0 }); /* default */ returns: { 'objectMode': true, 'highWaterMark': 16 } # Contributing See separate [contribution guidelines](CONTRIBUTING.md).
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsprim/README.md
README.md
# Contributing This repository uses [cr.joyent.us](https://cr.joyent.us) (Gerrit) for new changes. Anyone can submit changes. To get started, see the [cr.joyent.us user guide](https://github.com/joyent/joyent-gerrit/blob/master/docs/user/README.md). This repo does not use GitHub pull requests. See the [Joyent Engineering Guidelines](https://github.com/joyent/eng/blob/master/docs/index.md) for general best practices expected in this repository. Contributions should be "make prepush" clean. The "prepush" target runs the "check" target, which requires these separate tools: * https://github.com/davepacheco/jsstyle * https://github.com/davepacheco/javascriptlint If you're changing something non-trivial or user-facing, you may want to submit an issue first.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsprim/CONTRIBUTING.md
CONTRIBUTING.md
var mod_assert = require('assert-plus'); var mod_util = require('util'); var mod_extsprintf = require('extsprintf'); var mod_verror = require('verror'); var mod_jsonschema = require('json-schema'); /* * Public interface */ exports.deepCopy = deepCopy; exports.deepEqual = deepEqual; exports.isEmpty = isEmpty; exports.hasKey = hasKey; exports.forEachKey = forEachKey; exports.pluck = pluck; exports.flattenObject = flattenObject; exports.flattenIter = flattenIter; exports.validateJsonObject = validateJsonObjectJS; exports.validateJsonObjectJS = validateJsonObjectJS; exports.randElt = randElt; exports.extraProperties = extraProperties; exports.mergeObjects = mergeObjects; exports.startsWith = startsWith; exports.endsWith = endsWith; exports.parseInteger = parseInteger; exports.iso8601 = iso8601; exports.rfc1123 = rfc1123; exports.parseDateTime = parseDateTime; exports.hrtimediff = hrtimeDiff; exports.hrtimeDiff = hrtimeDiff; exports.hrtimeAccum = hrtimeAccum; exports.hrtimeAdd = hrtimeAdd; exports.hrtimeNanosec = hrtimeNanosec; exports.hrtimeMicrosec = hrtimeMicrosec; exports.hrtimeMillisec = hrtimeMillisec; /* * Deep copy an acyclic *basic* Javascript object. This only handles basic * scalars (strings, numbers, booleans) and arbitrarily deep arrays and objects * containing these. This does *not* handle instances of other classes. */ function deepCopy(obj) { var ret, key; var marker = '__deepCopy'; if (obj && obj[marker]) throw (new Error('attempted deep copy of cyclic object')); if (obj && obj.constructor == Object) { ret = {}; obj[marker] = true; for (key in obj) { if (key == marker) continue; ret[key] = deepCopy(obj[key]); } delete (obj[marker]); return (ret); } if (obj && obj.constructor == Array) { ret = []; obj[marker] = true; for (key = 0; key < obj.length; key++) ret.push(deepCopy(obj[key])); delete (obj[marker]); return (ret); } /* * It must be a primitive type -- just return it. */ return (obj); } function deepEqual(obj1, obj2) { if (typeof (obj1) != typeof (obj2)) return (false); if (obj1 === null || obj2 === null || typeof (obj1) != 'object') return (obj1 === obj2); if (obj1.constructor != obj2.constructor) return (false); var k; for (k in obj1) { if (!obj2.hasOwnProperty(k)) return (false); if (!deepEqual(obj1[k], obj2[k])) return (false); } for (k in obj2) { if (!obj1.hasOwnProperty(k)) return (false); } return (true); } function isEmpty(obj) { var key; for (key in obj) return (false); return (true); } function hasKey(obj, key) { mod_assert.equal(typeof (key), 'string'); return (Object.prototype.hasOwnProperty.call(obj, key)); } function forEachKey(obj, callback) { for (var key in obj) { if (hasKey(obj, key)) { callback(key, obj[key]); } } } function pluck(obj, key) { mod_assert.equal(typeof (key), 'string'); return (pluckv(obj, key)); } function pluckv(obj, key) { if (obj === null || typeof (obj) !== 'object') return (undefined); if (obj.hasOwnProperty(key)) return (obj[key]); var i = key.indexOf('.'); if (i == -1) return (undefined); var key1 = key.substr(0, i); if (!obj.hasOwnProperty(key1)) return (undefined); return (pluckv(obj[key1], key.substr(i + 1))); } /* * Invoke callback(row) for each entry in the array that would be returned by * flattenObject(data, depth). This is just like flattenObject(data, * depth).forEach(callback), except that the intermediate array is never * created. */ function flattenIter(data, depth, callback) { doFlattenIter(data, depth, [], callback); } function doFlattenIter(data, depth, accum, callback) { var each; var key; if (depth === 0) { each = accum.slice(0); each.push(data); callback(each); return; } mod_assert.ok(data !== null); mod_assert.equal(typeof (data), 'object'); mod_assert.equal(typeof (depth), 'number'); mod_assert.ok(depth >= 0); for (key in data) { each = accum.slice(0); each.push(key); doFlattenIter(data[key], depth - 1, each, callback); } } function flattenObject(data, depth) { if (depth === 0) return ([ data ]); mod_assert.ok(data !== null); mod_assert.equal(typeof (data), 'object'); mod_assert.equal(typeof (depth), 'number'); mod_assert.ok(depth >= 0); var rv = []; var key; for (key in data) { flattenObject(data[key], depth - 1).forEach(function (p) { rv.push([ key ].concat(p)); }); } return (rv); } function startsWith(str, prefix) { return (str.substr(0, prefix.length) == prefix); } function endsWith(str, suffix) { return (str.substr( str.length - suffix.length, suffix.length) == suffix); } function iso8601(d) { if (typeof (d) == 'number') d = new Date(d); mod_assert.ok(d.constructor === Date); return (mod_extsprintf.sprintf('%4d-%02d-%02dT%02d:%02d:%02d.%03dZ', d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds())); } var RFC1123_MONTHS = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; var RFC1123_DAYS = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; function rfc1123(date) { return (mod_extsprintf.sprintf('%s, %02d %s %04d %02d:%02d:%02d GMT', RFC1123_DAYS[date.getUTCDay()], date.getUTCDate(), RFC1123_MONTHS[date.getUTCMonth()], date.getUTCFullYear(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds())); } /* * Parses a date expressed as a string, as either a number of milliseconds since * the epoch or any string format that Date accepts, giving preference to the * former where these two sets overlap (e.g., small numbers). */ function parseDateTime(str) { /* * This is irritatingly implicit, but significantly more concise than * alternatives. The "+str" will convert a string containing only a * number directly to a Number, or NaN for other strings. Thus, if the * conversion succeeds, we use it (this is the milliseconds-since-epoch * case). Otherwise, we pass the string directly to the Date * constructor to parse. */ var numeric = +str; if (!isNaN(numeric)) { return (new Date(numeric)); } else { return (new Date(str)); } } /* * Number.*_SAFE_INTEGER isn't present before node v0.12, so we hardcode * the ES6 definitions here, while allowing for them to someday be higher. */ var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991; /* * Default options for parseInteger(). */ var PI_DEFAULTS = { base: 10, allowSign: true, allowPrefix: false, allowTrailing: false, allowImprecise: false, trimWhitespace: false, leadingZeroIsOctal: false }; var CP_0 = 0x30; var CP_9 = 0x39; var CP_A = 0x41; var CP_B = 0x42; var CP_O = 0x4f; var CP_T = 0x54; var CP_X = 0x58; var CP_Z = 0x5a; var CP_a = 0x61; var CP_b = 0x62; var CP_o = 0x6f; var CP_t = 0x74; var CP_x = 0x78; var CP_z = 0x7a; var PI_CONV_DEC = 0x30; var PI_CONV_UC = 0x37; var PI_CONV_LC = 0x57; /* * A stricter version of parseInt() that provides options for changing what * is an acceptable string (for example, disallowing trailing characters). */ function parseInteger(str, uopts) { mod_assert.string(str, 'str'); mod_assert.optionalObject(uopts, 'options'); var baseOverride = false; var options = PI_DEFAULTS; if (uopts) { baseOverride = hasKey(uopts, 'base'); options = mergeObjects(options, uopts); mod_assert.number(options.base, 'options.base'); mod_assert.ok(options.base >= 2, 'options.base >= 2'); mod_assert.ok(options.base <= 36, 'options.base <= 36'); mod_assert.bool(options.allowSign, 'options.allowSign'); mod_assert.bool(options.allowPrefix, 'options.allowPrefix'); mod_assert.bool(options.allowTrailing, 'options.allowTrailing'); mod_assert.bool(options.allowImprecise, 'options.allowImprecise'); mod_assert.bool(options.trimWhitespace, 'options.trimWhitespace'); mod_assert.bool(options.leadingZeroIsOctal, 'options.leadingZeroIsOctal'); if (options.leadingZeroIsOctal) { mod_assert.ok(!baseOverride, '"base" and "leadingZeroIsOctal" are ' + 'mutually exclusive'); } } var c; var pbase = -1; var base = options.base; var start; var mult = 1; var value = 0; var idx = 0; var len = str.length; /* Trim any whitespace on the left side. */ if (options.trimWhitespace) { while (idx < len && isSpace(str.charCodeAt(idx))) { ++idx; } } /* Check the number for a leading sign. */ if (options.allowSign) { if (str[idx] === '-') { idx += 1; mult = -1; } else if (str[idx] === '+') { idx += 1; } } /* Parse the base-indicating prefix if there is one. */ if (str[idx] === '0') { if (options.allowPrefix) { pbase = prefixToBase(str.charCodeAt(idx + 1)); if (pbase !== -1 && (!baseOverride || pbase === base)) { base = pbase; idx += 2; } } if (pbase === -1 && options.leadingZeroIsOctal) { base = 8; } } /* Parse the actual digits. */ for (start = idx; idx < len; ++idx) { c = translateDigit(str.charCodeAt(idx)); if (c !== -1 && c < base) { value *= base; value += c; } else { break; } } /* If we didn't parse any digits, we have an invalid number. */ if (start === idx) { return (new Error('invalid number: ' + JSON.stringify(str))); } /* Trim any whitespace on the right side. */ if (options.trimWhitespace) { while (idx < len && isSpace(str.charCodeAt(idx))) { ++idx; } } /* Check for trailing characters. */ if (idx < len && !options.allowTrailing) { return (new Error('trailing characters after number: ' + JSON.stringify(str.slice(idx)))); } /* If our value is 0, we return now, to avoid returning -0. */ if (value === 0) { return (0); } /* Calculate our final value. */ var result = value * mult; /* * If the string represents a value that cannot be precisely represented * by JavaScript, then we want to check that: * * - We never increased the value past MAX_SAFE_INTEGER * - We don't make the result negative and below MIN_SAFE_INTEGER * * Because we only ever increment the value during parsing, there's no * chance of moving past MAX_SAFE_INTEGER and then dropping below it * again, losing precision in the process. This means that we only need * to do our checks here, at the end. */ if (!options.allowImprecise && (value > MAX_SAFE_INTEGER || result < MIN_SAFE_INTEGER)) { return (new Error('number is outside of the supported range: ' + JSON.stringify(str.slice(start, idx)))); } return (result); } /* * Interpret a character code as a base-36 digit. */ function translateDigit(d) { if (d >= CP_0 && d <= CP_9) { /* '0' to '9' -> 0 to 9 */ return (d - PI_CONV_DEC); } else if (d >= CP_A && d <= CP_Z) { /* 'A' - 'Z' -> 10 to 35 */ return (d - PI_CONV_UC); } else if (d >= CP_a && d <= CP_z) { /* 'a' - 'z' -> 10 to 35 */ return (d - PI_CONV_LC); } else { /* Invalid character code */ return (-1); } } /* * Test if a value matches the ECMAScript definition of trimmable whitespace. */ function isSpace(c) { return (c === 0x20) || (c >= 0x0009 && c <= 0x000d) || (c === 0x00a0) || (c === 0x1680) || (c === 0x180e) || (c >= 0x2000 && c <= 0x200a) || (c === 0x2028) || (c === 0x2029) || (c === 0x202f) || (c === 0x205f) || (c === 0x3000) || (c === 0xfeff); } /* * Determine which base a character indicates (e.g., 'x' indicates hex). */ function prefixToBase(c) { if (c === CP_b || c === CP_B) { /* 0b/0B (binary) */ return (2); } else if (c === CP_o || c === CP_O) { /* 0o/0O (octal) */ return (8); } else if (c === CP_t || c === CP_T) { /* 0t/0T (decimal) */ return (10); } else if (c === CP_x || c === CP_X) { /* 0x/0X (hexadecimal) */ return (16); } else { /* Not a meaningful character */ return (-1); } } function validateJsonObjectJS(schema, input) { var report = mod_jsonschema.validate(input, schema); if (report.errors.length === 0) return (null); /* Currently, we only do anything useful with the first error. */ var error = report.errors[0]; /* The failed property is given by a URI with an irrelevant prefix. */ var propname = error['property']; var reason = error['message'].toLowerCase(); var i, j; /* * There's at least one case where the property error message is * confusing at best. We work around this here. */ if ((i = reason.indexOf('the property ')) != -1 && (j = reason.indexOf(' is not defined in the schema and the ' + 'schema does not allow additional properties')) != -1) { i += 'the property '.length; if (propname === '') propname = reason.substr(i, j - i); else propname = propname + '.' + reason.substr(i, j - i); reason = 'unsupported property'; } var rv = new mod_verror.VError('property "%s": %s', propname, reason); rv.jsv_details = error; return (rv); } function randElt(arr) { mod_assert.ok(Array.isArray(arr) && arr.length > 0, 'randElt argument must be a non-empty array'); return (arr[Math.floor(Math.random() * arr.length)]); } function assertHrtime(a) { mod_assert.ok(a[0] >= 0 && a[1] >= 0, 'negative numbers not allowed in hrtimes'); mod_assert.ok(a[1] < 1e9, 'nanoseconds column overflow'); } /* * Compute the time elapsed between hrtime readings A and B, where A is later * than B. hrtime readings come from Node's process.hrtime(). There is no * defined way to represent negative deltas, so it's illegal to diff B from A * where the time denoted by B is later than the time denoted by A. If this * becomes valuable, we can define a representation and extend the * implementation to support it. */ function hrtimeDiff(a, b) { assertHrtime(a); assertHrtime(b); mod_assert.ok(a[0] > b[0] || (a[0] == b[0] && a[1] >= b[1]), 'negative differences not allowed'); var rv = [ a[0] - b[0], 0 ]; if (a[1] >= b[1]) { rv[1] = a[1] - b[1]; } else { rv[0]--; rv[1] = 1e9 - (b[1] - a[1]); } return (rv); } /* * Convert a hrtime reading from the array format returned by Node's * process.hrtime() into a scalar number of nanoseconds. */ function hrtimeNanosec(a) { assertHrtime(a); return (Math.floor(a[0] * 1e9 + a[1])); } /* * Convert a hrtime reading from the array format returned by Node's * process.hrtime() into a scalar number of microseconds. */ function hrtimeMicrosec(a) { assertHrtime(a); return (Math.floor(a[0] * 1e6 + a[1] / 1e3)); } /* * Convert a hrtime reading from the array format returned by Node's * process.hrtime() into a scalar number of milliseconds. */ function hrtimeMillisec(a) { assertHrtime(a); return (Math.floor(a[0] * 1e3 + a[1] / 1e6)); } /* * Add two hrtime readings A and B, overwriting A with the result of the * addition. This function is useful for accumulating several hrtime intervals * into a counter. Returns A. */ function hrtimeAccum(a, b) { assertHrtime(a); assertHrtime(b); /* * Accumulate the nanosecond component. */ a[1] += b[1]; if (a[1] >= 1e9) { /* * The nanosecond component overflowed, so carry to the seconds * field. */ a[0]++; a[1] -= 1e9; } /* * Accumulate the seconds component. */ a[0] += b[0]; return (a); } /* * Add two hrtime readings A and B, returning the result as a new hrtime array. * Does not modify either input argument. */ function hrtimeAdd(a, b) { assertHrtime(a); var rv = [ a[0], a[1] ]; return (hrtimeAccum(rv, b)); } /* * Check an object for unexpected properties. Accepts the object to check, and * an array of allowed property names (strings). Returns an array of key names * that were found on the object, but did not appear in the list of allowed * properties. If no properties were found, the returned array will be of * zero length. */ function extraProperties(obj, allowed) { mod_assert.ok(typeof (obj) === 'object' && obj !== null, 'obj argument must be a non-null object'); mod_assert.ok(Array.isArray(allowed), 'allowed argument must be an array of strings'); for (var i = 0; i < allowed.length; i++) { mod_assert.ok(typeof (allowed[i]) === 'string', 'allowed argument must be an array of strings'); } return (Object.keys(obj).filter(function (key) { return (allowed.indexOf(key) === -1); })); } /* * Given three sets of properties "provided" (may be undefined), "overrides" * (required), and "defaults" (may be undefined), construct an object containing * the union of these sets with "overrides" overriding "provided", and * "provided" overriding "defaults". None of the input objects are modified. */ function mergeObjects(provided, overrides, defaults) { var rv, k; rv = {}; if (defaults) { for (k in defaults) rv[k] = defaults[k]; } if (provided) { for (k in provided) rv[k] = provided[k]; } if (overrides) { for (k in overrides) rv[k] = overrides[k]; } return (rv); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/jsprim/lib/jsprim.js
jsprim.js
var crypto = require('crypto') function sha (key, body, algorithm) { return crypto.createHmac(algorithm, key).update(body).digest('base64') } function rsa (key, body) { return crypto.createSign('RSA-SHA1').update(body).sign(key, 'base64') } function rfc3986 (str) { return encodeURIComponent(str) .replace(/!/g,'%21') .replace(/\*/g,'%2A') .replace(/\(/g,'%28') .replace(/\)/g,'%29') .replace(/'/g,'%27') } // Maps object to bi-dimensional array // Converts { foo: 'A', bar: [ 'b', 'B' ]} to // [ ['foo', 'A'], ['bar', 'b'], ['bar', 'B'] ] function map (obj) { var key, val, arr = [] for (key in obj) { val = obj[key] if (Array.isArray(val)) for (var i = 0; i < val.length; i++) arr.push([key, val[i]]) else if (typeof val === 'object') for (var prop in val) arr.push([key + '[' + prop + ']', val[prop]]) else arr.push([key, val]) } return arr } // Compare function for sort function compare (a, b) { return a > b ? 1 : a < b ? -1 : 0 } function generateBase (httpMethod, base_uri, params) { // adapted from https://dev.twitter.com/docs/auth/oauth and // https://dev.twitter.com/docs/auth/creating-signature // Parameter normalization // http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2 var normalized = map(params) // 1. First, the name and value of each parameter are encoded .map(function (p) { return [ rfc3986(p[0]), rfc3986(p[1] || '') ] }) // 2. The parameters are sorted by name, using ascending byte value // ordering. If two or more parameters share the same name, they // are sorted by their value. .sort(function (a, b) { return compare(a[0], b[0]) || compare(a[1], b[1]) }) // 3. The name of each parameter is concatenated to its corresponding // value using an "=" character (ASCII code 61) as a separator, even // if the value is empty. .map(function (p) { return p.join('=') }) // 4. The sorted name/value pairs are concatenated together into a // single string by using an "&" character (ASCII code 38) as // separator. .join('&') var base = [ rfc3986(httpMethod ? httpMethod.toUpperCase() : 'GET'), rfc3986(base_uri), rfc3986(normalized) ].join('&') return base } function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret) { var base = generateBase(httpMethod, base_uri, params) var key = [ consumer_secret || '', token_secret || '' ].map(rfc3986).join('&') return sha(key, base, 'sha1') } function hmacsign256 (httpMethod, base_uri, params, consumer_secret, token_secret) { var base = generateBase(httpMethod, base_uri, params) var key = [ consumer_secret || '', token_secret || '' ].map(rfc3986).join('&') return sha(key, base, 'sha256') } function rsasign (httpMethod, base_uri, params, private_key, token_secret) { var base = generateBase(httpMethod, base_uri, params) var key = private_key || '' return rsa(key, base) } function plaintext (consumer_secret, token_secret) { var key = [ consumer_secret || '', token_secret || '' ].map(rfc3986).join('&') return key } function sign (signMethod, httpMethod, base_uri, params, consumer_secret, token_secret) { var method var skipArgs = 1 switch (signMethod) { case 'RSA-SHA1': method = rsasign break case 'HMAC-SHA1': method = hmacsign break case 'HMAC-SHA256': method = hmacsign256 break case 'PLAINTEXT': method = plaintext skipArgs = 4 break default: throw new Error('Signature method not supported: ' + signMethod) } return method.apply(null, [].slice.call(arguments, skipArgs)) } exports.hmacsign = hmacsign exports.hmacsign256 = hmacsign256 exports.rsasign = rsasign exports.plaintext = plaintext exports.sign = sign exports.rfc3986 = rfc3986 exports.generateBase = generateBase
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/oauth-sign/index.js
index.js
# CSSStyleDeclaration A Node JS implementation of the CSS Object Model [CSSStyleDeclaration interface](https://www.w3.org/TR/cssom-1/#the-cssstyledeclaration-interface). [![NpmVersion](https://img.shields.io/npm/v/cssstyle.svg)](https://www.npmjs.com/package/cssstyle) [![Build Status](https://travis-ci.org/jsdom/cssstyle.svg?branch=master)](https://travis-ci.org/jsdom/cssstyle) [![codecov](https://codecov.io/gh/jsdom/cssstyle/branch/master/graph/badge.svg)](https://codecov.io/gh/jsdom/cssstyle) --- #### Background This package is an extension of the CSSStyleDeclaration class in Nikita Vasilyev's [CSSOM](https://github.com/NV/CSSOM) with added support for CSS 2 & 3 properties. The primary use case is for testing browser code in a Node environment. It was originally created by Chad Walker, it is now maintaind by Jon Sakas and other open source contributors. Bug reports and pull requests are welcome.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssstyle/README.md
README.md
CSSOM.js is a CSS parser written in pure JavaScript. It is also a partial implementation of [CSS Object Model](http://dev.w3.org/csswg/cssom/). CSSOM.parse("body {color: black}") -> { cssRules: [ { selectorText: "body", style: { 0: "color", color: "black", length: 1 } } ] } ## [Parser demo](http://nv.github.com/CSSOM/docs/parse.html) Works well in Google Chrome 6+, Safari 5+, Firefox 3.6+, Opera 10.63+. Doesn't work in IE < 9 because of unsupported getters/setters. To use CSSOM.js in the browser you might want to build a one-file version that exposes a single `CSSOM` global variable: ➤ git clone https://github.com/NV/CSSOM.git ➤ cd CSSOM ➤ node build.js build/CSSOM.js is done To use it with Node.js or any other CommonJS loader: ➤ npm install cssom ## Don’t use it if... You parse CSS to mungle, minify or reformat code like this: ```css div { background: gray; background: linear-gradient(to bottom, white 0%, black 100%); } ``` This pattern is often used to give browsers that don’t understand linear gradients a fallback solution (e.g. gray color in the example). In CSSOM, `background: gray` [gets overwritten](http://nv.github.io/CSSOM/docs/parse.html#css=div%20%7B%0A%20%20%20%20%20%20background%3A%20gray%3B%0A%20%20%20%20background%3A%20linear-gradient(to%20bottom%2C%20white%200%25%2C%20black%20100%25)%3B%0A%7D). It doesn't get preserved. If you do CSS mungling, minification, image inlining, and such, CSSOM.js is no good for you, considere using one of the following: * [postcss](https://github.com/postcss/postcss) * [reworkcss/css](https://github.com/reworkcss/css) * [csso](https://github.com/css/csso) * [mensch](https://github.com/brettstimmerman/mensch) ## [Tests](http://nv.github.com/CSSOM/spec/) To run tests locally: ➤ git submodule init ➤ git submodule update ## [Who uses CSSOM.js](https://github.com/NV/CSSOM/wiki/Who-uses-CSSOM.js)
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssstyle/node_modules/cssom/README.mdown
README.mdown
var CSSOM = { StyleSheet: require("cssom/lib/StyleSheet").StyleSheet, CSSStyleRule: require("cssom/lib/CSSStyleRule").CSSStyleRule }; ///CommonJS /** * @constructor * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet */ CSSOM.CSSStyleSheet = function CSSStyleSheet() { CSSOM.StyleSheet.call(this); this.cssRules = []; }; CSSOM.CSSStyleSheet.prototype = new CSSOM.StyleSheet(); CSSOM.CSSStyleSheet.prototype.constructor = CSSOM.CSSStyleSheet; /** * Used to insert a new rule into the style sheet. The new rule now becomes part of the cascade. * * sheet = new Sheet("body {margin: 0}") * sheet.toString() * -> "body{margin:0;}" * sheet.insertRule("img {border: none}", 0) * -> 0 * sheet.toString() * -> "img{border:none;}body{margin:0;}" * * @param {string} rule * @param {number} index * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-insertRule * @return {number} The index within the style sheet's rule collection of the newly inserted rule. */ CSSOM.CSSStyleSheet.prototype.insertRule = function(rule, index) { if (index < 0 || index > this.cssRules.length) { throw new RangeError("INDEX_SIZE_ERR"); } var cssRule = CSSOM.parse(rule).cssRules[0]; cssRule.parentStyleSheet = this; this.cssRules.splice(index, 0, cssRule); return index; }; /** * Used to delete a rule from the style sheet. * * sheet = new Sheet("img{border:none} body{margin:0}") * sheet.toString() * -> "img{border:none;}body{margin:0;}" * sheet.deleteRule(0) * sheet.toString() * -> "body{margin:0;}" * * @param {number} index within the style sheet's rule list of the rule to remove. * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-deleteRule */ CSSOM.CSSStyleSheet.prototype.deleteRule = function(index) { if (index < 0 || index >= this.cssRules.length) { throw new RangeError("INDEX_SIZE_ERR"); } this.cssRules.splice(index, 1); }; /** * NON-STANDARD * @return {string} serialize stylesheet */ CSSOM.CSSStyleSheet.prototype.toString = function() { var result = ""; var rules = this.cssRules; for (var i=0; i<rules.length; i++) { result += rules[i].cssText + "\n"; } return result; }; //.CommonJS exports.CSSStyleSheet = CSSOM.CSSStyleSheet; CSSOM.parse = require('cssom/lib/parse').parse; // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleSheet.js ///CommonJS
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssstyle/node_modules/cssom/lib/CSSStyleSheet.js
CSSStyleSheet.js
var CSSOM = { CSSValue: require('cssom/lib/CSSValue').CSSValue }; ///CommonJS /** * @constructor * @see http://msdn.microsoft.com/en-us/library/ms537634(v=vs.85).aspx * */ CSSOM.CSSValueExpression = function CSSValueExpression(token, idx) { this._token = token; this._idx = idx; }; CSSOM.CSSValueExpression.prototype = new CSSOM.CSSValue(); CSSOM.CSSValueExpression.prototype.constructor = CSSOM.CSSValueExpression; /** * parse css expression() value * * @return {Object} * - error: * or * - idx: * - expression: * * Example: * * .selector { * zoom: expression(documentElement.clientWidth > 1000 ? '1000px' : 'auto'); * } */ CSSOM.CSSValueExpression.prototype.parse = function() { var token = this._token, idx = this._idx; var character = '', expression = '', error = '', info, paren = []; for (; ; ++idx) { character = token.charAt(idx); // end of token if (character === '') { error = 'css expression error: unfinished expression!'; break; } switch(character) { case '(': paren.push(character); expression += character; break; case ')': paren.pop(character); expression += character; break; case '/': if ((info = this._parseJSComment(token, idx))) { // comment? if (info.error) { error = 'css expression error: unfinished comment in expression!'; } else { idx = info.idx; // ignore the comment } } else if ((info = this._parseJSRexExp(token, idx))) { // regexp idx = info.idx; expression += info.text; } else { // other expression += character; } break; case "'": case '"': info = this._parseJSString(token, idx, character); if (info) { // string idx = info.idx; expression += info.text; } else { expression += character; } break; default: expression += character; break; } if (error) { break; } // end of expression if (paren.length === 0) { break; } } var ret; if (error) { ret = { error: error }; } else { ret = { idx: idx, expression: expression }; } return ret; }; /** * * @return {Object|false} * - idx: * - text: * or * - error: * or * false * */ CSSOM.CSSValueExpression.prototype._parseJSComment = function(token, idx) { var nextChar = token.charAt(idx + 1), text; if (nextChar === '/' || nextChar === '*') { var startIdx = idx, endIdx, commentEndChar; if (nextChar === '/') { // line comment commentEndChar = '\n'; } else if (nextChar === '*') { // block comment commentEndChar = '*/'; } endIdx = token.indexOf(commentEndChar, startIdx + 1 + 1); if (endIdx !== -1) { endIdx = endIdx + commentEndChar.length - 1; text = token.substring(idx, endIdx + 1); return { idx: endIdx, text: text }; } else { var error = 'css expression error: unfinished comment in expression!'; return { error: error }; } } else { return false; } }; /** * * @return {Object|false} * - idx: * - text: * or * false * */ CSSOM.CSSValueExpression.prototype._parseJSString = function(token, idx, sep) { var endIdx = this._findMatchedIdx(token, idx, sep), text; if (endIdx === -1) { return false; } else { text = token.substring(idx, endIdx + sep.length); return { idx: endIdx, text: text }; } }; /** * parse regexp in css expression * * @return {Object|false} * - idx: * - regExp: * or * false */ /* all legal RegExp /a/ (/a/) [/a/] [12, /a/] !/a/ +/a/ -/a/ * /a/ / /a/ %/a/ ===/a/ !==/a/ ==/a/ !=/a/ >/a/ >=/a/ </a/ <=/a/ &/a/ |/a/ ^/a/ ~/a/ <</a/ >>/a/ >>>/a/ &&/a/ ||/a/ ?/a/ =/a/ ,/a/ delete /a/ in /a/ instanceof /a/ new /a/ typeof /a/ void /a/ */ CSSOM.CSSValueExpression.prototype._parseJSRexExp = function(token, idx) { var before = token.substring(0, idx).replace(/\s+$/, ""), legalRegx = [ /^$/, /\($/, /\[$/, /\!$/, /\+$/, /\-$/, /\*$/, /\/\s+/, /\%$/, /\=$/, /\>$/, /<$/, /\&$/, /\|$/, /\^$/, /\~$/, /\?$/, /\,$/, /delete$/, /in$/, /instanceof$/, /new$/, /typeof$/, /void$/ ]; var isLegal = legalRegx.some(function(reg) { return reg.test(before); }); if (!isLegal) { return false; } else { var sep = '/'; // same logic as string return this._parseJSString(token, idx, sep); } }; /** * * find next sep(same line) index in `token` * * @return {Number} * */ CSSOM.CSSValueExpression.prototype._findMatchedIdx = function(token, idx, sep) { var startIdx = idx, endIdx; var NOT_FOUND = -1; while(true) { endIdx = token.indexOf(sep, startIdx + 1); if (endIdx === -1) { // not found endIdx = NOT_FOUND; break; } else { var text = token.substring(idx + 1, endIdx), matched = text.match(/\\+$/); if (!matched || matched[0] % 2 === 0) { // not escaped break; } else { startIdx = endIdx; } } } // boundary must be in the same line(js sting or regexp) var nextNewLineIdx = token.indexOf('\n', idx + 1); if (nextNewLineIdx < endIdx) { endIdx = NOT_FOUND; } return endIdx; }; //.CommonJS exports.CSSValueExpression = CSSOM.CSSValueExpression; ///CommonJS
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssstyle/node_modules/cssom/lib/CSSValueExpression.js
CSSValueExpression.js
var CSSOM = {}; ///CommonJS /** * @param {string} token */ CSSOM.parse = function parse(token) { var i = 0; /** "before-selector" or "selector" or "atRule" or "atBlock" or "conditionBlock" or "before-name" or "name" or "before-value" or "value" */ var state = "before-selector"; var index; var buffer = ""; var valueParenthesisDepth = 0; var SIGNIFICANT_WHITESPACE = { "selector": true, "value": true, "value-parenthesis": true, "atRule": true, "importRule-begin": true, "importRule": true, "atBlock": true, "conditionBlock": true, 'documentRule-begin': true }; var styleSheet = new CSSOM.CSSStyleSheet(); // @type CSSStyleSheet|CSSMediaRule|CSSSupportsRule|CSSFontFaceRule|CSSKeyframesRule|CSSDocumentRule var currentScope = styleSheet; // @type CSSMediaRule|CSSSupportsRule|CSSKeyframesRule|CSSDocumentRule var parentRule; var ancestorRules = []; var hasAncestors = false; var prevScope; var name, priority="", styleRule, mediaRule, supportsRule, importRule, fontFaceRule, keyframesRule, documentRule, hostRule; var atKeyframesRegExp = /@(-(?:\w+-)+)?keyframes/g; var parseError = function(message) { var lines = token.substring(0, i).split('\n'); var lineCount = lines.length; var charCount = lines.pop().length + 1; var error = new Error(message + ' (line ' + lineCount + ', char ' + charCount + ')'); error.line = lineCount; /* jshint sub : true */ error['char'] = charCount; error.styleSheet = styleSheet; throw error; }; for (var character; (character = token.charAt(i)); i++) { switch (character) { case " ": case "\t": case "\r": case "\n": case "\f": if (SIGNIFICANT_WHITESPACE[state]) { buffer += character; } break; // String case '"': index = i + 1; do { index = token.indexOf('"', index) + 1; if (!index) { parseError('Unmatched "'); } } while (token[index - 2] === '\\'); buffer += token.slice(i, index); i = index - 1; switch (state) { case 'before-value': state = 'value'; break; case 'importRule-begin': state = 'importRule'; break; } break; case "'": index = i + 1; do { index = token.indexOf("'", index) + 1; if (!index) { parseError("Unmatched '"); } } while (token[index - 2] === '\\'); buffer += token.slice(i, index); i = index - 1; switch (state) { case 'before-value': state = 'value'; break; case 'importRule-begin': state = 'importRule'; break; } break; // Comment case "/": if (token.charAt(i + 1) === "*") { i += 2; index = token.indexOf("*/", i); if (index === -1) { parseError("Missing */"); } else { i = index + 1; } } else { buffer += character; } if (state === "importRule-begin") { buffer += " "; state = "importRule"; } break; // At-rule case "@": if (token.indexOf("@-moz-document", i) === i) { state = "documentRule-begin"; documentRule = new CSSOM.CSSDocumentRule(); documentRule.__starts = i; i += "-moz-document".length; buffer = ""; break; } else if (token.indexOf("@media", i) === i) { state = "atBlock"; mediaRule = new CSSOM.CSSMediaRule(); mediaRule.__starts = i; i += "media".length; buffer = ""; break; } else if (token.indexOf("@supports", i) === i) { state = "conditionBlock"; supportsRule = new CSSOM.CSSSupportsRule(); supportsRule.__starts = i; i += "supports".length; buffer = ""; break; } else if (token.indexOf("@host", i) === i) { state = "hostRule-begin"; i += "host".length; hostRule = new CSSOM.CSSHostRule(); hostRule.__starts = i; buffer = ""; break; } else if (token.indexOf("@import", i) === i) { state = "importRule-begin"; i += "import".length; buffer += "@import"; break; } else if (token.indexOf("@font-face", i) === i) { state = "fontFaceRule-begin"; i += "font-face".length; fontFaceRule = new CSSOM.CSSFontFaceRule(); fontFaceRule.__starts = i; buffer = ""; break; } else { atKeyframesRegExp.lastIndex = i; var matchKeyframes = atKeyframesRegExp.exec(token); if (matchKeyframes && matchKeyframes.index === i) { state = "keyframesRule-begin"; keyframesRule = new CSSOM.CSSKeyframesRule(); keyframesRule.__starts = i; keyframesRule._vendorPrefix = matchKeyframes[1]; // Will come out as undefined if no prefix was found i += matchKeyframes[0].length - 1; buffer = ""; break; } else if (state === "selector") { state = "atRule"; } } buffer += character; break; case "{": if (state === "selector" || state === "atRule") { styleRule.selectorText = buffer.trim(); styleRule.style.__starts = i; buffer = ""; state = "before-name"; } else if (state === "atBlock") { mediaRule.media.mediaText = buffer.trim(); if (parentRule) { ancestorRules.push(parentRule); } currentScope = parentRule = mediaRule; mediaRule.parentStyleSheet = styleSheet; buffer = ""; state = "before-selector"; } else if (state === "conditionBlock") { supportsRule.conditionText = buffer.trim(); if (parentRule) { ancestorRules.push(parentRule); } currentScope = parentRule = supportsRule; supportsRule.parentStyleSheet = styleSheet; buffer = ""; state = "before-selector"; } else if (state === "hostRule-begin") { if (parentRule) { ancestorRules.push(parentRule); } currentScope = parentRule = hostRule; hostRule.parentStyleSheet = styleSheet; buffer = ""; state = "before-selector"; } else if (state === "fontFaceRule-begin") { if (parentRule) { ancestorRules.push(parentRule); fontFaceRule.parentRule = parentRule; } fontFaceRule.parentStyleSheet = styleSheet; styleRule = fontFaceRule; buffer = ""; state = "before-name"; } else if (state === "keyframesRule-begin") { keyframesRule.name = buffer.trim(); if (parentRule) { ancestorRules.push(parentRule); keyframesRule.parentRule = parentRule; } keyframesRule.parentStyleSheet = styleSheet; currentScope = parentRule = keyframesRule; buffer = ""; state = "keyframeRule-begin"; } else if (state === "keyframeRule-begin") { styleRule = new CSSOM.CSSKeyframeRule(); styleRule.keyText = buffer.trim(); styleRule.__starts = i; buffer = ""; state = "before-name"; } else if (state === "documentRule-begin") { // FIXME: what if this '{' is in the url text of the match function? documentRule.matcher.matcherText = buffer.trim(); if (parentRule) { ancestorRules.push(parentRule); documentRule.parentRule = parentRule; } currentScope = parentRule = documentRule; documentRule.parentStyleSheet = styleSheet; buffer = ""; state = "before-selector"; } break; case ":": if (state === "name") { name = buffer.trim(); buffer = ""; state = "before-value"; } else { buffer += character; } break; case "(": if (state === 'value') { // ie css expression mode if (buffer.trim() === 'expression') { var info = (new CSSOM.CSSValueExpression(token, i)).parse(); if (info.error) { parseError(info.error); } else { buffer += info.expression; i = info.idx; } } else { state = 'value-parenthesis'; //always ensure this is reset to 1 on transition //from value to value-parenthesis valueParenthesisDepth = 1; buffer += character; } } else if (state === 'value-parenthesis') { valueParenthesisDepth++; buffer += character; } else { buffer += character; } break; case ")": if (state === 'value-parenthesis') { valueParenthesisDepth--; if (valueParenthesisDepth === 0) state = 'value'; } buffer += character; break; case "!": if (state === "value" && token.indexOf("!important", i) === i) { priority = "important"; i += "important".length; } else { buffer += character; } break; case ";": switch (state) { case "value": styleRule.style.setProperty(name, buffer.trim(), priority); priority = ""; buffer = ""; state = "before-name"; break; case "atRule": buffer = ""; state = "before-selector"; break; case "importRule": importRule = new CSSOM.CSSImportRule(); importRule.parentStyleSheet = importRule.styleSheet.parentStyleSheet = styleSheet; importRule.cssText = buffer + character; styleSheet.cssRules.push(importRule); buffer = ""; state = "before-selector"; break; default: buffer += character; break; } break; case "}": switch (state) { case "value": styleRule.style.setProperty(name, buffer.trim(), priority); priority = ""; /* falls through */ case "before-name": case "name": styleRule.__ends = i + 1; if (parentRule) { styleRule.parentRule = parentRule; } styleRule.parentStyleSheet = styleSheet; currentScope.cssRules.push(styleRule); buffer = ""; if (currentScope.constructor === CSSOM.CSSKeyframesRule) { state = "keyframeRule-begin"; } else { state = "before-selector"; } break; case "keyframeRule-begin": case "before-selector": case "selector": // End of media/supports/document rule. if (!parentRule) { parseError("Unexpected }"); } // Handle rules nested in @media or @supports hasAncestors = ancestorRules.length > 0; while (ancestorRules.length > 0) { parentRule = ancestorRules.pop(); if ( parentRule.constructor.name === "CSSMediaRule" || parentRule.constructor.name === "CSSSupportsRule" ) { prevScope = currentScope; currentScope = parentRule; currentScope.cssRules.push(prevScope); break; } if (ancestorRules.length === 0) { hasAncestors = false; } } if (!hasAncestors) { currentScope.__ends = i + 1; styleSheet.cssRules.push(currentScope); currentScope = styleSheet; parentRule = null; } buffer = ""; state = "before-selector"; break; } break; default: switch (state) { case "before-selector": state = "selector"; styleRule = new CSSOM.CSSStyleRule(); styleRule.__starts = i; break; case "before-name": state = "name"; break; case "before-value": state = "value"; break; case "importRule-begin": state = "importRule"; break; } buffer += character; break; } } return styleSheet; }; //.CommonJS exports.parse = CSSOM.parse; // The following modules cannot be included sooner due to the mutual dependency with parse.js CSSOM.CSSStyleSheet = require("cssom/lib/CSSStyleSheet").CSSStyleSheet; CSSOM.CSSStyleRule = require("cssom/lib/CSSStyleRule").CSSStyleRule; CSSOM.CSSImportRule = require("cssom/lib/CSSImportRule").CSSImportRule; CSSOM.CSSMediaRule = require("cssom/lib/CSSMediaRule").CSSMediaRule; CSSOM.CSSSupportsRule = require("cssom/lib/CSSSupportsRule").CSSSupportsRule; CSSOM.CSSFontFaceRule = require("cssom/lib/CSSFontFaceRule").CSSFontFaceRule; CSSOM.CSSHostRule = require("cssom/lib/CSSHostRule").CSSHostRule; CSSOM.CSSStyleDeclaration = require('cssom/lib/CSSStyleDeclaration').CSSStyleDeclaration; CSSOM.CSSKeyframeRule = require('cssom/lib/CSSKeyframeRule').CSSKeyframeRule; CSSOM.CSSKeyframesRule = require('cssom/lib/CSSKeyframesRule').CSSKeyframesRule; CSSOM.CSSValueExpression = require('cssom/lib/CSSValueExpression').CSSValueExpression; CSSOM.CSSDocumentRule = require('cssom/lib/CSSDocumentRule').CSSDocumentRule; ///CommonJS
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssstyle/node_modules/cssom/lib/parse.js
parse.js
var CSSOM = {}; ///CommonJS /** * @constructor * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration */ CSSOM.CSSStyleDeclaration = function CSSStyleDeclaration(){ this.length = 0; this.parentRule = null; // NON-STANDARD this._importants = {}; }; CSSOM.CSSStyleDeclaration.prototype = { constructor: CSSOM.CSSStyleDeclaration, /** * * @param {string} name * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-getPropertyValue * @return {string} the value of the property if it has been explicitly set for this declaration block. * Returns the empty string if the property has not been set. */ getPropertyValue: function(name) { return this[name] || ""; }, /** * * @param {string} name * @param {string} value * @param {string} [priority=null] "important" or null * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-setProperty */ setProperty: function(name, value, priority) { if (this[name]) { // Property already exist. Overwrite it. var index = Array.prototype.indexOf.call(this, name); if (index < 0) { this[this.length] = name; this.length++; } } else { // New property. this[this.length] = name; this.length++; } this[name] = value + ""; this._importants[name] = priority; }, /** * * @param {string} name * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-removeProperty * @return {string} the value of the property if it has been explicitly set for this declaration block. * Returns the empty string if the property has not been set or the property name does not correspond to a known CSS property. */ removeProperty: function(name) { if (!(name in this)) { return ""; } var index = Array.prototype.indexOf.call(this, name); if (index < 0) { return ""; } var prevValue = this[name]; this[name] = ""; // That's what WebKit and Opera do Array.prototype.splice.call(this, index, 1); // That's what Firefox does //this[index] = "" return prevValue; }, getPropertyCSSValue: function() { //FIXME }, /** * * @param {String} name */ getPropertyPriority: function(name) { return this._importants[name] || ""; }, /** * element.style.overflow = "auto" * element.style.getPropertyShorthand("overflow-x") * -> "overflow" */ getPropertyShorthand: function() { //FIXME }, isPropertyImplicit: function() { //FIXME }, // Doesn't work in IE < 9 get cssText(){ var properties = []; for (var i=0, length=this.length; i < length; ++i) { var name = this[i]; var value = this.getPropertyValue(name); var priority = this.getPropertyPriority(name); if (priority) { priority = " !" + priority; } properties[i] = name + ": " + value + priority + ";"; } return properties.join(" "); }, set cssText(text){ var i, name; for (i = this.length; i--;) { name = this[i]; this[name] = ""; } Array.prototype.splice.call(this, 0, this.length); this._importants = {}; var dummyRule = CSSOM.parse('#bogus{' + text + '}').cssRules[0].style; var length = dummyRule.length; for (i = 0; i < length; ++i) { name = dummyRule[i]; this.setProperty(dummyRule[i], dummyRule.getPropertyValue(name), dummyRule.getPropertyPriority(name)); } } }; //.CommonJS exports.CSSStyleDeclaration = CSSOM.CSSStyleDeclaration; CSSOM.parse = require('cssom/lib/parse').parse; // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleDeclaration.js ///CommonJS
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssstyle/node_modules/cssom/lib/CSSStyleDeclaration.js
CSSStyleDeclaration.js
var CSSOM = { CSSStyleSheet: require("cssom/lib/CSSStyleSheet").CSSStyleSheet, CSSStyleRule: require("cssom/lib/CSSStyleRule").CSSStyleRule, CSSMediaRule: require("cssom/lib/CSSMediaRule").CSSMediaRule, CSSSupportsRule: require("cssom/lib/CSSSupportsRule").CSSSupportsRule, CSSStyleDeclaration: require("cssom/lib/CSSStyleDeclaration").CSSStyleDeclaration, CSSKeyframeRule: require('cssom/lib/CSSKeyframeRule').CSSKeyframeRule, CSSKeyframesRule: require('cssom/lib/CSSKeyframesRule').CSSKeyframesRule }; ///CommonJS /** * Produces a deep copy of stylesheet — the instance variables of stylesheet are copied recursively. * @param {CSSStyleSheet|CSSOM.CSSStyleSheet} stylesheet * @nosideeffects * @return {CSSOM.CSSStyleSheet} */ CSSOM.clone = function clone(stylesheet) { var cloned = new CSSOM.CSSStyleSheet(); var rules = stylesheet.cssRules; if (!rules) { return cloned; } var RULE_TYPES = { 1: CSSOM.CSSStyleRule, 4: CSSOM.CSSMediaRule, //3: CSSOM.CSSImportRule, //5: CSSOM.CSSFontFaceRule, //6: CSSOM.CSSPageRule, 8: CSSOM.CSSKeyframesRule, 9: CSSOM.CSSKeyframeRule, 12: CSSOM.CSSSupportsRule }; for (var i=0, rulesLength=rules.length; i < rulesLength; i++) { var rule = rules[i]; var ruleClone = cloned.cssRules[i] = new RULE_TYPES[rule.type](); var style = rule.style; if (style) { var styleClone = ruleClone.style = new CSSOM.CSSStyleDeclaration(); for (var j=0, styleLength=style.length; j < styleLength; j++) { var name = styleClone[j] = style[j]; styleClone[name] = style[name]; styleClone._importants[name] = style.getPropertyPriority(name); } styleClone.length = style.length; } if (rule.hasOwnProperty('keyText')) { ruleClone.keyText = rule.keyText; } if (rule.hasOwnProperty('selectorText')) { ruleClone.selectorText = rule.selectorText; } if (rule.hasOwnProperty('mediaText')) { ruleClone.mediaText = rule.mediaText; } if (rule.hasOwnProperty('conditionText')) { ruleClone.conditionText = rule.conditionText; } if (rule.hasOwnProperty('cssRules')) { ruleClone.cssRules = clone(rule).cssRules; } } return cloned; }; //.CommonJS exports.clone = CSSOM.clone; ///CommonJS
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssstyle/node_modules/cssom/lib/clone.js
clone.js
var CSSOM = { CSSRule: require("cssom/lib/CSSRule").CSSRule, CSSStyleSheet: require("cssom/lib/CSSStyleSheet").CSSStyleSheet, MediaList: require("cssom/lib/MediaList").MediaList }; ///CommonJS /** * @constructor * @see http://dev.w3.org/csswg/cssom/#cssimportrule * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSImportRule */ CSSOM.CSSImportRule = function CSSImportRule() { CSSOM.CSSRule.call(this); this.href = ""; this.media = new CSSOM.MediaList(); this.styleSheet = new CSSOM.CSSStyleSheet(); }; CSSOM.CSSImportRule.prototype = new CSSOM.CSSRule(); CSSOM.CSSImportRule.prototype.constructor = CSSOM.CSSImportRule; CSSOM.CSSImportRule.prototype.type = 3; Object.defineProperty(CSSOM.CSSImportRule.prototype, "cssText", { get: function() { var mediaText = this.media.mediaText; return "@import url(" + this.href + ")" + (mediaText ? " " + mediaText : "") + ";"; }, set: function(cssText) { var i = 0; /** * @import url(partial.css) screen, handheld; * || | * after-import media * | * url */ var state = ''; var buffer = ''; var index; for (var character; (character = cssText.charAt(i)); i++) { switch (character) { case ' ': case '\t': case '\r': case '\n': case '\f': if (state === 'after-import') { state = 'url'; } else { buffer += character; } break; case '@': if (!state && cssText.indexOf('@import', i) === i) { state = 'after-import'; i += 'import'.length; buffer = ''; } break; case 'u': if (state === 'url' && cssText.indexOf('url(', i) === i) { index = cssText.indexOf(')', i + 1); if (index === -1) { throw i + ': ")" not found'; } i += 'url('.length; var url = cssText.slice(i, index); if (url[0] === url[url.length - 1]) { if (url[0] === '"' || url[0] === "'") { url = url.slice(1, -1); } } this.href = url; i = index; state = 'media'; } break; case '"': if (state === 'url') { index = cssText.indexOf('"', i + 1); if (!index) { throw i + ": '\"' not found"; } this.href = cssText.slice(i + 1, index); i = index; state = 'media'; } break; case "'": if (state === 'url') { index = cssText.indexOf("'", i + 1); if (!index) { throw i + ': "\'" not found'; } this.href = cssText.slice(i + 1, index); i = index; state = 'media'; } break; case ';': if (state === 'media') { if (buffer) { this.media.mediaText = buffer.trim(); } } break; default: if (state === 'media') { buffer += character; } break; } } } }); //.CommonJS exports.CSSImportRule = CSSOM.CSSImportRule; ///CommonJS
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssstyle/node_modules/cssom/lib/CSSImportRule.js
CSSImportRule.js
var CSSOM = { CSSStyleDeclaration: require("cssom/lib/CSSStyleDeclaration").CSSStyleDeclaration, CSSRule: require("cssom/lib/CSSRule").CSSRule }; ///CommonJS /** * @constructor * @see http://dev.w3.org/csswg/cssom/#cssstylerule * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleRule */ CSSOM.CSSStyleRule = function CSSStyleRule() { CSSOM.CSSRule.call(this); this.selectorText = ""; this.style = new CSSOM.CSSStyleDeclaration(); this.style.parentRule = this; }; CSSOM.CSSStyleRule.prototype = new CSSOM.CSSRule(); CSSOM.CSSStyleRule.prototype.constructor = CSSOM.CSSStyleRule; CSSOM.CSSStyleRule.prototype.type = 1; Object.defineProperty(CSSOM.CSSStyleRule.prototype, "cssText", { get: function() { var text; if (this.selectorText) { text = this.selectorText + " {" + this.style.cssText + "}"; } else { text = ""; } return text; }, set: function(cssText) { var rule = CSSOM.CSSStyleRule.parse(cssText); this.style = rule.style; this.selectorText = rule.selectorText; } }); /** * NON-STANDARD * lightweight version of parse.js. * @param {string} ruleText * @return CSSStyleRule */ CSSOM.CSSStyleRule.parse = function(ruleText) { var i = 0; var state = "selector"; var index; var j = i; var buffer = ""; var SIGNIFICANT_WHITESPACE = { "selector": true, "value": true }; var styleRule = new CSSOM.CSSStyleRule(); var name, priority=""; for (var character; (character = ruleText.charAt(i)); i++) { switch (character) { case " ": case "\t": case "\r": case "\n": case "\f": if (SIGNIFICANT_WHITESPACE[state]) { // Squash 2 or more white-spaces in the row into 1 switch (ruleText.charAt(i - 1)) { case " ": case "\t": case "\r": case "\n": case "\f": break; default: buffer += " "; break; } } break; // String case '"': j = i + 1; index = ruleText.indexOf('"', j) + 1; if (!index) { throw '" is missing'; } buffer += ruleText.slice(i, index); i = index - 1; break; case "'": j = i + 1; index = ruleText.indexOf("'", j) + 1; if (!index) { throw "' is missing"; } buffer += ruleText.slice(i, index); i = index - 1; break; // Comment case "/": if (ruleText.charAt(i + 1) === "*") { i += 2; index = ruleText.indexOf("*/", i); if (index === -1) { throw new SyntaxError("Missing */"); } else { i = index + 1; } } else { buffer += character; } break; case "{": if (state === "selector") { styleRule.selectorText = buffer.trim(); buffer = ""; state = "name"; } break; case ":": if (state === "name") { name = buffer.trim(); buffer = ""; state = "value"; } else { buffer += character; } break; case "!": if (state === "value" && ruleText.indexOf("!important", i) === i) { priority = "important"; i += "important".length; } else { buffer += character; } break; case ";": if (state === "value") { styleRule.style.setProperty(name, buffer.trim(), priority); priority = ""; buffer = ""; state = "name"; } else { buffer += character; } break; case "}": if (state === "value") { styleRule.style.setProperty(name, buffer.trim(), priority); priority = ""; buffer = ""; } else if (state === "name") { break; } else { buffer += character; } state = "selector"; break; default: buffer += character; break; } } return styleRule; }; //.CommonJS exports.CSSStyleRule = CSSOM.CSSStyleRule; ///CommonJS
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssstyle/node_modules/cssom/lib/CSSStyleRule.js
CSSStyleRule.js
'use strict'; /** * This file contains all implemented properties that are not a part of any * current specifications or drafts, but are handled by browsers nevertheless. */ module.exports = [ 'animation', 'animation-delay', 'animation-direction', 'animation-duration', 'animation-fill-mode', 'animation-iteration-count', 'animation-name', 'animation-play-state', 'animation-timing-function', 'appearance', 'aspect-ratio', 'backface-visibility', 'background-clip', 'background-composite', 'background-origin', 'background-size', 'border-after', 'border-after-color', 'border-after-style', 'border-after-width', 'border-before', 'border-before-color', 'border-before-style', 'border-before-width', 'border-end', 'border-end-color', 'border-end-style', 'border-end-width', 'border-fit', 'border-horizontal-spacing', 'border-image', 'border-radius', 'border-start', 'border-start-color', 'border-start-style', 'border-start-width', 'border-vertical-spacing', 'box-align', 'box-direction', 'box-flex', 'box-flex-group', 'box-lines', 'box-ordinal-group', 'box-orient', 'box-pack', 'box-reflect', 'box-shadow', 'color-correction', 'column-axis', 'column-break-after', 'column-break-before', 'column-break-inside', 'column-count', 'column-gap', 'column-rule', 'column-rule-color', 'column-rule-style', 'column-rule-width', 'columns', 'column-span', 'column-width', 'filter', 'flex-align', 'flex-direction', 'flex-flow', 'flex-item-align', 'flex-line-pack', 'flex-order', 'flex-pack', 'flex-wrap', 'flow-from', 'flow-into', 'font-feature-settings', 'font-kerning', 'font-size-delta', 'font-smoothing', 'font-variant-ligatures', 'highlight', 'hyphenate-character', 'hyphenate-limit-after', 'hyphenate-limit-before', 'hyphenate-limit-lines', 'hyphens', 'line-align', 'line-box-contain', 'line-break', 'line-clamp', 'line-grid', 'line-snap', 'locale', 'logical-height', 'logical-width', 'margin-after', 'margin-after-collapse', 'margin-before', 'margin-before-collapse', 'margin-bottom-collapse', 'margin-collapse', 'margin-end', 'margin-start', 'margin-top-collapse', 'marquee', 'marquee-direction', 'marquee-increment', 'marquee-repetition', 'marquee-speed', 'marquee-style', 'mask', 'mask-attachment', 'mask-box-image', 'mask-box-image-outset', 'mask-box-image-repeat', 'mask-box-image-slice', 'mask-box-image-source', 'mask-box-image-width', 'mask-clip', 'mask-composite', 'mask-image', 'mask-origin', 'mask-position', 'mask-position-x', 'mask-position-y', 'mask-repeat', 'mask-repeat-x', 'mask-repeat-y', 'mask-size', 'match-nearest-mail-blockquote-color', 'max-logical-height', 'max-logical-width', 'min-logical-height', 'min-logical-width', 'nbsp-mode', 'overflow-scrolling', 'padding-after', 'padding-before', 'padding-end', 'padding-start', 'perspective', 'perspective-origin', 'perspective-origin-x', 'perspective-origin-y', 'print-color-adjust', 'region-break-after', 'region-break-before', 'region-break-inside', 'region-overflow', 'rtl-ordering', 'svg-shadow', 'tap-highlight-color', 'text-combine', 'text-decorations-in-effect', 'text-emphasis', 'text-emphasis-color', 'text-emphasis-position', 'text-emphasis-style', 'text-fill-color', 'text-orientation', 'text-security', 'text-size-adjust', 'text-stroke', 'text-stroke-color', 'text-stroke-width', 'transform', 'transform-origin', 'transform-origin-x', 'transform-origin-y', 'transform-origin-z', 'transform-style', 'transition', 'transition-delay', 'transition-duration', 'transition-property', 'transition-timing-function', 'user-drag', 'user-modify', 'user-select', 'wrap', 'wrap-flow', 'wrap-margin', 'wrap-padding', 'wrap-shape-inside', 'wrap-shape-outside', 'wrap-through', 'writing-mode', 'zoom', ].map(prop => 'webkit-' + prop);
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssstyle/lib/allWebkitProperties.js
allWebkitProperties.js
'use strict'; const namedColors = require('cssstyle/lib/named_colors.json'); const { hslToRgb } = require('cssstyle/lib/utils/colorSpace'); exports.TYPES = { INTEGER: 1, NUMBER: 2, LENGTH: 3, PERCENT: 4, URL: 5, COLOR: 6, STRING: 7, ANGLE: 8, KEYWORD: 9, NULL_OR_EMPTY_STR: 10, CALC: 11, }; // rough regular expressions var integerRegEx = /^[-+]?[0-9]+$/; var numberRegEx = /^[-+]?[0-9]*\.?[0-9]+$/; var lengthRegEx = /^(0|[-+]?[0-9]*\.?[0-9]+(in|cm|em|mm|pt|pc|px|ex|rem|vh|vw|ch))$/; var percentRegEx = /^[-+]?[0-9]*\.?[0-9]+%$/; var urlRegEx = /^url\(\s*([^)]*)\s*\)$/; var stringRegEx = /^("[^"]*"|'[^']*')$/; var colorRegEx1 = /^#([0-9a-fA-F]{3,4}){1,2}$/; var colorRegEx2 = /^rgb\(([^)]*)\)$/; var colorRegEx3 = /^rgba\(([^)]*)\)$/; var calcRegEx = /^calc\(([^)]*)\)$/; var colorRegEx4 = /^hsla?\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*(,\s*(-?\d+|-?\d*.\d+)\s*)?\)/; var angleRegEx = /^([-+]?[0-9]*\.?[0-9]+)(deg|grad|rad)$/; // This will return one of the above types based on the passed in string exports.valueType = function valueType(val) { if (val === '' || val === null) { return exports.TYPES.NULL_OR_EMPTY_STR; } if (typeof val === 'number') { val = val.toString(); } if (typeof val !== 'string') { return undefined; } if (integerRegEx.test(val)) { return exports.TYPES.INTEGER; } if (numberRegEx.test(val)) { return exports.TYPES.NUMBER; } if (lengthRegEx.test(val)) { return exports.TYPES.LENGTH; } if (percentRegEx.test(val)) { return exports.TYPES.PERCENT; } if (urlRegEx.test(val)) { return exports.TYPES.URL; } if (calcRegEx.test(val)) { return exports.TYPES.CALC; } if (stringRegEx.test(val)) { return exports.TYPES.STRING; } if (angleRegEx.test(val)) { return exports.TYPES.ANGLE; } if (colorRegEx1.test(val)) { return exports.TYPES.COLOR; } var res = colorRegEx2.exec(val); var parts; if (res !== null) { parts = res[1].split(/\s*,\s*/); if (parts.length !== 3) { return undefined; } if ( parts.every(percentRegEx.test.bind(percentRegEx)) || parts.every(integerRegEx.test.bind(integerRegEx)) ) { return exports.TYPES.COLOR; } return undefined; } res = colorRegEx3.exec(val); if (res !== null) { parts = res[1].split(/\s*,\s*/); if (parts.length !== 4) { return undefined; } if ( parts.slice(0, 3).every(percentRegEx.test.bind(percentRegEx)) || parts.slice(0, 3).every(integerRegEx.test.bind(integerRegEx)) ) { if (numberRegEx.test(parts[3])) { return exports.TYPES.COLOR; } } return undefined; } if (colorRegEx4.test(val)) { return exports.TYPES.COLOR; } // could still be a color, one of the standard keyword colors val = val.toLowerCase(); if (namedColors.includes(val)) { return exports.TYPES.COLOR; } switch (val) { // the following are deprecated in CSS3 case 'activeborder': case 'activecaption': case 'appworkspace': case 'background': case 'buttonface': case 'buttonhighlight': case 'buttonshadow': case 'buttontext': case 'captiontext': case 'graytext': case 'highlight': case 'highlighttext': case 'inactiveborder': case 'inactivecaption': case 'inactivecaptiontext': case 'infobackground': case 'infotext': case 'menu': case 'menutext': case 'scrollbar': case 'threeddarkshadow': case 'threedface': case 'threedhighlight': case 'threedlightshadow': case 'threedshadow': case 'window': case 'windowframe': case 'windowtext': return exports.TYPES.COLOR; default: return exports.TYPES.KEYWORD; } }; exports.parseInteger = function parseInteger(val) { var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } if (type !== exports.TYPES.INTEGER) { return undefined; } return String(parseInt(val, 10)); }; exports.parseNumber = function parseNumber(val) { var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } if (type !== exports.TYPES.NUMBER && type !== exports.TYPES.INTEGER) { return undefined; } return String(parseFloat(val)); }; exports.parseLength = function parseLength(val) { if (val === 0 || val === '0') { return '0px'; } var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } if (type !== exports.TYPES.LENGTH) { return undefined; } return val; }; exports.parsePercent = function parsePercent(val) { if (val === 0 || val === '0') { return '0%'; } var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } if (type !== exports.TYPES.PERCENT) { return undefined; } return val; }; // either a length or a percent exports.parseMeasurement = function parseMeasurement(val) { var type = exports.valueType(val); if (type === exports.TYPES.CALC) { return val; } var length = exports.parseLength(val); if (length !== undefined) { return length; } return exports.parsePercent(val); }; exports.parseUrl = function parseUrl(val) { var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } var res = urlRegEx.exec(val); // does it match the regex? if (!res) { return undefined; } var str = res[1]; // if it starts with single or double quotes, does it end with the same? if ((str[0] === '"' || str[0] === "'") && str[0] !== str[str.length - 1]) { return undefined; } if (str[0] === '"' || str[0] === "'") { str = str.substr(1, str.length - 2); } var i; for (i = 0; i < str.length; i++) { switch (str[i]) { case '(': case ')': case ' ': case '\t': case '\n': case "'": case '"': return undefined; case '\\': i++; break; } } return 'url(' + str + ')'; }; exports.parseString = function parseString(val) { var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } if (type !== exports.TYPES.STRING) { return undefined; } var i; for (i = 1; i < val.length - 1; i++) { switch (val[i]) { case val[0]: return undefined; case '\\': i++; while (i < val.length - 1 && /[0-9A-Fa-f]/.test(val[i])) { i++; } break; } } if (i >= val.length) { return undefined; } return val; }; exports.parseColor = function parseColor(val) { var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } var red, green, blue, hue, saturation, lightness, alpha = 1; var parts; var res = colorRegEx1.exec(val); // is it #aaa, #ababab, #aaaa, #abababaa if (res) { var defaultHex = val.substr(1); var hex = val.substr(1); if (hex.length === 3 || hex.length === 4) { hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; if (defaultHex.length === 4) { hex = hex + defaultHex[3] + defaultHex[3]; } } red = parseInt(hex.substr(0, 2), 16); green = parseInt(hex.substr(2, 2), 16); blue = parseInt(hex.substr(4, 2), 16); if (hex.length === 8) { var hexAlpha = hex.substr(6, 2); var hexAlphaToRgbaAlpha = Number((parseInt(hexAlpha, 16) / 255).toFixed(3)); return 'rgba(' + red + ', ' + green + ', ' + blue + ', ' + hexAlphaToRgbaAlpha + ')'; } return 'rgb(' + red + ', ' + green + ', ' + blue + ')'; } res = colorRegEx2.exec(val); if (res) { parts = res[1].split(/\s*,\s*/); if (parts.length !== 3) { return undefined; } if (parts.every(percentRegEx.test.bind(percentRegEx))) { red = Math.floor((parseFloat(parts[0].slice(0, -1)) * 255) / 100); green = Math.floor((parseFloat(parts[1].slice(0, -1)) * 255) / 100); blue = Math.floor((parseFloat(parts[2].slice(0, -1)) * 255) / 100); } else if (parts.every(integerRegEx.test.bind(integerRegEx))) { red = parseInt(parts[0], 10); green = parseInt(parts[1], 10); blue = parseInt(parts[2], 10); } else { return undefined; } red = Math.min(255, Math.max(0, red)); green = Math.min(255, Math.max(0, green)); blue = Math.min(255, Math.max(0, blue)); return 'rgb(' + red + ', ' + green + ', ' + blue + ')'; } res = colorRegEx3.exec(val); if (res) { parts = res[1].split(/\s*,\s*/); if (parts.length !== 4) { return undefined; } if (parts.slice(0, 3).every(percentRegEx.test.bind(percentRegEx))) { red = Math.floor((parseFloat(parts[0].slice(0, -1)) * 255) / 100); green = Math.floor((parseFloat(parts[1].slice(0, -1)) * 255) / 100); blue = Math.floor((parseFloat(parts[2].slice(0, -1)) * 255) / 100); alpha = parseFloat(parts[3]); } else if (parts.slice(0, 3).every(integerRegEx.test.bind(integerRegEx))) { red = parseInt(parts[0], 10); green = parseInt(parts[1], 10); blue = parseInt(parts[2], 10); alpha = parseFloat(parts[3]); } else { return undefined; } if (isNaN(alpha)) { alpha = 1; } red = Math.min(255, Math.max(0, red)); green = Math.min(255, Math.max(0, green)); blue = Math.min(255, Math.max(0, blue)); alpha = Math.min(1, Math.max(0, alpha)); if (alpha === 1) { return 'rgb(' + red + ', ' + green + ', ' + blue + ')'; } return 'rgba(' + red + ', ' + green + ', ' + blue + ', ' + alpha + ')'; } res = colorRegEx4.exec(val); if (res) { const [, _hue, _saturation, _lightness, _alphaString = ''] = res; const _alpha = parseFloat(_alphaString.replace(',', '').trim()); if (!_hue || !_saturation || !_lightness) { return undefined; } hue = parseFloat(_hue); saturation = parseInt(_saturation, 10); lightness = parseInt(_lightness, 10); if (_alpha && numberRegEx.test(_alpha)) { alpha = parseFloat(_alpha); } const [r, g, b] = hslToRgb(hue, saturation / 100, lightness / 100); if (!_alphaString || alpha === 1) { return 'rgb(' + r + ', ' + g + ', ' + b + ')'; } return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + alpha + ')'; } if (type === exports.TYPES.COLOR) { return val; } return undefined; }; exports.parseAngle = function parseAngle(val) { var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } if (type !== exports.TYPES.ANGLE) { return undefined; } var res = angleRegEx.exec(val); var flt = parseFloat(res[1]); if (res[2] === 'rad') { flt *= 180 / Math.PI; } else if (res[2] === 'grad') { flt *= 360 / 400; } while (flt < 0) { flt += 360; } while (flt > 360) { flt -= 360; } return flt + 'deg'; }; exports.parseKeyword = function parseKeyword(val, valid_keywords) { var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } if (type !== exports.TYPES.KEYWORD) { return undefined; } val = val.toString().toLowerCase(); var i; for (i = 0; i < valid_keywords.length; i++) { if (valid_keywords[i].toLowerCase() === val) { return valid_keywords[i]; } } return undefined; }; // utility to translate from border-width to borderWidth var dashedToCamelCase = function(dashed) { var i; var camel = ''; var nextCap = false; for (i = 0; i < dashed.length; i++) { if (dashed[i] !== '-') { camel += nextCap ? dashed[i].toUpperCase() : dashed[i]; nextCap = false; } else { nextCap = true; } } return camel; }; exports.dashedToCamelCase = dashedToCamelCase; var is_space = /\s/; var opening_deliminators = ['"', "'", '(']; var closing_deliminators = ['"', "'", ')']; // this splits on whitespace, but keeps quoted and parened parts together var getParts = function(str) { var deliminator_stack = []; var length = str.length; var i; var parts = []; var current_part = ''; var opening_index; var closing_index; for (i = 0; i < length; i++) { opening_index = opening_deliminators.indexOf(str[i]); closing_index = closing_deliminators.indexOf(str[i]); if (is_space.test(str[i])) { if (deliminator_stack.length === 0) { if (current_part !== '') { parts.push(current_part); } current_part = ''; } else { current_part += str[i]; } } else { if (str[i] === '\\') { i++; current_part += str[i]; } else { current_part += str[i]; if ( closing_index !== -1 && closing_index === deliminator_stack[deliminator_stack.length - 1] ) { deliminator_stack.pop(); } else if (opening_index !== -1) { deliminator_stack.push(opening_index); } } } } if (current_part !== '') { parts.push(current_part); } return parts; }; /* * this either returns undefined meaning that it isn't valid * or returns an object where the keys are dashed short * hand properties and the values are the values to set * on them */ exports.shorthandParser = function parse(v, shorthand_for) { var obj = {}; var type = exports.valueType(v); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { Object.keys(shorthand_for).forEach(function(property) { obj[property] = ''; }); return obj; } if (typeof v === 'number') { v = v.toString(); } if (typeof v !== 'string') { return undefined; } if (v.toLowerCase() === 'inherit') { return {}; } var parts = getParts(v); var valid = true; parts.forEach(function(part, i) { var part_valid = false; Object.keys(shorthand_for).forEach(function(property) { if (shorthand_for[property].isValid(part, i)) { part_valid = true; obj[property] = part; } }); valid = valid && part_valid; }); if (!valid) { return undefined; } return obj; }; exports.shorthandSetter = function(property, shorthand_for) { return function(v) { var obj = exports.shorthandParser(v, shorthand_for); if (obj === undefined) { return; } //console.log('shorthandSetter for:', property, 'obj:', obj); Object.keys(obj).forEach(function(subprop) { // in case subprop is an implicit property, this will clear // *its* subpropertiesX var camel = dashedToCamelCase(subprop); this[camel] = obj[subprop]; // in case it gets translated into something else (0 -> 0px) obj[subprop] = this[camel]; this.removeProperty(subprop); // don't add in empty properties if (obj[subprop] !== '') { this._values[subprop] = obj[subprop]; } }, this); Object.keys(shorthand_for).forEach(function(subprop) { if (!obj.hasOwnProperty(subprop)) { this.removeProperty(subprop); delete this._values[subprop]; } }, this); // in case the value is something like 'none' that removes all values, // check that the generated one is not empty, first remove the property // if it already exists, then call the shorthandGetter, if it's an empty // string, don't set the property this.removeProperty(property); var calculated = exports.shorthandGetter(property, shorthand_for).call(this); if (calculated !== '') { this._setProperty(property, calculated); } }; }; exports.shorthandGetter = function(property, shorthand_for) { return function() { if (this._values[property] !== undefined) { return this.getPropertyValue(property); } return Object.keys(shorthand_for) .map(function(subprop) { return this.getPropertyValue(subprop); }, this) .filter(function(value) { return value !== ''; }) .join(' '); }; }; // isValid(){1,4} | inherit // if one, it applies to all // if two, the first applies to the top and bottom, and the second to left and right // if three, the first applies to the top, the second to left and right, the third bottom // if four, top, right, bottom, left exports.implicitSetter = function(property_before, property_after, isValid, parser) { property_after = property_after || ''; if (property_after !== '') { property_after = '-' + property_after; } var part_names = ['top', 'right', 'bottom', 'left']; return function(v) { if (typeof v === 'number') { v = v.toString(); } if (typeof v !== 'string') { return undefined; } var parts; if (v.toLowerCase() === 'inherit' || v === '') { parts = [v]; } else { parts = getParts(v); } if (parts.length < 1 || parts.length > 4) { return undefined; } if (!parts.every(isValid)) { return undefined; } parts = parts.map(function(part) { return parser(part); }); this._setProperty(property_before + property_after, parts.join(' ')); if (parts.length === 1) { parts[1] = parts[0]; } if (parts.length === 2) { parts[2] = parts[0]; } if (parts.length === 3) { parts[3] = parts[1]; } for (var i = 0; i < 4; i++) { var property = property_before + '-' + part_names[i] + property_after; this.removeProperty(property); if (parts[i] !== '') { this._values[property] = parts[i]; } } return v; }; }; // // Companion to implicitSetter, but for the individual parts. // This sets the individual value, and checks to see if all four // sub-parts are set. If so, it sets the shorthand version and removes // the individual parts from the cssText. // exports.subImplicitSetter = function(prefix, part, isValid, parser) { var property = prefix + '-' + part; var subparts = [prefix + '-top', prefix + '-right', prefix + '-bottom', prefix + '-left']; return function(v) { if (typeof v === 'number') { v = v.toString(); } if (typeof v !== 'string') { return undefined; } if (!isValid(v)) { return undefined; } v = parser(v); this._setProperty(property, v); var parts = []; for (var i = 0; i < 4; i++) { if (this._values[subparts[i]] == null || this._values[subparts[i]] === '') { break; } parts.push(this._values[subparts[i]]); } if (parts.length === 4) { for (i = 0; i < 4; i++) { this.removeProperty(subparts[i]); this._values[subparts[i]] = parts[i]; } this._setProperty(prefix, parts.join(' ')); } return v; }; }; var camel_to_dashed = /[A-Z]/g; var first_segment = /^\([^-]\)-/; var vendor_prefixes = ['o', 'moz', 'ms', 'webkit']; exports.camelToDashed = function(camel_case) { var match; var dashed = camel_case.replace(camel_to_dashed, '-$&').toLowerCase(); match = dashed.match(first_segment); if (match && vendor_prefixes.indexOf(match[1]) !== -1) { dashed = '-' + dashed; } return dashed; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssstyle/lib/parsers.js
parsers.js
'use strict'; var CSSOM = require('cssom'); var allProperties = require('cssstyle/lib/allProperties'); var allExtraProperties = require('cssstyle/lib/allExtraProperties'); var implementedProperties = require('cssstyle/lib/implementedProperties'); var { dashedToCamelCase } = require('cssstyle/lib/parsers'); var getBasicPropertyDescriptor = require('cssstyle/lib/utils/getBasicPropertyDescriptor'); /** * @constructor * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration */ var CSSStyleDeclaration = function CSSStyleDeclaration(onChangeCallback) { this._values = {}; this._importants = {}; this._length = 0; this._onChange = onChangeCallback || function() { return; }; }; CSSStyleDeclaration.prototype = { constructor: CSSStyleDeclaration, /** * * @param {string} name * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-getPropertyValue * @return {string} the value of the property if it has been explicitly set for this declaration block. * Returns the empty string if the property has not been set. */ getPropertyValue: function(name) { if (!this._values.hasOwnProperty(name)) { return ''; } return this._values[name].toString(); }, /** * * @param {string} name * @param {string} value * @param {string} [priority=null] "important" or null * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-setProperty */ setProperty: function(name, value, priority) { if (value === undefined) { return; } if (value === null || value === '') { this.removeProperty(name); return; } var isCustomProperty = name.indexOf('--') === 0; if (isCustomProperty) { this._setProperty(name, value, priority); return; } var lowercaseName = name.toLowerCase(); if (!allProperties.has(lowercaseName) && !allExtraProperties.has(lowercaseName)) { return; } this[lowercaseName] = value; this._importants[lowercaseName] = priority; }, _setProperty: function(name, value, priority) { if (value === undefined) { return; } if (value === null || value === '') { this.removeProperty(name); return; } if (this._values[name]) { // Property already exist. Overwrite it. var index = Array.prototype.indexOf.call(this, name); if (index < 0) { this[this._length] = name; this._length++; } } else { // New property. this[this._length] = name; this._length++; } this._values[name] = value; this._importants[name] = priority; this._onChange(this.cssText); }, /** * * @param {string} name * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-removeProperty * @return {string} the value of the property if it has been explicitly set for this declaration block. * Returns the empty string if the property has not been set or the property name does not correspond to a known CSS property. */ removeProperty: function(name) { if (!this._values.hasOwnProperty(name)) { return ''; } var prevValue = this._values[name]; delete this._values[name]; delete this._importants[name]; var index = Array.prototype.indexOf.call(this, name); if (index < 0) { return prevValue; } // That's what WebKit and Opera do Array.prototype.splice.call(this, index, 1); // That's what Firefox does //this[index] = "" this._onChange(this.cssText); return prevValue; }, /** * * @param {String} name */ getPropertyPriority: function(name) { return this._importants[name] || ''; }, getPropertyCSSValue: function() { //FIXME return; }, /** * element.style.overflow = "auto" * element.style.getPropertyShorthand("overflow-x") * -> "overflow" */ getPropertyShorthand: function() { //FIXME return; }, isPropertyImplicit: function() { //FIXME return; }, /** * http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-item */ item: function(index) { index = parseInt(index, 10); if (index < 0 || index >= this._length) { return ''; } return this[index]; }, }; Object.defineProperties(CSSStyleDeclaration.prototype, { cssText: { get: function() { var properties = []; var i; var name; var value; var priority; for (i = 0; i < this._length; i++) { name = this[i]; value = this.getPropertyValue(name); priority = this.getPropertyPriority(name); if (priority !== '') { priority = ' !' + priority; } properties.push([name, ': ', value, priority, ';'].join('')); } return properties.join(' '); }, set: function(value) { var i; this._values = {}; Array.prototype.splice.call(this, 0, this._length); this._importants = {}; var dummyRule; try { dummyRule = CSSOM.parse('#bogus{' + value + '}').cssRules[0].style; } catch (err) { // malformed css, just return return; } var rule_length = dummyRule.length; var name; for (i = 0; i < rule_length; ++i) { name = dummyRule[i]; this.setProperty( dummyRule[i], dummyRule.getPropertyValue(name), dummyRule.getPropertyPriority(name) ); } this._onChange(this.cssText); }, enumerable: true, configurable: true, }, parentRule: { get: function() { return null; }, enumerable: true, configurable: true, }, length: { get: function() { return this._length; }, /** * This deletes indices if the new length is less then the current * length. If the new length is more, it does nothing, the new indices * will be undefined until set. **/ set: function(value) { var i; for (i = value; i < this._length; i++) { delete this[i]; } this._length = value; }, enumerable: true, configurable: true, }, }); require('cssstyle/lib/properties')(CSSStyleDeclaration.prototype); allProperties.forEach(function(property) { if (!implementedProperties.has(property)) { var declaration = getBasicPropertyDescriptor(property); Object.defineProperty(CSSStyleDeclaration.prototype, property, declaration); Object.defineProperty(CSSStyleDeclaration.prototype, dashedToCamelCase(property), declaration); } }); allExtraProperties.forEach(function(property) { if (!implementedProperties.has(property)) { var declaration = getBasicPropertyDescriptor(property); Object.defineProperty(CSSStyleDeclaration.prototype, property, declaration); Object.defineProperty(CSSStyleDeclaration.prototype, dashedToCamelCase(property), declaration); } }); exports.CSSStyleDeclaration = CSSStyleDeclaration;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssstyle/lib/CSSStyleDeclaration.js
CSSStyleDeclaration.js
'use strict'; var parsers = require('cssstyle/lib/parsers'); module.exports.definition = { set: function(v) { var valueType = parsers.valueType(v); if (valueType === parsers.TYPES.ANGLE) { return this._setProperty('azimuth', parsers.parseAngle(v)); } if (valueType === parsers.TYPES.KEYWORD) { var keywords = v .toLowerCase() .trim() .split(/\s+/); var hasBehind = false; if (keywords.length > 2) { return; } var behindIndex = keywords.indexOf('behind'); hasBehind = behindIndex !== -1; if (keywords.length === 2) { if (!hasBehind) { return; } keywords.splice(behindIndex, 1); } if (keywords[0] === 'leftwards' || keywords[0] === 'rightwards') { if (hasBehind) { return; } return this._setProperty('azimuth', keywords[0]); } if (keywords[0] === 'behind') { return this._setProperty('azimuth', '180deg'); } switch (keywords[0]) { case 'left-side': return this._setProperty('azimuth', '270deg'); case 'far-left': return this._setProperty('azimuth', (hasBehind ? 240 : 300) + 'deg'); case 'left': return this._setProperty('azimuth', (hasBehind ? 220 : 320) + 'deg'); case 'center-left': return this._setProperty('azimuth', (hasBehind ? 200 : 340) + 'deg'); case 'center': return this._setProperty('azimuth', (hasBehind ? 180 : 0) + 'deg'); case 'center-right': return this._setProperty('azimuth', (hasBehind ? 160 : 20) + 'deg'); case 'right': return this._setProperty('azimuth', (hasBehind ? 140 : 40) + 'deg'); case 'far-right': return this._setProperty('azimuth', (hasBehind ? 120 : 60) + 'deg'); case 'right-side': return this._setProperty('azimuth', '90deg'); default: return; } } }, get: function() { return this.getPropertyValue('azimuth'); }, enumerable: true, configurable: true, };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/cssstyle/lib/properties/azimuth.js
azimuth.js
aws4 ---- [![Build Status](https://api.travis-ci.org/mhart/aws4.png?branch=master)](https://travis-ci.org/github/mhart/aws4) A small utility to sign vanilla Node.js http(s) request options using Amazon's [AWS Signature Version 4](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). If you want to sign and send AWS requests in a modern browser, or an environment like [Cloudflare Workers](https://developers.cloudflare.com/workers/), then check out [aws4fetch](https://github.com/mhart/aws4fetch) – otherwise you can also bundle this library for use [in older browsers](./browser). The only AWS service that *doesn't* support v4 as of 2020-05-22 is [SimpleDB](https://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API.html) (it only supports [AWS Signature Version 2](https://github.com/mhart/aws2)). It also provides defaults for a number of core AWS headers and request parameters, making it very easy to query AWS services, or build out a fully-featured AWS library. Example ------- ```javascript var http = require('https') var aws4 = require('aws4') // to illustrate usage, we'll create a utility function to request and pipe to stdout function request(opts) { http.request(opts, function(res) { res.pipe(process.stdout) }).end(opts.body || '') } // aws4 will sign an options object as you'd pass to http.request, with an AWS service and region var opts = { host: 'my-bucket.s3.us-west-1.amazonaws.com', path: '/my-object', service: 's3', region: 'us-west-1' } // aws4.sign() will sign and modify these options, ready to pass to http.request aws4.sign(opts, { accessKeyId: '', secretAccessKey: '' }) // or it can get credentials from process.env.AWS_ACCESS_KEY_ID, etc aws4.sign(opts) // for most AWS services, aws4 can figure out the service and region if you pass a host opts = { host: 'my-bucket.s3.us-west-1.amazonaws.com', path: '/my-object' } // usually it will add/modify request headers, but you can also sign the query: opts = { host: 'my-bucket.s3.amazonaws.com', path: '/?X-Amz-Expires=12345', signQuery: true } // and for services with simple hosts, aws4 can infer the host from service and region: opts = { service: 'sqs', region: 'us-east-1', path: '/?Action=ListQueues' } // and if you're using us-east-1, it's the default: opts = { service: 'sqs', path: '/?Action=ListQueues' } aws4.sign(opts) console.log(opts) /* { host: 'sqs.us-east-1.amazonaws.com', path: '/?Action=ListQueues', headers: { Host: 'sqs.us-east-1.amazonaws.com', 'X-Amz-Date': '20121226T061030Z', Authorization: 'AWS4-HMAC-SHA256 Credential=ABCDEF/20121226/us-east-1/sqs/aws4_request, ...' } } */ // we can now use this to query AWS request(opts) /* <?xml version="1.0"?> <ListQueuesResponse xmlns="https://queue.amazonaws.com/doc/2012-11-05/"> ... */ // aws4 can infer the HTTP method if a body is passed in // method will be POST and Content-Type: 'application/x-www-form-urlencoded; charset=utf-8' request(aws4.sign({ service: 'iam', body: 'Action=ListGroups&Version=2010-05-08' })) /* <ListGroupsResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/"> ... */ // you can specify any custom option or header as per usual request(aws4.sign({ service: 'dynamodb', region: 'ap-southeast-2', method: 'POST', path: '/', headers: { 'Content-Type': 'application/x-amz-json-1.0', 'X-Amz-Target': 'DynamoDB_20120810.ListTables' }, body: '{}' })) /* {"TableNames":[]} ... */ // see example.js for examples with other services ``` API --- ### aws4.sign(requestOptions, [credentials]) This calculates and populates the `Authorization` header of `requestOptions`, and any other necessary AWS headers and/or request options. Returns `requestOptions` as a convenience for chaining. `requestOptions` is an object holding the same options that the node.js [http.request](https://nodejs.org/docs/latest/api/http.html#http_http_request_options_callback) function takes. The following properties of `requestOptions` are used in the signing or populated if they don't already exist: - `hostname` or `host` (will try to be determined from `service` and `region` if not given) - `method` (will use `'GET'` if not given or `'POST'` if there is a `body`) - `path` (will use `'/'` if not given) - `body` (will use `''` if not given) - `service` (will try to be calculated from `hostname` or `host` if not given) - `region` (will try to be calculated from `hostname` or `host` or use `'us-east-1'` if not given) - `headers['Host']` (will use `hostname` or `host` or be calculated if not given) - `headers['Content-Type']` (will use `'application/x-www-form-urlencoded; charset=utf-8'` if not given and there is a `body`) - `headers['Date']` (used to calculate the signature date if given, otherwise `new Date` is used) Your AWS credentials (which can be found in your [AWS console](https://portal.aws.amazon.com/gp/aws/securityCredentials)) can be specified in one of two ways: - As the second argument, like this: ```javascript aws4.sign(requestOptions, { secretAccessKey: "<your-secret-access-key>", accessKeyId: "<your-access-key-id>", sessionToken: "<your-session-token>" }) ``` - From `process.env`, such as this: ``` export AWS_ACCESS_KEY_ID="<your-access-key-id>" export AWS_SECRET_ACCESS_KEY="<your-secret-access-key>" export AWS_SESSION_TOKEN="<your-session-token>" ``` (will also use `AWS_ACCESS_KEY` and `AWS_SECRET_KEY` if available) The `sessionToken` property and `AWS_SESSION_TOKEN` environment variable are optional for signing with [IAM STS temporary credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html). Installation ------------ With [npm](https://www.npmjs.com/) do: ``` npm install aws4 ``` Can also be used [in the browser](./browser). Thanks ------ Thanks to [@jed](https://github.com/jed) for his [dynamo-client](https://github.com/jed/dynamo-client) lib where I first committed and subsequently extracted this code. Also thanks to the [official node.js AWS SDK](https://github.com/aws/aws-sdk-js) for giving me a start on implementing the v4 signature.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/aws4/README.md
README.md
var aws4 = exports, url = require('url'), querystring = require('querystring'), crypto = require('crypto'), lru = require('aws4/lru'), credentialsCache = lru(1000) // http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html function hmac(key, string, encoding) { return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding) } function hash(string, encoding) { return crypto.createHash('sha256').update(string, 'utf8').digest(encoding) } // This function assumes the string has already been percent encoded function encodeRfc3986(urlEncodedString) { return urlEncodedString.replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() }) } function encodeRfc3986Full(str) { return encodeRfc3986(encodeURIComponent(str)) } // request: { path | body, [host], [method], [headers], [service], [region] } // credentials: { accessKeyId, secretAccessKey, [sessionToken] } function RequestSigner(request, credentials) { if (typeof request === 'string') request = url.parse(request) var headers = request.headers = (request.headers || {}), hostParts = (!this.service || !this.region) && this.matchHost(request.hostname || request.host || headers.Host || headers.host) this.request = request this.credentials = credentials || this.defaultCredentials() this.service = request.service || hostParts[0] || '' this.region = request.region || hostParts[1] || 'us-east-1' // SES uses a different domain from the service name if (this.service === 'email') this.service = 'ses' if (!request.method && request.body) request.method = 'POST' if (!headers.Host && !headers.host) { headers.Host = request.hostname || request.host || this.createHost() // If a port is specified explicitly, use it as is if (request.port) headers.Host += ':' + request.port } if (!request.hostname && !request.host) request.hostname = headers.Host || headers.host this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' } RequestSigner.prototype.matchHost = function(host) { var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/) var hostParts = (match || []).slice(1, 3) // ES's hostParts are sometimes the other way round, if the value that is expected // to be region equals ‘es’ switch them back // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com if (hostParts[1] === 'es') hostParts = hostParts.reverse() if (hostParts[1] == 's3') { hostParts[0] = 's3' hostParts[1] = 'us-east-1' } else { for (var i = 0; i < 2; i++) { if (/^s3-/.test(hostParts[i])) { hostParts[1] = hostParts[i].slice(3) hostParts[0] = 's3' break } } } return hostParts } // http://docs.aws.amazon.com/general/latest/gr/rande.html RequestSigner.prototype.isSingleRegion = function() { // Special case for S3 and SimpleDB in us-east-1 if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts'] .indexOf(this.service) >= 0 } RequestSigner.prototype.createHost = function() { var region = this.isSingleRegion() ? '' : '.' + this.region, subdomain = this.service === 'ses' ? 'email' : this.service return subdomain + region + '.amazonaws.com' } RequestSigner.prototype.prepareRequest = function() { this.parsePath() var request = this.request, headers = request.headers, query if (request.signQuery) { this.parsedPath.query = query = this.parsedPath.query || {} if (this.credentials.sessionToken) query['X-Amz-Security-Token'] = this.credentials.sessionToken if (this.service === 's3' && !query['X-Amz-Expires']) query['X-Amz-Expires'] = 86400 if (query['X-Amz-Date']) this.datetime = query['X-Amz-Date'] else query['X-Amz-Date'] = this.getDateTime() query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256' query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString() query['X-Amz-SignedHeaders'] = this.signedHeaders() } else { if (!request.doNotModifyHeaders && !this.isCodeCommitGit) { if (request.body && !headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8' if (request.body && !headers['Content-Length'] && !headers['content-length']) headers['Content-Length'] = Buffer.byteLength(request.body) if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) headers['X-Amz-Security-Token'] = this.credentials.sessionToken if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex') if (headers['X-Amz-Date'] || headers['x-amz-date']) this.datetime = headers['X-Amz-Date'] || headers['x-amz-date'] else headers['X-Amz-Date'] = this.getDateTime() } delete headers.Authorization delete headers.authorization } } RequestSigner.prototype.sign = function() { if (!this.parsedPath) this.prepareRequest() if (this.request.signQuery) { this.parsedPath.query['X-Amz-Signature'] = this.signature() } else { this.request.headers.Authorization = this.authHeader() } this.request.path = this.formatPath() return this.request } RequestSigner.prototype.getDateTime = function() { if (!this.datetime) { var headers = this.request.headers, date = new Date(headers.Date || headers.date || new Date) this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '') // Remove the trailing 'Z' on the timestamp string for CodeCommit git access if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1) } return this.datetime } RequestSigner.prototype.getDate = function() { return this.getDateTime().substr(0, 8) } RequestSigner.prototype.authHeader = function() { return [ 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), 'SignedHeaders=' + this.signedHeaders(), 'Signature=' + this.signature(), ].join(', ') } RequestSigner.prototype.signature = function() { var date = this.getDate(), cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(), kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey) if (!kCredentials) { kDate = hmac('AWS4' + this.credentials.secretAccessKey, date) kRegion = hmac(kDate, this.region) kService = hmac(kRegion, this.service) kCredentials = hmac(kService, 'aws4_request') credentialsCache.set(cacheKey, kCredentials) } return hmac(kCredentials, this.stringToSign(), 'hex') } RequestSigner.prototype.stringToSign = function() { return [ 'AWS4-HMAC-SHA256', this.getDateTime(), this.credentialString(), hash(this.canonicalString(), 'hex'), ].join('\n') } RequestSigner.prototype.canonicalString = function() { if (!this.parsedPath) this.prepareRequest() var pathStr = this.parsedPath.path, query = this.parsedPath.query, headers = this.request.headers, queryStr = '', normalizePath = this.service !== 's3', decodePath = this.service === 's3' || this.request.doNotEncodePath, decodeSlashesInPath = this.service === 's3', firstValOnly = this.service === 's3', bodyHash if (this.service === 's3' && this.request.signQuery) { bodyHash = 'UNSIGNED-PAYLOAD' } else if (this.isCodeCommitGit) { bodyHash = '' } else { bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] || hash(this.request.body || '', 'hex') } if (query) { var reducedQuery = Object.keys(query).reduce(function(obj, key) { if (!key) return obj obj[encodeRfc3986Full(key)] = !Array.isArray(query[key]) ? query[key] : (firstValOnly ? query[key][0] : query[key]) return obj }, {}) var encodedQueryPieces = [] Object.keys(reducedQuery).sort().forEach(function(key) { if (!Array.isArray(reducedQuery[key])) { encodedQueryPieces.push(key + '=' + encodeRfc3986Full(reducedQuery[key])) } else { reducedQuery[key].map(encodeRfc3986Full).sort() .forEach(function(val) { encodedQueryPieces.push(key + '=' + val) }) } }) queryStr = encodedQueryPieces.join('&') } if (pathStr !== '/') { if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/') pathStr = pathStr.split('/').reduce(function(path, piece) { if (normalizePath && piece === '..') { path.pop() } else if (!normalizePath || piece !== '.') { if (decodePath) piece = decodeURIComponent(piece).replace(/\+/g, ' ') path.push(encodeRfc3986Full(piece)) } return path }, []).join('/') if (pathStr[0] !== '/') pathStr = '/' + pathStr if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/') } return [ this.request.method || 'GET', pathStr, queryStr, this.canonicalHeaders() + '\n', this.signedHeaders(), bodyHash, ].join('\n') } RequestSigner.prototype.canonicalHeaders = function() { var headers = this.request.headers function trimAll(header) { return header.toString().trim().replace(/\s+/g, ' ') } return Object.keys(headers) .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 }) .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) }) .join('\n') } RequestSigner.prototype.signedHeaders = function() { return Object.keys(this.request.headers) .map(function(key) { return key.toLowerCase() }) .sort() .join(';') } RequestSigner.prototype.credentialString = function() { return [ this.getDate(), this.region, this.service, 'aws4_request', ].join('/') } RequestSigner.prototype.defaultCredentials = function() { var env = process.env return { accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY, secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY, sessionToken: env.AWS_SESSION_TOKEN, } } RequestSigner.prototype.parsePath = function() { var path = this.request.path || '/' // S3 doesn't always encode characters > 127 correctly and // all services don't encode characters > 255 correctly // So if there are non-reserved chars (and it's not already all % encoded), just encode them all if (/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(path)) { path = encodeURI(decodeURI(path)) } var queryIx = path.indexOf('?'), query = null if (queryIx >= 0) { query = querystring.parse(path.slice(queryIx + 1)) path = path.slice(0, queryIx) } this.parsedPath = { path: path, query: query, } } RequestSigner.prototype.formatPath = function() { var path = this.parsedPath.path, query = this.parsedPath.query if (!query) return path // Services don't support empty query string keys if (query[''] != null) delete query[''] return path + '?' + encodeRfc3986(querystring.stringify(query)) } aws4.RequestSigner = RequestSigner aws4.sign = function(request, credentials) { return new RequestSigner(request, credentials).sign() }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/aws4/aws4.js
aws4.js
# acorn-globals Detect global variables in JavaScript using acorn [Get supported acorn-globals with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-acorn_globals?utm_source=npm-acorn-globals&utm_medium=referral&utm_campaign=readme) [![Build Status](https://img.shields.io/travis/ForbesLindesay/acorn-globals/master.svg)](https://travis-ci.org/ForbesLindesay/acorn-globals) [![Dependency Status](https://img.shields.io/david/ForbesLindesay/acorn-globals.svg)](https://david-dm.org/ForbesLindesay/acorn-globals) [![NPM version](https://img.shields.io/npm/v/acorn-globals.svg)](https://www.npmjs.org/package/acorn-globals) ## Installation npm install acorn-globals ## Usage detect.js ```js var fs = require('fs'); var detect = require('acorn-globals'); var src = fs.readFileSync(__dirname + '/input.js', 'utf8'); var scope = detect(src); console.dir(scope); ``` input.js ```js var x = 5; var y = 3, z = 2; w.foo(); w = 2; RAWR=444; RAWR.foo(); BLARG=3; foo(function () { var BAR = 3; process.nextTick(function (ZZZZZZZZZZZZ) { console.log('beep boop'); var xyz = 4; x += 10; x.zzzzzz; ZZZ=6; }); function doom () { } ZZZ.foo(); }); console.log(xyz); ``` output: ``` $ node example/detect.js [ { name: 'BLARG', nodes: [ [Object] ] }, { name: 'RAWR', nodes: [ [Object], [Object] ] }, { name: 'ZZZ', nodes: [ [Object], [Object] ] }, { name: 'console', nodes: [ [Object], [Object] ] }, { name: 'foo', nodes: [ [Object] ] }, { name: 'process', nodes: [ [Object] ] }, { name: 'w', nodes: [ [Object], [Object] ] }, { name: 'xyz', nodes: [ [Object] ] } ] ``` ## Security contact information To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. ## License MIT
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/acorn-globals/README.md
README.md
'use strict'; var acorn = require('acorn'); var walk = require('acorn-walk'); function isScope(node) { return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration' || node.type === 'ArrowFunctionExpression' || node.type === 'Program'; } function isBlockScope(node) { return node.type === 'BlockStatement' || isScope(node); } function declaresArguments(node) { return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration'; } function declaresThis(node) { return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration'; } function reallyParse(source, options) { var parseOptions = Object.assign({}, options, { allowReturnOutsideFunction: true, allowImportExportEverywhere: true, allowHashBang: true } ); return acorn.parse(source, parseOptions); } module.exports = findGlobals; module.exports.parse = reallyParse; function findGlobals(source, options) { options = options || {}; var globals = []; var ast; // istanbul ignore else if (typeof source === 'string') { ast = reallyParse(source, options); } else { ast = source; } // istanbul ignore if if (!(ast && typeof ast === 'object' && ast.type === 'Program')) { throw new TypeError('Source must be either a string of JavaScript or an acorn AST'); } var declareFunction = function (node) { var fn = node; fn.locals = fn.locals || Object.create(null); node.params.forEach(function (node) { declarePattern(node, fn); }); if (node.id) { fn.locals[node.id.name] = true; } }; var declareClass = function (node) { node.locals = node.locals || Object.create(null); if (node.id) { node.locals[node.id.name] = true; } }; var declarePattern = function (node, parent) { switch (node.type) { case 'Identifier': parent.locals[node.name] = true; break; case 'ObjectPattern': node.properties.forEach(function (node) { declarePattern(node.value || node.argument, parent); }); break; case 'ArrayPattern': node.elements.forEach(function (node) { if (node) declarePattern(node, parent); }); break; case 'RestElement': declarePattern(node.argument, parent); break; case 'AssignmentPattern': declarePattern(node.left, parent); break; // istanbul ignore next default: throw new Error('Unrecognized pattern type: ' + node.type); } }; var declareModuleSpecifier = function (node, parents) { ast.locals = ast.locals || Object.create(null); ast.locals[node.local.name] = true; }; walk.ancestor(ast, { 'VariableDeclaration': function (node, parents) { var parent = null; for (var i = parents.length - 1; i >= 0 && parent === null; i--) { if (node.kind === 'var' ? isScope(parents[i]) : isBlockScope(parents[i])) { parent = parents[i]; } } parent.locals = parent.locals || Object.create(null); node.declarations.forEach(function (declaration) { declarePattern(declaration.id, parent); }); }, 'FunctionDeclaration': function (node, parents) { var parent = null; for (var i = parents.length - 2; i >= 0 && parent === null; i--) { if (isScope(parents[i])) { parent = parents[i]; } } parent.locals = parent.locals || Object.create(null); if (node.id) { parent.locals[node.id.name] = true; } declareFunction(node); }, 'Function': declareFunction, 'ClassDeclaration': function (node, parents) { var parent = null; for (var i = parents.length - 2; i >= 0 && parent === null; i--) { if (isBlockScope(parents[i])) { parent = parents[i]; } } parent.locals = parent.locals || Object.create(null); if (node.id) { parent.locals[node.id.name] = true; } declareClass(node); }, 'Class': declareClass, 'TryStatement': function (node) { if (node.handler === null) return; node.handler.locals = node.handler.locals || Object.create(null); declarePattern(node.handler.param, node.handler); }, 'ImportDefaultSpecifier': declareModuleSpecifier, 'ImportSpecifier': declareModuleSpecifier, 'ImportNamespaceSpecifier': declareModuleSpecifier }); function identifier(node, parents) { var name = node.name; if (name === 'undefined') return; for (var i = 0; i < parents.length; i++) { if (name === 'arguments' && declaresArguments(parents[i])) { return; } if (parents[i].locals && name in parents[i].locals) { return; } } node.parents = parents.slice(); globals.push(node); } walk.ancestor(ast, { 'VariablePattern': identifier, 'Identifier': identifier, 'ThisExpression': function (node, parents) { for (var i = 0; i < parents.length; i++) { if (declaresThis(parents[i])) { return; } } node.parents = parents.slice(); globals.push(node); } }); var groupedGlobals = Object.create(null); globals.forEach(function (node) { var name = node.type === 'ThisExpression' ? 'this' : node.name; groupedGlobals[name] = (groupedGlobals[name] || []); groupedGlobals[name].push(node); }); return Object.keys(groupedGlobals).sort().map(function (name) { return {name: name, nodes: groupedGlobals[name]}; }); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/acorn-globals/index.js
index.js
btoa === | [atob](https://git.coolaj86.com/coolaj86/atob.js) | **btoa** | [unibabel.js](https://git.coolaj86.com/coolaj86/unibabel.js) | Sponsored by [ppl](https://ppl.family) A port of the browser's `btoa` function. Uses `Buffer` to emulate the exact functionality of the browser's btoa (except that it supports some unicode that the browser may not). It turns <strong>b</strong>inary data __to__ base64-encoded <strong>a</strong>scii. ```js (function () { "use strict"; var btoa = require('btoa'); var bin = "Hello, 世界"; var b64 = btoa(bin); console.log(b64); // "SGVsbG8sIBZM" }()); ``` **Note**: Unicode may or may not be handled incorrectly. This module is intended to provide exact compatibility with the browser. Copyright and License === Code copyright 2012-2018 AJ ONeal Dual-licensed MIT and Apache-2.0 Docs copyright 2012-2018 AJ ONeal Docs released under [Creative Commons](https://git.coolaj86.com/coolaj86/btoa.js/blob/master/LICENSE.DOCS).
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/btoa/README.md
README.md
# whatwg-url whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). ## Specification conformance whatwg-url is currently up to date with the URL spec up to commit [cceb435](https://github.com/whatwg/url/commit/cceb4356cca233b6dfdaabd888263157b2204e44). For `file:` URLs, whose [origin is left unspecified](https://url.spec.whatwg.org/#concept-url-origin), whatwg-url chooses to use a new opaque origin (which serializes to `"null"`). ## API ### The `URL` and `URLSearchParams` classes The main API is provided by the [`URL`](https://url.spec.whatwg.org/#url-class) and [`URLSearchParams`](https://url.spec.whatwg.org/#interface-urlsearchparams) exports, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use these. ### Low-level URL Standard API The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They mostly operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. - [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` - [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` - [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` - [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` - [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` - [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin): `serializeURLOrigin(urlRecord)` - [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` - [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` - [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` - [Percent decode](https://url.spec.whatwg.org/#percent-decode): `percentDecode(buffer)` The `stateOverride` parameter is one of the following strings: - [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) - [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) - [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) - [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) - [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) - [`"relative"`](https://url.spec.whatwg.org/#relative-state) - [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) - [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) - [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) - [`"authority"`](https://url.spec.whatwg.org/#authority-state) - [`"host"`](https://url.spec.whatwg.org/#host-state) - [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) - [`"port"`](https://url.spec.whatwg.org/#port-state) - [`"file"`](https://url.spec.whatwg.org/#file-state) - [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) - [`"file host"`](https://url.spec.whatwg.org/#file-host-state) - [`"path start"`](https://url.spec.whatwg.org/#path-start-state) - [`"path"`](https://url.spec.whatwg.org/#path-state) - [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) - [`"query"`](https://url.spec.whatwg.org/#query-state) - [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) The URL record type has the following API: - [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) - [`username`](https://url.spec.whatwg.org/#concept-url-username) - [`password`](https://url.spec.whatwg.org/#concept-url-password) - [`host`](https://url.spec.whatwg.org/#concept-url-host) - [`port`](https://url.spec.whatwg.org/#concept-url-port) - [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) - [`query`](https://url.spec.whatwg.org/#concept-url-query) - [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) - [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. The return value of "failure" in the spec is represented by `null`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ `null`. ### `whatwg-url/webidl2js-wrapper` module This module exports the `URL` and `URLSearchParams` [interface wrappers API](https://github.com/jsdom/webidl2js#for-interfaces) generated by [webidl2js](https://github.com/jsdom/webidl2js). ## Development instructions First, install [Node.js](https://nodejs.org/). Then, fetch the dependencies of whatwg-url, by running from this directory: npm install To run tests: npm test To generate a coverage report: npm run coverage To build and run the live viewer: npm run build npm run build-live-viewer Serve the contents of the `live-viewer` directory using any web server. ## Supporting whatwg-url The jsdom project (including whatwg-url) is a community-driven project maintained by a team of [volunteers](https://github.com/orgs/jsdom/people). You could support us by: - [Getting professional support for whatwg-url](https://tidelift.com/subscription/pkg/npm-whatwg-url?utm_source=npm-whatwg-url&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 directly to the project.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/whatwg-url/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/whatwg-url/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/whatwg-url/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/whatwg-url/node_modules/webidl-conversions/lib/index.js
index.js
"use strict"; const punycode = require("punycode"); const tr46 = require("tr46"); const infra = require("whatwg-url/lib/infra"); const { percentEncode, percentDecode } = require("whatwg-url/lib/urlencoded"); const specialSchemes = { ftp: 21, file: null, http: 80, https: 443, ws: 80, wss: 443 }; const failure = Symbol("failure"); function countSymbols(str) { return punycode.ucs2.decode(str).length; } function at(input, idx) { const c = input[idx]; return isNaN(c) ? undefined : String.fromCodePoint(c); } function isSingleDot(buffer) { return buffer === "." || buffer.toLowerCase() === "%2e"; } function isDoubleDot(buffer) { buffer = buffer.toLowerCase(); return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; } function isWindowsDriveLetterCodePoints(cp1, cp2) { return infra.isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); } function isWindowsDriveLetterString(string) { return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); } function isNormalizedWindowsDriveLetterString(string) { return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; } function containsForbiddenHostCodePoint(string) { return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; } function containsForbiddenHostCodePointExcludingPercent(string) { return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; } function isSpecialScheme(scheme) { return specialSchemes[scheme] !== undefined; } function isSpecial(url) { return isSpecialScheme(url.scheme); } function isNotSpecial(url) { return !isSpecialScheme(url.scheme); } function defaultPort(scheme) { return specialSchemes[scheme]; } function utf8PercentEncode(c) { const buf = Buffer.from(c); let str = ""; for (let i = 0; i < buf.length; ++i) { str += percentEncode(buf[i]); } return str; } function isC0ControlPercentEncode(c) { return c <= 0x1F || c > 0x7E; } const extraUserinfoPercentEncodeSet = new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); function isUserinfoPercentEncode(c) { return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); } const extraFragmentPercentEncodeSet = new Set([32, 34, 60, 62, 96]); function isFragmentPercentEncode(c) { return isC0ControlPercentEncode(c) || extraFragmentPercentEncodeSet.has(c); } const extraPathPercentEncodeSet = new Set([35, 63, 123, 125]); function isPathPercentEncode(c) { return isFragmentPercentEncode(c) || extraPathPercentEncodeSet.has(c); } function percentEncodeChar(c, encodeSetPredicate) { const cStr = String.fromCodePoint(c); if (encodeSetPredicate(c)) { return utf8PercentEncode(cStr); } return cStr; } function parseIPv4Number(input) { let R = 10; if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { input = input.substring(2); R = 16; } else if (input.length >= 2 && input.charAt(0) === "0") { input = input.substring(1); R = 8; } if (input === "") { return 0; } let regex = /[^0-7]/; if (R === 10) { regex = /[^0-9]/; } if (R === 16) { regex = /[^0-9A-Fa-f]/; } if (regex.test(input)) { return failure; } return parseInt(input, R); } function parseIPv4(input) { const parts = input.split("."); if (parts[parts.length - 1] === "") { if (parts.length > 1) { parts.pop(); } } if (parts.length > 4) { return input; } const numbers = []; for (const part of parts) { if (part === "") { return input; } const n = parseIPv4Number(part); if (n === failure) { return input; } numbers.push(n); } for (let i = 0; i < numbers.length - 1; ++i) { if (numbers[i] > 255) { return failure; } } if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { return failure; } let ipv4 = numbers.pop(); let counter = 0; for (const n of numbers) { ipv4 += n * Math.pow(256, 3 - counter); ++counter; } return ipv4; } function serializeIPv4(address) { let output = ""; let n = address; for (let i = 1; i <= 4; ++i) { output = String(n % 256) + output; if (i !== 4) { output = "." + output; } n = Math.floor(n / 256); } return output; } function parseIPv6(input) { const address = [0, 0, 0, 0, 0, 0, 0, 0]; let pieceIndex = 0; let compress = null; let pointer = 0; input = punycode.ucs2.decode(input); if (input[pointer] === 58) { if (input[pointer + 1] !== 58) { return failure; } pointer += 2; ++pieceIndex; compress = pieceIndex; } while (pointer < input.length) { if (pieceIndex === 8) { return failure; } if (input[pointer] === 58) { if (compress !== null) { return failure; } ++pointer; ++pieceIndex; compress = pieceIndex; continue; } let value = 0; let length = 0; while (length < 4 && infra.isASCIIHex(input[pointer])) { value = value * 0x10 + parseInt(at(input, pointer), 16); ++pointer; ++length; } if (input[pointer] === 46) { if (length === 0) { return failure; } pointer -= length; if (pieceIndex > 6) { return failure; } let numbersSeen = 0; while (input[pointer] !== undefined) { let ipv4Piece = null; if (numbersSeen > 0) { if (input[pointer] === 46 && numbersSeen < 4) { ++pointer; } else { return failure; } } if (!infra.isASCIIDigit(input[pointer])) { return failure; } while (infra.isASCIIDigit(input[pointer])) { const number = parseInt(at(input, pointer)); if (ipv4Piece === null) { ipv4Piece = number; } else if (ipv4Piece === 0) { return failure; } else { ipv4Piece = ipv4Piece * 10 + number; } if (ipv4Piece > 255) { return failure; } ++pointer; } address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; ++numbersSeen; if (numbersSeen === 2 || numbersSeen === 4) { ++pieceIndex; } } if (numbersSeen !== 4) { return failure; } break; } else if (input[pointer] === 58) { ++pointer; if (input[pointer] === undefined) { return failure; } } else if (input[pointer] !== undefined) { return failure; } address[pieceIndex] = value; ++pieceIndex; } if (compress !== null) { let swaps = pieceIndex - compress; pieceIndex = 7; while (pieceIndex !== 0 && swaps > 0) { const temp = address[compress + swaps - 1]; address[compress + swaps - 1] = address[pieceIndex]; address[pieceIndex] = temp; --pieceIndex; --swaps; } } else if (compress === null && pieceIndex !== 8) { return failure; } return address; } function serializeIPv6(address) { let output = ""; const seqResult = findLongestZeroSequence(address); const compress = seqResult.idx; let ignore0 = false; for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { if (ignore0 && address[pieceIndex] === 0) { continue; } else if (ignore0) { ignore0 = false; } if (compress === pieceIndex) { const separator = pieceIndex === 0 ? "::" : ":"; output += separator; ignore0 = true; continue; } output += address[pieceIndex].toString(16); if (pieceIndex !== 7) { output += ":"; } } return output; } function parseHost(input, isNotSpecialArg = false) { if (input[0] === "[") { if (input[input.length - 1] !== "]") { return failure; } return parseIPv6(input.substring(1, input.length - 1)); } if (isNotSpecialArg) { return parseOpaqueHost(input); } const domain = percentDecode(Buffer.from(input)).toString(); const asciiDomain = domainToASCII(domain); if (asciiDomain === failure) { return failure; } if (containsForbiddenHostCodePoint(asciiDomain)) { return failure; } const ipv4Host = parseIPv4(asciiDomain); if (typeof ipv4Host === "number" || ipv4Host === failure) { return ipv4Host; } return asciiDomain; } function parseOpaqueHost(input) { if (containsForbiddenHostCodePointExcludingPercent(input)) { return failure; } let output = ""; const decoded = punycode.ucs2.decode(input); for (let i = 0; i < decoded.length; ++i) { output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); } return output; } function findLongestZeroSequence(arr) { let maxIdx = null; let maxLen = 1; // only find elements > 1 let currStart = null; let currLen = 0; for (let i = 0; i < arr.length; ++i) { if (arr[i] !== 0) { if (currLen > maxLen) { maxIdx = currStart; maxLen = currLen; } currStart = null; currLen = 0; } else { if (currStart === null) { currStart = i; } ++currLen; } } // if trailing zeros if (currLen > maxLen) { maxIdx = currStart; maxLen = currLen; } return { idx: maxIdx, len: maxLen }; } function serializeHost(host) { if (typeof host === "number") { return serializeIPv4(host); } // IPv6 serializer if (host instanceof Array) { return "[" + serializeIPv6(host) + "]"; } return host; } function domainToASCII(domain, beStrict = false) { const result = tr46.toASCII(domain, { checkBidi: true, checkHyphens: false, checkJoiners: true, useSTD3ASCIIRules: beStrict, verifyDNSLength: beStrict }); if (result === null || result === "") { return failure; } return result; } function trimControlChars(url) { return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); } function trimTabAndNewline(url) { return url.replace(/\u0009|\u000A|\u000D/g, ""); } function shortenPath(url) { const { path } = url; if (path.length === 0) { return; } if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { return; } path.pop(); } function includesCredentials(url) { return url.username !== "" || url.password !== ""; } function cannotHaveAUsernamePasswordPort(url) { return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; } function isNormalizedWindowsDriveLetter(string) { return /^[A-Za-z]:$/.test(string); } function URLStateMachine(input, base, encodingOverride, url, stateOverride) { this.pointer = 0; this.input = input; this.base = base || null; this.encodingOverride = encodingOverride || "utf-8"; this.stateOverride = stateOverride; this.url = url; this.failure = false; this.parseError = false; if (!this.url) { this.url = { scheme: "", username: "", password: "", host: null, port: null, path: [], query: null, fragment: null, cannotBeABaseURL: false }; const res = trimControlChars(this.input); if (res !== this.input) { this.parseError = true; } this.input = res; } const res = trimTabAndNewline(this.input); if (res !== this.input) { this.parseError = true; } this.input = res; this.state = stateOverride || "scheme start"; this.buffer = ""; this.atFlag = false; this.arrFlag = false; this.passwordTokenSeenFlag = false; this.input = punycode.ucs2.decode(this.input); for (; this.pointer <= this.input.length; ++this.pointer) { const c = this.input[this.pointer]; const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); // exec state machine const ret = this["parse " + this.state](c, cStr); if (!ret) { break; // terminate algorithm } else if (ret === failure) { this.failure = true; break; } } } URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { if (infra.isASCIIAlpha(c)) { this.buffer += cStr.toLowerCase(); this.state = "scheme"; } else if (!this.stateOverride) { this.state = "no scheme"; --this.pointer; } else { this.parseError = true; return failure; } return true; }; URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { if (infra.isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { this.buffer += cStr.toLowerCase(); } else if (c === 58) { if (this.stateOverride) { if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { return false; } if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { return false; } if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { return false; } if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { return false; } } this.url.scheme = this.buffer; if (this.stateOverride) { if (this.url.port === defaultPort(this.url.scheme)) { this.url.port = null; } return false; } this.buffer = ""; if (this.url.scheme === "file") { if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { this.parseError = true; } this.state = "file"; } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { this.state = "special relative or authority"; } else if (isSpecial(this.url)) { this.state = "special authority slashes"; } else if (this.input[this.pointer + 1] === 47) { this.state = "path or authority"; ++this.pointer; } else { this.url.cannotBeABaseURL = true; this.url.path.push(""); this.state = "cannot-be-a-base-URL path"; } } else if (!this.stateOverride) { this.buffer = ""; this.state = "no scheme"; this.pointer = -1; } else { this.parseError = true; return failure; } return true; }; URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { return failure; } else if (this.base.cannotBeABaseURL && c === 35) { this.url.scheme = this.base.scheme; this.url.path = this.base.path.slice(); this.url.query = this.base.query; this.url.fragment = ""; this.url.cannotBeABaseURL = true; this.state = "fragment"; } else if (this.base.scheme === "file") { this.state = "file"; --this.pointer; } else { this.state = "relative"; --this.pointer; } return true; }; URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { if (c === 47 && this.input[this.pointer + 1] === 47) { this.state = "special authority ignore slashes"; ++this.pointer; } else { this.parseError = true; this.state = "relative"; --this.pointer; } return true; }; URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { if (c === 47) { this.state = "authority"; } else { this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse relative"] = function parseRelative(c) { this.url.scheme = this.base.scheme; if (isNaN(c)) { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(); this.url.query = this.base.query; } else if (c === 47) { this.state = "relative slash"; } else if (c === 63) { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(); this.url.query = ""; this.state = "query"; } else if (c === 35) { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(); this.url.query = this.base.query; this.url.fragment = ""; this.state = "fragment"; } else if (isSpecial(this.url) && c === 92) { this.parseError = true; this.state = "relative slash"; } else { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(0, this.base.path.length - 1); this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { if (isSpecial(this.url) && (c === 47 || c === 92)) { if (c === 92) { this.parseError = true; } this.state = "special authority ignore slashes"; } else if (c === 47) { this.state = "authority"; } else { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { if (c === 47 && this.input[this.pointer + 1] === 47) { this.state = "special authority ignore slashes"; ++this.pointer; } else { this.parseError = true; this.state = "special authority ignore slashes"; --this.pointer; } return true; }; URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { if (c !== 47 && c !== 92) { this.state = "authority"; --this.pointer; } else { this.parseError = true; } return true; }; URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { if (c === 64) { this.parseError = true; if (this.atFlag) { this.buffer = "%40" + this.buffer; } this.atFlag = true; // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars const len = countSymbols(this.buffer); for (let pointer = 0; pointer < len; ++pointer) { const codePoint = this.buffer.codePointAt(pointer); if (codePoint === 58 && !this.passwordTokenSeenFlag) { this.passwordTokenSeenFlag = true; continue; } const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); if (this.passwordTokenSeenFlag) { this.url.password += encodedCodePoints; } else { this.url.username += encodedCodePoints; } } this.buffer = ""; } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || (isSpecial(this.url) && c === 92)) { if (this.atFlag && this.buffer === "") { this.parseError = true; return failure; } this.pointer -= countSymbols(this.buffer) + 1; this.buffer = ""; this.state = "host"; } else { this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse hostname"] = URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { if (this.stateOverride && this.url.scheme === "file") { --this.pointer; this.state = "file host"; } else if (c === 58 && !this.arrFlag) { if (this.buffer === "") { this.parseError = true; return failure; } const host = parseHost(this.buffer, isNotSpecial(this.url)); if (host === failure) { return failure; } this.url.host = host; this.buffer = ""; this.state = "port"; if (this.stateOverride === "hostname") { return false; } } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || (isSpecial(this.url) && c === 92)) { --this.pointer; if (isSpecial(this.url) && this.buffer === "") { this.parseError = true; return failure; } else if (this.stateOverride && this.buffer === "" && (includesCredentials(this.url) || this.url.port !== null)) { this.parseError = true; return false; } const host = parseHost(this.buffer, isNotSpecial(this.url)); if (host === failure) { return failure; } this.url.host = host; this.buffer = ""; this.state = "path start"; if (this.stateOverride) { return false; } } else { if (c === 91) { this.arrFlag = true; } else if (c === 93) { this.arrFlag = false; } this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { if (infra.isASCIIDigit(c)) { this.buffer += cStr; } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || (isSpecial(this.url) && c === 92) || this.stateOverride) { if (this.buffer !== "") { const port = parseInt(this.buffer); if (port > Math.pow(2, 16) - 1) { this.parseError = true; return failure; } this.url.port = port === defaultPort(this.url.scheme) ? null : port; this.buffer = ""; } if (this.stateOverride) { return false; } this.state = "path start"; --this.pointer; } else { this.parseError = true; return failure; } return true; }; const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); function startsWithWindowsDriveLetter(input, pointer) { const length = input.length - pointer; return length >= 2 && isWindowsDriveLetterCodePoints(input[pointer], input[pointer + 1]) && (length === 2 || fileOtherwiseCodePoints.has(input[pointer + 2])); } URLStateMachine.prototype["parse file"] = function parseFile(c) { this.url.scheme = "file"; if (c === 47 || c === 92) { if (c === 92) { this.parseError = true; } this.state = "file slash"; } else if (this.base !== null && this.base.scheme === "file") { if (isNaN(c)) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); this.url.query = this.base.query; } else if (c === 63) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); this.url.query = ""; this.state = "query"; } else if (c === 35) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); this.url.query = this.base.query; this.url.fragment = ""; this.state = "fragment"; } else { if (!startsWithWindowsDriveLetter(this.input, this.pointer)) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); shortenPath(this.url); } else { this.parseError = true; } this.state = "path"; --this.pointer; } } else { this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { if (c === 47 || c === 92) { if (c === 92) { this.parseError = true; } this.state = "file host"; } else { if (this.base !== null && this.base.scheme === "file" && !startsWithWindowsDriveLetter(this.input, this.pointer)) { if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { this.url.path.push(this.base.path[0]); } else { this.url.host = this.base.host; } } this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { --this.pointer; if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { this.parseError = true; this.state = "path"; } else if (this.buffer === "") { this.url.host = ""; if (this.stateOverride) { return false; } this.state = "path start"; } else { let host = parseHost(this.buffer, isNotSpecial(this.url)); if (host === failure) { return failure; } if (host === "localhost") { host = ""; } this.url.host = host; if (this.stateOverride) { return false; } this.buffer = ""; this.state = "path start"; } } else { this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { if (isSpecial(this.url)) { if (c === 92) { this.parseError = true; } this.state = "path"; if (c !== 47 && c !== 92) { --this.pointer; } } else if (!this.stateOverride && c === 63) { this.url.query = ""; this.state = "query"; } else if (!this.stateOverride && c === 35) { this.url.fragment = ""; this.state = "fragment"; } else if (c !== undefined) { this.state = "path"; if (c !== 47) { --this.pointer; } } return true; }; URLStateMachine.prototype["parse path"] = function parsePath(c) { if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || (!this.stateOverride && (c === 63 || c === 35))) { if (isSpecial(this.url) && c === 92) { this.parseError = true; } if (isDoubleDot(this.buffer)) { shortenPath(this.url); if (c !== 47 && !(isSpecial(this.url) && c === 92)) { this.url.path.push(""); } } else if (isSingleDot(this.buffer) && c !== 47 && !(isSpecial(this.url) && c === 92)) { this.url.path.push(""); } else if (!isSingleDot(this.buffer)) { if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { if (this.url.host !== "" && this.url.host !== null) { this.parseError = true; this.url.host = ""; } this.buffer = this.buffer[0] + ":"; } this.url.path.push(this.buffer); } this.buffer = ""; if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { while (this.url.path.length > 1 && this.url.path[0] === "") { this.parseError = true; this.url.path.shift(); } } if (c === 63) { this.url.query = ""; this.state = "query"; } if (c === 35) { this.url.fragment = ""; this.state = "fragment"; } } else { // TODO: If c is not a URL code point and not "%", parse error. if (c === 37 && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } this.buffer += percentEncodeChar(c, isPathPercentEncode); } return true; }; URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { if (c === 63) { this.url.query = ""; this.state = "query"; } else if (c === 35) { this.url.fragment = ""; this.state = "fragment"; } else { // TODO: Add: not a URL code point if (!isNaN(c) && c !== 37) { this.parseError = true; } if (c === 37 && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } if (!isNaN(c)) { this.url.path[0] += percentEncodeChar(c, isC0ControlPercentEncode); } } return true; }; URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { if (isNaN(c) || (!this.stateOverride && c === 35)) { if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { this.encodingOverride = "utf-8"; } const buffer = Buffer.from(this.buffer); // TODO: Use encoding override instead for (let i = 0; i < buffer.length; ++i) { if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || buffer[i] === 0x3C || buffer[i] === 0x3E || (buffer[i] === 0x27 && isSpecial(this.url))) { this.url.query += percentEncode(buffer[i]); } else { this.url.query += String.fromCodePoint(buffer[i]); } } this.buffer = ""; if (c === 35) { this.url.fragment = ""; this.state = "fragment"; } } else { // TODO: If c is not a URL code point and not "%", parse error. if (c === 37 && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { if (!isNaN(c)) { // TODO: If c is not a URL code point and not "%", parse error. if (c === 37 && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } this.url.fragment += percentEncodeChar(c, isFragmentPercentEncode); } return true; }; function serializeURL(url, excludeFragment) { let output = url.scheme + ":"; if (url.host !== null) { output += "//"; if (url.username !== "" || url.password !== "") { output += url.username; if (url.password !== "") { output += ":" + url.password; } output += "@"; } output += serializeHost(url.host); if (url.port !== null) { output += ":" + url.port; } } else if (url.host === null && url.scheme === "file") { output += "//"; } if (url.cannotBeABaseURL) { output += url.path[0]; } else { for (const string of url.path) { output += "/" + string; } } if (url.query !== null) { output += "?" + url.query; } if (!excludeFragment && url.fragment !== null) { output += "#" + url.fragment; } return output; } function serializeOrigin(tuple) { let result = tuple.scheme + "://"; result += serializeHost(tuple.host); if (tuple.port !== null) { result += ":" + tuple.port; } return result; } module.exports.serializeURL = serializeURL; module.exports.serializeURLOrigin = function (url) { // https://url.spec.whatwg.org/#concept-url-origin switch (url.scheme) { case "blob": try { return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); } catch (e) { // serializing an opaque origin returns "null" return "null"; } case "ftp": case "http": case "https": case "ws": case "wss": return serializeOrigin({ scheme: url.scheme, host: url.host, port: url.port }); case "file": // The spec says: // > Unfortunate as it is, this is left as an exercise to the reader. When in doubt, return a new opaque origin. // Browsers tested so far: // - Chrome says "file://", but treats file: URLs as cross-origin for most (all?) purposes; see e.g. // https://bugs.chromium.org/p/chromium/issues/detail?id=37586 // - Firefox says "null", but treats file: URLs as same-origin sometimes based on directory stuff; see // https://developer.mozilla.org/en-US/docs/Archive/Misc_top_level/Same-origin_policy_for_file:_URIs return "null"; default: // serializing an opaque origin returns "null" return "null"; } }; module.exports.basicURLParse = function (input, options) { if (options === undefined) { options = {}; } const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); if (usm.failure) { return null; } return usm.url; }; module.exports.setTheUsername = function (url, username) { url.username = ""; const decoded = punycode.ucs2.decode(username); for (let i = 0; i < decoded.length; ++i) { url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); } }; module.exports.setThePassword = function (url, password) { url.password = ""; const decoded = punycode.ucs2.decode(password); for (let i = 0; i < decoded.length; ++i) { url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); } }; module.exports.serializeHost = serializeHost; module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; module.exports.serializeInteger = function (integer) { return String(integer); }; module.exports.parseURL = function (input, options) { if (options === undefined) { options = {}; } // We don't handle blobs, so this just delegates: return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/whatwg-url/lib/url-state-machine.js
url-state-machine.js
"use strict"; const { isASCIIHex } = require("whatwg-url/lib/infra"); function strictlySplitByteSequence(buf, cp) { const list = []; let last = 0; let i = buf.indexOf(cp); while (i >= 0) { list.push(buf.slice(last, i)); last = i + 1; i = buf.indexOf(cp, last); } if (last !== buf.length) { list.push(buf.slice(last)); } return list; } function replaceByteInByteSequence(buf, from, to) { let i = buf.indexOf(from); while (i >= 0) { buf[i] = to; i = buf.indexOf(from, i + 1); } return buf; } function percentEncode(c) { let hex = c.toString(16).toUpperCase(); if (hex.length === 1) { hex = "0" + hex; } return "%" + hex; } function percentDecode(input) { const output = Buffer.alloc(input.byteLength); let ptr = 0; for (let i = 0; i < input.length; ++i) { if (input[i] !== 37 || !isASCIIHex(input[i + 1]) || !isASCIIHex(input[i + 2])) { output[ptr++] = input[i]; } else { output[ptr++] = parseInt(input.slice(i + 1, i + 3).toString(), 16); i += 2; } } return output.slice(0, ptr); } function parseUrlencoded(input) { const sequences = strictlySplitByteSequence(input, 38); const output = []; for (const bytes of sequences) { if (bytes.length === 0) { continue; } let name; let value; const indexOfEqual = bytes.indexOf(61); if (indexOfEqual >= 0) { name = bytes.slice(0, indexOfEqual); value = bytes.slice(indexOfEqual + 1); } else { name = bytes; value = Buffer.alloc(0); } name = replaceByteInByteSequence(Buffer.from(name), 43, 32); value = replaceByteInByteSequence(Buffer.from(value), 43, 32); output.push([percentDecode(name).toString(), percentDecode(value).toString()]); } return output; } function serializeUrlencodedByte(input) { let output = ""; for (const byte of input) { if (byte === 32) { output += "+"; } else if (byte === 42 || byte === 45 || byte === 46 || (byte >= 48 && byte <= 57) || (byte >= 65 && byte <= 90) || byte === 95 || (byte >= 97 && byte <= 122)) { output += String.fromCodePoint(byte); } else { output += percentEncode(byte); } } return output; } function serializeUrlencoded(tuples, encodingOverride = undefined) { let encoding = "utf-8"; if (encodingOverride !== undefined) { encoding = encodingOverride; } let output = ""; for (const [i, tuple] of tuples.entries()) { // TODO: handle encoding override const name = serializeUrlencodedByte(Buffer.from(tuple[0])); let value = tuple[1]; if (tuple.length > 2 && tuple[2] !== undefined) { if (tuple[2] === "hidden" && name === "_charset_") { value = encoding; } else if (tuple[2] === "file") { // value is a File object value = value.name; } } value = serializeUrlencodedByte(Buffer.from(value)); if (i !== 0) { output += "&"; } output += `${name}=${value}`; } return output; } module.exports = { percentEncode, percentDecode, // application/x-www-form-urlencoded string parser parseUrlencoded(input) { return parseUrlencoded(Buffer.from(input)); }, // application/x-www-form-urlencoded serializer serializeUrlencoded };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/whatwg-url/lib/urlencoded.js
urlencoded.js
"use strict"; const usm = require("whatwg-url/lib/url-state-machine"); const urlencoded = require("whatwg-url/lib/urlencoded"); const URLSearchParams = require("whatwg-url/lib/URLSearchParams"); exports.implementation = class URLImpl { constructor(globalObject, constructorArgs) { const url = constructorArgs[0]; const base = constructorArgs[1]; let parsedBase = null; if (base !== undefined) { parsedBase = usm.basicURLParse(base); if (parsedBase === null) { throw new TypeError(`Invalid base URL: ${base}`); } } const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); if (parsedURL === null) { throw new TypeError(`Invalid URL: ${url}`); } const query = parsedURL.query !== null ? parsedURL.query : ""; this._url = parsedURL; // We cannot invoke the "new URLSearchParams object" algorithm without going through the constructor, which strips // question mark by default. Therefore the doNotStripQMark hack is used. this._query = URLSearchParams.createImpl(globalObject, [query], { doNotStripQMark: true }); this._query._url = this; } get href() { return usm.serializeURL(this._url); } set href(v) { const parsedURL = usm.basicURLParse(v); if (parsedURL === null) { throw new TypeError(`Invalid URL: ${v}`); } this._url = parsedURL; this._query._list.splice(0); const { query } = parsedURL; if (query !== null) { this._query._list = urlencoded.parseUrlencoded(query); } } get origin() { return usm.serializeURLOrigin(this._url); } get protocol() { return this._url.scheme + ":"; } set protocol(v) { usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); } get username() { return this._url.username; } set username(v) { if (usm.cannotHaveAUsernamePasswordPort(this._url)) { return; } usm.setTheUsername(this._url, v); } get password() { return this._url.password; } set password(v) { if (usm.cannotHaveAUsernamePasswordPort(this._url)) { return; } usm.setThePassword(this._url, v); } get host() { const url = this._url; if (url.host === null) { return ""; } if (url.port === null) { return usm.serializeHost(url.host); } return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); } set host(v) { if (this._url.cannotBeABaseURL) { return; } usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); } get hostname() { if (this._url.host === null) { return ""; } return usm.serializeHost(this._url.host); } set hostname(v) { if (this._url.cannotBeABaseURL) { return; } usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); } get port() { if (this._url.port === null) { return ""; } return usm.serializeInteger(this._url.port); } set port(v) { if (usm.cannotHaveAUsernamePasswordPort(this._url)) { return; } if (v === "") { this._url.port = null; } else { usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); } } get pathname() { if (this._url.cannotBeABaseURL) { return this._url.path[0]; } if (this._url.path.length === 0) { return ""; } return "/" + this._url.path.join("/"); } set pathname(v) { if (this._url.cannotBeABaseURL) { return; } this._url.path = []; usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); } get search() { if (this._url.query === null || this._url.query === "") { return ""; } return "?" + this._url.query; } set search(v) { const url = this._url; if (v === "") { url.query = null; this._query._list = []; return; } const input = v[0] === "?" ? v.substring(1) : v; url.query = ""; usm.basicURLParse(input, { url, stateOverride: "query" }); this._query._list = urlencoded.parseUrlencoded(input); } get searchParams() { return this._query; } get hash() { if (this._url.fragment === null || this._url.fragment === "") { return ""; } return "#" + this._url.fragment; } set hash(v) { if (v === "") { this._url.fragment = null; return; } const input = v[0] === "#" ? v.substring(1) : v; this._url.fragment = ""; usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); } toJSON() { return this.href; } };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/whatwg-url/lib/URL-impl.js
URL-impl.js
"use strict"; const stableSortBy = require("lodash.sortby"); const urlencoded = require("whatwg-url/lib/urlencoded"); exports.implementation = class URLSearchParamsImpl { constructor(globalObject, constructorArgs, { doNotStripQMark = false }) { let init = constructorArgs[0]; this._list = []; this._url = null; if (!doNotStripQMark && typeof init === "string" && init[0] === "?") { init = init.slice(1); } if (Array.isArray(init)) { for (const pair of init) { if (pair.length !== 2) { throw new TypeError("Failed to construct 'URLSearchParams': parameter 1 sequence's element does not " + "contain exactly two elements."); } this._list.push([pair[0], pair[1]]); } } else if (typeof init === "object" && Object.getPrototypeOf(init) === null) { for (const name of Object.keys(init)) { const value = init[name]; this._list.push([name, value]); } } else { this._list = urlencoded.parseUrlencoded(init); } } _updateSteps() { if (this._url !== null) { let query = urlencoded.serializeUrlencoded(this._list); if (query === "") { query = null; } this._url._url.query = query; } } append(name, value) { this._list.push([name, value]); this._updateSteps(); } delete(name) { let i = 0; while (i < this._list.length) { if (this._list[i][0] === name) { this._list.splice(i, 1); } else { i++; } } this._updateSteps(); } get(name) { for (const tuple of this._list) { if (tuple[0] === name) { return tuple[1]; } } return null; } getAll(name) { const output = []; for (const tuple of this._list) { if (tuple[0] === name) { output.push(tuple[1]); } } return output; } has(name) { for (const tuple of this._list) { if (tuple[0] === name) { return true; } } return false; } set(name, value) { let found = false; let i = 0; while (i < this._list.length) { if (this._list[i][0] === name) { if (found) { this._list.splice(i, 1); } else { found = true; this._list[i][1] = value; i++; } } else { i++; } } if (!found) { this._list.push([name, value]); } this._updateSteps(); } sort() { this._list = stableSortBy(this._list, [0]); this._updateSteps(); } [Symbol.iterator]() { return this._list[Symbol.iterator](); } toString() { return urlencoded.serializeUrlencoded(this._list); } };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/whatwg-url/lib/URLSearchParams-impl.js
URLSearchParams-impl.js
"use strict"; const conversions = require("webidl-conversions"); const utils = require("whatwg-url/lib/utils.js"); const impl = utils.implSymbol; const ctorRegistry = utils.ctorRegistrySymbol; const interfaceName = "URLSearchParams"; const IteratorPrototype = Object.create(utils.IteratorPrototype, { next: { value: function next() { const internal = this[utils.iterInternalSymbol]; const { target, kind, index } = internal; const values = Array.from(target[impl]); const len = values.length; if (index >= len) { return { value: undefined, done: true }; } const pair = values[index]; internal.index = index + 1; const [key, value] = pair.map(utils.tryWrapperForImpl); let result; switch (kind) { case "key": result = key; break; case "value": result = value; break; case "key+value": result = [key, value]; break; } return { value: result, done: false }; }, writable: true, enumerable: true, configurable: true }, [Symbol.toStringTag]: { value: "URLSearchParams Iterator", configurable: true } }); /** * 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. */ exports._mixedIntoPredicates = []; exports.is = function is(obj) { if (obj) { if (utils.hasOwn(obj, impl) && obj[impl] instanceof Impl.implementation) { return true; } for (const isMixedInto of exports._mixedIntoPredicates) { if (isMixedInto(obj)) { return true; } } } return false; }; exports.isImpl = function isImpl(obj) { if (obj) { if (obj instanceof Impl.implementation) { return true; } const wrapper = utils.wrapperForImpl(obj); for (const isMixedInto of exports._mixedIntoPredicates) { if (isMixedInto(wrapper)) { return true; } } } return false; }; exports.convert = function convert(obj, { context = "The provided value" } = {}) { if (exports.is(obj)) { return utils.implForWrapper(obj); } throw new TypeError(`${context} is not of type 'URLSearchParams'.`); }; exports.createDefaultIterator = function createDefaultIterator(target, kind) { const iterator = Object.create(IteratorPrototype); Object.defineProperty(iterator, utils.iterInternalSymbol, { value: { target, kind, index: 0 }, configurable: true }); return iterator; }; exports.create = function create(globalObject, constructorArgs, privateData) { if (globalObject[ctorRegistry] === undefined) { throw new Error("Internal error: invalid global object"); } const ctor = globalObject[ctorRegistry]["URLSearchParams"]; if (ctor === undefined) { throw new Error("Internal error: constructor URLSearchParams is not installed on the passed global object"); } let obj = Object.create(ctor.prototype); obj = exports.setup(obj, globalObject, constructorArgs, privateData); return obj; }; exports.createImpl = function createImpl(globalObject, constructorArgs, privateData) { const obj = exports.create(globalObject, constructorArgs, privateData); return utils.implForWrapper(obj); }; exports._internalSetup = function _internalSetup(obj) {}; exports.setup = function setup(obj, globalObject, constructorArgs = [], privateData = {}) { privateData.wrapper = obj; exports._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; }; exports.install = function install(globalObject) { class URLSearchParams { constructor() { const args = []; { let curArg = arguments[0]; if (curArg !== undefined) { if (utils.isObject(curArg)) { if (curArg[Symbol.iterator] !== undefined) { if (!utils.isObject(curArg)) { throw new TypeError( "Failed to construct 'URLSearchParams': parameter 1" + " sequence" + " is not an iterable object." ); } else { const V = []; const tmp = curArg; for (let nextItem of tmp) { if (!utils.isObject(nextItem)) { throw new TypeError( "Failed to construct 'URLSearchParams': parameter 1" + " sequence" + "'s element" + " is not an iterable object." ); } else { const V = []; const tmp = nextItem; for (let nextItem of tmp) { nextItem = conversions["USVString"](nextItem, { context: "Failed to construct 'URLSearchParams': parameter 1" + " sequence" + "'s element" + "'s element" }); V.push(nextItem); } nextItem = V; } V.push(nextItem); } curArg = V; } } else { if (!utils.isObject(curArg)) { throw new TypeError( "Failed to construct 'URLSearchParams': parameter 1" + " record" + " is not an object." ); } else { const result = Object.create(null); for (const key of Reflect.ownKeys(curArg)) { const desc = Object.getOwnPropertyDescriptor(curArg, key); if (desc && desc.enumerable) { let typedKey = key; typedKey = conversions["USVString"](typedKey, { context: "Failed to construct 'URLSearchParams': parameter 1" + " record" + "'s key" }); let typedValue = curArg[key]; typedValue = conversions["USVString"](typedValue, { context: "Failed to construct 'URLSearchParams': parameter 1" + " record" + "'s value" }); result[typedKey] = typedValue; } } curArg = result; } } } else { curArg = conversions["USVString"](curArg, { context: "Failed to construct 'URLSearchParams': parameter 1" }); } } else { curArg = ""; } args.push(curArg); } return exports.setup(Object.create(new.target.prototype), globalObject, args); } append(name, value) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 2) { throw new TypeError( "Failed to execute 'append' on 'URLSearchParams': 2 arguments required, but only " + arguments.length + " present." ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'append' on 'URLSearchParams': parameter 1" }); args.push(curArg); } { let curArg = arguments[1]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'append' on 'URLSearchParams': parameter 2" }); args.push(curArg); } return this[impl].append(...args); } delete(name) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 1) { throw new TypeError( "Failed to execute 'delete' on 'URLSearchParams': 1 argument required, but only " + arguments.length + " present." ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'delete' on 'URLSearchParams': parameter 1" }); args.push(curArg); } return this[impl].delete(...args); } get(name) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 1) { throw new TypeError( "Failed to execute 'get' on 'URLSearchParams': 1 argument required, but only " + arguments.length + " present." ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'get' on 'URLSearchParams': parameter 1" }); args.push(curArg); } return this[impl].get(...args); } getAll(name) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 1) { throw new TypeError( "Failed to execute 'getAll' on 'URLSearchParams': 1 argument required, but only " + arguments.length + " present." ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'getAll' on 'URLSearchParams': parameter 1" }); args.push(curArg); } return utils.tryWrapperForImpl(this[impl].getAll(...args)); } has(name) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 1) { throw new TypeError( "Failed to execute 'has' on 'URLSearchParams': 1 argument required, but only " + arguments.length + " present." ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'has' on 'URLSearchParams': parameter 1" }); args.push(curArg); } return this[impl].has(...args); } set(name, value) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 2) { throw new TypeError( "Failed to execute 'set' on 'URLSearchParams': 2 arguments required, but only " + arguments.length + " present." ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'set' on 'URLSearchParams': parameter 1" }); args.push(curArg); } { let curArg = arguments[1]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'set' on 'URLSearchParams': parameter 2" }); args.push(curArg); } return this[impl].set(...args); } sort() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl].sort(); } toString() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl].toString(); } keys() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return exports.createDefaultIterator(this, "key"); } values() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return exports.createDefaultIterator(this, "value"); } entries() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return exports.createDefaultIterator(this, "key+value"); } forEach(callback) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 1) { throw new TypeError("Failed to execute 'forEach' on 'iterable': 1 argument required, " + "but only 0 present."); } if (typeof callback !== "function") { throw new TypeError( "Failed to execute 'forEach' on 'iterable': The callback provided " + "as parameter 1 is not a function." ); } const thisArg = arguments[1]; let pairs = Array.from(this[impl]); let i = 0; while (i < pairs.length) { const [key, value] = pairs[i].map(utils.tryWrapperForImpl); callback.call(thisArg, value, key, this); pairs = Array.from(this[impl]); i++; } } } Object.defineProperties(URLSearchParams.prototype, { append: { enumerable: true }, delete: { enumerable: true }, get: { enumerable: true }, getAll: { enumerable: true }, has: { enumerable: true }, set: { enumerable: true }, sort: { enumerable: true }, toString: { enumerable: true }, keys: { enumerable: true }, values: { enumerable: true }, entries: { enumerable: true }, forEach: { enumerable: true }, [Symbol.toStringTag]: { value: "URLSearchParams", configurable: true }, [Symbol.iterator]: { value: URLSearchParams.prototype.entries, configurable: true, writable: true } }); if (globalObject[ctorRegistry] === undefined) { globalObject[ctorRegistry] = Object.create(null); } globalObject[ctorRegistry][interfaceName] = URLSearchParams; Object.defineProperty(globalObject, interfaceName, { configurable: true, writable: true, value: URLSearchParams }); }; const Impl = require("whatwg-url/lib/URLSearchParams-impl.js");
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/whatwg-url/lib/URLSearchParams.js
URLSearchParams.js
"use strict"; const conversions = require("webidl-conversions"); const utils = require("whatwg-url/lib/utils.js"); const impl = utils.implSymbol; const ctorRegistry = utils.ctorRegistrySymbol; const interfaceName = "URL"; /** * 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. */ exports._mixedIntoPredicates = []; exports.is = function is(obj) { if (obj) { if (utils.hasOwn(obj, impl) && obj[impl] instanceof Impl.implementation) { return true; } for (const isMixedInto of exports._mixedIntoPredicates) { if (isMixedInto(obj)) { return true; } } } return false; }; exports.isImpl = function isImpl(obj) { if (obj) { if (obj instanceof Impl.implementation) { return true; } const wrapper = utils.wrapperForImpl(obj); for (const isMixedInto of exports._mixedIntoPredicates) { if (isMixedInto(wrapper)) { return true; } } } return false; }; exports.convert = function convert(obj, { context = "The provided value" } = {}) { if (exports.is(obj)) { return utils.implForWrapper(obj); } throw new TypeError(`${context} is not of type 'URL'.`); }; exports.create = function create(globalObject, constructorArgs, privateData) { if (globalObject[ctorRegistry] === undefined) { throw new Error("Internal error: invalid global object"); } const ctor = globalObject[ctorRegistry]["URL"]; if (ctor === undefined) { throw new Error("Internal error: constructor URL is not installed on the passed global object"); } let obj = Object.create(ctor.prototype); obj = exports.setup(obj, globalObject, constructorArgs, privateData); return obj; }; exports.createImpl = function createImpl(globalObject, constructorArgs, privateData) { const obj = exports.create(globalObject, constructorArgs, privateData); return utils.implForWrapper(obj); }; exports._internalSetup = function _internalSetup(obj) {}; exports.setup = function setup(obj, globalObject, constructorArgs = [], privateData = {}) { privateData.wrapper = obj; exports._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; }; exports.install = function install(globalObject) { class URL { constructor(url) { if (arguments.length < 1) { throw new TypeError( "Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present." ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to construct 'URL': parameter 1" }); args.push(curArg); } { let curArg = arguments[1]; if (curArg !== undefined) { curArg = conversions["USVString"](curArg, { context: "Failed to construct 'URL': parameter 2" }); } args.push(curArg); } return exports.setup(Object.create(new.target.prototype), globalObject, args); } toJSON() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl].toJSON(); } get href() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl]["href"]; } set href(V) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } V = conversions["USVString"](V, { context: "Failed to set the 'href' property on 'URL': The provided value" }); this[impl]["href"] = V; } toString() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl]["href"]; } get origin() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl]["origin"]; } get protocol() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl]["protocol"]; } set protocol(V) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } V = conversions["USVString"](V, { context: "Failed to set the 'protocol' property on 'URL': The provided value" }); this[impl]["protocol"] = V; } get username() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl]["username"]; } set username(V) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } V = conversions["USVString"](V, { context: "Failed to set the 'username' property on 'URL': The provided value" }); this[impl]["username"] = V; } get password() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl]["password"]; } set password(V) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } V = conversions["USVString"](V, { context: "Failed to set the 'password' property on 'URL': The provided value" }); this[impl]["password"] = V; } get host() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl]["host"]; } set host(V) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } V = conversions["USVString"](V, { context: "Failed to set the 'host' property on 'URL': The provided value" }); this[impl]["host"] = V; } get hostname() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl]["hostname"]; } set hostname(V) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } V = conversions["USVString"](V, { context: "Failed to set the 'hostname' property on 'URL': The provided value" }); this[impl]["hostname"] = V; } get port() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl]["port"]; } set port(V) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } V = conversions["USVString"](V, { context: "Failed to set the 'port' property on 'URL': The provided value" }); this[impl]["port"] = V; } get pathname() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl]["pathname"]; } set pathname(V) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } V = conversions["USVString"](V, { context: "Failed to set the 'pathname' property on 'URL': The provided value" }); this[impl]["pathname"] = V; } get search() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl]["search"]; } set search(V) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } V = conversions["USVString"](V, { context: "Failed to set the 'search' property on 'URL': The provided value" }); this[impl]["search"] = V; } get searchParams() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return utils.getSameObject(this, "searchParams", () => { return utils.tryWrapperForImpl(this[impl]["searchParams"]); }); } get hash() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl]["hash"]; } set hash(V) { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } V = conversions["USVString"](V, { context: "Failed to set the 'hash' property on 'URL': The provided value" }); this[impl]["hash"] = V; } } Object.defineProperties(URL.prototype, { toJSON: { enumerable: true }, href: { enumerable: true }, toString: { enumerable: true }, origin: { enumerable: true }, protocol: { enumerable: true }, username: { enumerable: true }, password: { enumerable: true }, host: { enumerable: true }, hostname: { enumerable: true }, port: { enumerable: true }, pathname: { enumerable: true }, search: { enumerable: true }, searchParams: { enumerable: true }, hash: { enumerable: true }, [Symbol.toStringTag]: { value: "URL", configurable: true } }); if (globalObject[ctorRegistry] === undefined) { globalObject[ctorRegistry] = Object.create(null); } globalObject[ctorRegistry][interfaceName] = URL; Object.defineProperty(globalObject, interfaceName, { configurable: true, writable: true, value: URL }); }; const Impl = require("whatwg-url/lib/URL-impl.js");
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/whatwg-url/lib/URL.js
URL.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/whatwg-url/lib/utils.js
utils.js
# mime-db [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Node.js Version][node-image]][node-url] [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] This is a database of all mime types. It consists of a single, public JSON file and does not include any logic, allowing it to remain as un-opinionated as possible with an API. It aggregates data from the following sources: - http://www.iana.org/assignments/media-types/media-types.xhtml - http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types - http://hg.nginx.org/nginx/raw-file/default/conf/mime.types ## Installation ```bash npm install mime-db ``` ### Database Download If you're crazy enough to use this in the browser, you can just grab the JSON file using [jsDelivr](https://www.jsdelivr.com/). It is recommended to replace `master` with [a release tag](https://github.com/jshttp/mime-db/tags) as the JSON format may change in the future. ``` https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json ``` ## Usage <!-- eslint-disable no-unused-vars --> ```js var db = require('mime-db') // grab data on .js files var data = db['application/javascript'] ``` ## Data Structure The JSON file is a map lookup for lowercased mime types. Each mime type has the following properties: - `.source` - where the mime type is defined. If not set, it's probably a custom media type. - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml) - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types) - `.extensions[]` - known extensions associated with this mime type. - `.compressible` - whether a file of this type can be gzipped. - `.charset` - the default charset associated with this type, if any. If unknown, every property could be `undefined`. ## Contributing To edit the database, only make PRs against `src/custom.json` or `src/custom-suffix.json`. The `src/custom.json` file is a JSON object with the MIME type as the keys and the values being an object with the following keys: - `compressible` - leave out if you don't know, otherwise `true`/`false` to indicate whether the data represented by the type is typically compressible. - `extensions` - include an array of file extensions that are associated with the type. - `notes` - human-readable notes about the type, typically what the type is. - `sources` - include an array of URLs of where the MIME type and the associated extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); links to type aggregating sites and Wikipedia are _not acceptable_. To update the build, run `npm run build`. ### Adding Custom Media Types The best way to get new media types included in this library is to register them with the IANA. The community registration procedure is outlined in [RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types registered with the IANA are automatically pulled into this library. If that is not possible / feasible, they can be added directly here as a "custom" type. To do this, it is required to have a primary source that definitively lists the media type. If an extension is going to be listed as associateed with this media type, the source must definitively link the media type and extension as well. [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master [coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master [node-image]: https://badgen.net/npm/node/mime-db [node-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/mime-db [npm-url]: https://npmjs.org/package/mime-db [npm-version-image]: https://badgen.net/npm/v/mime-db [travis-image]: https://badgen.net/travis/jshttp/mime-db/master [travis-url]: https://travis-ci.org/jshttp/mime-db
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/mime-db/README.md
README.md
1.44.0 / 2020-04-22 =================== * Add charsets from IANA * Add extension `.cjs` to `application/node` * Add new upstream MIME types 1.43.0 / 2020-01-05 =================== * Add `application/x-keepass2` with extension `.kdbx` * Add extension `.mxmf` to `audio/mobile-xmf` * Add extensions from IANA for `application/*+xml` types * Add new upstream MIME types 1.42.0 / 2019-09-25 =================== * Add `image/vnd.ms-dds` with extension `.dds` * Add new upstream MIME types * Remove compressible from `multipart/mixed` 1.41.0 / 2019-08-30 =================== * Add new upstream MIME types * Add `application/toml` with extension `.toml` * Mark `font/ttf` as compressible 1.40.0 / 2019-04-20 =================== * Add extensions from IANA for `model/*` types * Add `text/mdx` with extension `.mdx` 1.39.0 / 2019-04-04 =================== * Add extensions `.siv` and `.sieve` to `application/sieve` * Add new upstream MIME types 1.38.0 / 2019-02-04 =================== * Add extension `.nq` to `application/n-quads` * Add extension `.nt` to `application/n-triples` * Add new upstream MIME types * Mark `text/less` as compressible 1.37.0 / 2018-10-19 =================== * Add extensions to HEIC image types * Add new upstream MIME types 1.36.0 / 2018-08-20 =================== * Add Apple file extensions from IANA * Add extensions from IANA for `image/*` types * Add new upstream MIME types 1.35.0 / 2018-07-15 =================== * Add extension `.owl` to `application/rdf+xml` * Add new upstream MIME types - Removes extension `.woff` from `application/font-woff` 1.34.0 / 2018-06-03 =================== * Add extension `.csl` to `application/vnd.citationstyles.style+xml` * Add extension `.es` to `application/ecmascript` * Add new upstream MIME types * Add `UTF-8` as default charset for `text/turtle` * Mark all XML-derived types as compressible 1.33.0 / 2018-02-15 =================== * Add extensions from IANA for `message/*` types * Add new upstream MIME types * Fix some incorrect OOXML types * Remove `application/font-woff2` 1.32.0 / 2017-11-29 =================== * Add new upstream MIME types * Update `text/hjson` to registered `application/hjson` * Add `text/shex` with extension `.shex` 1.31.0 / 2017-10-25 =================== * Add `application/raml+yaml` with extension `.raml` * Add `application/wasm` with extension `.wasm` * Add new `font` type from IANA * Add new upstream font extensions * Add new upstream MIME types * Add extensions for JPEG-2000 images 1.30.0 / 2017-08-27 =================== * Add `application/vnd.ms-outlook` * Add `application/x-arj` * Add extension `.mjs` to `application/javascript` * Add glTF types and extensions * Add new upstream MIME types * Add `text/x-org` * Add VirtualBox MIME types * Fix `source` records for `video/*` types that are IANA * Update `font/opentype` to registered `font/otf` 1.29.0 / 2017-07-10 =================== * Add `application/fido.trusted-apps+json` * Add extension `.wadl` to `application/vnd.sun.wadl+xml` * Add new upstream MIME types * Add `UTF-8` as default charset for `text/css` 1.28.0 / 2017-05-14 =================== * Add new upstream MIME types * Add extension `.gz` to `application/gzip` * Update extensions `.md` and `.markdown` to be `text/markdown` 1.27.0 / 2017-03-16 =================== * Add new upstream MIME types * Add `image/apng` with extension `.apng` 1.26.0 / 2017-01-14 =================== * Add new upstream MIME types * Add extension `.geojson` to `application/geo+json` 1.25.0 / 2016-11-11 =================== * Add new upstream MIME types 1.24.0 / 2016-09-18 =================== * Add `audio/mp3` * Add new upstream MIME types 1.23.0 / 2016-05-01 =================== * Add new upstream MIME types * Add extension `.3gpp` to `audio/3gpp` 1.22.0 / 2016-02-15 =================== * Add `text/slim` * Add extension `.rng` to `application/xml` * Add new upstream MIME types * Fix extension of `application/dash+xml` to be `.mpd` * Update primary extension to `.m4a` for `audio/mp4` 1.21.0 / 2016-01-06 =================== * Add Google document types * Add new upstream MIME types 1.20.0 / 2015-11-10 =================== * Add `text/x-suse-ymp` * Add new upstream MIME types 1.19.0 / 2015-09-17 =================== * Add `application/vnd.apple.pkpass` * Add new upstream MIME types 1.18.0 / 2015-09-03 =================== * Add new upstream MIME types 1.17.0 / 2015-08-13 =================== * Add `application/x-msdos-program` * Add `audio/g711-0` * Add `image/vnd.mozilla.apng` * Add extension `.exe` to `application/x-msdos-program` 1.16.0 / 2015-07-29 =================== * Add `application/vnd.uri-map` 1.15.0 / 2015-07-13 =================== * Add `application/x-httpd-php` 1.14.0 / 2015-06-25 =================== * Add `application/scim+json` * Add `application/vnd.3gpp.ussd+xml` * Add `application/vnd.biopax.rdf+xml` * Add `text/x-processing` 1.13.0 / 2015-06-07 =================== * Add nginx as a source * Add `application/x-cocoa` * Add `application/x-java-archive-diff` * Add `application/x-makeself` * Add `application/x-perl` * Add `application/x-pilot` * Add `application/x-redhat-package-manager` * Add `application/x-sea` * Add `audio/x-m4a` * Add `audio/x-realaudio` * Add `image/x-jng` * Add `text/mathml` 1.12.0 / 2015-06-05 =================== * Add `application/bdoc` * Add `application/vnd.hyperdrive+json` * Add `application/x-bdoc` * Add extension `.rtf` to `text/rtf` 1.11.0 / 2015-05-31 =================== * Add `audio/wav` * Add `audio/wave` * Add extension `.litcoffee` to `text/coffeescript` * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` 1.10.0 / 2015-05-19 =================== * Add `application/vnd.balsamiq.bmpr` * Add `application/vnd.microsoft.portable-executable` * Add `application/x-ns-proxy-autoconfig` 1.9.1 / 2015-04-19 ================== * Remove `.json` extension from `application/manifest+json` - This is causing bugs downstream 1.9.0 / 2015-04-19 ================== * Add `application/manifest+json` * Add `application/vnd.micro+json` * Add `image/vnd.zbrush.pcx` * Add `image/x-ms-bmp` 1.8.0 / 2015-03-13 ================== * Add `application/vnd.citationstyles.style+xml` * Add `application/vnd.fastcopy-disk-image` * Add `application/vnd.gov.sk.xmldatacontainer+xml` * Add extension `.jsonld` to `application/ld+json` 1.7.0 / 2015-02-08 ================== * Add `application/vnd.gerber` * Add `application/vnd.msa-disk-image` 1.6.1 / 2015-02-05 ================== * Community extensions ownership transferred from `node-mime` 1.6.0 / 2015-01-29 ================== * Add `application/jose` * Add `application/jose+json` * Add `application/json-seq` * Add `application/jwk+json` * Add `application/jwk-set+json` * Add `application/jwt` * Add `application/rdap+json` * Add `application/vnd.gov.sk.e-form+xml` * Add `application/vnd.ims.imsccv1p3` 1.5.0 / 2014-12-30 ================== * Add `application/vnd.oracle.resource+json` * Fix various invalid MIME type entries - `application/mbox+xml` - `application/oscp-response` - `application/vwg-multiplexed` - `audio/g721` 1.4.0 / 2014-12-21 ================== * Add `application/vnd.ims.imsccv1p2` * Fix various invalid MIME type entries - `application/vnd-acucobol` - `application/vnd-curl` - `application/vnd-dart` - `application/vnd-dxr` - `application/vnd-fdf` - `application/vnd-mif` - `application/vnd-sema` - `application/vnd-wap-wmlc` - `application/vnd.adobe.flash-movie` - `application/vnd.dece-zip` - `application/vnd.dvb_service` - `application/vnd.micrografx-igx` - `application/vnd.sealed-doc` - `application/vnd.sealed-eml` - `application/vnd.sealed-mht` - `application/vnd.sealed-ppt` - `application/vnd.sealed-tiff` - `application/vnd.sealed-xls` - `application/vnd.sealedmedia.softseal-html` - `application/vnd.sealedmedia.softseal-pdf` - `application/vnd.wap-slc` - `application/vnd.wap-wbxml` - `audio/vnd.sealedmedia.softseal-mpeg` - `image/vnd-djvu` - `image/vnd-svf` - `image/vnd-wap-wbmp` - `image/vnd.sealed-png` - `image/vnd.sealedmedia.softseal-gif` - `image/vnd.sealedmedia.softseal-jpg` - `model/vnd-dwf` - `model/vnd.parasolid.transmit-binary` - `model/vnd.parasolid.transmit-text` - `text/vnd-a` - `text/vnd-curl` - `text/vnd.wap-wml` * Remove example template MIME types - `application/example` - `audio/example` - `image/example` - `message/example` - `model/example` - `multipart/example` - `text/example` - `video/example` 1.3.1 / 2014-12-16 ================== * Fix missing extensions - `application/json5` - `text/hjson` 1.3.0 / 2014-12-07 ================== * Add `application/a2l` * Add `application/aml` * Add `application/atfx` * Add `application/atxml` * Add `application/cdfx+xml` * Add `application/dii` * Add `application/json5` * Add `application/lxf` * Add `application/mf4` * Add `application/vnd.apache.thrift.compact` * Add `application/vnd.apache.thrift.json` * Add `application/vnd.coffeescript` * Add `application/vnd.enphase.envoy` * Add `application/vnd.ims.imsccv1p1` * Add `text/csv-schema` * Add `text/hjson` * Add `text/markdown` * Add `text/yaml` 1.2.0 / 2014-11-09 ================== * Add `application/cea` * Add `application/dit` * Add `application/vnd.gov.sk.e-form+zip` * Add `application/vnd.tmd.mediaflex.api+xml` * Type `application/epub+zip` is now IANA-registered 1.1.2 / 2014-10-23 ================== * Rebuild database for `application/x-www-form-urlencoded` change 1.1.1 / 2014-10-20 ================== * Mark `application/x-www-form-urlencoded` as compressible. 1.1.0 / 2014-09-28 ================== * Add `application/font-woff2` 1.0.3 / 2014-09-25 ================== * Fix engine requirement in package 1.0.2 / 2014-09-25 ================== * Add `application/coap-group+json` * Add `application/dcd` * Add `application/vnd.apache.thrift.binary` * Add `image/vnd.tencent.tap` * Mark all JSON-derived types as compressible * Update `text/vtt` data 1.0.1 / 2014-08-30 ================== * Fix extension ordering 1.0.0 / 2014-08-30 ================== * Add `application/atf` * Add `application/merge-patch+json` * Add `multipart/x-mixed-replace` * Add `source: 'apache'` metadata * Add `source: 'iana'` metadata * Remove badly-assumed charset data
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/mime-db/HISTORY.md
HISTORY.md
### esutils [![Build Status](https://secure.travis-ci.org/estools/esutils.svg)](http://travis-ci.org/estools/esutils) esutils ([esutils](http://github.com/estools/esutils)) is utility box for ECMAScript language tools. ### API ### ast #### ast.isExpression(node) Returns true if `node` is an Expression as defined in ECMA262 edition 5.1 section [11](https://es5.github.io/#x11). #### ast.isStatement(node) Returns true if `node` is a Statement as defined in ECMA262 edition 5.1 section [12](https://es5.github.io/#x12). #### ast.isIterationStatement(node) Returns true if `node` is an IterationStatement as defined in ECMA262 edition 5.1 section [12.6](https://es5.github.io/#x12.6). #### ast.isSourceElement(node) Returns true if `node` is a SourceElement as defined in ECMA262 edition 5.1 section [14](https://es5.github.io/#x14). #### ast.trailingStatement(node) Returns `Statement?` if `node` has trailing `Statement`. ```js if (cond) consequent; ``` When taking this `IfStatement`, returns `consequent;` statement. #### ast.isProblematicIfStatement(node) Returns true if `node` is a problematic IfStatement. If `node` is a problematic `IfStatement`, `node` cannot be represented as an one on one JavaScript code. ```js { type: 'IfStatement', consequent: { type: 'WithStatement', body: { type: 'IfStatement', consequent: {type: 'EmptyStatement'} } }, alternate: {type: 'EmptyStatement'} } ``` The above node cannot be represented as a JavaScript code, since the top level `else` alternate belongs to an inner `IfStatement`. ### code #### code.isDecimalDigit(code) Return true if provided code is decimal digit. #### code.isHexDigit(code) Return true if provided code is hexadecimal digit. #### code.isOctalDigit(code) Return true if provided code is octal digit. #### code.isWhiteSpace(code) Return true if provided code is white space. White space characters are formally defined in ECMA262. #### code.isLineTerminator(code) Return true if provided code is line terminator. Line terminator characters are formally defined in ECMA262. #### code.isIdentifierStart(code) Return true if provided code can be the first character of ECMA262 Identifier. They are formally defined in ECMA262. #### code.isIdentifierPart(code) Return true if provided code can be the trailing character of ECMA262 Identifier. They are formally defined in ECMA262. ### keyword #### keyword.isKeywordES5(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 sections [7.6.1.1](http://es5.github.io/#x7.6.1.1) and [7.6.1.2](http://es5.github.io/#x7.6.1.2), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isKeywordES6(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 sections [11.6.2.1](http://ecma-international.org/ecma-262/6.0/#sec-keywords) and [11.6.2.2](http://ecma-international.org/ecma-262/6.0/#sec-future-reserved-words), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isReservedWordES5(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 section [7.6.1](http://es5.github.io/#x7.6.1). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isReservedWordES6(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 section [11.6.2](http://ecma-international.org/ecma-262/6.0/#sec-reserved-words). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isRestrictedWord(id) Returns `true` if provided identifier string is one of `eval` or `arguments`. They are restricted in strict mode code throughout ECMA262 edition 5.1 and in ECMA262 edition 6 section [12.1.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers-static-semantics-early-errors). #### keyword.isIdentifierNameES5(id) Return true if provided identifier string is an IdentifierName as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). #### keyword.isIdentifierNameES6(id) Return true if provided identifier string is an IdentifierName as specified in ECMA262 edition 6 section [11.6](http://ecma-international.org/ecma-262/6.0/#sec-names-and-keywords). #### keyword.isIdentifierES5(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. #### keyword.isIdentifierES6(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 6 section [12.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. ### License Copyright (C) 2013 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 <COPYRIGHT HOLDER> 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/esutils/README.md
README.md
(function () { 'use strict'; var code = require('esutils/lib/code'); function isStrictModeReservedWordES6(id) { switch (id) { case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'let': return true; default: return false; } } function isKeywordES5(id, strict) { // yield should not be treated as keyword under non-strict mode. if (!strict && id === 'yield') { return false; } return isKeywordES6(id, strict); } function isKeywordES6(id, strict) { if (strict && isStrictModeReservedWordES6(id)) { return true; } switch (id.length) { case 2: return (id === 'if') || (id === 'in') || (id === 'do'); case 3: return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try'); case 4: return (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with') || (id === 'enum'); case 5: return (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw') || (id === 'const') || (id === 'yield') || (id === 'class') || (id === 'super'); case 6: return (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') || (id === 'import'); case 7: return (id === 'default') || (id === 'finally') || (id === 'extends'); case 8: return (id === 'function') || (id === 'continue') || (id === 'debugger'); case 10: return (id === 'instanceof'); default: return false; } } function isReservedWordES5(id, strict) { return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); } function isReservedWordES6(id, strict) { return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); } function isRestrictedWord(id) { return id === 'eval' || id === 'arguments'; } function isIdentifierNameES5(id) { var i, iz, ch; if (id.length === 0) { return false; } ch = id.charCodeAt(0); if (!code.isIdentifierStartES5(ch)) { return false; } for (i = 1, iz = id.length; i < iz; ++i) { ch = id.charCodeAt(i); if (!code.isIdentifierPartES5(ch)) { return false; } } return true; } function decodeUtf16(lead, trail) { return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; } function isIdentifierNameES6(id) { var i, iz, ch, lowCh, check; if (id.length === 0) { return false; } check = code.isIdentifierStartES6; for (i = 0, iz = id.length; i < iz; ++i) { ch = id.charCodeAt(i); if (0xD800 <= ch && ch <= 0xDBFF) { ++i; if (i >= iz) { return false; } lowCh = id.charCodeAt(i); if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { return false; } ch = decodeUtf16(ch, lowCh); } if (!check(ch)) { return false; } check = code.isIdentifierPartES6; } return true; } function isIdentifierES5(id, strict) { return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); } function isIdentifierES6(id, strict) { return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); } module.exports = { isKeywordES5: isKeywordES5, isKeywordES6: isKeywordES6, isReservedWordES5: isReservedWordES5, isReservedWordES6: isReservedWordES6, isRestrictedWord: isRestrictedWord, isIdentifierNameES5: isIdentifierNameES5, isIdentifierNameES6: isIdentifierNameES6, isIdentifierES5: isIdentifierES5, isIdentifierES6: isIdentifierES6 }; }()); /* vim: set sw=4 ts=4 et tw=80 : */
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/esutils/lib/keyword.js
keyword.js
(function () { 'use strict'; function isExpression(node) { if (node == null) { return false; } switch (node.type) { case 'ArrayExpression': case 'AssignmentExpression': case 'BinaryExpression': case 'CallExpression': case 'ConditionalExpression': case 'FunctionExpression': case 'Identifier': case 'Literal': case 'LogicalExpression': case 'MemberExpression': case 'NewExpression': case 'ObjectExpression': case 'SequenceExpression': case 'ThisExpression': case 'UnaryExpression': case 'UpdateExpression': return true; } return false; } function isIterationStatement(node) { if (node == null) { return false; } switch (node.type) { case 'DoWhileStatement': case 'ForInStatement': case 'ForStatement': case 'WhileStatement': return true; } return false; } function isStatement(node) { if (node == null) { return false; } switch (node.type) { case 'BlockStatement': case 'BreakStatement': case 'ContinueStatement': case 'DebuggerStatement': case 'DoWhileStatement': case 'EmptyStatement': case 'ExpressionStatement': case 'ForInStatement': case 'ForStatement': case 'IfStatement': case 'LabeledStatement': case 'ReturnStatement': case 'SwitchStatement': case 'ThrowStatement': case 'TryStatement': case 'VariableDeclaration': case 'WhileStatement': case 'WithStatement': return true; } return false; } function isSourceElement(node) { return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; } function trailingStatement(node) { switch (node.type) { case 'IfStatement': if (node.alternate != null) { return node.alternate; } return node.consequent; case 'LabeledStatement': case 'ForStatement': case 'ForInStatement': case 'WhileStatement': case 'WithStatement': return node.body; } return null; } function isProblematicIfStatement(node) { var current; if (node.type !== 'IfStatement') { return false; } if (node.alternate == null) { return false; } current = node.consequent; do { if (current.type === 'IfStatement') { if (current.alternate == null) { return true; } } current = trailingStatement(current); } while (current); return false; } module.exports = { isExpression: isExpression, isStatement: isStatement, isIterationStatement: isIterationStatement, isSourceElement: isSourceElement, isProblematicIfStatement: isProblematicIfStatement, trailingStatement: trailingStatement }; }()); /* vim: set sw=4 ts=4 et tw=80 : */
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/esutils/lib/ast.js
ast.js
(function () { 'use strict'; var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`. ES5Regex = { // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart: NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/, // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart: NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/ }; ES6Regex = { // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart: NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart: NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ }; function isDecimalDigit(ch) { return 0x30 <= ch && ch <= 0x39; // 0..9 } function isHexDigit(ch) { return 0x30 <= ch && ch <= 0x39 || // 0..9 0x61 <= ch && ch <= 0x66 || // a..f 0x41 <= ch && ch <= 0x46; // A..F } function isOctalDigit(ch) { return ch >= 0x30 && ch <= 0x37; // 0..7 } // 7.2 White Space NON_ASCII_WHITESPACES = [ 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF ]; function isWhiteSpace(ch) { return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0; } // 7.3 Line Terminators function isLineTerminator(ch) { return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029; } // 7.6 Identifier Names and Identifiers function fromCodePoint(cp) { if (cp <= 0xFFFF) { return String.fromCharCode(cp); } var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); var cu2 = String.fromCharCode(((cp - 0x10000) % 0x400) + 0xDC00); return cu1 + cu2; } IDENTIFIER_START = new Array(0x80); for(ch = 0; ch < 0x80; ++ch) { IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z ch >= 0x41 && ch <= 0x5A || // A..Z ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) } IDENTIFIER_PART = new Array(0x80); for(ch = 0; ch < 0x80; ++ch) { IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z ch >= 0x41 && ch <= 0x5A || // A..Z ch >= 0x30 && ch <= 0x39 || // 0..9 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) } function isIdentifierStartES5(ch) { return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); } function isIdentifierPartES5(ch) { return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); } function isIdentifierStartES6(ch) { return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); } function isIdentifierPartES6(ch) { return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); } module.exports = { isDecimalDigit: isDecimalDigit, isHexDigit: isHexDigit, isOctalDigit: isOctalDigit, isWhiteSpace: isWhiteSpace, isLineTerminator: isLineTerminator, isIdentifierStartES5: isIdentifierStartES5, isIdentifierPartES5: isIdentifierPartES5, isIdentifierStartES6: isIdentifierStartES6, isIdentifierPartES6: isIdentifierPartES6 }; }()); /* vim: set sw=4 ts=4 et tw=80 : */
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/esutils/lib/code.js
code.js
// Requires ec.js, jsbn.js, and jsbn2.js var BigInteger = require('jsbn').BigInteger var ECCurveFp = require('ecc-jsbn/lib/ec.js').ECCurveFp // ---------------- // X9ECParameters // constructor function X9ECParameters(curve,g,n,h) { this.curve = curve; this.g = g; this.n = n; this.h = h; } function x9getCurve() { return this.curve; } function x9getG() { return this.g; } function x9getN() { return this.n; } function x9getH() { return this.h; } X9ECParameters.prototype.getCurve = x9getCurve; X9ECParameters.prototype.getG = x9getG; X9ECParameters.prototype.getN = x9getN; X9ECParameters.prototype.getH = x9getH; // ---------------- // SECNamedCurves function fromHex(s) { return new BigInteger(s, 16); } function secp128r1() { // p = 2^128 - 2^97 - 1 var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"); var b = fromHex("E87579C11079F43DD824993C2CEE5ED3"); //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679"); var n = fromHex("FFFFFFFE0000000075A30D1B9038A115"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "161FF7528B899B2D0C28607CA52C5B86" + "CF5AC8395BAFEB13C02DA292DDED7A83"); return new X9ECParameters(curve, G, n, h); } function secp160k1() { // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); var a = BigInteger.ZERO; var b = fromHex("7"); //byte[] S = null; var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB" + "938CF935318FDCED6BC28286531733C3F03C4FEE"); return new X9ECParameters(curve, G, n, h); } function secp160r1() { // p = 2^160 - 2^31 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"); var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"); var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"); //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345"); var n = fromHex("0100000000000000000001F4C8F927AED3CA752257"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "4A96B5688EF573284664698968C38BB913CBFC82" + "23A628553168947D59DCC912042351377AC5FB32"); return new X9ECParameters(curve, G, n, h); } function secp192k1() { // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"); var a = BigInteger.ZERO; var b = fromHex("3"); //byte[] S = null; var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D" + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"); return new X9ECParameters(curve, G, n, h); } function secp192r1() { // p = 2^192 - 2^64 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"); var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"); var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"); //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5"); var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012" + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); return new X9ECParameters(curve, G, n, h); } function secp224r1() { // p = 2^224 - 2^96 + 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"); var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"); var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"); //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21" + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"); return new X9ECParameters(curve, G, n, h); } function secp256r1() { // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1 var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"); var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"); var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"); //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90"); var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296" + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"); return new X9ECParameters(curve, G, n, h); } // TODO: make this into a proper hashtable function getSECCurveByName(name) { if(name == "secp128r1") return secp128r1(); if(name == "secp160k1") return secp160k1(); if(name == "secp160r1") return secp160r1(); if(name == "secp192k1") return secp192k1(); if(name == "secp192r1") return secp192r1(); if(name == "secp224r1") return secp224r1(); if(name == "secp256r1") return secp256r1(); return null; } module.exports = { "secp128r1":secp128r1, "secp160k1":secp160k1, "secp160r1":secp160r1, "secp192k1":secp192k1, "secp192r1":secp192r1, "secp224r1":secp224r1, "secp256r1":secp256r1 }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ecc-jsbn/lib/sec.js
sec.js
// Requires jsbn.js and jsbn2.js var BigInteger = require('jsbn').BigInteger var Barrett = BigInteger.prototype.Barrett // ---------------- // ECFieldElementFp // constructor function ECFieldElementFp(q,x) { this.x = x; // TODO if(x.compareTo(q) >= 0) error this.q = q; } function feFpEquals(other) { if(other == this) return true; return (this.q.equals(other.q) && this.x.equals(other.x)); } function feFpToBigInteger() { return this.x; } function feFpNegate() { return new ECFieldElementFp(this.q, this.x.negate().mod(this.q)); } function feFpAdd(b) { return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); } function feFpSubtract(b) { return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); } function feFpMultiply(b) { return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); } function feFpSquare() { return new ECFieldElementFp(this.q, this.x.square().mod(this.q)); } function feFpDivide(b) { return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)); } ECFieldElementFp.prototype.equals = feFpEquals; ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger; ECFieldElementFp.prototype.negate = feFpNegate; ECFieldElementFp.prototype.add = feFpAdd; ECFieldElementFp.prototype.subtract = feFpSubtract; ECFieldElementFp.prototype.multiply = feFpMultiply; ECFieldElementFp.prototype.square = feFpSquare; ECFieldElementFp.prototype.divide = feFpDivide; // ---------------- // ECPointFp // constructor function ECPointFp(curve,x,y,z) { this.curve = curve; this.x = x; this.y = y; // Projective coordinates: either zinv == null or z * zinv == 1 // z and zinv are just BigIntegers, not fieldElements if(z == null) { this.z = BigInteger.ONE; } else { this.z = z; } this.zinv = null; //TODO: compression flag } function pointFpGetX() { if(this.zinv == null) { this.zinv = this.z.modInverse(this.curve.q); } var r = this.x.toBigInteger().multiply(this.zinv); this.curve.reduce(r); return this.curve.fromBigInteger(r); } function pointFpGetY() { if(this.zinv == null) { this.zinv = this.z.modInverse(this.curve.q); } var r = this.y.toBigInteger().multiply(this.zinv); this.curve.reduce(r); return this.curve.fromBigInteger(r); } function pointFpEquals(other) { if(other == this) return true; if(this.isInfinity()) return other.isInfinity(); if(other.isInfinity()) return this.isInfinity(); var u, v; // u = Y2 * Z1 - Y1 * Z2 u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q); if(!u.equals(BigInteger.ZERO)) return false; // v = X2 * Z1 - X1 * Z2 v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q); return v.equals(BigInteger.ZERO); } function pointFpIsInfinity() { if((this.x == null) && (this.y == null)) return true; return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); } function pointFpNegate() { return new ECPointFp(this.curve, this.x, this.y.negate(), this.z); } function pointFpAdd(b) { if(this.isInfinity()) return b; if(b.isInfinity()) return this; // u = Y2 * Z1 - Y1 * Z2 var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q); // v = X2 * Z1 - X1 * Z2 var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q); if(BigInteger.ZERO.equals(v)) { if(BigInteger.ZERO.equals(u)) { return this.twice(); // this == b, so double } return this.curve.getInfinity(); // this = -b, so infinity } var THREE = new BigInteger("3"); var x1 = this.x.toBigInteger(); var y1 = this.y.toBigInteger(); var x2 = b.x.toBigInteger(); var y2 = b.y.toBigInteger(); var v2 = v.square(); var v3 = v2.multiply(v); var x1v2 = x1.multiply(v2); var zu2 = u.square().multiply(this.z); // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q); // z3 = v^3 * z1 * z2 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); } function pointFpTwice() { if(this.isInfinity()) return this; if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); // TODO: optimized handling of constants var THREE = new BigInteger("3"); var x1 = this.x.toBigInteger(); var y1 = this.y.toBigInteger(); var y1z1 = y1.multiply(this.z); var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); var a = this.curve.a.toBigInteger(); // w = 3 * x1^2 + a * z1^2 var w = x1.square().multiply(THREE); if(!BigInteger.ZERO.equals(a)) { w = w.add(this.z.square().multiply(a)); } w = w.mod(this.curve.q); //this.curve.reduce(w); // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q); // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); // z3 = 8 * (y1 * z1)^3 var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); } // Simple NAF (Non-Adjacent Form) multiplication algorithm // TODO: modularize the multiplication algorithm function pointFpMultiply(k) { if(this.isInfinity()) return this; if(k.signum() == 0) return this.curve.getInfinity(); var e = k; var h = e.multiply(new BigInteger("3")); var neg = this.negate(); var R = this; var i; for(i = h.bitLength() - 2; i > 0; --i) { R = R.twice(); var hBit = h.testBit(i); var eBit = e.testBit(i); if (hBit != eBit) { R = R.add(hBit ? this : neg); } } return R; } // Compute this*j + x*k (simultaneous multiplication) function pointFpMultiplyTwo(j,x,k) { var i; if(j.bitLength() > k.bitLength()) i = j.bitLength() - 1; else i = k.bitLength() - 1; var R = this.curve.getInfinity(); var both = this.add(x); while(i >= 0) { R = R.twice(); if(j.testBit(i)) { if(k.testBit(i)) { R = R.add(both); } else { R = R.add(this); } } else { if(k.testBit(i)) { R = R.add(x); } } --i; } return R; } ECPointFp.prototype.getX = pointFpGetX; ECPointFp.prototype.getY = pointFpGetY; ECPointFp.prototype.equals = pointFpEquals; ECPointFp.prototype.isInfinity = pointFpIsInfinity; ECPointFp.prototype.negate = pointFpNegate; ECPointFp.prototype.add = pointFpAdd; ECPointFp.prototype.twice = pointFpTwice; ECPointFp.prototype.multiply = pointFpMultiply; ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo; // ---------------- // ECCurveFp // constructor function ECCurveFp(q,a,b) { this.q = q; this.a = this.fromBigInteger(a); this.b = this.fromBigInteger(b); this.infinity = new ECPointFp(this, null, null); this.reducer = new Barrett(this.q); } function curveFpGetQ() { return this.q; } function curveFpGetA() { return this.a; } function curveFpGetB() { return this.b; } function curveFpEquals(other) { if(other == this) return true; return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); } function curveFpGetInfinity() { return this.infinity; } function curveFpFromBigInteger(x) { return new ECFieldElementFp(this.q, x); } function curveReduce(x) { this.reducer.reduce(x); } // for now, work with hex strings because they're easier in JS function curveFpDecodePointHex(s) { switch(parseInt(s.substr(0,2), 16)) { // first byte case 0: return this.infinity; case 2: case 3: // point compression not supported yet return null; case 4: case 6: case 7: var len = (s.length - 2) / 2; var xHex = s.substr(2, len); var yHex = s.substr(len+2, len); return new ECPointFp(this, this.fromBigInteger(new BigInteger(xHex, 16)), this.fromBigInteger(new BigInteger(yHex, 16))); default: // unsupported return null; } } function curveFpEncodePointHex(p) { if (p.isInfinity()) return "00"; var xHex = p.getX().toBigInteger().toString(16); var yHex = p.getY().toBigInteger().toString(16); var oLen = this.getQ().toString(16).length; if ((oLen % 2) != 0) oLen++; while (xHex.length < oLen) { xHex = "0" + xHex; } while (yHex.length < oLen) { yHex = "0" + yHex; } return "04" + xHex + yHex; } ECCurveFp.prototype.getQ = curveFpGetQ; ECCurveFp.prototype.getA = curveFpGetA; ECCurveFp.prototype.getB = curveFpGetB; ECCurveFp.prototype.equals = curveFpEquals; ECCurveFp.prototype.getInfinity = curveFpGetInfinity; ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger; ECCurveFp.prototype.reduce = curveReduce; //ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex; ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex; // from: https://github.com/kaielvin/jsbn-ec-point-compression ECCurveFp.prototype.decodePointHex = function(s) { var yIsEven; switch(parseInt(s.substr(0,2), 16)) { // first byte case 0: return this.infinity; case 2: yIsEven = false; case 3: if(yIsEven == undefined) yIsEven = true; var len = s.length - 2; var xHex = s.substr(2, len); var x = this.fromBigInteger(new BigInteger(xHex,16)); var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); var beta = alpha.sqrt(); if (beta == null) throw "Invalid point compression"; var betaValue = beta.toBigInteger(); if (betaValue.testBit(0) != yIsEven) { // Use the other root beta = this.fromBigInteger(this.getQ().subtract(betaValue)); } return new ECPointFp(this,x,beta); case 4: case 6: case 7: var len = (s.length - 2) / 2; var xHex = s.substr(2, len); var yHex = s.substr(len+2, len); return new ECPointFp(this, this.fromBigInteger(new BigInteger(xHex, 16)), this.fromBigInteger(new BigInteger(yHex, 16))); default: // unsupported return null; } } ECCurveFp.prototype.encodeCompressedPointHex = function(p) { if (p.isInfinity()) return "00"; var xHex = p.getX().toBigInteger().toString(16); var oLen = this.getQ().toString(16).length; if ((oLen % 2) != 0) oLen++; while (xHex.length < oLen) xHex = "0" + xHex; var yPrefix; if(p.getY().toBigInteger().isEven()) yPrefix = "02"; else yPrefix = "03"; return yPrefix + xHex; } ECFieldElementFp.prototype.getR = function() { if(this.r != undefined) return this.r; this.r = null; var bitLength = this.q.bitLength(); if (bitLength > 128) { var firstWord = this.q.shiftRight(bitLength - 64); if (firstWord.intValue() == -1) { this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q); } } return this.r; } ECFieldElementFp.prototype.modMult = function(x1,x2) { return this.modReduce(x1.multiply(x2)); } ECFieldElementFp.prototype.modReduce = function(x) { if (this.getR() != null) { var qLen = q.bitLength(); while (x.bitLength() > (qLen + 1)) { var u = x.shiftRight(qLen); var v = x.subtract(u.shiftLeft(qLen)); if (!this.getR().equals(BigInteger.ONE)) { u = u.multiply(this.getR()); } x = u.add(v); } while (x.compareTo(q) >= 0) { x = x.subtract(q); } } else { x = x.mod(q); } return x; } ECFieldElementFp.prototype.sqrt = function() { if (!this.q.testBit(0)) throw "unsupported"; // p mod 4 == 3 if (this.q.testBit(1)) { var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q)); return z.square().equals(this) ? z : null; } // p mod 4 == 1 var qMinusOne = this.q.subtract(BigInteger.ONE); var legendreExponent = qMinusOne.shiftRight(1); if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) { return null; } var u = qMinusOne.shiftRight(2); var k = u.shiftLeft(1).add(BigInteger.ONE); var Q = this.x; var fourQ = modDouble(modDouble(Q)); var U, V; do { var P; do { P = new BigInteger(this.q.bitLength(), new SecureRandom()); } while (P.compareTo(this.q) >= 0 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne))); var result = this.lucasSequence(P, Q, k); U = result[0]; V = result[1]; if (this.modMult(V, V).equals(fourQ)) { // Integer division by 2, mod q if (V.testBit(0)) { V = V.add(q); } V = V.shiftRight(1); return new ECFieldElementFp(q,V); } } while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); return null; } ECFieldElementFp.prototype.lucasSequence = function(P,Q,k) { var n = k.bitLength(); var s = k.getLowestSetBit(); var Uh = BigInteger.ONE; var Vl = BigInteger.TWO; var Vh = P; var Ql = BigInteger.ONE; var Qh = BigInteger.ONE; for (var j = n - 1; j >= s + 1; --j) { Ql = this.modMult(Ql, Qh); if (k.testBit(j)) { Qh = this.modMult(Ql, Q); Uh = this.modMult(Uh, Vh); Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1))); } else { Qh = Ql; Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); } } Ql = this.modMult(Ql, Qh); Qh = this.modMult(Ql, Q); Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Ql = this.modMult(Ql, Qh); for (var j = 1; j <= s; ++j) { Uh = this.modMult(Uh, Vl); Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); Ql = this.modMult(Ql, Ql); } return [ Uh, Vl ]; } var exports = { ECCurveFp: ECCurveFp, ECPointFp: ECPointFp, ECFieldElementFp: ECFieldElementFp } module.exports = exports
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ecc-jsbn/lib/ec.js
ec.js
## Pure JS character encoding conversion [![Build Status](https://travis-ci.org/ashtuchkin/iconv-lite.svg?branch=master)](https://travis-ci.org/ashtuchkin/iconv-lite) * Doesn't need native code compilation. Works on Windows and in sandboxed environments like [Cloud9](http://c9.io). * Used in popular projects like [Express.js (body_parser)](https://github.com/expressjs/body-parser), [Grunt](http://gruntjs.com/), [Nodemailer](http://www.nodemailer.com/), [Yeoman](http://yeoman.io/) and others. * Faster than [node-iconv](https://github.com/bnoordhuis/node-iconv) (see below for performance comparison). * Intuitive encode/decode API * Streaming support for Node v0.10+ * [Deprecated] Can extend Node.js primitives (buffers, streams) to support all iconv-lite encodings. * In-browser usage via [Browserify](https://github.com/substack/node-browserify) (~180k gzip compressed with Buffer shim included). * Typescript [type definition file](https://github.com/ashtuchkin/iconv-lite/blob/master/lib/index.d.ts) included. * React Native is supported (need to explicitly `npm install` two more modules: `buffer` and `stream`). * License: MIT. [![NPM Stats](https://nodei.co/npm/iconv-lite.png?downloads=true&downloadRank=true)](https://npmjs.org/packages/iconv-lite/) ## Usage ### Basic API ```javascript var iconv = require('iconv-lite'); // Convert from an encoded buffer to js string. str = iconv.decode(Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251'); // Convert from js string to an encoded buffer. buf = iconv.encode("Sample input string", 'win1251'); // Check if encoding is supported iconv.encodingExists("us-ascii") ``` ### Streaming API (Node v0.10+) ```javascript // Decode stream (from binary stream to js strings) http.createServer(function(req, res) { var converterStream = iconv.decodeStream('win1251'); req.pipe(converterStream); converterStream.on('data', function(str) { console.log(str); // Do something with decoded strings, chunk-by-chunk. }); }); // Convert encoding streaming example fs.createReadStream('file-in-win1251.txt') .pipe(iconv.decodeStream('win1251')) .pipe(iconv.encodeStream('ucs2')) .pipe(fs.createWriteStream('file-in-ucs2.txt')); // Sugar: all encode/decode streams have .collect(cb) method to accumulate data. http.createServer(function(req, res) { req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) { assert(typeof body == 'string'); console.log(body); // full request body string }); }); ``` ### [Deprecated] Extend Node.js own encodings > NOTE: This doesn't work on latest Node versions. See [details](https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility). ```javascript // After this call all Node basic primitives will understand iconv-lite encodings. iconv.extendNodeEncodings(); // Examples: buf = new Buffer(str, 'win1251'); buf.write(str, 'gbk'); str = buf.toString('latin1'); assert(Buffer.isEncoding('iso-8859-15')); Buffer.byteLength(str, 'us-ascii'); http.createServer(function(req, res) { req.setEncoding('big5'); req.collect(function(err, body) { console.log(body); }); }); fs.createReadStream("file.txt", "shift_jis"); // External modules are also supported (if they use Node primitives, which they probably do). request = require('request'); request({ url: "http://github.com/", encoding: "cp932" }); // To remove extensions iconv.undoExtendNodeEncodings(); ``` ## Supported encodings * All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex. * Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap. * All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. Aliases like 'latin1', 'us-ascii' also supported. * All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2312, GBK, GB18030, Big5, Shift_JIS, EUC-JP. See [all supported encodings on wiki](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings). Most singlebyte encodings are generated automatically from [node-iconv](https://github.com/bnoordhuis/node-iconv). Thank you Ben Noordhuis and libiconv authors! Multibyte encodings are generated from [Unicode.org mappings](http://www.unicode.org/Public/MAPPINGS/) and [WHATWG Encoding Standard mappings](http://encoding.spec.whatwg.org/). Thank you, respective authors! ## Encoding/decoding speed Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0). Note: your results may vary, so please always check on your hardware. operation [email protected] [email protected] ---------------------------------------------------------- encode('win1251') ~96 Mb/s ~320 Mb/s decode('win1251') ~95 Mb/s ~246 Mb/s ## BOM handling * Decoding: BOM is stripped by default, unless overridden by passing `stripBOM: false` in options (f.ex. `iconv.decode(buf, enc, {stripBOM: false})`). A callback might also be given as a `stripBOM` parameter - it'll be called if BOM character was actually found. * If you want to detect UTF-8 BOM when decoding other encodings, use [node-autodetect-decoder-stream](https://github.com/danielgindi/node-autodetect-decoder-stream) module. * Encoding: No BOM added, unless overridden by `addBOM: true` option. ## UTF-16 Encodings This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be smart about endianness in the following ways: * Decoding: uses BOM and 'spaces heuristic' to determine input endianness. Default is UTF-16LE, but can be overridden with `defaultEncoding: 'utf-16be'` option. Strips BOM unless `stripBOM: false`. * Encoding: uses UTF-16LE and writes BOM by default. Use `addBOM: false` to override. ## Other notes When decoding, be sure to supply a Buffer to decode() method, otherwise [bad things usually happen](https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding). Untranslatable characters are set to � or ?. No transliteration is currently supported. Node versions 0.10.31 and 0.11.13 are buggy, don't use them (see #65, #77). ## Testing ```bash $ git clone [email protected]:ashtuchkin/iconv-lite.git $ cd iconv-lite $ npm install $ npm test $ # To view performance: $ node test/performance.js $ # To view test coverage: $ npm run coverage $ open coverage/lcov-report/index.html ```
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/iconv-lite/README.md
README.md
# 0.4.24 / 2018-08-22 * Added MIK encoding (#196, by @Ivan-Kalatchev) # 0.4.23 / 2018-05-07 * Fix deprecation warning in Node v10 due to the last usage of `new Buffer` (#185, by @felixbuenemann) * Switched from NodeBuffer to Buffer in typings (#155 by @felixfbecker, #186 by @larssn) # 0.4.22 / 2018-05-05 * Use older semver style for dependencies to be compatible with Node version 0.10 (#182, by @dougwilson) * Fix tests to accomodate fixes in Node v10 (#182, by @dougwilson) # 0.4.21 / 2018-04-06 * Fix encoding canonicalization (#156) * Fix the paths in the "browser" field in package.json (#174 by @LMLB) * Removed "contributors" section in package.json - see Git history instead. # 0.4.20 / 2018-04-06 * Updated `new Buffer()` usages with recommended replacements as it's being deprecated in Node v10 (#176, #178 by @ChALkeR) # 0.4.19 / 2017-09-09 * Fixed iso8859-1 codec regression in handling untranslatable characters (#162, caused by #147) * Re-generated windows1255 codec, because it was updated in iconv project * Fixed grammar in error message when iconv-lite is loaded with encoding other than utf8 # 0.4.18 / 2017-06-13 * Fixed CESU-8 regression in Node v8. # 0.4.17 / 2017-04-22 * Updated typescript definition file to support Angular 2 AoT mode (#153 by @larssn) # 0.4.16 / 2017-04-22 * Added support for React Native (#150) * Changed iso8859-1 encoding to usine internal 'binary' encoding, as it's the same thing (#147 by @mscdex) * Fixed typo in Readme (#138 by @jiangzhuo) * Fixed build for Node v6.10+ by making correct version comparison * Added a warning if iconv-lite is loaded not as utf-8 (see #142) # 0.4.15 / 2016-11-21 * Fixed typescript type definition (#137) # 0.4.14 / 2016-11-20 * Preparation for v1.0 * Added Node v6 and latest Node versions to Travis CI test rig * Deprecated Node v0.8 support * Typescript typings (@larssn) * Fix encoding of Euro character in GB 18030 (inspired by @lygstate) * Add ms prefix to dbcs windows encodings (@rokoroku) # 0.4.13 / 2015-10-01 * Fix silly mistake in deprecation notice. # 0.4.12 / 2015-09-26 * Node v4 support: * Added CESU-8 decoding (#106) * Added deprecation notice for `extendNodeEncodings` * Added Travis tests for Node v4 and io.js latest (#105 by @Mithgol) # 0.4.11 / 2015-07-03 * Added CESU-8 encoding. # 0.4.10 / 2015-05-26 * Changed UTF-16 endianness heuristic to take into account any ASCII chars, not just spaces. This should minimize the importance of "default" endianness. # 0.4.9 / 2015-05-24 * Streamlined BOM handling: strip BOM by default, add BOM when encoding if addBOM: true. Added docs to Readme. * UTF16 now uses UTF16-LE by default. * Fixed minor issue with big5 encoding. * Added io.js testing on Travis; updated node-iconv version to test against. Now we just skip testing SBCS encodings that node-iconv doesn't support. * (internal refactoring) Updated codec interface to use classes. * Use strict mode in all files. # 0.4.8 / 2015-04-14 * added alias UNICODE-1-1-UTF-7 for UTF-7 encoding (#94) # 0.4.7 / 2015-02-05 * stop official support of Node.js v0.8. Should still work, but no guarantees. reason: Packages needed for testing are hard to get on Travis CI. * work in environment where Object.prototype is monkey patched with enumerable props (#89). # 0.4.6 / 2015-01-12 * fix rare aliases of single-byte encodings (thanks @mscdex) * double the timeout for dbcs tests to make them less flaky on travis # 0.4.5 / 2014-11-20 * fix windows-31j and x-sjis encoding support (@nleush) * minor fix: undefined variable reference when internal error happens # 0.4.4 / 2014-07-16 * added encodings UTF-7 (RFC2152) and UTF-7-IMAP (RFC3501 Section 5.1.3) * fixed streaming base64 encoding # 0.4.3 / 2014-06-14 * added encodings UTF-16BE and UTF-16 with BOM # 0.4.2 / 2014-06-12 * don't throw exception if `extendNodeEncodings()` is called more than once # 0.4.1 / 2014-06-11 * codepage 808 added # 0.4.0 / 2014-06-10 * code is rewritten from scratch * all widespread encodings are supported * streaming interface added * browserify compatibility added * (optional) extend core primitive encodings to make usage even simpler * moved from vows to mocha as the testing framework
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/iconv-lite/Changelog.md
Changelog.md
"use strict"; var Buffer = require("buffer").Buffer, Transform = require("stream").Transform; // == Exports ================================================================== module.exports = function(iconv) { // Additional Public API. iconv.encodeStream = function encodeStream(encoding, options) { return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); } iconv.decodeStream = function decodeStream(encoding, options) { return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); } iconv.supportsStreams = true; // Not published yet. iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; iconv._collect = IconvLiteDecoderStream.prototype.collect; }; // == Encoder stream ======================================================= function IconvLiteEncoderStream(conv, options) { this.conv = conv; options = options || {}; options.decodeStrings = false; // We accept only strings, so we don't need to decode them. Transform.call(this, options); } IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { constructor: { value: IconvLiteEncoderStream } }); IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { if (typeof chunk != 'string') return done(new Error("Iconv encoding stream needs strings as its input.")); try { var res = this.conv.write(chunk); if (res && res.length) this.push(res); done(); } catch (e) { done(e); } } IconvLiteEncoderStream.prototype._flush = function(done) { try { var res = this.conv.end(); if (res && res.length) this.push(res); done(); } catch (e) { done(e); } } IconvLiteEncoderStream.prototype.collect = function(cb) { var chunks = []; this.on('error', cb); this.on('data', function(chunk) { chunks.push(chunk); }); this.on('end', function() { cb(null, Buffer.concat(chunks)); }); return this; } // == Decoder stream ======================================================= function IconvLiteDecoderStream(conv, options) { this.conv = conv; options = options || {}; options.encoding = this.encoding = 'utf8'; // We output strings. Transform.call(this, options); } IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { constructor: { value: IconvLiteDecoderStream } }); IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { if (!Buffer.isBuffer(chunk)) return done(new Error("Iconv decoding stream needs buffers as its input.")); try { var res = this.conv.write(chunk); if (res && res.length) this.push(res, this.encoding); done(); } catch (e) { done(e); } } IconvLiteDecoderStream.prototype._flush = function(done) { try { var res = this.conv.end(); if (res && res.length) this.push(res, this.encoding); done(); } catch (e) { done(e); } } IconvLiteDecoderStream.prototype.collect = function(cb) { var res = ''; this.on('error', cb); this.on('data', function(chunk) { res += chunk; }); this.on('end', function() { cb(null, res); }); return this; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/iconv-lite/lib/streams.js
streams.js