text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```javascript
const parse = require('./parse')
const clean = (version, options) => {
const s = parse(version.trim().replace(/^[=v]+/, ''), options)
return s ? s.version : null
}
module.exports = clean
``` | /content/code_sandbox/node_modules/semver/functions/clean.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 51 |
```javascript
const { MAX_LENGTH } = require('../internal/constants')
const { re, t } = require('../internal/re')
const SemVer = require('../classes/semver')
const parseOptions = require('../internal/parse-options')
const parse = (version, options) => {
options = parseOptions(options)
if (version instanceof SemVer) {
return version
}
if (typeof version !== 'string') {
return null
}
if (version.length > MAX_LENGTH) {
return null
}
const r = options.loose ? re[t.LOOSE] : re[t.FULL]
if (!r.test(version)) {
return null
}
try {
return new SemVer(version, options)
} catch (er) {
return null
}
}
module.exports = parse
``` | /content/code_sandbox/node_modules/semver/functions/parse.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 174 |
```javascript
const compare = require('./compare')
const gt = (a, b, loose) => compare(a, b, loose) > 0
module.exports = gt
``` | /content/code_sandbox/node_modules/semver/functions/gt.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 35 |
```javascript
const Range = require('../classes/range')
const satisfies = (version, range, options) => {
try {
range = new Range(range, options)
} catch (er) {
return false
}
return range.test(version)
}
module.exports = satisfies
``` | /content/code_sandbox/node_modules/semver/functions/satisfies.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 59 |
```javascript
const parse = require('./parse')
const valid = (version, options) => {
const v = parse(version, options)
return v ? v.version : null
}
module.exports = valid
``` | /content/code_sandbox/node_modules/semver/functions/valid.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 42 |
```javascript
const SemVer = require('../classes/semver')
const inc = (version, release, options, identifier) => {
if (typeof (options) === 'string') {
identifier = options
options = undefined
}
try {
return new SemVer(
version instanceof SemVer ? version.version : version,
options
).inc(release, identifier).version
} catch (er) {
return null
}
}
module.exports = inc
``` | /content/code_sandbox/node_modules/semver/functions/inc.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 102 |
```javascript
const compareBuild = require('./compare-build')
const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
module.exports = rsort
``` | /content/code_sandbox/node_modules/semver/functions/rsort.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 42 |
```javascript
const compareBuild = require('./compare-build')
const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
module.exports = sort
``` | /content/code_sandbox/node_modules/semver/functions/sort.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 40 |
```javascript
const compare = require('./compare')
const compareLoose = (a, b) => compare(a, b, true)
module.exports = compareLoose
``` | /content/code_sandbox/node_modules/semver/functions/compare-loose.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 33 |
```javascript
const SemVer = require('../classes/semver')
const compare = (a, b, loose) =>
new SemVer(a, loose).compare(new SemVer(b, loose))
module.exports = compare
``` | /content/code_sandbox/node_modules/semver/functions/compare.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 44 |
```javascript
const SemVer = require('../classes/semver')
const patch = (a, loose) => new SemVer(a, loose).patch
module.exports = patch
``` | /content/code_sandbox/node_modules/semver/functions/patch.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 35 |
```javascript
const compare = require('./compare')
const lte = (a, b, loose) => compare(a, b, loose) <= 0
module.exports = lte
``` | /content/code_sandbox/node_modules/semver/functions/lte.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 37 |
```javascript
const compare = require('./compare')
const eq = (a, b, loose) => compare(a, b, loose) === 0
module.exports = eq
``` | /content/code_sandbox/node_modules/semver/functions/eq.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 35 |
```javascript
const SemVer = require('../classes/semver')
const compareBuild = (a, b, loose) => {
const versionA = new SemVer(a, loose)
const versionB = new SemVer(b, loose)
return versionA.compare(versionB) || versionA.compareBuild(versionB)
}
module.exports = compareBuild
``` | /content/code_sandbox/node_modules/semver/functions/compare-build.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 72 |
```javascript
const eq = require('./eq')
const neq = require('./neq')
const gt = require('./gt')
const gte = require('./gte')
const lt = require('./lt')
const lte = require('./lte')
const cmp = (a, op, b, loose) => {
switch (op) {
case '===':
if (typeof a === 'object') {
a = a.version
}
if (typeof b === 'object') {
b = b.version
}
return a === b
case '!==':
if (typeof a === 'object') {
a = a.version
}
if (typeof b === 'object') {
b = b.version
}
return a !== b
case '':
case '=':
case '==':
return eq(a, b, loose)
case '!=':
return neq(a, b, loose)
case '>':
return gt(a, b, loose)
case '>=':
return gte(a, b, loose)
case '<':
return lt(a, b, loose)
case '<=':
return lte(a, b, loose)
default:
throw new TypeError(`Invalid operator: ${op}`)
}
}
module.exports = cmp
``` | /content/code_sandbox/node_modules/semver/functions/cmp.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 275 |
```javascript
const SemVer = require('../classes/semver')
const parse = require('./parse')
const { re, t } = require('../internal/re')
const coerce = (version, options) => {
if (version instanceof SemVer) {
return version
}
if (typeof version === 'number') {
version = String(version)
}
if (typeof version !== 'string') {
return null
}
options = options || {}
let match = null
if (!options.rtl) {
match = version.match(re[t.COERCE])
} else {
// Find the right-most coercible string that does not share
// a terminus with a more left-ward coercible string.
// Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
//
// Walk through the string checking with a /g regexp
// Manually set the index so as to pick up overlapping matches.
// Stop when we get a match that ends at the string end, since no
// coercible string can be more right-ward without the same terminus.
let next
while ((next = re[t.COERCERTL].exec(version)) &&
(!match || match.index + match[0].length !== version.length)
) {
if (!match ||
next.index + next[0].length !== match.index + match[0].length) {
match = next
}
re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
}
// leave it in a clean state
re[t.COERCERTL].lastIndex = -1
}
if (match === null) {
return null
}
return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
}
module.exports = coerce
``` | /content/code_sandbox/node_modules/semver/functions/coerce.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 425 |
```javascript
const compare = require('./compare')
const lt = (a, b, loose) => compare(a, b, loose) < 0
module.exports = lt
``` | /content/code_sandbox/node_modules/semver/functions/lt.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 35 |
```javascript
const compare = require('./compare')
const gte = (a, b, loose) => compare(a, b, loose) >= 0
module.exports = gte
``` | /content/code_sandbox/node_modules/semver/functions/gte.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 37 |
```javascript
const parse = require('./parse')
const eq = require('./eq')
const diff = (version1, version2) => {
if (eq(version1, version2)) {
return null
} else {
const v1 = parse(version1)
const v2 = parse(version2)
const hasPre = v1.prerelease.length || v2.prerelease.length
const prefix = hasPre ? 'pre' : ''
const defaultResult = hasPre ? 'prerelease' : ''
for (const key in v1) {
if (key === 'major' || key === 'minor' || key === 'patch') {
if (v1[key] !== v2[key]) {
return prefix + key
}
}
}
return defaultResult // may be undefined
}
}
module.exports = diff
``` | /content/code_sandbox/node_modules/semver/functions/diff.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 183 |
```javascript
#!/usr/bin/env node
// Standalone semver comparison program.
// Exits successfully and prints matching version(s) if
// any supplied version is valid and passes all tests.
const argv = process.argv.slice(2)
let versions = []
const range = []
let inc = null
const version = require('../package.json').version
let loose = false
let includePrerelease = false
let coerce = false
let rtl = false
let identifier
const semver = require('../')
let reverse = false
let options = {}
const main = () => {
if (!argv.length) {
return help()
}
while (argv.length) {
let a = argv.shift()
const indexOfEqualSign = a.indexOf('=')
if (indexOfEqualSign !== -1) {
const value = a.slice(indexOfEqualSign + 1)
a = a.slice(0, indexOfEqualSign)
argv.unshift(value)
}
switch (a) {
case '-rv': case '-rev': case '--rev': case '--reverse':
reverse = true
break
case '-l': case '--loose':
loose = true
break
case '-p': case '--include-prerelease':
includePrerelease = true
break
case '-v': case '--version':
versions.push(argv.shift())
break
case '-i': case '--inc': case '--increment':
switch (argv[0]) {
case 'major': case 'minor': case 'patch': case 'prerelease':
case 'premajor': case 'preminor': case 'prepatch':
inc = argv.shift()
break
default:
inc = 'patch'
break
}
break
case '--preid':
identifier = argv.shift()
break
case '-r': case '--range':
range.push(argv.shift())
break
case '-c': case '--coerce':
coerce = true
break
case '--rtl':
rtl = true
break
case '--ltr':
rtl = false
break
case '-h': case '--help': case '-?':
return help()
default:
versions.push(a)
break
}
}
options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl }
versions = versions.map((v) => {
return coerce ? (semver.coerce(v, options) || { version: v }).version : v
}).filter((v) => {
return semver.valid(v)
})
if (!versions.length) {
return fail()
}
if (inc && (versions.length !== 1 || range.length)) {
return failInc()
}
for (let i = 0, l = range.length; i < l; i++) {
versions = versions.filter((v) => {
return semver.satisfies(v, range[i], options)
})
if (!versions.length) {
return fail()
}
}
return success(versions)
}
const failInc = () => {
console.error('--inc can only be used on a single version with no range')
fail()
}
const fail = () => process.exit(1)
const success = () => {
const compare = reverse ? 'rcompare' : 'compare'
versions.sort((a, b) => {
return semver[compare](a, b, options)
}).map((v) => {
return semver.clean(v, options)
}).map((v) => {
return inc ? semver.inc(v, inc, options, identifier) : v
}).forEach((v, i, _) => {
console.log(v)
})
}
const help = () => console.log(
`SemVer ${version}
A JavaScript implementation of the path_to_url specification
Usage: semver [options] <version> [<version> [...]]
Prints valid versions sorted by SemVer precedence
Options:
-r --range <range>
Print versions that match the specified range.
-i --increment [<level>]
Increment a version by the specified level. Level can
be one of: major, minor, patch, premajor, preminor,
prepatch, or prerelease. Default level is 'patch'.
Only one version may be specified.
--preid <identifier>
Identifier to be used to prefix premajor, preminor,
prepatch or prerelease version increments.
-l --loose
Interpret versions and ranges loosely
-p --include-prerelease
Always include prerelease versions in range matching
-c --coerce
Coerce a string into SemVer if possible
(does not imply --loose)
--rtl
Coerce version strings right to left
--ltr
Coerce version strings left to right (default)
Program exits successfully if any valid version satisfies
all supplied ranges, and prints all satisfying versions.
If no satisfying versions are found, then exits failure.
Versions are printed in ascending order, so supplying
multiple versions to the utility will just sort them.`)
main()
``` | /content/code_sandbox/node_modules/semver/bin/semver.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,087 |
```javascript
const numeric = /^[0-9]+$/
const compareIdentifiers = (a, b) => {
const anum = numeric.test(a)
const bnum = numeric.test(b)
if (anum && bnum) {
a = +a
b = +b
}
return a === b ? 0
: (anum && !bnum) ? -1
: (bnum && !anum) ? 1
: a < b ? -1
: 1
}
const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
module.exports = {
compareIdentifiers,
rcompareIdentifiers,
}
``` | /content/code_sandbox/node_modules/semver/internal/identifiers.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 151 |
```javascript
const { MAX_SAFE_COMPONENT_LENGTH } = require('./constants')
const debug = require('./debug')
exports = module.exports = {}
// The actual regexps go on exports.re
const re = exports.re = []
const src = exports.src = []
const t = exports.t = {}
let R = 0
const createToken = (name, value, isGlobal) => {
const index = R++
debug(name, index, value)
t[name] = index
src[index] = value
re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
}
// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.
// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.
createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+')
// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.
createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*')
// ## Main Version
// Three dot-separated numeric identifiers.
createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
`(${src[t.NUMERICIDENTIFIER]})\\.` +
`(${src[t.NUMERICIDENTIFIER]})`)
createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
`(${src[t.NUMERICIDENTIFIERLOOSE]})`)
// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
}|${src[t.NONNUMERICIDENTIFIER]})`)
createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
}|${src[t.NONNUMERICIDENTIFIER]})`)
// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.
createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.
createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+')
// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.
createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
}(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
// ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.
// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups. The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.
createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
}${src[t.PRERELEASE]}?${
src[t.BUILD]}?`)
createToken('FULL', `^${src[t.FULLPLAIN]}$`)
// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
}${src[t.PRERELEASELOOSE]}?${
src[t.BUILD]}?`)
createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
createToken('GTLT', '((?:<|>)?=?)')
// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
`(?:${src[t.PRERELEASE]})?${
src[t.BUILD]}?` +
`)?)?`)
createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:${src[t.PRERELEASELOOSE]})?${
src[t.BUILD]}?` +
`)?)?`)
createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
// Coercion.
// Extract anything that could conceivably be a part of a valid semver
createToken('COERCE', `${'(^|[^\\d])' +
'(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
`(?:$|[^\\d])`)
createToken('COERCERTL', src[t.COERCE], true)
// Tilde ranges.
// Meaning is "reasonably at or greater than"
createToken('LONETILDE', '(?:~>?)')
createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
exports.tildeTrimReplace = '$1~'
createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
// Caret ranges.
// Meaning is "at least and backwards compatible with"
createToken('LONECARET', '(?:\\^)')
createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
exports.caretTrimReplace = '$1^'
createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
// A simple gt/lt/eq thing, or just "" to indicate "any version"
createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
exports.comparatorTrimReplace = '$1$2$3'
// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
`\\s+-\\s+` +
`(${src[t.XRANGEPLAIN]})` +
`\\s*$`)
createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
`\\s+-\\s+` +
`(${src[t.XRANGEPLAINLOOSE]})` +
`\\s*$`)
// Star ranges basically just allow anything at all.
createToken('STAR', '(<|>)?=?\\s*\\*')
// >=0.0.0 is like a star
createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$')
createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$')
``` | /content/code_sandbox/node_modules/semver/internal/re.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 2,041 |
```javascript
// parse out just the options we care about so we always get a consistent
// obj with keys in a consistent order.
const opts = ['includePrerelease', 'loose', 'rtl']
const parseOptions = options =>
!options ? {}
: typeof options !== 'object' ? { loose: true }
: opts.filter(k => options[k]).reduce((o, k) => {
o[k] = true
return o
}, {})
module.exports = parseOptions
``` | /content/code_sandbox/node_modules/semver/internal/parse-options.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 104 |
```javascript
// Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
const SEMVER_SPEC_VERSION = '2.0.0'
const MAX_LENGTH = 256
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
/* istanbul ignore next */ 9007199254740991
// Max safe segment length for coercion.
const MAX_SAFE_COMPONENT_LENGTH = 16
module.exports = {
SEMVER_SPEC_VERSION,
MAX_LENGTH,
MAX_SAFE_INTEGER,
MAX_SAFE_COMPONENT_LENGTH,
}
``` | /content/code_sandbox/node_modules/semver/internal/constants.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 116 |
```javascript
const debug = (
typeof process === 'object' &&
process.env &&
process.env.NODE_DEBUG &&
/\bsemver\b/i.test(process.env.NODE_DEBUG)
) ? (...args) => console.error('SEMVER', ...args)
: () => {}
module.exports = debug
``` | /content/code_sandbox/node_modules/semver/internal/debug.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 61 |
```javascript
module.exports = {
SemVer: require('./semver.js'),
Range: require('./range.js'),
Comparator: require('./comparator.js'),
}
``` | /content/code_sandbox/node_modules/semver/classes/index.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 33 |
```javascript
const debug = require('../internal/debug')
const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')
const { re, t } = require('../internal/re')
const parseOptions = require('../internal/parse-options')
const { compareIdentifiers } = require('../internal/identifiers')
class SemVer {
constructor (version, options) {
options = parseOptions(options)
if (version instanceof SemVer) {
if (version.loose === !!options.loose &&
version.includePrerelease === !!options.includePrerelease) {
return version
} else {
version = version.version
}
} else if (typeof version !== 'string') {
throw new TypeError(`Invalid Version: ${version}`)
}
if (version.length > MAX_LENGTH) {
throw new TypeError(
`version is longer than ${MAX_LENGTH} characters`
)
}
debug('SemVer', version, options)
this.options = options
this.loose = !!options.loose
// this isn't actually relevant for versions, but keep it so that we
// don't run into trouble passing this.options around.
this.includePrerelease = !!options.includePrerelease
const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
if (!m) {
throw new TypeError(`Invalid Version: ${version}`)
}
this.raw = version
// these are actually numbers
this.major = +m[1]
this.minor = +m[2]
this.patch = +m[3]
if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
throw new TypeError('Invalid major version')
}
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
throw new TypeError('Invalid minor version')
}
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
throw new TypeError('Invalid patch version')
}
// numberify any prerelease numeric ids
if (!m[4]) {
this.prerelease = []
} else {
this.prerelease = m[4].split('.').map((id) => {
if (/^[0-9]+$/.test(id)) {
const num = +id
if (num >= 0 && num < MAX_SAFE_INTEGER) {
return num
}
}
return id
})
}
this.build = m[5] ? m[5].split('.') : []
this.format()
}
format () {
this.version = `${this.major}.${this.minor}.${this.patch}`
if (this.prerelease.length) {
this.version += `-${this.prerelease.join('.')}`
}
return this.version
}
toString () {
return this.version
}
compare (other) {
debug('SemVer.compare', this.version, this.options, other)
if (!(other instanceof SemVer)) {
if (typeof other === 'string' && other === this.version) {
return 0
}
other = new SemVer(other, this.options)
}
if (other.version === this.version) {
return 0
}
return this.compareMain(other) || this.comparePre(other)
}
compareMain (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
return (
compareIdentifiers(this.major, other.major) ||
compareIdentifiers(this.minor, other.minor) ||
compareIdentifiers(this.patch, other.patch)
)
}
comparePre (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
// NOT having a prerelease is > having one
if (this.prerelease.length && !other.prerelease.length) {
return -1
} else if (!this.prerelease.length && other.prerelease.length) {
return 1
} else if (!this.prerelease.length && !other.prerelease.length) {
return 0
}
let i = 0
do {
const a = this.prerelease[i]
const b = other.prerelease[i]
debug('prerelease compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
compareBuild (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
let i = 0
do {
const a = this.build[i]
const b = other.build[i]
debug('prerelease compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
// preminor will bump the version up to the next minor release, and immediately
// down to pre-release. premajor and prepatch work the same way.
inc (release, identifier) {
switch (release) {
case 'premajor':
this.prerelease.length = 0
this.patch = 0
this.minor = 0
this.major++
this.inc('pre', identifier)
break
case 'preminor':
this.prerelease.length = 0
this.patch = 0
this.minor++
this.inc('pre', identifier)
break
case 'prepatch':
// If this is already a prerelease, it will bump to the next version
// drop any prereleases that might already exist, since they are not
// relevant at this point.
this.prerelease.length = 0
this.inc('patch', identifier)
this.inc('pre', identifier)
break
// If the input is a non-prerelease version, this acts the same as
// prepatch.
case 'prerelease':
if (this.prerelease.length === 0) {
this.inc('patch', identifier)
}
this.inc('pre', identifier)
break
case 'major':
// If this is a pre-major version, bump up to the same major version.
// Otherwise increment major.
// 1.0.0-5 bumps to 1.0.0
// 1.1.0 bumps to 2.0.0
if (
this.minor !== 0 ||
this.patch !== 0 ||
this.prerelease.length === 0
) {
this.major++
}
this.minor = 0
this.patch = 0
this.prerelease = []
break
case 'minor':
// If this is a pre-minor version, bump up to the same minor version.
// Otherwise increment minor.
// 1.2.0-5 bumps to 1.2.0
// 1.2.1 bumps to 1.3.0
if (this.patch !== 0 || this.prerelease.length === 0) {
this.minor++
}
this.patch = 0
this.prerelease = []
break
case 'patch':
// If this is not a pre-release version, it will increment the patch.
// If it is a pre-release it will bump up to the same patch version.
// 1.2.0-5 patches to 1.2.0
// 1.2.0 patches to 1.2.1
if (this.prerelease.length === 0) {
this.patch++
}
this.prerelease = []
break
// This probably shouldn't be used publicly.
// 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
case 'pre':
if (this.prerelease.length === 0) {
this.prerelease = [0]
} else {
let i = this.prerelease.length
while (--i >= 0) {
if (typeof this.prerelease[i] === 'number') {
this.prerelease[i]++
i = -2
}
}
if (i === -1) {
// didn't increment anything
this.prerelease.push(0)
}
}
if (identifier) {
// 1.2.0-beta.1 bumps to 1.2.0-beta.2,
// 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
if (isNaN(this.prerelease[1])) {
this.prerelease = [identifier, 0]
}
} else {
this.prerelease = [identifier, 0]
}
}
break
default:
throw new Error(`invalid increment argument: ${release}`)
}
this.format()
this.raw = this.version
return this
}
}
module.exports = SemVer
``` | /content/code_sandbox/node_modules/semver/classes/semver.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 2,106 |
```javascript
const ANY = Symbol('SemVer ANY')
// hoisted class for cyclic dependency
class Comparator {
static get ANY () {
return ANY
}
constructor (comp, options) {
options = parseOptions(options)
if (comp instanceof Comparator) {
if (comp.loose === !!options.loose) {
return comp
} else {
comp = comp.value
}
}
debug('comparator', comp, options)
this.options = options
this.loose = !!options.loose
this.parse(comp)
if (this.semver === ANY) {
this.value = ''
} else {
this.value = this.operator + this.semver.version
}
debug('comp', this)
}
parse (comp) {
const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
const m = comp.match(r)
if (!m) {
throw new TypeError(`Invalid comparator: ${comp}`)
}
this.operator = m[1] !== undefined ? m[1] : ''
if (this.operator === '=') {
this.operator = ''
}
// if it literally is just '>' or '' then allow anything.
if (!m[2]) {
this.semver = ANY
} else {
this.semver = new SemVer(m[2], this.options.loose)
}
}
toString () {
return this.value
}
test (version) {
debug('Comparator.test', version, this.options.loose)
if (this.semver === ANY || version === ANY) {
return true
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
return cmp(version, this.operator, this.semver, this.options)
}
intersects (comp, options) {
if (!(comp instanceof Comparator)) {
throw new TypeError('a Comparator is required')
}
if (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false,
}
}
if (this.operator === '') {
if (this.value === '') {
return true
}
return new Range(comp.value, options).test(this.value)
} else if (comp.operator === '') {
if (comp.value === '') {
return true
}
return new Range(this.value, options).test(comp.semver)
}
const sameDirectionIncreasing =
(this.operator === '>=' || this.operator === '>') &&
(comp.operator === '>=' || comp.operator === '>')
const sameDirectionDecreasing =
(this.operator === '<=' || this.operator === '<') &&
(comp.operator === '<=' || comp.operator === '<')
const sameSemVer = this.semver.version === comp.semver.version
const differentDirectionsInclusive =
(this.operator === '>=' || this.operator === '<=') &&
(comp.operator === '>=' || comp.operator === '<=')
const oppositeDirectionsLessThan =
cmp(this.semver, '<', comp.semver, options) &&
(this.operator === '>=' || this.operator === '>') &&
(comp.operator === '<=' || comp.operator === '<')
const oppositeDirectionsGreaterThan =
cmp(this.semver, '>', comp.semver, options) &&
(this.operator === '<=' || this.operator === '<') &&
(comp.operator === '>=' || comp.operator === '>')
return (
sameDirectionIncreasing ||
sameDirectionDecreasing ||
(sameSemVer && differentDirectionsInclusive) ||
oppositeDirectionsLessThan ||
oppositeDirectionsGreaterThan
)
}
}
module.exports = Comparator
const parseOptions = require('../internal/parse-options')
const { re, t } = require('../internal/re')
const cmp = require('../functions/cmp')
const debug = require('../internal/debug')
const SemVer = require('./semver')
const Range = require('./range')
``` | /content/code_sandbox/node_modules/semver/classes/comparator.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 864 |
```javascript
// hoisted class for cyclic dependency
class Range {
constructor (range, options) {
options = parseOptions(options)
if (range instanceof Range) {
if (
range.loose === !!options.loose &&
range.includePrerelease === !!options.includePrerelease
) {
return range
} else {
return new Range(range.raw, options)
}
}
if (range instanceof Comparator) {
// just put it in the set and return
this.raw = range.value
this.set = [[range]]
this.format()
return this
}
this.options = options
this.loose = !!options.loose
this.includePrerelease = !!options.includePrerelease
// First, split based on boolean or ||
this.raw = range
this.set = range
.split('||')
// map the range to a 2d array of comparators
.map(r => this.parseRange(r.trim()))
// throw out any comparator lists that are empty
// this generally means that it was not a valid range, which is allowed
// in loose mode, but will still throw if the WHOLE range is invalid.
.filter(c => c.length)
if (!this.set.length) {
throw new TypeError(`Invalid SemVer Range: ${range}`)
}
// if we have any that are not the null set, throw out null sets.
if (this.set.length > 1) {
// keep the first one, in case they're all null sets
const first = this.set[0]
this.set = this.set.filter(c => !isNullSet(c[0]))
if (this.set.length === 0) {
this.set = [first]
} else if (this.set.length > 1) {
// if we have any that are *, then the range is just *
for (const c of this.set) {
if (c.length === 1 && isAny(c[0])) {
this.set = [c]
break
}
}
}
}
this.format()
}
format () {
this.range = this.set
.map((comps) => {
return comps.join(' ').trim()
})
.join('||')
.trim()
return this.range
}
toString () {
return this.range
}
parseRange (range) {
range = range.trim()
// memoize range parsing for performance.
// this is a very hot path, and fully deterministic.
const memoOpts = Object.keys(this.options).join(',')
const memoKey = `parseRange:${memoOpts}:${range}`
const cached = cache.get(memoKey)
if (cached) {
return cached
}
const loose = this.options.loose
// `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
debug('hyphen replace', range)
// `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
debug('comparator trim', range)
// `~ 1.2.3` => `~1.2.3`
range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
// `^ 1.2.3` => `^1.2.3`
range = range.replace(re[t.CARETTRIM], caretTrimReplace)
// normalize spaces
range = range.split(/\s+/).join(' ')
// At this point, the range is completely trimmed and
// ready to be split into comparators.
let rangeList = range
.split(' ')
.map(comp => parseComparator(comp, this.options))
.join(' ')
.split(/\s+/)
// >=0.0.0 is equivalent to *
.map(comp => replaceGTE0(comp, this.options))
if (loose) {
// in loose mode, throw out any that are not valid comparators
rangeList = rangeList.filter(comp => {
debug('loose invalid filter', comp, this.options)
return !!comp.match(re[t.COMPARATORLOOSE])
})
}
debug('range list', rangeList)
// if any comparators are the null set, then replace with JUST null set
// if more than one comparator, remove any * comparators
// also, don't include the same comparator more than once
const rangeMap = new Map()
const comparators = rangeList.map(comp => new Comparator(comp, this.options))
for (const comp of comparators) {
if (isNullSet(comp)) {
return [comp]
}
rangeMap.set(comp.value, comp)
}
if (rangeMap.size > 1 && rangeMap.has('')) {
rangeMap.delete('')
}
const result = [...rangeMap.values()]
cache.set(memoKey, result)
return result
}
intersects (range, options) {
if (!(range instanceof Range)) {
throw new TypeError('a Range is required')
}
return this.set.some((thisComparators) => {
return (
isSatisfiable(thisComparators, options) &&
range.set.some((rangeComparators) => {
return (
isSatisfiable(rangeComparators, options) &&
thisComparators.every((thisComparator) => {
return rangeComparators.every((rangeComparator) => {
return thisComparator.intersects(rangeComparator, options)
})
})
)
})
)
})
}
// if ANY of the sets match ALL of its comparators, then pass
test (version) {
if (!version) {
return false
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
for (let i = 0; i < this.set.length; i++) {
if (testSet(this.set[i], version, this.options)) {
return true
}
}
return false
}
}
module.exports = Range
const LRU = require('lru-cache')
const cache = new LRU({ max: 1000 })
const parseOptions = require('../internal/parse-options')
const Comparator = require('./comparator')
const debug = require('../internal/debug')
const SemVer = require('./semver')
const {
re,
t,
comparatorTrimReplace,
tildeTrimReplace,
caretTrimReplace,
} = require('../internal/re')
const isNullSet = c => c.value === '<0.0.0-0'
const isAny = c => c.value === ''
// take a set of comparators and determine whether there
// exists a version which can satisfy it
const isSatisfiable = (comparators, options) => {
let result = true
const remainingComparators = comparators.slice()
let testComparator = remainingComparators.pop()
while (result && remainingComparators.length) {
result = remainingComparators.every((otherComparator) => {
return testComparator.intersects(otherComparator, options)
})
testComparator = remainingComparators.pop()
}
return result
}
// comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
const parseComparator = (comp, options) => {
debug('comp', comp, options)
comp = replaceCarets(comp, options)
debug('caret', comp)
comp = replaceTildes(comp, options)
debug('tildes', comp)
comp = replaceXRanges(comp, options)
debug('xrange', comp)
comp = replaceStars(comp, options)
debug('stars', comp)
return comp
}
const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
const replaceTildes = (comp, options) =>
comp.trim().split(/\s+/).map((c) => {
return replaceTilde(c, options)
}).join(' ')
const replaceTilde = (comp, options) => {
const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
return comp.replace(r, (_, M, m, p, pr) => {
debug('tilde', comp, _, M, m, p, pr)
let ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
} else if (isX(p)) {
// ~1.2 == >=1.2.0 <1.3.0-0
ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
} else if (pr) {
debug('replaceTilde pr', pr)
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${+m + 1}.0-0`
} else {
// ~1.2.3 == >=1.2.3 <1.3.0-0
ret = `>=${M}.${m}.${p
} <${M}.${+m + 1}.0-0`
}
debug('tilde return', ret)
return ret
})
}
// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
// ^1.2.3 --> >=1.2.3 <2.0.0-0
// ^1.2.0 --> >=1.2.0 <2.0.0-0
const replaceCarets = (comp, options) =>
comp.trim().split(/\s+/).map((c) => {
return replaceCaret(c, options)
}).join(' ')
const replaceCaret = (comp, options) => {
debug('caret', comp, options)
const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
const z = options.includePrerelease ? '-0' : ''
return comp.replace(r, (_, M, m, p, pr) => {
debug('caret', comp, _, M, m, p, pr)
let ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
} else if (isX(p)) {
if (M === '0') {
ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
} else {
ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
}
} else if (pr) {
debug('replaceCaret pr', pr)
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${m}.${+p + 1}-0`
} else {
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${+m + 1}.0-0`
}
} else {
ret = `>=${M}.${m}.${p}-${pr
} <${+M + 1}.0.0-0`
}
} else {
debug('no pr')
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p
}${z} <${M}.${m}.${+p + 1}-0`
} else {
ret = `>=${M}.${m}.${p
}${z} <${M}.${+m + 1}.0-0`
}
} else {
ret = `>=${M}.${m}.${p
} <${+M + 1}.0.0-0`
}
}
debug('caret return', ret)
return ret
})
}
const replaceXRanges = (comp, options) => {
debug('replaceXRanges', comp, options)
return comp.split(/\s+/).map((c) => {
return replaceXRange(c, options)
}).join(' ')
}
const replaceXRange = (comp, options) => {
comp = comp.trim()
const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
debug('xRange', comp, ret, gtlt, M, m, p, pr)
const xM = isX(M)
const xm = xM || isX(m)
const xp = xm || isX(p)
const anyX = xp
if (gtlt === '=' && anyX) {
gtlt = ''
}
// if we're including prereleases in the match, then we need
// to fix this to -0, the lowest possible prerelease value
pr = options.includePrerelease ? '-0' : ''
if (xM) {
if (gtlt === '>' || gtlt === '<') {
// nothing is allowed
ret = '<0.0.0-0'
} else {
// nothing is forbidden
ret = '*'
}
} else if (gtlt && anyX) {
// we know patch is an x, because we have any x at all.
// replace X with 0
if (xm) {
m = 0
}
p = 0
if (gtlt === '>') {
// >1 => >=2.0.0
// >1.2 => >=1.3.0
gtlt = '>='
if (xm) {
M = +M + 1
m = 0
p = 0
} else {
m = +m + 1
p = 0
}
} else if (gtlt === '<=') {
// <=0.7.x is actually <0.8.0, since any 0.7.x should
// pass. Similarly, <=7.x is actually <8.0.0, etc.
gtlt = '<'
if (xm) {
M = +M + 1
} else {
m = +m + 1
}
}
if (gtlt === '<') {
pr = '-0'
}
ret = `${gtlt + M}.${m}.${p}${pr}`
} else if (xm) {
ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
} else if (xp) {
ret = `>=${M}.${m}.0${pr
} <${M}.${+m + 1}.0-0`
}
debug('xRange return', ret)
return ret
})
}
// Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
const replaceStars = (comp, options) => {
debug('replaceStars', comp, options)
// Looseness is ignored here. star is always as loose as it gets!
return comp.trim().replace(re[t.STAR], '')
}
const replaceGTE0 = (comp, options) => {
debug('replaceGTE0', comp, options)
return comp.trim()
.replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
}
// This function is passed to string.replace(re[t.HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
const hyphenReplace = incPr => ($0,
from, fM, fm, fp, fpr, fb,
to, tM, tm, tp, tpr, tb) => {
if (isX(fM)) {
from = ''
} else if (isX(fm)) {
from = `>=${fM}.0.0${incPr ? '-0' : ''}`
} else if (isX(fp)) {
from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
} else if (fpr) {
from = `>=${from}`
} else {
from = `>=${from}${incPr ? '-0' : ''}`
}
if (isX(tM)) {
to = ''
} else if (isX(tm)) {
to = `<${+tM + 1}.0.0-0`
} else if (isX(tp)) {
to = `<${tM}.${+tm + 1}.0-0`
} else if (tpr) {
to = `<=${tM}.${tm}.${tp}-${tpr}`
} else if (incPr) {
to = `<${tM}.${tm}.${+tp + 1}-0`
} else {
to = `<=${to}`
}
return (`${from} ${to}`).trim()
}
const testSet = (set, version, options) => {
for (let i = 0; i < set.length; i++) {
if (!set[i].test(version)) {
return false
}
}
if (version.prerelease.length && !options.includePrerelease) {
// Find the set of versions that are allowed to have prereleases
// For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
// That should allow `1.2.3-pr.2` to pass.
// However, `1.2.4-alpha.notready` should NOT be allowed,
// even though it's within the range set by the comparators.
for (let i = 0; i < set.length; i++) {
debug(set[i].semver)
if (set[i].semver === Comparator.ANY) {
continue
}
if (set[i].semver.prerelease.length > 0) {
const allowed = set[i].semver
if (allowed.major === version.major &&
allowed.minor === version.minor &&
allowed.patch === version.patch) {
return true
}
}
}
// Version has a -pre, but it's not one of the ones we like.
return false
}
return true
}
``` | /content/code_sandbox/node_modules/semver/classes/range.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 4,529 |
```javascript
'use strict'
module.exports = function (Yallist) {
Yallist.prototype[Symbol.iterator] = function* () {
for (let walker = this.head; walker; walker = walker.next) {
yield walker.value
}
}
}
``` | /content/code_sandbox/node_modules/semver/node_modules/yallist/iterator.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 55 |
```javascript
'use strict'
module.exports = Yallist
Yallist.Node = Node
Yallist.create = Yallist
function Yallist (list) {
var self = this
if (!(self instanceof Yallist)) {
self = new Yallist()
}
self.tail = null
self.head = null
self.length = 0
if (list && typeof list.forEach === 'function') {
list.forEach(function (item) {
self.push(item)
})
} else if (arguments.length > 0) {
for (var i = 0, l = arguments.length; i < l; i++) {
self.push(arguments[i])
}
}
return self
}
Yallist.prototype.removeNode = function (node) {
if (node.list !== this) {
throw new Error('removing node which does not belong to this list')
}
var next = node.next
var prev = node.prev
if (next) {
next.prev = prev
}
if (prev) {
prev.next = next
}
if (node === this.head) {
this.head = next
}
if (node === this.tail) {
this.tail = prev
}
node.list.length--
node.next = null
node.prev = null
node.list = null
return next
}
Yallist.prototype.unshiftNode = function (node) {
if (node === this.head) {
return
}
if (node.list) {
node.list.removeNode(node)
}
var head = this.head
node.list = this
node.next = head
if (head) {
head.prev = node
}
this.head = node
if (!this.tail) {
this.tail = node
}
this.length++
}
Yallist.prototype.pushNode = function (node) {
if (node === this.tail) {
return
}
if (node.list) {
node.list.removeNode(node)
}
var tail = this.tail
node.list = this
node.prev = tail
if (tail) {
tail.next = node
}
this.tail = node
if (!this.head) {
this.head = node
}
this.length++
}
Yallist.prototype.push = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
push(this, arguments[i])
}
return this.length
}
Yallist.prototype.unshift = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
unshift(this, arguments[i])
}
return this.length
}
Yallist.prototype.pop = function () {
if (!this.tail) {
return undefined
}
var res = this.tail.value
this.tail = this.tail.prev
if (this.tail) {
this.tail.next = null
} else {
this.head = null
}
this.length--
return res
}
Yallist.prototype.shift = function () {
if (!this.head) {
return undefined
}
var res = this.head.value
this.head = this.head.next
if (this.head) {
this.head.prev = null
} else {
this.tail = null
}
this.length--
return res
}
Yallist.prototype.forEach = function (fn, thisp) {
thisp = thisp || this
for (var walker = this.head, i = 0; walker !== null; i++) {
fn.call(thisp, walker.value, i, this)
walker = walker.next
}
}
Yallist.prototype.forEachReverse = function (fn, thisp) {
thisp = thisp || this
for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
fn.call(thisp, walker.value, i, this)
walker = walker.prev
}
}
Yallist.prototype.get = function (n) {
for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
// abort out of the list early if we hit a cycle
walker = walker.next
}
if (i === n && walker !== null) {
return walker.value
}
}
Yallist.prototype.getReverse = function (n) {
for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
// abort out of the list early if we hit a cycle
walker = walker.prev
}
if (i === n && walker !== null) {
return walker.value
}
}
Yallist.prototype.map = function (fn, thisp) {
thisp = thisp || this
var res = new Yallist()
for (var walker = this.head; walker !== null;) {
res.push(fn.call(thisp, walker.value, this))
walker = walker.next
}
return res
}
Yallist.prototype.mapReverse = function (fn, thisp) {
thisp = thisp || this
var res = new Yallist()
for (var walker = this.tail; walker !== null;) {
res.push(fn.call(thisp, walker.value, this))
walker = walker.prev
}
return res
}
Yallist.prototype.reduce = function (fn, initial) {
var acc
var walker = this.head
if (arguments.length > 1) {
acc = initial
} else if (this.head) {
walker = this.head.next
acc = this.head.value
} else {
throw new TypeError('Reduce of empty list with no initial value')
}
for (var i = 0; walker !== null; i++) {
acc = fn(acc, walker.value, i)
walker = walker.next
}
return acc
}
Yallist.prototype.reduceReverse = function (fn, initial) {
var acc
var walker = this.tail
if (arguments.length > 1) {
acc = initial
} else if (this.tail) {
walker = this.tail.prev
acc = this.tail.value
} else {
throw new TypeError('Reduce of empty list with no initial value')
}
for (var i = this.length - 1; walker !== null; i--) {
acc = fn(acc, walker.value, i)
walker = walker.prev
}
return acc
}
Yallist.prototype.toArray = function () {
var arr = new Array(this.length)
for (var i = 0, walker = this.head; walker !== null; i++) {
arr[i] = walker.value
walker = walker.next
}
return arr
}
Yallist.prototype.toArrayReverse = function () {
var arr = new Array(this.length)
for (var i = 0, walker = this.tail; walker !== null; i++) {
arr[i] = walker.value
walker = walker.prev
}
return arr
}
Yallist.prototype.slice = function (from, to) {
to = to || this.length
if (to < 0) {
to += this.length
}
from = from || 0
if (from < 0) {
from += this.length
}
var ret = new Yallist()
if (to < from || to < 0) {
return ret
}
if (from < 0) {
from = 0
}
if (to > this.length) {
to = this.length
}
for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
walker = walker.next
}
for (; walker !== null && i < to; i++, walker = walker.next) {
ret.push(walker.value)
}
return ret
}
Yallist.prototype.sliceReverse = function (from, to) {
to = to || this.length
if (to < 0) {
to += this.length
}
from = from || 0
if (from < 0) {
from += this.length
}
var ret = new Yallist()
if (to < from || to < 0) {
return ret
}
if (from < 0) {
from = 0
}
if (to > this.length) {
to = this.length
}
for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
walker = walker.prev
}
for (; walker !== null && i > from; i--, walker = walker.prev) {
ret.push(walker.value)
}
return ret
}
Yallist.prototype.splice = function (start, deleteCount, ...nodes) {
if (start > this.length) {
start = this.length - 1
}
if (start < 0) {
start = this.length + start;
}
for (var i = 0, walker = this.head; walker !== null && i < start; i++) {
walker = walker.next
}
var ret = []
for (var i = 0; walker && i < deleteCount; i++) {
ret.push(walker.value)
walker = this.removeNode(walker)
}
if (walker === null) {
walker = this.tail
}
if (walker !== this.head && walker !== this.tail) {
walker = walker.prev
}
for (var i = 0; i < nodes.length; i++) {
walker = insert(this, walker, nodes[i])
}
return ret;
}
Yallist.prototype.reverse = function () {
var head = this.head
var tail = this.tail
for (var walker = head; walker !== null; walker = walker.prev) {
var p = walker.prev
walker.prev = walker.next
walker.next = p
}
this.head = tail
this.tail = head
return this
}
function insert (self, node, value) {
var inserted = node === self.head ?
new Node(value, null, node, self) :
new Node(value, node, node.next, self)
if (inserted.next === null) {
self.tail = inserted
}
if (inserted.prev === null) {
self.head = inserted
}
self.length++
return inserted
}
function push (self, item) {
self.tail = new Node(item, self.tail, null, self)
if (!self.head) {
self.head = self.tail
}
self.length++
}
function unshift (self, item) {
self.head = new Node(item, null, self.head, self)
if (!self.tail) {
self.tail = self.head
}
self.length++
}
function Node (value, prev, next, list) {
if (!(this instanceof Node)) {
return new Node(value, prev, next, list)
}
this.list = list
this.value = value
if (prev) {
prev.next = this
this.prev = prev
} else {
this.prev = null
}
if (next) {
next.prev = this
this.next = next
} else {
this.next = null
}
}
try {
// add if support for Symbol.iterator is present
require('./iterator.js')(Yallist)
} catch (er) {}
``` | /content/code_sandbox/node_modules/semver/node_modules/yallist/yallist.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 2,525 |
```javascript
(function webpackUniversalModuleDefinition(root, factory) {
/* istanbul ignore next */
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
/* istanbul ignore next */
else if(typeof exports === 'object')
exports["esprima"] = factory();
else
root["esprima"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/* istanbul ignore if */
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
/*
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.
*/
"use strict";
var comment_handler_1 = __webpack_require__(1);
var parser_1 = __webpack_require__(3);
var jsx_parser_1 = __webpack_require__(11);
var tokenizer_1 = __webpack_require__(15);
function parse(code, options, delegate) {
var commentHandler = null;
var proxyDelegate = function (node, metadata) {
if (delegate) {
delegate(node, metadata);
}
if (commentHandler) {
commentHandler.visit(node, metadata);
}
};
var parserDelegate = (typeof delegate === 'function') ? proxyDelegate : null;
var collectComment = false;
if (options) {
collectComment = (typeof options.comment === 'boolean' && options.comment);
var attachComment = (typeof options.attachComment === 'boolean' && options.attachComment);
if (collectComment || attachComment) {
commentHandler = new comment_handler_1.CommentHandler();
commentHandler.attach = attachComment;
options.comment = true;
parserDelegate = proxyDelegate;
}
}
var parser;
if (options && typeof options.jsx === 'boolean' && options.jsx) {
parser = new jsx_parser_1.JSXParser(code, options, parserDelegate);
}
else {
parser = new parser_1.Parser(code, options, parserDelegate);
}
var ast = (parser.parseProgram());
if (collectComment) {
ast.comments = commentHandler.comments;
}
if (parser.config.tokens) {
ast.tokens = parser.tokens;
}
if (parser.config.tolerant) {
ast.errors = parser.errorHandler.errors;
}
return ast;
}
exports.parse = parse;
function tokenize(code, options, delegate) {
var tokenizer = new tokenizer_1.Tokenizer(code, options);
var tokens;
tokens = [];
try {
while (true) {
var token = tokenizer.getNextToken();
if (!token) {
break;
}
if (delegate) {
token = delegate(token);
}
tokens.push(token);
}
}
catch (e) {
tokenizer.errorHandler.tolerate(e);
}
if (tokenizer.errorHandler.tolerant) {
tokens.errors = tokenizer.errors();
}
return tokens;
}
exports.tokenize = tokenize;
var syntax_1 = __webpack_require__(2);
exports.Syntax = syntax_1.Syntax;
// Sync with *.json manifests.
exports.version = '3.1.3';
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var syntax_1 = __webpack_require__(2);
var CommentHandler = (function () {
function CommentHandler() {
this.attach = false;
this.comments = [];
this.stack = [];
this.leading = [];
this.trailing = [];
}
CommentHandler.prototype.insertInnerComments = function (node, metadata) {
// innnerComments for properties empty block
// `function a() {/** comments **\/}`
if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) {
var innerComments = [];
for (var i = this.leading.length - 1; i >= 0; --i) {
var entry = this.leading[i];
if (metadata.end.offset >= entry.start) {
innerComments.unshift(entry.comment);
this.leading.splice(i, 1);
this.trailing.splice(i, 1);
}
}
if (innerComments.length) {
node.innerComments = innerComments;
}
}
};
CommentHandler.prototype.findTrailingComments = function (node, metadata) {
var trailingComments = [];
if (this.trailing.length > 0) {
for (var i = this.trailing.length - 1; i >= 0; --i) {
var entry_1 = this.trailing[i];
if (entry_1.start >= metadata.end.offset) {
trailingComments.unshift(entry_1.comment);
}
}
this.trailing.length = 0;
return trailingComments;
}
var entry = this.stack[this.stack.length - 1];
if (entry && entry.node.trailingComments) {
var firstComment = entry.node.trailingComments[0];
if (firstComment && firstComment.range[0] >= metadata.end.offset) {
trailingComments = entry.node.trailingComments;
delete entry.node.trailingComments;
}
}
return trailingComments;
};
CommentHandler.prototype.findLeadingComments = function (node, metadata) {
var leadingComments = [];
var target;
while (this.stack.length > 0) {
var entry = this.stack[this.stack.length - 1];
if (entry && entry.start >= metadata.start.offset) {
target = this.stack.pop().node;
}
else {
break;
}
}
if (target) {
var count = target.leadingComments ? target.leadingComments.length : 0;
for (var i = count - 1; i >= 0; --i) {
var comment = target.leadingComments[i];
if (comment.range[1] <= metadata.start.offset) {
leadingComments.unshift(comment);
target.leadingComments.splice(i, 1);
}
}
if (target.leadingComments && target.leadingComments.length === 0) {
delete target.leadingComments;
}
return leadingComments;
}
for (var i = this.leading.length - 1; i >= 0; --i) {
var entry = this.leading[i];
if (entry.start <= metadata.start.offset) {
leadingComments.unshift(entry.comment);
this.leading.splice(i, 1);
}
}
return leadingComments;
};
CommentHandler.prototype.visitNode = function (node, metadata) {
if (node.type === syntax_1.Syntax.Program && node.body.length > 0) {
return;
}
this.insertInnerComments(node, metadata);
var trailingComments = this.findTrailingComments(node, metadata);
var leadingComments = this.findLeadingComments(node, metadata);
if (leadingComments.length > 0) {
node.leadingComments = leadingComments;
}
if (trailingComments.length > 0) {
node.trailingComments = trailingComments;
}
this.stack.push({
node: node,
start: metadata.start.offset
});
};
CommentHandler.prototype.visitComment = function (node, metadata) {
var type = (node.type[0] === 'L') ? 'Line' : 'Block';
var comment = {
type: type,
value: node.value
};
if (node.range) {
comment.range = node.range;
}
if (node.loc) {
comment.loc = node.loc;
}
this.comments.push(comment);
if (this.attach) {
var entry = {
comment: {
type: type,
value: node.value,
range: [metadata.start.offset, metadata.end.offset]
},
start: metadata.start.offset
};
if (node.loc) {
entry.comment.loc = node.loc;
}
node.type = type;
this.leading.push(entry);
this.trailing.push(entry);
}
};
CommentHandler.prototype.visit = function (node, metadata) {
if (node.type === 'LineComment') {
this.visitComment(node, metadata);
}
else if (node.type === 'BlockComment') {
this.visitComment(node, metadata);
}
else if (this.attach) {
this.visitNode(node, metadata);
}
};
return CommentHandler;
}());
exports.CommentHandler = CommentHandler;
/***/ },
/* 2 */
/***/ function(module, exports) {
"use strict";
exports.Syntax = {
AssignmentExpression: 'AssignmentExpression',
AssignmentPattern: 'AssignmentPattern',
ArrayExpression: 'ArrayExpression',
ArrayPattern: 'ArrayPattern',
ArrowFunctionExpression: 'ArrowFunctionExpression',
BlockStatement: 'BlockStatement',
BinaryExpression: 'BinaryExpression',
BreakStatement: 'BreakStatement',
CallExpression: 'CallExpression',
CatchClause: 'CatchClause',
ClassBody: 'ClassBody',
ClassDeclaration: 'ClassDeclaration',
ClassExpression: 'ClassExpression',
ConditionalExpression: 'ConditionalExpression',
ContinueStatement: 'ContinueStatement',
DoWhileStatement: 'DoWhileStatement',
DebuggerStatement: 'DebuggerStatement',
EmptyStatement: 'EmptyStatement',
ExportAllDeclaration: 'ExportAllDeclaration',
ExportDefaultDeclaration: 'ExportDefaultDeclaration',
ExportNamedDeclaration: 'ExportNamedDeclaration',
ExportSpecifier: 'ExportSpecifier',
ExpressionStatement: 'ExpressionStatement',
ForStatement: 'ForStatement',
ForOfStatement: 'ForOfStatement',
ForInStatement: 'ForInStatement',
FunctionDeclaration: 'FunctionDeclaration',
FunctionExpression: 'FunctionExpression',
Identifier: 'Identifier',
IfStatement: 'IfStatement',
ImportDeclaration: 'ImportDeclaration',
ImportDefaultSpecifier: 'ImportDefaultSpecifier',
ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
ImportSpecifier: 'ImportSpecifier',
Literal: 'Literal',
LabeledStatement: 'LabeledStatement',
LogicalExpression: 'LogicalExpression',
MemberExpression: 'MemberExpression',
MetaProperty: 'MetaProperty',
MethodDefinition: 'MethodDefinition',
NewExpression: 'NewExpression',
ObjectExpression: 'ObjectExpression',
ObjectPattern: 'ObjectPattern',
Program: 'Program',
Property: 'Property',
RestElement: 'RestElement',
ReturnStatement: 'ReturnStatement',
SequenceExpression: 'SequenceExpression',
SpreadElement: 'SpreadElement',
Super: 'Super',
SwitchCase: 'SwitchCase',
SwitchStatement: 'SwitchStatement',
TaggedTemplateExpression: 'TaggedTemplateExpression',
TemplateElement: 'TemplateElement',
TemplateLiteral: 'TemplateLiteral',
ThisExpression: 'ThisExpression',
ThrowStatement: 'ThrowStatement',
TryStatement: 'TryStatement',
UnaryExpression: 'UnaryExpression',
UpdateExpression: 'UpdateExpression',
VariableDeclaration: 'VariableDeclaration',
VariableDeclarator: 'VariableDeclarator',
WhileStatement: 'WhileStatement',
WithStatement: 'WithStatement',
YieldExpression: 'YieldExpression'
};
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var assert_1 = __webpack_require__(4);
var messages_1 = __webpack_require__(5);
var error_handler_1 = __webpack_require__(6);
var token_1 = __webpack_require__(7);
var scanner_1 = __webpack_require__(8);
var syntax_1 = __webpack_require__(2);
var Node = __webpack_require__(10);
var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder';
var Parser = (function () {
function Parser(code, options, delegate) {
if (options === void 0) { options = {}; }
this.config = {
range: (typeof options.range === 'boolean') && options.range,
loc: (typeof options.loc === 'boolean') && options.loc,
source: null,
tokens: (typeof options.tokens === 'boolean') && options.tokens,
comment: (typeof options.comment === 'boolean') && options.comment,
tolerant: (typeof options.tolerant === 'boolean') && options.tolerant
};
if (this.config.loc && options.source && options.source !== null) {
this.config.source = String(options.source);
}
this.delegate = delegate;
this.errorHandler = new error_handler_1.ErrorHandler();
this.errorHandler.tolerant = this.config.tolerant;
this.scanner = new scanner_1.Scanner(code, this.errorHandler);
this.scanner.trackComment = this.config.comment;
this.operatorPrecedence = {
')': 0,
';': 0,
',': 0,
'=': 0,
']': 0,
'||': 1,
'&&': 2,
'|': 3,
'^': 4,
'&': 5,
'==': 6,
'!=': 6,
'===': 6,
'!==': 6,
'<': 7,
'>': 7,
'<=': 7,
'>=': 7,
'<<': 8,
'>>': 8,
'>>>': 8,
'+': 9,
'-': 9,
'*': 11,
'/': 11,
'%': 11
};
this.sourceType = (options && options.sourceType === 'module') ? 'module' : 'script';
this.lookahead = null;
this.hasLineTerminator = false;
this.context = {
allowIn: true,
allowYield: true,
firstCoverInitializedNameError: null,
isAssignmentTarget: false,
isBindingElement: false,
inFunctionBody: false,
inIteration: false,
inSwitch: false,
labelSet: {},
strict: (this.sourceType === 'module')
};
this.tokens = [];
this.startMarker = {
index: 0,
lineNumber: this.scanner.lineNumber,
lineStart: 0
};
this.lastMarker = {
index: 0,
lineNumber: this.scanner.lineNumber,
lineStart: 0
};
this.nextToken();
this.lastMarker = {
index: this.scanner.index,
lineNumber: this.scanner.lineNumber,
lineStart: this.scanner.lineStart
};
}
Parser.prototype.throwError = function (messageFormat) {
var values = [];
for (var _i = 1; _i < arguments.length; _i++) {
values[_i - 1] = arguments[_i];
}
var args = Array.prototype.slice.call(arguments, 1);
var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) {
assert_1.assert(idx < args.length, 'Message reference must be in range');
return args[idx];
});
var index = this.lastMarker.index;
var line = this.lastMarker.lineNumber;
var column = this.lastMarker.index - this.lastMarker.lineStart + 1;
throw this.errorHandler.createError(index, line, column, msg);
};
Parser.prototype.tolerateError = function (messageFormat) {
var values = [];
for (var _i = 1; _i < arguments.length; _i++) {
values[_i - 1] = arguments[_i];
}
var args = Array.prototype.slice.call(arguments, 1);
var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) {
assert_1.assert(idx < args.length, 'Message reference must be in range');
return args[idx];
});
var index = this.lastMarker.index;
var line = this.scanner.lineNumber;
var column = this.lastMarker.index - this.lastMarker.lineStart + 1;
this.errorHandler.tolerateError(index, line, column, msg);
};
// Throw an exception because of the token.
Parser.prototype.unexpectedTokenError = function (token, message) {
var msg = message || messages_1.Messages.UnexpectedToken;
var value;
if (token) {
if (!message) {
msg = (token.type === token_1.Token.EOF) ? messages_1.Messages.UnexpectedEOS :
(token.type === token_1.Token.Identifier) ? messages_1.Messages.UnexpectedIdentifier :
(token.type === token_1.Token.NumericLiteral) ? messages_1.Messages.UnexpectedNumber :
(token.type === token_1.Token.StringLiteral) ? messages_1.Messages.UnexpectedString :
(token.type === token_1.Token.Template) ? messages_1.Messages.UnexpectedTemplate :
messages_1.Messages.UnexpectedToken;
if (token.type === token_1.Token.Keyword) {
if (this.scanner.isFutureReservedWord(token.value)) {
msg = messages_1.Messages.UnexpectedReserved;
}
else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) {
msg = messages_1.Messages.StrictReservedWord;
}
}
}
value = (token.type === token_1.Token.Template) ? token.value.raw : token.value;
}
else {
value = 'ILLEGAL';
}
msg = msg.replace('%0', value);
if (token && typeof token.lineNumber === 'number') {
var index = token.start;
var line = token.lineNumber;
var column = token.start - this.lastMarker.lineStart + 1;
return this.errorHandler.createError(index, line, column, msg);
}
else {
var index = this.lastMarker.index;
var line = this.lastMarker.lineNumber;
var column = index - this.lastMarker.lineStart + 1;
return this.errorHandler.createError(index, line, column, msg);
}
};
Parser.prototype.throwUnexpectedToken = function (token, message) {
throw this.unexpectedTokenError(token, message);
};
Parser.prototype.tolerateUnexpectedToken = function (token, message) {
this.errorHandler.tolerate(this.unexpectedTokenError(token, message));
};
Parser.prototype.collectComments = function () {
if (!this.config.comment) {
this.scanner.scanComments();
}
else {
var comments = this.scanner.scanComments();
if (comments.length > 0 && this.delegate) {
for (var i = 0; i < comments.length; ++i) {
var e = comments[i];
var node = void 0;
node = {
type: e.multiLine ? 'BlockComment' : 'LineComment',
value: this.scanner.source.slice(e.slice[0], e.slice[1])
};
if (this.config.range) {
node.range = e.range;
}
if (this.config.loc) {
node.loc = e.loc;
}
var metadata = {
start: {
line: e.loc.start.line,
column: e.loc.start.column,
offset: e.range[0]
},
end: {
line: e.loc.end.line,
column: e.loc.end.column,
offset: e.range[1]
}
};
this.delegate(node, metadata);
}
}
}
};
// From internal representation to an external structure
Parser.prototype.getTokenRaw = function (token) {
return this.scanner.source.slice(token.start, token.end);
};
Parser.prototype.convertToken = function (token) {
var t;
t = {
type: token_1.TokenName[token.type],
value: this.getTokenRaw(token)
};
if (this.config.range) {
t.range = [token.start, token.end];
}
if (this.config.loc) {
t.loc = {
start: {
line: this.startMarker.lineNumber,
column: this.startMarker.index - this.startMarker.lineStart
},
end: {
line: this.scanner.lineNumber,
column: this.scanner.index - this.scanner.lineStart
}
};
}
if (token.regex) {
t.regex = token.regex;
}
return t;
};
Parser.prototype.nextToken = function () {
var token = this.lookahead;
this.lastMarker.index = this.scanner.index;
this.lastMarker.lineNumber = this.scanner.lineNumber;
this.lastMarker.lineStart = this.scanner.lineStart;
this.collectComments();
this.startMarker.index = this.scanner.index;
this.startMarker.lineNumber = this.scanner.lineNumber;
this.startMarker.lineStart = this.scanner.lineStart;
var next;
next = this.scanner.lex();
this.hasLineTerminator = (token && next) ? (token.lineNumber !== next.lineNumber) : false;
if (next && this.context.strict && next.type === token_1.Token.Identifier) {
if (this.scanner.isStrictModeReservedWord(next.value)) {
next.type = token_1.Token.Keyword;
}
}
this.lookahead = next;
if (this.config.tokens && next.type !== token_1.Token.EOF) {
this.tokens.push(this.convertToken(next));
}
return token;
};
Parser.prototype.nextRegexToken = function () {
this.collectComments();
var token = this.scanner.scanRegExp();
if (this.config.tokens) {
// Pop the previous token, '/' or '/='
// This is added from the lookahead token.
this.tokens.pop();
this.tokens.push(this.convertToken(token));
}
// Prime the next lookahead.
this.lookahead = token;
this.nextToken();
return token;
};
Parser.prototype.createNode = function () {
return {
index: this.startMarker.index,
line: this.startMarker.lineNumber,
column: this.startMarker.index - this.startMarker.lineStart
};
};
Parser.prototype.startNode = function (token) {
return {
index: token.start,
line: token.lineNumber,
column: token.start - token.lineStart
};
};
Parser.prototype.finalize = function (meta, node) {
if (this.config.range) {
node.range = [meta.index, this.lastMarker.index];
}
if (this.config.loc) {
node.loc = {
start: {
line: meta.line,
column: meta.column
},
end: {
line: this.lastMarker.lineNumber,
column: this.lastMarker.index - this.lastMarker.lineStart
}
};
if (this.config.source) {
node.loc.source = this.config.source;
}
}
if (this.delegate) {
var metadata = {
start: {
line: meta.line,
column: meta.column,
offset: meta.index
},
end: {
line: this.lastMarker.lineNumber,
column: this.lastMarker.index - this.lastMarker.lineStart,
offset: this.lastMarker.index
}
};
this.delegate(node, metadata);
}
return node;
};
// Expect the next token to match the specified punctuator.
// If not, an exception will be thrown.
Parser.prototype.expect = function (value) {
var token = this.nextToken();
if (token.type !== token_1.Token.Punctuator || token.value !== value) {
this.throwUnexpectedToken(token);
}
};
// Quietly expect a comma when in tolerant mode, otherwise delegates to expect().
Parser.prototype.expectCommaSeparator = function () {
if (this.config.tolerant) {
var token = this.lookahead;
if (token.type === token_1.Token.Punctuator && token.value === ',') {
this.nextToken();
}
else if (token.type === token_1.Token.Punctuator && token.value === ';') {
this.nextToken();
this.tolerateUnexpectedToken(token);
}
else {
this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken);
}
}
else {
this.expect(',');
}
};
// Expect the next token to match the specified keyword.
// If not, an exception will be thrown.
Parser.prototype.expectKeyword = function (keyword) {
var token = this.nextToken();
if (token.type !== token_1.Token.Keyword || token.value !== keyword) {
this.throwUnexpectedToken(token);
}
};
// Return true if the next token matches the specified punctuator.
Parser.prototype.match = function (value) {
return this.lookahead.type === token_1.Token.Punctuator && this.lookahead.value === value;
};
// Return true if the next token matches the specified keyword
Parser.prototype.matchKeyword = function (keyword) {
return this.lookahead.type === token_1.Token.Keyword && this.lookahead.value === keyword;
};
// Return true if the next token matches the specified contextual keyword
// (where an identifier is sometimes a keyword depending on the context)
Parser.prototype.matchContextualKeyword = function (keyword) {
return this.lookahead.type === token_1.Token.Identifier && this.lookahead.value === keyword;
};
// Return true if the next token is an assignment operator
Parser.prototype.matchAssign = function () {
if (this.lookahead.type !== token_1.Token.Punctuator) {
return false;
}
var op = this.lookahead.value;
return op === '=' ||
op === '*=' ||
op === '**=' ||
op === '/=' ||
op === '%=' ||
op === '+=' ||
op === '-=' ||
op === '<<=' ||
op === '>>=' ||
op === '>>>=' ||
op === '&=' ||
op === '^=' ||
op === '|=';
};
// Cover grammar support.
//
// When an assignment expression position starts with an left parenthesis, the determination of the type
// of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead)
// or the first comma. This situation also defers the determination of all the expressions nested in the pair.
//
// There are three productions that can be parsed in a parentheses pair that needs to be determined
// after the outermost pair is closed. They are:
//
// 1. AssignmentExpression
// 2. BindingElements
// 3. AssignmentTargets
//
// In order to avoid exponential backtracking, we use two flags to denote if the production can be
// binding element or assignment target.
//
// The three productions have the relationship:
//
// BindingElements AssignmentTargets AssignmentExpression
//
// with a single exception that CoverInitializedName when used directly in an Expression, generates
// an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the
// first usage of CoverInitializedName and report it when we reached the end of the parentheses pair.
//
// isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not
// effect the current flags. This means the production the parser parses is only used as an expression. Therefore
// the CoverInitializedName check is conducted.
//
// inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates
// the flags outside of the parser. This means the production the parser parses is used as a part of a potential
// pattern. The CoverInitializedName check is deferred.
Parser.prototype.isolateCoverGrammar = function (parseFunction) {
var previousIsBindingElement = this.context.isBindingElement;
var previousIsAssignmentTarget = this.context.isAssignmentTarget;
var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
this.context.isBindingElement = true;
this.context.isAssignmentTarget = true;
this.context.firstCoverInitializedNameError = null;
var result = parseFunction.call(this);
if (this.context.firstCoverInitializedNameError !== null) {
this.throwUnexpectedToken(this.context.firstCoverInitializedNameError);
}
this.context.isBindingElement = previousIsBindingElement;
this.context.isAssignmentTarget = previousIsAssignmentTarget;
this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError;
return result;
};
Parser.prototype.inheritCoverGrammar = function (parseFunction) {
var previousIsBindingElement = this.context.isBindingElement;
var previousIsAssignmentTarget = this.context.isAssignmentTarget;
var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
this.context.isBindingElement = true;
this.context.isAssignmentTarget = true;
this.context.firstCoverInitializedNameError = null;
var result = parseFunction.call(this);
this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement;
this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget;
this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError;
return result;
};
Parser.prototype.consumeSemicolon = function () {
if (this.match(';')) {
this.nextToken();
}
else if (!this.hasLineTerminator) {
if (this.lookahead.type !== token_1.Token.EOF && !this.match('}')) {
this.throwUnexpectedToken(this.lookahead);
}
this.lastMarker.index = this.startMarker.index;
this.lastMarker.lineNumber = this.startMarker.lineNumber;
this.lastMarker.lineStart = this.startMarker.lineStart;
}
};
// ECMA-262 12.2 Primary Expressions
Parser.prototype.parsePrimaryExpression = function () {
var node = this.createNode();
var expr;
var value, token, raw;
switch (this.lookahead.type) {
case token_1.Token.Identifier:
if (this.sourceType === 'module' && this.lookahead.value === 'await') {
this.tolerateUnexpectedToken(this.lookahead);
}
expr = this.finalize(node, new Node.Identifier(this.nextToken().value));
break;
case token_1.Token.NumericLiteral:
case token_1.Token.StringLiteral:
if (this.context.strict && this.lookahead.octal) {
this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral);
}
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
token = this.nextToken();
raw = this.getTokenRaw(token);
expr = this.finalize(node, new Node.Literal(token.value, raw));
break;
case token_1.Token.BooleanLiteral:
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
token = this.nextToken();
token.value = (token.value === 'true');
raw = this.getTokenRaw(token);
expr = this.finalize(node, new Node.Literal(token.value, raw));
break;
case token_1.Token.NullLiteral:
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
token = this.nextToken();
token.value = null;
raw = this.getTokenRaw(token);
expr = this.finalize(node, new Node.Literal(token.value, raw));
break;
case token_1.Token.Template:
expr = this.parseTemplateLiteral();
break;
case token_1.Token.Punctuator:
value = this.lookahead.value;
switch (value) {
case '(':
this.context.isBindingElement = false;
expr = this.inheritCoverGrammar(this.parseGroupExpression);
break;
case '[':
expr = this.inheritCoverGrammar(this.parseArrayInitializer);
break;
case '{':
expr = this.inheritCoverGrammar(this.parseObjectInitializer);
break;
case '/':
case '/=':
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
this.scanner.index = this.startMarker.index;
token = this.nextRegexToken();
raw = this.getTokenRaw(token);
expr = this.finalize(node, new Node.RegexLiteral(token.value, raw, token.regex));
break;
default:
this.throwUnexpectedToken(this.nextToken());
}
break;
case token_1.Token.Keyword:
if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) {
expr = this.parseIdentifierName();
}
else if (!this.context.strict && this.matchKeyword('let')) {
expr = this.finalize(node, new Node.Identifier(this.nextToken().value));
}
else {
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
if (this.matchKeyword('function')) {
expr = this.parseFunctionExpression();
}
else if (this.matchKeyword('this')) {
this.nextToken();
expr = this.finalize(node, new Node.ThisExpression());
}
else if (this.matchKeyword('class')) {
expr = this.parseClassExpression();
}
else {
this.throwUnexpectedToken(this.nextToken());
}
}
break;
default:
this.throwUnexpectedToken(this.nextToken());
}
return expr;
};
// ECMA-262 12.2.5 Array Initializer
Parser.prototype.parseSpreadElement = function () {
var node = this.createNode();
this.expect('...');
var arg = this.inheritCoverGrammar(this.parseAssignmentExpression);
return this.finalize(node, new Node.SpreadElement(arg));
};
Parser.prototype.parseArrayInitializer = function () {
var node = this.createNode();
var elements = [];
this.expect('[');
while (!this.match(']')) {
if (this.match(',')) {
this.nextToken();
elements.push(null);
}
else if (this.match('...')) {
var element = this.parseSpreadElement();
if (!this.match(']')) {
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
this.expect(',');
}
elements.push(element);
}
else {
elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
if (!this.match(']')) {
this.expect(',');
}
}
}
this.expect(']');
return this.finalize(node, new Node.ArrayExpression(elements));
};
// ECMA-262 12.2.6 Object Initializer
Parser.prototype.parsePropertyMethod = function (params) {
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
var previousStrict = this.context.strict;
var body = this.isolateCoverGrammar(this.parseFunctionSourceElements);
if (this.context.strict && params.firstRestricted) {
this.tolerateUnexpectedToken(params.firstRestricted, params.message);
}
if (this.context.strict && params.stricted) {
this.tolerateUnexpectedToken(params.stricted, params.message);
}
this.context.strict = previousStrict;
return body;
};
Parser.prototype.parsePropertyMethodFunction = function () {
var isGenerator = false;
var node = this.createNode();
var previousAllowYield = this.context.allowYield;
this.context.allowYield = false;
var params = this.parseFormalParameters();
var method = this.parsePropertyMethod(params);
this.context.allowYield = previousAllowYield;
return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
};
Parser.prototype.parseObjectPropertyKey = function () {
var node = this.createNode();
var token = this.nextToken();
var key = null;
switch (token.type) {
case token_1.Token.StringLiteral:
case token_1.Token.NumericLiteral:
if (this.context.strict && token.octal) {
this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral);
}
var raw = this.getTokenRaw(token);
key = this.finalize(node, new Node.Literal(token.value, raw));
break;
case token_1.Token.Identifier:
case token_1.Token.BooleanLiteral:
case token_1.Token.NullLiteral:
case token_1.Token.Keyword:
key = this.finalize(node, new Node.Identifier(token.value));
break;
case token_1.Token.Punctuator:
if (token.value === '[') {
key = this.isolateCoverGrammar(this.parseAssignmentExpression);
this.expect(']');
}
else {
this.throwUnexpectedToken(token);
}
break;
default:
this.throwUnexpectedToken(token);
}
return key;
};
Parser.prototype.isPropertyKey = function (key, value) {
return (key.type === syntax_1.Syntax.Identifier && key.name === value) ||
(key.type === syntax_1.Syntax.Literal && key.value === value);
};
Parser.prototype.parseObjectProperty = function (hasProto) {
var node = this.createNode();
var token = this.lookahead;
var kind;
var key;
var value;
var computed = false;
var method = false;
var shorthand = false;
if (token.type === token_1.Token.Identifier) {
this.nextToken();
key = this.finalize(node, new Node.Identifier(token.value));
}
else if (this.match('*')) {
this.nextToken();
}
else {
computed = this.match('[');
key = this.parseObjectPropertyKey();
}
var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
if (token.type === token_1.Token.Identifier && token.value === 'get' && lookaheadPropertyKey) {
kind = 'get';
computed = this.match('[');
key = this.parseObjectPropertyKey();
this.context.allowYield = false;
value = this.parseGetterMethod();
}
else if (token.type === token_1.Token.Identifier && token.value === 'set' && lookaheadPropertyKey) {
kind = 'set';
computed = this.match('[');
key = this.parseObjectPropertyKey();
value = this.parseSetterMethod();
}
else if (token.type === token_1.Token.Punctuator && token.value === '*' && lookaheadPropertyKey) {
kind = 'init';
computed = this.match('[');
key = this.parseObjectPropertyKey();
value = this.parseGeneratorMethod();
method = true;
}
else {
if (!key) {
this.throwUnexpectedToken(this.lookahead);
}
kind = 'init';
if (this.match(':')) {
if (!computed && this.isPropertyKey(key, '__proto__')) {
if (hasProto.value) {
this.tolerateError(messages_1.Messages.DuplicateProtoProperty);
}
hasProto.value = true;
}
this.nextToken();
value = this.inheritCoverGrammar(this.parseAssignmentExpression);
}
else if (this.match('(')) {
value = this.parsePropertyMethodFunction();
method = true;
}
else if (token.type === token_1.Token.Identifier) {
var id = this.finalize(node, new Node.Identifier(token.value));
if (this.match('=')) {
this.context.firstCoverInitializedNameError = this.lookahead;
this.nextToken();
shorthand = true;
var init = this.isolateCoverGrammar(this.parseAssignmentExpression);
value = this.finalize(node, new Node.AssignmentPattern(id, init));
}
else {
shorthand = true;
value = id;
}
}
else {
this.throwUnexpectedToken(this.nextToken());
}
}
return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand));
};
Parser.prototype.parseObjectInitializer = function () {
var node = this.createNode();
this.expect('{');
var properties = [];
var hasProto = { value: false };
while (!this.match('}')) {
properties.push(this.parseObjectProperty(hasProto));
if (!this.match('}')) {
this.expectCommaSeparator();
}
}
this.expect('}');
return this.finalize(node, new Node.ObjectExpression(properties));
};
// ECMA-262 12.2.9 Template Literals
Parser.prototype.parseTemplateHead = function () {
assert_1.assert(this.lookahead.head, 'Template literal must start with a template head');
var node = this.createNode();
var token = this.nextToken();
var value = {
raw: token.value.raw,
cooked: token.value.cooked
};
return this.finalize(node, new Node.TemplateElement(value, token.tail));
};
Parser.prototype.parseTemplateElement = function () {
if (this.lookahead.type !== token_1.Token.Template) {
this.throwUnexpectedToken();
}
var node = this.createNode();
var token = this.nextToken();
var value = {
raw: token.value.raw,
cooked: token.value.cooked
};
return this.finalize(node, new Node.TemplateElement(value, token.tail));
};
Parser.prototype.parseTemplateLiteral = function () {
var node = this.createNode();
var expressions = [];
var quasis = [];
var quasi = this.parseTemplateHead();
quasis.push(quasi);
while (!quasi.tail) {
expressions.push(this.parseExpression());
quasi = this.parseTemplateElement();
quasis.push(quasi);
}
return this.finalize(node, new Node.TemplateLiteral(quasis, expressions));
};
// ECMA-262 12.2.10 The Grouping Operator
Parser.prototype.reinterpretExpressionAsPattern = function (expr) {
switch (expr.type) {
case syntax_1.Syntax.Identifier:
case syntax_1.Syntax.MemberExpression:
case syntax_1.Syntax.RestElement:
case syntax_1.Syntax.AssignmentPattern:
break;
case syntax_1.Syntax.SpreadElement:
expr.type = syntax_1.Syntax.RestElement;
this.reinterpretExpressionAsPattern(expr.argument);
break;
case syntax_1.Syntax.ArrayExpression:
expr.type = syntax_1.Syntax.ArrayPattern;
for (var i = 0; i < expr.elements.length; i++) {
if (expr.elements[i] !== null) {
this.reinterpretExpressionAsPattern(expr.elements[i]);
}
}
break;
case syntax_1.Syntax.ObjectExpression:
expr.type = syntax_1.Syntax.ObjectPattern;
for (var i = 0; i < expr.properties.length; i++) {
this.reinterpretExpressionAsPattern(expr.properties[i].value);
}
break;
case syntax_1.Syntax.AssignmentExpression:
expr.type = syntax_1.Syntax.AssignmentPattern;
delete expr.operator;
this.reinterpretExpressionAsPattern(expr.left);
break;
default:
// Allow other node type for tolerant parsing.
break;
}
};
Parser.prototype.parseGroupExpression = function () {
var expr;
this.expect('(');
if (this.match(')')) {
this.nextToken();
if (!this.match('=>')) {
this.expect('=>');
}
expr = {
type: ArrowParameterPlaceHolder,
params: []
};
}
else {
var startToken = this.lookahead;
var params = [];
if (this.match('...')) {
expr = this.parseRestElement(params);
this.expect(')');
if (!this.match('=>')) {
this.expect('=>');
}
expr = {
type: ArrowParameterPlaceHolder,
params: [expr]
};
}
else {
var arrow = false;
this.context.isBindingElement = true;
expr = this.inheritCoverGrammar(this.parseAssignmentExpression);
if (this.match(',')) {
var expressions = [];
this.context.isAssignmentTarget = false;
expressions.push(expr);
while (this.startMarker.index < this.scanner.length) {
if (!this.match(',')) {
break;
}
this.nextToken();
if (this.match('...')) {
if (!this.context.isBindingElement) {
this.throwUnexpectedToken(this.lookahead);
}
expressions.push(this.parseRestElement(params));
this.expect(')');
if (!this.match('=>')) {
this.expect('=>');
}
this.context.isBindingElement = false;
for (var i = 0; i < expressions.length; i++) {
this.reinterpretExpressionAsPattern(expressions[i]);
}
arrow = true;
expr = {
type: ArrowParameterPlaceHolder,
params: expressions
};
}
else {
expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
}
if (arrow) {
break;
}
}
if (!arrow) {
expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
}
}
if (!arrow) {
this.expect(')');
if (this.match('=>')) {
if (expr.type === syntax_1.Syntax.Identifier && expr.name === 'yield') {
arrow = true;
expr = {
type: ArrowParameterPlaceHolder,
params: [expr]
};
}
if (!arrow) {
if (!this.context.isBindingElement) {
this.throwUnexpectedToken(this.lookahead);
}
if (expr.type === syntax_1.Syntax.SequenceExpression) {
for (var i = 0; i < expr.expressions.length; i++) {
this.reinterpretExpressionAsPattern(expr.expressions[i]);
}
}
else {
this.reinterpretExpressionAsPattern(expr);
}
var params_1 = (expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]);
expr = {
type: ArrowParameterPlaceHolder,
params: params_1
};
}
}
this.context.isBindingElement = false;
}
}
}
return expr;
};
// ECMA-262 12.3 Left-Hand-Side Expressions
Parser.prototype.parseArguments = function () {
this.expect('(');
var args = [];
if (!this.match(')')) {
while (true) {
var expr = this.match('...') ? this.parseSpreadElement() :
this.isolateCoverGrammar(this.parseAssignmentExpression);
args.push(expr);
if (this.match(')')) {
break;
}
this.expectCommaSeparator();
}
}
this.expect(')');
return args;
};
Parser.prototype.isIdentifierName = function (token) {
return token.type === token_1.Token.Identifier ||
token.type === token_1.Token.Keyword ||
token.type === token_1.Token.BooleanLiteral ||
token.type === token_1.Token.NullLiteral;
};
Parser.prototype.parseIdentifierName = function () {
var node = this.createNode();
var token = this.nextToken();
if (!this.isIdentifierName(token)) {
this.throwUnexpectedToken(token);
}
return this.finalize(node, new Node.Identifier(token.value));
};
Parser.prototype.parseNewExpression = function () {
var node = this.createNode();
var id = this.parseIdentifierName();
assert_1.assert(id.name === 'new', 'New expression must start with `new`');
var expr;
if (this.match('.')) {
this.nextToken();
if (this.lookahead.type === token_1.Token.Identifier && this.context.inFunctionBody && this.lookahead.value === 'target') {
var property = this.parseIdentifierName();
expr = new Node.MetaProperty(id, property);
}
else {
this.throwUnexpectedToken(this.lookahead);
}
}
else {
var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression);
var args = this.match('(') ? this.parseArguments() : [];
expr = new Node.NewExpression(callee, args);
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
}
return this.finalize(node, expr);
};
Parser.prototype.parseLeftHandSideExpressionAllowCall = function () {
var startToken = this.lookahead;
var previousAllowIn = this.context.allowIn;
this.context.allowIn = true;
var expr;
if (this.matchKeyword('super') && this.context.inFunctionBody) {
expr = this.createNode();
this.nextToken();
expr = this.finalize(expr, new Node.Super());
if (!this.match('(') && !this.match('.') && !this.match('[')) {
this.throwUnexpectedToken(this.lookahead);
}
}
else {
expr = this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression);
}
while (true) {
if (this.match('.')) {
this.context.isBindingElement = false;
this.context.isAssignmentTarget = true;
this.expect('.');
var property = this.parseIdentifierName();
expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property));
}
else if (this.match('(')) {
this.context.isBindingElement = false;
this.context.isAssignmentTarget = false;
var args = this.parseArguments();
expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args));
}
else if (this.match('[')) {
this.context.isBindingElement = false;
this.context.isAssignmentTarget = true;
this.expect('[');
var property = this.isolateCoverGrammar(this.parseExpression);
this.expect(']');
expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property));
}
else if (this.lookahead.type === token_1.Token.Template && this.lookahead.head) {
var quasi = this.parseTemplateLiteral();
expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi));
}
else {
break;
}
}
this.context.allowIn = previousAllowIn;
return expr;
};
Parser.prototype.parseSuper = function () {
var node = this.createNode();
this.expectKeyword('super');
if (!this.match('[') && !this.match('.')) {
this.throwUnexpectedToken(this.lookahead);
}
return this.finalize(node, new Node.Super());
};
Parser.prototype.parseLeftHandSideExpression = function () {
assert_1.assert(this.context.allowIn, 'callee of new expression always allow in keyword.');
var node = this.startNode(this.lookahead);
var expr = (this.matchKeyword('super') && this.context.inFunctionBody) ? this.parseSuper() :
this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression);
while (true) {
if (this.match('[')) {
this.context.isBindingElement = false;
this.context.isAssignmentTarget = true;
this.expect('[');
var property = this.isolateCoverGrammar(this.parseExpression);
this.expect(']');
expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property));
}
else if (this.match('.')) {
this.context.isBindingElement = false;
this.context.isAssignmentTarget = true;
this.expect('.');
var property = this.parseIdentifierName();
expr = this.finalize(node, new Node.StaticMemberExpression(expr, property));
}
else if (this.lookahead.type === token_1.Token.Template && this.lookahead.head) {
var quasi = this.parseTemplateLiteral();
expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi));
}
else {
break;
}
}
return expr;
};
// ECMA-262 12.4 Update Expressions
Parser.prototype.parseUpdateExpression = function () {
var expr;
var startToken = this.lookahead;
if (this.match('++') || this.match('--')) {
var node = this.startNode(startToken);
var token = this.nextToken();
expr = this.inheritCoverGrammar(this.parseUnaryExpression);
if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
this.tolerateError(messages_1.Messages.StrictLHSPrefix);
}
if (!this.context.isAssignmentTarget) {
this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
}
var prefix = true;
expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix));
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
}
else {
expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
if (!this.hasLineTerminator && this.lookahead.type === token_1.Token.Punctuator) {
if (this.match('++') || this.match('--')) {
if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
this.tolerateError(messages_1.Messages.StrictLHSPostfix);
}
if (!this.context.isAssignmentTarget) {
this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
}
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
var operator = this.nextToken().value;
var prefix = false;
expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix));
}
}
}
return expr;
};
// ECMA-262 12.5 Unary Operators
Parser.prototype.parseUnaryExpression = function () {
var expr;
if (this.match('+') || this.match('-') || this.match('~') || this.match('!') ||
this.matchKeyword('delete') || this.matchKeyword('void') || this.matchKeyword('typeof')) {
var node = this.startNode(this.lookahead);
var token = this.nextToken();
expr = this.inheritCoverGrammar(this.parseUnaryExpression);
expr = this.finalize(node, new Node.UnaryExpression(token.value, expr));
if (this.context.strict && expr.operator === 'delete' && expr.argument.type === syntax_1.Syntax.Identifier) {
this.tolerateError(messages_1.Messages.StrictDelete);
}
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
}
else {
expr = this.parseUpdateExpression();
}
return expr;
};
Parser.prototype.parseExponentiationExpression = function () {
var startToken = this.lookahead;
var expr = this.inheritCoverGrammar(this.parseUnaryExpression);
if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match('**')) {
this.nextToken();
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
var left = expr;
var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression('**', left, right));
}
return expr;
};
// ECMA-262 12.6 Exponentiation Operators
// ECMA-262 12.7 Multiplicative Operators
// ECMA-262 12.8 Additive Operators
// ECMA-262 12.9 Bitwise Shift Operators
// ECMA-262 12.10 Relational Operators
// ECMA-262 12.11 Equality Operators
// ECMA-262 12.12 Binary Bitwise Operators
// ECMA-262 12.13 Binary Logical Operators
Parser.prototype.binaryPrecedence = function (token) {
var op = token.value;
var precedence;
if (token.type === token_1.Token.Punctuator) {
precedence = this.operatorPrecedence[op] || 0;
}
else if (token.type === token_1.Token.Keyword) {
precedence = (op === 'instanceof' || (this.context.allowIn && op === 'in')) ? 7 : 0;
}
else {
precedence = 0;
}
return precedence;
};
Parser.prototype.parseBinaryExpression = function () {
var startToken = this.lookahead;
var expr = this.inheritCoverGrammar(this.parseExponentiationExpression);
var token = this.lookahead;
var prec = this.binaryPrecedence(token);
if (prec > 0) {
this.nextToken();
token.prec = prec;
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
var markers = [startToken, this.lookahead];
var left = expr;
var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
var stack = [left, token, right];
while (true) {
prec = this.binaryPrecedence(this.lookahead);
if (prec <= 0) {
break;
}
// Reduce: make a binary expression from the three topmost entries.
while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
right = stack.pop();
var operator = stack.pop().value;
left = stack.pop();
markers.pop();
var node = this.startNode(markers[markers.length - 1]);
stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right)));
}
// Shift.
token = this.nextToken();
token.prec = prec;
stack.push(token);
markers.push(this.lookahead);
stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression));
}
// Final reduce to clean-up the stack.
var i = stack.length - 1;
expr = stack[i];
markers.pop();
while (i > 1) {
var node = this.startNode(markers.pop());
expr = this.finalize(node, new Node.BinaryExpression(stack[i - 1].value, stack[i - 2], expr));
i -= 2;
}
}
return expr;
};
// ECMA-262 12.14 Conditional Operator
Parser.prototype.parseConditionalExpression = function () {
var startToken = this.lookahead;
var expr = this.inheritCoverGrammar(this.parseBinaryExpression);
if (this.match('?')) {
this.nextToken();
var previousAllowIn = this.context.allowIn;
this.context.allowIn = true;
var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression);
this.context.allowIn = previousAllowIn;
this.expect(':');
var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression);
expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate));
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
}
return expr;
};
// ECMA-262 12.15 Assignment Operators
Parser.prototype.checkPatternParam = function (options, param) {
switch (param.type) {
case syntax_1.Syntax.Identifier:
this.validateParam(options, param, param.name);
break;
case syntax_1.Syntax.RestElement:
this.checkPatternParam(options, param.argument);
break;
case syntax_1.Syntax.AssignmentPattern:
this.checkPatternParam(options, param.left);
break;
case syntax_1.Syntax.ArrayPattern:
for (var i = 0; i < param.elements.length; i++) {
if (param.elements[i] !== null) {
this.checkPatternParam(options, param.elements[i]);
}
}
break;
case syntax_1.Syntax.YieldExpression:
break;
default:
assert_1.assert(param.type === syntax_1.Syntax.ObjectPattern, 'Invalid type');
for (var i = 0; i < param.properties.length; i++) {
this.checkPatternParam(options, param.properties[i].value);
}
break;
}
};
Parser.prototype.reinterpretAsCoverFormalsList = function (expr) {
var params = [expr];
var options;
switch (expr.type) {
case syntax_1.Syntax.Identifier:
break;
case ArrowParameterPlaceHolder:
params = expr.params;
break;
default:
return null;
}
options = {
paramSet: {}
};
for (var i = 0; i < params.length; ++i) {
var param = params[i];
if (param.type === syntax_1.Syntax.AssignmentPattern) {
if (param.right.type === syntax_1.Syntax.YieldExpression) {
if (param.right.argument) {
this.throwUnexpectedToken(this.lookahead);
}
param.right.type = syntax_1.Syntax.Identifier;
param.right.name = 'yield';
delete param.right.argument;
delete param.right.delegate;
}
}
this.checkPatternParam(options, param);
params[i] = param;
}
if (this.context.strict || !this.context.allowYield) {
for (var i = 0; i < params.length; ++i) {
var param = params[i];
if (param.type === syntax_1.Syntax.YieldExpression) {
this.throwUnexpectedToken(this.lookahead);
}
}
}
if (options.message === messages_1.Messages.StrictParamDupe) {
var token = this.context.strict ? options.stricted : options.firstRestricted;
this.throwUnexpectedToken(token, options.message);
}
return {
params: params,
stricted: options.stricted,
firstRestricted: options.firstRestricted,
message: options.message
};
};
Parser.prototype.parseAssignmentExpression = function () {
var expr;
if (!this.context.allowYield && this.matchKeyword('yield')) {
expr = this.parseYieldExpression();
}
else {
var startToken = this.lookahead;
var token = startToken;
expr = this.parseConditionalExpression();
if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) {
// ECMA-262 14.2 Arrow Function Definitions
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
var list = this.reinterpretAsCoverFormalsList(expr);
if (list) {
if (this.hasLineTerminator) {
this.tolerateUnexpectedToken(this.lookahead);
}
this.context.firstCoverInitializedNameError = null;
var previousStrict = this.context.strict;
var previousAllowYield = this.context.allowYield;
this.context.allowYield = true;
var node = this.startNode(startToken);
this.expect('=>');
var body = this.match('{') ? this.parseFunctionSourceElements() :
this.isolateCoverGrammar(this.parseAssignmentExpression);
var expression = body.type !== syntax_1.Syntax.BlockStatement;
if (this.context.strict && list.firstRestricted) {
this.throwUnexpectedToken(list.firstRestricted, list.message);
}
if (this.context.strict && list.stricted) {
this.tolerateUnexpectedToken(list.stricted, list.message);
}
expr = this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression));
this.context.strict = previousStrict;
this.context.allowYield = previousAllowYield;
}
}
else {
if (this.matchAssign()) {
if (!this.context.isAssignmentTarget) {
this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
}
if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) {
var id = (expr);
if (this.scanner.isRestrictedWord(id.name)) {
this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment);
}
if (this.scanner.isStrictModeReservedWord(id.name)) {
this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
}
}
if (!this.match('=')) {
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
}
else {
this.reinterpretExpressionAsPattern(expr);
}
token = this.nextToken();
var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(token.value, expr, right));
this.context.firstCoverInitializedNameError = null;
}
}
}
return expr;
};
// ECMA-262 12.16 Comma Operator
Parser.prototype.parseExpression = function () {
var startToken = this.lookahead;
var expr = this.isolateCoverGrammar(this.parseAssignmentExpression);
if (this.match(',')) {
var expressions = [];
expressions.push(expr);
while (this.startMarker.index < this.scanner.length) {
if (!this.match(',')) {
break;
}
this.nextToken();
expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
}
expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
}
return expr;
};
// ECMA-262 13.2 Block
Parser.prototype.parseStatementListItem = function () {
var statement = null;
this.context.isAssignmentTarget = true;
this.context.isBindingElement = true;
if (this.lookahead.type === token_1.Token.Keyword) {
switch (this.lookahead.value) {
case 'export':
if (this.sourceType !== 'module') {
this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration);
}
statement = this.parseExportDeclaration();
break;
case 'import':
if (this.sourceType !== 'module') {
this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration);
}
statement = this.parseImportDeclaration();
break;
case 'const':
statement = this.parseLexicalDeclaration({ inFor: false });
break;
case 'function':
statement = this.parseFunctionDeclaration();
break;
case 'class':
statement = this.parseClassDeclaration();
break;
case 'let':
statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement();
break;
default:
statement = this.parseStatement();
break;
}
}
else {
statement = this.parseStatement();
}
return statement;
};
Parser.prototype.parseBlock = function () {
var node = this.createNode();
this.expect('{');
var block = [];
while (true) {
if (this.match('}')) {
break;
}
block.push(this.parseStatementListItem());
}
this.expect('}');
return this.finalize(node, new Node.BlockStatement(block));
};
// ECMA-262 13.3.1 Let and Const Declarations
Parser.prototype.parseLexicalBinding = function (kind, options) {
var node = this.createNode();
var params = [];
var id = this.parsePattern(params, kind);
// ECMA-262 12.2.1
if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
if (this.scanner.isRestrictedWord((id).name)) {
this.tolerateError(messages_1.Messages.StrictVarName);
}
}
var init = null;
if (kind === 'const') {
if (!this.matchKeyword('in') && !this.matchContextualKeyword('of')) {
this.expect('=');
init = this.isolateCoverGrammar(this.parseAssignmentExpression);
}
}
else if ((!options.inFor && id.type !== syntax_1.Syntax.Identifier) || this.match('=')) {
this.expect('=');
init = this.isolateCoverGrammar(this.parseAssignmentExpression);
}
return this.finalize(node, new Node.VariableDeclarator(id, init));
};
Parser.prototype.parseBindingList = function (kind, options) {
var list = [this.parseLexicalBinding(kind, options)];
while (this.match(',')) {
this.nextToken();
list.push(this.parseLexicalBinding(kind, options));
}
return list;
};
Parser.prototype.isLexicalDeclaration = function () {
var previousIndex = this.scanner.index;
var previousLineNumber = this.scanner.lineNumber;
var previousLineStart = this.scanner.lineStart;
this.collectComments();
var next = this.scanner.lex();
this.scanner.index = previousIndex;
this.scanner.lineNumber = previousLineNumber;
this.scanner.lineStart = previousLineStart;
return (next.type === token_1.Token.Identifier) ||
(next.type === token_1.Token.Punctuator && next.value === '[') ||
(next.type === token_1.Token.Punctuator && next.value === '{') ||
(next.type === token_1.Token.Keyword && next.value === 'let') ||
(next.type === token_1.Token.Keyword && next.value === 'yield');
};
Parser.prototype.parseLexicalDeclaration = function (options) {
var node = this.createNode();
var kind = this.nextToken().value;
assert_1.assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const');
var declarations = this.parseBindingList(kind, options);
this.consumeSemicolon();
return this.finalize(node, new Node.VariableDeclaration(declarations, kind));
};
// ECMA-262 13.3.3 Destructuring Binding Patterns
Parser.prototype.parseBindingRestElement = function (params, kind) {
var node = this.createNode();
this.expect('...');
var arg = this.parsePattern(params, kind);
return this.finalize(node, new Node.RestElement(arg));
};
Parser.prototype.parseArrayPattern = function (params, kind) {
var node = this.createNode();
this.expect('[');
var elements = [];
while (!this.match(']')) {
if (this.match(',')) {
this.nextToken();
elements.push(null);
}
else {
if (this.match('...')) {
elements.push(this.parseBindingRestElement(params, kind));
break;
}
else {
elements.push(this.parsePatternWithDefault(params, kind));
}
if (!this.match(']')) {
this.expect(',');
}
}
}
this.expect(']');
return this.finalize(node, new Node.ArrayPattern(elements));
};
Parser.prototype.parsePropertyPattern = function (params, kind) {
var node = this.createNode();
var computed = false;
var shorthand = false;
var method = false;
var key;
var value;
if (this.lookahead.type === token_1.Token.Identifier) {
var keyToken = this.lookahead;
key = this.parseVariableIdentifier();
var init = this.finalize(node, new Node.Identifier(keyToken.value));
if (this.match('=')) {
params.push(keyToken);
shorthand = true;
this.nextToken();
var expr = this.parseAssignmentExpression();
value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr));
}
else if (!this.match(':')) {
params.push(keyToken);
shorthand = true;
value = init;
}
else {
this.expect(':');
value = this.parsePatternWithDefault(params, kind);
}
}
else {
computed = this.match('[');
key = this.parseObjectPropertyKey();
this.expect(':');
value = this.parsePatternWithDefault(params, kind);
}
return this.finalize(node, new Node.Property('init', key, computed, value, method, shorthand));
};
Parser.prototype.parseObjectPattern = function (params, kind) {
var node = this.createNode();
var properties = [];
this.expect('{');
while (!this.match('}')) {
properties.push(this.parsePropertyPattern(params, kind));
if (!this.match('}')) {
this.expect(',');
}
}
this.expect('}');
return this.finalize(node, new Node.ObjectPattern(properties));
};
Parser.prototype.parsePattern = function (params, kind) {
var pattern;
if (this.match('[')) {
pattern = this.parseArrayPattern(params, kind);
}
else if (this.match('{')) {
pattern = this.parseObjectPattern(params, kind);
}
else {
if (this.matchKeyword('let') && (kind === 'const' || kind === 'let')) {
this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.UnexpectedToken);
}
params.push(this.lookahead);
pattern = this.parseVariableIdentifier(kind);
}
return pattern;
};
Parser.prototype.parsePatternWithDefault = function (params, kind) {
var startToken = this.lookahead;
var pattern = this.parsePattern(params, kind);
if (this.match('=')) {
this.nextToken();
var previousAllowYield = this.context.allowYield;
this.context.allowYield = true;
var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
this.context.allowYield = previousAllowYield;
pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right));
}
return pattern;
};
// ECMA-262 13.3.2 Variable Statement
Parser.prototype.parseVariableIdentifier = function (kind) {
var node = this.createNode();
var token = this.nextToken();
if (token.type === token_1.Token.Keyword && token.value === 'yield') {
if (this.context.strict) {
this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
}
if (!this.context.allowYield) {
this.throwUnexpectedToken(token);
}
}
else if (token.type !== token_1.Token.Identifier) {
if (this.context.strict && token.type === token_1.Token.Keyword && this.scanner.isStrictModeReservedWord(token.value)) {
this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
}
else {
if (this.context.strict || token.value !== 'let' || kind !== 'var') {
this.throwUnexpectedToken(token);
}
}
}
else if (this.sourceType === 'module' && token.type === token_1.Token.Identifier && token.value === 'await') {
this.tolerateUnexpectedToken(token);
}
return this.finalize(node, new Node.Identifier(token.value));
};
Parser.prototype.parseVariableDeclaration = function (options) {
var node = this.createNode();
var params = [];
var id = this.parsePattern(params, 'var');
// ECMA-262 12.2.1
if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
if (this.scanner.isRestrictedWord((id).name)) {
this.tolerateError(messages_1.Messages.StrictVarName);
}
}
var init = null;
if (this.match('=')) {
this.nextToken();
init = this.isolateCoverGrammar(this.parseAssignmentExpression);
}
else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) {
this.expect('=');
}
return this.finalize(node, new Node.VariableDeclarator(id, init));
};
Parser.prototype.parseVariableDeclarationList = function (options) {
var opt = { inFor: options.inFor };
var list = [];
list.push(this.parseVariableDeclaration(opt));
while (this.match(',')) {
this.nextToken();
list.push(this.parseVariableDeclaration(opt));
}
return list;
};
Parser.prototype.parseVariableStatement = function () {
var node = this.createNode();
this.expectKeyword('var');
var declarations = this.parseVariableDeclarationList({ inFor: false });
this.consumeSemicolon();
return this.finalize(node, new Node.VariableDeclaration(declarations, 'var'));
};
// ECMA-262 13.4 Empty Statement
Parser.prototype.parseEmptyStatement = function () {
var node = this.createNode();
this.expect(';');
return this.finalize(node, new Node.EmptyStatement());
};
// ECMA-262 13.5 Expression Statement
Parser.prototype.parseExpressionStatement = function () {
var node = this.createNode();
var expr = this.parseExpression();
this.consumeSemicolon();
return this.finalize(node, new Node.ExpressionStatement(expr));
};
// ECMA-262 13.6 If statement
Parser.prototype.parseIfStatement = function () {
var node = this.createNode();
var consequent;
var alternate = null;
this.expectKeyword('if');
this.expect('(');
var test = this.parseExpression();
if (!this.match(')') && this.config.tolerant) {
this.tolerateUnexpectedToken(this.nextToken());
consequent = this.finalize(this.createNode(), new Node.EmptyStatement());
}
else {
this.expect(')');
consequent = this.parseStatement();
if (this.matchKeyword('else')) {
this.nextToken();
alternate = this.parseStatement();
}
}
return this.finalize(node, new Node.IfStatement(test, consequent, alternate));
};
// ECMA-262 13.7.2 The do-while Statement
Parser.prototype.parseDoWhileStatement = function () {
var node = this.createNode();
this.expectKeyword('do');
var previousInIteration = this.context.inIteration;
this.context.inIteration = true;
var body = this.parseStatement();
this.context.inIteration = previousInIteration;
this.expectKeyword('while');
this.expect('(');
var test = this.parseExpression();
this.expect(')');
if (this.match(';')) {
this.nextToken();
}
return this.finalize(node, new Node.DoWhileStatement(body, test));
};
// ECMA-262 13.7.3 The while Statement
Parser.prototype.parseWhileStatement = function () {
var node = this.createNode();
var body;
this.expectKeyword('while');
this.expect('(');
var test = this.parseExpression();
if (!this.match(')') && this.config.tolerant) {
this.tolerateUnexpectedToken(this.nextToken());
body = this.finalize(this.createNode(), new Node.EmptyStatement());
}
else {
this.expect(')');
var previousInIteration = this.context.inIteration;
this.context.inIteration = true;
body = this.parseStatement();
this.context.inIteration = previousInIteration;
}
return this.finalize(node, new Node.WhileStatement(test, body));
};
// ECMA-262 13.7.4 The for Statement
// ECMA-262 13.7.5 The for-in and for-of Statements
Parser.prototype.parseForStatement = function () {
var init = null;
var test = null;
var update = null;
var forIn = true;
var left, right;
var node = this.createNode();
this.expectKeyword('for');
this.expect('(');
if (this.match(';')) {
this.nextToken();
}
else {
if (this.matchKeyword('var')) {
init = this.createNode();
this.nextToken();
var previousAllowIn = this.context.allowIn;
this.context.allowIn = false;
var declarations = this.parseVariableDeclarationList({ inFor: true });
this.context.allowIn = previousAllowIn;
if (declarations.length === 1 && this.matchKeyword('in')) {
var decl = declarations[0];
if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) {
this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in');
}
init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
this.nextToken();
left = init;
right = this.parseExpression();
init = null;
}
else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) {
init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
this.nextToken();
left = init;
right = this.parseAssignmentExpression();
init = null;
forIn = false;
}
else {
init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
this.expect(';');
}
}
else if (this.matchKeyword('const') || this.matchKeyword('let')) {
init = this.createNode();
var kind = this.nextToken().value;
if (!this.context.strict && this.lookahead.value === 'in') {
init = this.finalize(init, new Node.Identifier(kind));
this.nextToken();
left = init;
right = this.parseExpression();
init = null;
}
else {
var previousAllowIn = this.context.allowIn;
this.context.allowIn = false;
var declarations = this.parseBindingList(kind, { inFor: true });
this.context.allowIn = previousAllowIn;
if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword('in')) {
init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
this.nextToken();
left = init;
right = this.parseExpression();
init = null;
}
else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) {
init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
this.nextToken();
left = init;
right = this.parseAssignmentExpression();
init = null;
forIn = false;
}
else {
this.consumeSemicolon();
init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
}
}
}
else {
var initStartToken = this.lookahead;
var previousAllowIn = this.context.allowIn;
this.context.allowIn = false;
init = this.inheritCoverGrammar(this.parseAssignmentExpression);
this.context.allowIn = previousAllowIn;
if (this.matchKeyword('in')) {
if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
this.tolerateError(messages_1.Messages.InvalidLHSInForIn);
}
this.nextToken();
this.reinterpretExpressionAsPattern(init);
left = init;
right = this.parseExpression();
init = null;
}
else if (this.matchContextualKeyword('of')) {
if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
this.tolerateError(messages_1.Messages.InvalidLHSInForLoop);
}
this.nextToken();
this.reinterpretExpressionAsPattern(init);
left = init;
right = this.parseAssignmentExpression();
init = null;
forIn = false;
}
else {
if (this.match(',')) {
var initSeq = [init];
while (this.match(',')) {
this.nextToken();
initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
}
init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq));
}
this.expect(';');
}
}
}
if (typeof left === 'undefined') {
if (!this.match(';')) {
test = this.parseExpression();
}
this.expect(';');
if (!this.match(')')) {
update = this.parseExpression();
}
}
var body;
if (!this.match(')') && this.config.tolerant) {
this.tolerateUnexpectedToken(this.nextToken());
body = this.finalize(this.createNode(), new Node.EmptyStatement());
}
else {
this.expect(')');
var previousInIteration = this.context.inIteration;
this.context.inIteration = true;
body = this.isolateCoverGrammar(this.parseStatement);
this.context.inIteration = previousInIteration;
}
return (typeof left === 'undefined') ?
this.finalize(node, new Node.ForStatement(init, test, update, body)) :
forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) :
this.finalize(node, new Node.ForOfStatement(left, right, body));
};
// ECMA-262 13.8 The continue statement
Parser.prototype.parseContinueStatement = function () {
var node = this.createNode();
this.expectKeyword('continue');
var label = null;
if (this.lookahead.type === token_1.Token.Identifier && !this.hasLineTerminator) {
label = this.parseVariableIdentifier();
var key = '$' + label.name;
if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
this.throwError(messages_1.Messages.UnknownLabel, label.name);
}
}
this.consumeSemicolon();
if (label === null && !this.context.inIteration) {
this.throwError(messages_1.Messages.IllegalContinue);
}
return this.finalize(node, new Node.ContinueStatement(label));
};
// ECMA-262 13.9 The break statement
Parser.prototype.parseBreakStatement = function () {
var node = this.createNode();
this.expectKeyword('break');
var label = null;
if (this.lookahead.type === token_1.Token.Identifier && !this.hasLineTerminator) {
label = this.parseVariableIdentifier();
var key = '$' + label.name;
if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
this.throwError(messages_1.Messages.UnknownLabel, label.name);
}
}
this.consumeSemicolon();
if (label === null && !this.context.inIteration && !this.context.inSwitch) {
this.throwError(messages_1.Messages.IllegalBreak);
}
return this.finalize(node, new Node.BreakStatement(label));
};
// ECMA-262 13.10 The return statement
Parser.prototype.parseReturnStatement = function () {
if (!this.context.inFunctionBody) {
this.tolerateError(messages_1.Messages.IllegalReturn);
}
var node = this.createNode();
this.expectKeyword('return');
var hasArgument = !this.match(';') && !this.match('}') &&
!this.hasLineTerminator && this.lookahead.type !== token_1.Token.EOF;
var argument = hasArgument ? this.parseExpression() : null;
this.consumeSemicolon();
return this.finalize(node, new Node.ReturnStatement(argument));
};
// ECMA-262 13.11 The with statement
Parser.prototype.parseWithStatement = function () {
if (this.context.strict) {
this.tolerateError(messages_1.Messages.StrictModeWith);
}
var node = this.createNode();
this.expectKeyword('with');
this.expect('(');
var object = this.parseExpression();
this.expect(')');
var body = this.parseStatement();
return this.finalize(node, new Node.WithStatement(object, body));
};
// ECMA-262 13.12 The switch statement
Parser.prototype.parseSwitchCase = function () {
var node = this.createNode();
var test;
if (this.matchKeyword('default')) {
this.nextToken();
test = null;
}
else {
this.expectKeyword('case');
test = this.parseExpression();
}
this.expect(':');
var consequent = [];
while (true) {
if (this.match('}') || this.matchKeyword('default') || this.matchKeyword('case')) {
break;
}
consequent.push(this.parseStatementListItem());
}
return this.finalize(node, new Node.SwitchCase(test, consequent));
};
Parser.prototype.parseSwitchStatement = function () {
var node = this.createNode();
this.expectKeyword('switch');
this.expect('(');
var discriminant = this.parseExpression();
this.expect(')');
var previousInSwitch = this.context.inSwitch;
this.context.inSwitch = true;
var cases = [];
var defaultFound = false;
this.expect('{');
while (true) {
if (this.match('}')) {
break;
}
var clause = this.parseSwitchCase();
if (clause.test === null) {
if (defaultFound) {
this.throwError(messages_1.Messages.MultipleDefaultsInSwitch);
}
defaultFound = true;
}
cases.push(clause);
}
this.expect('}');
this.context.inSwitch = previousInSwitch;
return this.finalize(node, new Node.SwitchStatement(discriminant, cases));
};
// ECMA-262 13.13 Labelled Statements
Parser.prototype.parseLabelledStatement = function () {
var node = this.createNode();
var expr = this.parseExpression();
var statement;
if ((expr.type === syntax_1.Syntax.Identifier) && this.match(':')) {
this.nextToken();
var id = (expr);
var key = '$' + id.name;
if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
this.throwError(messages_1.Messages.Redeclaration, 'Label', id.name);
}
this.context.labelSet[key] = true;
var labeledBody = this.parseStatement();
delete this.context.labelSet[key];
statement = new Node.LabeledStatement(id, labeledBody);
}
else {
this.consumeSemicolon();
statement = new Node.ExpressionStatement(expr);
}
return this.finalize(node, statement);
};
// ECMA-262 13.14 The throw statement
Parser.prototype.parseThrowStatement = function () {
var node = this.createNode();
this.expectKeyword('throw');
if (this.hasLineTerminator) {
this.throwError(messages_1.Messages.NewlineAfterThrow);
}
var argument = this.parseExpression();
this.consumeSemicolon();
return this.finalize(node, new Node.ThrowStatement(argument));
};
// ECMA-262 13.15 The try statement
Parser.prototype.parseCatchClause = function () {
var node = this.createNode();
this.expectKeyword('catch');
this.expect('(');
if (this.match(')')) {
this.throwUnexpectedToken(this.lookahead);
}
var params = [];
var param = this.parsePattern(params);
var paramMap = {};
for (var i = 0; i < params.length; i++) {
var key = '$' + params[i].value;
if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value);
}
paramMap[key] = true;
}
if (this.context.strict && param.type === syntax_1.Syntax.Identifier) {
if (this.scanner.isRestrictedWord((param).name)) {
this.tolerateError(messages_1.Messages.StrictCatchVariable);
}
}
this.expect(')');
var body = this.parseBlock();
return this.finalize(node, new Node.CatchClause(param, body));
};
Parser.prototype.parseFinallyClause = function () {
this.expectKeyword('finally');
return this.parseBlock();
};
Parser.prototype.parseTryStatement = function () {
var node = this.createNode();
this.expectKeyword('try');
var block = this.parseBlock();
var handler = this.matchKeyword('catch') ? this.parseCatchClause() : null;
var finalizer = this.matchKeyword('finally') ? this.parseFinallyClause() : null;
if (!handler && !finalizer) {
this.throwError(messages_1.Messages.NoCatchOrFinally);
}
return this.finalize(node, new Node.TryStatement(block, handler, finalizer));
};
// ECMA-262 13.16 The debugger statement
Parser.prototype.parseDebuggerStatement = function () {
var node = this.createNode();
this.expectKeyword('debugger');
this.consumeSemicolon();
return this.finalize(node, new Node.DebuggerStatement());
};
// ECMA-262 13 Statements
Parser.prototype.parseStatement = function () {
var statement = null;
switch (this.lookahead.type) {
case token_1.Token.BooleanLiteral:
case token_1.Token.NullLiteral:
case token_1.Token.NumericLiteral:
case token_1.Token.StringLiteral:
case token_1.Token.Template:
case token_1.Token.RegularExpression:
statement = this.parseExpressionStatement();
break;
case token_1.Token.Punctuator:
var value = this.lookahead.value;
if (value === '{') {
statement = this.parseBlock();
}
else if (value === '(') {
statement = this.parseExpressionStatement();
}
else if (value === ';') {
statement = this.parseEmptyStatement();
}
else {
statement = this.parseExpressionStatement();
}
break;
case token_1.Token.Identifier:
statement = this.parseLabelledStatement();
break;
case token_1.Token.Keyword:
switch (this.lookahead.value) {
case 'break':
statement = this.parseBreakStatement();
break;
case 'continue':
statement = this.parseContinueStatement();
break;
case 'debugger':
statement = this.parseDebuggerStatement();
break;
case 'do':
statement = this.parseDoWhileStatement();
break;
case 'for':
statement = this.parseForStatement();
break;
case 'function':
statement = this.parseFunctionDeclaration();
break;
case 'if':
statement = this.parseIfStatement();
break;
case 'return':
statement = this.parseReturnStatement();
break;
case 'switch':
statement = this.parseSwitchStatement();
break;
case 'throw':
statement = this.parseThrowStatement();
break;
case 'try':
statement = this.parseTryStatement();
break;
case 'var':
statement = this.parseVariableStatement();
break;
case 'while':
statement = this.parseWhileStatement();
break;
case 'with':
statement = this.parseWithStatement();
break;
default:
statement = this.parseExpressionStatement();
break;
}
break;
default:
this.throwUnexpectedToken(this.lookahead);
}
return statement;
};
// ECMA-262 14.1 Function Definition
Parser.prototype.parseFunctionSourceElements = function () {
var node = this.createNode();
this.expect('{');
var body = this.parseDirectivePrologues();
var previousLabelSet = this.context.labelSet;
var previousInIteration = this.context.inIteration;
var previousInSwitch = this.context.inSwitch;
var previousInFunctionBody = this.context.inFunctionBody;
this.context.labelSet = {};
this.context.inIteration = false;
this.context.inSwitch = false;
this.context.inFunctionBody = true;
while (this.startMarker.index < this.scanner.length) {
if (this.match('}')) {
break;
}
body.push(this.parseStatementListItem());
}
this.expect('}');
this.context.labelSet = previousLabelSet;
this.context.inIteration = previousInIteration;
this.context.inSwitch = previousInSwitch;
this.context.inFunctionBody = previousInFunctionBody;
return this.finalize(node, new Node.BlockStatement(body));
};
Parser.prototype.validateParam = function (options, param, name) {
var key = '$' + name;
if (this.context.strict) {
if (this.scanner.isRestrictedWord(name)) {
options.stricted = param;
options.message = messages_1.Messages.StrictParamName;
}
if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
options.stricted = param;
options.message = messages_1.Messages.StrictParamDupe;
}
}
else if (!options.firstRestricted) {
if (this.scanner.isRestrictedWord(name)) {
options.firstRestricted = param;
options.message = messages_1.Messages.StrictParamName;
}
else if (this.scanner.isStrictModeReservedWord(name)) {
options.firstRestricted = param;
options.message = messages_1.Messages.StrictReservedWord;
}
else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
options.stricted = param;
options.message = messages_1.Messages.StrictParamDupe;
}
}
/* istanbul ignore next */
if (typeof Object.defineProperty === 'function') {
Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true });
}
else {
options.paramSet[key] = true;
}
};
Parser.prototype.parseRestElement = function (params) {
var node = this.createNode();
this.expect('...');
var arg = this.parsePattern(params);
if (this.match('=')) {
this.throwError(messages_1.Messages.DefaultRestParameter);
}
if (!this.match(')')) {
this.throwError(messages_1.Messages.ParameterAfterRestParameter);
}
return this.finalize(node, new Node.RestElement(arg));
};
Parser.prototype.parseFormalParameter = function (options) {
var params = [];
var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params);
for (var i = 0; i < params.length; i++) {
this.validateParam(options, params[i], params[i].value);
}
options.params.push(param);
return !this.match(')');
};
Parser.prototype.parseFormalParameters = function (firstRestricted) {
var options;
options = {
params: [],
firstRestricted: firstRestricted
};
this.expect('(');
if (!this.match(')')) {
options.paramSet = {};
while (this.startMarker.index < this.scanner.length) {
if (!this.parseFormalParameter(options)) {
break;
}
this.expect(',');
}
}
this.expect(')');
return {
params: options.params,
stricted: options.stricted,
firstRestricted: options.firstRestricted,
message: options.message
};
};
Parser.prototype.parseFunctionDeclaration = function (identifierIsOptional) {
var node = this.createNode();
this.expectKeyword('function');
var isGenerator = this.match('*');
if (isGenerator) {
this.nextToken();
}
var message;
var id = null;
var firstRestricted = null;
if (!identifierIsOptional || !this.match('(')) {
var token = this.lookahead;
id = this.parseVariableIdentifier();
if (this.context.strict) {
if (this.scanner.isRestrictedWord(token.value)) {
this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
}
}
else {
if (this.scanner.isRestrictedWord(token.value)) {
firstRestricted = token;
message = messages_1.Messages.StrictFunctionName;
}
else if (this.scanner.isStrictModeReservedWord(token.value)) {
firstRestricted = token;
message = messages_1.Messages.StrictReservedWord;
}
}
}
var previousAllowYield = this.context.allowYield;
this.context.allowYield = !isGenerator;
var formalParameters = this.parseFormalParameters(firstRestricted);
var params = formalParameters.params;
var stricted = formalParameters.stricted;
firstRestricted = formalParameters.firstRestricted;
if (formalParameters.message) {
message = formalParameters.message;
}
var previousStrict = this.context.strict;
var body = this.parseFunctionSourceElements();
if (this.context.strict && firstRestricted) {
this.throwUnexpectedToken(firstRestricted, message);
}
if (this.context.strict && stricted) {
this.tolerateUnexpectedToken(stricted, message);
}
this.context.strict = previousStrict;
this.context.allowYield = previousAllowYield;
return this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator));
};
Parser.prototype.parseFunctionExpression = function () {
var node = this.createNode();
this.expectKeyword('function');
var isGenerator = this.match('*');
if (isGenerator) {
this.nextToken();
}
var message;
var id = null;
var firstRestricted;
var previousAllowYield = this.context.allowYield;
this.context.allowYield = !isGenerator;
if (!this.match('(')) {
var token = this.lookahead;
id = (!this.context.strict && !isGenerator && this.matchKeyword('yield')) ? this.parseIdentifierName() : this.parseVariableIdentifier();
if (this.context.strict) {
if (this.scanner.isRestrictedWord(token.value)) {
this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
}
}
else {
if (this.scanner.isRestrictedWord(token.value)) {
firstRestricted = token;
message = messages_1.Messages.StrictFunctionName;
}
else if (this.scanner.isStrictModeReservedWord(token.value)) {
firstRestricted = token;
message = messages_1.Messages.StrictReservedWord;
}
}
}
var formalParameters = this.parseFormalParameters(firstRestricted);
var params = formalParameters.params;
var stricted = formalParameters.stricted;
firstRestricted = formalParameters.firstRestricted;
if (formalParameters.message) {
message = formalParameters.message;
}
var previousStrict = this.context.strict;
var body = this.parseFunctionSourceElements();
if (this.context.strict && firstRestricted) {
this.throwUnexpectedToken(firstRestricted, message);
}
if (this.context.strict && stricted) {
this.tolerateUnexpectedToken(stricted, message);
}
this.context.strict = previousStrict;
this.context.allowYield = previousAllowYield;
return this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator));
};
// ECMA-262 14.1.1 Directive Prologues
Parser.prototype.parseDirective = function () {
var token = this.lookahead;
var directive = null;
var node = this.createNode();
var expr = this.parseExpression();
if (expr.type === syntax_1.Syntax.Literal) {
directive = this.getTokenRaw(token).slice(1, -1);
}
this.consumeSemicolon();
return this.finalize(node, directive ? new Node.Directive(expr, directive) :
new Node.ExpressionStatement(expr));
};
Parser.prototype.parseDirectivePrologues = function () {
var firstRestricted = null;
var body = [];
while (true) {
var token = this.lookahead;
if (token.type !== token_1.Token.StringLiteral) {
break;
}
var statement = this.parseDirective();
body.push(statement);
var directive = statement.directive;
if (typeof directive !== 'string') {
break;
}
if (directive === 'use strict') {
this.context.strict = true;
if (firstRestricted) {
this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral);
}
}
else {
if (!firstRestricted && token.octal) {
firstRestricted = token;
}
}
}
return body;
};
// ECMA-262 14.3 Method Definitions
Parser.prototype.qualifiedPropertyName = function (token) {
switch (token.type) {
case token_1.Token.Identifier:
case token_1.Token.StringLiteral:
case token_1.Token.BooleanLiteral:
case token_1.Token.NullLiteral:
case token_1.Token.NumericLiteral:
case token_1.Token.Keyword:
return true;
case token_1.Token.Punctuator:
return token.value === '[';
}
return false;
};
Parser.prototype.parseGetterMethod = function () {
var node = this.createNode();
this.expect('(');
this.expect(')');
var isGenerator = false;
var params = {
params: [],
stricted: null,
firstRestricted: null,
message: null
};
var previousAllowYield = this.context.allowYield;
this.context.allowYield = false;
var method = this.parsePropertyMethod(params);
this.context.allowYield = previousAllowYield;
return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
};
Parser.prototype.parseSetterMethod = function () {
var node = this.createNode();
var options = {
params: [],
firstRestricted: null,
paramSet: {}
};
var isGenerator = false;
var previousAllowYield = this.context.allowYield;
this.context.allowYield = false;
this.expect('(');
if (this.match(')')) {
this.tolerateUnexpectedToken(this.lookahead);
}
else {
this.parseFormalParameter(options);
}
this.expect(')');
var method = this.parsePropertyMethod(options);
this.context.allowYield = previousAllowYield;
return this.finalize(node, new Node.FunctionExpression(null, options.params, method, isGenerator));
};
Parser.prototype.parseGeneratorMethod = function () {
var node = this.createNode();
var isGenerator = true;
var previousAllowYield = this.context.allowYield;
this.context.allowYield = true;
var params = this.parseFormalParameters();
this.context.allowYield = false;
var method = this.parsePropertyMethod(params);
this.context.allowYield = previousAllowYield;
return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
};
// ECMA-262 14.4 Generator Function Definitions
Parser.prototype.isStartOfExpression = function () {
var start = true;
var value = this.lookahead.value;
switch (this.lookahead.type) {
case token_1.Token.Punctuator:
start = (value === '[') || (value === '(') || (value === '{') ||
(value === '+') || (value === '-') ||
(value === '!') || (value === '~') ||
(value === '++') || (value === '--') ||
(value === '/') || (value === '/='); // regular expression literal
break;
case token_1.Token.Keyword:
start = (value === 'class') || (value === 'delete') ||
(value === 'function') || (value === 'let') || (value === 'new') ||
(value === 'super') || (value === 'this') || (value === 'typeof') ||
(value === 'void') || (value === 'yield');
break;
default:
break;
}
return start;
};
Parser.prototype.parseYieldExpression = function () {
var node = this.createNode();
this.expectKeyword('yield');
var argument = null;
var delegate = false;
if (!this.hasLineTerminator) {
var previousAllowYield = this.context.allowYield;
this.context.allowYield = false;
delegate = this.match('*');
if (delegate) {
this.nextToken();
argument = this.parseAssignmentExpression();
}
else if (this.isStartOfExpression()) {
argument = this.parseAssignmentExpression();
}
this.context.allowYield = previousAllowYield;
}
return this.finalize(node, new Node.YieldExpression(argument, delegate));
};
// ECMA-262 14.5 Class Definitions
Parser.prototype.parseClassElement = function (hasConstructor) {
var token = this.lookahead;
var node = this.createNode();
var kind;
var key;
var value;
var computed = false;
var method = false;
var isStatic = false;
if (this.match('*')) {
this.nextToken();
}
else {
computed = this.match('[');
key = this.parseObjectPropertyKey();
var id = key;
if (id.name === 'static' && (this.qualifiedPropertyName(this.lookahead) || this.match('*'))) {
token = this.lookahead;
isStatic = true;
computed = this.match('[');
if (this.match('*')) {
this.nextToken();
}
else {
key = this.parseObjectPropertyKey();
}
}
}
var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
if (token.type === token_1.Token.Identifier) {
if (token.value === 'get' && lookaheadPropertyKey) {
kind = 'get';
computed = this.match('[');
key = this.parseObjectPropertyKey();
this.context.allowYield = false;
value = this.parseGetterMethod();
}
else if (token.value === 'set' && lookaheadPropertyKey) {
kind = 'set';
computed = this.match('[');
key = this.parseObjectPropertyKey();
value = this.parseSetterMethod();
}
}
else if (token.type === token_1.Token.Punctuator && token.value === '*' && lookaheadPropertyKey) {
kind = 'init';
computed = this.match('[');
key = this.parseObjectPropertyKey();
value = this.parseGeneratorMethod();
method = true;
}
if (!kind && key && this.match('(')) {
kind = 'init';
value = this.parsePropertyMethodFunction();
method = true;
}
if (!kind) {
this.throwUnexpectedToken(this.lookahead);
}
if (kind === 'init') {
kind = 'method';
}
if (!computed) {
if (isStatic && this.isPropertyKey(key, 'prototype')) {
this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype);
}
if (!isStatic && this.isPropertyKey(key, 'constructor')) {
if (kind !== 'method' || !method || value.generator) {
this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod);
}
if (hasConstructor.value) {
this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor);
}
else {
hasConstructor.value = true;
}
kind = 'constructor';
}
}
return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic));
};
Parser.prototype.parseClassElementList = function () {
var body = [];
var hasConstructor = { value: false };
this.expect('{');
while (!this.match('}')) {
if (this.match(';')) {
this.nextToken();
}
else {
body.push(this.parseClassElement(hasConstructor));
}
}
this.expect('}');
return body;
};
Parser.prototype.parseClassBody = function () {
var node = this.createNode();
var elementList = this.parseClassElementList();
return this.finalize(node, new Node.ClassBody(elementList));
};
Parser.prototype.parseClassDeclaration = function (identifierIsOptional) {
var node = this.createNode();
var previousStrict = this.context.strict;
this.context.strict = true;
this.expectKeyword('class');
var id = (identifierIsOptional && (this.lookahead.type !== token_1.Token.Identifier)) ? null : this.parseVariableIdentifier();
var superClass = null;
if (this.matchKeyword('extends')) {
this.nextToken();
superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
}
var classBody = this.parseClassBody();
this.context.strict = previousStrict;
return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody));
};
Parser.prototype.parseClassExpression = function () {
var node = this.createNode();
var previousStrict = this.context.strict;
this.context.strict = true;
this.expectKeyword('class');
var id = (this.lookahead.type === token_1.Token.Identifier) ? this.parseVariableIdentifier() : null;
var superClass = null;
if (this.matchKeyword('extends')) {
this.nextToken();
superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
}
var classBody = this.parseClassBody();
this.context.strict = previousStrict;
return this.finalize(node, new Node.ClassExpression(id, superClass, classBody));
};
// ECMA-262 15.1 Scripts
// ECMA-262 15.2 Modules
Parser.prototype.parseProgram = function () {
var node = this.createNode();
var body = this.parseDirectivePrologues();
while (this.startMarker.index < this.scanner.length) {
body.push(this.parseStatementListItem());
}
return this.finalize(node, new Node.Program(body, this.sourceType));
};
// ECMA-262 15.2.2 Imports
Parser.prototype.parseModuleSpecifier = function () {
var node = this.createNode();
if (this.lookahead.type !== token_1.Token.StringLiteral) {
this.throwError(messages_1.Messages.InvalidModuleSpecifier);
}
var token = this.nextToken();
var raw = this.getTokenRaw(token);
return this.finalize(node, new Node.Literal(token.value, raw));
};
// import {<foo as bar>} ...;
Parser.prototype.parseImportSpecifier = function () {
var node = this.createNode();
var imported;
var local;
if (this.lookahead.type === token_1.Token.Identifier) {
imported = this.parseVariableIdentifier();
local = imported;
if (this.matchContextualKeyword('as')) {
this.nextToken();
local = this.parseVariableIdentifier();
}
}
else {
imported = this.parseIdentifierName();
local = imported;
if (this.matchContextualKeyword('as')) {
this.nextToken();
local = this.parseVariableIdentifier();
}
else {
this.throwUnexpectedToken(this.nextToken());
}
}
return this.finalize(node, new Node.ImportSpecifier(local, imported));
};
// {foo, bar as bas}
Parser.prototype.parseNamedImports = function () {
this.expect('{');
var specifiers = [];
while (!this.match('}')) {
specifiers.push(this.parseImportSpecifier());
if (!this.match('}')) {
this.expect(',');
}
}
this.expect('}');
return specifiers;
};
// import <foo> ...;
Parser.prototype.parseImportDefaultSpecifier = function () {
var node = this.createNode();
var local = this.parseIdentifierName();
return this.finalize(node, new Node.ImportDefaultSpecifier(local));
};
// import <* as foo> ...;
Parser.prototype.parseImportNamespaceSpecifier = function () {
var node = this.createNode();
this.expect('*');
if (!this.matchContextualKeyword('as')) {
this.throwError(messages_1.Messages.NoAsAfterImportNamespace);
}
this.nextToken();
var local = this.parseIdentifierName();
return this.finalize(node, new Node.ImportNamespaceSpecifier(local));
};
Parser.prototype.parseImportDeclaration = function () {
if (this.context.inFunctionBody) {
this.throwError(messages_1.Messages.IllegalImportDeclaration);
}
var node = this.createNode();
this.expectKeyword('import');
var src;
var specifiers = [];
if (this.lookahead.type === token_1.Token.StringLiteral) {
// import 'foo';
src = this.parseModuleSpecifier();
}
else {
if (this.match('{')) {
// import {bar}
specifiers = specifiers.concat(this.parseNamedImports());
}
else if (this.match('*')) {
// import * as foo
specifiers.push(this.parseImportNamespaceSpecifier());
}
else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword('default')) {
// import foo
specifiers.push(this.parseImportDefaultSpecifier());
if (this.match(',')) {
this.nextToken();
if (this.match('*')) {
// import foo, * as foo
specifiers.push(this.parseImportNamespaceSpecifier());
}
else if (this.match('{')) {
// import foo, {bar}
specifiers = specifiers.concat(this.parseNamedImports());
}
else {
this.throwUnexpectedToken(this.lookahead);
}
}
}
else {
this.throwUnexpectedToken(this.nextToken());
}
if (!this.matchContextualKeyword('from')) {
var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
this.throwError(message, this.lookahead.value);
}
this.nextToken();
src = this.parseModuleSpecifier();
}
this.consumeSemicolon();
return this.finalize(node, new Node.ImportDeclaration(specifiers, src));
};
// ECMA-262 15.2.3 Exports
Parser.prototype.parseExportSpecifier = function () {
var node = this.createNode();
var local = this.parseIdentifierName();
var exported = local;
if (this.matchContextualKeyword('as')) {
this.nextToken();
exported = this.parseIdentifierName();
}
return this.finalize(node, new Node.ExportSpecifier(local, exported));
};
Parser.prototype.parseExportDeclaration = function () {
if (this.context.inFunctionBody) {
this.throwError(messages_1.Messages.IllegalExportDeclaration);
}
var node = this.createNode();
this.expectKeyword('export');
var exportDeclaration;
if (this.matchKeyword('default')) {
// export default ...
this.nextToken();
if (this.matchKeyword('function')) {
// export default function foo () {}
// export default function () {}
var declaration = this.parseFunctionDeclaration(true);
exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
}
else if (this.matchKeyword('class')) {
// export default class foo {}
var declaration = this.parseClassDeclaration(true);
exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
}
else {
if (this.matchContextualKeyword('from')) {
this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value);
}
// export default {};
// export default [];
// export default (1 + 2);
var declaration = this.match('{') ? this.parseObjectInitializer() :
this.match('[') ? this.parseArrayInitializer() : this.parseAssignmentExpression();
this.consumeSemicolon();
exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
}
}
else if (this.match('*')) {
// export * from 'foo';
this.nextToken();
if (!this.matchContextualKeyword('from')) {
var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
this.throwError(message, this.lookahead.value);
}
this.nextToken();
var src = this.parseModuleSpecifier();
this.consumeSemicolon();
exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src));
}
else if (this.lookahead.type === token_1.Token.Keyword) {
// export var f = 1;
var declaration = void 0;
switch (this.lookahead.value) {
case 'let':
case 'const':
declaration = this.parseLexicalDeclaration({ inFor: false });
break;
case 'var':
case 'class':
case 'function':
declaration = this.parseStatementListItem();
break;
default:
this.throwUnexpectedToken(this.lookahead);
}
exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null));
}
else {
var specifiers = [];
var source = null;
var isExportFromIdentifier = false;
this.expect('{');
while (!this.match('}')) {
isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword('default');
specifiers.push(this.parseExportSpecifier());
if (!this.match('}')) {
this.expect(',');
}
}
this.expect('}');
if (this.matchContextualKeyword('from')) {
// export {default} from 'foo';
// export {foo} from 'foo';
this.nextToken();
source = this.parseModuleSpecifier();
this.consumeSemicolon();
}
else if (isExportFromIdentifier) {
// export {default}; // missing fromClause
var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
this.throwError(message, this.lookahead.value);
}
else {
// export {foo};
this.consumeSemicolon();
}
exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source));
}
return exportDeclaration;
};
return Parser;
}());
exports.Parser = Parser;
/***/ },
/* 4 */
/***/ function(module, exports) {
// Ensure the condition is true, otherwise throw an error.
// This is only to have a better contract semantic, i.e. another safety net
// to catch a logic error. The condition shall be fulfilled in normal case.
// Do NOT use this to enforce a certain condition on any user input.
"use strict";
function assert(condition, message) {
/* istanbul ignore if */
if (!condition) {
throw new Error('ASSERT: ' + message);
}
}
exports.assert = assert;
/***/ },
/* 5 */
/***/ function(module, exports) {
"use strict";
// Error messages should be identical to V8.
exports.Messages = {
UnexpectedToken: 'Unexpected token %0',
UnexpectedTokenIllegal: 'Unexpected token ILLEGAL',
UnexpectedNumber: 'Unexpected number',
UnexpectedString: 'Unexpected string',
UnexpectedIdentifier: 'Unexpected identifier',
UnexpectedReserved: 'Unexpected reserved word',
UnexpectedTemplate: 'Unexpected quasi %0',
UnexpectedEOS: 'Unexpected end of input',
NewlineAfterThrow: 'Illegal newline after throw',
InvalidRegExp: 'Invalid regular expression',
UnterminatedRegExp: 'Invalid regular expression: missing /',
InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
InvalidLHSInForIn: 'Invalid left-hand side in for-in',
InvalidLHSInForLoop: 'Invalid left-hand side in for-loop',
MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
NoCatchOrFinally: 'Missing catch or finally after try',
UnknownLabel: 'Undefined label \'%0\'',
Redeclaration: '%0 \'%1\' has already been declared',
IllegalContinue: 'Illegal continue statement',
IllegalBreak: 'Illegal break statement',
IllegalReturn: 'Illegal return statement',
StrictModeWith: 'Strict mode code may not include a with statement',
StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
StrictVarName: 'Variable name may not be eval or arguments in strict mode',
StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
StrictDelete: 'Delete of an unqualified identifier in strict mode.',
StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
StrictReservedWord: 'Use of future reserved word in strict mode',
TemplateOctalLiteral: 'Octal literals are not allowed in template strings.',
ParameterAfterRestParameter: 'Rest parameter must be last formal parameter',
DefaultRestParameter: 'Unexpected token =',
DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals',
ConstructorSpecialMethod: 'Class constructor may not be an accessor',
DuplicateConstructor: 'A class may only have one constructor',
StaticPrototype: 'Classes may not have static property named prototype',
MissingFromClause: 'Unexpected token',
NoAsAfterImportNamespace: 'Unexpected token',
InvalidModuleSpecifier: 'Unexpected token',
IllegalImportDeclaration: 'Unexpected token',
IllegalExportDeclaration: 'Unexpected token',
DuplicateBinding: 'Duplicate binding %0',
ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer'
};
/***/ },
/* 6 */
/***/ function(module, exports) {
"use strict";
var ErrorHandler = (function () {
function ErrorHandler() {
this.errors = [];
this.tolerant = false;
}
;
ErrorHandler.prototype.recordError = function (error) {
this.errors.push(error);
};
;
ErrorHandler.prototype.tolerate = function (error) {
if (this.tolerant) {
this.recordError(error);
}
else {
throw error;
}
};
;
ErrorHandler.prototype.constructError = function (msg, column) {
var error = new Error(msg);
try {
throw error;
}
catch (base) {
/* istanbul ignore else */
if (Object.create && Object.defineProperty) {
error = Object.create(base);
Object.defineProperty(error, 'column', { value: column });
}
}
finally {
return error;
}
};
;
ErrorHandler.prototype.createError = function (index, line, col, description) {
var msg = 'Line ' + line + ': ' + description;
var error = this.constructError(msg, col);
error.index = index;
error.lineNumber = line;
error.description = description;
return error;
};
;
ErrorHandler.prototype.throwError = function (index, line, col, description) {
throw this.createError(index, line, col, description);
};
;
ErrorHandler.prototype.tolerateError = function (index, line, col, description) {
var error = this.createError(index, line, col, description);
if (this.tolerant) {
this.recordError(error);
}
else {
throw error;
}
};
;
return ErrorHandler;
}());
exports.ErrorHandler = ErrorHandler;
/***/ },
/* 7 */
/***/ function(module, exports) {
"use strict";
(function (Token) {
Token[Token["BooleanLiteral"] = 1] = "BooleanLiteral";
Token[Token["EOF"] = 2] = "EOF";
Token[Token["Identifier"] = 3] = "Identifier";
Token[Token["Keyword"] = 4] = "Keyword";
Token[Token["NullLiteral"] = 5] = "NullLiteral";
Token[Token["NumericLiteral"] = 6] = "NumericLiteral";
Token[Token["Punctuator"] = 7] = "Punctuator";
Token[Token["StringLiteral"] = 8] = "StringLiteral";
Token[Token["RegularExpression"] = 9] = "RegularExpression";
Token[Token["Template"] = 10] = "Template";
})(exports.Token || (exports.Token = {}));
var Token = exports.Token;
;
exports.TokenName = {};
exports.TokenName[Token.BooleanLiteral] = 'Boolean';
exports.TokenName[Token.EOF] = '<end>';
exports.TokenName[Token.Identifier] = 'Identifier';
exports.TokenName[Token.Keyword] = 'Keyword';
exports.TokenName[Token.NullLiteral] = 'Null';
exports.TokenName[Token.NumericLiteral] = 'Numeric';
exports.TokenName[Token.Punctuator] = 'Punctuator';
exports.TokenName[Token.StringLiteral] = 'String';
exports.TokenName[Token.RegularExpression] = 'RegularExpression';
exports.TokenName[Token.Template] = 'Template';
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var assert_1 = __webpack_require__(4);
var messages_1 = __webpack_require__(5);
var character_1 = __webpack_require__(9);
var token_1 = __webpack_require__(7);
function hexValue(ch) {
return '0123456789abcdef'.indexOf(ch.toLowerCase());
}
function octalValue(ch) {
return '01234567'.indexOf(ch);
}
var Scanner = (function () {
function Scanner(code, handler) {
this.source = code;
this.errorHandler = handler;
this.trackComment = false;
this.length = code.length;
this.index = 0;
this.lineNumber = (code.length > 0) ? 1 : 0;
this.lineStart = 0;
this.curlyStack = [];
}
;
Scanner.prototype.eof = function () {
return this.index >= this.length;
};
;
Scanner.prototype.throwUnexpectedToken = function (message) {
if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; }
this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
};
;
Scanner.prototype.tolerateUnexpectedToken = function () {
this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, messages_1.Messages.UnexpectedTokenIllegal);
};
;
// ECMA-262 11.4 Comments
Scanner.prototype.skipSingleLineComment = function (offset) {
var comments;
var start, loc;
if (this.trackComment) {
comments = [];
start = this.index - offset;
loc = {
start: {
line: this.lineNumber,
column: this.index - this.lineStart - offset
},
end: {}
};
}
while (!this.eof()) {
var ch = this.source.charCodeAt(this.index);
++this.index;
if (character_1.Character.isLineTerminator(ch)) {
if (this.trackComment) {
loc.end = {
line: this.lineNumber,
column: this.index - this.lineStart - 1
};
var entry = {
multiLine: false,
slice: [start + offset, this.index - 1],
range: [start, this.index - 1],
loc: loc
};
comments.push(entry);
}
if (ch === 13 && this.source.charCodeAt(this.index) === 10) {
++this.index;
}
++this.lineNumber;
this.lineStart = this.index;
return comments;
}
}
if (this.trackComment) {
loc.end = {
line: this.lineNumber,
column: this.index - this.lineStart
};
var entry = {
multiLine: false,
slice: [start + offset, this.index],
range: [start, this.index],
loc: loc
};
comments.push(entry);
}
return comments;
};
;
Scanner.prototype.skipMultiLineComment = function () {
var comments;
var start, loc;
if (this.trackComment) {
comments = [];
start = this.index - 2;
loc = {
start: {
line: this.lineNumber,
column: this.index - this.lineStart - 2
},
end: {}
};
}
while (!this.eof()) {
var ch = this.source.charCodeAt(this.index);
if (character_1.Character.isLineTerminator(ch)) {
if (ch === 0x0D && this.source.charCodeAt(this.index + 1) === 0x0A) {
++this.index;
}
++this.lineNumber;
++this.index;
this.lineStart = this.index;
}
else if (ch === 0x2A) {
// Block comment ends with '*/'.
if (this.source.charCodeAt(this.index + 1) === 0x2F) {
this.index += 2;
if (this.trackComment) {
loc.end = {
line: this.lineNumber,
column: this.index - this.lineStart
};
var entry = {
multiLine: true,
slice: [start + 2, this.index - 2],
range: [start, this.index],
loc: loc
};
comments.push(entry);
}
return comments;
}
++this.index;
}
else {
++this.index;
}
}
// Ran off the end of the file - the whole thing is a comment
if (this.trackComment) {
loc.end = {
line: this.lineNumber,
column: this.index - this.lineStart
};
var entry = {
multiLine: true,
slice: [start + 2, this.index],
range: [start, this.index],
loc: loc
};
comments.push(entry);
}
this.tolerateUnexpectedToken();
return comments;
};
;
Scanner.prototype.scanComments = function () {
var comments;
if (this.trackComment) {
comments = [];
}
var start = (this.index === 0);
while (!this.eof()) {
var ch = this.source.charCodeAt(this.index);
if (character_1.Character.isWhiteSpace(ch)) {
++this.index;
}
else if (character_1.Character.isLineTerminator(ch)) {
++this.index;
if (ch === 0x0D && this.source.charCodeAt(this.index) === 0x0A) {
++this.index;
}
++this.lineNumber;
this.lineStart = this.index;
start = true;
}
else if (ch === 0x2F) {
ch = this.source.charCodeAt(this.index + 1);
if (ch === 0x2F) {
this.index += 2;
var comment = this.skipSingleLineComment(2);
if (this.trackComment) {
comments = comments.concat(comment);
}
start = true;
}
else if (ch === 0x2A) {
this.index += 2;
var comment = this.skipMultiLineComment();
if (this.trackComment) {
comments = comments.concat(comment);
}
}
else {
break;
}
}
else if (start && ch === 0x2D) {
// U+003E is '>'
if ((this.source.charCodeAt(this.index + 1) === 0x2D) && (this.source.charCodeAt(this.index + 2) === 0x3E)) {
// '-->' is a single-line comment
this.index += 3;
var comment = this.skipSingleLineComment(3);
if (this.trackComment) {
comments = comments.concat(comment);
}
}
else {
break;
}
}
else if (ch === 0x3C) {
if (this.source.slice(this.index + 1, this.index + 4) === '!--') {
this.index += 4; // `<!--`
var comment = this.skipSingleLineComment(4);
if (this.trackComment) {
comments = comments.concat(comment);
}
}
else {
break;
}
}
else {
break;
}
}
return comments;
};
;
// ECMA-262 11.6.2.2 Future Reserved Words
Scanner.prototype.isFutureReservedWord = function (id) {
switch (id) {
case 'enum':
case 'export':
case 'import':
case 'super':
return true;
default:
return false;
}
};
;
Scanner.prototype.isStrictModeReservedWord = function (id) {
switch (id) {
case 'implements':
case 'interface':
case 'package':
case 'private':
case 'protected':
case 'public':
case 'static':
case 'yield':
case 'let':
return true;
default:
return false;
}
};
;
Scanner.prototype.isRestrictedWord = function (id) {
return id === 'eval' || id === 'arguments';
};
;
// ECMA-262 11.6.2.1 Keywords
Scanner.prototype.isKeyword = function (id) {
switch (id.length) {
case 2:
return (id === 'if') || (id === 'in') || (id === 'do');
case 3:
return (id === 'var') || (id === 'for') || (id === 'new') ||
(id === 'try') || (id === 'let');
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;
}
};
;
Scanner.prototype.codePointAt = function (i) {
var cp = this.source.charCodeAt(i);
if (cp >= 0xD800 && cp <= 0xDBFF) {
var second = this.source.charCodeAt(i + 1);
if (second >= 0xDC00 && second <= 0xDFFF) {
var first = cp;
cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
}
}
return cp;
};
;
Scanner.prototype.scanHexEscape = function (prefix) {
var len = (prefix === 'u') ? 4 : 2;
var code = 0;
for (var i = 0; i < len; ++i) {
if (!this.eof() && character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
code = code * 16 + hexValue(this.source[this.index++]);
}
else {
return '';
}
}
return String.fromCharCode(code);
};
;
Scanner.prototype.scanUnicodeCodePointEscape = function () {
var ch = this.source[this.index];
var code = 0;
// At least, one hex digit is required.
if (ch === '}') {
this.throwUnexpectedToken();
}
while (!this.eof()) {
ch = this.source[this.index++];
if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) {
break;
}
code = code * 16 + hexValue(ch);
}
if (code > 0x10FFFF || ch !== '}') {
this.throwUnexpectedToken();
}
return character_1.Character.fromCodePoint(code);
};
;
Scanner.prototype.getIdentifier = function () {
var start = this.index++;
while (!this.eof()) {
var ch = this.source.charCodeAt(this.index);
if (ch === 0x5C) {
// Blackslash (U+005C) marks Unicode escape sequence.
this.index = start;
return this.getComplexIdentifier();
}
else if (ch >= 0xD800 && ch < 0xDFFF) {
// Need to handle surrogate pairs.
this.index = start;
return this.getComplexIdentifier();
}
if (character_1.Character.isIdentifierPart(ch)) {
++this.index;
}
else {
break;
}
}
return this.source.slice(start, this.index);
};
;
Scanner.prototype.getComplexIdentifier = function () {
var cp = this.codePointAt(this.index);
var id = character_1.Character.fromCodePoint(cp);
this.index += id.length;
// '\u' (U+005C, U+0075) denotes an escaped character.
var ch;
if (cp === 0x5C) {
if (this.source.charCodeAt(this.index) !== 0x75) {
this.throwUnexpectedToken();
}
++this.index;
if (this.source[this.index] === '{') {
++this.index;
ch = this.scanUnicodeCodePointEscape();
}
else {
ch = this.scanHexEscape('u');
cp = ch.charCodeAt(0);
if (!ch || ch === '\\' || !character_1.Character.isIdentifierStart(cp)) {
this.throwUnexpectedToken();
}
}
id = ch;
}
while (!this.eof()) {
cp = this.codePointAt(this.index);
if (!character_1.Character.isIdentifierPart(cp)) {
break;
}
ch = character_1.Character.fromCodePoint(cp);
id += ch;
this.index += ch.length;
// '\u' (U+005C, U+0075) denotes an escaped character.
if (cp === 0x5C) {
id = id.substr(0, id.length - 1);
if (this.source.charCodeAt(this.index) !== 0x75) {
this.throwUnexpectedToken();
}
++this.index;
if (this.source[this.index] === '{') {
++this.index;
ch = this.scanUnicodeCodePointEscape();
}
else {
ch = this.scanHexEscape('u');
cp = ch.charCodeAt(0);
if (!ch || ch === '\\' || !character_1.Character.isIdentifierPart(cp)) {
this.throwUnexpectedToken();
}
}
id += ch;
}
}
return id;
};
;
Scanner.prototype.octalToDecimal = function (ch) {
// \0 is not octal escape sequence
var octal = (ch !== '0');
var code = octalValue(ch);
if (!this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
octal = true;
code = code * 8 + octalValue(this.source[this.index++]);
// 3 digits are only allowed when string starts
// with 0, 1, 2, 3
if ('0123'.indexOf(ch) >= 0 && !this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
code = code * 8 + octalValue(this.source[this.index++]);
}
}
return {
code: code,
octal: octal
};
};
;
// ECMA-262 11.6 Names and Keywords
Scanner.prototype.scanIdentifier = function () {
var type;
var start = this.index;
// Backslash (U+005C) starts an escaped character.
var id = (this.source.charCodeAt(start) === 0x5C) ? this.getComplexIdentifier() : this.getIdentifier();
// There is no keyword or literal with only one character.
// Thus, it must be an identifier.
if (id.length === 1) {
type = token_1.Token.Identifier;
}
else if (this.isKeyword(id)) {
type = token_1.Token.Keyword;
}
else if (id === 'null') {
type = token_1.Token.NullLiteral;
}
else if (id === 'true' || id === 'false') {
type = token_1.Token.BooleanLiteral;
}
else {
type = token_1.Token.Identifier;
}
return {
type: type,
value: id,
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
;
// ECMA-262 11.7 Punctuators
Scanner.prototype.scanPunctuator = function () {
var token = {
type: token_1.Token.Punctuator,
value: '',
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: this.index,
end: this.index
};
// Check for most common single-character punctuators.
var str = this.source[this.index];
switch (str) {
case '(':
case '{':
if (str === '{') {
this.curlyStack.push('{');
}
++this.index;
break;
case '.':
++this.index;
if (this.source[this.index] === '.' && this.source[this.index + 1] === '.') {
// Spread operator: ...
this.index += 2;
str = '...';
}
break;
case '}':
++this.index;
this.curlyStack.pop();
break;
case ')':
case ';':
case ',':
case '[':
case ']':
case ':':
case '?':
case '~':
++this.index;
break;
default:
// 4-character punctuator.
str = this.source.substr(this.index, 4);
if (str === '>>>=') {
this.index += 4;
}
else {
// 3-character punctuators.
str = str.substr(0, 3);
if (str === '===' || str === '!==' || str === '>>>' ||
str === '<<=' || str === '>>=' || str === '**=') {
this.index += 3;
}
else {
// 2-character punctuators.
str = str.substr(0, 2);
if (str === '&&' || str === '||' || str === '==' || str === '!=' ||
str === '+=' || str === '-=' || str === '*=' || str === '/=' ||
str === '++' || str === '--' || str === '<<' || str === '>>' ||
str === '&=' || str === '|=' || str === '^=' || str === '%=' ||
str === '<=' || str === '>=' || str === '=>' || str === '**') {
this.index += 2;
}
else {
// 1-character punctuators.
str = this.source[this.index];
if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
++this.index;
}
}
}
}
}
if (this.index === token.start) {
this.throwUnexpectedToken();
}
token.end = this.index;
token.value = str;
return token;
};
;
// ECMA-262 11.8.3 Numeric Literals
Scanner.prototype.scanHexLiteral = function (start) {
var number = '';
while (!this.eof()) {
if (!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
break;
}
number += this.source[this.index++];
}
if (number.length === 0) {
this.throwUnexpectedToken();
}
if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
this.throwUnexpectedToken();
}
return {
type: token_1.Token.NumericLiteral,
value: parseInt('0x' + number, 16),
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
;
Scanner.prototype.scanBinaryLiteral = function (start) {
var number = '';
var ch;
while (!this.eof()) {
ch = this.source[this.index];
if (ch !== '0' && ch !== '1') {
break;
}
number += this.source[this.index++];
}
if (number.length === 0) {
// only 0b or 0B
this.throwUnexpectedToken();
}
if (!this.eof()) {
ch = this.source.charCodeAt(this.index);
/* istanbul ignore else */
if (character_1.Character.isIdentifierStart(ch) || character_1.Character.isDecimalDigit(ch)) {
this.throwUnexpectedToken();
}
}
return {
type: token_1.Token.NumericLiteral,
value: parseInt(number, 2),
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
;
Scanner.prototype.scanOctalLiteral = function (prefix, start) {
var number = '';
var octal = false;
if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) {
octal = true;
number = '0' + this.source[this.index++];
}
else {
++this.index;
}
while (!this.eof()) {
if (!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
break;
}
number += this.source[this.index++];
}
if (!octal && number.length === 0) {
// only 0o or 0O
this.throwUnexpectedToken();
}
if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) || character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
this.throwUnexpectedToken();
}
return {
type: token_1.Token.NumericLiteral,
value: parseInt(number, 8),
octal: octal,
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
;
Scanner.prototype.isImplicitOctalLiteral = function () {
// Implicit octal, unless there is a non-octal digit.
// (Annex B.1.1 on Numeric Literals)
for (var i = this.index + 1; i < this.length; ++i) {
var ch = this.source[i];
if (ch === '8' || ch === '9') {
return false;
}
if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
return true;
}
}
return true;
};
;
Scanner.prototype.scanNumericLiteral = function () {
var start = this.index;
var ch = this.source[start];
assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point');
var number = '';
if (ch !== '.') {
number = this.source[this.index++];
ch = this.source[this.index];
// Hex number starts with '0x'.
// Octal number starts with '0'.
// Octal number in ES6 starts with '0o'.
// Binary number in ES6 starts with '0b'.
if (number === '0') {
if (ch === 'x' || ch === 'X') {
++this.index;
return this.scanHexLiteral(start);
}
if (ch === 'b' || ch === 'B') {
++this.index;
return this.scanBinaryLiteral(start);
}
if (ch === 'o' || ch === 'O') {
return this.scanOctalLiteral(ch, start);
}
if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
if (this.isImplicitOctalLiteral()) {
return this.scanOctalLiteral(ch, start);
}
}
}
while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
number += this.source[this.index++];
}
ch = this.source[this.index];
}
if (ch === '.') {
number += this.source[this.index++];
while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
number += this.source[this.index++];
}
ch = this.source[this.index];
}
if (ch === 'e' || ch === 'E') {
number += this.source[this.index++];
ch = this.source[this.index];
if (ch === '+' || ch === '-') {
number += this.source[this.index++];
}
if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
number += this.source[this.index++];
}
}
else {
this.throwUnexpectedToken();
}
}
if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
this.throwUnexpectedToken();
}
return {
type: token_1.Token.NumericLiteral,
value: parseFloat(number),
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
;
// ECMA-262 11.8.4 String Literals
Scanner.prototype.scanStringLiteral = function () {
var start = this.index;
var quote = this.source[start];
assert_1.assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote');
++this.index;
var octal = false;
var str = '';
while (!this.eof()) {
var ch = this.source[this.index++];
if (ch === quote) {
quote = '';
break;
}
else if (ch === '\\') {
ch = this.source[this.index++];
if (!ch || !character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
switch (ch) {
case 'u':
case 'x':
if (this.source[this.index] === '{') {
++this.index;
str += this.scanUnicodeCodePointEscape();
}
else {
var unescaped = this.scanHexEscape(ch);
if (!unescaped) {
this.throwUnexpectedToken();
}
str += unescaped;
}
break;
case 'n':
str += '\n';
break;
case 'r':
str += '\r';
break;
case 't':
str += '\t';
break;
case 'b':
str += '\b';
break;
case 'f':
str += '\f';
break;
case 'v':
str += '\x0B';
break;
case '8':
case '9':
str += ch;
this.tolerateUnexpectedToken();
break;
default:
if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
var octToDec = this.octalToDecimal(ch);
octal = octToDec.octal || octal;
str += String.fromCharCode(octToDec.code);
}
else {
str += ch;
}
break;
}
}
else {
++this.lineNumber;
if (ch === '\r' && this.source[this.index] === '\n') {
++this.index;
}
this.lineStart = this.index;
}
}
else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
break;
}
else {
str += ch;
}
}
if (quote !== '') {
this.index = start;
this.throwUnexpectedToken();
}
return {
type: token_1.Token.StringLiteral,
value: str,
octal: octal,
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
;
// ECMA-262 11.8.6 Template Literal Lexical Components
Scanner.prototype.scanTemplate = function () {
var cooked = '';
var terminated = false;
var start = this.index;
var head = (this.source[start] === '`');
var tail = false;
var rawOffset = 2;
++this.index;
while (!this.eof()) {
var ch = this.source[this.index++];
if (ch === '`') {
rawOffset = 1;
tail = true;
terminated = true;
break;
}
else if (ch === '$') {
if (this.source[this.index] === '{') {
this.curlyStack.push('${');
++this.index;
terminated = true;
break;
}
cooked += ch;
}
else if (ch === '\\') {
ch = this.source[this.index++];
if (!character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
switch (ch) {
case 'n':
cooked += '\n';
break;
case 'r':
cooked += '\r';
break;
case 't':
cooked += '\t';
break;
case 'u':
case 'x':
if (this.source[this.index] === '{') {
++this.index;
cooked += this.scanUnicodeCodePointEscape();
}
else {
var restore = this.index;
var unescaped = this.scanHexEscape(ch);
if (unescaped) {
cooked += unescaped;
}
else {
this.index = restore;
cooked += ch;
}
}
break;
case 'b':
cooked += '\b';
break;
case 'f':
cooked += '\f';
break;
case 'v':
cooked += '\v';
break;
default:
if (ch === '0') {
if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
// Illegal: \01 \02 and so on
this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
}
cooked += '\0';
}
else if (character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
// Illegal: \1 \2
this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
}
else {
cooked += ch;
}
break;
}
}
else {
++this.lineNumber;
if (ch === '\r' && this.source[this.index] === '\n') {
++this.index;
}
this.lineStart = this.index;
}
}
else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
++this.lineNumber;
if (ch === '\r' && this.source[this.index] === '\n') {
++this.index;
}
this.lineStart = this.index;
cooked += '\n';
}
else {
cooked += ch;
}
}
if (!terminated) {
this.throwUnexpectedToken();
}
if (!head) {
this.curlyStack.pop();
}
return {
type: token_1.Token.Template,
value: {
cooked: cooked,
raw: this.source.slice(start + 1, this.index - rawOffset)
},
head: head,
tail: tail,
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
;
// ECMA-262 11.8.5 Regular Expression Literals
Scanner.prototype.testRegExp = function (pattern, flags) {
// The BMP character to use as a replacement for astral symbols when
// translating an ES6 "u"-flagged pattern to an ES5-compatible
// approximation.
// Note: replacing with '\uFFFF' enables false positives in unlikely
// scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid
// pattern that would not be detected by this substitution.
var astralSubstitute = '\uFFFF';
var tmp = pattern;
var self = this;
if (flags.indexOf('u') >= 0) {
tmp = tmp
.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) {
var codePoint = parseInt($1 || $2, 16);
if (codePoint > 0x10FFFF) {
self.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
}
if (codePoint <= 0xFFFF) {
return String.fromCharCode(codePoint);
}
return astralSubstitute;
})
.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, astralSubstitute);
}
// First, detect invalid regular expressions.
try {
RegExp(tmp);
}
catch (e) {
this.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
}
// Return a regular expression object for this pattern-flag pair, or
// `null` in case the current environment doesn't support the flags it
// uses.
try {
return new RegExp(pattern, flags);
}
catch (exception) {
/* istanbul ignore next */
return null;
}
};
;
Scanner.prototype.scanRegExpBody = function () {
var ch = this.source[this.index];
assert_1.assert(ch === '/', 'Regular expression literal must start with a slash');
var str = this.source[this.index++];
var classMarker = false;
var terminated = false;
while (!this.eof()) {
ch = this.source[this.index++];
str += ch;
if (ch === '\\') {
ch = this.source[this.index++];
// ECMA-262 7.8.5
if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
}
str += ch;
}
else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
}
else if (classMarker) {
if (ch === ']') {
classMarker = false;
}
}
else {
if (ch === '/') {
terminated = true;
break;
}
else if (ch === '[') {
classMarker = true;
}
}
}
if (!terminated) {
this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
}
// Exclude leading and trailing slash.
var body = str.substr(1, str.length - 2);
return {
value: body,
literal: str
};
};
;
Scanner.prototype.scanRegExpFlags = function () {
var str = '';
var flags = '';
while (!this.eof()) {
var ch = this.source[this.index];
if (!character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
break;
}
++this.index;
if (ch === '\\' && !this.eof()) {
ch = this.source[this.index];
if (ch === 'u') {
++this.index;
var restore = this.index;
ch = this.scanHexEscape('u');
if (ch) {
flags += ch;
for (str += '\\u'; restore < this.index; ++restore) {
str += this.source[restore];
}
}
else {
this.index = restore;
flags += 'u';
str += '\\u';
}
this.tolerateUnexpectedToken();
}
else {
str += '\\';
this.tolerateUnexpectedToken();
}
}
else {
flags += ch;
str += ch;
}
}
return {
value: flags,
literal: str
};
};
;
Scanner.prototype.scanRegExp = function () {
var start = this.index;
var body = this.scanRegExpBody();
var flags = this.scanRegExpFlags();
var value = this.testRegExp(body.value, flags.value);
return {
type: token_1.Token.RegularExpression,
value: value,
literal: body.literal + flags.literal,
regex: {
pattern: body.value,
flags: flags.value
},
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
;
Scanner.prototype.lex = function () {
if (this.eof()) {
return {
type: token_1.Token.EOF,
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: this.index,
end: this.index
};
}
var cp = this.source.charCodeAt(this.index);
if (character_1.Character.isIdentifierStart(cp)) {
return this.scanIdentifier();
}
// Very common: ( and ) and ;
if (cp === 0x28 || cp === 0x29 || cp === 0x3B) {
return this.scanPunctuator();
}
// String literal starts with single quote (U+0027) or double quote (U+0022).
if (cp === 0x27 || cp === 0x22) {
return this.scanStringLiteral();
}
// Dot (.) U+002E can also start a floating-point number, hence the need
// to check the next character.
if (cp === 0x2E) {
if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) {
return this.scanNumericLiteral();
}
return this.scanPunctuator();
}
if (character_1.Character.isDecimalDigit(cp)) {
return this.scanNumericLiteral();
}
// Template literals start with ` (U+0060) for template head
// or } (U+007D) for template middle or template tail.
if (cp === 0x60 || (cp === 0x7D && this.curlyStack[this.curlyStack.length - 1] === '${')) {
return this.scanTemplate();
}
// Possible identifier start in a surrogate pair.
if (cp >= 0xD800 && cp < 0xDFFF) {
if (character_1.Character.isIdentifierStart(this.codePointAt(this.index))) {
return this.scanIdentifier();
}
}
return this.scanPunctuator();
};
;
return Scanner;
}());
exports.Scanner = Scanner;
/***/ },
/* 9 */
/***/ function(module, exports) {
"use strict";
// See also tools/generate-unicode-regex.js.
var Regex = {
// Unicode v8.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\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\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\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\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-\uA7AD\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\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[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\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]|\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]|\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]/,
// Unicode v8.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\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\u0C81-\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\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\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\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-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\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\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\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[\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]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\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]|\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]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\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]/
};
exports.Character = {
fromCodePoint: function (cp) {
return (cp < 0x10000) ? String.fromCharCode(cp) :
String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) +
String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023));
},
// ECMA-262 11.2 White Space
isWhiteSpace: function (cp) {
return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp === 0x0C) || (cp === 0xA0) ||
(cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(cp) >= 0);
},
// ECMA-262 11.3 Line Terminators
isLineTerminator: function (cp) {
return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029);
},
// ECMA-262 11.6 Identifier Names and Identifiers
isIdentifierStart: function (cp) {
return (cp === 0x24) || (cp === 0x5F) ||
(cp >= 0x41 && cp <= 0x5A) ||
(cp >= 0x61 && cp <= 0x7A) ||
(cp === 0x5C) ||
((cp >= 0x80) && Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp)));
},
isIdentifierPart: function (cp) {
return (cp === 0x24) || (cp === 0x5F) ||
(cp >= 0x41 && cp <= 0x5A) ||
(cp >= 0x61 && cp <= 0x7A) ||
(cp >= 0x30 && cp <= 0x39) ||
(cp === 0x5C) ||
((cp >= 0x80) && Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp)));
},
// ECMA-262 11.8.3 Numeric Literals
isDecimalDigit: function (cp) {
return (cp >= 0x30 && cp <= 0x39); // 0..9
},
isHexDigit: function (cp) {
return (cp >= 0x30 && cp <= 0x39) ||
(cp >= 0x41 && cp <= 0x46) ||
(cp >= 0x61 && cp <= 0x66); // a..f
},
isOctalDigit: function (cp) {
return (cp >= 0x30 && cp <= 0x37); // 0..7
}
};
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var syntax_1 = __webpack_require__(2);
var ArrayExpression = (function () {
function ArrayExpression(elements) {
this.type = syntax_1.Syntax.ArrayExpression;
this.elements = elements;
}
return ArrayExpression;
}());
exports.ArrayExpression = ArrayExpression;
var ArrayPattern = (function () {
function ArrayPattern(elements) {
this.type = syntax_1.Syntax.ArrayPattern;
this.elements = elements;
}
return ArrayPattern;
}());
exports.ArrayPattern = ArrayPattern;
var ArrowFunctionExpression = (function () {
function ArrowFunctionExpression(params, body, expression) {
this.type = syntax_1.Syntax.ArrowFunctionExpression;
this.id = null;
this.params = params;
this.body = body;
this.generator = false;
this.expression = expression;
}
return ArrowFunctionExpression;
}());
exports.ArrowFunctionExpression = ArrowFunctionExpression;
var AssignmentExpression = (function () {
function AssignmentExpression(operator, left, right) {
this.type = syntax_1.Syntax.AssignmentExpression;
this.operator = operator;
this.left = left;
this.right = right;
}
return AssignmentExpression;
}());
exports.AssignmentExpression = AssignmentExpression;
var AssignmentPattern = (function () {
function AssignmentPattern(left, right) {
this.type = syntax_1.Syntax.AssignmentPattern;
this.left = left;
this.right = right;
}
return AssignmentPattern;
}());
exports.AssignmentPattern = AssignmentPattern;
var BinaryExpression = (function () {
function BinaryExpression(operator, left, right) {
var logical = (operator === '||' || operator === '&&');
this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression;
this.operator = operator;
this.left = left;
this.right = right;
}
return BinaryExpression;
}());
exports.BinaryExpression = BinaryExpression;
var BlockStatement = (function () {
function BlockStatement(body) {
this.type = syntax_1.Syntax.BlockStatement;
this.body = body;
}
return BlockStatement;
}());
exports.BlockStatement = BlockStatement;
var BreakStatement = (function () {
function BreakStatement(label) {
this.type = syntax_1.Syntax.BreakStatement;
this.label = label;
}
return BreakStatement;
}());
exports.BreakStatement = BreakStatement;
var CallExpression = (function () {
function CallExpression(callee, args) {
this.type = syntax_1.Syntax.CallExpression;
this.callee = callee;
this.arguments = args;
}
return CallExpression;
}());
exports.CallExpression = CallExpression;
var CatchClause = (function () {
function CatchClause(param, body) {
this.type = syntax_1.Syntax.CatchClause;
this.param = param;
this.body = body;
}
return CatchClause;
}());
exports.CatchClause = CatchClause;
var ClassBody = (function () {
function ClassBody(body) {
this.type = syntax_1.Syntax.ClassBody;
this.body = body;
}
return ClassBody;
}());
exports.ClassBody = ClassBody;
var ClassDeclaration = (function () {
function ClassDeclaration(id, superClass, body) {
this.type = syntax_1.Syntax.ClassDeclaration;
this.id = id;
this.superClass = superClass;
this.body = body;
}
return ClassDeclaration;
}());
exports.ClassDeclaration = ClassDeclaration;
var ClassExpression = (function () {
function ClassExpression(id, superClass, body) {
this.type = syntax_1.Syntax.ClassExpression;
this.id = id;
this.superClass = superClass;
this.body = body;
}
return ClassExpression;
}());
exports.ClassExpression = ClassExpression;
var ComputedMemberExpression = (function () {
function ComputedMemberExpression(object, property) {
this.type = syntax_1.Syntax.MemberExpression;
this.computed = true;
this.object = object;
this.property = property;
}
return ComputedMemberExpression;
}());
exports.ComputedMemberExpression = ComputedMemberExpression;
var ConditionalExpression = (function () {
function ConditionalExpression(test, consequent, alternate) {
this.type = syntax_1.Syntax.ConditionalExpression;
this.test = test;
this.consequent = consequent;
this.alternate = alternate;
}
return ConditionalExpression;
}());
exports.ConditionalExpression = ConditionalExpression;
var ContinueStatement = (function () {
function ContinueStatement(label) {
this.type = syntax_1.Syntax.ContinueStatement;
this.label = label;
}
return ContinueStatement;
}());
exports.ContinueStatement = ContinueStatement;
var DebuggerStatement = (function () {
function DebuggerStatement() {
this.type = syntax_1.Syntax.DebuggerStatement;
}
return DebuggerStatement;
}());
exports.DebuggerStatement = DebuggerStatement;
var Directive = (function () {
function Directive(expression, directive) {
this.type = syntax_1.Syntax.ExpressionStatement;
this.expression = expression;
this.directive = directive;
}
return Directive;
}());
exports.Directive = Directive;
var DoWhileStatement = (function () {
function DoWhileStatement(body, test) {
this.type = syntax_1.Syntax.DoWhileStatement;
this.body = body;
this.test = test;
}
return DoWhileStatement;
}());
exports.DoWhileStatement = DoWhileStatement;
var EmptyStatement = (function () {
function EmptyStatement() {
this.type = syntax_1.Syntax.EmptyStatement;
}
return EmptyStatement;
}());
exports.EmptyStatement = EmptyStatement;
var ExportAllDeclaration = (function () {
function ExportAllDeclaration(source) {
this.type = syntax_1.Syntax.ExportAllDeclaration;
this.source = source;
}
return ExportAllDeclaration;
}());
exports.ExportAllDeclaration = ExportAllDeclaration;
var ExportDefaultDeclaration = (function () {
function ExportDefaultDeclaration(declaration) {
this.type = syntax_1.Syntax.ExportDefaultDeclaration;
this.declaration = declaration;
}
return ExportDefaultDeclaration;
}());
exports.ExportDefaultDeclaration = ExportDefaultDeclaration;
var ExportNamedDeclaration = (function () {
function ExportNamedDeclaration(declaration, specifiers, source) {
this.type = syntax_1.Syntax.ExportNamedDeclaration;
this.declaration = declaration;
this.specifiers = specifiers;
this.source = source;
}
return ExportNamedDeclaration;
}());
exports.ExportNamedDeclaration = ExportNamedDeclaration;
var ExportSpecifier = (function () {
function ExportSpecifier(local, exported) {
this.type = syntax_1.Syntax.ExportSpecifier;
this.exported = exported;
this.local = local;
}
return ExportSpecifier;
}());
exports.ExportSpecifier = ExportSpecifier;
var ExpressionStatement = (function () {
function ExpressionStatement(expression) {
this.type = syntax_1.Syntax.ExpressionStatement;
this.expression = expression;
}
return ExpressionStatement;
}());
exports.ExpressionStatement = ExpressionStatement;
var ForInStatement = (function () {
function ForInStatement(left, right, body) {
this.type = syntax_1.Syntax.ForInStatement;
this.left = left;
this.right = right;
this.body = body;
this.each = false;
}
return ForInStatement;
}());
exports.ForInStatement = ForInStatement;
var ForOfStatement = (function () {
function ForOfStatement(left, right, body) {
this.type = syntax_1.Syntax.ForOfStatement;
this.left = left;
this.right = right;
this.body = body;
}
return ForOfStatement;
}());
exports.ForOfStatement = ForOfStatement;
var ForStatement = (function () {
function ForStatement(init, test, update, body) {
this.type = syntax_1.Syntax.ForStatement;
this.init = init;
this.test = test;
this.update = update;
this.body = body;
}
return ForStatement;
}());
exports.ForStatement = ForStatement;
var FunctionDeclaration = (function () {
function FunctionDeclaration(id, params, body, generator) {
this.type = syntax_1.Syntax.FunctionDeclaration;
this.id = id;
this.params = params;
this.body = body;
this.generator = generator;
this.expression = false;
}
return FunctionDeclaration;
}());
exports.FunctionDeclaration = FunctionDeclaration;
var FunctionExpression = (function () {
function FunctionExpression(id, params, body, generator) {
this.type = syntax_1.Syntax.FunctionExpression;
this.id = id;
this.params = params;
this.body = body;
this.generator = generator;
this.expression = false;
}
return FunctionExpression;
}());
exports.FunctionExpression = FunctionExpression;
var Identifier = (function () {
function Identifier(name) {
this.type = syntax_1.Syntax.Identifier;
this.name = name;
}
return Identifier;
}());
exports.Identifier = Identifier;
var IfStatement = (function () {
function IfStatement(test, consequent, alternate) {
this.type = syntax_1.Syntax.IfStatement;
this.test = test;
this.consequent = consequent;
this.alternate = alternate;
}
return IfStatement;
}());
exports.IfStatement = IfStatement;
var ImportDeclaration = (function () {
function ImportDeclaration(specifiers, source) {
this.type = syntax_1.Syntax.ImportDeclaration;
this.specifiers = specifiers;
this.source = source;
}
return ImportDeclaration;
}());
exports.ImportDeclaration = ImportDeclaration;
var ImportDefaultSpecifier = (function () {
function ImportDefaultSpecifier(local) {
this.type = syntax_1.Syntax.ImportDefaultSpecifier;
this.local = local;
}
return ImportDefaultSpecifier;
}());
exports.ImportDefaultSpecifier = ImportDefaultSpecifier;
var ImportNamespaceSpecifier = (function () {
function ImportNamespaceSpecifier(local) {
this.type = syntax_1.Syntax.ImportNamespaceSpecifier;
this.local = local;
}
return ImportNamespaceSpecifier;
}());
exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier;
var ImportSpecifier = (function () {
function ImportSpecifier(local, imported) {
this.type = syntax_1.Syntax.ImportSpecifier;
this.local = local;
this.imported = imported;
}
return ImportSpecifier;
}());
exports.ImportSpecifier = ImportSpecifier;
var LabeledStatement = (function () {
function LabeledStatement(label, body) {
this.type = syntax_1.Syntax.LabeledStatement;
this.label = label;
this.body = body;
}
return LabeledStatement;
}());
exports.LabeledStatement = LabeledStatement;
var Literal = (function () {
function Literal(value, raw) {
this.type = syntax_1.Syntax.Literal;
this.value = value;
this.raw = raw;
}
return Literal;
}());
exports.Literal = Literal;
var MetaProperty = (function () {
function MetaProperty(meta, property) {
this.type = syntax_1.Syntax.MetaProperty;
this.meta = meta;
this.property = property;
}
return MetaProperty;
}());
exports.MetaProperty = MetaProperty;
var MethodDefinition = (function () {
function MethodDefinition(key, computed, value, kind, isStatic) {
this.type = syntax_1.Syntax.MethodDefinition;
this.key = key;
this.computed = computed;
this.value = value;
this.kind = kind;
this.static = isStatic;
}
return MethodDefinition;
}());
exports.MethodDefinition = MethodDefinition;
var NewExpression = (function () {
function NewExpression(callee, args) {
this.type = syntax_1.Syntax.NewExpression;
this.callee = callee;
this.arguments = args;
}
return NewExpression;
}());
exports.NewExpression = NewExpression;
var ObjectExpression = (function () {
function ObjectExpression(properties) {
this.type = syntax_1.Syntax.ObjectExpression;
this.properties = properties;
}
return ObjectExpression;
}());
exports.ObjectExpression = ObjectExpression;
var ObjectPattern = (function () {
function ObjectPattern(properties) {
this.type = syntax_1.Syntax.ObjectPattern;
this.properties = properties;
}
return ObjectPattern;
}());
exports.ObjectPattern = ObjectPattern;
var Program = (function () {
function Program(body, sourceType) {
this.type = syntax_1.Syntax.Program;
this.body = body;
this.sourceType = sourceType;
}
return Program;
}());
exports.Program = Program;
var Property = (function () {
function Property(kind, key, computed, value, method, shorthand) {
this.type = syntax_1.Syntax.Property;
this.key = key;
this.computed = computed;
this.value = value;
this.kind = kind;
this.method = method;
this.shorthand = shorthand;
}
return Property;
}());
exports.Property = Property;
var RegexLiteral = (function () {
function RegexLiteral(value, raw, regex) {
this.type = syntax_1.Syntax.Literal;
this.value = value;
this.raw = raw;
this.regex = regex;
}
return RegexLiteral;
}());
exports.RegexLiteral = RegexLiteral;
var RestElement = (function () {
function RestElement(argument) {
this.type = syntax_1.Syntax.RestElement;
this.argument = argument;
}
return RestElement;
}());
exports.RestElement = RestElement;
var ReturnStatement = (function () {
function ReturnStatement(argument) {
this.type = syntax_1.Syntax.ReturnStatement;
this.argument = argument;
}
return ReturnStatement;
}());
exports.ReturnStatement = ReturnStatement;
var SequenceExpression = (function () {
function SequenceExpression(expressions) {
this.type = syntax_1.Syntax.SequenceExpression;
this.expressions = expressions;
}
return SequenceExpression;
}());
exports.SequenceExpression = SequenceExpression;
var SpreadElement = (function () {
function SpreadElement(argument) {
this.type = syntax_1.Syntax.SpreadElement;
this.argument = argument;
}
return SpreadElement;
}());
exports.SpreadElement = SpreadElement;
var StaticMemberExpression = (function () {
function StaticMemberExpression(object, property) {
this.type = syntax_1.Syntax.MemberExpression;
this.computed = false;
this.object = object;
this.property = property;
}
return StaticMemberExpression;
}());
exports.StaticMemberExpression = StaticMemberExpression;
var Super = (function () {
function Super() {
this.type = syntax_1.Syntax.Super;
}
return Super;
}());
exports.Super = Super;
var SwitchCase = (function () {
function SwitchCase(test, consequent) {
this.type = syntax_1.Syntax.SwitchCase;
this.test = test;
this.consequent = consequent;
}
return SwitchCase;
}());
exports.SwitchCase = SwitchCase;
var SwitchStatement = (function () {
function SwitchStatement(discriminant, cases) {
this.type = syntax_1.Syntax.SwitchStatement;
this.discriminant = discriminant;
this.cases = cases;
}
return SwitchStatement;
}());
exports.SwitchStatement = SwitchStatement;
var TaggedTemplateExpression = (function () {
function TaggedTemplateExpression(tag, quasi) {
this.type = syntax_1.Syntax.TaggedTemplateExpression;
this.tag = tag;
this.quasi = quasi;
}
return TaggedTemplateExpression;
}());
exports.TaggedTemplateExpression = TaggedTemplateExpression;
var TemplateElement = (function () {
function TemplateElement(value, tail) {
this.type = syntax_1.Syntax.TemplateElement;
this.value = value;
this.tail = tail;
}
return TemplateElement;
}());
exports.TemplateElement = TemplateElement;
var TemplateLiteral = (function () {
function TemplateLiteral(quasis, expressions) {
this.type = syntax_1.Syntax.TemplateLiteral;
this.quasis = quasis;
this.expressions = expressions;
}
return TemplateLiteral;
}());
exports.TemplateLiteral = TemplateLiteral;
var ThisExpression = (function () {
function ThisExpression() {
this.type = syntax_1.Syntax.ThisExpression;
}
return ThisExpression;
}());
exports.ThisExpression = ThisExpression;
var ThrowStatement = (function () {
function ThrowStatement(argument) {
this.type = syntax_1.Syntax.ThrowStatement;
this.argument = argument;
}
return ThrowStatement;
}());
exports.ThrowStatement = ThrowStatement;
var TryStatement = (function () {
function TryStatement(block, handler, finalizer) {
this.type = syntax_1.Syntax.TryStatement;
this.block = block;
this.handler = handler;
this.finalizer = finalizer;
}
return TryStatement;
}());
exports.TryStatement = TryStatement;
var UnaryExpression = (function () {
function UnaryExpression(operator, argument) {
this.type = syntax_1.Syntax.UnaryExpression;
this.operator = operator;
this.argument = argument;
this.prefix = true;
}
return UnaryExpression;
}());
exports.UnaryExpression = UnaryExpression;
var UpdateExpression = (function () {
function UpdateExpression(operator, argument, prefix) {
this.type = syntax_1.Syntax.UpdateExpression;
this.operator = operator;
this.argument = argument;
this.prefix = prefix;
}
return UpdateExpression;
}());
exports.UpdateExpression = UpdateExpression;
var VariableDeclaration = (function () {
function VariableDeclaration(declarations, kind) {
this.type = syntax_1.Syntax.VariableDeclaration;
this.declarations = declarations;
this.kind = kind;
}
return VariableDeclaration;
}());
exports.VariableDeclaration = VariableDeclaration;
var VariableDeclarator = (function () {
function VariableDeclarator(id, init) {
this.type = syntax_1.Syntax.VariableDeclarator;
this.id = id;
this.init = init;
}
return VariableDeclarator;
}());
exports.VariableDeclarator = VariableDeclarator;
var WhileStatement = (function () {
function WhileStatement(test, body) {
this.type = syntax_1.Syntax.WhileStatement;
this.test = test;
this.body = body;
}
return WhileStatement;
}());
exports.WhileStatement = WhileStatement;
var WithStatement = (function () {
function WithStatement(object, body) {
this.type = syntax_1.Syntax.WithStatement;
this.object = object;
this.body = body;
}
return WithStatement;
}());
exports.WithStatement = WithStatement;
var YieldExpression = (function () {
function YieldExpression(argument, delegate) {
this.type = syntax_1.Syntax.YieldExpression;
this.argument = argument;
this.delegate = delegate;
}
return YieldExpression;
}());
exports.YieldExpression = YieldExpression;
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
/* istanbul ignore next */
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var character_1 = __webpack_require__(9);
var token_1 = __webpack_require__(7);
var parser_1 = __webpack_require__(3);
var xhtml_entities_1 = __webpack_require__(12);
var jsx_syntax_1 = __webpack_require__(13);
var Node = __webpack_require__(10);
var JSXNode = __webpack_require__(14);
var JSXToken;
(function (JSXToken) {
JSXToken[JSXToken["Identifier"] = 100] = "Identifier";
JSXToken[JSXToken["Text"] = 101] = "Text";
})(JSXToken || (JSXToken = {}));
token_1.TokenName[JSXToken.Identifier] = 'JSXIdentifier';
token_1.TokenName[JSXToken.Text] = 'JSXText';
// Fully qualified element name, e.g. <svg:path> returns "svg:path"
function getQualifiedElementName(elementName) {
var qualifiedName;
switch (elementName.type) {
case jsx_syntax_1.JSXSyntax.JSXIdentifier:
var id = (elementName);
qualifiedName = id.name;
break;
case jsx_syntax_1.JSXSyntax.JSXNamespacedName:
var ns = (elementName);
qualifiedName = getQualifiedElementName(ns.namespace) + ':' +
getQualifiedElementName(ns.name);
break;
case jsx_syntax_1.JSXSyntax.JSXMemberExpression:
var expr = (elementName);
qualifiedName = getQualifiedElementName(expr.object) + '.' +
getQualifiedElementName(expr.property);
break;
}
return qualifiedName;
}
var JSXParser = (function (_super) {
__extends(JSXParser, _super);
function JSXParser(code, options, delegate) {
_super.call(this, code, options, delegate);
}
JSXParser.prototype.parsePrimaryExpression = function () {
return this.match('<') ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this);
};
JSXParser.prototype.startJSX = function () {
// Unwind the scanner before the lookahead token.
this.scanner.index = this.startMarker.index;
this.scanner.lineNumber = this.startMarker.lineNumber;
this.scanner.lineStart = this.startMarker.lineStart;
};
JSXParser.prototype.finishJSX = function () {
// Prime the next lookahead.
this.nextToken();
};
JSXParser.prototype.reenterJSX = function () {
this.startJSX();
this.expectJSX('}');
// Pop the closing '}' added from the lookahead.
if (this.config.tokens) {
this.tokens.pop();
}
};
JSXParser.prototype.createJSXNode = function () {
this.collectComments();
return {
index: this.scanner.index,
line: this.scanner.lineNumber,
column: this.scanner.index - this.scanner.lineStart
};
};
JSXParser.prototype.createJSXChildNode = function () {
return {
index: this.scanner.index,
line: this.scanner.lineNumber,
column: this.scanner.index - this.scanner.lineStart
};
};
JSXParser.prototype.scanXHTMLEntity = function (quote) {
var result = '&';
var valid = true;
var terminated = false;
var numeric = false;
var hex = false;
while (!this.scanner.eof() && valid && !terminated) {
var ch = this.scanner.source[this.scanner.index];
if (ch === quote) {
break;
}
terminated = (ch === ';');
result += ch;
++this.scanner.index;
if (!terminated) {
switch (result.length) {
case 2:
// e.g. '{'
numeric = (ch === '#');
break;
case 3:
if (numeric) {
// e.g. 'A'
hex = (ch === 'x');
valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0));
numeric = numeric && !hex;
}
break;
default:
valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0)));
valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0)));
break;
}
}
}
if (valid && terminated && result.length > 2) {
// e.g. 'A' becomes just '#x41'
var str = result.substr(1, result.length - 2);
if (numeric && str.length > 1) {
result = String.fromCharCode(parseInt(str.substr(1), 10));
}
else if (hex && str.length > 2) {
result = String.fromCharCode(parseInt('0' + str.substr(1), 16));
}
else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) {
result = xhtml_entities_1.XHTMLEntities[str];
}
}
return result;
};
// Scan the next JSX token. This replaces Scanner#lex when in JSX mode.
JSXParser.prototype.lexJSX = function () {
var cp = this.scanner.source.charCodeAt(this.scanner.index);
// < > / : = { }
if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) {
var value = this.scanner.source[this.scanner.index++];
return {
type: token_1.Token.Punctuator,
value: value,
lineNumber: this.scanner.lineNumber,
lineStart: this.scanner.lineStart,
start: this.scanner.index - 1,
end: this.scanner.index
};
}
// " '
if (cp === 34 || cp === 39) {
var start = this.scanner.index;
var quote = this.scanner.source[this.scanner.index++];
var str = '';
while (!this.scanner.eof()) {
var ch = this.scanner.source[this.scanner.index++];
if (ch === quote) {
break;
}
else if (ch === '&') {
str += this.scanXHTMLEntity(quote);
}
else {
str += ch;
}
}
return {
type: token_1.Token.StringLiteral,
value: str,
lineNumber: this.scanner.lineNumber,
lineStart: this.scanner.lineStart,
start: start,
end: this.scanner.index
};
}
// ... or .
if (cp === 46) {
var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1);
var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2);
var value = (n1 === 46 && n2 === 46) ? '...' : '.';
var start = this.scanner.index;
this.scanner.index += value.length;
return {
type: token_1.Token.Punctuator,
value: value,
lineNumber: this.scanner.lineNumber,
lineStart: this.scanner.lineStart,
start: start,
end: this.scanner.index
};
}
// `
if (cp === 96) {
// Only placeholder, since it will be rescanned as a real assignment expression.
return {
type: token_1.Token.Template,
lineNumber: this.scanner.lineNumber,
lineStart: this.scanner.lineStart,
start: this.scanner.index,
end: this.scanner.index
};
}
// Identifer can not contain backslash (char code 92).
if (character_1.Character.isIdentifierStart(cp) && (cp !== 92)) {
var start = this.scanner.index;
++this.scanner.index;
while (!this.scanner.eof()) {
var ch = this.scanner.source.charCodeAt(this.scanner.index);
if (character_1.Character.isIdentifierPart(ch) && (ch !== 92)) {
++this.scanner.index;
}
else if (ch === 45) {
// Hyphen (char code 45) can be part of an identifier.
++this.scanner.index;
}
else {
break;
}
}
var id = this.scanner.source.slice(start, this.scanner.index);
return {
type: JSXToken.Identifier,
value: id,
lineNumber: this.scanner.lineNumber,
lineStart: this.scanner.lineStart,
start: start,
end: this.scanner.index
};
}
this.scanner.throwUnexpectedToken();
};
JSXParser.prototype.nextJSXToken = function () {
this.collectComments();
this.startMarker.index = this.scanner.index;
this.startMarker.lineNumber = this.scanner.lineNumber;
this.startMarker.lineStart = this.scanner.lineStart;
var token = this.lexJSX();
this.lastMarker.index = this.scanner.index;
this.lastMarker.lineNumber = this.scanner.lineNumber;
this.lastMarker.lineStart = this.scanner.lineStart;
if (this.config.tokens) {
this.tokens.push(this.convertToken(token));
}
return token;
};
JSXParser.prototype.nextJSXText = function () {
this.startMarker.index = this.scanner.index;
this.startMarker.lineNumber = this.scanner.lineNumber;
this.startMarker.lineStart = this.scanner.lineStart;
var start = this.scanner.index;
var text = '';
while (!this.scanner.eof()) {
var ch = this.scanner.source[this.scanner.index];
if (ch === '{' || ch === '<') {
break;
}
++this.scanner.index;
text += ch;
if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
++this.scanner.lineNumber;
if (ch === '\r' && this.scanner.source[this.scanner.index] === '\n') {
++this.scanner.index;
}
this.scanner.lineStart = this.scanner.index;
}
}
this.lastMarker.index = this.scanner.index;
this.lastMarker.lineNumber = this.scanner.lineNumber;
this.lastMarker.lineStart = this.scanner.lineStart;
var token = {
type: JSXToken.Text,
value: text,
lineNumber: this.scanner.lineNumber,
lineStart: this.scanner.lineStart,
start: start,
end: this.scanner.index
};
if ((text.length > 0) && this.config.tokens) {
this.tokens.push(this.convertToken(token));
}
return token;
};
JSXParser.prototype.peekJSXToken = function () {
var previousIndex = this.scanner.index;
var previousLineNumber = this.scanner.lineNumber;
var previousLineStart = this.scanner.lineStart;
this.scanner.scanComments();
var next = this.lexJSX();
this.scanner.index = previousIndex;
this.scanner.lineNumber = previousLineNumber;
this.scanner.lineStart = previousLineStart;
return next;
};
// Expect the next JSX token to match the specified punctuator.
// If not, an exception will be thrown.
JSXParser.prototype.expectJSX = function (value) {
var token = this.nextJSXToken();
if (token.type !== token_1.Token.Punctuator || token.value !== value) {
this.throwUnexpectedToken(token);
}
};
// Return true if the next JSX token matches the specified punctuator.
JSXParser.prototype.matchJSX = function (value) {
var next = this.peekJSXToken();
return next.type === token_1.Token.Punctuator && next.value === value;
};
JSXParser.prototype.parseJSXIdentifier = function () {
var node = this.createJSXNode();
var token = this.nextJSXToken();
if (token.type !== JSXToken.Identifier) {
this.throwUnexpectedToken(token);
}
return this.finalize(node, new JSXNode.JSXIdentifier(token.value));
};
JSXParser.prototype.parseJSXElementName = function () {
var node = this.createJSXNode();
var elementName = this.parseJSXIdentifier();
if (this.matchJSX(':')) {
var namespace = elementName;
this.expectJSX(':');
var name_1 = this.parseJSXIdentifier();
elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1));
}
else if (this.matchJSX('.')) {
while (this.matchJSX('.')) {
var object = elementName;
this.expectJSX('.');
var property = this.parseJSXIdentifier();
elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property));
}
}
return elementName;
};
JSXParser.prototype.parseJSXAttributeName = function () {
var node = this.createJSXNode();
var attributeName;
var identifier = this.parseJSXIdentifier();
if (this.matchJSX(':')) {
var namespace = identifier;
this.expectJSX(':');
var name_2 = this.parseJSXIdentifier();
attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2));
}
else {
attributeName = identifier;
}
return attributeName;
};
JSXParser.prototype.parseJSXStringLiteralAttribute = function () {
var node = this.createJSXNode();
var token = this.nextJSXToken();
if (token.type !== token_1.Token.StringLiteral) {
this.throwUnexpectedToken(token);
}
var raw = this.getTokenRaw(token);
return this.finalize(node, new Node.Literal(token.value, raw));
};
JSXParser.prototype.parseJSXExpressionAttribute = function () {
var node = this.createJSXNode();
this.expectJSX('{');
this.finishJSX();
if (this.match('}')) {
this.tolerateError('JSX attributes must only be assigned a non-empty expression');
}
var expression = this.parseAssignmentExpression();
this.reenterJSX();
return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
};
JSXParser.prototype.parseJSXAttributeValue = function () {
return this.matchJSX('{') ? this.parseJSXExpressionAttribute() :
this.matchJSX('<') ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute();
};
JSXParser.prototype.parseJSXNameValueAttribute = function () {
var node = this.createJSXNode();
var name = this.parseJSXAttributeName();
var value = null;
if (this.matchJSX('=')) {
this.expectJSX('=');
value = this.parseJSXAttributeValue();
}
return this.finalize(node, new JSXNode.JSXAttribute(name, value));
};
JSXParser.prototype.parseJSXSpreadAttribute = function () {
var node = this.createJSXNode();
this.expectJSX('{');
this.expectJSX('...');
this.finishJSX();
var argument = this.parseAssignmentExpression();
this.reenterJSX();
return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument));
};
JSXParser.prototype.parseJSXAttributes = function () {
var attributes = [];
while (!this.matchJSX('/') && !this.matchJSX('>')) {
var attribute = this.matchJSX('{') ? this.parseJSXSpreadAttribute() :
this.parseJSXNameValueAttribute();
attributes.push(attribute);
}
return attributes;
};
JSXParser.prototype.parseJSXOpeningElement = function () {
var node = this.createJSXNode();
this.expectJSX('<');
var name = this.parseJSXElementName();
var attributes = this.parseJSXAttributes();
var selfClosing = this.matchJSX('/');
if (selfClosing) {
this.expectJSX('/');
}
this.expectJSX('>');
return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
};
JSXParser.prototype.parseJSXBoundaryElement = function () {
var node = this.createJSXNode();
this.expectJSX('<');
if (this.matchJSX('/')) {
this.expectJSX('/');
var name_3 = this.parseJSXElementName();
this.expectJSX('>');
return this.finalize(node, new JSXNode.JSXClosingElement(name_3));
}
var name = this.parseJSXElementName();
var attributes = this.parseJSXAttributes();
var selfClosing = this.matchJSX('/');
if (selfClosing) {
this.expectJSX('/');
}
this.expectJSX('>');
return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
};
JSXParser.prototype.parseJSXEmptyExpression = function () {
var node = this.createJSXChildNode();
this.collectComments();
this.lastMarker.index = this.scanner.index;
this.lastMarker.lineNumber = this.scanner.lineNumber;
this.lastMarker.lineStart = this.scanner.lineStart;
return this.finalize(node, new JSXNode.JSXEmptyExpression());
};
JSXParser.prototype.parseJSXExpressionContainer = function () {
var node = this.createJSXNode();
this.expectJSX('{');
var expression;
if (this.matchJSX('}')) {
expression = this.parseJSXEmptyExpression();
this.expectJSX('}');
}
else {
this.finishJSX();
expression = this.parseAssignmentExpression();
this.reenterJSX();
}
return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
};
JSXParser.prototype.parseJSXChildren = function () {
var children = [];
while (!this.scanner.eof()) {
var node = this.createJSXChildNode();
var token = this.nextJSXText();
if (token.start < token.end) {
var raw = this.getTokenRaw(token);
var child = this.finalize(node, new JSXNode.JSXText(token.value, raw));
children.push(child);
}
if (this.scanner.source[this.scanner.index] === '{') {
var container = this.parseJSXExpressionContainer();
children.push(container);
}
else {
break;
}
}
return children;
};
JSXParser.prototype.parseComplexJSXElement = function (el) {
var stack = [];
while (!this.scanner.eof()) {
el.children = el.children.concat(this.parseJSXChildren());
var node = this.createJSXChildNode();
var element = this.parseJSXBoundaryElement();
if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) {
var opening = (element);
if (opening.selfClosing) {
var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null));
el.children.push(child);
}
else {
stack.push(el);
el = { node: node, opening: opening, closing: null, children: [] };
}
}
if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) {
el.closing = (element);
var open_1 = getQualifiedElementName(el.opening.name);
var close_1 = getQualifiedElementName(el.closing.name);
if (open_1 !== close_1) {
this.tolerateError('Expected corresponding JSX closing tag for %0', open_1);
}
if (stack.length > 0) {
var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing));
el = stack.pop();
el.children.push(child);
}
else {
break;
}
}
}
return el;
};
JSXParser.prototype.parseJSXElement = function () {
var node = this.createJSXNode();
var opening = this.parseJSXOpeningElement();
var children = [];
var closing = null;
if (!opening.selfClosing) {
var el = this.parseComplexJSXElement({ node: node, opening: opening, closing: closing, children: children });
children = el.children;
closing = el.closing;
}
return this.finalize(node, new JSXNode.JSXElement(opening, children, closing));
};
JSXParser.prototype.parseJSXRoot = function () {
// Pop the opening '<' added from the lookahead.
if (this.config.tokens) {
this.tokens.pop();
}
this.startJSX();
var element = this.parseJSXElement();
this.finishJSX();
return element;
};
return JSXParser;
}(parser_1.Parser));
exports.JSXParser = JSXParser;
/***/ },
/* 12 */
/***/ function(module, exports) {
// Generated by generate-xhtml-entities.js. DO NOT MODIFY!
"use strict";
exports.XHTMLEntities = {
quot: '\u0022',
amp: '\u0026',
apos: '\u0027',
gt: '\u003E',
nbsp: '\u00A0',
iexcl: '\u00A1',
cent: '\u00A2',
pound: '\u00A3',
curren: '\u00A4',
yen: '\u00A5',
brvbar: '\u00A6',
sect: '\u00A7',
uml: '\u00A8',
copy: '\u00A9',
ordf: '\u00AA',
laquo: '\u00AB',
not: '\u00AC',
shy: '\u00AD',
reg: '\u00AE',
macr: '\u00AF',
deg: '\u00B0',
plusmn: '\u00B1',
sup2: '\u00B2',
sup3: '\u00B3',
acute: '\u00B4',
micro: '\u00B5',
para: '\u00B6',
middot: '\u00B7',
cedil: '\u00B8',
sup1: '\u00B9',
ordm: '\u00BA',
raquo: '\u00BB',
frac14: '\u00BC',
frac12: '\u00BD',
frac34: '\u00BE',
iquest: '\u00BF',
Agrave: '\u00C0',
Aacute: '\u00C1',
Acirc: '\u00C2',
Atilde: '\u00C3',
Auml: '\u00C4',
Aring: '\u00C5',
AElig: '\u00C6',
Ccedil: '\u00C7',
Egrave: '\u00C8',
Eacute: '\u00C9',
Ecirc: '\u00CA',
Euml: '\u00CB',
Igrave: '\u00CC',
Iacute: '\u00CD',
Icirc: '\u00CE',
Iuml: '\u00CF',
ETH: '\u00D0',
Ntilde: '\u00D1',
Ograve: '\u00D2',
Oacute: '\u00D3',
Ocirc: '\u00D4',
Otilde: '\u00D5',
Ouml: '\u00D6',
times: '\u00D7',
Oslash: '\u00D8',
Ugrave: '\u00D9',
Uacute: '\u00DA',
Ucirc: '\u00DB',
Uuml: '\u00DC',
Yacute: '\u00DD',
THORN: '\u00DE',
szlig: '\u00DF',
agrave: '\u00E0',
aacute: '\u00E1',
acirc: '\u00E2',
atilde: '\u00E3',
auml: '\u00E4',
aring: '\u00E5',
aelig: '\u00E6',
ccedil: '\u00E7',
egrave: '\u00E8',
eacute: '\u00E9',
ecirc: '\u00EA',
euml: '\u00EB',
igrave: '\u00EC',
iacute: '\u00ED',
icirc: '\u00EE',
iuml: '\u00EF',
eth: '\u00F0',
ntilde: '\u00F1',
ograve: '\u00F2',
oacute: '\u00F3',
ocirc: '\u00F4',
otilde: '\u00F5',
ouml: '\u00F6',
divide: '\u00F7',
oslash: '\u00F8',
ugrave: '\u00F9',
uacute: '\u00FA',
ucirc: '\u00FB',
uuml: '\u00FC',
yacute: '\u00FD',
thorn: '\u00FE',
yuml: '\u00FF',
OElig: '\u0152',
oelig: '\u0153',
Scaron: '\u0160',
scaron: '\u0161',
Yuml: '\u0178',
fnof: '\u0192',
circ: '\u02C6',
tilde: '\u02DC',
Alpha: '\u0391',
Beta: '\u0392',
Gamma: '\u0393',
Delta: '\u0394',
Epsilon: '\u0395',
Zeta: '\u0396',
Eta: '\u0397',
Theta: '\u0398',
Iota: '\u0399',
Kappa: '\u039A',
Lambda: '\u039B',
Mu: '\u039C',
Nu: '\u039D',
Xi: '\u039E',
Omicron: '\u039F',
Pi: '\u03A0',
Rho: '\u03A1',
Sigma: '\u03A3',
Tau: '\u03A4',
Upsilon: '\u03A5',
Phi: '\u03A6',
Chi: '\u03A7',
Psi: '\u03A8',
Omega: '\u03A9',
alpha: '\u03B1',
beta: '\u03B2',
gamma: '\u03B3',
delta: '\u03B4',
epsilon: '\u03B5',
zeta: '\u03B6',
eta: '\u03B7',
theta: '\u03B8',
iota: '\u03B9',
kappa: '\u03BA',
lambda: '\u03BB',
mu: '\u03BC',
nu: '\u03BD',
xi: '\u03BE',
omicron: '\u03BF',
pi: '\u03C0',
rho: '\u03C1',
sigmaf: '\u03C2',
sigma: '\u03C3',
tau: '\u03C4',
upsilon: '\u03C5',
phi: '\u03C6',
chi: '\u03C7',
psi: '\u03C8',
omega: '\u03C9',
thetasym: '\u03D1',
upsih: '\u03D2',
piv: '\u03D6',
ensp: '\u2002',
emsp: '\u2003',
thinsp: '\u2009',
zwnj: '\u200C',
zwj: '\u200D',
lrm: '\u200E',
rlm: '\u200F',
ndash: '\u2013',
mdash: '\u2014',
lsquo: '\u2018',
rsquo: '\u2019',
sbquo: '\u201A',
ldquo: '\u201C',
rdquo: '\u201D',
bdquo: '\u201E',
dagger: '\u2020',
Dagger: '\u2021',
bull: '\u2022',
hellip: '\u2026',
permil: '\u2030',
prime: '\u2032',
Prime: '\u2033',
lsaquo: '\u2039',
rsaquo: '\u203A',
oline: '\u203E',
frasl: '\u2044',
euro: '\u20AC',
image: '\u2111',
weierp: '\u2118',
real: '\u211C',
trade: '\u2122',
alefsym: '\u2135',
larr: '\u2190',
uarr: '\u2191',
rarr: '\u2192',
darr: '\u2193',
harr: '\u2194',
crarr: '\u21B5',
lArr: '\u21D0',
uArr: '\u21D1',
rArr: '\u21D2',
dArr: '\u21D3',
hArr: '\u21D4',
forall: '\u2200',
part: '\u2202',
exist: '\u2203',
empty: '\u2205',
nabla: '\u2207',
isin: '\u2208',
notin: '\u2209',
ni: '\u220B',
prod: '\u220F',
sum: '\u2211',
minus: '\u2212',
lowast: '\u2217',
radic: '\u221A',
prop: '\u221D',
infin: '\u221E',
ang: '\u2220',
and: '\u2227',
or: '\u2228',
cap: '\u2229',
cup: '\u222A',
int: '\u222B',
there4: '\u2234',
sim: '\u223C',
cong: '\u2245',
asymp: '\u2248',
ne: '\u2260',
equiv: '\u2261',
le: '\u2264',
ge: '\u2265',
sub: '\u2282',
sup: '\u2283',
nsub: '\u2284',
sube: '\u2286',
supe: '\u2287',
oplus: '\u2295',
otimes: '\u2297',
perp: '\u22A5',
sdot: '\u22C5',
lceil: '\u2308',
rceil: '\u2309',
lfloor: '\u230A',
rfloor: '\u230B',
loz: '\u25CA',
spades: '\u2660',
clubs: '\u2663',
hearts: '\u2665',
diams: '\u2666',
lang: '\u27E8',
rang: '\u27E9'
};
/***/ },
/* 13 */
/***/ function(module, exports) {
"use strict";
exports.JSXSyntax = {
JSXAttribute: 'JSXAttribute',
JSXClosingElement: 'JSXClosingElement',
JSXElement: 'JSXElement',
JSXEmptyExpression: 'JSXEmptyExpression',
JSXExpressionContainer: 'JSXExpressionContainer',
JSXIdentifier: 'JSXIdentifier',
JSXMemberExpression: 'JSXMemberExpression',
JSXNamespacedName: 'JSXNamespacedName',
JSXOpeningElement: 'JSXOpeningElement',
JSXSpreadAttribute: 'JSXSpreadAttribute',
JSXText: 'JSXText'
};
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var jsx_syntax_1 = __webpack_require__(13);
var JSXClosingElement = (function () {
function JSXClosingElement(name) {
this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement;
this.name = name;
}
return JSXClosingElement;
}());
exports.JSXClosingElement = JSXClosingElement;
var JSXElement = (function () {
function JSXElement(openingElement, children, closingElement) {
this.type = jsx_syntax_1.JSXSyntax.JSXElement;
this.openingElement = openingElement;
this.children = children;
this.closingElement = closingElement;
}
return JSXElement;
}());
exports.JSXElement = JSXElement;
var JSXEmptyExpression = (function () {
function JSXEmptyExpression() {
this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression;
}
return JSXEmptyExpression;
}());
exports.JSXEmptyExpression = JSXEmptyExpression;
var JSXExpressionContainer = (function () {
function JSXExpressionContainer(expression) {
this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer;
this.expression = expression;
}
return JSXExpressionContainer;
}());
exports.JSXExpressionContainer = JSXExpressionContainer;
var JSXIdentifier = (function () {
function JSXIdentifier(name) {
this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier;
this.name = name;
}
return JSXIdentifier;
}());
exports.JSXIdentifier = JSXIdentifier;
var JSXMemberExpression = (function () {
function JSXMemberExpression(object, property) {
this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression;
this.object = object;
this.property = property;
}
return JSXMemberExpression;
}());
exports.JSXMemberExpression = JSXMemberExpression;
var JSXAttribute = (function () {
function JSXAttribute(name, value) {
this.type = jsx_syntax_1.JSXSyntax.JSXAttribute;
this.name = name;
this.value = value;
}
return JSXAttribute;
}());
exports.JSXAttribute = JSXAttribute;
var JSXNamespacedName = (function () {
function JSXNamespacedName(namespace, name) {
this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName;
this.namespace = namespace;
this.name = name;
}
return JSXNamespacedName;
}());
exports.JSXNamespacedName = JSXNamespacedName;
var JSXOpeningElement = (function () {
function JSXOpeningElement(name, selfClosing, attributes) {
this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement;
this.name = name;
this.selfClosing = selfClosing;
this.attributes = attributes;
}
return JSXOpeningElement;
}());
exports.JSXOpeningElement = JSXOpeningElement;
var JSXSpreadAttribute = (function () {
function JSXSpreadAttribute(argument) {
this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute;
this.argument = argument;
}
return JSXSpreadAttribute;
}());
exports.JSXSpreadAttribute = JSXSpreadAttribute;
var JSXText = (function () {
function JSXText(value, raw) {
this.type = jsx_syntax_1.JSXSyntax.JSXText;
this.value = value;
this.raw = raw;
}
return JSXText;
}());
exports.JSXText = JSXText;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var scanner_1 = __webpack_require__(8);
var error_handler_1 = __webpack_require__(6);
var token_1 = __webpack_require__(7);
var Reader = (function () {
function Reader() {
this.values = [];
this.curly = this.paren = -1;
}
;
// A function following one of those tokens is an expression.
Reader.prototype.beforeFunctionExpression = function (t) {
return ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
'return', 'case', 'delete', 'throw', 'void',
// assignment operators
'=', '+=', '-=', '*=', '**=', '/=', '%=', '<<=', '>>=', '>>>=',
'&=', '|=', '^=', ',',
// binary/unary operators
'+', '-', '*', '**', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
'|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
'<=', '<', '>', '!=', '!=='].indexOf(t) >= 0;
};
;
// Determine if forward slash (/) is an operator or part of a regular expression
// path_to_url
Reader.prototype.isRegexStart = function () {
var previous = this.values[this.values.length - 1];
var regex = (previous !== null);
switch (previous) {
case 'this':
case ']':
regex = false;
break;
case ')':
var check = this.values[this.paren - 1];
regex = (check === 'if' || check === 'while' || check === 'for' || check === 'with');
break;
case '}':
// Dividing a function by anything makes little sense,
// but we have to check for that.
regex = false;
if (this.values[this.curly - 3] === 'function') {
// Anonymous function, e.g. function(){} /42
var check_1 = this.values[this.curly - 4];
regex = check_1 ? !this.beforeFunctionExpression(check_1) : false;
}
else if (this.values[this.curly - 4] === 'function') {
// Named function, e.g. function f(){} /42/
var check_2 = this.values[this.curly - 5];
regex = check_2 ? !this.beforeFunctionExpression(check_2) : true;
}
}
return regex;
};
;
Reader.prototype.push = function (token) {
if (token.type === token_1.Token.Punctuator || token.type === token_1.Token.Keyword) {
if (token.value === '{') {
this.curly = this.values.length;
}
else if (token.value === '(') {
this.paren = this.values.length;
}
this.values.push(token.value);
}
else {
this.values.push(null);
}
};
;
return Reader;
}());
var Tokenizer = (function () {
function Tokenizer(code, config) {
this.errorHandler = new error_handler_1.ErrorHandler();
this.errorHandler.tolerant = config ? (typeof config.tolerant === 'boolean' && config.tolerant) : false;
this.scanner = new scanner_1.Scanner(code, this.errorHandler);
this.scanner.trackComment = config ? (typeof config.comment === 'boolean' && config.comment) : false;
this.trackRange = config ? (typeof config.range === 'boolean' && config.range) : false;
this.trackLoc = config ? (typeof config.loc === 'boolean' && config.loc) : false;
this.buffer = [];
this.reader = new Reader();
}
;
Tokenizer.prototype.errors = function () {
return this.errorHandler.errors;
};
;
Tokenizer.prototype.getNextToken = function () {
if (this.buffer.length === 0) {
var comments = this.scanner.scanComments();
if (this.scanner.trackComment) {
for (var i = 0; i < comments.length; ++i) {
var e = comments[i];
var comment = void 0;
var value = this.scanner.source.slice(e.slice[0], e.slice[1]);
comment = {
type: e.multiLine ? 'BlockComment' : 'LineComment',
value: value
};
if (this.trackRange) {
comment.range = e.range;
}
if (this.trackLoc) {
comment.loc = e.loc;
}
this.buffer.push(comment);
}
}
if (!this.scanner.eof()) {
var loc = void 0;
if (this.trackLoc) {
loc = {
start: {
line: this.scanner.lineNumber,
column: this.scanner.index - this.scanner.lineStart
},
end: {}
};
}
var token = void 0;
if (this.scanner.source[this.scanner.index] === '/') {
token = this.reader.isRegexStart() ? this.scanner.scanRegExp() : this.scanner.scanPunctuator();
}
else {
token = this.scanner.lex();
}
this.reader.push(token);
var entry = void 0;
entry = {
type: token_1.TokenName[token.type],
value: this.scanner.source.slice(token.start, token.end)
};
if (this.trackRange) {
entry.range = [token.start, token.end];
}
if (this.trackLoc) {
loc.end = {
line: this.scanner.lineNumber,
column: this.scanner.index - this.scanner.lineStart
};
entry.loc = loc;
}
if (token.regex) {
entry.regex = token.regex;
}
this.buffer.push(entry);
}
}
return this.buffer.shift();
};
;
return Tokenizer;
}());
exports.Tokenizer = Tokenizer;
/***/ }
/******/ ])
});
;
``` | /content/code_sandbox/node_modules/escodegen/node_modules/esprima/dist/esprima.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 59,308 |
```javascript
"use strict";
/* eslint-disable no-unused-expressions */
() => `jsdom 7.x onward only works on Node.js 4 or newer: path_to_url#install`;
/* eslint-enable no-unused-expressions */
const fs = require("fs");
const path = require("path");
const CookieJar = require("tough-cookie").CookieJar;
const toFileUrl = require("./jsdom/utils").toFileUrl;
const defineGetter = require("./jsdom/utils").defineGetter;
const defineSetter = require("./jsdom/utils").defineSetter;
const documentFeatures = require("./jsdom/browser/documentfeatures");
const domToHtml = require("./jsdom/browser/domtohtml").domToHtml;
const Window = require("./jsdom/browser/Window");
const resourceLoader = require("./jsdom/browser/resource-loader");
const VirtualConsole = require("./jsdom/virtual-console");
const locationInfo = require("./jsdom/living/helpers/internal-constants").locationInfo;
require("./jsdom/living"); // Enable living standard features
/* eslint-disable no-restricted-modules */
// TODO: stop using the built-in URL in favor of the spec-compliant whatwg-url package
// This legacy usage is in the process of being purged.
const URL = require("url");
/* eslint-enable no-restricted-modules */
const canReadFilesFromFS = Boolean(fs.readFile); // in a browserify environment, this isn't present
exports.createVirtualConsole = function (options) {
return new VirtualConsole(options);
};
exports.getVirtualConsole = function (window) {
return window._virtualConsole;
};
exports.createCookieJar = function () {
return new CookieJar(null, { looseMode: true });
};
exports.nodeLocation = function (node) {
return node[locationInfo];
};
exports.reconfigureWindow = function (window, newProps) {
if ("top" in newProps) {
window._top = newProps.top;
}
};
exports.debugMode = false;
// Proxy feature functions to features module.
for (const propName of ["availableDocumentFeatures", "defaultDocumentFeatures", "applyDocumentFeatures"]) {
defineGetter(exports, propName, () => documentFeatures[propName]);
defineSetter(exports, propName, val => documentFeatures[propName] = val);
}
exports.jsdom = function (html, options) {
if (options === undefined) {
options = {};
}
if (options.parsingMode === undefined || options.parsingMode === "auto") {
options.parsingMode = "html";
}
if (options.parsingMode !== "html" && options.parsingMode !== "xml") {
throw new RangeError(`Invalid parsingMode option ${JSON.stringify(options.parsingMode)}; must be either "html", ` +
`"xml", "auto", or undefined`);
}
setGlobalDefaultConfig(options);
// Back-compat hack: we have previously suggested nesting these under document, for jsdom.env at least.
// So we need to support that.
if (options.document) {
if (options.document.cookie !== undefined) {
options.cookie = options.document.cookie;
}
if (options.document.referrer !== undefined) {
options.referrer = options.document.referrer;
}
}
// List options explicitly to be clear which are passed through
const window = new Window({
parsingMode: options.parsingMode,
contentType: options.contentType,
parser: options.parser,
url: options.url,
referrer: options.referrer,
cookieJar: options.cookieJar,
cookie: options.cookie,
resourceLoader: options.resourceLoader,
deferClose: options.deferClose,
concurrentNodeIterators: options.concurrentNodeIterators,
virtualConsole: options.virtualConsole,
pool: options.pool,
agentOptions: options.agentOptions,
userAgent: options.userAgent
});
documentFeatures.applyDocumentFeatures(window.document, options.features);
if (options.created) {
options.created(null, window.document.defaultView);
}
if (options.parsingMode === "html") {
if (html === undefined || html === "") {
html = "<html><head></head><body></body></html>";
}
window.document.write(html);
}
if (options.parsingMode === "xml") {
if (html !== undefined) {
window.document._htmlToDom.appendHtmlToDocument(html, window.document);
}
}
if (window.document.close && !options.deferClose) {
window.document.close();
}
return window.document;
};
exports.jQueryify = exports.jsdom.jQueryify = function (window, jqueryUrl, callback) {
if (!window || !window.document) {
return;
}
const features = window.document.implementation._features;
window.document.implementation._addFeature("FetchExternalResources", ["script"]);
window.document.implementation._addFeature("ProcessExternalResources", ["script"]);
window.document.implementation._addFeature("MutationEvents", ["2.0"]);
const scriptEl = window.document.createElement("script");
scriptEl.className = "jsdom";
scriptEl.src = jqueryUrl;
scriptEl.onload = scriptEl.onerror = () => {
window.document.implementation._features = features;
if (callback) {
callback(window, window.jQuery);
}
};
window.document.body.appendChild(scriptEl);
};
exports.env = exports.jsdom.env = function () {
const config = getConfigFromArguments(arguments);
let req = null;
if (config.file && canReadFilesFromFS) {
req = resourceLoader.readFile(config.file, (err, text) => {
if (err) {
reportInitError(err, config);
return;
}
setParsingModeFromExtension(config, config.file);
config.html = text;
processHTML(config);
});
} else if (config.html !== undefined) {
processHTML(config);
} else if (config.url) {
req = handleUrl(config);
} else if (config.somethingToAutodetect !== undefined) {
const url = URL.parse(config.somethingToAutodetect);
if (url.protocol && url.hostname) {
config.url = config.somethingToAutodetect;
req = handleUrl(config.somethingToAutodetect);
} else if (canReadFilesFromFS) {
req = resourceLoader.readFile(config.somethingToAutodetect, (err, text) => {
if (err) {
if (err.code === "ENOENT" || err.code === "ENAMETOOLONG") {
config.html = config.somethingToAutodetect;
processHTML(config);
} else {
reportInitError(err, config);
}
} else {
setParsingModeFromExtension(config, config.somethingToAutodetect);
config.html = text;
config.url = toFileUrl(config.somethingToAutodetect);
processHTML(config);
}
});
} else {
config.html = config.somethingToAutodetect;
processHTML(config);
}
}
function handleUrl() {
const options = {
encoding: config.encoding || "utf8",
headers: config.headers || {},
pool: config.pool,
agentOptions: config.agentOptions
};
if (config.proxy) {
options.proxy = config.proxy;
}
options.headers["User-Agent"] = config.userAgent;
config.cookieJar = config.cookieJar || exports.createCookieJar();
return resourceLoader.download(config.url, options, config.cookieJar, null, (err, responseText, res) => {
if (err) {
reportInitError(err, config);
return;
}
// The use of `res.request.uri.href` ensures that `window.location.href`
// is updated when `request` follows redirects.
config.html = responseText;
config.url = res.request.uri.href;
const contentType = res.headers["content-type"];
if (config.parsingMode === "auto" && (
contentType === "application/xml" ||
contentType === "text/xml" ||
contentType === "application/xhtml+xml")) {
config.parsingMode = "xml";
}
processHTML(config);
});
}
return req;
};
exports.serializeDocument = function (doc) {
return domToHtml([doc]);
};
function processHTML(config) {
const window = exports.jsdom(config.html, config).defaultView;
const features = JSON.parse(JSON.stringify(window.document.implementation._features));
let docsLoaded = 0;
const totalDocs = config.scripts.length + config.src.length;
if (!window || !window.document) {
reportInitError(new Error("JSDOM: a window object could not be created."), config);
return;
}
function scriptComplete() {
docsLoaded++;
if (docsLoaded >= totalDocs) {
window.document.implementation._features = features;
process.nextTick(() => {
if (config.onload) {
config.onload(window);
}
if (config.done) {
config.done(null, window);
}
});
}
}
function handleScriptError() {
// nextTick so that an exception within scriptComplete won't cause
// another script onerror (which would be an infinite loop)
process.nextTick(scriptComplete);
}
if (config.scripts.length > 0 || config.src.length > 0) {
window.document.implementation._addFeature("FetchExternalResources", ["script"]);
window.document.implementation._addFeature("ProcessExternalResources", ["script"]);
window.document.implementation._addFeature("MutationEvents", ["2.0"]);
for (const scriptSrc of config.scripts) {
const script = window.document.createElement("script");
script.className = "jsdom";
script.onload = scriptComplete;
script.onerror = handleScriptError;
script.src = scriptSrc;
window.document.body.appendChild(script);
}
for (const scriptText of config.src) {
const script = window.document.createElement("script");
script.onload = scriptComplete;
script.onerror = handleScriptError;
script.text = scriptText;
window.document.documentElement.appendChild(script);
window.document.documentElement.removeChild(script);
}
} else if (window.document.readyState === "complete") {
scriptComplete();
} else {
window.addEventListener("load", scriptComplete);
}
}
function setGlobalDefaultConfig(config) {
config.pool = config.pool !== undefined ? config.pool : {
maxSockets: 6
};
config.agentOptions = config.agentOptions !== undefined ? config.agentOptions : {
keepAlive: true,
keepAliveMsecs: 115 * 1000
};
config.userAgent = config.userAgent || "Node.js (" + process.platform + "; U; rv:" + process.version + ")";
}
function getConfigFromArguments(args) {
const config = {};
if (typeof args[0] === "object") {
Object.assign(config, args[0]);
} else {
for (const arg of args) {
switch (typeof arg) {
case "string":
config.somethingToAutodetect = arg;
break;
case "function":
config.done = arg;
break;
case "object":
if (Array.isArray(arg)) {
config.scripts = arg;
} else {
Object.assign(config, arg);
}
break;
}
}
}
if (!config.done && !config.created && !config.onload) {
throw new Error("Must pass a \"created\", \"onload\", or \"done\" option, or a callback, to jsdom.env");
}
if (config.somethingToAutodetect === undefined &&
config.html === undefined && !config.file && !config.url) {
throw new Error("Must pass a \"html\", \"file\", or \"url\" option, or a string, to jsdom.env");
}
config.scripts = ensureArray(config.scripts);
config.src = ensureArray(config.src);
config.parsingMode = config.parsingMode || "auto";
config.features = config.features || {
FetchExternalResources: false,
ProcessExternalResources: false,
SkipExternalResources: false
};
if (!config.url && config.file) {
config.url = toFileUrl(config.file);
}
setGlobalDefaultConfig(config);
return config;
}
function reportInitError(err, config) {
if (config.created) {
config.created(err);
}
if (config.done) {
config.done(err);
}
}
function ensureArray(value) {
let array = value || [];
if (typeof array === "string") {
array = [array];
}
return array;
}
function setParsingModeFromExtension(config, filename) {
if (config.parsingMode === "auto") {
const ext = path.extname(filename);
if (ext === ".xhtml" || ext === ".xml") {
config.parsingMode = "xml";
}
}
}
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 2,744 |
```javascript
"use strict";
const EventEmitter = require("events").EventEmitter;
module.exports = class VirtualConsole extends EventEmitter {
constructor() {
super();
// If "error" event has no listeners,
// EventEmitter throws an exception
this.on("error", () => { });
}
sendTo(anyConsole, options) {
if (options === undefined) {
options = {};
}
for (const method of Object.keys(anyConsole)) {
if (typeof anyConsole[method] === "function") {
function onMethodCall() {
anyConsole[method].apply(anyConsole, arguments);
}
this.on(method, onMethodCall);
}
}
if (!options.omitJsdomErrors) {
this.on("jsdomError", e => anyConsole.error(e.stack, e.detail));
}
return this;
}
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/virtual-console.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 180 |
```javascript
"use strict";
// path_to_url#idl-named-properties
const IS_NAMED_PROPERTY = Symbol();
const TRACKER = Symbol();
/**
* Create a new NamedPropertiesTracker for the given `object`.
*
* Named properties are used in DOM to let you lookup (for example) a Node by accessing a property on another object.
* For example `window.foo` might resolve to an image element with id "foo".
*
* This tracker is a workaround because the ES6 Proxy feature is not yet available.
*
* @param {Object} object
* @param {Function} resolverFunc Each time a property is accessed, this function is called to determine the value of
* the property. The function is passed 3 arguments: (object, name, values).
* `object` is identical to the `object` parameter of this `create` function.
* `name` is the name of the property.
* `values` is a function that returns a Set with all the tracked values for this name. The order of these
* values is undefined.
*
* @returns {NamedPropertiesTracker}
*/
exports.create = function (object, resolverFunc) {
if (object[TRACKER]) {
throw Error("A NamedPropertiesTracker has already been created for this object");
}
const tracker = new NamedPropertiesTracker(object, resolverFunc);
object[TRACKER] = tracker;
return tracker;
};
exports.get = function (object) {
if (!object) {
return null;
}
return object[TRACKER] || null;
};
function NamedPropertiesTracker(object, resolverFunc) {
this.object = object;
this.resolverFunc = resolverFunc;
this.trackedValues = new Map(); // Map<Set<value>>
}
function newPropertyDescriptor(tracker, name) {
const emptySet = new Set();
function getValues() {
return tracker.trackedValues.get(name) || emptySet;
}
const descriptor = {
enumerable: true,
configurable: true,
get() {
return tracker.resolverFunc(tracker.object, name, getValues);
},
set(value) {
Object.defineProperty(tracker.object, name, {
enumerable: true,
configurable: true,
writable: true,
value
});
}
};
descriptor.get[IS_NAMED_PROPERTY] = true;
descriptor.set[IS_NAMED_PROPERTY] = true;
return descriptor;
}
/**
* Track a value (e.g. a Node) for a specified name.
*
* Values can be tracked eagerly, which means that not all tracked values *have* to appear in the output. The resolver
* function that was passed to the output may filter the value.
*
* Tracking the same `name` and `value` pair multiple times has no effect
*
* @param {String} name
* @param {*} value
*/
NamedPropertiesTracker.prototype.track = function (name, value) {
if (name === undefined || name === null || name === "") {
return;
}
let valueSet = this.trackedValues.get(name);
if (!valueSet) {
valueSet = new Set();
this.trackedValues.set(name, valueSet);
}
valueSet.add(value);
if (name in this.object) {
// already added our getter or it is not a named property (e.g. "addEventListener")
return;
}
const descriptor = newPropertyDescriptor(this, name);
Object.defineProperty(this.object, name, descriptor);
};
/**
* Stop tracking a previously tracked `name` & `value` pair, see track().
*
* Untracking the same `name` and `value` pair multiple times has no effect
*
* @param {String} name
* @param {*} value
*/
NamedPropertiesTracker.prototype.untrack = function (name, value) {
if (name === undefined || name === null || name === "") {
return;
}
const valueSet = this.trackedValues.get(name);
if (!valueSet) {
// the value is not present
return;
}
if (!valueSet.delete(value)) {
// the value was not present
return;
}
if (valueSet.size === 0) {
this.trackedValues.delete(name);
}
if (valueSet.size > 0) {
// other values for this name are still present
return;
}
// at this point there are no more values, delete the property
const descriptor = Object.getOwnPropertyDescriptor(this.object, name);
if (!descriptor || !descriptor.get || descriptor.get[IS_NAMED_PROPERTY] !== true) {
// Not defined by NamedPropertyTracker
return;
}
// note: delete puts the object in dictionary mode.
// if this turns out to be a performance issue, maybe add:
// path_to_url#L177
delete this.object[name];
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/named-properties-tracker.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,032 |
```javascript
"use strict";
const path = require("path");
const URL = require("whatwg-url-compat").createURLConstructor();
const domSymbolTree = require("./living/helpers/internal-constants").domSymbolTree;
const SYMBOL_TREE_POSITION = require("symbol-tree").TreePosition;
exports.URL = URL;
exports.toFileUrl = function (fileName) {
// Beyond just the `path.resolve`, this is mostly for the benefit of Windows,
// where we need to convert "\" to "/" and add an extra "/" prefix before the
// drive letter.
let pathname = path.resolve(process.cwd(), fileName).replace(/\\/g, "/");
if (pathname[0] !== "/") {
pathname = "/" + pathname;
}
// path might contain spaces, so convert those to %20
return "file://" + encodeURI(pathname);
};
/**
* Define a setter on an object
*
* This method replaces any existing setter but leaves getters in place.
*
* - `object` {Object} the object to define the setter on
* - `property` {String} the name of the setter
* - `setterFn` {Function} the setter
*/
exports.defineSetter = function defineSetter(object, property, setterFn) {
const descriptor = Object.getOwnPropertyDescriptor(object, property) || {
configurable: true,
enumerable: true
};
descriptor.set = setterFn;
Object.defineProperty(object, property, descriptor);
};
/**
* Define a getter on an object
*
* This method replaces any existing getter but leaves setters in place.
*
* - `object` {Object} the object to define the getter on
* - `property` {String} the name of the getter
* - `getterFn` {Function} the getter
*/
exports.defineGetter = function defineGetter(object, property, getterFn) {
const descriptor = Object.getOwnPropertyDescriptor(object, property) || {
configurable: true,
enumerable: true
};
descriptor.get = getterFn;
Object.defineProperty(object, property, descriptor);
};
/**
* Create an object with the given prototype
*
* Optionally augment the created object.
*
* - `prototype` {Object} the created object's prototype
* - `[properties]` {Object} properties to attach to the created object
*/
exports.createFrom = function createFrom(prototype, properties) {
properties = properties || {};
const descriptors = {};
for (const name of Object.getOwnPropertyNames(properties)) {
descriptors[name] = Object.getOwnPropertyDescriptor(properties, name);
}
for (const symbol of Object.getOwnPropertySymbols(properties)) {
descriptors[symbol] = Object.getOwnPropertyDescriptor(properties, symbol);
}
return Object.create(prototype, descriptors);
};
/**
* Create an inheritance relationship between two classes
*
* Optionally augment the inherited prototype.
*
* - `Superclass` {Function} the inherited class
* - `Subclass` {Function} the inheriting class
* - `[properties]` {Object} properties to attach to the inherited prototype
*/
exports.inheritFrom = function inheritFrom(Superclass, Subclass, properties) {
properties = properties || {};
Object.defineProperty(properties, "constructor", {
value: Subclass,
writable: true,
configurable: true
});
Subclass.prototype = exports.createFrom(Superclass.prototype, properties);
};
/**
* Define a set of properties on an object, by copying the property descriptors
* from the original object.
*
* - `object` {Object} the target object
* - `properties` {Object} the source from which to copy property descriptors
*/
exports.define = function define(object, properties) {
for (const name of Object.getOwnPropertyNames(properties)) {
const propDesc = Object.getOwnPropertyDescriptor(properties, name);
Object.defineProperty(object, name, propDesc);
}
};
/**
* Define a list of constants on a constructor and its .prototype
*
* - `Constructor` {Function} the constructor to define the constants on
* - `propertyMap` {Object} key/value map of properties to define
*/
exports.addConstants = function addConstants(Constructor, propertyMap) {
for (const property in propertyMap) {
const value = propertyMap[property];
addConstant(Constructor, property, value);
addConstant(Constructor.prototype, property, value);
}
};
function addConstant(object, property, value) {
Object.defineProperty(object, property, {
configurable: false,
enumerable: true,
writable: false,
value
});
}
let memoizeQueryTypeCounter = 0;
/**
* Returns a version of a method that memoizes specific types of calls on the object
*
* - `fn` {Function} the method to be memozied
*/
exports.memoizeQuery = function memoizeQuery(fn) {
// Only memoize query functions with arity <= 2
if (fn.length > 2) {
return fn;
}
const type = memoizeQueryTypeCounter++;
return function () {
if (!this._memoizedQueries) {
return fn.apply(this, arguments);
}
if (!this._memoizedQueries[type]) {
this._memoizedQueries[type] = Object.create(null);
}
let key;
if (arguments.length === 1 && typeof arguments[0] === "string") {
key = arguments[0];
} else if (arguments.length === 2 && typeof arguments[0] === "string" && typeof arguments[1] === "string") {
key = arguments[0] + "::" + arguments[1];
} else {
return fn.apply(this, arguments);
}
if (!(key in this._memoizedQueries[type])) {
this._memoizedQueries[type][key] = fn.apply(this, arguments);
}
return this._memoizedQueries[type][key];
};
};
exports.resolveHref = function resolveHref(baseUrl, href) {
try {
return new URL(href, baseUrl).href;
} catch (e) {
// can't throw since this utility is basically used everywhere
// do what the spec says regarding anchor tags: just don't parse it
// path_to_url#dom-urlutils-href
return href;
}
};
exports.mapper = function (parent, filter, recursive) {
function skipRoot(node) {
return node !== parent && (!filter || filter(node));
}
return () => {
if (recursive !== false) { // default is not recursive
return domSymbolTree.treeToArray(parent, { filter: skipRoot });
}
return domSymbolTree.childrenToArray(parent, { filter });
};
};
function isValidAbsoluteURL(str) {
try {
/* eslint-disable no-new */
new URL(str);
/* eslint-enable no-new */
// If we can parse it, it's a valid absolute URL.
return true;
} catch (e) {
return false;
}
}
exports.isValidTargetOrigin = function (str) {
return str === "*" || str === "/" || isValidAbsoluteURL(str);
};
exports.simultaneousIterators = function* (first, second) {
for (;;) {
const firstResult = first.next();
const secondResult = second.next();
if (firstResult.done && secondResult.done) {
return;
}
yield [
firstResult.done ? null : firstResult.value,
secondResult.done ? null : secondResult.value
];
}
};
exports.treeOrderSorter = function (a, b) {
const compare = domSymbolTree.compareTreePosition(a, b);
if (compare & SYMBOL_TREE_POSITION.PRECEDING) { // b is preceding a
return 1;
}
if (compare & SYMBOL_TREE_POSITION.FOLLOWING) {
return -1;
}
// disconnected or equal:
return 0;
};
exports.lengthFromProperties = function (arrayLike) {
let max = -1;
const keys = Object.keys(arrayLike);
const highestKeyIndex = keys.length - 1;
// Abuses a v8 implementation detail for a very fast case
// (if this implementation detail changes, this method will still
// return correct results)
/* eslint-disable eqeqeq */
if (highestKeyIndex == keys[highestKeyIndex]) { // not ===
/* eslint-enable eqeqeq */
return keys.length;
}
for (let i = highestKeyIndex; i >= 0; --i) {
const asNumber = Number(keys[i]);
if (!Number.isNaN(asNumber) && asNumber > max) {
max = asNumber;
}
}
return max + 1;
};
const base64Regexp = /^(?:[A-Z0-9+\/]{4})*(?:[A-Z0-9+\/]{2}==|[A-Z0-9+\/]{3}=|[A-Z0-9+\/]{4})$/i;
exports.parseDataUrl = function parseDataUrl(url) {
const urlParts = url.match(/^data:(.+?)(?:;(base64))?,(.*)$/);
let buffer;
if (urlParts[2] === "base64") {
if (urlParts[3] && !base64Regexp.test(urlParts[3])) {
throw new Error("Not a base64 string");
}
buffer = new Buffer(urlParts[3], "base64");
} else {
buffer = new Buffer(urlParts[3]);
}
return { buffer, type: urlParts[1] };
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/utils.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 2,003 |
```javascript
"use strict";
const inheritFrom = require("../utils").inheritFrom;
const addConstants = require("../utils").addConstants;
const table = require("./dom-exception-table.json"); // path_to_url#idl-DOMException-error-names
// Precompute some stuff. Mostly unnecessary once we take care of the TODO below.
const namesWithCodes = Object.keys(table).filter(name => "legacyCodeValue" in table[name]);
const codesToNames = Object.create(null);
for (const name of namesWithCodes) {
codesToNames[table[name].legacyCodeValue] = name;
}
module.exports = DOMException;
// TODO: update constructor signature to match WebIDL spec
// See also path_to_url which isn't merged as of yet
function DOMException(code, message) {
const name = codesToNames[code];
if (message === undefined) {
message = table[name].description;
}
Error.call(this, message);
Object.defineProperty(this, "name", { value: name, writable: true, configurable: true, enumerable: false });
Object.defineProperty(this, "code", { value: code, writable: true, configurable: true, enumerable: false });
if (Error.captureStackTrace) {
Error.captureStackTrace(this, DOMException);
}
}
inheritFrom(Error, DOMException);
const constants = Object.create(null);
for (const name of namesWithCodes) {
constants[table[name].legacyCodeName] = table[name].legacyCodeValue;
}
addConstants(DOMException, constants);
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/web-idl/DOMException.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 315 |
```javascript
"use strict";
const acorn = require("acorn");
const findGlobals = require("acorn-globals");
const escodegen = require("escodegen");
// We can't use the default browserify vm shim because it doesn't work in a web worker.
// From ES spec table of contents. Also, don't forget the Annex B additions.
// If someone feels ambitious maybe make this into an npm package.
const builtInConsts = ["Infinity", "NaN", "undefined"];
const otherBuiltIns = ["eval", "isFinite", "isNaN", "parseFloat", "parseInt", "decodeURI", "decodeURIComponent",
"encodeURI", "encodeURIComponent", "Array", "ArrayBuffer", "Boolean", "DataView", "Date", "Error", "EvalError",
"Float32Array", "Float64Array", "Function", "Int8Array", "Int16Array", "Int32Array", "Map", "Number", "Object",
"Proxy", "Promise", "RangeError", "ReferenceError", "RegExp", "Set", "String", "Symbol", "SyntaxError", "TypeError",
"Uint8Array", "Uint8ClampedArray", "Uint16Array", "Uint32Array", "URIError", "WeakMap", "WeakSet", "JSON", "Math",
"Reflect", "escape", "unescape"];
exports.createContext = function (sandbox) {
Object.defineProperty(sandbox, "__isVMShimContext", {
value: true,
writable: true,
configurable: true,
enumerable: false
});
for (const builtIn of builtInConsts) {
Object.defineProperty(sandbox, builtIn, {
value: global[builtIn],
writable: false,
configurable: false,
enumerable: false
});
}
for (const builtIn of otherBuiltIns) {
Object.defineProperty(sandbox, builtIn, {
value: global[builtIn],
writable: true,
configurable: true,
enumerable: false
});
}
};
exports.isContext = function (sandbox) {
return sandbox.__isVMShimContext;
};
exports.runInContext = function (code, contextifiedSandbox, options) {
if (code === "this") {
// Special case for during window creation.
return contextifiedSandbox;
}
if (options === undefined) {
options = {};
}
const comments = [];
const tokens = [];
const ast = acorn.parse(code, {
ecmaVersion: 6,
allowReturnOutsideFunction: true,
ranges: true,
// collect comments in Esprima's format
onComment: comments,
// collect token ranges
onToken: tokens
});
// make sure we keep comments
escodegen.attachComments(ast, comments, tokens);
const globals = findGlobals(ast);
for (let i = 0; i < globals.length; ++i) {
if (globals[i].name === "window") {
continue;
}
const nodes = globals[i].nodes;
for (let j = 0; j < nodes.length; ++j) {
const type = nodes[j].type;
const name = nodes[j].name;
nodes[j].type = "MemberExpression";
nodes[j].property = { name, type };
nodes[j].computed = false;
nodes[j].object = {
name: "window",
type: "Identifier"
};
}
}
const lastNode = ast.body[ast.body.length - 1];
if (lastNode.type === "ExpressionStatement") {
lastNode.type = "ReturnStatement";
lastNode.argument = lastNode.expression;
delete lastNode.expression;
}
const rewrittenCode = escodegen.generate(ast, { comment: true });
const suffix = options.filename !== undefined ? "\n//# sourceURL=" + options.filename : "";
return Function("window", rewrittenCode + suffix).bind(contextifiedSandbox)(contextifiedSandbox);
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/vm-shim.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 852 |
```javascript
"use strict";
var core = require("../level1/core"),
defineGetter = require('../utils').defineGetter,
defineSetter = require('../utils').defineSetter,
HtmlToDom = require('../browser/htmltodom').HtmlToDom;
const domSymbolTree = require("../living/helpers/internal-constants").domSymbolTree;
const NODE_TYPE = require("../living/node-type");
/*
valuetype DOMString sequence<unsigned short>;
typedef unsigned long long DOMTimeStamp;
typedef any DOMUserData;
typedef Object DOMObject;
*/
/*
// Introduced in DOM Level 3:
interface NameList {
DOMString getName(in unsigned long index);
DOMString getNamespaceURI(in unsigned long index);
readonly attribute unsigned long length;
boolean contains(in DOMString str);
boolean containsNS(in DOMString namespaceURI,
in DOMString name);
};
// Introduced in DOM Level 3:
interface DOMImplementationList {
DOMImplementation item(in unsigned long index);
readonly attribute unsigned long length;
};
// Introduced in DOM Level 3:
interface DOMImplementationSource {
DOMImplementation getDOMImplementation(in DOMString features);
DOMImplementationList getDOMImplementationList(in DOMString features);
};
*/
core.DOMImplementation.prototype.getFeature = function(feature, version) {
};
/*
interface Node {
// Modified in DOM Level 3:
Node insertBefore(in Node newChild,
in Node refChild)
raises(DOMException);
// Modified in DOM Level 3:
Node replaceChild(in Node newChild,
in Node oldChild)
raises(DOMException);
// Modified in DOM Level 3:
Node removeChild(in Node oldChild)
raises(DOMException);
// Modified in DOM Level 3:
Node appendChild(in Node newChild)
raises(DOMException);
boolean hasChildNodes();
Node cloneNode(in boolean deep);
// Modified in DOM Level 3:
void normalize();
// Introduced in DOM Level 3:
readonly attribute DOMString baseURI;
*/
// Compare Document Position
var DOCUMENT_POSITION_DISCONNECTED = core.Node.DOCUMENT_POSITION_DISCONNECTED =
core.Node.prototype.DOCUMENT_POSITION_DISCONNECTED = 0x01;
var DOCUMENT_POSITION_PRECEDING = core.Node.DOCUMENT_POSITION_PRECEDING =
core.Node.prototype.DOCUMENT_POSITION_PRECEDING = 0x02;
var DOCUMENT_POSITION_FOLLOWING = core.Node.DOCUMENT_POSITION_FOLLOWING =
core.Node.prototype.DOCUMENT_POSITION_FOLLOWING = 0x04;
var DOCUMENT_POSITION_CONTAINS = core.Node.DOCUMENT_POSITION_CONTAINS =
core.Node.prototype.DOCUMENT_POSITION_CONTAINS = 0x08;
var DOCUMENT_POSITION_CONTAINED_BY = core.Node.DOCUMENT_POSITION_CONTAINED_BY =
core.Node.prototype.DOCUMENT_POSITION_CONTAINED_BY = 0x10;
var DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = core.Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC =
core.Node.prototype.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20;
// @see path_to_url#Node3-textContent
defineGetter(core.Node.prototype, 'textContent', function() {
let text;
switch (this.nodeType) {
case NODE_TYPE.COMMENT_NODE:
case NODE_TYPE.CDATA_SECTION_NODE:
case NODE_TYPE.PROCESSING_INSTRUCTION_NODE:
case NODE_TYPE.TEXT_NODE:
return this.nodeValue;
case NODE_TYPE.ATTRIBUTE_NODE:
case NODE_TYPE.DOCUMENT_FRAGMENT_NODE:
case NODE_TYPE.ELEMENT_NODE:
text = '';
for (const child of domSymbolTree.treeIterator(this)) {
if (child.nodeType === NODE_TYPE.TEXT_NODE) {
text += child.nodeValue;
}
}
return text;
default:
return null;
}
});
defineSetter(core.Node.prototype, 'textContent', function(txt) {
switch (this.nodeType) {
case NODE_TYPE.COMMENT_NODE:
case NODE_TYPE.CDATA_SECTION_NODE:
case NODE_TYPE.PROCESSING_INSTRUCTION_NODE:
case NODE_TYPE.TEXT_NODE:
return this.nodeValue = String(txt);
}
for (let child = null; child = domSymbolTree.firstChild(this);) {
this.removeChild(child);
}
if (txt !== "" && txt != null) {
this.appendChild(this._ownerDocument.createTextNode(txt));
}
return txt;
});
/*
// Introduced in DOM Level 3:
DOMString lookupPrefix(in DOMString namespaceURI);
// Introduced in DOM Level 3:
boolean isDefaultNamespace(in DOMString namespaceURI);
// Introduced in DOM Level 3:
DOMString lookupNamespaceURI(in DOMString prefix);
// Introduced in DOM Level 3:
DOMObject getFeature(in DOMString feature,
in DOMString version);
*/
// Introduced in DOM Level 3:
core.Node.prototype.setUserData = function(key, data, handler) {
var r = this[key] || null;
this[key] = data;
return(r);
};
// Introduced in DOM Level 3:
core.Node.prototype.getUserData = function(key) {
var r = this[key] || null;
return(r);
};
/*
interface NodeList {
Node item(in unsigned long index);
readonly attribute unsigned long length;
};
interface NamedNodeMap {
Node getNamedItem(in DOMString name);
Node setNamedItem(in Node arg)
raises(DOMException);
Node removeNamedItem(in DOMString name)
raises(DOMException);
Node item(in unsigned long index);
readonly attribute unsigned long length;
// Introduced in DOM Level 2:
Node getNamedItemNS(in DOMString namespaceURI,
in DOMString localName)
raises(DOMException);
// Introduced in DOM Level 2:
Node setNamedItemNS(in Node arg)
raises(DOMException);
// Introduced in DOM Level 2:
Node removeNamedItemNS(in DOMString namespaceURI,
in DOMString localName)
raises(DOMException);
};
interface CharacterData : Node {
attribute DOMString data;
// raises(DOMException) on setting
// raises(DOMException) on retrieval
readonly attribute unsigned long length;
DOMString substringData(in unsigned long offset,
in unsigned long count)
raises(DOMException);
void appendData(in DOMString arg)
raises(DOMException);
void insertData(in unsigned long offset,
in DOMString arg)
raises(DOMException);
void deleteData(in unsigned long offset,
in unsigned long count)
raises(DOMException);
void replaceData(in unsigned long offset,
in unsigned long count,
in DOMString arg)
raises(DOMException);
};
interface Attr : Node {
readonly attribute DOMString name;
readonly attribute boolean specified;
attribute DOMString value;
// raises(DOMException) on setting
// Introduced in DOM Level 2:
readonly attribute Element ownerElement;
// Introduced in DOM Level 3:
readonly attribute TypeInfo schemaTypeInfo;
*/
// Introduced in DOM Level 3:
/*
};
interface Element : Node {
readonly attribute DOMString tagName;
DOMString getAttribute(in DOMString name);
void setAttribute(in DOMString name,
in DOMString value)
raises(DOMException);
void removeAttribute(in DOMString name)
raises(DOMException);
Attr getAttributeNode(in DOMString name);
Attr setAttributeNode(in Attr newAttr)
raises(DOMException);
Attr removeAttributeNode(in Attr oldAttr)
raises(DOMException);
NodeList getElementsByTagName(in DOMString name);
// Introduced in DOM Level 2:
DOMString getAttributeNS(in DOMString namespaceURI,
in DOMString localName)
raises(DOMException);
// Introduced in DOM Level 2:
void setAttributeNS(in DOMString namespaceURI,
in DOMString qualifiedName,
in DOMString value)
raises(DOMException);
// Introduced in DOM Level 2:
void removeAttributeNS(in DOMString namespaceURI,
in DOMString localName)
raises(DOMException);
// Introduced in DOM Level 2:
Attr getAttributeNodeNS(in DOMString namespaceURI,
in DOMString localName)
raises(DOMException);
// Introduced in DOM Level 2:
Attr setAttributeNodeNS(in Attr newAttr)
raises(DOMException);
// Introduced in DOM Level 2:
NodeList getElementsByTagNameNS(in DOMString namespaceURI,
in DOMString localName)
raises(DOMException);
// Introduced in DOM Level 2:
boolean hasAttribute(in DOMString name);
// Introduced in DOM Level 2:
boolean hasAttributeNS(in DOMString namespaceURI,
in DOMString localName)
raises(DOMException);
// Introduced in DOM Level 3:
readonly attribute TypeInfo schemaTypeInfo;
// Introduced in DOM Level 3:
void setIdAttribute(in DOMString name,
in boolean isId)
raises(DOMException);
// Introduced in DOM Level 3:
void setIdAttributeNS(in DOMString namespaceURI,
in DOMString localName,
in boolean isId)
raises(DOMException);
// Introduced in DOM Level 3:
void setIdAttributeNode(in Attr idAttr,
in boolean isId)
raises(DOMException);
};
interface Text : CharacterData {
Text splitText(in unsigned long offset)
raises(DOMException);
// Introduced in DOM Level 3:
readonly attribute boolean isElementContentWhitespace;
// Introduced in DOM Level 3:
readonly attribute DOMString wholeText;
// Introduced in DOM Level 3:
Text replaceWholeText(in DOMString content)
raises(DOMException);
};
interface Comment : CharacterData {
};
// Introduced in DOM Level 3:
interface TypeInfo {
readonly attribute DOMString typeName;
readonly attribute DOMString typeNamespace;
// DerivationMethods
const unsigned long DERIVATION_RESTRICTION = 0x00000001;
const unsigned long DERIVATION_EXTENSION = 0x00000002;
const unsigned long DERIVATION_UNION = 0x00000004;
const unsigned long DERIVATION_LIST = 0x00000008;
boolean isDerivedFrom(in DOMString typeNamespaceArg,
in DOMString typeNameArg,
in unsigned long derivationMethod);
};
*/
// Introduced in DOM Level 3:
core.UserDataHandler = function() {};
core.UserDataHandler.prototype.NODE_CLONED = 1;
core.UserDataHandler.prototype.NODE_IMPORTED = 2;
core.UserDataHandler.prototype.NODE_DELETED = 3;
core.UserDataHandler.prototype.NODE_RENAMED = 4;
core.UserDataHandler.prototype.NODE_ADOPTED = 5;
core.UserDataHandler.prototype.handle = function(operation, key, data, src, dst) {};
// Introduced in DOM Level 3:
core.DOMError = function(severity, message, type, relatedException, relatedData, location) {
this._severity = severity;
this._message = message;
this._type = type;
this._relatedException = relatedException;
this._relatedData = relatedData;
this._location = location;
};
core.DOMError.prototype = {};
core.DOMError.prototype.SEVERITY_WARNING = 1;
core.DOMError.prototype.SEVERITY_ERROR = 2;
core.DOMError.prototype.SEVERITY_FATAL_ERROR = 3;
defineGetter(core.DOMError.prototype, 'severity', function() {
return this._severity;
});
defineGetter(core.DOMError.prototype, 'message', function() {
return this._message;
});
defineGetter(core.DOMError.prototype, 'type', function() {
return this._type;
});
defineGetter(core.DOMError.prototype, 'relatedException', function() {
return this._relatedException;
});
defineGetter(core.DOMError.prototype, 'relatedData', function() {
return this._relatedData;
});
defineGetter(core.DOMError.prototype, 'location', function() {
return this._location;
});
/*
// Introduced in DOM Level 3:
interface DOMErrorHandler {
boolean handleError(in DOMError error);
};
// Introduced in DOM Level 3:
interface DOMLocator {
readonly attribute long lineNumber;
readonly attribute long columnNumber;
readonly attribute long byteOffset;
readonly attribute long utf16Offset;
readonly attribute Node relatedNode;
readonly attribute DOMString uri;
};
*/
// Introduced in DOM Level 3:
core.DOMConfiguration = function(){
var possibleParameterNames = {
'canonical-form': [false, true], // extra rules for true
'cdata-sections': [true, false],
'check-character-normalization': [false, true],
'comments': [true, false],
'datatype-normalization': [false, true],
'element-content-whitespace': [true, false],
'entities': [true, false],
// 'error-handler': [],
'infoset': [undefined, true, false], // extra rules for true
'namespaces': [true, false],
'namespace-declarations': [true, false], // only checked if namespaces is true
'normalize-characters': [false, true],
// 'schema-location': [],
// 'schema-type': [],
'split-cdata-sections': [true, false],
'validate': [false, true],
'validate-if-schema': [false, true],
'well-formed': [true, false]
}
};
core.DOMConfiguration.prototype = {
setParameter: function(name, value) {},
getParameter: function(name) {},
canSetParameter: function(name, value) {},
parameterNames: function() {}
};
//core.Document.prototype._domConfig = new core.DOMConfiguration();
defineGetter(core.Document.prototype, 'domConfig', function() {
return this._domConfig || new core.DOMConfiguration();;
});
// Introduced in DOM Level 3:
core.DOMStringList = function() {};
core.DOMStringList.prototype = {
item: function() {},
length: function() {},
contains: function() {}
};
/*
interface CDATASection : Text {
};
interface DocumentType : Node {
readonly attribute DOMString name;
readonly attribute NamedNodeMap entities;
readonly attribute NamedNodeMap notations;
// Introduced in DOM Level 2:
readonly attribute DOMString publicId;
// Introduced in DOM Level 2:
readonly attribute DOMString systemId;
// Introduced in DOM Level 2:
readonly attribute DOMString internalSubset;
};
interface Notation : Node {
readonly attribute DOMString publicId;
readonly attribute DOMString systemId;
};
interface Entity : Node {
readonly attribute DOMString publicId;
readonly attribute DOMString systemId;
readonly attribute DOMString notationName;
// Introduced in DOM Level 3:
readonly attribute DOMString inputEncoding;
// Introduced in DOM Level 3:
readonly attribute DOMString xmlEncoding;
// Introduced in DOM Level 3:
readonly attribute DOMString xmlVersion;
};
interface EntityReference : Node {
};
interface ProcessingInstruction : Node {
readonly attribute DOMString target;
attribute DOMString data;
// raises(DOMException) on setting
};
interface DocumentFragment : Node {
};
interface Document : Node {
// Modified in DOM Level 3:
readonly attribute DocumentType doctype;
readonly attribute DOMImplementation implementation;
readonly attribute Element documentElement;
Element createElement(in DOMString tagName)
raises(DOMException);
DocumentFragment createDocumentFragment();
Text createTextNode(in DOMString data);
Comment createComment(in DOMString data);
CDATASection createCDATASection(in DOMString data)
raises(DOMException);
ProcessingInstruction createProcessingInstruction(in DOMString target,
in DOMString data)
raises(DOMException);
Attr createAttribute(in DOMString name)
raises(DOMException);
EntityReference createEntityReference(in DOMString name)
raises(DOMException);
NodeList getElementsByTagName(in DOMString tagname);
// Introduced in DOM Level 2:
Node importNode(in Node importedNode,
in boolean deep)
raises(DOMException);
// Introduced in DOM Level 2:
Element createElementNS(in DOMString namespaceURI,
in DOMString qualifiedName)
raises(DOMException);
// Introduced in DOM Level 2:
Attr createAttributeNS(in DOMString namespaceURI,
in DOMString qualifiedName)
raises(DOMException);
// Introduced in DOM Level 2:
NodeList getElementsByTagNameNS(in DOMString namespaceURI,
in DOMString localName);
// Introduced in DOM Level 2:
Element getElementById(in DOMString elementId);
*/
/*
// Introduced in DOM Level 3:
readonly attribute DOMString xmlEncoding;
// Introduced in DOM Level 3:
attribute boolean xmlStandalone;
// raises(DOMException) on setting
// Introduced in DOM Level 3:
attribute DOMString xmlVersion;
// raises(DOMException) on setting
// Introduced in DOM Level 3:
attribute boolean strictErrorChecking;
// Introduced in DOM Level 3:
attribute DOMString documentURI;
// Introduced in DOM Level 3:
Node adoptNode(in Node source)
raises(DOMException);
// Introduced in DOM Level 3:
readonly attribute DOMConfiguration domConfig;
// Introduced in DOM Level 3:
void normalizeDocument();
// Introduced in DOM Level 3:
Node renameNode(in Node n,
in DOMString namespaceURI,
in DOMString qualifiedName)
raises(DOMException);
};
};
#endif // _DOM_IDL_
*/
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/level3/core.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 3,841 |
```javascript
// w3c Load/Save functionality: path_to_url
var core = require('../level1/core');
var createFrom = require('../utils').createFrom;
var ls = {};
// TODO: what is this?
//typedef dom::DOMConfiguration DOMConfiguration;
ls.LSException = function LSException(code) {
this.code = code;
};
ls.LSException.prototype = {
// LSExceptionCode
PARSE_ERR : 81,
SERIALIZE_ERR : 82
};
ls.DOMImplementationLS = function DOMImplementationLS() {
};
var DOMImplementationExtension = {
// DOMImplementationLSMode
MODE_SYNCHRONOUS : 1,
MODE_ASYNCHRONOUS : 2,
// raises(dom::DOMException);
createLSParser : function(/* int */ mode, /* string */ schemaType) {
return new ls.LSParser(mode, schemaType);
},
createLSSerializer : function() {
return new ls.LSSerializer();
},
createLSInput : function() {
return new ls.LSInput();
},
createLSOutput : function() {
return new ls.LSOutput();
}
};
Object.keys(DOMImplementationExtension).forEach(function(k, v) {
core.DOMImplementation.prototype[k] = DOMImplementationExtension[k];
});
ls.DOMImplementationLS.prototype = DOMImplementationExtension;
core.Document.getFeature = function() {
return DOMImplementationExtension;
};
ls.LSParser = function LSParser() {
this._domConfig = new core.DOMConfiguration();
};
ls.LSParser.prototype = {
get domConfig() { return this._domConfig; },
get filter() { return this._filter || null; },
set filter(value) { this._filter = value; },
get async() { return this._async; },
get busy() { return this._busy; },
// raises(dom::DOMException, LSException);
parse : function (/* LSInput */ input) {
var doc = new core.Document();
doc._inputEncoding = 'UTF-16';
return doc;
},
// raises(dom::DOMException, LSException);
parseURI : function(/* string */ uri) {
return new core.Document();
},
// ACTION_TYPES
ACTION_APPEND_AS_CHILDREN : 1,
ACTION_REPLACE_CHILDREN : 2,
ACTION_INSERT_BEFORE : 3,
ACTION_INSERT_AFTER : 4,
ACTION_REPLACE : 5,
// @returns Node
// @raises DOMException, LSException
parseWithContext : function(/* LSInput */ input, /* Node */ contextArg, /* int */ action) {
return new core.Node();
},
abort : function() {
// TODO: implement
}
};
ls.LSInput = function LSInput() {};
ls.LSInput.prototype = {
get characterStream() { return this._characterStream || null; },
set characterStream(value) { this._characterStream = value; },
get byteStream() { return this._byteStream || null; },
set byteStream(value) { this._byteStream = value; },
get stringData() { return this._stringData || null; },
set stringData(value) { this._stringData = value; },
get systemId() { return this._systemId || null; },
set systemId(value) { this._systemId = value; },
get publicId() { return this._publicId || null; },
set publicId(value) { this._publicId = value; },
get baseURI() { return this._baseURI || null; },
set baseURI(value) { this._baseURI = value; },
get encoding() { return this._encoding || null; },
set encoding(value) { this._encoding = value; },
get certifiedText() { return this._certifiedText || null; },
set certifiedText(value) { this._certifiedText = value; },
};
ls.LSResourceResolver = function LSResourceResolver() {};
// @returns LSInput
ls.LSResourceResolver.prototype.resolveResource = function(type, namespaceURI, publicId, systemId, baseURI) {
return new ls.LSInput();
};
ls.LSParserFilter = function LSParserFilter() {};
ls.LSParserFilter.prototype = {
// Constants returned by startElement and acceptNode
FILTER_ACCEPT : 1,
FILTER_REJECT : 2,
FILTER_SKIP : 3,
FILTER_INTERRUPT : 4,
get whatToShow() { return this._whatToShow; },
// @returns int
startElement : function(/* Element */ elementArg) {
return 0;
},
// @returns int
acceptNode : function(/* Node */ nodeArg) {
return nodeArg;
}
};
ls.LSSerializer = function LSSerializer() {
this._domConfig = new core.DOMConfiguration();
};
ls.LSSerializer.prototype = {
get domConfig() { return this._domConfig; },
get newLine() { return this._newLine || null; },
set newLine(value) { this._newLine = value; },
get filter() { return this._filter || null; },
set filter(value) { this._filter = value; },
// @returns boolean
// @raises LSException
write : function(/* Node */ nodeArg, /* LSOutput */ destination) {
return true;
},
// @returns boolean
// @raises LSException
writeToURI : function(/* Node */ nodeArg, /* string */ uri) {
return true;
},
// @returns string
// @raises DOMException, LSException
writeToString : function(/* Node */ nodeArg) {
return "";
}
};
ls.LSOutput = function LSOutput() {};
ls.LSOutput.prototype = {
get characterStream() { return this._characterStream || null; },
set characterStream(value) { this._characterStream = value; },
get byteStream() { return this._byteStream || null; },
set byteStream(value) { this._byteStream = value; },
get systemId() { return this._systemId || null; },
set systemId(value) { this._systemId = value; },
get encoding() { return this._encoding || null; },
set encoding(value) { this._encoding = value; },
};
ls.LSProgressEvent = function LSProgressEvent() {};
ls.LSProgressEvent.prototype = createFrom(core.Event, {
constructor: ls.LSProgressEvent,
get input() { return this._input; },
get position() { return this._position; },
get totalSize() { return this._totalSize; },
});
ls.LSLoadEvent = function LSLoadEvent() {};
ls.LSLoadEvent.prototype = createFrom(core.Event, {
get newDocument() { return this._newDocument; },
get input() { return this._input; },
});
// TODO: do traversal
ls.LSSerializerFilter = function LSSerializerFilter() {};
ls.LSSerializerFilter.prototype = {
get whatToShow() { return this._whatToShow; },
};
// ls.LSSerializerFilter.prototype.__proto__ = level2.traversal.NodeFiler;
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/level3/ls.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,539 |
```javascript
"use strict";
const request = require("request");
const EventEmitter = require("events").EventEmitter;
const fs = require("fs");
const utils = require("../utils");
const xhrSymbols = require("./xmlhttprequest-symbols");
const internalConstants = require("./helpers/internal-constants");
function wrapCookieJarForRequest(cookieJar) {
const jarWrapper = request.jar();
jarWrapper._jar = cookieJar;
return jarWrapper;
}
function getRequestHeader(requestHeaders, header) {
const keys = Object.keys(requestHeaders);
let n = keys.length;
while (n--) {
const key = keys[n];
if (key.toLowerCase() === header.toLowerCase()) {
return requestHeaders[key];
}
}
return null;
}
exports.getRequestHeader = getRequestHeader;
// return a "request" client object or an event emitter matching the same behaviour for unsupported protocols
// the callback should be called with a "request" response object or an event emitter matching the same behaviour too
exports.createClient = function createClient(xhr, callback) {
const flag = xhr[xhrSymbols.flag];
const urlObj = new utils.URL(flag.uri);
const uri = urlObj.href;
const requestManager = xhr._ownerDocument[internalConstants.requestManager];
if (urlObj.protocol === "file:") {
const response = new EventEmitter();
response.statusCode = 200;
response.rawHeaders = [];
response.headers = {};
const filePath = urlObj.pathname
.replace(/^file:\/\//, "")
.replace(/^\/([a-z]):\//i, "$1:/")
.replace(/%20/g, " ");
const client = new EventEmitter();
const readableStream = fs.createReadStream(filePath, { encoding: "utf8" });
readableStream.on("data", chunk => {
response.emit("data", new Buffer(chunk));
client.emit("data", new Buffer(chunk));
});
readableStream.on("end", () => {
response.emit("end");
client.emit("end");
});
readableStream.on("error", err => {
response.emit("error", err);
client.emit("error", err);
});
client.abort = function () {
readableStream.destroy();
client.emit("abort");
};
if (requestManager) {
const req = {
abort() {
xhr.abort();
}
};
requestManager.add(req);
const rmReq = requestManager.remove.bind(requestManager, req);
client.on("abort", rmReq);
client.on("error", rmReq);
client.on("end", rmReq);
}
process.nextTick(() => callback(null, response));
return client;
}
if (urlObj.protocol === "data:") {
const response = new EventEmitter();
let buffer;
if (flag.method === "GET") {
try {
const dataUrlContent = utils.parseDataUrl(decodeURI(uri));
buffer = dataUrlContent.buffer;
response.statusCode = 200;
response.rawHeaders = dataUrlContent.type ? ["Content-Type", dataUrlContent.type] : [];
response.headers = dataUrlContent.type ? { "content-type": dataUrlContent.type } : {};
} catch (err) {
process.nextTick(() => callback(err, null));
return null;
}
} else {
buffer = new Buffer("");
response.statusCode = 0;
response.rawHeaders = {};
response.headers = {};
}
const client = new EventEmitter();
client.abort = function () {};
process.nextTick(() => {
callback(null, response);
process.nextTick(() => {
response.emit("data", buffer);
client.emit("data", buffer);
response.emit("end");
client.emit("end");
});
});
return client;
}
const requestHeaders = {};
for (const header in flag.requestHeaders) {
requestHeaders[header] = flag.requestHeaders[header];
}
if (!getRequestHeader(flag.requestHeaders, "Referer")) {
requestHeaders.Referer = flag.baseUrl;
}
if (!getRequestHeader(flag.requestHeaders, "User-Agent")) {
requestHeaders["User-Agent"] = flag.userAgent;
}
if (!getRequestHeader(flag.requestHeaders, "Accept-Language")) {
requestHeaders["Accept-Language"] = "en";
}
if (!getRequestHeader(flag.requestHeaders, "Accept")) {
requestHeaders.Accept = "*/*";
}
const options = {
uri,
method: flag.method,
headers: requestHeaders,
gzip: true,
maxRedirects: 21,
followAllRedirects: true
};
if (flag.auth) {
options.auth = {
user: flag.auth.user || "",
pass: flag.auth.pass || "",
sendImmediately: false
};
}
if (xhr._ownerDocument._cookieJar) {
options.jar = wrapCookieJarForRequest(xhr._ownerDocument._cookieJar);
}
options.pool = xhr._ownerDocument[internalConstants.pool];
options.agentOptions = xhr._ownerDocument[internalConstants.agentOptions];
const body = flag.body;
const hasBody = body !== undefined &&
body !== null &&
body !== "" &&
!(flag.method === "HEAD" || flag.method === "GET");
if (hasBody && !flag.formData) {
options.body = body;
}
try {
const client = request(options)
.on("response", response => callback(null, response))
.on("error", callback);
if (hasBody && flag.formData) {
const form = client.form();
for (const entry of body) {
form.append(entry.name, entry.value, entry.options);
}
}
if (requestManager) {
const req = {
abort() {
xhr.abort();
}
};
requestManager.add(req);
const rmReq = requestManager.remove.bind(requestManager, req);
client.on("abort", rmReq);
client.on("error", rmReq);
client.on("end", rmReq);
}
return client;
} catch (e) {
process.nextTick(() => callback(e));
return null;
}
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/xhr-utils.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,303 |
```javascript
"use strict";
module.exports = Object.freeze({
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2, // historical
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4, // historical
ENTITY_REFERENCE_NODE: 5, // historical
ENTITY_NODE: 6, // historical
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11,
NOTATION_NODE: 12 // historical
});
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/node-type.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 118 |
```javascript
"use strict";
exports.name = Symbol("name");
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/file-symbols.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 11 |
```javascript
"use strict";
const DOMException = require("../web-idl/DOMException");
const defineGetter = require("../utils").defineGetter;
const idlUtils = require("./generated/utils");
const attrGenerated = require("./generated/Attr");
const changeAttributeImpl = require("./attributes/Attr-impl").changeAttributeImpl;
const getAttrImplQualifiedName = require("./attributes/Attr-impl").getAttrImplQualifiedName;
// path_to_url#namednodemap
const INTERNAL = Symbol("NamedNodeMap internal");
// TODO: use NamedPropertyTracker when path_to_url lands?
// Don't emulate named getters for these properties.
// Compiled later after NamedNodeMap is all set up.
const reservedNames = new Set();
function NamedNodeMap() {
throw new TypeError("Illegal constructor");
}
defineGetter(NamedNodeMap.prototype, "length", function () {
return this[INTERNAL].attributeList.length;
});
NamedNodeMap.prototype.item = function (index) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to NamedNodeMap.prototype.item");
}
// Don't bother with full unsigned long long conversion. When we have better WebIDL support generally, revisit.
index = Number(index);
return this[index] || null;
};
NamedNodeMap.prototype.getNamedItem = function (name) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to NamedNodeMap.prototype.getNamedItem");
}
name = String(name);
return exports.getAttributeByName(this[INTERNAL].element, name);
};
NamedNodeMap.prototype.getNamedItemNS = function (namespace, localName) {
if (arguments.length < 2) {
throw new TypeError("Not enough arguments to NamedNodeMap.prototype.getNamedItemNS");
}
if (namespace === undefined || namespace === null) {
namespace = null;
} else {
namespace = String(namespace);
}
localName = String(localName);
return exports.getAttributeByNameNS(this[INTERNAL].element, namespace, localName);
};
NamedNodeMap.prototype.setNamedItem = function (attr) {
if (!attrGenerated.is(attr)) {
throw new TypeError("First argument to NamedNodeMap.prototype.setNamedItem must be an Attr");
}
return exports.setAttribute(this[INTERNAL].element, attr);
};
NamedNodeMap.prototype.setNamedItemNS = function (attr) {
if (!attrGenerated.is(attr)) {
throw new TypeError("First argument to NamedNodeMap.prototype.setNamedItemNS must be an Attr");
}
return exports.setAttribute(this[INTERNAL].element, attr);
};
NamedNodeMap.prototype.removeNamedItem = function (name) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to NamedNodeMap.prototype.getNamedItem");
}
name = String(name);
const attr = exports.removeAttributeByName(this[INTERNAL].element, name);
if (attr === null) {
throw new DOMException(DOMException.NOT_FOUND_ERR, "Tried to remove an attribute that was not present");
}
return attr;
};
NamedNodeMap.prototype.removeNamedItemNS = function (namespace, localName) {
if (arguments.length < 2) {
throw new TypeError("Not enough arguments to NamedNodeMap.prototype.removeNamedItemNS");
}
if (namespace === undefined || namespace === null) {
namespace = null;
} else {
namespace = String(namespace);
}
localName = String(localName);
const attr = exports.removeAttributeByNameNS(this[INTERNAL].element, namespace, localName);
if (attr === null) {
throw new DOMException(DOMException.NOT_FOUND_ERR, "Tried to remove an attribute that was not present");
}
return attr;
};
exports.NamedNodeMap = NamedNodeMap;
{
let prototype = NamedNodeMap.prototype;
while (prototype) {
for (const name of Object.getOwnPropertyNames(prototype)) {
reservedNames.add(name);
}
prototype = Object.getPrototypeOf(prototype);
}
}
exports.createNamedNodeMap = function (element) {
const nnm = Object.create(NamedNodeMap.prototype);
nnm[INTERNAL] = {
element,
attributeList: [],
attributesByNameMap: new Map()
};
return nnm;
};
// The following three are for path_to_url#concept-element-attribute-has. We don't just have a
// predicate tester since removing that kind of flexibility gives us the potential for better future optimizations.
exports.hasAttribute = function (element, A) {
const attributesNNM = element._attributes;
const attributeList = attributesNNM[INTERNAL].attributeList;
return attributeList.indexOf(A) !== -1;
};
exports.hasAttributeByName = function (element, name) {
const attributesNNM = element._attributes;
const attributesByNameMap = attributesNNM[INTERNAL].attributesByNameMap;
return attributesByNameMap.has(name);
};
exports.hasAttributeByNameNS = function (element, namespace, localName) {
const attributesNNM = element._attributes;
const attributeList = attributesNNM[INTERNAL].attributeList;
return attributeList.some(attribute => {
const impl = idlUtils.implForWrapper(attribute);
return impl && impl._localName === localName && impl._namespace === namespace;
});
};
exports.changeAttribute = function (element, attribute, value) {
// path_to_url#concept-element-attributes-change
// The partitioning here works around a particularly bad circular require problem. See
// path_to_url#issuecomment-149060470
changeAttributeImpl(element, idlUtils.implForWrapper(attribute), value);
};
exports.appendAttribute = function (element, attribute) {
// path_to_url#concept-element-attributes-append
const impl = idlUtils.implForWrapper(attribute);
const attributesNNM = element._attributes;
const attributeList = attributesNNM[INTERNAL].attributeList;
// TODO mutation observer stuff
attributeList.push(attribute);
impl._element = element;
// Sync target indexed properties
attributesNNM[attributeList.length - 1] = attribute;
// Sync target named properties
const name = getAttrImplQualifiedName(impl);
if (!reservedNames.has(name)) {
attributesNNM[name] = attribute;
}
// Sync name cache
const cache = attributesNNM[INTERNAL].attributesByNameMap;
let entry = cache.get(name);
if (!entry) {
entry = [];
cache.set(name, entry);
}
entry.push(attribute);
// Run jsdom hooks; roughly correspond to spec's "An attribute is set and an attribute is added."
element._attrModified(name, impl._value, null);
};
exports.removeAttribute = function (element, attribute) {
// path_to_url#concept-element-attributes-remove
const attributesNNM = element._attributes;
const attributeList = attributesNNM[INTERNAL].attributeList;
// TODO mutation observer stuff
for (let i = 0; i < attributeList.length; ++i) {
if (attributeList[i] === attribute) {
const impl = idlUtils.implForWrapper(attribute);
attributeList.splice(i, 1);
impl._element = null;
// Sync target indexed properties
for (let j = i; j < attributeList.length; ++j) {
attributesNNM[j] = attributeList[j];
}
delete attributesNNM[attributeList.length];
// Sync target named properties
const name = getAttrImplQualifiedName(impl);
if (!reservedNames.has(name)) {
delete attributesNNM[name];
}
// Sync name cache
const cache = attributesNNM[INTERNAL].attributesByNameMap;
const entry = cache.get(name);
entry.splice(entry.indexOf(attribute), 1);
if (entry.length === 0) {
cache.delete(name);
}
// Run jsdom hooks; roughly correspond to spec's "An attribute is removed."
element._attrModified(name, null, impl._value);
return;
}
}
};
exports.getAttributeByName = function (element, name) {
// path_to_url#concept-element-attributes-get-by-name
if (element._namespaceURI === "path_to_url" &&
element._ownerDocument._parsingMode === "html") {
name = name.toLowerCase();
}
const cache = element._attributes[INTERNAL].attributesByNameMap;
const entry = cache.get(name);
if (!entry) {
return null;
}
return entry[0];
};
exports.getAttributeValue = function (element, name) {
const attr = exports.getAttributeByName(element, name);
if (!attr) {
return null;
}
return idlUtils.implForWrapper(attr)._value;
};
exports.getAttributeByNameNS = function (element, namespace, localName) {
// path_to_url#concept-element-attributes-get-by-namespace
if (namespace === "") {
namespace = null;
}
const attributeList = element._attributes[INTERNAL].attributeList;
for (let i = 0; i < attributeList.length; ++i) {
const attr = attributeList[i];
const impl = idlUtils.implForWrapper(attr);
if (impl._namespace === namespace && impl._localName === localName) {
return attr;
}
}
return null;
};
exports.getAttributeValueByNameNS = function (element, namespace, localName) {
const attr = exports.getAttributeByNameNS(element, namespace, localName);
if (!attr) {
return null;
}
return idlUtils.implForWrapper(attr)._value;
};
exports.setAttribute = function (element, attr) {
// path_to_url#concept-element-attributes-set
const impl = idlUtils.implForWrapper(attr);
if (impl._element !== null && impl._element !== element) {
throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR);
}
const oldAttr = exports.getAttributeByNameNS(element, impl._namespace, impl._localName);
if (oldAttr === attr) {
return attr;
}
if (oldAttr !== null) {
exports.removeAttribute(element, oldAttr);
}
exports.appendAttribute(element, attr);
return oldAttr;
};
exports.setAttributeValue = function (element, localName, value, prefix, namespace) {
// path_to_url#concept-element-attributes-set-value
if (prefix === undefined) {
prefix = null;
}
if (namespace === undefined) {
namespace = null;
}
const attribute = exports.getAttributeByNameNS(element, namespace, localName);
if (attribute === null) {
const newAttribute = attrGenerated.create([], { namespace, namespacePrefix: prefix, localName, value });
exports.appendAttribute(element, newAttribute);
return;
}
exports.changeAttribute(element, attribute, value);
};
exports.removeAttributeByName = function (element, name) {
// path_to_url#concept-element-attributes-remove-by-name
const attr = exports.getAttributeByName(element, name);
if (attr !== null) {
exports.removeAttribute(element, attr);
}
return attr;
};
exports.removeAttributeByNameNS = function (element, namespace, localName) {
// path_to_url#concept-element-attributes-remove-by-namespace
const attr = exports.getAttributeByNameNS(element, namespace, localName);
if (attr !== null) {
exports.removeAttribute(element, attr);
}
return attr;
};
exports.copyAttributeList = function (sourceElement, destElement) {
// Needed by path_to_url#concept-node-clone
for (const sourceAttr of sourceElement._attributes[INTERNAL].attributeList) {
const sourceImpl = idlUtils.implForWrapper(sourceAttr);
const destAttr = attrGenerated.create([], {
namespace: sourceImpl._namespace,
prefix: sourceImpl._prefix,
localName: sourceImpl._localName,
value: sourceImpl._value
});
exports.appendAttribute(destElement, destAttr);
}
};
exports.attributeListsEqual = function (elementA, elementB) {
// Needed by path_to_url#concept-node-equals
const listA = elementA._attributes[INTERNAL].attributeList;
const listB = elementB._attributes[INTERNAL].attributeList;
if (listA.length !== listB.length) {
return false;
}
for (let i = 0; i < listA.length; ++i) {
const attrA = listA[i];
const implA = idlUtils.implForWrapper(attrA);
if (!listB.some(attrB => equalsA(attrB))) {
return false;
}
function equalsA(attrB) {
const implB = idlUtils.implForWrapper(attrB);
return implA._namespace === implB._namespace && implA._localName === implB._localName &&
implA._value === implB._value;
}
}
return true;
};
exports.hasAttributes = function (element) {
// Needed by path_to_url#dom-element-hasattributes
return element._attributes[INTERNAL].attributeList.length > 0;
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/attributes.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 2,786 |
```javascript
"use strict";
exports.list = Symbol("list");
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/filelist-symbols.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 11 |
```javascript
"use strict";
const lengthFromProperties = require("../utils").lengthFromProperties;
const getAttributeValue = require("./attributes").getAttributeValue;
const privates = Symbol("HTMLCollection internal slots");
class HTMLCollection {
constructor(secret, element, query) {
if (secret !== privates) {
throw new TypeError("Invalid constructor");
}
this[privates] = { element, query, snapshot: undefined, keys: [], length: 0, version: -1 };
updateHTMLCollection(this);
}
get length() {
updateHTMLCollection(this);
return this[privates].length;
}
item(index) {
updateHTMLCollection(this);
return this[index] || null;
}
namedItem(name) {
updateHTMLCollection(this);
if (Object.prototype.hasOwnProperty.call(this, name)) {
return this[name];
}
return null;
}
}
function updateHTMLCollection(collection) {
if (collection[privates].version < collection[privates].element._version) {
collection[privates].snapshot = collection[privates].query();
resetHTMLCollectionTo(collection, collection[privates].snapshot);
collection[privates].version = collection[privates].element._version;
}
}
function resetHTMLCollectionTo(collection, els) {
const startingLength = lengthFromProperties(collection);
for (let i = 0; i < startingLength; ++i) {
delete collection[i];
}
for (let i = 0; i < els.length; ++i) {
collection[i] = els[i];
}
collection[privates].length = els.length;
const keys = collection[privates].keys;
for (let i = 0; i < keys.length; ++i) {
delete collection[keys[i]];
}
keys.length = 0;
for (let i = 0; i < els.length; ++i) {
addIfAttrPresent(els[i], "name");
}
for (let i = 0; i < els.length; ++i) {
addIfAttrPresent(els[i], "id");
}
function addIfAttrPresent(el, attr) {
const value = getAttributeValue(el, attr);
if (value === null || value === "") {
return;
}
// Don't overwrite numeric indices with named ones.
const valueAsNumber = Number(value);
if (!Number.isNaN(valueAsNumber) && valueAsNumber >= 0) {
return;
}
collection[value] = el;
keys.push(value);
}
}
module.exports = function (core) {
core.HTMLCollection = HTMLCollection;
};
module.exports.create = function (element, query) {
return new HTMLCollection(privates, element, query);
};
module.exports.update = updateHTMLCollection;
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/html-collection.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 602 |
```javascript
"use strict";
module.exports = function (core) {
const XMLHttpRequestEventTarget = core.XMLHttpRequestEventTarget;
class XMLHttpRequestUpload extends XMLHttpRequestEventTarget {
constructor() {
super();
if (!(this instanceof XMLHttpRequestUpload)) {
throw new TypeError("DOM object constructor cannot be called as a function.");
}
}
}
core.XMLHttpRequestUpload = XMLHttpRequestUpload;
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/xmlhttprequest-upload.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 80 |
```javascript
"use strict";
const addConstants = require("../utils").addConstants;
module.exports = function (core) {
// path_to_url#interface-nodefilter
core.NodeFilter = function () {
throw new TypeError("Illegal constructor");
};
/**
* Returns an unsigned short that will be used to tell if a given Node must
* be accepted or not by the NodeIterator or TreeWalker iteration
* algorithm. This method is expected to be written by the user of a
* NodeFilter.
*
* @see path_to_url
* @interface
*
* @param {Node} node DOM Node
* @return {FILTER_ACCEPT|FILTER_REJECT|FILTER_SKIP}
*/
core.NodeFilter.acceptNode = function (/* node */) {
throw new Error("This method is expected to be written by the user of a NodeFilter.");
};
addConstants(core.NodeFilter, {
// Constants for whatToShow
SHOW_ALL: 0xFFFFFFFF,
SHOW_ELEMENT: 0x00000001,
SHOW_ATTRIBUTE: 0x00000002,
SHOW_TEXT: 0x00000004,
SHOW_CDATA_SECTION: 0x00000008,
SHOW_ENTITY_REFERENCE: 0x00000010,
SHOW_ENTITY: 0x00000020,
SHOW_PROCESSING_INSTRUCTION: 0x00000040,
SHOW_COMMENT: 0x00000080,
SHOW_DOCUMENT: 0x00000100,
SHOW_DOCUMENT_TYPE: 0x00000200,
SHOW_DOCUMENT_FRAGMENT: 0x00000400,
SHOW_NOTATION: 0x00000800,
// Constants returned by acceptNode
FILTER_ACCEPT: 1,
FILTER_REJECT: 2,
FILTER_SKIP: 3
});
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/node-filter.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 386 |
```javascript
"use strict";
const isValidTargetOrigin = require("../utils").isValidTargetOrigin;
const DOMException = require("../web-idl/DOMException");
module.exports = function (message, targetOrigin) {
if (arguments.length < 2) {
throw new TypeError("'postMessage' requires 2 arguments: 'message' and 'targetOrigin'");
}
targetOrigin = String(targetOrigin);
if (!isValidTargetOrigin(targetOrigin)) {
throw new DOMException(DOMException.SYNTAX_ERR, "Failed to execute 'postMessage' on 'Window': " +
"Invalid target origin '" + targetOrigin + "' in a call to 'postMessage'.");
}
// TODO: targetOrigin === '/' - requires reference to source window
// See path_to_url#issuecomment-111587499
if (targetOrigin !== "*" && targetOrigin !== this.origin) {
return;
}
// TODO: event.source - requires reference to source window
// TODO: event.origin - requires reference to source window
// TODO: event.ports
// TODO: event.data - structured clone message - requires cloning DOM nodes
const event = new this.MessageEvent("message", {
data: message
});
event.initEvent("message", false, false);
setTimeout(() => {
this.dispatchEvent(event);
}, 0);
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/post-message.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 286 |
```javascript
"use strict";
const core = module.exports = require("../level1/core");
// These (because of how they were written) directly include level1/core and modify it.
// ORDER IS IMPORTANT
require("../level2/core");
require("../level2/events");
require("../level2/html");
require("../level2/style");
require("../level3/core");
require("../level3/ls");
require("../level3/xpath");
require("./document-type")(core);
require("./character-data")(core);
require("./processing-instruction")(core);
require("./comment")(core);
require("./text")(core);
require("./dom-implementation")(core);
require("./document")(core);
require("./element")(core);
require("./html-collection")(core);
require("./node-filter")(core);
require("./node-iterator")(core);
require("./node-list")(core);
require("./node")(core);
require("./selectors")(core);
require("./parent-node")(core);
require("./non-document-type-child-node")(core);
require("./url")(core);
require("./blob")(core);
require("./file")(core);
require("./filelist")(core);
require("./form-data")(core);
require("./xmlhttprequest-event-target")(core);
require("./xmlhttprequest-upload")(core);
core.Attr = require("./generated/Attr").interface;
core.DOMTokenList = require("./dom-token-list").DOMTokenList;
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/index.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 274 |
```javascript
"use strict";
const defineGetter = require("../utils").defineGetter;
const domSymbolTree = require("./helpers/internal-constants").domSymbolTree;
const NODE_TYPE = require("./node-type");
module.exports = function (core) {
// path_to_url#nondocumenttypechildnode
for (const Constructor of [core.Element, core.CharacterData]) {
defineGetter(Constructor.prototype, "nextElementSibling", function () {
for (const sibling of domSymbolTree.nextSiblingsIterator(this)) {
if (sibling.nodeType === NODE_TYPE.ELEMENT_NODE) {
return sibling;
}
}
return null;
});
defineGetter(Constructor.prototype, "previousElementSibling", function () {
for (const sibling of domSymbolTree.previousSiblingsIterator(this)) {
if (sibling.nodeType === NODE_TYPE.ELEMENT_NODE) {
return sibling;
}
}
return null;
});
}
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/non-document-type-child-node.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 195 |
```javascript
"use strict";
const domSymbolTree = require("./helpers/internal-constants").domSymbolTree;
const defineGetter = require("../utils").defineGetter;
const INTERNAL = Symbol("NodeIterator internal");
module.exports = function (core) {
// path_to_url#interface-nodeiterator
function NodeIteratorInternal(document, root, whatToShow, filter) {
this.active = true;
this.document = document;
this.root = root;
this.referenceNode = root;
this.pointerBeforeReferenceNode = true;
this.whatToShow = whatToShow;
this.filter = filter;
}
NodeIteratorInternal.prototype.throwIfNotActive = function () {
// (only thrown for getters/methods that are affected by removing steps)
if (!this.active) {
throw Error("This NodeIterator is no longer active. " +
"More than " + this.document._activeNodeIteratorsMax +
" iterators are being used concurrently. " +
"You can increase the 'concurrentNodeIterators' option to " +
"make this error go away."
);
// Alternatively, you can pester Ecma to add support for weak references,
// the DOM standard assumes the implementor has control over object life cycles.
}
};
NodeIteratorInternal.prototype.traverse = function (next) {
let node = this.referenceNode;
let beforeNode = this.pointerBeforeReferenceNode;
do {
if (next) {
if (!beforeNode) {
node = domSymbolTree.following(node, { root: this.root });
if (!node) {
return null;
}
}
beforeNode = false;
} else { // previous
if (beforeNode) {
node = domSymbolTree.preceding(node, { root: this.root });
if (!node) {
return null;
}
}
beforeNode = true;
}
}
while (this.filterNode(node) !== core.NodeFilter.FILTER_ACCEPT);
this.pointerBeforeReferenceNode = beforeNode;
this.referenceNode = node;
return node;
};
NodeIteratorInternal.prototype.filterNode = function (node) {
const n = node.nodeType - 1;
if (!(this.whatToShow & (1 << n))) {
return core.NodeFilter.FILTER_SKIP;
}
let ret = core.NodeFilter.FILTER_ACCEPT;
const filter = this.filter;
if (typeof filter === "function") {
ret = filter(node);
} else if (filter && typeof filter.acceptNode === "function") {
ret = filter.acceptNode(node);
}
if (ret === true) {
return core.NodeFilter.FILTER_ACCEPT;
} else if (ret === false) {
return core.NodeFilter.FILTER_REJECT;
}
return ret;
};
NodeIteratorInternal.prototype.runRemovingSteps = function (oldNode, oldParent, oldPreviousSibling) {
if (oldNode.contains(this.root)) {
return;
}
// If oldNode is not an inclusive ancestor of the referenceNode
// attribute value, terminate these steps.
if (!oldNode.contains(this.referenceNode)) {
return;
}
if (this.pointerBeforeReferenceNode) {
// Let nextSibling be oldPreviousSiblings next sibling, if oldPreviousSibling is non-null,
// and oldParents first child otherwise.
const nextSibling = oldPreviousSibling ?
oldPreviousSibling.nextSibling :
oldParent.firstChild;
// If nextSibling is non-null, set the referenceNode attribute to nextSibling
// and terminate these steps.
if (nextSibling) {
this.referenceNode = nextSibling;
return;
}
// Let next be the first node following oldParent (excluding any children of oldParent).
const next = domSymbolTree.following(oldParent, { skipChildren: true });
// If root is an inclusive ancestor of next, set the referenceNode
// attribute to next and terminate these steps.
if (this.root.contains(next)) {
this.referenceNode = next;
return;
}
// Otherwise, set the pointerBeforeReferenceNode attribute to false.
this.pointerBeforeReferenceNode = false;
// Note: Steps are not terminated here.
}
// Set the referenceNode attribute to the last inclusive descendant in tree order of oldPreviousSibling,
// if oldPreviousSibling is non-null, and to oldParent otherwise.
this.referenceNode = oldPreviousSibling ?
domSymbolTree.lastInclusiveDescendant(oldPreviousSibling) :
oldParent;
};
core.Document._removingSteps.push((document, oldNode, oldParent, oldPreviousSibling) => {
for (let i = 0; i < document._activeNodeIterators.length; ++i) {
const internal = document._activeNodeIterators[i];
internal.runRemovingSteps(oldNode, oldParent, oldPreviousSibling);
}
});
core.Document.prototype.createNodeIterator = function (root, whatToShow, filter) {
if (!root) {
throw new TypeError("Not enough arguments to Document.createNodeIterator.");
}
if (filter === undefined) {
filter = null;
}
if (filter !== null &&
typeof filter !== "function" &&
typeof filter.acceptNode !== "function") {
throw new TypeError("Argument 3 of Document.createNodeIterator should be a function or implement NodeFilter.");
}
const document = root._ownerDocument;
whatToShow = whatToShow === undefined ?
core.NodeFilter.SHOW_ALL :
(whatToShow & core.NodeFilter.SHOW_ALL) >>> 0; // >>> makes sure the result is unsigned
filter = filter || null;
const it = Object.create(core.NodeIterator.prototype);
const internal = new NodeIteratorInternal(document, root, whatToShow, filter);
it[INTERNAL] = internal;
document._activeNodeIterators.push(internal);
while (document._activeNodeIterators.length > document._activeNodeIteratorsMax) {
const internalOther = document._activeNodeIterators.shift();
internalOther.active = false;
}
return it;
};
core.NodeIterator = function NodeIterator() {
throw new TypeError("Illegal constructor");
};
defineGetter(core.NodeIterator.prototype, "root", function () {
return this[INTERNAL].root;
});
defineGetter(core.NodeIterator.prototype, "referenceNode", function () {
const internal = this[INTERNAL];
internal.throwIfNotActive();
return internal.referenceNode;
});
defineGetter(core.NodeIterator.prototype, "pointerBeforeReferenceNode", function () {
const internal = this[INTERNAL];
internal.throwIfNotActive();
return internal.pointerBeforeReferenceNode;
});
defineGetter(core.NodeIterator.prototype, "whatToShow", function () {
return this[INTERNAL].whatToShow;
});
defineGetter(core.NodeIterator.prototype, "filter", function () {
return this[INTERNAL].filter;
});
core.NodeIterator.prototype.previousNode = function () {
const internal = this[INTERNAL];
internal.throwIfNotActive();
return internal.traverse(false);
};
core.NodeIterator.prototype.nextNode = function () {
const internal = this[INTERNAL];
internal.throwIfNotActive();
return internal.traverse(true);
};
core.NodeIterator.prototype.detach = function () {
// noop
};
core.NodeIterator.prototype.toString = function () {
return "[object NodeIterator]";
};
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/node-iterator.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,571 |
```javascript
"use strict";
const validateNames = require("./helpers/validate-names");
const createDocumentTypeInternal = require("./document-type").create;
module.exports = function (core) {
core.DOMImplementation.prototype.hasFeature = function () {
return true;
};
core.DOMImplementation.prototype.createDocumentType = function (qualifiedName, publicId, systemId) {
if (arguments.length < 3) {
throw new TypeError("Expected 3 arguments to createDocumentType");
}
qualifiedName = String(qualifiedName);
publicId = String(publicId);
systemId = String(systemId);
validateNames.qname(qualifiedName);
return createDocumentTypeInternal(core, this._ownerDocument, qualifiedName, publicId, systemId);
};
core.DOMImplementation.prototype.createDocument = function (namespace, qualifiedName, doctype) {
namespace = namespace !== null ? String(namespace) : namespace;
qualifiedName = qualifiedName === null ? "" : String(qualifiedName);
if (doctype === undefined) {
doctype = null;
}
const document = new core.Document({ parsingMode: "xml" });
let element = null;
if (qualifiedName !== "") {
element = document.createElementNS(namespace, qualifiedName);
}
if (doctype !== null) {
document.appendChild(doctype);
}
if (element !== null) {
document.appendChild(element);
}
return document;
};
core.DOMImplementation.prototype.createHTMLDocument = function (title) {
// Let doc be a new document that is an HTML document.
// Set doc's content type to "text/html".
const document = new core.HTMLDocument({ parsingMode: "html" });
// Create a doctype, with "html" as its name and with its node document set
// to doc. Append the newly created node to doc.
const doctype = createDocumentTypeInternal(core, this, "html", "", "");
document.appendChild(doctype);
// Create an html element in the HTML namespace, and append it to doc.
const htmlElement = document.createElementNS("path_to_url", "html");
document.appendChild(htmlElement);
// Create a head element in the HTML namespace, and append it to the html
// element created in the previous step.
const headElement = document.createElement("head");
htmlElement.appendChild(headElement);
// If the title argument is not omitted:
if (title !== undefined) {
// Create a title element in the HTML namespace, and append it to the head
// element created in the previous step.
const titleElement = document.createElement("title");
headElement.appendChild(titleElement);
// Create a Text node, set its data to title (which could be the empty
// string), and append it to the title element created in the previous step.
titleElement.appendChild(document.createTextNode(title));
}
// Create a body element in the HTML namespace, and append it to the html
// element created in the earlier step.
htmlElement.appendChild(document.createElement("body"));
// doc's origin is an alias to the origin of the context object's associated
// document, and doc's effective script origin is an alias to the effective
// script origin of the context object's associated document.
return document;
};
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/dom-implementation.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 696 |
```javascript
"use strict";
const NODE_TYPE = require("../living/node-type");
const privates = Symbol("DocumentType internal slots");
module.exports = core => {
core.DocumentType = class DocumentType extends core.Node {
constructor(secret, ownerDocument, name, publicId, systemId) {
if (secret !== privates) {
throw new TypeError("Invalid constructor");
}
super(ownerDocument);
this[privates] = { name, publicId, systemId };
}
get name() {
return this[privates].name;
}
get publicId() {
return this[privates].publicId;
}
get systemId() {
return this[privates].systemId;
}
};
core.DocumentType.prototype.nodeType = NODE_TYPE.DOCUMENT_TYPE_NODE; // TODO should be on Node, not here
};
module.exports.create = (core, ownerDocument, name, publicId, systemId) => {
return new core.DocumentType(privates, ownerDocument, name, publicId, systemId);
};
module.exports.clone = (core, otherDoctype) => {
return new core.DocumentType(
privates,
otherDoctype._ownerDocument,
otherDoctype[privates].name,
otherDoctype[privates].publicId,
otherDoctype[privates].systemId
);
};
module.exports.getPrivates = doctype => {
return doctype[privates];
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/document-type.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 307 |
```javascript
"use strict";
const DOMException = require("../web-idl/DOMException");
const EventTarget = require("./generated/EventTarget");
const addConstants = require("../utils").addConstants;
const blobSymbols = require("./blob-symbols");
function FileReaderEventTarget() {
if (!(this instanceof FileReaderEventTarget)) {
throw new TypeError("DOM object constructor cannot be called as a function.");
}
EventTarget.setup(this);
}
FileReaderEventTarget.prototype = Object.create(EventTarget.interface.prototype);
module.exports = function createFileReader(window) {
const ProgressEvent = window.ProgressEvent;
class FileReader extends FileReaderEventTarget {
constructor() {
super();
this.error = null;
this.readyState = FileReader.EMPTY;
this.result = null;
this.onloadstart = null;
this.onprogress = null;
this.onload = null;
this.onabort = null;
this.onerror = null;
this.onloadend = null;
}
readAsArrayBuffer(file) {
readFile(this, file, "buffer");
}
readAsBinaryString(file) {
readFile(this, file, "binary");
}
readAsDataURL(file) {
readFile(this, file, "dataUrl");
}
readAsText(file, encoding) {
readFile(this, file, "text", encoding);
}
abort() {
if (this.readyState === this.DONE || this.readyState === this.EMPTY) {
this.result = null;
return;
}
if (this.readyState === this.LOADING) {
this.readyState = this.DONE;
}
this.dispatchEvent(new ProgressEvent("abort"));
this.dispatchEvent(new ProgressEvent("loadend"));
}
get _ownerDocument() {
return window.document;
}
}
addConstants(FileReader, {
EMPTY: 0,
LOADING: 1,
DONE: 2
});
function readFile(self, file, format, encoding) {
if (self.readyState === self.LOADING) {
throw new DOMException(DOMException.INVALID_STATE_ERR);
}
if (file[blobSymbols.closed]) {
self.error = new DOMException(DOMException.INVALID_STATE_ERR);
self.dispatchEvent(new ProgressEvent("error"));
}
self.readyState = self.LOADING;
self.dispatchEvent(new ProgressEvent("loadstart"));
process.nextTick(() => {
let data = file[blobSymbols.buffer];
if (!data) {
data = new Buffer("");
}
self.dispatchEvent(new ProgressEvent("progress", {
lengthComputable: !isNaN(file.size),
total: file.size,
loaded: data.length
}));
process.nextTick(() => {
self.readyState = self.DONE;
switch (format) {
default:
case "buffer":
const ab = new ArrayBuffer(data.length);
const view = new Uint8Array(ab);
for (let i = 0; i < data.length; ++i) {
view[i] = data[i];
}
self.result = ab;
break;
case "binary":
self.result = data.toString("binary");
break;
case "dataUrl":
let dataUrl = "data:";
if (file.type) {
dataUrl += file.type + ";";
}
if (/text/i.test(file.type)) {
dataUrl += "charset=utf-8,";
dataUrl += data.toString("utf8");
} else {
dataUrl += "base64,";
dataUrl += data.toString("base64");
}
self.result = dataUrl;
break;
case "text":
if (encoding) {
encoding = encoding.toLowerCase();
if (encoding === "utf-16" || encoding === "utf16") {
encoding = "utf-16le";
}
} else {
encoding = "utf8";
}
self.result = data.toString(encoding);
break;
}
self.dispatchEvent(new ProgressEvent("load"));
process.nextTick(() => {
if (self.readyState !== self.LOADING) {
self.dispatchEvent(new ProgressEvent("loadend"));
}
});
});
});
}
return FileReader;
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/file-reader.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 877 |
```javascript
/** Here is yet another implementation of XPath 1.0 in Javascript.
*
* My goal was to make it relatively compact, but as I fixed all the axis bugs
* the axes became more and more complicated. :-(.
*
* I have not implemented namespaces or case-sensitive axes for XML yet.
*
* How to test it in Chrome: You can make a Chrome extension that replaces
* the WebKit XPath parser with this one. But it takes a bit of effort to
* get around isolated world and same-origin restrictions:
* manifest.json:
{
"name": "XPathTest",
"version": "0.1",
"content_scripts": [{
"matches": ["path_to_url"], // or wildcard host
"js": ["xpath.js", "injection.js"],
"all_frames": true, "run_at": "document_start"
}]
}
* injection.js:
// goal: give my xpath object to the website's JS context.
var script = document.createElement('script');
script.textContent =
"document.addEventListener('xpathextend', function(e) {\n" +
" console.log('extending document with xpath...');\n" +
" e.detail(window);" +
"});";
document.documentElement.appendChild(script);
document.documentElement.removeChild(script);
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent('xpathextend', true, true, this.xpath.extend);
document.dispatchEvent(evt);
*/
(function() {
var xpath;
var core;
if ('function' === typeof require) {
xpath = exports; // the tests go through this
core = require("../living");
} else {
xpath = {};
core = this;
}
// Helper function to deal with the migration of Attr to no longer have a nodeName property despite this codebase
// assuming it does.
function getNodeName(nodeOrAttr) {
return nodeOrAttr.constructor.name === 'Attr' ? nodeOrAttr.name : nodeOrAttr.nodeName;
}
/***************************************************************************
* Tokenization *
***************************************************************************/
/**
* The XPath lexer is basically a single regular expression, along with
* some helper functions to pop different types.
*/
var Stream = xpath.Stream = function Stream(str) {
this.original = this.str = str;
this.peeked = null;
// TODO: not really needed, but supposedly tokenizer also disambiguates
// a * b vs. node test *
this.prev = null; // for debugging
this.prevprev = null;
}
Stream.prototype = {
peek: function() {
if (this.peeked) return this.peeked;
var m = this.re.exec(this.str);
if (!m) return null;
this.str = this.str.substr(m[0].length);
return this.peeked = m[1];
},
/** Peek 2 tokens ahead. */
peek2: function() {
this.peek(); // make sure this.peeked is set
var m = this.re.exec(this.str);
if (!m) return null;
return m[1];
},
pop: function() {
var r = this.peek();
this.peeked = null;
this.prevprev = this.prev;
this.prev = r;
return r;
},
trypop: function(tokens) {
var tok = this.peek();
if (tok === tokens) return this.pop();
if (Array.isArray(tokens)) {
for (var i = 0; i < tokens.length; ++i) {
var t = tokens[i];
if (t == tok) return this.pop();;
}
}
},
trypopfuncname: function() {
var tok = this.peek();
if (!this.isQnameRe.test(tok))
return null;
switch (tok) {
case 'comment': case 'text': case 'processing-instruction': case 'node':
return null;
}
if ('(' != this.peek2()) return null;
return this.pop();
},
trypopaxisname: function() {
var tok = this.peek();
switch (tok) {
case 'ancestor': case 'ancestor-or-self': case 'attribute':
case 'child': case 'descendant': case 'descendant-or-self':
case 'following': case 'following-sibling': case 'namespace':
case 'parent': case 'preceding': case 'preceding-sibling': case 'self':
if ('::' == this.peek2()) return this.pop();
}
return null;
},
trypopnametest: function() {
var tok = this.peek();
if ('*' === tok || this.startsWithNcNameRe.test(tok)) return this.pop();
return null;
},
trypopliteral: function() {
var tok = this.peek();
if (null == tok) return null;
var first = tok.charAt(0);
var last = tok.charAt(tok.length - 1);
if ('"' === first && '"' === last ||
"'" === first && "'" === last) {
this.pop();
return tok.substr(1, tok.length - 2);
}
},
trypopnumber: function() {
var tok = this.peek();
if (this.isNumberRe.test(tok)) return parseFloat(this.pop());
else return null;
},
trypopvarref: function() {
var tok = this.peek();
if (null == tok) return null;
if ('$' === tok.charAt(0)) return this.pop().substr(1);
else return null;
},
position: function() {
return this.original.length - this.str.length;
}
};
(function() {
// path_to_url#NT-NCName
var nameStartCharsExceptColon =
'A-Z_a-z\xc0-\xd6\xd8-\xf6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF' +
'\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF' +
'\uFDF0-\uFFFD'; // JS doesn't support [#x10000-#xEFFFF]
var nameCharExceptColon = nameStartCharsExceptColon +
'\\-\\.0-9\xb7\u0300-\u036F\u203F-\u2040';
var ncNameChars = '[' + nameStartCharsExceptColon +
'][' + nameCharExceptColon + ']*'
// path_to_url#NT-QName
var qNameChars = ncNameChars + '(?::' + ncNameChars + ')?';
var otherChars = '\\.\\.|[\\(\\)\\[\\].@,]|::'; // .. must come before [.]
var operatorChars =
'and|or|mod|div|' +
'//|!=|<=|>=|[*/|+\\-=<>]'; // //, !=, <=, >= before individual ones.
var literal = '"[^"]*"|' + "'[^']*'";
var numberChars = '[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+';
var variableReference = '\\$' + qNameChars;
var nameTestChars = '\\*|' + ncNameChars + ':\\*|' + qNameChars;
var optionalSpace = '[ \t\r\n]*'; // stricter than regexp \s.
var nodeType = 'comment|text|processing-instruction|node';
var re = new RegExp(
// numberChars before otherChars so that leading-decimal doesn't become .
'^' + optionalSpace + '(' + numberChars + '|' + otherChars + '|' +
nameTestChars + '|' + operatorChars + '|' + literal + '|' +
variableReference + ')'
// operatorName | nodeType | functionName | axisName are lumped into
// qName for now; we'll check them on pop.
);
Stream.prototype.re = re;
Stream.prototype.startsWithNcNameRe = new RegExp('^' + ncNameChars);
Stream.prototype.isQnameRe = new RegExp('^' + qNameChars + '$');
Stream.prototype.isNumberRe = new RegExp('^' + numberChars + '$');
})();
/***************************************************************************
* Parsing *
***************************************************************************/
var parse = xpath.parse = function parse(stream, a) {
var r = orExpr(stream,a);
var x, unparsed = [];
while (x = stream.pop()) {
unparsed.push(x);
}
if (unparsed.length)
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Unparsed tokens: ' + unparsed.join(' '));
return r;
}
/**
* binaryL ::= subExpr
* | binaryL op subExpr
* so a op b op c becomes ((a op b) op c)
*/
function binaryL(subExpr, stream, a, ops) {
var lhs = subExpr(stream, a);
if (lhs == null) return null;
var op;
while (op = stream.trypop(ops)) {
var rhs = subExpr(stream, a);
if (rhs == null)
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Expected something after ' + op);
lhs = a.node(op, lhs, rhs);
}
return lhs;
}
/**
* Too bad this is never used. If they made a ** operator (raise to power),
( we would use it.
* binaryR ::= subExpr
* | subExpr op binaryR
* so a op b op c becomes (a op (b op c))
*/
function binaryR(subExpr, stream, a, ops) {
var lhs = subExpr(stream, a);
if (lhs == null) return null;
var op = stream.trypop(ops);
if (op) {
var rhs = binaryR(stream, a);
if (rhs == null)
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Expected something after ' + op);
return a.node(op, lhs, rhs);
} else {
return lhs;// TODO
}
}
/** [1] LocationPath::= RelativeLocationPath | AbsoluteLocationPath
* e.g. a, a/b, //a/b
*/
function locationPath(stream, a) {
return absoluteLocationPath(stream, a) ||
relativeLocationPath(null, stream, a);
}
/** [2] AbsoluteLocationPath::= '/' RelativeLocationPath? | AbbreviatedAbsoluteLocationPath
* [10] AbbreviatedAbsoluteLocationPath::= '//' RelativeLocationPath
*/
function absoluteLocationPath(stream, a) {
var op = stream.peek();
if ('/' === op || '//' === op) {
var lhs = a.node('Root');
return relativeLocationPath(lhs, stream, a, true);
} else {
return null;
}
}
/** [3] RelativeLocationPath::= Step | RelativeLocationPath '/' Step |
* | AbbreviatedRelativeLocationPath
* [11] AbbreviatedRelativeLocationPath::= RelativeLocationPath '//' Step
* e.g. p/a, etc.
*/
function relativeLocationPath(lhs, stream, a, isOnlyRootOk) {
if (null == lhs) {
lhs = step(stream, a);
if (null == lhs) return lhs;
}
var op;
while (op = stream.trypop(['/', '//'])) {
if ('//' === op) {
lhs = a.node('/', lhs,
a.node('Axis', 'descendant-or-self', 'node', undefined));
}
var rhs = step(stream, a);
if (null == rhs && '/' === op && isOnlyRootOk) return lhs;
else isOnlyRootOk = false;
if (null == rhs)
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Expected step after ' + op);
lhs = a.node('/', lhs, rhs);
}
return lhs;
}
/** [4] Step::= AxisSpecifier NodeTest Predicate* | AbbreviatedStep
* [12] AbbreviatedStep::= '.' | '..'
* e.g. @href, self::p, p, a[@href], ., ..
*/
function step(stream, a) {
var abbrStep = stream.trypop(['.', '..']);
if ('.' === abbrStep) // A location step of . is short for self::node().
return a.node('Axis', 'self', 'node');
if ('..' === abbrStep) // A location step of .. is short for parent::node()
return a.node('Axis', 'parent', 'node');
var axis = axisSpecifier(stream, a);
var nodeType = nodeTypeTest(stream, a);
var nodeName;
if (null == nodeType) nodeName = nodeNameTest(stream, a);
if (null == axis && null == nodeType && null == nodeName) return null;
if (null == nodeType && null == nodeName)
throw new XPathException(
XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Expected nodeTest after axisSpecifier ' + axis);
if (null == axis) axis = 'child';
if (null == nodeType) {
// When there's only a node name, then the node type is forced to be the
// principal node type of the axis.
// see path_to_url#dt-principal-node-type
if ('attribute' === axis) nodeType = 'attribute';
else if ('namespace' === axis) nodeType = 'namespace';
else nodeType = 'element';
}
var lhs = a.node('Axis', axis, nodeType, nodeName);
var pred;
while (null != (pred = predicate(lhs, stream, a))) {
lhs = pred;
}
return lhs;
}
/** [5] AxisSpecifier::= AxisName '::' | AbbreviatedAxisSpecifier
* [6] AxisName::= 'ancestor' | 'ancestor-or-self' | 'attribute' | 'child'
* | 'descendant' | 'descendant-or-self' | 'following'
* | 'following-sibling' | 'namespace' | 'parent' |
* | 'preceding' | 'preceding-sibling' | 'self'
* [13] AbbreviatedAxisSpecifier::= '@'?
*/
function axisSpecifier(stream, a) {
var attr = stream.trypop('@');
if (null != attr) return 'attribute';
var axisName = stream.trypopaxisname();
if (null != axisName) {
var coloncolon = stream.trypop('::');
if (null == coloncolon)
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Should not happen. Should be ::.');
return axisName;
}
}
/** [7] NodeTest::= NameTest | NodeType '(' ')' | 'processing-instruction' '(' Literal ')'
* [38] NodeType::= 'comment' | 'text' | 'processing-instruction' | 'node'
* I've split nodeTypeTest from nodeNameTest for convenience.
*/
function nodeTypeTest(stream, a) {
if ('(' !== stream.peek2()) {
return null;
}
var type = stream.trypop(['comment', 'text', 'processing-instruction', 'node']);
if (null != type) {
if (null == stream.trypop('('))
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Should not happen.');
var param = undefined;
if (type == 'processing-instruction') {
param = stream.trypopliteral();
}
if (null == stream.trypop(')'))
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Expected close parens.');
return type
}
}
function nodeNameTest(stream, a) {
var name = stream.trypopnametest();
if (name != null) return name;
else return null;
}
/** [8] Predicate::= '[' PredicateExpr ']'
* [9] PredicateExpr::= Expr
*/
function predicate(lhs, stream, a) {
if (null == stream.trypop('[')) return null;
var expr = orExpr(stream, a);
if (null == expr)
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Expected expression after [');
if (null == stream.trypop(']'))
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Expected ] after expression.');
return a.node('Predicate', lhs, expr);
}
/** [14] Expr::= OrExpr
*/
/** [15] PrimaryExpr::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall
* e.g. $x, (3+4), "hi", 32, f(x)
*/
function primaryExpr(stream, a) {
var x = stream.trypopliteral();
if (null == x)
x = stream.trypopnumber();
if (null != x) {
return x;
}
var varRef = stream.trypopvarref();
if (null != varRef) return a.node('VariableReference', varRef);
var funCall = functionCall(stream, a);
if (null != funCall) {
return funCall;
}
if (stream.trypop('(')) {
var e = orExpr(stream, a);
if (null == e)
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Expected expression after (.');
if (null == stream.trypop(')'))
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Expected ) after expression.');
return e;
}
return null;
}
/** [16] FunctionCall::= FunctionName '(' ( Argument ( ',' Argument )* )? ')'
* [17] Argument::= Expr
*/
function functionCall(stream, a) {
var name = stream.trypopfuncname(stream, a);
if (null == name) return null;
if (null == stream.trypop('('))
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Expected ( ) after function name.');
var params = [];
var first = true;
while (null == stream.trypop(')')) {
if (!first && null == stream.trypop(','))
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Expected , between arguments of the function.');
first = false;
var param = orExpr(stream, a);
if (param == null)
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Expected expression as argument of function.');
params.push(param);
}
return a.node('FunctionCall', name, params);
}
/** [18] UnionExpr::= PathExpr | UnionExpr '|' PathExpr
*/
function unionExpr(stream, a) { return binaryL(pathExpr, stream, a, '|'); }
/** [19] PathExpr ::= LocationPath
* | FilterExpr
* | FilterExpr '/' RelativeLocationPath
* | FilterExpr '//' RelativeLocationPath
* Unlike most other nodes, this one always generates a node because
* at this point all reverse nodesets must turn into a forward nodeset
*/
function pathExpr(stream, a) {
// We have to do FilterExpr before LocationPath because otherwise
// LocationPath will eat up the name from a function call.
var filter = filterExpr(stream, a);
if (null == filter) {
var loc = locationPath(stream, a);
if (null == loc) {
throw new Error
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': The expression shouldn\'t be empty...');
}
return a.node('PathExpr', loc);
}
var rel = relativeLocationPath(filter, stream, a, false);
if (filter === rel) return rel;
else return a.node('PathExpr', rel);
}
/** [20] FilterExpr::= PrimaryExpr | FilterExpr Predicate
* aka. FilterExpr ::= PrimaryExpr Predicate*
*/
function filterExpr(stream, a) {
var primary = primaryExpr(stream, a);
if (primary == null) return null;
var pred, lhs = primary;
while (null != (pred = predicate(lhs, stream, a))) {
lhs = pred;
}
return lhs;
}
/** [21] OrExpr::= AndExpr | OrExpr 'or' AndExpr
*/
function orExpr(stream, a) {
var orig = (stream.peeked || '') + stream.str
var r = binaryL(andExpr, stream, a, 'or');
var now = (stream.peeked || '') + stream.str;
return r;
}
/** [22] AndExpr::= EqualityExpr | AndExpr 'and' EqualityExpr
*/
function andExpr(stream, a) { return binaryL(equalityExpr, stream, a, 'and'); }
/** [23] EqualityExpr::= RelationalExpr | EqualityExpr '=' RelationalExpr
* | EqualityExpr '!=' RelationalExpr
*/
function equalityExpr(stream, a) { return binaryL(relationalExpr, stream, a, ['=','!=']); }
/** [24] RelationalExpr::= AdditiveExpr | RelationalExpr '<' AdditiveExpr
* | RelationalExpr '>' AdditiveExpr
* | RelationalExpr '<=' AdditiveExpr
* | RelationalExpr '>=' AdditiveExpr
*/
function relationalExpr(stream, a) { return binaryL(additiveExpr, stream, a, ['<','>','<=','>=']); }
/** [25] AdditiveExpr::= MultiplicativeExpr
* | AdditiveExpr '+' MultiplicativeExpr
* | AdditiveExpr '-' MultiplicativeExpr
*/
function additiveExpr(stream, a) { return binaryL(multiplicativeExpr, stream, a, ['+','-']); }
/** [26] MultiplicativeExpr::= UnaryExpr
* | MultiplicativeExpr MultiplyOperator UnaryExpr
* | MultiplicativeExpr 'div' UnaryExpr
* | MultiplicativeExpr 'mod' UnaryExpr
*/
function multiplicativeExpr(stream, a) { return binaryL(unaryExpr, stream, a, ['*','div','mod']); }
/** [27] UnaryExpr::= UnionExpr | '-' UnaryExpr
*/
function unaryExpr(stream, a) {
if (stream.trypop('-')) {
var e = unaryExpr(stream, a);
if (null == e)
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Expected unary expression after -');
return a.node('UnaryMinus', e);
}
else return unionExpr(stream, a);
}
var astFactory = {
node: function() {return Array.prototype.slice.call(arguments);}
};
/***************************************************************************
* Optimizations (TODO) *
***************************************************************************/
/**
* Some things I've been considering:
* 1) a//b becomes a/descendant::b if there's no predicate that uses
* position() or last()
* 2) axis[pred]: when pred doesn't use position, evaluate it just once per
* node in the node-set rather than once per (node, position, last).
* For more optimizations, look up Gecko's optimizer:
* path_to_url
*/
// TODO
function optimize(ast) {
}
/***************************************************************************
* Evaluation: axes *
***************************************************************************/
/**
* Data types: For string, number, boolean, we just use Javascript types.
* Node-sets have the form
* {nodes: [node, ...]}
* or {nodes: [node, ...], pos: [[1], [2], ...], lasts: [[1], [2], ...]}
*
* Most of the time, only the node is used and the position information is
* discarded. But if you use a predicate, we need to try every value of
* position and last in case the predicate calls position() or last().
*/
/**
* The NodeMultiSet is a helper class to help generate
* {nodes:[], pos:[], lasts:[]} structures. It is useful for the
* descendant, descendant-or-self, following-sibling, and
* preceding-sibling axes for which we can use a stack to organize things.
*/
function NodeMultiSet(isReverseAxis) {
this.nodes = [];
this.pos = [];
this.lasts = [];
this.nextPos = [];
this.seriesIndexes = []; // index within nodes that each series begins.
this.isReverseAxis = isReverseAxis;
this._pushToNodes = isReverseAxis ? Array.prototype.unshift : Array.prototype.push;
}
NodeMultiSet.prototype = {
pushSeries: function pushSeries() {
this.nextPos.push(1);
this.seriesIndexes.push(this.nodes.length);
},
popSeries: function popSeries() {
console.assert(0 < this.nextPos.length, this.nextPos);
var last = this.nextPos.pop() - 1,
indexInPos = this.nextPos.length,
seriesBeginIndex = this.seriesIndexes.pop(),
seriesEndIndex = this.nodes.length;
for (var i = seriesBeginIndex; i < seriesEndIndex; ++i) {
console.assert(indexInPos < this.lasts[i].length);
console.assert(undefined === this.lasts[i][indexInPos]);
this.lasts[i][indexInPos] = last;
}
},
finalize: function() {
if (null == this.nextPos) return this;
console.assert(0 === this.nextPos.length);
for (var i = 0; i < this.lasts.length; ++i) {
for (var j = 0; j < this.lasts[i].length; ++j) {
console.assert(null != this.lasts[i][j], i + ',' + j + ':' + JSON.stringify(this.lasts));
}
}
this.pushSeries = this.popSeries = this.addNode = function() {
throw new Error('Already finalized.');
};
return this;
},
addNode: function addNode(node) {
console.assert(node);
this._pushToNodes.call(this.nodes, node)
this._pushToNodes.call(this.pos, this.nextPos.slice());
this._pushToNodes.call(this.lasts, new Array(this.nextPos.length));
for (var i = 0; i < this.nextPos.length; ++i) this.nextPos[i]++;
},
simplify: function() {
this.finalize();
return {nodes:this.nodes, pos:this.pos, lasts:this.lasts};
}
};
function eachContext(nodeMultiSet) {
var r = [];
for (var i = 0; i < nodeMultiSet.nodes.length; i++) {
var node = nodeMultiSet.nodes[i];
if (!nodeMultiSet.pos) {
r.push({nodes:[node], pos: [[i + 1]], lasts: [[nodeMultiSet.nodes.length]]});
} else {
for (var j = 0; j < nodeMultiSet.pos[i].length; ++j) {
r.push({nodes:[node], pos: [[nodeMultiSet.pos[i][j]]], lasts: [[nodeMultiSet.lasts[i][j]]]});
}
}
}
return r;
}
/** Matcher used in the axes.
*/
function NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase) {
this.nodeTypeNum = nodeTypeNum;
this.nodeName = nodeName;
this.shouldLowerCase = shouldLowerCase;
this.nodeNameTest =
null == nodeName ? this._alwaysTrue :
shouldLowerCase ? this._nodeNameLowerCaseEquals :
this._nodeNameEquals;
}
NodeMatcher.prototype = {
matches: function matches(node) {
if (0 === this.nodeTypeNum || this._nodeTypeMatches(node)) {
return this.nodeNameTest(getNodeName(node));
}
return false;
},
_nodeTypeMatches(nodeOrAttr) {
if (nodeOrAttr.constructor.name === 'Attr' && this.nodeTypeNum === 2) {
return true;
}
return nodeOrAttr.nodeType === this.nodeTypeNum;
},
_alwaysTrue: function(name) {return true;},
_nodeNameEquals: function _nodeNameEquals(name) {
return this.nodeName === name;
},
_nodeNameLowerCaseEquals: function _nodeNameLowerCaseEquals(name) {
return this.nodeName === name.toLowerCase();
}
};
function followingSiblingHelper(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, shift, peek, followingNode, andSelf, isReverseAxis) {
var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase);
var nodeMultiSet = new NodeMultiSet(isReverseAxis);
while (0 < nodeList.length) { // can be if for following, preceding
var node = shift.call(nodeList);
console.assert(node != null);
node = followingNode(node);
nodeMultiSet.pushSeries();
var numPushed = 1;
while (null != node) {
if (! andSelf && matcher.matches(node))
nodeMultiSet.addNode(node);
if (node === peek.call(nodeList)) {
shift.call(nodeList);
nodeMultiSet.pushSeries();
numPushed++;
}
if (andSelf && matcher.matches(node))
nodeMultiSet.addNode(node);
node = followingNode(node);
}
while (0 < numPushed--)
nodeMultiSet.popSeries();
}
return nodeMultiSet;
}
/** Returns the next non-descendant node in document order.
* This is the first node in following::node(), if node is the context.
*/
function followingNonDescendantNode(node) {
if (node.ownerElement) {
if (node.ownerElement.firstChild)
return node.ownerElement.firstChild;
node = node.ownerElement;
}
do {
if (node.nextSibling) return node.nextSibling;
} while (node = node.parentNode);
return null;
}
/** Returns the next node in a document-order depth-first search.
* See the definition of document order[1]:
* 1) element
* 2) namespace nodes
* 3) attributes
* 4) children
* [1]: path_to_url#dt-document-order
*/
function followingNode(node) {
if (node.ownerElement) // attributes: following node of element.
node = node.ownerElement;
if (null != node.firstChild)
return node.firstChild;
do {
if (null != node.nextSibling) {
return node.nextSibling;
}
node = node.parentNode;
} while (node);
return null;
}
/** Returns the previous node in document order (excluding attributes
* and namespace nodes).
*/
function precedingNode(node) {
if (node.ownerElement)
return node.ownerElement;
if (null != node.previousSibling) {
node = node.previousSibling;
while (null != node.lastChild) {
node = node.lastChild;
}
return node;
}
if (null != node.parentNode) {
return node.parentNode;
}
return null;
}
/** This axis is inefficient if there are many nodes in the nodeList.
* But I think it's a pretty useless axis so it's ok. */
function followingHelper(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) {
var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase);
var nodeMultiSet = new NodeMultiSet(false);
var cursor = nodeList[0];
var unorderedFollowingStarts = [];
for (var i = 0; i < nodeList.length; i++) {
var node = nodeList[i];
var start = followingNonDescendantNode(node);
if (start)
unorderedFollowingStarts.push(start);
}
if (0 === unorderedFollowingStarts.length)
return {nodes:[]};
var pos = [], nextPos = [];
var started = 0;
while (cursor = followingNode(cursor)) {
for (var i = unorderedFollowingStarts.length - 1; i >= 0; i--){
if (cursor === unorderedFollowingStarts[i]) {
nodeMultiSet.pushSeries();
unorderedFollowingStarts.splice(i,i+1);
started++;
}
}
if (started && matcher.matches(cursor)) {
nodeMultiSet.addNode(cursor);
}
}
console.assert(0 === unorderedFollowingStarts.length);
for (var i = 0; i < started; i++)
nodeMultiSet.popSeries();
return nodeMultiSet.finalize();
}
function precedingHelper(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) {
var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase);
var cursor = nodeList.pop();
if (null == cursor) return {nodes:{}};
var r = {nodes:[], pos:[], lasts:[]};
var nextParents = [cursor.parentNode || cursor.ownerElement], nextPos = [1];
while (cursor = precedingNode(cursor)) {
if (cursor === nodeList[nodeList.length - 1]) {
nextParents.push(nodeList.pop());
nextPos.push(1);
}
var matches = matcher.matches(cursor);
var pos, someoneUsed = false;
if (matches)
pos = nextPos.slice();
for (var i = 0; i < nextParents.length; ++i) {
if (cursor === nextParents[i]) {
nextParents[i] = cursor.parentNode || cursor.ownerElement;
if (matches) {
pos[i] = null;
}
} else {
if (matches) {
pos[i] = nextPos[i]++;
someoneUsed = true;
}
}
}
if (someoneUsed) {
r.nodes.unshift(cursor);
r.pos.unshift(pos);
}
}
for (var i = 0; i < r.pos.length; ++i) {
var lasts = [];
r.lasts.push(lasts);
for (var j = r.pos[i].length - 1; j >= 0; j--) {
if (null == r.pos[i][j]) {
r.pos[i].splice(j, j+1);
} else {
lasts.unshift(nextPos[j] - 1);
}
}
}
return r;
}
/** node-set, axis -> node-set */
function descendantDfs(nodeMultiSet, node, remaining, matcher, andSelf, attrIndices, attrNodes) {
while (0 < remaining.length && null != remaining[0].ownerElement) {
var attr = remaining.shift();
if (andSelf && matcher.matches(attr)) {
attrNodes.push(attr);
attrIndices.push(nodeMultiSet.nodes.length);
}
}
if (null != node && !andSelf) {
if (matcher.matches(node))
nodeMultiSet.addNode(node);
}
var pushed = false;
if (null == node) {
if (0 === remaining.length) return;
node = remaining.shift();
nodeMultiSet.pushSeries();
pushed = true;
} else if (0 < remaining.length && node === remaining[0]) {
nodeMultiSet.pushSeries();
pushed = true;
remaining.shift();
}
if (andSelf) {
if (matcher.matches(node))
nodeMultiSet.addNode(node);
}
// TODO: use optimization. Also try element.getElementsByTagName
// var nodeList = 1 === nodeTypeNum && null != node.children ? node.children : node.childNodes;
var nodeList = node.childNodes;
for (var j = 0; j < nodeList.length; ++j) {
var child = nodeList[j];
descendantDfs(nodeMultiSet, child, remaining, matcher, andSelf, attrIndices, attrNodes);
}
if (pushed) {
nodeMultiSet.popSeries();
}
}
function descenantHelper(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, andSelf) {
var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase);
var nodeMultiSet = new NodeMultiSet(false);
var attrIndices = [], attrNodes = [];
while (0 < nodeList.length) {
// var node = nodeList.shift();
descendantDfs(nodeMultiSet, null, nodeList, matcher, andSelf, attrIndices, attrNodes);
}
nodeMultiSet.finalize();
for (var i = attrNodes.length-1; i >= 0; --i) {
nodeMultiSet.nodes.splice(attrIndices[i], attrIndices[i], attrNodes[i]);
nodeMultiSet.pos.splice(attrIndices[i], attrIndices[i], [1]);
nodeMultiSet.lasts.splice(attrIndices[i], attrIndices[i], [1]);
}
return nodeMultiSet;
}
/**
*/
function ancestorHelper(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, andSelf) {
var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase);
var ancestors = []; // array of non-empty arrays of matching ancestors
for (var i = 0; i < nodeList.length; ++i) {
var node = nodeList[i];
var isFirst = true;
var a = [];
while (null != node) {
if (!isFirst || andSelf) {
if (matcher.matches(node))
a.push(node);
}
isFirst = false;
node = node.parentNode || node.ownerElement;
}
if (0 < a.length)
ancestors.push(a);
}
var lasts = [];
for (var i = 0; i < ancestors.length; ++i) lasts.push(ancestors[i].length);
var nodeMultiSet = new NodeMultiSet(true);
var newCtx = {nodes:[], pos:[], lasts:[]};
while (0 < ancestors.length) {
var pos = [ancestors[0].length];
var last = [lasts[0]];
var node = ancestors[0].pop();
for (var i = ancestors.length - 1; i > 0; --i) {
if (node === ancestors[i][ancestors[i].length - 1]) {
pos.push(ancestors[i].length);
last.push(lasts[i]);
ancestors[i].pop();
if (0 === ancestors[i].length) {
ancestors.splice(i, i+1);
lasts.splice(i, i+1);
}
}
}
if (0 === ancestors[0].length) {
ancestors.shift();
lasts.shift();
}
newCtx.nodes.push(node);
newCtx.pos.push(pos);
newCtx.lasts.push(last);
}
return newCtx;
}
/** Helper function for sortDocumentOrder. Returns a list of indices, from the
* node to the root, of positions within parent.
* For convenience, the node is the first element of the array.
*/
function addressVector(node) {
var r = [node];
if (null != node.ownerElement) {
node = node.ownerElement;
r.push(-1);
}
while (null != node) {
var i = 0;
while (null != node.previousSibling) {
node = node.previousSibling;
i++;
}
r.push(i);
node = node.parentNode
}
return r;
}
function addressComparator(a, b) {
var minlen = Math.min(a.length - 1, b.length - 1), // not including [0]=node
alen = a.length,
blen = b.length;
if (a[0] === b[0]) return 0;
var c;
for (var i = 0; i < minlen; ++i) {
c = a[alen - i - 1] - b[blen - i - 1];
if (0 !== c)
break;
}
if (null == c || 0 === c) {
// All equal until one of the nodes. The longer one is the descendant.
c = alen - blen;
}
if (0 === c)
c = getNodeName(a) - getNodeName(b);
if (0 === c)
c = 1;
return c;
}
var sortUniqDocumentOrder = xpath.sortUniqDocumentOrder = function(nodes) {
var a = [];
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
var v = addressVector(node);
a.push(v);
}
a.sort(addressComparator);
var b = [];
for (var i = 0; i < a.length; i++) {
if (0 < i && a[i][0] === a[i - 1][0])
continue;
b.push(a[i][0]);
}
return b;
}
/** Sort node multiset. Does not do any de-duping. */
function sortNodeMultiSet(nodeMultiSet) {
var a = [];
for (var i = 0; i < nodeMultiSet.nodes.length; i++) {
var v = addressVector(nodeMultiSet.nodes[i]);
a.push({v:v, n:nodeMultiSet.nodes[i],
p:nodeMultiSet.pos[i], l:nodeMultiSet.lasts[i]});
}
a.sort(compare);
var r = {nodes:[], pos:[], lasts:[]};
for (var i = 0; i < a.length; ++i) {
r.nodes.push(a[i].n);
r.pos.push(a[i].p);
r.lasts.push(a[i].l);
}
function compare(x, y) {
return addressComparator(x.v, y.v);
}
return r;
}
/** Returns an array containing all the ancestors down to a node.
* The array starts with document.
*/
function nodeAndAncestors(node) {
var ancestors = [node];
var p = node;
while (p = p.parentNode || p.ownerElement) {
ancestors.unshift(p);
}
return ancestors;
}
function compareSiblings(a, b) {
if (a === b) return 0;
var c = a;
while (c = c.previousSibling) {
if (c === b)
return 1; // b < a
}
c = b;
while (c = c.previousSibling) {
if (c === a)
return -1; // a < b
}
throw new Error('a and b are not siblings: ' + xpath.stringifyObject(a) + ' vs ' + xpath.stringifyObject(b));
}
/** The merge in merge-sort.*/
function mergeNodeLists(x, y) {
var a, b, aanc, banc, r = [];
if ('object' !== typeof x)
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Invalid LHS for | operator ' +
'(expected node-set): ' + x);
if ('object' !== typeof y)
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Invalid LHS for | operator ' +
'(expected node-set): ' + y);
while (true) {
if (null == a) {
a = x.shift();
if (null != a)
aanc = addressVector(a);
}
if (null == b) {
b = y.shift();
if (null != b)
banc = addressVector(b);
}
if (null == a || null == b) break;
var c = addressComparator(aanc, banc);
if (c < 0) {
r.push(a);
a = null;
aanc = null;
} else if (c > 0) {
r.push(b);
b = null;
banc = null;
} else if (getNodeName(a) < getNodeName(b)) { // attributes
r.push(a);
a = null;
aanc = null;
} else if (getNodeName(a) > getNodeName(b)) { // attributes
r.push(b);
b = null;
banc = null;
} else if (a !== b) {
// choose b arbitrarily
r.push(b);
b = null;
banc = null;
} else {
console.assert(a === b, c);
// just skip b without pushing it.
b = null;
banc = null;
}
}
while (a) {
r.push(a);
a = x.shift();
}
while (b) {
r.push(b);
b = y.shift();
}
return r;
}
function comparisonHelper(test, x, y, isNumericComparison) {
var coersion;
if (isNumericComparison)
coersion = fn.number;
else coersion =
'boolean' === typeof x || 'boolean' === typeof y ? fn['boolean'] :
'number' === typeof x || 'number' === typeof y ? fn.number :
fn.string;
if ('object' === typeof x && 'object' === typeof y) {
var aMap = {};
for (var i = 0; i < x.nodes.length; ++i) {
var xi = coersion({nodes:[x.nodes[i]]});
for (var j = 0; j < y.nodes.length; ++j) {
var yj = coersion({nodes:[y.nodes[j]]});
if (test(xi, yj)) return true;
}
}
return false;
} else if ('object' === typeof x && x.nodes && x.nodes.length) {
for (var i = 0; i < x.nodes.length; ++i) {
var xi = coersion({nodes:[x.nodes[i]]}), yc = coersion(y);
if (test(xi, yc))
return true;
}
return false;
} else if ('object' === typeof y && x.nodes && x.nodes.length) {
for (var i = 0; i < x.nodes.length; ++i) {
var yi = coersion({nodes:[y.nodes[i]]}), xc = coersion(x);
if (test(xc, yi))
return true;
}
return false;
} else {
var xc = coersion(x), yc = coersion(y);
return test(xc, yc);
}
}
var axes = xpath.axes = {
'ancestor':
function ancestor(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) {
return ancestorHelper(
nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, false);
},
'ancestor-or-self':
function ancestorOrSelf(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) {
return ancestorHelper(
nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, true);
},
'attribute':
function attribute(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) {
// TODO: figure out whether positions should be undefined here.
var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase);
var nodeMultiSet = new NodeMultiSet(false);
if (null != nodeName) {
// TODO: with namespace
for (var i = 0; i < nodeList.length; ++i) {
var node = nodeList[i];
if (null == node.getAttributeNode)
continue; // only Element has .getAttributeNode
var attr = node.getAttributeNode(nodeName);
if (null != attr && matcher.matches(attr)) {
nodeMultiSet.pushSeries();
nodeMultiSet.addNode(attr);
nodeMultiSet.popSeries();
}
}
} else {
for (var i = 0; i < nodeList.length; ++i) {
var node = nodeList[i];
if (null != node.attributes) {
nodeMultiSet.pushSeries();
for (var j = 0; j < node.attributes.length; j++) { // all nodes have .attributes
var attr = node.attributes[j];
if (matcher.matches(attr)) // TODO: I think this check is unnecessary
nodeMultiSet.addNode(attr);
}
nodeMultiSet.popSeries();
}
}
}
return nodeMultiSet.finalize();
},
'child':
function child(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) {
var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase);
var nodeMultiSet = new NodeMultiSet(false);
for (var i = 0; i < nodeList.length; ++i) {
var n = nodeList[i];
if (n.ownerElement) // skip attribute nodes' text child.
continue;
if (n.childNodes) {
nodeMultiSet.pushSeries();
var childList = 1 === nodeTypeNum && null != n.children ?
n.children : n.childNodes;
for (var j = 0; j < childList.length; ++j) {
var child = childList[j];
if (matcher.matches(child)) {
nodeMultiSet.addNode(child);
}
// don't have to do de-duping because children have parent,
// which are current context.
}
nodeMultiSet.popSeries();
}
}
nodeMultiSet.finalize();
return sortNodeMultiSet(nodeMultiSet);
},
'descendant':
function descenant(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) {
return descenantHelper(
nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, false);
},
'descendant-or-self':
function descenantOrSelf(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) {
return descenantHelper(
nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase, true);
},
'following':
function following(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) {
return followingHelper(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase);
},
'following-sibling':
function followingSibling(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) {
return followingSiblingHelper(
nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase,
Array.prototype.shift, function() {return this[0];},
function(node) {return node.nextSibling;});
},
'namespace':
function namespace(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) {
// TODO
},
'parent':
function parent(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) {
var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase);
var nodes = [], pos = [];
for (var i = 0; i < nodeList.length; ++i) {
var parent = nodeList[i].parentNode || nodeList[i].ownerElement;
if (null == parent)
continue;
if (!matcher.matches(parent))
continue;
if (nodes.length > 0 && parent === nodes[nodes.length-1])
continue;
nodes.push(parent);
pos.push([1]);
}
return {nodes:nodes, pos:pos, lasts:pos};
},
'preceding':
function preceding(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) {
return precedingHelper(
nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase);
},
'preceding-sibling':
function precedingSibling(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) {
return followingSiblingHelper(
nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase,
Array.prototype.pop, function() {return this[this.length-1];},
function(node) {return node.previousSibling},
false, true);
},
'self':
function self(nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase) {
var nodes = [], pos = [];
var matcher = new NodeMatcher(nodeTypeNum, nodeName, shouldLowerCase);
for (var i = 0; i < nodeList.length; ++i) {
if (matcher.matches(nodeList[i])) {
nodes.push(nodeList[i]);
pos.push([1]);
}
}
return {nodes: nodes, pos: pos, lasts: pos}
}
};
/***************************************************************************
* Evaluation: functions *
***************************************************************************/
var fn = {
'number': function number(optObject) {
if ('number' === typeof optObject)
return optObject;
if ('string' === typeof optObject)
return parseFloat(optObject); // note: parseFloat(' ') -> NaN, unlike +' ' -> 0.
if ('boolean' === typeof optObject)
return +optObject;
return fn.number(fn.string.call(this, optObject)); // for node-sets
},
'string': function string(optObject) {
if (null == optObject)
return fn.string(this);
if ('string' === typeof optObject || 'boolean' === typeof optObject ||
'number' === typeof optObject)
return '' + optObject;
if (0 == optObject.nodes.length) return '';
if (null != optObject.nodes[0].textContent)
return optObject.nodes[0].textContent;
return optObject.nodes[0].nodeValue;
},
'boolean': function booleanVal(x) {
return 'object' === typeof x ? x.nodes.length > 0 : !!x;
},
'last': function last() {
console.assert(Array.isArray(this.pos));
console.assert(Array.isArray(this.lasts));
console.assert(1 === this.pos.length);
console.assert(1 === this.lasts.length);
console.assert(1 === this.lasts[0].length);
return this.lasts[0][0];
},
'position': function position() {
console.assert(Array.isArray(this.pos));
console.assert(Array.isArray(this.lasts));
console.assert(1 === this.pos.length);
console.assert(1 === this.lasts.length);
console.assert(1 === this.pos[0].length);
return this.pos[0][0];
},
'count': function count(nodeSet) {
if ('object' !== typeof nodeSet)
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Position ' + stream.position() +
': Function count(node-set) ' +
'got wrong argument type: ' + nodeSet);
return nodeSet.nodes.length;
},
'id': function id(object) {
var r = {nodes: []};
var doc = this.nodes[0].ownerDocument || this.nodes[0];
console.assert(doc);
var ids;
if ('object' === typeof object) {
// for node-sets, map id over each node value.
ids = [];
for (var i = 0; i < object.nodes.length; ++i) {
var idNode = object.nodes[i];
var idsString = fn.string({nodes:[idNode]});
var a = idsString.split(/[ \t\r\n]+/g);
Array.prototype.push.apply(ids, a);
}
} else {
var idsString = fn.string(object);
var a = idsString.split(/[ \t\r\n]+/g);
ids = a;
}
for (var i = 0; i < ids.length; ++i) {
var id = ids[i];
if (0 === id.length)
continue;
var node = doc.getElementById(id);
if (null != node)
r.nodes.push(node);
}
r.nodes = sortUniqDocumentOrder(r.nodes);
return r;
},
'local-name': function(nodeSet) {
if (null == nodeSet)
return fn.name(this);
if (null == nodeSet.nodes) {
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'argument to name() must be a node-set. got ' + nodeSet);
}
// TODO: namespaced version
return nodeSet.nodes[0].localName;
},
'namespace-uri': function(nodeSet) {
// TODO
throw new Error('not implemented yet');
},
'name': function(nodeSet) {
if (null == nodeSet)
return fn.name(this);
if (null == nodeSet.nodes) {
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'argument to name() must be a node-set. got ' + nodeSet);
}
return nodeSet.nodes[0].name;
},
'concat': function concat(x) {
var l = [];
for (var i = 0; i < arguments.length; ++i) {
l.push(fn.string(arguments[i]));
}
return l.join('');
},
'starts-with': function startsWith(a, b) {
var as = fn.string(a), bs = fn.string(b);
return as.substr(0, bs.length) === bs;
},
'contains': function contains(a, b) {
var as = fn.string(a), bs = fn.string(b);
var i = as.indexOf(bs);
if (-1 === i) return false;
return true;
},
'substring-before': function substringBefore(a, b) {
var as = fn.string(a), bs = fn.string(b);
var i = as.indexOf(bs);
if (-1 === i) return '';
return as.substr(0, i);
},
'substring-after': function substringBefore(a, b) {
var as = fn.string(a), bs = fn.string(b);
var i = as.indexOf(bs);
if (-1 === i) return '';
return as.substr(i + bs.length);
},
'substring': function substring(string, start, optEnd) {
if (null == string || null == start) {
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Must be at least 2 arguments to string()');
}
var sString = fn.string(string),
iStart = fn.round(start),
iEnd = optEnd == null ? null : fn.round(optEnd);
// Note that xpath string positions user 1-based index
if (iEnd == null)
return sString.substr(iStart - 1);
else
return sString.substr(iStart - 1, iEnd);
},
'string-length': function stringLength(optString) {
return fn.string.call(this, optString).length;
},
'normalize-space': function normalizeSpace(optString) {
var s = fn.string.call(this, optString);
return s.replace(/[ \t\r\n]+/g, ' ').replace(/^ | $/g, '');
},
'translate': function translate(string, from, to) {
var sString = fn.string.call(this, string),
sFrom = fn.string(from),
sTo = fn.string(to);
var eachCharRe = [];
var map = {};
for (var i = 0; i < sFrom.length; ++i) {
var c = sFrom.charAt(i);
map[c] = sTo.charAt(i); // returns '' if beyond length of sTo.
// copied from goog.string.regExpEscape in the Closure library.
eachCharRe.push(
c.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
replace(/\x08/g, '\\x08'));
}
var re = new RegExp(eachCharRe.join('|'), 'g');
return sString.replace(re, function(c) {return map[c];});
},
/// Boolean functions
'not': function not(x) {
var bx = fn['boolean'](x);
return !bx;
},
'true': function trueVal() { return true; },
'false': function falseVal() { return false; },
// TODO
'lang': function lang(string) { throw new Error('Not implemented');},
'sum': function sum(optNodeSet) {
if (null == optNodeSet) return fn.sum(this);
// for node-sets, map id over each node value.
var sum = 0;
for (var i = 0; i < optNodeSet.nodes.length; ++i) {
var node = optNodeSet.nodes[i];
var x = fn.number({nodes:[node]});
sum += x;
}
return sum;
},
'floor': function floor(number) {
return Math.floor(fn.number(number));
},
'ceiling': function ceiling(number) {
return Math.ceil(fn.number(number));
},
'round': function round(number) {
return Math.round(fn.number(number));
}
};
/***************************************************************************
* Evaluation: operators *
***************************************************************************/
var more = {
UnaryMinus: function(x) { return -fn.number(x); },
'+': function(x, y) { return fn.number(x) + fn.number(y); },
'-': function(x, y) { return fn.number(x) - fn.number(y); },
'*': function(x, y) { return fn.number(x) * fn.number(y); },
'div': function(x, y) { return fn.number(x) / fn.number(y); },
'mod': function(x, y) { return fn.number(x) % fn.number(y); },
'<': function(x, y) {
return comparisonHelper(function(x, y) { return fn.number(x) < fn.number(y);}, x, y, true);
},
'<=': function(x, y) {
return comparisonHelper(function(x, y) { return fn.number(x) <= fn.number(y);}, x, y, true);
},
'>': function(x, y) {
return comparisonHelper(function(x, y) { return fn.number(x) > fn.number(y);}, x, y, true);
},
'>=': function(x, y) {
return comparisonHelper(function(x, y) { return fn.number(x) >= fn.number(y);}, x, y, true);
},
'and': function(x, y) { return fn['boolean'](x) && fn['boolean'](y); },
'or': function(x, y) { return fn['boolean'](x) || fn['boolean'](y); },
'|': function(x, y) { return {nodes: mergeNodeLists(x.nodes, y.nodes)}; },
'=': function(x, y) {
// optimization for two node-sets case: avoid n^2 comparisons.
if ('object' === typeof x && 'object' === typeof y) {
var aMap = {};
for (var i = 0; i < x.nodes.length; ++i) {
var s = fn.string({nodes:[x.nodes[i]]});
aMap[s] = true;
}
for (var i = 0; i < y.nodes.length; ++i) {
var s = fn.string({nodes:[y.nodes[i]]});
if (aMap[s]) return true;
}
return false;
} else {
return comparisonHelper(function(x, y) {return x === y;}, x, y);
}
},
'!=': function(x, y) {
// optimization for two node-sets case: avoid n^2 comparisons.
if ('object' === typeof x && 'object' === typeof y) {
if (0 === x.nodes.length || 0 === y.nodes.length) return false;
var aMap = {};
for (var i = 0; i < x.nodes.length; ++i) {
var s = fn.string({nodes:[x.nodes[i]]});
aMap[s] = true;
}
for (var i = 0; i < y.nodes.length; ++i) {
var s = fn.string({nodes:[y.nodes[i]]});
if (!aMap[s]) return true;
}
return false;
} else {
return comparisonHelper(function(x, y) {return x !== y;}, x, y);
}
}
};
var nodeTypes = xpath.nodeTypes = {
'node': 0,
'attribute': 2,
'comment': 8, // this.doc.COMMENT_NODE,
'text': 3, // this.doc.TEXT_NODE,
'processing-instruction': 7, // this.doc.PROCESSING_INSTRUCTION_NODE,
'element': 1 //this.doc.ELEMENT_NODE
};
/** For debugging and unit tests: returnjs a stringified version of the
* argument. */
var stringifyObject = xpath.stringifyObject = function stringifyObject(ctx) {
var seenKey = 'seen' + Math.floor(Math.random()*1000000000);
return JSON.stringify(helper(ctx));
function helper(ctx) {
if (Array.isArray(ctx)) {
return ctx.map(function(x) {return helper(x);});
}
if ('object' !== typeof ctx) return ctx;
if (null == ctx) return ctx;
// if (ctx.toString) return ctx.toString();
if (null != ctx.outerHTML) return ctx.outerHTML;
if (null != ctx.nodeValue) return ctx.nodeName + '=' + ctx.nodeValue;
if (ctx[seenKey]) return '[circular]';
ctx[seenKey] = true;
var nicer = {};
for (var key in ctx) {
if (seenKey === key)
continue;
try {
nicer[key] = helper(ctx[key]);
} catch (e) {
nicer[key] = '[exception: ' + e.message + ']';
}
}
delete ctx[seenKey];
return nicer;
}
}
var Evaluator = xpath.Evaluator = function Evaluator(doc) {
this.doc = doc;
}
Evaluator.prototype = {
val: function val(ast, ctx) {
console.assert(ctx.nodes);
if ('number' === typeof ast || 'string' === typeof ast) return ast;
if (more[ast[0]]) {
var evaluatedParams = [];
for (var i = 1; i < ast.length; ++i) {
evaluatedParams.push(this.val(ast[i], ctx));
}
var r = more[ast[0]].apply(ctx, evaluatedParams);
return r;
}
switch (ast[0]) {
case 'Root': return {nodes: [this.doc]};
case 'FunctionCall':
var functionName = ast[1], functionParams = ast[2];
if (null == fn[functionName])
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR,
'Unknown function: ' + functionName);
var evaluatedParams = [];
for (var i = 0; i < functionParams.length; ++i) {
evaluatedParams.push(this.val(functionParams[i], ctx));
}
var r = fn[functionName].apply(ctx, evaluatedParams);
return r;
case 'Predicate':
var lhs = this.val(ast[1], ctx);
var ret = {nodes: []};
var contexts = eachContext(lhs);
for (var i = 0; i < contexts.length; ++i) {
var singleNodeSet = contexts[i];
var rhs = this.val(ast[2], singleNodeSet);
var success;
if ('number' === typeof rhs) {
success = rhs === singleNodeSet.pos[0][0];
} else {
success = fn['boolean'](rhs);
}
if (success) {
var node = singleNodeSet.nodes[0];
ret.nodes.push(node);
// skip over all the rest of the same node.
while (i+1 < contexts.length && node === contexts[i+1].nodes[0]) {
i++;
}
}
}
return ret;
case 'PathExpr':
// turn the path into an expressoin; i.e., remove the position
// information of the last axis.
var x = this.val(ast[1], ctx);
// Make the nodeset a forward-direction-only one.
if (x.finalize) { // it is a NodeMultiSet
return {nodes: x.nodes};
} else {
return x;
}
case '/':
// TODO: don't generate '/' nodes, just Axis nodes.
var lhs = this.val(ast[1], ctx);
console.assert(null != lhs);
var r = this.val(ast[2], lhs);
console.assert(null != r);
return r;
case 'Axis':
// All the axis tests from Step. We only get AxisSpecifier NodeTest,
// not the predicate (which is applied later)
var axis = ast[1],
nodeType = ast[2],
nodeTypeNum = nodeTypes[nodeType],
shouldLowerCase = true, // TODO: give option
nodeName = ast[3] && shouldLowerCase ? ast[3].toLowerCase() : ast[3];
nodeName = nodeName === '*' ? null : nodeName;
if ('object' !== typeof ctx) return {nodes:[], pos:[]};
var nodeList = ctx.nodes.slice(); // TODO: is copy needed?
var r = axes[axis](nodeList /*destructive!*/, nodeTypeNum, nodeName, shouldLowerCase);
return r;
}
}
};
var evaluate = xpath.evaluate = function evaluate(expr, doc, context) {
//var astFactory = new AstEvaluatorFactory(doc, context);
var stream = new Stream(expr);
var ast = parse(stream, astFactory);
var val = new Evaluator(doc).val(ast, {nodes: [context]});
return val;
}
/***************************************************************************
* DOM interface *
***************************************************************************/
var XPathException = xpath.XPathException = function XPathException(code, message) {
var e = new Error(message);
e.name = 'XPathException';
e.code = code;
return e;
}
XPathException.INVALID_EXPRESSION_ERR = 51;
XPathException.TYPE_ERR = 52;
var XPathEvaluator = xpath.XPathEvaluator = function XPathEvaluator() {}
XPathEvaluator.prototype = {
createExpression: function(expression, resolver) {
return new XPathExpression(expression, resolver);
},
createNSResolver: function(nodeResolver) {
// TODO
},
evaluate: function evaluate(expression, contextNode, resolver, type, result) {
var expr = new XPathExpression(expression, resolver);
return expr.evaluate(contextNode, type, result);
}
};
var XPathExpression = xpath.XPathExpression = function XPathExpression(expression, resolver, optDoc) {
var stream = new Stream(expression);
this._ast = parse(stream, astFactory);
this._doc = optDoc;
}
XPathExpression.prototype = {
evaluate: function evaluate(contextNode, type, result) {
if (null == contextNode.nodeType)
throw new Error('bad argument (expected context node): ' + contextNode);
var doc = contextNode.ownerDocument || contextNode;
if (null != this._doc && this._doc !== doc) {
throw new core.DOMException(
core.DOMException.WRONG_DOCUMENT_ERR,
'The document must be the same as the context node\'s document.');
}
var evaluator = new Evaluator(doc);
var value = evaluator.val(this._ast, {nodes: [contextNode]});
if (XPathResult.NUMBER_TYPE === type)
value = fn.number(value);
else if (XPathResult.STRING_TYPE === type)
value = fn.string(value);
else if (XPathResult.BOOLEAN_TYPE === type)
value = fn['boolean'](value);
else if (XPathResult.ANY_TYPE !== type &&
XPathResult.UNORDERED_NODE_ITERATOR_TYPE !== type &&
XPathResult.ORDERED_NODE_ITERATOR_TYPE !== type &&
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE !== type &&
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE !== type &&
XPathResult.ANY_UNORDERED_NODE_TYPE !== type &&
XPathResult.FIRST_ORDERED_NODE_TYPE !== type)
throw new core.DOMException(
core.DOMException.NOT_SUPPORTED_ERR,
'You must provide an XPath result type (0=any).');
else if (XPathResult.ANY_TYPE !== type &&
'object' !== typeof value)
throw new XPathException(
XPathException.TYPE_ERR,
'Value should be a node-set: ' + value);
return new XPathResult(doc, value, type);
}
}
var XPathResult = xpath.XPathResult = function XPathResult(doc, value, resultType) {
this._value = value;
this._resultType = resultType;
this._i = 0;
this._invalidated = false;
if (this.resultType === XPathResult.UNORDERED_NODE_ITERATOR_TYPE ||
this.resultType === XPathResult.ORDERED_NODE_ITERATOR_TYPE) {
doc.addEventListener('DOMSubtreeModified', invalidate, true);
var self = this;
function invalidate() {
self._invalidated = true;
doc.removeEventListener('DOMSubtreeModified', invalidate, true);
}
}
}
XPathResult.ANY_TYPE = 0;
XPathResult.NUMBER_TYPE = 1;
XPathResult.STRING_TYPE = 2;
XPathResult.BOOLEAN_TYPE = 3;
XPathResult.UNORDERED_NODE_ITERATOR_TYPE = 4;
XPathResult.ORDERED_NODE_ITERATOR_TYPE = 5;
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE = 6;
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE = 7;
XPathResult.ANY_UNORDERED_NODE_TYPE = 8;
XPathResult.FIRST_ORDERED_NODE_TYPE = 9;
var proto = {
// XPathResultType
get resultType() {
if (this._resultType) return this._resultType;
switch (typeof this._value) {
case 'number': return XPathResult.NUMBER_TYPE;
case 'string': return XPathResult.STRING_TYPE;
case 'boolean': return XPathResult.BOOLEAN_TYPE;
default: return XPathResult.UNORDERED_NODE_ITERATOR_TYPE;
}
},
get numberValue() {
if (XPathResult.NUMBER_TYPE !== this.resultType)
throw new XPathException(XPathException.TYPE_ERR,
'You should have asked for a NUMBER_TYPE.');
return this._value;
},
get stringValue() {
if (XPathResult.STRING_TYPE !== this.resultType)
throw new XPathException(XPathException.TYPE_ERR,
'You should have asked for a STRING_TYPE.');
return this._value;
},
get booleanValue() {
if (XPathResult.BOOLEAN_TYPE !== this.resultType)
throw new XPathException(XPathException.TYPE_ERR,
'You should have asked for a BOOLEAN_TYPE.');
return this._value;
},
get singleNodeValue() {
if (XPathResult.ANY_UNORDERED_NODE_TYPE !== this.resultType &&
XPathResult.FIRST_ORDERED_NODE_TYPE !== this.resultType)
throw new XPathException(
XPathException.TYPE_ERR,
'You should have asked for a FIRST_ORDERED_NODE_TYPE.');
return this._value.nodes[0] || null;
},
get invalidIteratorState() {
if (XPathResult.UNORDERED_NODE_ITERATOR_TYPE !== this.resultType &&
XPathResult.ORDERED_NODE_ITERATOR_TYPE !== this.resultType)
return false;
return !!this._invalidated;
},
get snapshotLength() {
if (XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE !== this.resultType &&
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE !== this.resultType)
throw new XPathException(
XPathException.TYPE_ERR,
'You should have asked for a ORDERED_NODE_SNAPSHOT_TYPE.');
return this._value.nodes.length;
},
iterateNext: function iterateNext() {
if (XPathResult.UNORDERED_NODE_ITERATOR_TYPE !== this.resultType &&
XPathResult.ORDERED_NODE_ITERATOR_TYPE !== this.resultType)
throw new XPathException(
XPathException.TYPE_ERR,
'You should have asked for a ORDERED_NODE_ITERATOR_TYPE.');
if (this.invalidIteratorState)
throw new core.DOMException(
core.DOMException.INVALID_STATE_ERR,
'The document has been mutated since the result was returned');
return this._value.nodes[this._i++] || null;
},
snapshotItem: function snapshotItem(index) {
if (XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE !== this.resultType &&
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE !== this.resultType)
throw new XPathException(
XPathException.TYPE_ERR,
'You should have asked for a ORDERED_NODE_SNAPSHOT_TYPE.');
return this._value.nodes[index] || null;
}
};
// so you can access ANY_TYPE etc. from the instances:
XPathResult.prototype = Object.create(XPathResult,
Object.keys(proto).reduce(function (descriptors, name) {
descriptors[name] = Object.getOwnPropertyDescriptor(proto, name);
return descriptors;
}, {
constructor: {
value: XPathResult,
writable: true,
configurable: true
}
}));
core.XPathException = XPathException;
core.XPathExpression = XPathExpression;
core.XPathResult = XPathResult;
core.XPathEvaluator = XPathEvaluator;
core.Document.prototype.createExpression =
XPathEvaluator.prototype.createExpression;
core.Document.prototype.createNSResolver =
XPathEvaluator.prototype.createNSResolver;
core.Document.prototype.evaluate = XPathEvaluator.prototype.evaluate;
})();
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/level3/xpath.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 17,011 |
```javascript
"use strict";
const DOMException = require("../web-idl/DOMException");
const validateNames = require("./helpers/validate-names");
const defineGetter = require("../utils").defineGetter;
const defineSetter = require("../utils").defineSetter;
const memoizeQuery = require("../utils").memoizeQuery;
const generatedAttr = require("./generated/Attr");
const clone = require("./node").clone;
const listOfElementsWithClassNames = require("./node").listOfElementsWithClassNames;
const validateName = require("./helpers/validate-names").name;
const validateAndExtract = require("./helpers/validate-names").validateAndExtract;
const NODE_TYPE = require("../living/node-type");
module.exports = function (core) {
core.Document.prototype.createProcessingInstruction = function (target, data) {
if (arguments.length < 2) {
throw new TypeError("Not enough arguments to Document.prototype.createProcessingInstruction");
}
target = String(target);
data = String(data);
validateNames.name(target);
if (data.indexOf("?>") !== -1) {
throw new core.DOMException(core.DOMException.INVALID_CHARACTER_ERR,
"Processing instruction data cannot contain the string \"?>\"");
}
return new core.ProcessingInstruction(this._ownerDocument, target, data);
};
core.Document.prototype.createTextNode = function (data) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to Document.prototype.createTextNode");
}
data = String(data);
return new core.Text(this, data);
};
core.Document.prototype.createComment = function (data) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to Document.prototype.createComment");
}
data = String(data);
return new core.Comment(this, data);
};
core.Document.prototype.createElement = function (localName) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to Document.prototype.createElement");
}
localName = String(localName);
validateName(localName);
if (this._parsingMode === "html") {
localName = localName.toLowerCase();
}
const element = this._createElementWithCorrectElementInterface(localName, "path_to_url");
element._namespaceURI = "path_to_url";
element._localName = localName;
element._ownerDocument = this;
return element;
};
core.Document.prototype.createElementNS = function (namespace, qualifiedName) {
if (arguments.length < 2) {
throw new TypeError("Not enough arguments to Document.prototype.createElementNS");
}
namespace = namespace !== null ? String(namespace) : namespace;
qualifiedName = String(qualifiedName);
const extracted = validateAndExtract(namespace, qualifiedName);
const element = this._createElementWithCorrectElementInterface(extracted.localName, extracted.namespace);
element._namespaceURI = extracted.namespace;
element._prefix = extracted.prefix;
element._localName = extracted.localName;
element._ownerDocument = this;
return element;
};
core.Document.prototype.createDocumentFragment = function () {
return new core.DocumentFragment(this);
};
core.Document.prototype.createAttribute = function (localName) {
if (arguments.length < 1) {
throw new TypeError("not enough arguments to Document.prototype.createAttribute");
}
localName = String(localName);
validateName(localName);
if (this._parsingMode === "html") {
localName = localName.toLowerCase();
}
return generatedAttr.create([], { localName });
};
core.Document.prototype.createAttributeNS = function (namespace, name) {
if (arguments.length < 2) {
throw new TypeError("not enough arguments to Document.prototype.createAttributeNS");
}
if (namespace === undefined) {
namespace = null;
}
namespace = namespace !== null ? String(namespace) : namespace;
name = String(name);
const extracted = validateAndExtract(namespace, name);
return generatedAttr.create([], {
namespace: extracted.namespace,
namespacePrefix: extracted.prefix,
localName: extracted.localName
});
};
core.Document.prototype.importNode = function (node, deep) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to Document.prototype.createElement");
}
if (!("_ownerDocument" in node)) {
throw new TypeError("First argument to importNode must be a Node");
}
deep = Boolean(deep);
if (node.nodeType === NODE_TYPE.DOCUMENT_NODE) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Cannot import a document node");
}
return clone(core, node, this, deep);
};
core.Document.prototype.getElementsByClassName = memoizeQuery(function getElementsByClassName(classNames) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to Document.prototype.getElementsByClassName");
}
classNames = String(classNames);
return listOfElementsWithClassNames(classNames, this);
});
// path_to_url#dom-document-cookie
defineGetter(core.Document.prototype, "cookie", function () {
return this._cookieJar.getCookieStringSync(this._URL, { http: false });
});
defineSetter(core.Document.prototype, "cookie", function (cookieStr) {
cookieStr = String(cookieStr);
this._cookieJar.setCookieSync(cookieStr, this._URL, {
http: false,
ignoreError: true
});
});
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/document.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,147 |
```javascript
"use strict";
const nwmatcher = require("nwmatcher/src/nwmatcher-noqsa");
const memoizeQuery = require("../utils").memoizeQuery;
const domSymbolTree = require("./helpers/internal-constants").domSymbolTree;
const createStaticNodeList = require("../living/node-list").createStatic;
const DOMException = require("../web-idl/DOMException");
module.exports = function (core) {
for (const Class of [core.Document, core.DocumentFragment, core.Element]) {
Class.prototype.querySelector = memoizeQuery(function (selectors) {
selectors = String(selectors);
const matcher = addNwmatcher(this);
try {
return matcher.first(selectors, this);
} catch (e) {
throw new DOMException(DOMException.SYNTAX_ERR, e.message);
}
});
Class.prototype.querySelectorAll = memoizeQuery(function (selectors) {
selectors = String(selectors);
const matcher = addNwmatcher(this);
let list;
try {
list = matcher.select(selectors, this);
} catch (e) {
throw new DOMException(DOMException.SYNTAX_ERR, e.message);
}
return createStaticNodeList(list);
});
}
core.Element.prototype.matches = memoizeQuery(function (selectors) {
selectors = String(selectors);
const matcher = addNwmatcher(this);
try {
return matcher.match(this, selectors);
} catch (e) {
throw new DOMException(DOMException.SYNTAX_ERR, e.message);
}
});
};
// Internal method so you don't have to go through the public API
module.exports.querySelector = function (parentNode, selectors) {
if (!domSymbolTree.hasChildren(parentNode) ||
(parentNode === parentNode._ownerDocument && !parentNode._documentElement)) {
// This allows us to avoid the explosion that occurs if you try to add nwmatcher to a document that is not yet
// initialized.
return null;
}
return addNwmatcher(parentNode).first(selectors, parentNode);
};
// nwmatcher gets `document.documentElement` at creation-time, so we have to initialize lazily, since in the initial
// stages of Document initialization, there is no documentElement present yet.
function addNwmatcher(parentNode) {
const document = parentNode._ownerDocument;
if (!document._nwmatcher) {
document._nwmatcher = nwmatcher({ document });
document._nwmatcher.configure({ UNIQUE_ID: false });
}
return document._nwmatcher;
}
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/selectors.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 531 |
```javascript
"use strict";
exports.formData = Symbol("entries");
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/form-data-symbols.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 11 |
```javascript
"use strict";
const defineGetter = require("../utils").defineGetter;
const memoizeQuery = require("../utils").memoizeQuery;
const attributes = require("./attributes");
const attrGenerated = require("./generated/Attr");
const createDOMTokenList = require("./dom-token-list").create;
const listOfElementsWithClassNames = require("./node").listOfElementsWithClassNames;
const validateNames = require("./helpers/validate-names");
const DOMException = require("../web-idl/DOMException");
module.exports = function (core) {
defineGetter(core.Element, "attributes", function () {
return this._attributes;
});
defineGetter(core.Element.prototype, "classList", function () {
if (this._classList === undefined) {
this._classList = createDOMTokenList(this, "class");
}
return this._classList;
});
core.Element.prototype.hasAttributes = function hasAttributes() {
return attributes.hasAttributes(this);
};
core.Element.prototype.getAttribute = function getAttribute(name) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to Element.prototype.getAttribute");
}
name = String(name);
return attributes.getAttributeValue(this, name);
};
core.Element.prototype.getAttributeNS = function getAttributeNS(namespace, localName) {
if (arguments.length < 2) {
throw new TypeError("Not enough arguments to Element.prototype.getAttributeNS");
}
if (namespace === undefined || namespace === null) {
namespace = null;
} else {
namespace = String(namespace);
}
localName = String(localName);
return attributes.getAttributeValueByNameNS(this, namespace, localName);
};
core.Element.prototype.setAttribute = function setAttribute(name, value) {
if (arguments.length < 2) {
throw new TypeError("Not enough arguments to Element.prototype.setAttribute");
}
name = String(name);
value = String(value);
validateNames.name(name);
if (this._namespaceURI === "path_to_url" && this._ownerDocument._parsingMode === "html") {
name = name.toLowerCase();
}
const attribute = attributes.getAttributeByName(this, name);
if (attribute === null) {
const newAttr = attrGenerated.create([], { localName: name, value });
attributes.appendAttribute(this, newAttr);
return;
}
attributes.changeAttribute(this, attribute, value);
};
core.Element.prototype.setAttributeNS = function setAttributeNS(namespace, name, value) {
if (arguments.length < 2) {
throw new TypeError("Not enough arguments to Element.prototype.setAttributeNS");
}
if (namespace === undefined || namespace === null) {
namespace = null;
} else {
namespace = String(namespace);
}
name = String(name);
value = String(value);
const extracted = validateNames.validateAndExtract(namespace, name);
attributes.setAttributeValue(this, extracted.localName, value, extracted.prefix, extracted.namespace);
};
core.Element.prototype.removeAttribute = function removeAttribute(name) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to Element.prototype.removeAttribute");
}
name = String(name);
attributes.removeAttributeByName(this, name);
};
core.Element.prototype.removeAttributeNS = function removeAttributeNS(namespace, localName) {
if (arguments.length < 2) {
throw new TypeError("Not enough arguments to Element.prototype.removeAttributeNS");
}
if (namespace === undefined || namespace === null) {
namespace = null;
} else {
namespace = String(namespace);
}
localName = String(localName);
attributes.removeAttributeByNameNS(this, namespace, localName);
};
core.Element.prototype.hasAttribute = function hasAttribute(name) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to Element.prototype.hasAttribute");
}
name = String(name);
if (this._namespaceURI === "path_to_url" && this._ownerDocument._parsingMode === "html") {
name = name.toLowerCase();
}
return attributes.hasAttributeByName(this, name);
};
core.Element.prototype.hasAttributeNS = function hasAttributeNS(namespace, localName) {
if (arguments.length < 2) {
throw new TypeError("Not enough arguments to Element.prototype.hasAttributeNS");
}
if (namespace === undefined || namespace === null) {
namespace = null;
} else {
namespace = String(namespace);
}
localName = String(localName);
if (namespace === "") {
namespace = null;
}
return attributes.hasAttributeByNameNS(this, namespace, localName);
};
core.Element.prototype.getAttributeNode = function getAttributeNode(name) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to Element.prototype.getAttributeNode");
}
name = String(name);
return attributes.getAttributeByName(this, name);
};
core.Element.prototype.getAttributeNodeNS = function getAttributeNodeNS(namespace, localName) {
if (arguments.length < 2) {
throw new TypeError("Not enough arguments to Element.prototype.getAttributeNodeNS");
}
if (namespace === undefined || namespace === null) {
namespace = null;
} else {
namespace = String(namespace);
}
localName = String(localName);
return attributes.getAttributeByNameNS(this, namespace, localName);
};
core.Element.prototype.setAttributeNode = function setAttributeNode(attr) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to Element.prototype.setAttributeNode");
}
if (!attrGenerated.is(attr)) {
throw new TypeError("First argument to Element.prototype.setAttributeNode must be an Attr");
}
return attributes.setAttribute(this, attr);
};
core.Element.prototype.setAttributeNodeNS = function setAttributeNodeNS(attr) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to Element.prototype.setAttributeNodeNS");
}
if (!attrGenerated.is(attr)) {
throw new TypeError("First argument to Element.prototype.setAttributeNodeNS must be an Attr");
}
return attributes.setAttribute(this, attr);
};
core.Element.prototype.removeAttributeNode = function removeAttributeNode(attr) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to Element.prototype.setAttributeNode");
}
if (!attrGenerated.is(attr)) {
throw new TypeError("First argument to Element.prototype.removeAttributeNode must be an Attr");
}
if (!attributes.hasAttribute(this, attr)) {
throw new DOMException(DOMException.NOT_FOUND_ERR, "Tried to remove an attribute that was not present");
}
attributes.removeAttribute(this, attr);
return attr;
};
core.Element.prototype.getElementsByClassName = memoizeQuery(function getElementsByClassName(classNames) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to Element.prototype.getElementsByClassName");
}
classNames = String(classNames);
return listOfElementsWithClassNames(classNames, this);
});
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/element.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,467 |
```javascript
"use strict";
const defineGetter = require("../utils").defineGetter;
const simultaneousIterators = require("../utils").simultaneousIterators;
const attributes = require("./attributes");
const cloneDoctype = require("./document-type").clone;
const cloningSteps = require("./helpers/internal-constants").cloningSteps;
const domSymbolTree = require("./helpers/internal-constants").domSymbolTree;
const NODE_TYPE = require("./node-type");
const documentBaseURL = require("./helpers/document-base-url").documentBaseURL;
const orderedSetParser = require("./helpers/ordered-set-parser");
const createHTMLCollection = require("./html-collection").create;
const domTokenListContains = require("./dom-token-list").contains;
const getDoctypePrivates = require("./document-type").getPrivates;
module.exports = function (core) {
const DOCUMENT_POSITION_DISCONNECTED = core.Node.DOCUMENT_POSITION_DISCONNECTED;
const DOCUMENT_POSITION_FOLLOWING = core.Node.DOCUMENT_POSITION_FOLLOWING;
const DOCUMENT_POSITION_CONTAINED_BY = core.Node.DOCUMENT_POSITION_CONTAINED_BY;
const DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = core.Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
/**
* Return true if node is of a type obsoleted by the WHATWG living standard
* @param {Node} node
* @return {Boolean}
*/
function isObsoleteNodeType(node) {
return node.nodeType === NODE_TYPE.ENTITY_NODE ||
node.nodeType === NODE_TYPE.ENTITY_REFERENCE_NODE ||
node.nodeType === NODE_TYPE.NOTATION_NODE ||
node.nodeType === NODE_TYPE.CDATA_SECTION_NODE;
}
core.Node.prototype.cloneNode = function (deep) {
deep = Boolean(deep);
return module.exports.clone(core, this, undefined, deep);
};
/**
* Returns a bitmask Number composed of DOCUMENT_POSITION constants based upon the rules defined in
* path_to_url#dom-node-comparedocumentposition
* @param {Node} other
* @return {Number}
*/
core.Node.prototype.compareDocumentPosition = function (other) {
// Let reference be the context object.
const reference = this;
if (!(other instanceof core.Node)) {
throw new Error("Comparing position against non-Node values is not allowed");
}
if (isObsoleteNodeType(reference) || isObsoleteNodeType(other)) {
throw new Error("Obsolete node type");
}
const result = domSymbolTree.compareTreePosition(reference, other);
// If other and reference are not in the same tree, return the result of adding DOCUMENT_POSITION_DISCONNECTED,
// DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, and either DOCUMENT_POSITION_PRECEDING or
// DOCUMENT_POSITION_FOLLOWING, with the constraint that this is to be consistent, together.
if (result === DOCUMENT_POSITION_DISCONNECTED) {
// symbol-tree does not add these bits required by the spec:
return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_FOLLOWING;
}
return result;
};
/**
* The contains(other) method returns true if other is an inclusive descendant of the context object,
* and false otherwise (including when other is null).
* @param {[Node]} other [the node to test]
* @return {[boolean]} [whether other is an inclusive descendant of this]
*/
core.Node.prototype.contains = function (other) {
return Boolean(other instanceof core.Node &&
(this === other || this.compareDocumentPosition(other) & DOCUMENT_POSITION_CONTAINED_BY)
);
};
// path_to_url#dom-node-parentelement
defineGetter(core.Node.prototype, "parentElement", function () {
const parentNode = domSymbolTree.parent(this);
return parentNode !== null && parentNode.nodeType === NODE_TYPE.ELEMENT_NODE ? parentNode : null;
});
// path_to_url#dom-node-baseuri
defineGetter(core.Node.prototype, "baseURI", function () {
return documentBaseURL(this._ownerDocument);
});
function nodeEquals(a, b) {
if (a.nodeType !== b.nodeType) {
return false;
}
switch (a.nodeType) {
case NODE_TYPE.DOCUMENT_TYPE_NODE:
const privatesA = getDoctypePrivates(a);
const privatesB = getDoctypePrivates(b);
if (privatesA.name !== privatesB.name || privatesA.publicId !== privatesB.publicId ||
privatesA.systemId !== privatesB.systemId) {
return false;
}
break;
case NODE_TYPE.ELEMENT_NODE:
if (a._namespaceURI !== b._namespaceURI || a._prefix !== b._prefix || a._localName !== b._localName ||
a._attributes.length !== b._attributes.length) {
return false;
}
break;
case NODE_TYPE.PROCESSING_INSTRUCTION_NODE:
if (a._target !== b._target || a._data !== b._data) {
return false;
}
break;
case NODE_TYPE.TEXT_NODE:
case NODE_TYPE.COMMENT_NODE:
if (a._data !== b._data) {
return false;
}
break;
}
if (a.nodeType === NODE_TYPE.ELEMENT_NODE && !attributes.attributeListsEqual(a, b)) {
return false;
}
for (const nodes of simultaneousIterators(domSymbolTree.childrenIterator(a), domSymbolTree.childrenIterator(b))) {
if (!nodes[0] || !nodes[1]) {
// mismatch in the amount of childNodes
return false;
}
if (!nodeEquals(nodes[0], nodes[1])) {
return false;
}
}
return true;
}
// path_to_url#dom-node-isequalnode
core.Node.prototype.isEqualNode = function (node) {
if (node === undefined) {
// this is what Node? means in the IDL
node = null;
}
if (node === null) {
return false;
}
// Fast-path, not in the spec
if (this === node) {
return true;
}
return nodeEquals(this, node);
};
};
module.exports.clone = function (core, node, document, cloneChildren) {
if (document === undefined) {
document = node._ownerDocument;
}
let copy;
switch (node.nodeType) {
case NODE_TYPE.DOCUMENT_NODE:
// TODO: just use Document when we eliminate the difference between Document and HTMLDocument.
copy = new node.constructor({
contentType: node._contentType,
url: node._URL,
parsingMode: node._parsingMode
});
document = copy;
break;
case NODE_TYPE.DOCUMENT_TYPE_NODE:
copy = cloneDoctype(core, node);
break;
case NODE_TYPE.ELEMENT_NODE:
copy = document._createElementWithCorrectElementInterface(node._localName, node._namespaceURI);
copy._namespaceURI = node._namespaceURI;
copy._prefix = node._prefix;
copy._localName = node._localName;
attributes.copyAttributeList(node, copy);
break;
case NODE_TYPE.TEXT_NODE:
copy = new core.Text(document, node._data);
break;
case NODE_TYPE.COMMENT_NODE:
copy = new core.Comment(document, node._data);
break;
case NODE_TYPE.PROCESSING_INSTRUCTION_NODE:
copy = new core.ProcessingInstruction(document, node._target, node._data);
break;
case NODE_TYPE.DOCUMENT_FRAGMENT_NODE:
copy = new core.DocumentFragment(document);
break;
}
if (node[cloningSteps]) {
node[cloningSteps](copy, node, document, cloneChildren);
}
if (cloneChildren) {
for (const child of domSymbolTree.childrenIterator(node)) {
const childCopy = module.exports.clone(core, child, document, true);
copy.appendChild(childCopy);
}
}
return copy;
};
module.exports.listOfElementsWithClassNames = function (classNames, root) {
// path_to_url#concept-getElementsByClassName
const classes = orderedSetParser(classNames);
if (classes.size === 0) {
return createHTMLCollection(root, () => false);
}
return createHTMLCollection(root, () => {
const isQuirksMode = root._ownerDocument.compatMode === "BackCompat";
return domSymbolTree.treeToArray(root, { filter(node) {
if (node.nodeType !== NODE_TYPE.ELEMENT_NODE || node === root) {
return false;
}
for (const className of classes) {
if (!domTokenListContains(node.classList, className, { caseInsensitive: isQuirksMode })) {
return false;
}
}
return true;
} });
});
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/node.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,855 |
```javascript
"use strict";
const filelistSymbols = require("./filelist-symbols");
module.exports = function (core) {
class FileList {
constructor() {
if (!(this instanceof FileList)) {
throw new TypeError("DOM object constructor cannot be called as a function.");
}
this[filelistSymbols.list] = [];
}
item(index) {
return this[filelistSymbols.list][index] || null;
}
get length() {
return this[filelistSymbols.list].length;
}
}
core.FileList = FileList;
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/filelist.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 118 |
```javascript
"use strict";
const util = require("util");
const jsdom = require("../../jsdom");
const xhrSymbols = require("./xmlhttprequest-symbols");
const chunks = [];
process.stdin.on("data", chunk => {
chunks.push(chunk);
});
process.stdin.on("end", () => {
const buffer = Buffer.concat(chunks);
const doc = jsdom.jsdom();
const xhr = new doc.defaultView.XMLHttpRequest();
const flag = JSON.parse(buffer.toString(), (k, v) => {
if (v && v.type === "Buffer" && v.data) {
return new Buffer(v.data);
}
return v;
});
flag.synchronous = false;
xhr[xhrSymbols.flag] = flag;
const properties = xhr[xhrSymbols.properties];
properties.readyState = doc.defaultView.XMLHttpRequest.OPENED;
try {
xhr.addEventListener("load", () => {
process.stdout.write(JSON.stringify({ properties }), () => {
process.exit(0);
});
}, false);
xhr.addEventListener("error", error => {
process.stdout.write(JSON.stringify({ properties, error: error.stack || util.inspect(error) }), () => {
process.exit(0);
});
}, false);
xhr.send(flag.body);
} catch (error) {
process.stdout.write(JSON.stringify({ properties, error: error.stack || util.inspect(error) }), () => {
process.exit(0);
});
}
});
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/xhr-sync-worker.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 300 |
```javascript
"use strict";
const formDataSymbols = require("./form-data-symbols");
module.exports = function (core) {
const Blob = core.Blob;
const File = core.File;
class FormData {
constructor(form) {
if (!(this instanceof FormData)) {
throw new TypeError("DOM object constructor cannot be called as a function.");
}
const entries = this[formDataSymbols.entries] = [];
if (form && form.elements) {
for (let i = 0; i < form.elements.length; i++) {
const el = form.elements[i];
if (el.type === "file") {
for (let j = 0; j < el.files.length; j++) {
entries.push({ name: el.name, value: el.files.item(j) });
}
} else {
entries.push({ name: el.name, value: el.value });
}
}
}
}
append(name, value, filename) {
if (value instanceof Blob) {
value = new File(
[value],
filename || value.name || "blob",
{ type: value.type, lastModified: value.lastModified }
);
} else {
value = String(value);
}
const entries = this[formDataSymbols.entries];
entries.push({ name, value });
}
delete(name) {
this[formDataSymbols.entries] = this[formDataSymbols.entries].filter(entry => entry.name !== name);
}
get(name) {
return this[formDataSymbols.entries].find(entry => entry.name === name) || null;
}
getAll(name) {
return this[formDataSymbols.entries].filter(entry => entry.name === name).map(entry => entry.value);
}
has(name) {
return this[formDataSymbols.entries].findIndex(entry => entry.name === name) !== -1;
}
set(name, value, filename) {
if (value instanceof Blob) {
value = new File(
[value],
filename || value.name || "blob",
{ type: value.type, lastModified: value.lastModified }
);
} else {
value = String(value);
}
const newEntry = { name, value };
const entries = this[formDataSymbols.entries];
const existing = entries.findIndex(entry => entry.name === name);
if (existing !== -1) {
entries[existing] = newEntry;
this[formDataSymbols.entries] = entries.filter((entry, index) => entry.name !== name || index === existing);
} else {
entries.push(newEntry);
}
}
toString() {
return "[object FormData]";
}
}
core.FormData = FormData;
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/form-data.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 564 |
```javascript
"use strict";
const inheritFrom = require("../utils").inheritFrom;
const domSymbolTree = require("./helpers/internal-constants").domSymbolTree;
const NODE_TYPE = require("../living/node-type");
module.exports = function (core) {
// TODO: constructor should not take ownerDocument
core.Text = function Text(ownerDocument, data) {
core.CharacterData.call(this, ownerDocument, data);
};
inheritFrom(core.CharacterData, core.Text, {
nodeType: NODE_TYPE.TEXT_NODE, // TODO should be on prototype, not here
splitText(offset) {
offset >>>= 0;
const length = this.length;
if (offset > length) {
throw new core.DOMException(core.DOMException.INDEX_SIZE_ERR);
}
const count = length - offset;
const newData = this.substringData(offset, count);
const newNode = this._ownerDocument.createTextNode(newData);
const parent = domSymbolTree.parent(this);
if (parent !== null) {
parent.insertBefore(newNode, this.nextSibling);
}
this.replaceData(offset, count, "");
return newNode;
// TODO: range stuff
}
// TODO: wholeText property
});
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/text.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 253 |
```javascript
"use strict";
const defineGetter = require("../utils").defineGetter;
const domSymbolTree = require("./helpers/internal-constants").domSymbolTree;
const NODE_TYPE = require("./node-type");
const createHTMLCollection = require("./html-collection").create;
const updateHTMLCollection = require("./html-collection").update;
module.exports = function (core) {
// path_to_url#interface-parentnode
// Note that ParentNode is a "NoInterfaceObject"
for (const Constructor of [core.Document, core.DocumentFragment, core.Element]) {
defineGetter(Constructor.prototype, "children", function () {
if (!this._childrenList) {
this._childrenList = createHTMLCollection(this, () => {
return domSymbolTree.childrenToArray(this, { filter(node) {
return node.nodeType === NODE_TYPE.ELEMENT_NODE;
} });
});
} else {
updateHTMLCollection(this._childrenList);
}
return this._childrenList;
});
defineGetter(Constructor.prototype, "firstElementChild", function () {
for (const child of domSymbolTree.childrenIterator(this)) {
if (child.nodeType === NODE_TYPE.ELEMENT_NODE) {
return child;
}
}
return null;
});
defineGetter(Constructor.prototype, "lastElementChild", function () {
for (const child of domSymbolTree.childrenIterator(this, { reverse: true })) {
if (child.nodeType === NODE_TYPE.ELEMENT_NODE) {
return child;
}
}
return null;
});
defineGetter(Constructor.prototype, "childElementCount", function () {
return this.children.length;
});
}
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/parent-node.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 342 |
```javascript
"use strict";
const inheritFrom = require("../utils").inheritFrom;
const NODE_TYPE = require("../living/node-type");
module.exports = function (core) {
core.ProcessingInstruction = function ProcessingInstruction(ownerDocument, target, data) {
core.CharacterData.call(this, ownerDocument, data);
this._target = target;
};
inheritFrom(core.CharacterData, core.ProcessingInstruction, {
nodeType: NODE_TYPE.PROCESSING_INSTRUCTION_NODE, // TODO should be on prototype, not here
get target() {
return this._target;
}
});
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/processing-instruction.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 123 |
```javascript
"use strict";
const blobSymbols = require("./blob-symbols");
class Blob {
constructor() {
if (!(this instanceof Blob)) {
throw new TypeError("DOM object constructor cannot be called as a function.");
}
const parts = arguments[0];
const properties = arguments[1];
if (arguments.length > 0) {
if (!parts || typeof parts !== "object" || parts instanceof Date || parts instanceof RegExp) {
throw new TypeError("Blob parts must be objects that are not Dates or RegExps");
}
}
const buffers = [];
if (parts) {
const l = Number(parts.length);
for (let i = 0; i < l; i++) {
const part = parts[i];
let buffer;
if (part instanceof ArrayBuffer) {
buffer = new Buffer(new Uint8Array(part));
} else if (part instanceof Blob) {
buffer = part[blobSymbols.buffer];
} else if (ArrayBuffer.isView(part)) {
buffer = new Buffer(new Uint8Array(part.buffer, part.byteOffset, part.byteLength));
} else {
buffer = new Buffer(typeof part === "string" ? part : String(part));
}
buffers.push(buffer);
}
}
this[blobSymbols.buffer] = Buffer.concat(buffers);
this[blobSymbols.type] = properties && properties.type ? String(properties.type).toLowerCase() : "";
if (!this[blobSymbols.type].match(/^ *[a-z0-9-]+(?:\/[a-z0-9-]+)? *(; *charset *= *[a-z0-9-]+ *)?$/)) {
this[blobSymbols.type] = "";
}
this[blobSymbols.lastModified] = properties && properties.lastModified ? properties.lastModified : null;
this[blobSymbols.closed] = false;
}
get size() {
return this[blobSymbols.buffer].length;
}
get type() {
return this[blobSymbols.type];
}
get lastModified() {
return this[blobSymbols.lastModified];
}
slice() {
const buffer = this[blobSymbols.buffer];
const slicedBuffer = buffer.slice(
arguments[0] || 0,
arguments[1] || this.size
);
const blob = new Blob([], { type: arguments[2] || this.type });
blob[blobSymbols.buffer] = slicedBuffer;
return blob;
}
close() {
this[blobSymbols.closed] = true;
}
toString() {
return "[object Blob]";
}
}
module.exports = function (core) {
core.Blob = Blob;
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/blob.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 561 |
```javascript
"use strict";
const inheritFrom = require("../utils").inheritFrom;
const NODE_TYPE = require("../living/node-type");
module.exports = function (core) {
// TODO: constructor should not take ownerDocument
core.Comment = function Comment(ownerDocument, data) {
core.CharacterData.call(this, ownerDocument, data);
};
inheritFrom(core.CharacterData, core.Comment, {
nodeType: NODE_TYPE.COMMENT_NODE // TODO should be on prototype, not here
});
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/comment.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 103 |
```javascript
"use strict";
const hasOwnProp = Object.prototype.hasOwnProperty;
const namedPropertiesTracker = require("../named-properties-tracker");
const NODE_TYPE = require("./node-type");
const createHTMLCollection = require("./html-collection").create;
const treeOrderSorter = require("../utils").treeOrderSorter;
function isNamedPropertyElement(element) {
// (for the name attribute)
// use hasOwnProperty to make sure contentWindow comes from the prototype,
// and is not set directly on the node by a script.
if ("contentWindow" in element && !hasOwnProp.call(element, "contentWindow")) {
return true;
}
switch (element.nodeName) {
case "A":
case "APPLET":
case "AREA":
case "EMBED":
case "FORM":
case "FRAMESET":
case "IMG":
case "OBJECT":
return true;
default:
return false;
}
}
function namedPropertyResolver(HTMLCollection, window, name, values) {
function getResult() {
const results = [];
for (const node of values().keys()) {
if (node.nodeType !== NODE_TYPE.ELEMENT_NODE) {
continue;
}
if (node.getAttribute("id") === name) {
results.push(node);
} else if (node.getAttribute("name") === name && isNamedPropertyElement(node)) {
results.push(node);
}
}
results.sort(treeOrderSorter);
return results;
}
const document = window._document;
const objects = createHTMLCollection(document.documentElement, getResult);
const length = objects.length;
for (let i = 0; i < length; ++i) {
const node = objects[i];
if ("contentWindow" in node && !hasOwnProp.call(node, "contentWindow")) {
return node.contentWindow;
}
}
if (length === 0) {
return undefined;
}
if (length === 1) {
return objects[0];
}
return objects;
}
exports.initializeWindow = function (window, HTMLCollection) {
namedPropertiesTracker.create(window, namedPropertyResolver.bind(null, HTMLCollection));
};
exports.elementAttributeModified = function (element, name, value, oldValue) {
if (!element._attached) {
return;
}
const useName = isNamedPropertyElement(element);
if (name === "id" || (name === "name" && useName)) {
const tracker = namedPropertiesTracker.get(element._ownerDocument._global);
// (tracker will be null if the document has no Window)
if (tracker) {
if (name === "id" && (!useName || element.getAttribute("name") !== oldValue)) {
tracker.untrack(oldValue, element);
}
if (name === "name" && element.getAttribute("id") !== oldValue) {
tracker.untrack(oldValue, element);
}
tracker.track(value, element);
}
}
};
exports.nodeAttachedToDocument = function (node) {
if (node.nodeType !== NODE_TYPE.ELEMENT_NODE) {
return;
}
const tracker = namedPropertiesTracker.get(node._ownerDocument._global);
if (!tracker) {
return;
}
tracker.track(node.getAttribute("id"), node);
if (isNamedPropertyElement(node)) {
tracker.track(node.getAttribute("name"), node);
}
};
exports.nodeDetachedFromDocument = function (node) {
if (node.nodeType !== NODE_TYPE.ELEMENT_NODE) {
return;
}
const tracker = namedPropertiesTracker.get(node._ownerDocument._global);
if (!tracker) {
return;
}
tracker.untrack(node.getAttribute("id"), node);
if (isNamedPropertyElement(node)) {
tracker.untrack(node.getAttribute("name"), node);
}
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/named-properties-window.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 807 |
```javascript
"use strict";
const lengthFromProperties = require("../utils").lengthFromProperties;
const privates = Symbol("NodeList internal slots");
class NodeList {
constructor(secret, config) {
if (secret !== privates) {
throw new TypeError("Invalid constructor");
}
if (config.nodes) {
this[privates] = {
isLive: false,
length: config.nodes.length
};
for (let i = 0; i < config.nodes.length; ++i) {
this[i] = config.nodes[i];
}
} else {
this[privates] = {
isLive: true,
element: config.element,
query: config.query,
snapshot: undefined,
length: 0,
version: -1
};
updateNodeList(this);
}
}
get length() {
updateNodeList(this);
return this[privates].length;
}
item(index) {
updateNodeList(this);
return this[index] || null;
}
}
NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
function updateNodeList(nodeList) {
if (nodeList[privates].isLive) {
if (nodeList[privates].version < nodeList[privates].element._version) {
nodeList[privates].snapshot = nodeList[privates].query();
resetNodeListTo(nodeList, nodeList[privates].snapshot);
nodeList[privates].version = nodeList[privates].element._version;
}
} else {
nodeList[privates].length = lengthFromProperties(nodeList);
}
}
function resetNodeListTo(nodeList, nodes) {
const startingLength = lengthFromProperties(nodeList);
for (let i = 0; i < startingLength; ++i) {
delete nodeList[i];
}
for (let i = 0; i < nodes.length; ++i) {
nodeList[i] = nodes[i];
}
nodeList[privates].length = nodes.length;
}
module.exports = function (core) {
core.NodeList = NodeList;
};
module.exports.createLive = function (element, query) {
return new NodeList(privates, { element, query });
};
module.exports.createStatic = function (nodes) {
return new NodeList(privates, { nodes });
};
module.exports.update = updateNodeList;
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/node-list.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 503 |
```javascript
"use strict";
const fileSymbols = require("./file-symbols");
module.exports = function (core) {
const Blob = core.Blob;
class File extends Blob {
constructor(fileBits, fileName) {
super(fileBits, arguments[2]);
if (!(this instanceof File)) {
throw new TypeError("DOM object constructor cannot be called as a function.");
}
this[fileSymbols.name] = fileName.replace(/\//g, ":");
}
get name() {
return this[fileSymbols.name];
}
}
core.File = File;
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/file.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 118 |
```javascript
"use strict";
const URL = require("whatwg-url-compat");
module.exports = function (core) {
core.URL = URL.createURLConstructor();
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/url.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 33 |
```javascript
"use strict";
exports.flag = Symbol("flag");
exports.properties = Symbol("properties");
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/xmlhttprequest-symbols.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 18 |
```javascript
"use strict";
const inheritFrom = require("../utils").inheritFrom;
const domSymbolTree = require("./helpers/internal-constants").domSymbolTree;
module.exports = function (core) {
core.CharacterData = function CharacterData(ownerDocument, data) {
core.Node.call(this, ownerDocument);
this._data = data;
};
inheritFrom(core.Node, core.CharacterData, {
get data() {
return this._data;
},
set data(data) {
if (data === null) {
data = "";
}
data = String(data);
this._setData(data);
},
get length() {
return this._data.length;
},
substringData(offset, count) {
if (arguments.length < 2) {
throw new TypeError("Not enough arguments to CharacterData.prototype.substringData");
}
offset >>>= 0;
count >>>= 0;
const length = this.length;
if (offset > length) {
throw new core.DOMException(core.DOMException.INDEX_SIZE_ERR);
}
if (offset + count > length) {
return this._data.substring(offset);
}
return this._data.substring(offset, offset + count);
},
appendData(data) {
if (arguments.length < 1) {
throw new TypeError("Not enough arguments to CharacterData.prototype.appendData");
}
this.replaceData(this.length, 0, data);
},
insertData(offset, data) {
if (arguments.length < 2) {
throw new TypeError("Not enough arguments to CharacterData.prototype.insertData");
}
this.replaceData(offset, 0, data);
},
deleteData(offset, count) {
if (arguments.length < 2) {
throw new TypeError("Not enough arguments to CharacterData.prototype.deleteData");
}
this.replaceData(offset, count, "");
},
replaceData(offset, count, data) {
if (arguments.length < 3) {
throw new TypeError("Not enough arguments to CharacterData.prototype.replaceData");
}
offset >>>= 0;
count >>>= 0;
data = String(data);
const length = this.length;
if (offset > length) {
throw new core.DOMException(core.DOMException.INDEX_SIZE_ERR);
}
if (offset + count > length) {
count = length - offset;
}
const start = this._data.substring(0, offset);
const end = this._data.substring(offset + count);
this._setData(start + data + end);
// TODO: range stuff
},
_setData(newData) {
// TODO: remove this once we no longer rely on mutation events internally, since they are nonstandard
const oldData = this._data;
this._data = newData;
if (this._ownerDocument &&
domSymbolTree.parent(this) &&
this._ownerDocument.implementation._hasFeature("MutationEvents")) {
const ev = this._ownerDocument.createEvent("MutationEvents");
ev.initMutationEvent("DOMCharacterDataModified", true, false, this, oldData, newData, null, null);
this.dispatchEvent(ev);
}
}
});
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/character-data.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 677 |
```javascript
"use strict";
const EventTarget = require("./generated/EventTarget");
function XMLHttpRequestEventTarget() {
if (!(this instanceof XMLHttpRequestEventTarget)) {
throw new TypeError("DOM object constructor cannot be called as a function.");
}
EventTarget.setup(this);
this.onabort = null;
this.onerror = null;
this.onload = null;
this.onloadend = null;
this.onloadstart = null;
this.onprogress = null;
this.ontimeout = null;
}
XMLHttpRequestEventTarget.prototype = Object.create(EventTarget.interface.prototype);
module.exports = function (core) {
core.XMLHttpRequestEventTarget = XMLHttpRequestEventTarget;
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/xmlhttprequest-event-target.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 137 |
```javascript
"use strict";
const HTTP_STATUS_CODES = require("http").STATUS_CODES;
const spawnSync = require("child_process").spawnSync;
const xhrUtils = require("./xhr-utils");
const DOMException = require("../web-idl/DOMException");
const xhrSymbols = require("./xmlhttprequest-symbols");
const blobSymbols = require("./blob-symbols");
const formDataSymbols = require("./form-data-symbols");
const utils = require("../utils");
const documentBaseURLHelper = require("./helpers/document-base-url");
const forbiddenRequestHeaders = new RegExp("^(?:" + [
"Accept-Charset",
"Accept-Encoding",
"Access-Control-Request-Headers",
"Access-Control-Request-Method",
"Connection",
"Content-Length",
"Cookie",
"Cookie2",
"Date",
"DNT",
"Expect",
"Host",
"Keep-Alive",
"Origin",
"Referer",
"TE",
"Trailer",
"Transfer-Encoding",
"Upgrade",
"User-Agent",
"Via",
"Sec-.*",
"Proxy-.*"
].join("|") + ")$", "i");
const uniqueResponseHeaders = new RegExp("^(?:" + [
"content-type",
"content-length",
"user-agent",
"referer",
"host",
"authorization",
"proxy-authorization",
"if-modified-since",
"if-unmodified-since",
"from",
"location",
"max-forwards"
].join("|") + ")$", "i");
const allowedRequestMethods = ["OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE"];
const forbiddenRequestMethods = ["TRACK", "TRACE", "CONNECT"];
const tokenRegexp = /^(?:(?![\x00-\x1F\x7F \t\(\)<>@,;:\\"\/\[\]?={}])[\x00-\x7F])+$/;
const fieldValueRegexp = /^(?:(?![\x00-\x1F\x7F])[\x00-\xFF])*$/;
const XMLHttpRequestResponseType = [
"",
"arraybuffer",
"blob",
"document",
"json",
"text"
];
module.exports = function createXMLHttpRequest(window) {
const Event = window.Event;
const ProgressEvent = window.ProgressEvent;
const Blob = window.Blob;
const FormData = window.FormData;
const XMLHttpRequestEventTarget = window.XMLHttpRequestEventTarget;
const XMLHttpRequestUpload = window.XMLHttpRequestUpload;
class XMLHttpRequest extends XMLHttpRequestEventTarget {
constructor() {
super();
if (!(this instanceof XMLHttpRequest)) {
throw new TypeError("DOM object constructor cannot be called as a function.");
}
this.upload = new XMLHttpRequestUpload();
this.upload._ownerDocument = window.document;
this[xhrSymbols.flag] = {
synchronous: false,
withCredentials: false,
mimeType: null,
auth: null,
method: undefined,
responseType: "",
requestHeaders: {},
baseUrl: "",
uri: "",
userAgent: "",
timeout: 0,
body: undefined,
formData: false
};
this[xhrSymbols.properties] = {
send: false,
timeoutStart: 0,
timeoutId: 0,
timeoutFn: null,
client: null,
responseHeaders: {},
responseBuffer: null,
responseCache: null,
responseTextCache: null,
responseXMLCache: null,
readyState: XMLHttpRequest.UNSENT,
status: 0,
statusText: ""
};
this.onreadystatechange = null;
}
get readyState() {
return this[xhrSymbols.properties].readyState;
}
get status() {
return this[xhrSymbols.properties].status;
}
get statusText() {
return this[xhrSymbols.properties].statusText;
}
get responseType() {
return this[xhrSymbols.flag].responseType;
}
set responseType(responseType) {
const flag = this[xhrSymbols.flag];
if (this.readyState === XMLHttpRequest.LOADING || this.readyState === XMLHttpRequest.DONE) {
throw new DOMException(DOMException.INVALID_STATE_ERR);
}
if (this.readyState === XMLHttpRequest.OPENED && flag.synchronous) {
throw new DOMException(DOMException.INVALID_ACCESS_ERR);
}
if (XMLHttpRequestResponseType.indexOf(responseType) === -1) {
responseType = "";
}
flag.responseType = responseType;
}
get response() {
const properties = this[xhrSymbols.properties];
if (properties.responseCache) {
return properties.responseCache;
}
let res = "";
switch (this.responseType) {
case "":
case "text":
res = this.responseText;
break;
case "arraybuffer":
if (!properties.responseBuffer) {
return null;
}
res = (new Uint8Array(properties.responseBuffer)).buffer;
break;
case "blob":
if (!properties.responseBuffer) {
return null;
}
res = new Blob([(new Uint8Array(properties.responseBuffer)).buffer]);
break;
case "document":
res = this.responseXML;
break;
case "json":
if (this.readyState !== XMLHttpRequest.DONE || !properties.responseBuffer) {
res = null;
}
try {
res = JSON.parse(properties.responseBuffer.toString());
} catch (e) {
res = null;
}
break;
}
properties.responseCache = res;
return res;
}
get responseText() {
const properties = this[xhrSymbols.properties];
if (this.responseType !== "" && this.responseType !== "text") {
throw new DOMException(DOMException.INVALID_STATE_ERR);
}
if (this.readyState !== XMLHttpRequest.LOADING && this.readyState !== XMLHttpRequest.DONE) {
return "";
}
if (properties.responseTextCache) {
return properties.responseTextCache;
}
const responseBuffer = properties.responseBuffer;
if (!responseBuffer) {
return "";
}
const res = responseBuffer.toString();
properties.responseTextCache = res;
return res;
}
get responseXML() {
const flag = this[xhrSymbols.flag];
const properties = this[xhrSymbols.properties];
if (this.responseType !== "" && this.responseType !== "document") {
throw new DOMException(DOMException.INVALID_STATE_ERR);
}
if (this.readyState !== XMLHttpRequest.DONE) {
return null;
}
if (properties.responseXMLCache) {
return properties.responseXMLCache;
}
const contentType = flag.mimeType || this.getResponseHeader("Content-Type");
if (contentType && !contentType.match(/^(?:text\/html|text\/xml|application\/xml|.*?\+xml)(?:;.*)*$/)) {
return null;
}
const responseBuffer = properties.responseBuffer;
if (!responseBuffer) {
return null;
}
const resText = responseBuffer.toString();
const res = new window.Document({ parsingMode: "xml" });
res._htmlToDom.appendHtmlToDocument(resText, res);
properties.responseXMLCache = res;
return res;
}
get timeout() {
return this[xhrSymbols.flag].timeout;
}
set timeout(val) {
const flag = this[xhrSymbols.flag];
const properties = this[xhrSymbols.properties];
if (flag.synchronous) {
throw new DOMException(DOMException.INVALID_ACCESS_ERR);
}
flag.timeout = val;
clearTimeout(properties.timeoutId);
if (val > 0 && properties.timeoutFn) {
properties.timeoutId = setTimeout(
properties.timeoutFn,
Math.max(0, val - ((new Date()).getTime() - properties.timeoutStart))
);
} else {
properties.timeoutFn = null;
properties.timeoutStart = 0;
}
}
get withCredentials() {
return this[xhrSymbols.flag].withCredentials;
}
set withCredentials(val) {
const flag = this[xhrSymbols.flag];
const properties = this[xhrSymbols.properties];
if (!(this.readyState === XMLHttpRequest.UNSENT || this.readyState === XMLHttpRequest.OPENED)) {
throw new DOMException(DOMException.INVALID_STATE_ERR);
}
if (properties.send) {
throw new DOMException(DOMException.INVALID_STATE_ERR);
}
if (flag.synchronous) {
throw new DOMException(DOMException.INVALID_ACCESS_ERR);
}
flag.withCredentials = val;
}
abort() {
const flag = this[xhrSymbols.flag];
const properties = this[xhrSymbols.properties];
clearTimeout(properties.timeoutId);
properties.timeoutFn = null;
properties.timeoutStart = 0;
const client = properties.client;
if (client) {
client.abort();
}
if (!(this.readyState === XMLHttpRequest.UNSENT ||
(this.readyState === XMLHttpRequest.OPENED && !properties.send) ||
this.readyState === XMLHttpRequest.DONE)) {
properties.send = false;
readyStateChange(this, XMLHttpRequest.DONE);
if (!(flag.method === "HEAD" || flag.method === "GET")) {
this.upload.dispatchEvent(new ProgressEvent("progress"));
this.upload.dispatchEvent(new ProgressEvent("abort"));
this.upload.dispatchEvent(new ProgressEvent("loadend"));
}
this.dispatchEvent(new ProgressEvent("progress"));
this.dispatchEvent(new ProgressEvent("abort"));
this.dispatchEvent(new ProgressEvent("loadend"));
}
properties.readyState = XMLHttpRequest.UNSENT;
}
getAllResponseHeaders() {
const properties = this[xhrSymbols.properties];
const readyState = this.readyState;
if ([XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED].indexOf(readyState) >= 0) {
return "";
}
return Object.keys(properties.responseHeaders)
.filter(key => {
const keyLc = key.toLowerCase();
return keyLc !== "set-cookie" && keyLc !== "set-cookie2";
})
.map(key => {
return [key, properties.responseHeaders[key]].join(": ");
}, this).join("\r\n");
}
getResponseHeader(header) {
const properties = this[xhrSymbols.properties];
const readyState = this.readyState;
if ([XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED].indexOf(readyState) >= 0) {
return null;
}
const keys = Object.keys(properties.responseHeaders);
let n = keys.length;
const responseHeaders = {};
while (n--) {
const key = keys[n];
responseHeaders[key.toLowerCase()] = properties.responseHeaders[key];
}
const key = header.toLowerCase();
if (key === "set-cookie" || key === "set-cookie2") {
return null;
}
const value = responseHeaders[key];
return typeof value !== "undefined" ? String(value) : null;
}
open(method, uri, async, user, password) {
const flag = this[xhrSymbols.flag];
const properties = this[xhrSymbols.properties];
const argumentCount = arguments.length;
if (argumentCount < 2) {
throw new TypeError("Not enought arguments");
}
if (!tokenRegexp.test(method)) {
throw new DOMException(DOMException.SYNTAX_ERR);
}
const upperCaseMethod = method.toUpperCase();
if (forbiddenRequestMethods.indexOf(upperCaseMethod) !== -1) {
throw new DOMException(DOMException.SECURITY_ERR);
}
const client = properties.client;
if (client && typeof client.abort === "function") {
client.abort();
}
if (allowedRequestMethods.indexOf(upperCaseMethod) !== -1) {
method = upperCaseMethod;
}
if (typeof async !== "undefined") {
flag.synchronous = !async;
} else {
flag.synchronous = false;
}
if (flag.responseType && flag.synchronous) {
throw new DOMException(DOMException.INVALID_ACCESS_ERR);
}
if (flag.synchronous && flag.timeout) {
throw new DOMException(DOMException.INVALID_ACCESS_ERR);
}
flag.method = method;
const baseUrl = documentBaseURLHelper.documentBaseURL(this._ownerDocument).toString();
flag.baseUrl = baseUrl;
const urlObj = new utils.URL(uri, baseUrl);
flag.uri = urlObj.href;
flag.userAgent = this._ownerDocument._defaultView.navigator.userAgent;
if (argumentCount >= 4 && (user || password)) {
flag.auth = {
user,
pass: password
};
}
flag.requestHeaders = {};
properties.send = false;
properties.requestBuffer = null;
properties.requestCache = null;
readyStateChange(this, XMLHttpRequest.OPENED);
}
overrideMimeType(mime) {
if ([XMLHttpRequest.LOADING, XMLHttpRequest.DONE].indexOf(this.readyState) >= 0) {
throw new DOMException(DOMException.INVALID_STATE_ERR);
}
this[xhrSymbols.flag].mimeType = mime;
}
send(body) {
const flag = this[xhrSymbols.flag];
const properties = this[xhrSymbols.properties];
const self = this;
if (this.readyState !== XMLHttpRequest.OPENED || properties.send) {
throw new DOMException(DOMException.INVALID_STATE_ERR);
}
if (!flag.body &&
body !== undefined &&
body !== null &&
body !== "" &&
!(flag.method === "HEAD" || flag.method === "GET")) {
if (body instanceof FormData) {
flag.formData = true;
const formData = [];
for (const entry of body[formDataSymbols.entries]) {
let val;
if (entry.value instanceof Blob) {
const blob = entry.value;
val = {
name: entry.name,
value: blob[blobSymbols.buffer],
options: {
filename: blob.name,
contentType: blob.type,
knownLength: blob.size
}
};
} else {
val = entry;
}
formData.push(val);
}
flag.body = formData;
} else if (body instanceof Blob) {
flag.body = body[blobSymbols.buffer];
} else if (body instanceof ArrayBuffer) {
flag.body = new Buffer(new Uint8Array(body));
} else if (typeof body !== "string") {
flag.body = String(body);
} else {
flag.body = body;
}
}
if (flag.synchronous) {
const flagStr = JSON.stringify(flag);
const res = spawnSync(
process.execPath,
[require.resolve("./xhr-sync-worker.js")],
{
input: flagStr
}
);
if (res.status !== 0) {
throw new Error(res.stderr.toString());
}
if (res.error) {
if (typeof res.error === "string") {
res.error = new Error(res.error);
}
throw res.error;
}
const response = JSON.parse(res.stdout.toString(), (k, v) => {
if (k === "responseBuffer" && v && v.data) {
return new Buffer(v.data);
}
return v;
});
response.properties.readyState = XMLHttpRequest.LOADING;
this[xhrSymbols.properties] = response.properties;
readyStateChange(self, XMLHttpRequest.DONE);
if (response.error) {
this.dispatchEvent(new ProgressEvent("error"));
this.dispatchEvent(new ProgressEvent("loadend"));
throw new DOMException(DOMException.NETWORK_ERR, response.error);
} else {
const responseBuffer = this[xhrSymbols.properties].responseBuffer;
const contentLength = this.getResponseHeader("content-length") || "0";
const bufferLength = parseInt(contentLength, 10) || responseBuffer.length;
const progressObj = { lengthComputable: false };
if (bufferLength !== 0) {
progressObj.total = bufferLength;
progressObj.loaded = bufferLength;
progressObj.lengthComputable = true;
}
this.dispatchEvent(new ProgressEvent("load"));
this.dispatchEvent(new ProgressEvent("loadend", progressObj));
}
} else {
properties.send = true;
this.dispatchEvent(new ProgressEvent("loadstart"));
const client = xhrUtils.createClient(this,
(err, response) => {
if (err) {
if (client) {
client.removeAllListeners();
}
readyStateChange(self, XMLHttpRequest.DONE);
if (!(flag.method === "HEAD" || flag.method === "GET")) {
self.upload.dispatchEvent(new ProgressEvent("error", err));
self.upload.dispatchEvent(new ProgressEvent("loadend"));
}
self.dispatchEvent(new ProgressEvent("error", err));
self.dispatchEvent(new ProgressEvent("loadend"));
return;
}
receiveResponse(self, response);
}
);
properties.client = client;
if (client) {
if (body !== undefined &&
body !== null &&
body !== "" &&
!(flag.method === "HEAD" || flag.method === "GET")) {
setDispatchProgressEvents(this);
}
if (this.timeout > 0) {
properties.timeoutStart = (new Date()).getTime();
properties.timeoutFn = function () {
client.abort();
if (!(self.readyState === XMLHttpRequest.UNSENT ||
(self.readyState === XMLHttpRequest.OPENED && !properties.send) ||
self.readyState === XMLHttpRequest.DONE)) {
properties.send = false;
readyStateChange(self, XMLHttpRequest.DONE);
if (!(flag.method === "HEAD" || flag.method === "GET")) {
self.upload.dispatchEvent(new ProgressEvent("progress"));
self.upload.dispatchEvent(new ProgressEvent("timeout"));
self.upload.dispatchEvent(new ProgressEvent("loadend"));
}
self.dispatchEvent(new ProgressEvent("progress"));
self.dispatchEvent(new ProgressEvent("timeout"));
self.dispatchEvent(new ProgressEvent("loadend"));
}
properties.readyState = XMLHttpRequest.UNSENT;
};
properties.timeoutId = setTimeout(properties.timeoutFn, this.timeout);
}
}
}
flag.body = undefined;
flag.formData = false;
}
setRequestHeader(header, value) {
const flag = this[xhrSymbols.flag];
const properties = this[xhrSymbols.properties];
if (arguments.length !== 2) {
throw new TypeError();
}
value = String(value);
if (!tokenRegexp.test(header) || !fieldValueRegexp.test(value)) {
throw new DOMException(DOMException.SYNTAX_ERR);
}
if (this.readyState !== XMLHttpRequest.OPENED || properties.send) {
throw new DOMException(DOMException.INVALID_STATE_ERR);
}
if (forbiddenRequestHeaders.test(header)) {
return;
}
const keys = Object.keys(flag.requestHeaders);
let n = keys.length;
while (n--) {
const key = keys[n];
if (key.toLowerCase() === header.toLowerCase()) {
flag.requestHeaders[key] += ", " + value;
return;
}
}
flag.requestHeaders[header] = value;
}
toString() {
return "[object XMLHttpRequest]";
}
get _ownerDocument() {
return window.document;
}
}
utils.addConstants(XMLHttpRequest, {
UNSENT: 0,
OPENED: 1,
HEADERS_RECEIVED: 2,
LOADING: 3,
DONE: 4
});
function readyStateChange(xhr, readyState) {
if (xhr.readyState !== readyState) {
const readyStateChangeEvent = new Event("readystatechange");
const properties = xhr[xhrSymbols.properties];
properties.readyState = readyState;
xhr.dispatchEvent(readyStateChangeEvent);
}
}
function receiveResponse(xhr, response) {
const properties = xhr[xhrSymbols.properties];
let byteOffset = 0;
const statusCode = response.statusCode;
properties.status = statusCode;
properties.statusText = response.statusMessage || HTTP_STATUS_CODES[statusCode] || "OK";
const headers = {};
const headerMap = {};
const rawHeaders = response.rawHeaders;
const n = Number(rawHeaders.length);
for (let i = 0; i < n; i += 2) {
const k = rawHeaders[i];
const kl = k.toLowerCase();
const v = rawHeaders[i + 1];
if (k.match(uniqueResponseHeaders)) {
if (headerMap[kl] !== undefined) {
delete headers[headerMap[kl]];
}
headers[k] = v;
} else if (headerMap[kl] !== undefined) {
headers[headerMap[kl]] += ", " + v;
} else {
headers[k] = v;
}
headerMap[kl] = k;
}
properties.responseHeaders = headers;
const contentLength = xhr.getResponseHeader("content-length") || "0";
const bufferLength = parseInt(contentLength, 10) || 0;
const progressObj = { lengthComputable: false };
if (bufferLength !== 0) {
progressObj.total = bufferLength;
progressObj.loaded = 0;
progressObj.lengthComputable = true;
}
properties.responseBuffer = new Buffer(0);
properties.responseCache = null;
properties.responseTextCache = null;
properties.responseXMLCache = null;
readyStateChange(xhr, XMLHttpRequest.HEADERS_RECEIVED);
properties.client.on("data", chunk => {
properties.responseBuffer = Buffer.concat([properties.responseBuffer, chunk]);
properties.responseCache = null;
properties.responseTextCache = null;
properties.responseXMLCache = null;
});
response.on("data", chunk => {
byteOffset += chunk.length;
progressObj.loaded = byteOffset;
readyStateChange(xhr, XMLHttpRequest.LOADING);
if (progressObj.total !== progressObj.loaded) {
xhr.dispatchEvent(new ProgressEvent("progress", progressObj));
}
});
properties.client.on("end", () => {
clearTimeout(properties.timeoutId);
properties.timeoutFn = null;
properties.timeoutStart = 0;
properties.client = null;
readyStateChange(xhr, XMLHttpRequest.DONE);
xhr.dispatchEvent(new ProgressEvent("load"));
xhr.dispatchEvent(new ProgressEvent("loadend", progressObj));
});
}
function setDispatchProgressEvents(xhr) {
const client = xhr[xhrSymbols.properties].client;
client.on("request", req => {
xhr.upload.dispatchEvent(new ProgressEvent("loadstart"));
req.on("response", () => {
let total = 0;
let lengthComputable = false;
const length = parseInt(xhrUtils.getRequestHeader(client.headers, "content-length"), 10);
if (length) {
total = length;
lengthComputable = true;
}
const progress = {
lengthComputable,
total,
loaded: total
};
xhr.upload.dispatchEvent(new ProgressEvent("progress", progress));
xhr.upload.dispatchEvent(new ProgressEvent("load"));
xhr.upload.dispatchEvent(new ProgressEvent("loadend"));
});
});
}
return XMLHttpRequest;
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 4,837 |
```javascript
"use strict";
exports.buffer = Symbol("buffer");
exports.type = Symbol("type");
exports.lastModified = Symbol("lastModified");
exports.closed = Symbol("closed");
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/blob-symbols.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 34 |
```javascript
"use strict";
const EventImpl = require("./Event-impl").implementation;
class HashChangeEventImpl extends EventImpl {
}
module.exports = {
implementation: HashChangeEventImpl
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/events/HashChangeEvent-impl.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 37 |
```javascript
"use strict";
const DOMException = require("../web-idl/DOMException");
const orderedSetParser = require("./helpers/ordered-set-parser");
// path_to_url#domtokenlist
const INTERNAL = Symbol("DOMTokenList internal");
class DOMTokenList {
constructor() {
throw new TypeError("Illegal constructor");
}
item(index) {
const length = this.length;
return length <= index || index < 0 ? null : this[index];
}
contains(token) {
token = String(token);
validateToken(token);
return indexOf(this, token) !== -1;
}
add(/* tokens... */) {
for (let i = 0; i < arguments.length; i++) {
const token = String(arguments[i]);
validateToken(token);
if (indexOf(this, token) === -1) {
push(this, token);
}
}
update(this);
}
remove(/* tokens... */) {
for (let i = 0; i < arguments.length; i++) {
const token = String(arguments[i]);
validateToken(token);
const index = indexOf(this, token);
if (index !== -1) {
spliceLite(this, index, 1);
}
}
update(this);
}
// if force is true, this behaves like add
// if force is false, this behaves like remove
// if force is undefined, this behaves as one would expect toggle to
// always returns whether classList contains token after toggling
toggle(token, force) {
token = String(token);
force = force === undefined ? undefined : Boolean(force);
validateToken(token);
const index = indexOf(this, token);
if (index !== -1) {
if (force === false || force === undefined) {
spliceLite(this, index, 1);
update(this);
return false;
}
return true;
}
if (force === false) {
return false;
}
push(this, token);
update(this);
return true;
}
get length() {
return this[INTERNAL].tokens.length;
}
toString() {
return this[INTERNAL].tokens.join(" ");
}
}
function validateToken(token) {
if (token === "") {
throw new DOMException(DOMException.SYNTAX_ERR, "The token provided must not be empty.");
}
if (/\s/.test(token)) {
const whitespaceMsg = "The token provided contains HTML space characters, which are not valid in tokens.";
throw new DOMException(DOMException.INVALID_CHARACTER_ERR, whitespaceMsg);
}
}
function update(list) {
const attribute = list[INTERNAL].attribute;
if (attribute !== undefined) {
list[INTERNAL].element.setAttribute(attribute, list.toString());
}
}
// calls indexOf on internal array
function indexOf(dtl, token) {
return dtl[INTERNAL].tokens.indexOf(token);
}
// calls push on internal array, then manually adds indexed property to dtl
function push(dtl, token) {
const len = dtl[INTERNAL].tokens.push(token);
dtl[len - 1] = token;
return len;
}
// calls splice on internal array then rewrites indexed properties of dtl
// does not allow items to be added, only removed, so splice-lite
function spliceLite(dtl, start, deleteCount) {
const tokens = dtl[INTERNAL].tokens;
const removedTokens = tokens.splice(start, deleteCount);
// remove indexed properties from list
const re = /^\d+$/;
for (const prop in dtl) {
if (re.test(prop)) {
delete dtl[prop];
}
}
// copy indexed properties from internal array
const len = tokens.length;
for (let i = 0; i < len; i++) {
dtl[i] = tokens[i];
}
return removedTokens;
}
exports.DOMTokenList = DOMTokenList;
// set dom token list without running update steps
exports.reset = function resetDOMTokenList(list, value) {
const tokens = list[INTERNAL].tokens;
spliceLite(list, 0, tokens.length);
value = (value || "").trim();
if (value !== "") {
for (const token of orderedSetParser(value)) {
push(list, token);
}
}
};
exports.create = function createDOMTokenList(element, attribute) {
const list = Object.create(DOMTokenList.prototype);
list[INTERNAL] = {
element,
attribute,
tokens: []
};
exports.reset(list, element.getAttribute(attribute));
return list;
};
exports.contains = function domTokenListContains(list, token, options) {
const caseInsensitive = options && options.caseInsensitive;
if (!caseInsensitive) {
return indexOf(list, token) !== -1;
}
const tokens = list[INTERNAL].tokens;
const lowerToken = token.toLowerCase();
for (let i = 0; i < tokens.length; ++i) {
if (tokens[i].toLowerCase() === lowerToken) {
return true;
}
}
return false;
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/dom-token-list.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,092 |
```javascript
"use strict";
const EventInit = require("../generated/EventInit");
class EventImpl {
constructor(args, privateData) {
const type = args[0]; // TODO: Replace with destructuring
const eventInitDict = args[1] || EventInit.convert(undefined);
if (type) {
this.type = type;
this._initializedFlag = true;
} else {
this.type = "";
this._initializedFlag = false;
}
const wrapper = privateData.wrapper;
for (const key in eventInitDict) {
if (key in wrapper) {
this[key] = eventInitDict[key];
}
}
this.target = null;
this.currentTarget = null;
this.eventPhase = 0;
this._stopPropagationFlag = false;
this._stopImmediatePropagationFlag = false;
this._canceledFlag = false;
this._dispatchFlag = false;
this.isTrusted = false;
this.timeStamp = Date.now();
}
get defaultPrevented() {
return this._canceledFlag;
}
stopPropagation() {
this._stopPropagationFlag = true;
}
stopImmediatePropagation() {
this._stopPropagationFlag = true;
this._stopImmediatePropagation = true;
}
preventDefault() {
if (this.cancelable) {
this._canceledFlag = true;
}
}
_initialize(type, bubbles, cancelable) {
if (type) {
this.type = type;
this._initializedFlag = true;
} else {
this.type = "";
this._initializedFlag = false;
}
this._stopPropagationFlag = false;
this._stopImmediatePropagationFlag = false;
this._canceledFlag = false;
this.isTrusted = false;
this.target = null;
this.bubbles = bubbles;
this.cancelable = cancelable;
}
initEvent(type, bubbles, cancelable) {
if (this._dispatchFlag) {
return;
}
this._initialize(type, bubbles, cancelable);
}
}
module.exports = {
implementation: EventImpl
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/events/Event-impl.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 457 |
```javascript
"use strict";
const UIEventImpl = require("./UIEvent-impl").implementation;
class TouchEventImpl extends UIEventImpl {
}
module.exports = {
implementation: TouchEventImpl
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/events/TouchEvent-impl.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 40 |
```javascript
"use strict";
const UIEventImpl = require("./UIEvent-impl").implementation;
class MouseEventImpl extends UIEventImpl {
initMouseEvent(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY,
ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget) {
if (this._dispatchFlag) {
return;
}
this.initUIEvent(type, bubbles, cancelable, view, detail);
this.screenX = screenX;
this.screenY = screenY;
this.clientX = clientX;
this.clientY = clientY;
this.ctrlKey = ctrlKey;
this.altKey = altKey;
this.shiftKey = shiftKey;
this.metaKey = metaKey;
this.button = button;
this.relatedTarget = relatedTarget;
}
}
module.exports = {
implementation: MouseEventImpl
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/events/MouseEvent-impl.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 191 |
```javascript
"use strict";
const EventImpl = require("./Event-impl").implementation;
class ErrorEventImpl extends EventImpl {
}
module.exports = {
implementation: ErrorEventImpl
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/events/ErrorEvent-impl.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 37 |
```javascript
"use strict";
const EventImpl = require("./Event-impl").implementation;
class CustomEventImpl extends EventImpl {
initCustomEvent(type, bubbles, cancelable, detail) {
if (this._dispatchFlag) {
return;
}
this.initEvent(type, bubbles, cancelable);
this.detail = detail;
}
}
module.exports = {
implementation: CustomEventImpl
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/events/CustomEvent-impl.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 84 |
```javascript
"use strict";
const UIEventImpl = require("./UIEvent-impl").implementation;
class KeyboardEventImpl extends UIEventImpl {
initKeyboardEvent(type, bubbles, cancelable, view, key, location, modifiersList, repeat, locale) {
if (this._dispatchFlag) {
return;
}
this.initUIEvent(type, bubbles, cancelable, view, key);
this.location = location;
this.modifiersList = modifiersList;
this.repeat = repeat;
this.locale = locale;
}
}
module.exports = {
implementation: KeyboardEventImpl
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/events/KeyboardEvent-impl.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 124 |
```javascript
"use strict";
const EventImpl = require("./Event-impl").implementation;
class MessageEventImpl extends EventImpl {
initMessageEvent(type, bubbles, cancelable, data, origin, lastEventId, source, ports) {
if (this._dispatchFlag) {
return;
}
this.initEvent(type, bubbles, cancelable);
this.data = data;
this.origin = origin;
this.lastEventId = lastEventId;
this.source = source;
this.ports = ports;
}
}
module.exports = {
implementation: MessageEventImpl
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/events/MessageEvent-impl.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 123 |
```javascript
"use strict";
const EventImpl = require("./Event-impl").implementation;
class MutationEventImpl extends EventImpl {
initMutationEvent(type, bubbles, cancelable, relatedNode, prevValue, newValue, attrName, attrChange) {
if (this._dispatchFlag) {
return;
}
this.initEvent(type, bubbles, cancelable);
this.relatedNode = relatedNode;
this.prevValue = prevValue;
this.newValue = newValue;
this.attrName = attrName;
this.attrChange = attrChange;
}
}
module.exports = {
implementation: MutationEventImpl
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/events/MutationEvent-impl.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 129 |
```javascript
"use strict";
const EventImpl = require("./Event-impl").implementation;
class ProgressEventImpl extends EventImpl {
}
module.exports = {
implementation: ProgressEventImpl
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/events/ProgressEvent-impl.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 37 |
```javascript
"use strict";
const EventImpl = require("./Event-impl").implementation;
class UIEventImpl extends EventImpl {
initUIEvent(type, bubbles, cancelable, view, detail) {
if (this._dispatchFlag) {
return;
}
this.initEvent(type, bubbles, cancelable);
this.view = view;
this.detail = detail;
}
}
module.exports = {
implementation: UIEventImpl
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/events/UIEvent-impl.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 92 |
```javascript
"use strict";
exports.implementation = class AttrImpl {
constructor(_, privateData) {
this._namespace = privateData.namespace !== undefined ? privateData.namespace : null;
this._namespacePrefix = privateData.namespacePrefix !== undefined ? privateData.namespacePrefix : null;
this._localName = privateData.localName;
this._value = privateData.value !== undefined ? privateData.value : "";
this._element = privateData.element !== undefined ? privateData.element : null;
this.specified = true;
}
get namespaceURI() {
return this._namespace;
}
get prefix() {
return this._namespacePrefix;
}
get localName() {
return this._localName;
}
get name() {
return exports.getAttrImplQualifiedName(this);
}
get value() {
return this._value;
}
set value(v) {
if (this._element === null) {
this._value = v;
} else {
exports.changeAttributeImpl(this._element, this, v);
}
}
// Delegate to value
get nodeValue() {
return this.value;
}
set nodeValue(v) {
this.value = v;
}
// Delegate to value
get textContent() {
return this.value;
}
set textContent(v) {
this.value = v;
}
get ownerElement() {
return this._element;
}
};
exports.changeAttributeImpl = function (element, attributeImpl, value) {
// path_to_url#concept-element-attributes-change
// TODO mutation observer stuff
const oldValue = attributeImpl._value;
attributeImpl._value = value;
// Run jsdom hooks; roughly correspond to spec's "An attribute is set and an attribute is changed."
element._attrModified(exports.getAttrImplQualifiedName(attributeImpl), value, oldValue);
};
exports.getAttrImplQualifiedName = function (attributeImpl) {
// path_to_url#concept-attribute-qualified-name
if (attributeImpl._namespacePrefix === null) {
return attributeImpl._localName;
}
return attributeImpl._namespacePrefix + ":" + attributeImpl._localName;
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/attributes/Attr-impl.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 464 |
```javascript
"use strict";
const conversions = require("webidl-conversions");
const utils = require("./utils.js");
const Impl = require("../events/MutationEvent-impl.js");
const Event = require("./Event.js");
const impl = utils.implSymbol;
function MutationEvent() {
throw new TypeError("Illegal constructor");
}
MutationEvent.prototype = Object.create(Event.interface.prototype);
MutationEvent.prototype.constructor = MutationEvent;
MutationEvent.prototype.initMutationEvent = function initMutationEvent(typeArg, bubblesArg, cancelableArg, relatedNodeArg, prevValueArg, newValueArg, attrNameArg, attrChangeArg) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
if (arguments.length < 8) {
throw new TypeError("Failed to execute 'initMutationEvent' on 'MutationEvent': 8 arguments required, but only " + arguments.length + " present.");
}
const args = [];
for (let i = 0; i < arguments.length && i < 8; ++i) {
args[i] = arguments[i];
}
args[0] = conversions["DOMString"](args[0]);
args[1] = conversions["boolean"](args[1]);
args[2] = conversions["boolean"](args[2]);
args[4] = conversions["DOMString"](args[4]);
args[5] = conversions["DOMString"](args[5]);
args[6] = conversions["DOMString"](args[6]);
args[7] = conversions["unsigned short"](args[7]);
return this[impl].initMutationEvent.apply(this[impl], args);
};
Object.defineProperty(MutationEvent, "MODIFICATION", {
value: 1,
enumerable: true
});
Object.defineProperty(MutationEvent.prototype, "MODIFICATION", {
value: 1,
enumerable: true
});
Object.defineProperty(MutationEvent, "ADDITION", {
value: 2,
enumerable: true
});
Object.defineProperty(MutationEvent.prototype, "ADDITION", {
value: 2,
enumerable: true
});
Object.defineProperty(MutationEvent, "REMOVAL", {
value: 3,
enumerable: true
});
Object.defineProperty(MutationEvent.prototype, "REMOVAL", {
value: 3,
enumerable: true
});
Object.defineProperty(MutationEvent.prototype, "relatedNode", {
get() {
return this[impl].relatedNode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MutationEvent.prototype, "prevValue", {
get() {
return this[impl].prevValue;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MutationEvent.prototype, "newValue", {
get() {
return this[impl].newValue;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MutationEvent.prototype, "attrName", {
get() {
return this[impl].attrName;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MutationEvent.prototype, "attrChange", {
get() {
return this[impl].attrChange;
},
enumerable: true,
configurable: true
});
module.exports = {
is(obj) {
return !!obj && obj[impl] instanceof Impl.implementation;
},
create(constructorArgs, privateData) {
let obj = Object.create(MutationEvent.prototype);
this.setup(obj, constructorArgs, privateData);
return obj;
},
setup(obj, constructorArgs, privateData) {
if (!privateData) privateData = {};
privateData.wrapper = obj;
obj[impl] = new Impl.implementation(constructorArgs, privateData);
obj[impl][utils.wrapperSymbol] = obj;
},
interface: MutationEvent,
expose: {
Window: { MutationEvent: MutationEvent }
}
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/MutationEvent.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 824 |
```javascript
"use strict";
const DOMException = require("../../web-idl/DOMException");
const reportException = require("../helpers/runtime-script-errors");
const domSymbolTree = require("../helpers/internal-constants").domSymbolTree;
const idlUtils = require("../generated/utils");
const Event = require("../generated/Event").interface;
class EventTargetImpl {
constructor() {
this._eventListeners = Object.create(null);
}
addEventListener(type, callback, capture) {
// webidl2js currently can't handle neither optional arguments nor callback interfaces
if (callback === undefined || callback === null) {
callback = null;
} else if (typeof callback === "object") {
callback = callback.handleEvent;
} else if (typeof callback !== "function") {
throw new TypeError("Only undefined, null, an object, or a function are allowed for the callback parameter");
}
if (callback === null) {
return;
}
if (!this._eventListeners[type]) {
this._eventListeners[type] = [];
}
for (let i = 0; i < this._eventListeners[type].length; ++i) {
const listener = this._eventListeners[type][i];
if (listener.capture === capture && listener.callback === callback) {
return;
}
}
this._eventListeners[type].push({
callback,
capture
});
}
removeEventListener(type, callback, capture) {
if (callback === undefined || callback === null) {
callback = null;
} else if (typeof callback === "object") {
callback = callback.handleEvent;
} else if (typeof callback !== "function") {
throw new TypeError("Only undefined, null, an object, or a function are allowed for the callback parameter");
}
if (callback === null) {
// Optimization, not in the spec.
return;
}
if (!this._eventListeners[type]) {
return;
}
for (let i = 0; i < this._eventListeners[type].length; ++i) {
const listener = this._eventListeners[type][i];
if (listener.callback === callback && listener.capture === capture) {
this._eventListeners[type].splice(i, 1);
break;
}
}
}
dispatchEvent(event) {
if (!(event instanceof Event)) {
throw new TypeError("Argument to dispatchEvent must be an Event");
}
const eventImpl = idlUtils.implForWrapper(event);
if (eventImpl._dispatchFlag || !eventImpl._initializedFlag) {
throw new DOMException(DOMException.INVALID_STATE_ERR, "Tried to dispatch an uninitialized event");
}
if (event.eventPhase !== event.NONE) {
throw new DOMException(DOMException.INVALID_STATE_ERR, "Tried to dispatch a dispatching event");
}
eventImpl.isTrusted = false;
return this._dispatch(event);
}
_dispatch(event, targetOverride) {
const eventImpl = idlUtils.implForWrapper(event);
eventImpl._dispatchFlag = true;
eventImpl.target = targetOverride || idlUtils.wrapperForImpl(this);
const eventPath = [];
let targetParent = domSymbolTree.parent(eventImpl.target);
let target = eventImpl.target;
while (targetParent) {
eventPath.push(targetParent);
target = targetParent;
targetParent = domSymbolTree.parent(targetParent);
}
if (event.type !== "load" && target._defaultView) { // path_to_url#events-and-the-window-object
eventPath.push(target._defaultView);
}
eventImpl.eventPhase = Event.CAPTURING_PHASE;
for (let i = eventPath.length - 1; i >= 0; --i) {
if (eventImpl._stopPropagationFlag) {
break;
}
const object = eventPath[i];
const objectImpl = idlUtils.implForWrapper(object);
const eventListeners = objectImpl._eventListeners[event.type];
invokeEventListeners(eventListeners, object, event);
}
eventImpl.eventPhase = Event.AT_TARGET;
if (!eventImpl._stopPropagationFlag) {
invokeInlineListeners(eventImpl.target, event);
if (this._eventListeners[event.type]) {
const eventListeners = this._eventListeners[event.type];
invokeEventListeners(eventListeners, eventImpl.target, event);
}
}
if (event.bubbles) {
eventImpl.eventPhase = Event.BUBBLING_PHASE;
for (let i = 0; i < eventPath.length; ++i) {
if (eventImpl._stopPropagationFlag) {
break;
}
const object = eventPath[i];
const objectImpl = idlUtils.implForWrapper(object);
const eventListeners = objectImpl._eventListeners[event.type];
invokeInlineListeners(object, event);
invokeEventListeners(eventListeners, object, event);
}
}
eventImpl._dispatchFlag = false;
eventImpl.eventPhase = Event.NONE;
eventImpl.currentTarget = null;
return !eventImpl._canceledFlag;
}
}
module.exports = {
implementation: EventTargetImpl
};
function invokeInlineListeners(object, event) {
const inlineListener = getListenerForInlineEventHandler(object, event.type);
if (inlineListener) {
const document = object._ownerDocument || object._document;
// Will be falsy for windows that have closed
if (document && (!object.nodeName || document.implementation._hasFeature("ProcessExternalResources", "script"))) {
invokeEventListeners([{ callback: inlineListener }], object, event);
}
}
}
function invokeEventListeners(listeners, target, event) {
const document = target._ownerDocument || target._document;
// Will be falsy for windows that have closed
if (!document) {
return;
}
const eventImpl = idlUtils.implForWrapper(event);
eventImpl.currentTarget = target;
if (!listeners) {
return;
}
const handlers = listeners.slice();
for (let i = 0; i < handlers.length; ++i) {
if (eventImpl._stopImmediatePropagationFlag) {
return;
}
const listener = handlers[i];
if (listeners.indexOf(listener) === -1 ||
(event.eventPhase === Event.CAPTURING_PHASE && !listener.capture) ||
(event.eventPhase === Event.BUBBLING_PHASE && listener.capture)) {
continue;
}
try {
listener.callback.call(eventImpl.currentTarget, event);
} catch (e) {
let window = null;
if (target._document) {
window = target;
} else if (target._ownerDocument) {
window = target._ownerDocument._defaultView;
}
if (window) {
reportException(window, e);
}
// Errors in window-less documents just get swallowed... can you think of anything better?
}
}
}
const wrappedListener = Symbol("inline event listener wrapper");
function getListenerForInlineEventHandler(target, type) {
const callback = target["on" + type];
if (!callback) { // TODO event handlers: only check null
return null;
}
if (!callback[wrappedListener]) {
// path_to_url#the-event-handler-processing-algorithm
callback[wrappedListener] = function (E) {
const isWindowError = E.constructor.name === "ErrorEvent" && type === "error"; // TODO branding
let returnValue;
if (isWindowError) {
returnValue = callback.call(E.currentTarget, E.message, E.filename, E.lineno, E.colno, E.error);
} else {
returnValue = callback.call(E.currentTarget, E);
}
if (type === "mouseover" || isWindowError) {
if (returnValue) {
E.preventDefault();
}
} else if (!returnValue) {
E.preventDefault();
}
};
}
return callback[wrappedListener];
}
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,695 |
```javascript
"use strict";
const conversions = require("webidl-conversions");
const utils = require("./utils.js");
const EventInit = require("./EventInit");
module.exports = {
convertInherit(obj, ret) {
EventInit.convertInherit(obj, ret);
let key, value;
key = "detail";
value = obj === undefined || obj === null ? undefined : obj[key];
if (value !== undefined) {
ret[key] = conversions["long"](value);
} else {
ret[key] = 0;
}
key = "view";
value = obj === undefined || obj === null ? undefined : obj[key];
if (value !== undefined) {
ret[key] = (value);
} else {
ret[key] = null;
}
},
convert(obj) {
if (obj !== undefined && typeof obj !== "object") {
throw new TypeError("Dictionary has to be an object");
}
if (obj instanceof Date || obj instanceof RegExp) {
throw new TypeError("Dictionary may not be a Date or RegExp object");
}
const ret = Object.create(null);
module.exports.convertInherit(obj, ret);
return ret;
}
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/UIEventInit.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 255 |
```javascript
"use strict";
const conversions = require("webidl-conversions");
const utils = require("./utils.js");
const Impl = require("../events/MessageEvent-impl.js");
const Event = require("./Event.js");
const impl = utils.implSymbol;
const convertMessageEventInit = require("./MessageEventInit").convert;
function MessageEvent(type) {
if (!this || this[impl] || !(this instanceof MessageEvent)) {
throw new TypeError("Failed to construct 'MessageEvent': Please use the 'new' operator, this DOM object constructor cannot be called as a function.");
}
if (arguments.length < 1) {
throw new TypeError("Failed to construct 'MessageEvent': 1 argument required, but only " + arguments.length + " present.");
}
const args = [];
for (let i = 0; i < arguments.length && i < 2; ++i) {
args[i] = arguments[i];
}
args[0] = conversions["DOMString"](args[0]);
args[1] = convertMessageEventInit(args[1]);
module.exports.setup(this, args);
}
MessageEvent.prototype = Object.create(Event.interface.prototype);
MessageEvent.prototype.constructor = MessageEvent;
MessageEvent.prototype.initMessageEvent = function initMessageEvent(type, bubbles, cancelable, data, origin, lastEventId, source, ports) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
if (arguments.length < 8) {
throw new TypeError("Failed to execute 'initMessageEvent' on 'MessageEvent': 8 arguments required, but only " + arguments.length + " present.");
}
const args = [];
for (let i = 0; i < arguments.length && i < 8; ++i) {
args[i] = arguments[i];
}
args[0] = conversions["DOMString"](args[0]);
args[1] = conversions["boolean"](args[1]);
args[2] = conversions["boolean"](args[2]);
args[4] = conversions["DOMString"](args[4]);
args[5] = conversions["DOMString"](args[5]);
return this[impl].initMessageEvent.apply(this[impl], args);
};
Object.defineProperty(MessageEvent.prototype, "data", {
get() {
return this[impl].data;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MessageEvent.prototype, "origin", {
get() {
return this[impl].origin;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MessageEvent.prototype, "lastEventId", {
get() {
return this[impl].lastEventId;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MessageEvent.prototype, "source", {
get() {
return this[impl].source;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MessageEvent.prototype, "ports", {
get() {
return this[impl].ports;
},
enumerable: true,
configurable: true
});
module.exports = {
is(obj) {
return !!obj && obj[impl] instanceof Impl.implementation;
},
create(constructorArgs, privateData) {
let obj = Object.create(MessageEvent.prototype);
this.setup(obj, constructorArgs, privateData);
return obj;
},
setup(obj, constructorArgs, privateData) {
if (!privateData) privateData = {};
privateData.wrapper = obj;
obj[impl] = new Impl.implementation(constructorArgs, privateData);
obj[impl][utils.wrapperSymbol] = obj;
},
interface: MessageEvent,
expose: {
Window: { MessageEvent: MessageEvent },
Worker: { MessageEvent: MessageEvent }
}
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/MessageEvent.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 812 |
```javascript
"use strict";
const conversions = require("webidl-conversions");
const utils = require("./utils.js");
const Impl = require("../events/Event-impl.js");
const impl = utils.implSymbol;
const convertEventInit = require("./EventInit").convert;
function Event(type) {
if (!this || this[impl] || !(this instanceof Event)) {
throw new TypeError("Failed to construct 'Event': Please use the 'new' operator, this DOM object constructor cannot be called as a function.");
}
if (arguments.length < 1) {
throw new TypeError("Failed to construct 'Event': 1 argument required, but only " + arguments.length + " present.");
}
const args = [];
for (let i = 0; i < arguments.length && i < 2; ++i) {
args[i] = arguments[i];
}
args[0] = conversions["DOMString"](args[0]);
args[1] = convertEventInit(args[1]);
module.exports.setup(this, args);
}
Event.prototype.stopPropagation = function stopPropagation() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
const args = [];
for (let i = 0; i < arguments.length && i < 0; ++i) {
args[i] = arguments[i];
}
return this[impl].stopPropagation.apply(this[impl], args);
};
Event.prototype.stopImmediatePropagation = function stopImmediatePropagation() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
const args = [];
for (let i = 0; i < arguments.length && i < 0; ++i) {
args[i] = arguments[i];
}
return this[impl].stopImmediatePropagation.apply(this[impl], args);
};
Event.prototype.preventDefault = function preventDefault() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
const args = [];
for (let i = 0; i < arguments.length && i < 0; ++i) {
args[i] = arguments[i];
}
return this[impl].preventDefault.apply(this[impl], args);
};
Event.prototype.initEvent = function initEvent(type, bubbles, cancelable) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
if (arguments.length < 3) {
throw new TypeError("Failed to execute 'initEvent' on 'Event': 3 arguments required, but only " + arguments.length + " present.");
}
const args = [];
for (let i = 0; i < arguments.length && i < 3; ++i) {
args[i] = arguments[i];
}
args[0] = conversions["DOMString"](args[0]);
args[1] = conversions["boolean"](args[1]);
args[2] = conversions["boolean"](args[2]);
return this[impl].initEvent.apply(this[impl], args);
};
Object.defineProperty(Event.prototype, "type", {
get() {
return this[impl].type;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Event.prototype, "target", {
get() {
return this[impl].target;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Event.prototype, "currentTarget", {
get() {
return this[impl].currentTarget;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Event, "NONE", {
value: 0,
enumerable: true
});
Object.defineProperty(Event.prototype, "NONE", {
value: 0,
enumerable: true
});
Object.defineProperty(Event, "CAPTURING_PHASE", {
value: 1,
enumerable: true
});
Object.defineProperty(Event.prototype, "CAPTURING_PHASE", {
value: 1,
enumerable: true
});
Object.defineProperty(Event, "AT_TARGET", {
value: 2,
enumerable: true
});
Object.defineProperty(Event.prototype, "AT_TARGET", {
value: 2,
enumerable: true
});
Object.defineProperty(Event, "BUBBLING_PHASE", {
value: 3,
enumerable: true
});
Object.defineProperty(Event.prototype, "BUBBLING_PHASE", {
value: 3,
enumerable: true
});
Object.defineProperty(Event.prototype, "eventPhase", {
get() {
return this[impl].eventPhase;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Event.prototype, "bubbles", {
get() {
return this[impl].bubbles;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Event.prototype, "cancelable", {
get() {
return this[impl].cancelable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Event.prototype, "defaultPrevented", {
get() {
return this[impl].defaultPrevented;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Event.prototype, "timeStamp", {
get() {
return this[impl].timeStamp;
},
enumerable: true,
configurable: true
});
module.exports = {
is(obj) {
return !!obj && obj[impl] instanceof Impl.implementation;
},
create(constructorArgs, privateData) {
let obj = Object.create(Event.prototype);
this.setup(obj, constructorArgs, privateData);
return obj;
},
setup(obj, constructorArgs, privateData) {
if (!privateData) privateData = {};
privateData.wrapper = obj;
Object.defineProperty(obj, "isTrusted", {
get() {
return obj[impl].isTrusted;
},
enumerable: true,
configurable: false
});
obj[impl] = new Impl.implementation(constructorArgs, privateData);
obj[impl][utils.wrapperSymbol] = obj;
},
interface: Event,
expose: {
Window: { Event: Event },
Worker: { Event: Event }
}
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/Event.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,310 |
```javascript
"use strict";
const conversions = require("webidl-conversions");
const utils = require("./utils.js");
const EventInit = require("./EventInit");
module.exports = {
convertInherit(obj, ret) {
EventInit.convertInherit(obj, ret);
let key, value;
key = "lengthComputable";
value = obj === undefined || obj === null ? undefined : obj[key];
if (value !== undefined) {
ret[key] = conversions["boolean"](value);
} else {
ret[key] = false;
}
key = "loaded";
value = obj === undefined || obj === null ? undefined : obj[key];
if (value !== undefined) {
ret[key] = conversions["unsigned long long"](value);
} else {
ret[key] = 0;
}
key = "total";
value = obj === undefined || obj === null ? undefined : obj[key];
if (value !== undefined) {
ret[key] = conversions["unsigned long long"](value);
} else {
ret[key] = 0;
}
},
convert(obj) {
if (obj !== undefined && typeof obj !== "object") {
throw new TypeError("Dictionary has to be an object");
}
if (obj instanceof Date || obj instanceof RegExp) {
throw new TypeError("Dictionary may not be a Date or RegExp object");
}
const ret = Object.create(null);
module.exports.convertInherit(obj, ret);
return ret;
}
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/ProgressEventInit.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 319 |
```javascript
"use strict";
module.exports.mixin = function mixin(target, source) {
const keys = Object.getOwnPropertyNames(source);
for (let i = 0; i < keys.length; ++i) {
Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i]));
}
};
module.exports.wrapperSymbol = Symbol("wrapper");
module.exports.implSymbol = Symbol("impl");
module.exports.wrapperForImpl = function (impl) {
return impl[module.exports.wrapperSymbol];
};
module.exports.implForWrapper = function (wrapper) {
return wrapper[module.exports.implSymbol];
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/utils.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 120 |
```javascript
"use strict";
const conversions = require("webidl-conversions");
const utils = require("./utils.js");
const Impl = require("../events/TouchEvent-impl.js");
const UIEvent = require("./UIEvent.js");
const impl = utils.implSymbol;
function TouchEvent() {
throw new TypeError("Illegal constructor");
}
TouchEvent.prototype = Object.create(UIEvent.interface.prototype);
TouchEvent.prototype.constructor = TouchEvent;
Object.defineProperty(TouchEvent.prototype, "touches", {
get() {
return this[impl].touches;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TouchEvent.prototype, "targetTouches", {
get() {
return this[impl].targetTouches;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TouchEvent.prototype, "changedTouches", {
get() {
return this[impl].changedTouches;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TouchEvent.prototype, "altKey", {
get() {
return this[impl].altKey;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TouchEvent.prototype, "metaKey", {
get() {
return this[impl].metaKey;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TouchEvent.prototype, "ctrlKey", {
get() {
return this[impl].ctrlKey;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TouchEvent.prototype, "shiftKey", {
get() {
return this[impl].shiftKey;
},
enumerable: true,
configurable: true
});
module.exports = {
is(obj) {
return !!obj && obj[impl] instanceof Impl.implementation;
},
create(constructorArgs, privateData) {
let obj = Object.create(TouchEvent.prototype);
this.setup(obj, constructorArgs, privateData);
return obj;
},
setup(obj, constructorArgs, privateData) {
if (!privateData) privateData = {};
privateData.wrapper = obj;
obj[impl] = new Impl.implementation(constructorArgs, privateData);
obj[impl][utils.wrapperSymbol] = obj;
},
interface: TouchEvent,
expose: {
Window: { TouchEvent: TouchEvent }
}
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/TouchEvent.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 491 |
```javascript
"use strict";
const conversions = require("webidl-conversions");
const utils = require("./utils.js");
const Impl = require("../events/MouseEvent-impl.js");
const UIEvent = require("./UIEvent.js");
const impl = utils.implSymbol;
const convertMouseEventInit = require("./MouseEventInit").convert;
function MouseEvent(typeArg) {
if (!this || this[impl] || !(this instanceof MouseEvent)) {
throw new TypeError("Failed to construct 'MouseEvent': Please use the 'new' operator, this DOM object constructor cannot be called as a function.");
}
if (arguments.length < 1) {
throw new TypeError("Failed to construct 'MouseEvent': 1 argument required, but only " + arguments.length + " present.");
}
const args = [];
for (let i = 0; i < arguments.length && i < 2; ++i) {
args[i] = arguments[i];
}
args[0] = conversions["DOMString"](args[0]);
args[1] = convertMouseEventInit(args[1]);
module.exports.setup(this, args);
}
MouseEvent.prototype = Object.create(UIEvent.interface.prototype);
MouseEvent.prototype.constructor = MouseEvent;
MouseEvent.prototype.getModifierState = function getModifierState(keyArg) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
if (arguments.length < 1) {
throw new TypeError("Failed to execute 'getModifierState' on 'MouseEvent': 1 argument required, but only " + arguments.length + " present.");
}
const args = [];
for (let i = 0; i < arguments.length && i < 1; ++i) {
args[i] = arguments[i];
}
args[0] = conversions["DOMString"](args[0]);
return this[impl].getModifierState.apply(this[impl], args);
};
MouseEvent.prototype.initMouseEvent = function initMouseEvent(typeArg, bubblesArg, cancelableArg, viewArg, detailArg, screenXArg, screenYArg, clientXArg, clientYArg, ctrlKeyArg, altKeyArg, shiftKeyArg, metaKeyArg, buttonArg, relatedTargetArg) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
if (arguments.length < 15) {
throw new TypeError("Failed to execute 'initMouseEvent' on 'MouseEvent': 15 arguments required, but only " + arguments.length + " present.");
}
const args = [];
for (let i = 0; i < arguments.length && i < 15; ++i) {
args[i] = arguments[i];
}
args[0] = conversions["DOMString"](args[0]);
args[1] = conversions["boolean"](args[1]);
args[2] = conversions["boolean"](args[2]);
args[4] = conversions["long"](args[4]);
args[5] = conversions["long"](args[5]);
args[6] = conversions["long"](args[6]);
args[7] = conversions["long"](args[7]);
args[8] = conversions["long"](args[8]);
args[9] = conversions["boolean"](args[9]);
args[10] = conversions["boolean"](args[10]);
args[11] = conversions["boolean"](args[11]);
args[12] = conversions["boolean"](args[12]);
args[13] = conversions["short"](args[13]);
return this[impl].initMouseEvent.apply(this[impl], args);
};
Object.defineProperty(MouseEvent.prototype, "screenX", {
get() {
return this[impl].screenX;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MouseEvent.prototype, "screenY", {
get() {
return this[impl].screenY;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MouseEvent.prototype, "clientX", {
get() {
return this[impl].clientX;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MouseEvent.prototype, "clientY", {
get() {
return this[impl].clientY;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MouseEvent.prototype, "ctrlKey", {
get() {
return this[impl].ctrlKey;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MouseEvent.prototype, "shiftKey", {
get() {
return this[impl].shiftKey;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MouseEvent.prototype, "altKey", {
get() {
return this[impl].altKey;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MouseEvent.prototype, "metaKey", {
get() {
return this[impl].metaKey;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MouseEvent.prototype, "button", {
get() {
return this[impl].button;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MouseEvent.prototype, "relatedTarget", {
get() {
return this[impl].relatedTarget;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MouseEvent.prototype, "buttons", {
get() {
return this[impl].buttons;
},
enumerable: true,
configurable: true
});
module.exports = {
is(obj) {
return !!obj && obj[impl] instanceof Impl.implementation;
},
create(constructorArgs, privateData) {
let obj = Object.create(MouseEvent.prototype);
this.setup(obj, constructorArgs, privateData);
return obj;
},
setup(obj, constructorArgs, privateData) {
if (!privateData) privateData = {};
privateData.wrapper = obj;
obj[impl] = new Impl.implementation(constructorArgs, privateData);
obj[impl][utils.wrapperSymbol] = obj;
},
interface: MouseEvent,
expose: {
Window: { MouseEvent: MouseEvent }
}
};
``` | /content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/MouseEvent.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,295 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.